<commit_before>/* All the validation types and the method name to validate */

var V = require('validator');

/* Add in Validator object the isString method */
V.isString = function(value){
  if(typeof value === 'string') return true; else return false;
};
/* Add in Validator object the isBoolean method */
V.isBoolean = function(value){
  if(typeof value === 'boolean') return true; else return false;
};

module.exports = {

  'email': {
    method: 'isEmail'
  },
  'email': {
    method: 'isEmail',
    sanitizer: V.normalizeEmail,
    type: 'email'
  },
  'url': {
    method: 'isURL'
  },
  'ip': {
    method: 'isIP'
  },
  'alpha': {
    method: 'isAlpha'
  },
  'numeric': {
    method: 'isNumeric'
  },
  'base64': {
    method: 'isBase64'
  },
  'hex': {
    method: 'isHexadecimal'
  },
  'hexcolor': {
    method: 'isHexColor'
  },
  'lower': {
    method: 'isLowercase'
  },
  'tolower': {
    method: 'isString',
    sanitizer: toLowerCase,
    type: 'string'
  },
  'upper': {
    method: 'isUppercase'
  },
  'toupper': {
    method: 'isString',
    sanitizer: toUpperCase,
    type: 'string'
  },
  'string': {
    sanitizer: 'toString'
  },
  'boolean': {
    method: 'isBoolean'
  },
  'toboolean': {
    sanitizer: 'toBoolean'
  },
  'int': {
    method: 'isInt',
    sanitizer: V.toInt
  },
  'float': {
    method: 'isFloat',
    sanitizer: V.toFloat
  },
  'date': {
    method: 'isDate'
  },
  'todate': {
    method: 'isDate',
    sanitizer: V.toDate,
    type: 'date'
  },
  'json': {
    method: 'isJSON'
  },
  'ascii': {
    method: 'isAscii'
  },
  'mongoid' : {
    method: 'isMongoId'
  },
  'alphanumeric': {
    method: 'isAlphanumeric'
  },
  'creditcard': {
    method: 'isCreditCard'
  }

};

/*
* toLowerCase - Function
* @params - value {String}
* Check if is posible to set the string .toLowerCase and if it is lowerCase
*/
function toLowerCase(value){
  console.log(value, value.toLowerCase());
  return value.toLowerCase();
};

/*
* toLowerCase - Function
* @params - value {String}
* Check if is posible to set the string .toLowerCase and if it is lowerCase
*/
function toUpperCase(value){
  return value.toUpperCase();
};
<commit_msg>Methods ordered<commit_after>/* All the validation types and the method name to validate */

var V = require('validator');

/* Add in Validator object the isString method */
V.isString = function(value){
  if(typeof value === 'string') return true; else return false;
};
/* Add in Validator object the isBoolean method */
V.isBoolean = function(value){
  if(typeof value === 'boolean') return true; else return false;
};

module.exports = {

  'alpha': {
    method: 'isAlpha'
  },
  'alphanumeric': {
    method: 'isAlphanumeric'
  },
  'ascii': {
    method: 'isAscii'
  },
  'base64': {
    method: 'isBase64'
  },
  'boolean': {
    method: 'isBoolean'
  },
  'creditcard': {
    method: 'isCreditCard'
  },
  'date': {
    method: 'isDate'
  },
  'email': {
    method: 'isEmail'
  },
  'float': {
    method: 'isFloat',
    sanitizer: V.toFloat
  },
  'hex': {
    method: 'isHexadecimal'
  },
  'hexcolor': {
    method: 'isHexColor'
  },
  'int': {
    method: 'isInt',
    sanitizer: V.toInt
  },
  'ip': {
    method: 'isIP'
  },
  'json': {
    method: 'isJSON'
  },
  'lower': {
    method: 'isLowercase'
  },
  'mongoid' : {
    method: 'isMongoId'
  },
  'numeric': {
    method: 'isNumeric'
  },
  'string': {
    sanitizer: 'toString'
  },
  'toboolean': {
    sanitizer: 'toBoolean'
  },
  'todate': {
    method: 'isDate',
    sanitizer: V.toDate,
    type: 'date'
  },
  'toemail': {
    method: 'isEmail',
    sanitizer: V.normalizeEmail,
    type: 'email'
  },
  'tolower': {
    method: 'isString',
    sanitizer: toLowerCase,
    type: 'string'
  },
  'toupper': {
    method: 'isString',
    sanitizer: toUpperCase,
    type: 'string'
  },
  'url': {
    method: 'isURL'
  },
  'upper': {
    method: 'isUppercase'
  }

};

/*
* toLowerCase - Function
* @params - value {String}
* Check if is posible to set the string .toLowerCase and if it is lowerCase
*/
function toLowerCase(value){
  console.log(value, value.toLowerCase());
  return value.toLowerCase();
};

/*
* toLowerCase - Function
* @params - value {String}
* Check if is posible to set the string .toLowerCase and if it is lowerCase
*/
function toUpperCase(value){
  return value.toUpperCase();
};
<|endoftext|>


<commit_before>const $ = require('jquery');

class InputReplacementService {
    /**
     * Input replacement service
     * @param pulsarFormComponent
     * @param queryService
     */
    constructor (
        pulsarFormComponent,
        queryService
    ) {
        this.queryService = queryService;
        this.pulsarFormComponent = pulsarFormComponent;
    }

    /**
     * Replace an input element with another of the same type (usually a clone)
     * @param elements
     * @param replacement
     * @returns {*|jQuery}
     */
    replace (elements, replacement) {
        const type = {
            'radio': this.replaceRadioInput.bind(this),
            'select-one': this.replaceSelect.bind(this),
            'select-multiple': this.replaceSelect.bind(this)
        };

        // If the type is not defined we will use jQuery's replaceWith(...) method
        // We are expecting an element list here, as with radio Inputs we'll have
        // a chance of receiving multiple inputs with the same name
        [].slice.call(elements).forEach(element => {
            type[element.type] === undefined ?
                $(element).replaceWith(replacement) :
                type[element.type](element, replacement);
        });
    }

    /**
     * Replace radio inputs
     * @param radio
     * @param replacement
     */
    replaceRadioInput (radio, replacement) {
        if (radio.getAttribute('data-pseudo-radio-id') === replacement.getAttribute('data-pseudo-radio-id')) {
            $(radio).replaceWith(replacement);
        }
    }

    /**
     * We don't need to replace the select2s here, we can update the original clone
     * we'll replace regular selects with their state-full clones
     * @param select
     * @param replacement
     */
    replaceSelect (select, replacement) {
        const $select = $(select);

        if ($select.hasClass('js-select2')) {
            // Parse our dumped select2 data
            const select2Data = JSON.parse(select.getAttribute(this.queryService.getAttr('select2-data')));

            // Set each options's selected value based on the parsed select2 data
            [].slice.call(select.children)
                .forEach(option => {
                    const previousState = select2Data.find(s2 => s2.id === option.value);

                    option.selected = previousState ? previousState.selected : false;
                });

            this.pulsarFormComponent.initSelect2($select);
        } else {
            $select.replaceWith(replacement);
        }
    }
}

module.exports = InputReplacementService;
<commit_msg>handle non-select2 selects<commit_after>const $ = require('jquery');

class InputReplacementService {
    /**
     * Input replacement service
     * @param pulsarFormComponent
     * @param queryService
     */
    constructor (
        pulsarFormComponent,
        queryService
    ) {
        this.queryService = queryService;
        this.pulsarFormComponent = pulsarFormComponent;
    }

    /**
     * Replace an input element with another of the same type (usually a clone)
     * @param elements
     * @param replacement
     * @returns {*|jQuery}
     */
    replace (elements, replacement) {
        const type = {
            'radio': this.replaceRadioInput.bind(this),
            'select-one': this.replaceSelect.bind(this),
            'select-multiple': this.replaceSelect.bind(this)
        };

        // If the type is not defined we will use jQuery's replaceWith(...) method
        // We are expecting an element list here, as with radio Inputs we'll have
        // a chance of receiving multiple inputs with the same name
        [].slice.call(elements).forEach(element => {
            type[element.type] === undefined ?
                $(element).replaceWith(replacement) :
                type[element.type](element, replacement);
        });
    }

    /**
     * Replace radio inputs
     * @param radio
     * @param replacement
     */
    replaceRadioInput (radio, replacement) {
        if (radio.getAttribute('data-pseudo-radio-id') === replacement.getAttribute('data-pseudo-radio-id')) {
            $(radio).replaceWith(replacement);
        }
    }

    /**
     * We don't need to replace the select2s here, we can update the original clone
     * we'll replace regular selects with their state-full clones
     * @param select
     * @param replacement
     */
    replaceSelect (select, replacement) {
        const $select = $(select);

        if ($select.hasClass('js-select2')) {
            // Parse our dumped select2 data
            const select2Data = JSON.parse(select.getAttribute(this.queryService.getAttr('select2-data')));

            if (select2Data) {
                // Set each options's selected value based on the parsed select2 data
                [].slice.call(select.children)
                    .forEach(option => {
                        const previousState = select2Data.find(s2 => s2.id === option.value);

                        option.selected = previousState ? previousState.selected : false;
                    });
            }

            this.pulsarFormComponent.initSelect2($select);
        } else {
            $select.replaceWith(replacement);
        }
    }
}

module.exports = InputReplacementService;
<|endoftext|>


<commit_before>(function () {
  'use strict';
  var badwords = '';
  jQuery('document') .ready(function () {
    $.get(RELATIVE_PATH + '/api/plugins/beep') .success(function (banned_words) {
      badwords = banned_words.split(',');
    }) .fail(function () {
      badwords = [
        'anal',
        'anus',
        'arse',
        'ass',
        'ballsack',
        'balls',
        'bastard',
        'bitch',
        'biatch',
        'bloody',
        'blowjob',
        'blow job',
        'bollock',
        'bollok',
        'boner',
        'boob',
        'bugger',
        'bum',
        'butt',
        'buttplug',
        'clitoris',
        'cock',
        'coon',
        'crap',
        'cunt',
        'damn',
        'dick',
        'dildo',
        'dyke',
        'fag',
        'feck',
        'fellate',
        'fellatio',
        'felching',
        'fuck',
        'f u c k',
        'fudgepacker',
        'fudge packer',
        'flange',
        'homo',
        'jerk',
        'jizz',
        'knobend',
        'knob end',
        'labia',
        'muff',
        'nigger',
        'nigga',
        'penis',
        'piss',
        'poop',
        'prick',
        'pube',
        'pussy',
        'queer',
        'sex',
        'shit',
        's hit',
        'sh1t',
        'slut',
        'smegma',
        'spunk',
        'tit',
        'tosser',
        'turd',
        'twat',
        'vagina',
        'wank',
        'whore'
      ];
    });
    $(window) .on('action:ajaxify.end', function (ev, data) {
      //if (data.url.match(/^category/) || data.url.match(/^unread/) || data.url.match(/^recent/) || data.url.match(/^popular/)|| data.url.match(/^search/)) {
      if (data.url.match(/^category/) || data.url.match(/^unread/) || data.url.match(/^recent/) || data.url.match(/^popular/)) {
        censorTopics();
      }
      if (data.url.match(/^topic/)) $(window) .on('scroll', censorTopics);
    });
    $(window) .on('action:categories.loaded', censorTopics);
    $(window) .on('action:categories.new_topic.loaded', censorTopics);
    $(window) .on('action:topic.loaded', censorTopics);
    socket.on('event:post_edited', function () {
      setTimeout(censorTopics, 270);
    });
  });
  function censorTopics() {
    for (var w in badwords) {
      var re = new RegExp(badwords[w], 'ig');
      var hidesting = '';
      for (var i = 0; i < badwords[w].length - 2; i++) {
        hidesting += '*';
      }
      var re2 = new RegExp(badwords[w].substring(1, badwords[w].length - 1), 'ig');
      //Change topic title on topic list
      $('.category-item .topic-title') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting)
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });
      //Change topic title on topic
      $('h3.topic-title p.topic-title') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting)
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });
      //Change Breadcrump
      $('ol.breadcrumb li.active span') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting)
          $(this) .html($(this) .html() .replace(re, hashword));));
        }
      });
      /* Causes stuff(random blinking on the homepage) to happen for some reason */
      /*
      //Change recent replies panel information
      $('.panel .recent-replies') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting)
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });
      */

      /* Won't work because of highlighting */
      /*
      //Change search information
      $('.search-result-text') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting)
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });*/

      //Change header information
      $('.header-topic-title span') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting)
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });
      var match = document.title.match(re);
      var hashword = match.replace(re2, hidesting)
      document.title = document.title.replace(re, hashword);
    }
  }
}());
<commit_msg>silly stuff<commit_after>(function () {
  'use strict';
  var badwords = '';
  jQuery('document') .ready(function () {
    $.get(RELATIVE_PATH + '/api/plugins/beep') .success(function (banned_words) {
      badwords = banned_words.split(',');
    }) .fail(function () {
      badwords = [
        'anal',
        'anus',
        'arse',
        'ass',
        'ballsack',
        'balls',
        'bastard',
        'bitch',
        'biatch',
        'bloody',
        'blowjob',
        'blow job',
        'bollock',
        'bollok',
        'boner',
        'boob',
        'bugger',
        'bum',
        'butt',
        'buttplug',
        'clitoris',
        'cock',
        'coon',
        'crap',
        'cunt',
        'damn',
        'dick',
        'dildo',
        'dyke',
        'fag',
        'feck',
        'fellate',
        'fellatio',
        'felching',
        'fuck',
        'f u c k',
        'fudgepacker',
        'fudge packer',
        'flange',
        'homo',
        'jerk',
        'jizz',
        'knobend',
        'knob end',
        'labia',
        'muff',
        'nigger',
        'nigga',
        'penis',
        'piss',
        'poop',
        'prick',
        'pube',
        'pussy',
        'queer',
        'sex',
        'shit',
        's hit',
        'sh1t',
        'slut',
        'smegma',
        'spunk',
        'tit',
        'tosser',
        'turd',
        'twat',
        'vagina',
        'wank',
        'whore'
      ];
    });
    $(window) .on('action:ajaxify.end', function (ev, data) {
      if (data.url.match(/^category/) || data.url.match(/^unread/) || data.url.match(/^recent/) || data.url.match(/^popular/)|| data.url.match(/^search/)) {
        censorTopics();
      }
      if (data.url.match(/^topic/)) $(window) .on('scroll', censorTopics);
    });
    $(window) .on('action:categories.loaded', censorTopics);
    $(window) .on('action:categories.new_topic.loaded', censorTopics);
    $(window) .on('action:topic.loaded', censorTopics);
    socket.on('event:post_edited', function () {
      setTimeout(censorTopics, 270);
    });
  });
  function censorTopics() {
    for (var w in badwords) {
      var re = new RegExp(badwords[w], 'ig');
      var hidesting = '';
      for (var i = 0; i < badwords[w].length - 2; i++) {
        hidesting += '*';
      }
      var re2 = new RegExp(badwords[w].substring(1, badwords[w].length - 1), 'ig');
      //Change topic title on topic list
      $('.category-item .topic-title') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting);
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });
      //Change topic title on topic
      $('h3.topic-title p.topic-title') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting);
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });
      //Change Breadcrump
      $('ol.breadcrumb li.active span') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting);
          $(this) .html($(this) .html() .replace(re, hashword));));
        }
      });
      /* Causes stuff(random blinking on the homepage) to happen for some reason */
      /*
      //Change recent replies panel information
      $('.panel .recent-replies') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting);
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });
      */

      /* Won't work because of highlighting */
      /*
      //Change search information
      $('.search-result-text') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting);
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });*/

      //Change header information
      $('.header-topic-title span') .each(function () {
        if ($(this) .html() .match(re)) {
          var match = $(this) .html() .match(re);
          var hashword = match.replace(re2, hidesting);
          $(this) .html($(this) .html() .replace(re, hashword));
        }
      });
      var match = document.title.match(re);
      var hashword = match.replace(re2, hidesting);
      document.title = document.title.replace(re, hashword);
    }
  }
}());
<|endoftext|>


<commit_before>var support = {
  searchParams: 'URLSearchParams' in self,
  iterable: 'Symbol' in self && 'iterator' in Symbol,
  blob:
    'FileReader' in self &&
    'Blob' in self &&
    (function() {
      try {
        new Blob()
        return true
      } catch (e) {
        return false
      }
    })(),
  formData: 'FormData' in self,
  arrayBuffer: 'ArrayBuffer' in self
}

if (support.arrayBuffer) {
  var viewClasses = [
    '[object Int8Array]',
    '[object Uint8Array]',
    '[object Uint8ClampedArray]',
    '[object Int16Array]',
    '[object Uint16Array]',
    '[object Int32Array]',
    '[object Uint32Array]',
    '[object Float32Array]',
    '[object Float64Array]'
  ]

  var isDataView = function(obj) {
    return obj && DataView.prototype.isPrototypeOf(obj)
  }

  var isArrayBufferView =
    ArrayBuffer.isView ||
    function(obj) {
      return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
    }
}

function normalizeName(name) {
  if (typeof name !== 'string') {
    name = String(name)
  }
  if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
    throw new TypeError('Invalid character in header field name')
  }
  return name.toLowerCase()
}

function normalizeValue(value) {
  if (typeof value !== 'string') {
    value = String(value)
  }
  return value
}

// Build a destructive iterator for the value list
function iteratorFor(items) {
  var iterator = {
    next: function() {
      var value = items.shift()
      return {done: value === undefined, value: value}
    }
  }

  if (support.iterable) {
    iterator[Symbol.iterator] = function() {
      return iterator
    }
  }

  return iterator
}

export function Headers(headers) {
  this.map = {}

  if (headers instanceof Headers) {
    headers.forEach(function(value, name) {
      this.append(name, value)
    }, this)
  } else if (Array.isArray(headers)) {
    headers.forEach(function(header) {
      this.append(header[0], header[1])
    }, this)
  } else if (headers) {
    Object.getOwnPropertyNames(headers).forEach(function(name) {
      this.append(name, headers[name])
    }, this)
  }
}

Headers.prototype.append = function(name, value) {
  name = normalizeName(name)
  value = normalizeValue(value)
  var oldValue = this.map[name]
  this.map[name] = oldValue ? oldValue + ',' + value : value
}

Headers.prototype['delete'] = function(name) {
  delete this.map[normalizeName(name)]
}

Headers.prototype.get = function(name) {
  name = normalizeName(name)
  return this.has(name) ? this.map[name] : null
}

Headers.prototype.has = function(name) {
  return this.map.hasOwnProperty(normalizeName(name))
}

Headers.prototype.set = function(name, value) {
  this.map[normalizeName(name)] = normalizeValue(value)
}

Headers.prototype.forEach = function(callback, thisArg) {
  for (var name in this.map) {
    if (this.map.hasOwnProperty(name)) {
      callback.call(thisArg, this.map[name], name, this)
    }
  }
}

Headers.prototype.keys = function() {
  var items = []
  this.forEach(function(value, name) {
    items.push(name)
  })
  return iteratorFor(items)
}

Headers.prototype.values = function() {
  var items = []
  this.forEach(function(value) {
    items.push(value)
  })
  return iteratorFor(items)
}

Headers.prototype.entries = function() {
  var items = []
  this.forEach(function(value, name) {
    items.push([name, value])
  })
  return iteratorFor(items)
}

if (support.iterable) {
  Headers.prototype[Symbol.iterator] = Headers.prototype.entries
}

function consumed(body) {
  if (body.bodyUsed) {
    return Promise.reject(new TypeError('Already read'))
  }
  body.bodyUsed = true
}

function fileReaderReady(reader) {
  return new Promise(function(resolve, reject) {
    reader.onload = function() {
      resolve(reader.result)
    }
    reader.onerror = function() {
      reject(reader.error)
    }
  })
}

function readBlobAsArrayBuffer(blob) {
  var reader = new FileReader()
  var promise = fileReaderReady(reader)
  reader.readAsArrayBuffer(blob)
  return promise
}

function readBlobAsText(blob) {
  var reader = new FileReader()
  var promise = fileReaderReady(reader)
  reader.readAsText(blob)
  return promise
}

function readArrayBufferAsText(buf) {
  var view = new Uint8Array(buf)
  var chars = new Array(view.length)

  for (var i = 0; i < view.length; i++) {
    chars[i] = String.fromCharCode(view[i])
  }
  return chars.join('')
}

function bufferClone(buf) {
  if (buf.slice) {
    return buf.slice(0)
  } else {
    var view = new Uint8Array(buf.byteLength)
    view.set(new Uint8Array(buf))
    return view.buffer
  }
}

function Body() {
  this.bodyUsed = false

  this._initBody = function(body) {
    this._bodyInit = body
    if (!body) {
      this._bodyText = ''
    } else if (typeof body === 'string') {
      this._bodyText = body
    } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
      this._bodyBlob = body
    } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
      this._bodyFormData = body
    } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
      this._bodyText = body.toString()
    } else if (support.arrayBuffer && support.blob && isDataView(body)) {
      this._bodyArrayBuffer = bufferClone(body.buffer)
      // IE 10-11 can't handle a DataView body.
      this._bodyInit = new Blob([this._bodyArrayBuffer])
    } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
      this._bodyArrayBuffer = bufferClone(body)
    } else {
      throw new Error('unsupported BodyInit type')
    }

    if (!this.headers.get('content-type')) {
      if (typeof body === 'string') {
        this.headers.set('content-type', 'text/plain;charset=UTF-8')
      } else if (this._bodyBlob && this._bodyBlob.type) {
        this.headers.set('content-type', this._bodyBlob.type)
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
      }
    }
  }

  if (support.blob) {
    this.blob = function() {
      var rejected = consumed(this)
      if (rejected) {
        return rejected
      }

      if (this._bodyBlob) {
        return Promise.resolve(this._bodyBlob)
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(new Blob([this._bodyArrayBuffer]))
      } else if (this._bodyFormData) {
        throw new Error('could not read FormData body as blob')
      } else {
        return Promise.resolve(new Blob([this._bodyText]))
      }
    }

    this.arrayBuffer = function() {
      if (this._bodyArrayBuffer) {
        return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
      } else {
        return this.blob().then(readBlobAsArrayBuffer)
      }
    }
  }

  this.text = function() {
    var rejected = consumed(this)
    if (rejected) {
      return rejected
    }

    if (this._bodyBlob) {
      return readBlobAsText(this._bodyBlob)
    } else if (this._bodyArrayBuffer) {
      return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
    } else if (this._bodyFormData) {
      throw new Error('could not read FormData body as text')
    } else {
      return Promise.resolve(this._bodyText)
    }
  }

  if (support.formData) {
    this.formData = function() {
      return this.text().then(decode)
    }
  }

  this.json = function() {
    return this.text().then(JSON.parse)
  }

  return this
}

// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

function normalizeMethod(method) {
  var upcased = method.toUpperCase()
  return methods.indexOf(upcased) > -1 ? upcased : method
}

export function Request(input, options) {
  options = options || {}
  var body = options.body

  if (input instanceof Request) {
    if (input.bodyUsed) {
      throw new TypeError('Already read')
    }
    this.url = input.url
    this.credentials = input.credentials
    if (!options.headers) {
      this.headers = new Headers(input.headers)
    }
    this.method = input.method
    this.mode = input.mode
    if (!body && input._bodyInit != null) {
      body = input._bodyInit
      input.bodyUsed = true
    }
  } else {
    this.url = String(input)
  }

  this.credentials = options.credentials || this.credentials || 'omit'
  if (options.headers || !this.headers) {
    this.headers = new Headers(options.headers)
  }
  this.method = normalizeMethod(options.method || this.method || 'GET')
  this.mode = options.mode || this.mode || null
  this.referrer = null

  if ((this.method === 'GET' || this.method === 'HEAD') && body) {
    throw new TypeError('Body not allowed for GET or HEAD requests')
  }
  this._initBody(body)
}

Request.prototype.clone = function() {
  return new Request(this, {body: this._bodyInit})
}

function decode(body) {
  var form = new FormData()
  body
    .trim()
    .split('&')
    .forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
  return form
}

function parseHeaders(rawHeaders) {
  var headers = new Headers()
  // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
  // https://tools.ietf.org/html/rfc7230#section-3.2
  var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ')
  preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
    var parts = line.split(':')
    var key = parts.shift().trim()
    if (key) {
      var value = parts.join(':').trim()
      headers.append(key, value)
    }
  })
  return headers
}

Body.call(Request.prototype)

export function Response(bodyInit, options) {
  if (!options) {
    options = {}
  }

  this.type = 'default'
  this.status = options.status === undefined ? 200 : options.status
  this.ok = this.status >= 200 && this.status < 300
  this.statusText = 'statusText' in options ? options.statusText : 'OK'
  this.headers = new Headers(options.headers)
  this.url = options.url || ''
  this._initBody(bodyInit)
}

Body.call(Response.prototype)

Response.prototype.clone = function() {
  return new Response(this._bodyInit, {
    status: this.status,
    statusText: this.statusText,
    headers: new Headers(this.headers),
    url: this.url
  })
}

Response.error = function() {
  var response = new Response(null, {status: 0, statusText: ''})
  response.type = 'error'
  return response
}

var redirectStatuses = [301, 302, 303, 307, 308]

Response.redirect = function(url, status) {
  if (redirectStatuses.indexOf(status) === -1) {
    throw new RangeError('Invalid status code')
  }

  return new Response(null, {status: status, headers: {location: url}})
}

export function fetch(input, init) {
  return new Promise(function(resolve, reject) {
    var request = new Request(input, init)
    var xhr = new XMLHttpRequest()

    xhr.onload = function() {
      var options = {
        status: xhr.status,
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders() || '')
      }
      options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
      var body = 'response' in xhr ? xhr.response : xhr.responseText
      resolve(new Response(body, options))
    }

    xhr.onerror = function() {
      reject(new TypeError('Network request failed'))
    }

    xhr.ontimeout = function() {
      reject(new TypeError('Network request failed'))
    }

    xhr.open(request.method, request.url, true)

    if (request.credentials === 'include') {
      xhr.withCredentials = true
    } else if (request.credentials === 'omit') {
      xhr.withCredentials = false
    }

    if ('responseType' in xhr && support.blob) {
      xhr.responseType = 'blob'
    }

    request.headers.forEach(function(value, name) {
      xhr.setRequestHeader(name, value)
    })

    xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
  })
}

fetch.polyfill = true

if (!self.fetch) {
  self.fetch = fetch
  self.Headers = Headers
  self.Request = Request
  self.Response = Response
}
<commit_msg>Make `fetch.js` compatible with eslint<commit_after>var support = {
  searchParams: 'URLSearchParams' in self,
  iterable: 'Symbol' in self && 'iterator' in Symbol,
  blob:
    'FileReader' in self &&
    'Blob' in self &&
    (function() {
      try {
        new Blob()
        return true
      } catch (e) {
        return false
      }
    })(),
  formData: 'FormData' in self,
  arrayBuffer: 'ArrayBuffer' in self
}

function isDataView(obj) {
  return obj && DataView.prototype.isPrototypeOf(obj)
}

if (support.arrayBuffer) {
  var viewClasses = [
    '[object Int8Array]',
    '[object Uint8Array]',
    '[object Uint8ClampedArray]',
    '[object Int16Array]',
    '[object Uint16Array]',
    '[object Int32Array]',
    '[object Uint32Array]',
    '[object Float32Array]',
    '[object Float64Array]'
  ]

  var isArrayBufferView =
    ArrayBuffer.isView ||
    function(obj) {
      return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
    }
}

function normalizeName(name) {
  if (typeof name !== 'string') {
    name = String(name)
  }
  if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) {
    throw new TypeError('Invalid character in header field name')
  }
  return name.toLowerCase()
}

function normalizeValue(value) {
  if (typeof value !== 'string') {
    value = String(value)
  }
  return value
}

// Build a destructive iterator for the value list
function iteratorFor(items) {
  var iterator = {
    next: function() {
      var value = items.shift()
      return {done: value === undefined, value: value}
    }
  }

  if (support.iterable) {
    iterator[Symbol.iterator] = function() {
      return iterator
    }
  }

  return iterator
}

export function Headers(headers) {
  this.map = {}

  if (headers instanceof Headers) {
    headers.forEach(function(value, name) {
      this.append(name, value)
    }, this)
  } else if (Array.isArray(headers)) {
    headers.forEach(function(header) {
      this.append(header[0], header[1])
    }, this)
  } else if (headers) {
    Object.getOwnPropertyNames(headers).forEach(function(name) {
      this.append(name, headers[name])
    }, this)
  }
}

Headers.prototype.append = function(name, value) {
  name = normalizeName(name)
  value = normalizeValue(value)
  var oldValue = this.map[name]
  this.map[name] = oldValue ? oldValue + ',' + value : value
}

Headers.prototype['delete'] = function(name) {
  delete this.map[normalizeName(name)]
}

Headers.prototype.get = function(name) {
  name = normalizeName(name)
  return this.has(name) ? this.map[name] : null
}

Headers.prototype.has = function(name) {
  return this.map.hasOwnProperty(normalizeName(name))
}

Headers.prototype.set = function(name, value) {
  this.map[normalizeName(name)] = normalizeValue(value)
}

Headers.prototype.forEach = function(callback, thisArg) {
  for (var name in this.map) {
    if (this.map.hasOwnProperty(name)) {
      callback.call(thisArg, this.map[name], name, this)
    }
  }
}

Headers.prototype.keys = function() {
  var items = []
  this.forEach(function(value, name) {
    items.push(name)
  })
  return iteratorFor(items)
}

Headers.prototype.values = function() {
  var items = []
  this.forEach(function(value) {
    items.push(value)
  })
  return iteratorFor(items)
}

Headers.prototype.entries = function() {
  var items = []
  this.forEach(function(value, name) {
    items.push([name, value])
  })
  return iteratorFor(items)
}

if (support.iterable) {
  Headers.prototype[Symbol.iterator] = Headers.prototype.entries
}

function consumed(body) {
  if (body.bodyUsed) {
    return Promise.reject(new TypeError('Already read'))
  }
  body.bodyUsed = true
}

function fileReaderReady(reader) {
  return new Promise(function(resolve, reject) {
    reader.onload = function() {
      resolve(reader.result)
    }
    reader.onerror = function() {
      reject(reader.error)
    }
  })
}

function readBlobAsArrayBuffer(blob) {
  var reader = new FileReader()
  var promise = fileReaderReady(reader)
  reader.readAsArrayBuffer(blob)
  return promise
}

function readBlobAsText(blob) {
  var reader = new FileReader()
  var promise = fileReaderReady(reader)
  reader.readAsText(blob)
  return promise
}

function readArrayBufferAsText(buf) {
  var view = new Uint8Array(buf)
  var chars = new Array(view.length)

  for (var i = 0; i < view.length; i++) {
    chars[i] = String.fromCharCode(view[i])
  }
  return chars.join('')
}

function bufferClone(buf) {
  if (buf.slice) {
    return buf.slice(0)
  } else {
    var view = new Uint8Array(buf.byteLength)
    view.set(new Uint8Array(buf))
    return view.buffer
  }
}

function Body() {
  this.bodyUsed = false

  this._initBody = function(body) {
    this._bodyInit = body
    if (!body) {
      this._bodyText = ''
    } else if (typeof body === 'string') {
      this._bodyText = body
    } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
      this._bodyBlob = body
    } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
      this._bodyFormData = body
    } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
      this._bodyText = body.toString()
    } else if (support.arrayBuffer && support.blob && isDataView(body)) {
      this._bodyArrayBuffer = bufferClone(body.buffer)
      // IE 10-11 can't handle a DataView body.
      this._bodyInit = new Blob([this._bodyArrayBuffer])
    } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
      this._bodyArrayBuffer = bufferClone(body)
    } else {
      throw new Error('unsupported BodyInit type')
    }

    if (!this.headers.get('content-type')) {
      if (typeof body === 'string') {
        this.headers.set('content-type', 'text/plain;charset=UTF-8')
      } else if (this._bodyBlob && this._bodyBlob.type) {
        this.headers.set('content-type', this._bodyBlob.type)
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
      }
    }
  }

  if (support.blob) {
    this.blob = function() {
      var rejected = consumed(this)
      if (rejected) {
        return rejected
      }

      if (this._bodyBlob) {
        return Promise.resolve(this._bodyBlob)
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(new Blob([this._bodyArrayBuffer]))
      } else if (this._bodyFormData) {
        throw new Error('could not read FormData body as blob')
      } else {
        return Promise.resolve(new Blob([this._bodyText]))
      }
    }

    this.arrayBuffer = function() {
      if (this._bodyArrayBuffer) {
        return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
      } else {
        return this.blob().then(readBlobAsArrayBuffer)
      }
    }
  }

  this.text = function() {
    var rejected = consumed(this)
    if (rejected) {
      return rejected
    }

    if (this._bodyBlob) {
      return readBlobAsText(this._bodyBlob)
    } else if (this._bodyArrayBuffer) {
      return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
    } else if (this._bodyFormData) {
      throw new Error('could not read FormData body as text')
    } else {
      return Promise.resolve(this._bodyText)
    }
  }

  if (support.formData) {
    this.formData = function() {
      return this.text().then(decode)
    }
  }

  this.json = function() {
    return this.text().then(JSON.parse)
  }

  return this
}

// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

function normalizeMethod(method) {
  var upcased = method.toUpperCase()
  return methods.indexOf(upcased) > -1 ? upcased : method
}

export function Request(input, options) {
  options = options || {}
  var body = options.body

  if (input instanceof Request) {
    if (input.bodyUsed) {
      throw new TypeError('Already read')
    }
    this.url = input.url
    this.credentials = input.credentials
    if (!options.headers) {
      this.headers = new Headers(input.headers)
    }
    this.method = input.method
    this.mode = input.mode
    if (!body && input._bodyInit != null) {
      body = input._bodyInit
      input.bodyUsed = true
    }
  } else {
    this.url = String(input)
  }

  this.credentials = options.credentials || this.credentials || 'omit'
  if (options.headers || !this.headers) {
    this.headers = new Headers(options.headers)
  }
  this.method = normalizeMethod(options.method || this.method || 'GET')
  this.mode = options.mode || this.mode || null
  this.referrer = null

  if ((this.method === 'GET' || this.method === 'HEAD') && body) {
    throw new TypeError('Body not allowed for GET or HEAD requests')
  }
  this._initBody(body)
}

Request.prototype.clone = function() {
  return new Request(this, {body: this._bodyInit})
}

function decode(body) {
  var form = new FormData()
  body
    .trim()
    .split('&')
    .forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
  return form
}

function parseHeaders(rawHeaders) {
  var headers = new Headers()
  // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
  // https://tools.ietf.org/html/rfc7230#section-3.2
  var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ')
  preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
    var parts = line.split(':')
    var key = parts.shift().trim()
    if (key) {
      var value = parts.join(':').trim()
      headers.append(key, value)
    }
  })
  return headers
}

Body.call(Request.prototype)

export function Response(bodyInit, options) {
  if (!options) {
    options = {}
  }

  this.type = 'default'
  this.status = options.status === undefined ? 200 : options.status
  this.ok = this.status >= 200 && this.status < 300
  this.statusText = 'statusText' in options ? options.statusText : 'OK'
  this.headers = new Headers(options.headers)
  this.url = options.url || ''
  this._initBody(bodyInit)
}

Body.call(Response.prototype)

Response.prototype.clone = function() {
  return new Response(this._bodyInit, {
    status: this.status,
    statusText: this.statusText,
    headers: new Headers(this.headers),
    url: this.url
  })
}

Response.error = function() {
  var response = new Response(null, {status: 0, statusText: ''})
  response.type = 'error'
  return response
}

var redirectStatuses = [301, 302, 303, 307, 308]

Response.redirect = function(url, status) {
  if (redirectStatuses.indexOf(status) === -1) {
    throw new RangeError('Invalid status code')
  }

  return new Response(null, {status: status, headers: {location: url}})
}

export function fetch(input, init) {
  return new Promise(function(resolve, reject) {
    var request = new Request(input, init)
    var xhr = new XMLHttpRequest()

    xhr.onload = function() {
      var options = {
        status: xhr.status,
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders() || '')
      }
      options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
      var body = 'response' in xhr ? xhr.response : xhr.responseText
      resolve(new Response(body, options))
    }

    xhr.onerror = function() {
      reject(new TypeError('Network request failed'))
    }

    xhr.ontimeout = function() {
      reject(new TypeError('Network request failed'))
    }

    xhr.open(request.method, request.url, true)

    if (request.credentials === 'include') {
      xhr.withCredentials = true
    } else if (request.credentials === 'omit') {
      xhr.withCredentials = false
    }

    if ('responseType' in xhr && support.blob) {
      xhr.responseType = 'blob'
    }

    request.headers.forEach(function(value, name) {
      xhr.setRequestHeader(name, value)
    })

    xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
  })
}

fetch.polyfill = true

if (!self.fetch) {
  self.fetch = fetch
  self.Headers = Headers
  self.Request = Request
  self.Response = Response
}
<|endoftext|>


<commit_before>// Copyright 2015 Endless Mobile, Inc.

const Gdk = imports.gi.Gdk;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
const WebKit2 = imports.gi.WebKit2;

const ARTICLE_SEARCH_BUTTONS_SPACING = 10;
const ARTICLE_SEARCH_MAX_RESULTS = 200;

const InArticleSearch = new Lang.Class({
    Name: 'ArticleSearch',
    Extends: Gtk.Grid,

    _init: function(web_view) {
        this.parent({
            column_spacing: ARTICLE_SEARCH_BUTTONS_SPACING
        });

        this._web_view = web_view;

        this._search_entry = new Gtk.SearchEntry({
            hexpand: true
        });
        this._search_entry.connect('search-changed',
                                   this.search_changed.bind(this));
        this._search_entry.connect('key-press-event',
                                   this.on_key_press_event.bind(this));

        this._next_button = new Gtk.Button({
            image: Gtk.Image.new_from_icon_name('go-down-symbolic',
                                                Gtk.IconSize.MENU)
        });
        this._next_button.connect('clicked', this.search_next.bind(this));

        this._previous_button = new Gtk.Button({
            image: Gtk.Image.new_from_icon_name('go-up-symbolic',
                                                Gtk.IconSize.MENU)
        });
        this._previous_button.connect('clicked',
                                      this.search_previous.bind(this));

        this._close_button = new Gtk.Button({
            image: Gtk.Image.new_from_icon_name('window-close-symbolic',
                                                Gtk.IconSize.MENU)
        });
        this._close_button.connect('clicked', this.close.bind(this));

        this.attach(this._search_entry, 0, 0, 1, 1);
        this.attach(this._next_button, 1, 0, 1, 1);
        this.attach(this._previous_button, 2, 0, 1, 1);
        this.attach(this._close_button, 3, 0, 1, 1);
    },

    search_changed: function() {
        this._findController.search(this._search_entry.text,
                                    WebKit2.FindOptions.CASE_INSENSITIVE |
                                    WebKit2.FindOptions.WRAP_AROUND,
                                    ARTICLE_SEARCH_MAX_RESULTS);
    },

    search_next: function() {
        this._findController.search_next();
    },

    search_previous: function() {
        this._findController.search_previous();
    },

    close: function() {
        this.hide();

        this._web_view.grab_focus();
        this._search_entry.set_text("");
        this._findController.search_finish();
    },

    open: function() {
        this.show_all();
        this._search_entry.grab_focus();
        this._findController = this._web_view.get_find_controller();
    },

    on_key_press_event: function(widget, event) {
        let keyval = event.get_keyval()[1];
        let state = event.get_state()[1];

        if ((state & Gdk.ModifierType.SHIFT_MASK != 0) &&
             keyval === Gdk.KEY_Return) {
            this.search_previous();
        } else if (keyval === Gdk.KEY_Return) {
            this.search_next();
        }
    }
});
<commit_msg>Standardize single quotes<commit_after>// Copyright 2015 Endless Mobile, Inc.

const Gdk = imports.gi.Gdk;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
const WebKit2 = imports.gi.WebKit2;

const ARTICLE_SEARCH_BUTTONS_SPACING = 10;
const ARTICLE_SEARCH_MAX_RESULTS = 200;

const InArticleSearch = new Lang.Class({
    Name: 'ArticleSearch',
    Extends: Gtk.Grid,

    _init: function(web_view) {
        this.parent({
            column_spacing: ARTICLE_SEARCH_BUTTONS_SPACING
        });

        this._web_view = web_view;

        this._search_entry = new Gtk.SearchEntry({
            hexpand: true
        });
        this._search_entry.connect('search-changed',
                                   this.search_changed.bind(this));
        this._search_entry.connect('key-press-event',
                                   this.on_key_press_event.bind(this));

        this._next_button = new Gtk.Button({
            image: Gtk.Image.new_from_icon_name('go-down-symbolic',
                                                Gtk.IconSize.MENU)
        });
        this._next_button.connect('clicked', this.search_next.bind(this));

        this._previous_button = new Gtk.Button({
            image: Gtk.Image.new_from_icon_name('go-up-symbolic',
                                                Gtk.IconSize.MENU)
        });
        this._previous_button.connect('clicked',
                                      this.search_previous.bind(this));

        this._close_button = new Gtk.Button({
            image: Gtk.Image.new_from_icon_name('window-close-symbolic',
                                                Gtk.IconSize.MENU)
        });
        this._close_button.connect('clicked', this.close.bind(this));

        this.attach(this._search_entry, 0, 0, 1, 1);
        this.attach(this._next_button, 1, 0, 1, 1);
        this.attach(this._previous_button, 2, 0, 1, 1);
        this.attach(this._close_button, 3, 0, 1, 1);
    },

    search_changed: function() {
        this._findController.search(this._search_entry.text,
                                    WebKit2.FindOptions.CASE_INSENSITIVE |
                                    WebKit2.FindOptions.WRAP_AROUND,
                                    ARTICLE_SEARCH_MAX_RESULTS);
    },

    search_next: function() {
        this._findController.search_next();
    },

    search_previous: function() {
        this._findController.search_previous();
    },

    close: function() {
        this.hide();

        this._web_view.grab_focus();
        this._search_entry.set_text('');
        this._findController.search_finish();
    },

    open: function() {
        this.show_all();
        this._search_entry.grab_focus();
        this._findController = this._web_view.get_find_controller();
    },

    on_key_press_event: function(widget, event) {
        let keyval = event.get_keyval()[1];
        let state = event.get_state()[1];

        if ((state & Gdk.ModifierType.SHIFT_MASK != 0) &&
             keyval === Gdk.KEY_Return) {
            this.search_previous();
        } else if (keyval === Gdk.KEY_Return) {
            this.search_next();
        }
    }
});
<|endoftext|>


<commit_before>function initialize() {
  var mapCanvas = document.getElementById('map_canvas');
  var mapOptions = {
    center: new google.maps.LatLng(44.5403, -78.5463),
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  var map = new google.maps.Map(mapCanvas, mapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>location upload<commit_after>// CONFIG (Move to different file)
var endpoint = {
  points: 'points'
};

var appUrl = 'http://localhost:3000/api/'

// END CONFIG

var request = function (options) {
  var xhr = new XMLHttpRequest();
  xhr.open(options.method, options.url);
  xhr.addEventListener('loaded', options.callback);
  xhr.send(JSON.stringify(options.data || {}));
};
///////////////////////////////////////////////////

function initialize() {
  var mapCanvas = document.getElementById('map_canvas');
  var mapOptions = {
    center: new google.maps.LatLng(44.5403, -78.5463),
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  var map = new google.maps.Map(mapCanvas, mapOptions);
}

function submitLocation(data, cb) {
  var options = {
    method: 'POST',
    url: appUrl + endpoint.points,
    data: data,
    callback: cb
  }
  request(options);
}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    function(position) {
    var callback = function(event) {
      console.log(event);
    };
    var data = {
      name: new Date().toString(),
      coordinates: [position.coords.latitude, position.coords.longitude]
    }
    submitLocation(data, callback);
  },
  function(error) {
    console.log(error);
  },{ timeout: 30000, enableHighAccuracy:false}
  );
} else {
  console.log('Permission denied');
}

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

const exec = require('child_process').exec;
const version = process.versions.v8;
const tmpfile = path.join(__dirname, version+'.flags.json');

if (!fs.existsSync(tmpfile)) {
  exec('node --v8-options', function (execErr, result) {
    var flags;
    if (execErr) {
      throw new Error(execErr);
    } else {
      flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
        return match.substring(2);
      });
      fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' },
        function (writeErr) {
          if (writeErr) {
            throw new Error(writeErr);
          } else {
            console.log('flags for v8 '+version+' cached.');
          }
        }
      );
    }
  });
}

module.exports = require.bind(null, tmpfile);
<commit_msg>get node path from process.env._<commit_after>const fs = require('fs');
const path = require('path');

const exec = require('child_process').exec;
const nodepath = process.env._;
const version = process.versions.v8;
const tmpfile = path.join(__dirname, version+'.flags.json');

if (!fs.existsSync(tmpfile)) {
  exec(nodepath+' --v8-options', function (execErr, result) {
    var flags;
    if (execErr) {
      throw new Error(execErr);
    } else {
      flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
        return match.substring(2);
      });
      fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' },
        function (writeErr) {
          if (writeErr) {
            throw new Error(writeErr);
          } else {
            console.log('flags for v8 '+version+' cached.');
          }
        }
      );
    }
  });
}

module.exports = require.bind(null, tmpfile);
<|endoftext|>


<commit_before>var extend = require('util-extend');
var request = require('request');
var util = require('util');
var winston = require('winston');

/**
 * Slack integration for Winston
 */
function Slack(options) {
  if (!(typeof options === 'object' && options.webhook)) {
    throw new Error('Invalid options parameter');
  }
  this.webhook = options.webhook;
  this.customFormatter = options.customFormatter;
  options = extend({
    channel: '#general',
    username: 'winston-slacker',
    icon_url: false,
    icon_emoji: false,
    level: 'info',
    silent: false,
    raw: false,
    name: 'slacker',
    handleExceptions: false
  }, options);

  /**
 * Handles the sending of a message to an Incoming webhook
 * @param {object} Message object containing text, channel and username
 * @param {function} Callback function for post execution
 */
  this.send = function (message, callback) {
    var has_callback = typeof callback === 'function';
    if (!(typeof message === 'object' && message.text) && has_callback) {
      return callback(new Error('No message'));
    }
    var options = {
      channel: message.channel,
      text: message.text,
      username: message.username,
      icon_emoji: this.icon_emoji,
      icon_url: this.icon_url,
      attachments: this.attachments
    };

    var request_params = {
      url: this.webhook,
      body: options,
      json: true
    };

    request.post(request_params, function(err, res, body) {
      if ((err || body !== 'ok') && has_callback) {
        return callback(err || new Error(body));
      }
      if (has_callback) {
        callback(err, body);
      }
    });
  }
};

util.inherits(Slack, winston.Transport);
winston.transports.Slack = Slack;

/**
 * Log method for Winston integration
 * @param {string} Logging level
 * @param {string} Message to send to slack
 * @param {string} Meta data for styling
 * @param {function} Callback function for post execution
 */
Slack.prototype.log = function (level, message, meta, callback) {
    // Use custom formatter for message if set
    message = this.customFormatter ? this.customFormatter(level, message, meta) : {
      text: ['[', level , ']', ' ', message].join(''),
      channel: this.channel,
      username: this.username
    };
    this.send(message, callback);
};

exports.Slack = Slack;
<commit_msg>Code formatting<commit_after>var extend = require('util-extend');
var request = require('request');
var util = require('util');
var winston = require('winston');

/**
 * Slack integration for Winston
 */
function Slack(options) {
  if (!(typeof options === 'object' && options.webhook)) {
    throw new Error('Invalid options parameter');
  }
  this.webhook = options.webhook;
  this.customFormatter = options.customFormatter;
  options = extend({
    channel: '#general',
    username: 'winston-slacker',
    icon_url: false,
    icon_emoji: false,
    level: 'info',
    silent: false,
    raw: false,
    name: 'slacker',
    handleExceptions: false
  }, options);

  /**
 * Handles the sending of a message to an Incoming webhook
 * @param {object} Message object containing text, channel and username
 * @param {function} Callback function for post execution
 */
  this.send = function (message, callback) {
    var has_callback = typeof callback === 'function';
    if (!(typeof message === 'object' && message.text) && has_callback) {
      return callback(new Error('No message'));
    }
    var options = {
      channel: message.channel,
      text: message.text,
      username: message.username,
      icon_emoji: this.icon_emoji,
      icon_url: this.icon_url,
      attachments: this.attachments
    };
    var request_params = {
      url: this.webhook,
      body: options,
      json: true
    };

    request.post(request_params, function(err, res, body) {
      if ((err || body !== 'ok') && has_callback) {
        return callback(err || new Error(body));
      }
      if (has_callback) {
        callback(err, body);
      }
    });
  }
};

util.inherits(Slack, winston.Transport);
winston.transports.Slack = Slack;

/**
 * Log method for Winston integration
 * @param {string} Logging level
 * @param {string} Message to send to slack
 * @param {string} Meta data for styling
 * @param {function} Callback function for post execution
 */
Slack.prototype.log = function (level, message, meta, callback) {
    // Use custom formatter for message if set
    message = this.customFormatter ? this.customFormatter(level, message, meta) : {
      text: ['[', level , ']', ' ', message].join(''),
      channel: this.channel,
      username: this.username
    };
    this.send(message, callback);
};

exports.Slack = Slack;
<|endoftext|>


<commit_before>$(function () {
    'use strict';

    var currentUser = "miika";

    //Displays all the results gotten from the api call
    function displaySearchResults(results) {
        console.log(results);
        var searchArr = [];
        if (results.Response == "True") {
            $('#searchResults').empty();
            countPages(results.totalResults);
            $('#searchResults').append('

Total Results: ' + results.totalResults + '

');
            searchArr = results.Search;
            for (var i = 0; i < searchArr.length; i++) {
                console.log(searchArr[i]);
                //hide error from previous search
                $('#error').hide();
                $('#searchResults').append('

' + searchArr[i].Title + ' (' + searchArr[i].Year + ')

');
                if (searchArr[i].Type == "movie") {
                    $('#' + searchArr[i].imdbID).append('

');
                } else if (searchArr[i].Type == "series") {
                    $('#' + searchArr[i].imdbID).append('

');
                } else if (searchArr[i].Type == "game") {
                    $('#' + searchArr[i].imdbID).append('

');
                }
            }
            initListeners();
            $('#searchResults').show();
        }
        // displays error message if no results was found
        else {
            $('#searchResults').hide();
            $('#content').hide();
            $('#error').find('.message').text('No results');
            $('#error').show();
        }
    }

    // Counts and displays pagenumbers
    function countPages(totalResults) {
        var totalPages = Math.ceil(totalResults / 10);
        $('#searchResults').append('

');
        if (totalPages > 1) {
            if (totalPages <= 100) {
                for (var i = 1; i <= totalPages; i++) {
                    $('#pages').append(' ' + i + ' ');
                }
            } else {
                for (var o = 1; o <= 100; o++) {
                    $('#pages').append(' ' + o + ' ');
                }
                $('#pages').append('
Only 100 pages can be shown
');
            }
        }
        initListeners();
    }

    //Displays data of a single result gotten from the api call
    function displayData(data) {
        console.log(data);

        if (data.Response == "True") {
            $('#error').hide();
            $('#searchResults').hide();
            $('#details').empty();
            $('#details').append('<input type="hidden" id="imdbID" value="' + data.imdbID + '">');
            $('#details').append('<input type="hidden" id="title" value="' + data.Title + '">');
            $('#details').append('<input type="hidden" id="type" value="' + data.Type + '">');
            $('#details').append('Go Back
' + data.Title + '(' + data.Year + ')

Plot

' + data.Plot + '

IMDb rating: ' + data.imdbRating + '

Rotten tomatoes rating: ' + data.tomatoRating + '

');

            //show content when data is received
            initListeners();
            $('.searchForm').hide();
            $('#details').show();

            // displays error message if no show/movie was found
        } else {
            $('#details').hide();
            $('#error').find('.message').text(data.Error);
            $('#error').show();
        }
    }

    function getUser(username, password) {
        var url = 'http://watchlist-miikanode.rhcloud.com/getUser?username=' + username + '&password=' + password;
        $.get(url);
    }

    function addToList(username, id, title, type) {
        var url = 'http://watchlist-miikanode.rhcloud.com/addToList?username=' + username + '&id=' + id + '&title=' + title + '&type=' + type;
        $.get(url);
    }

    // Sends username and password to the database (NOT HASHED)
    function addUser(username, password) {
        var url = 'http://watchlist-miikanode.rhcloud.com/addUser?username=' + username + '&password=' + password;
        $.get(url);
        window.location = '../index.html';
    }

    // makes a search api call with title, type, year and page parameters
    function apiCallSearch(title, type, year, page) {
        var url = 'http://www.omdbapi.com/?s=' + title + '&y=' + year + '&type=' + type + '&tomatoes=true&plot=full&page=' + page;
        $.get(url, function (response) {
            displaySearchResults(response);
        });
    }
    // makes a search api call with id
    function apiCallDetails(id) {
        var url = 'http://www.omdbapi.com/?i=' + id + '&tomatoes=true&plot=full';
        $.get(url, function (response) {
            displayData(response);
        });
    }

    // initiates listeners when called
    function initListeners() {
        $('.searchForm').on('submit', function (event) {
            event.preventDefault();
            var page = 1;
            var title = $('form').find('#title').val();
            var type = $('form').find('select').val();
            var year = $('form').find('#year').val();
            apiCallSearch(title, type, year, page);
        });
        $('.signupForm').on('submit', function (event) {
            event.preventDefault();
            var username = $('form').find('#username').val();
            var password = $('form').find('#password').val();
            addUser(username, password);
        });
        $('.loginForm').on('submit', function (event) {
            event.preventDefault();
            var username = $('form').find('#username').val();
            var password = $('form').find('#password').val();
            getUser(username, password);
        });

        $('.result').on('click', function () {
            var id = $(this).attr("id");
            apiCallDetails(id);
        });

        $('.pageNum').on('click', function () {
            var page = $(this).attr("id");
            var title = $('form').find('#title').val();
            var type = $('form').find('select').val();
            var year = $('form').find('#year').val();
            apiCallSearch(title, type, year, page);
        });

        $('#goBack').on('click', function () {
            $('.searchForm').show();
            $('#details').hide();
            $('#searchResults').show();
        });
        $('#addToList').on('click', function () {
            var id = $('#imdbID').attr("val");
            var title = $('#title').attr("val");
            var type = $('#type').attr("val");
            addToList(currentUser, id, title, type);
        });

    }

    //Starts the app
    function start() {
        // hide content on load
        $('#content').hide();
        $('#error').hide();
        initListeners();
    }
    start();
});<commit_msg>add to list<commit_after>$(function () {
    'use strict';

    var currentUser = "miika";

    //Displays all the results gotten from the api call
    function displaySearchResults(results) {
        console.log(results);
        var searchArr = [];
        if (results.Response == "True") {
            $('#searchResults').empty();
            countPages(results.totalResults);
            $('#searchResults').append('

Total Results: ' + results.totalResults + '

');
            searchArr = results.Search;
            for (var i = 0; i < searchArr.length; i++) {
                console.log(searchArr[i]);
                //hide error from previous search
                $('#error').hide();
                $('#searchResults').append('

' + searchArr[i].Title + ' (' + searchArr[i].Year + ')

');
                if (searchArr[i].Type == "movie") {
                    $('#' + searchArr[i].imdbID).append('

');
                } else if (searchArr[i].Type == "series") {
                    $('#' + searchArr[i].imdbID).append('

');
                } else if (searchArr[i].Type == "game") {
                    $('#' + searchArr[i].imdbID).append('

');
                }
            }
            initListeners();
            $('#searchResults').show();
        }
        // displays error message if no results was found
        else {
            $('#searchResults').hide();
            $('#content').hide();
            $('#error').find('.message').text('No results');
            $('#error').show();
        }
    }

    // Counts and displays pagenumbers
    function countPages(totalResults) {
        var totalPages = Math.ceil(totalResults / 10);
        $('#searchResults').append('

');
        if (totalPages > 1) {
            if (totalPages <= 100) {
                for (var i = 1; i <= totalPages; i++) {
                    $('#pages').append(' ' + i + ' ');
                }
            } else {
                for (var o = 1; o <= 100; o++) {
                    $('#pages').append(' ' + o + ' ');
                }
                $('#pages').append('
Only 100 pages can be shown
');
            }
        }
        initListeners();
    }

    //Displays data of a single result gotten from the api call
    function displayData(data) {
        console.log(data);

        if (data.Response == "True") {
            $('#error').hide();
            $('#searchResults').hide();
            $('#details').empty();
            $('#details').append('<input type="hidden" id="imdbID" value="' + data.imdbID + '">');
            $('#details').append('<input type="hidden" id="title" value="' + data.Title + '">');
            $('#details').append('<input type="hidden" id="type" value="' + data.Type + '">');
            $('#details').append('Go Back
' + data.Title + '(' + data.Year + ')

Plot

' + data.Plot + '

IMDb rating: ' + data.imdbRating + '

Rotten tomatoes rating: ' + data.tomatoRating + '

');

            //show content when data is received
            initListeners();
            $('.searchForm').hide();
            $('#details').show();

            // displays error message if no show/movie was found
        } else {
            $('#details').hide();
            $('#error').find('.message').text(data.Error);
            $('#error').show();
        }
    }

    function getUser(username, password) {
        var url = 'http://watchlist-miikanode.rhcloud.com/getUser?username=' + username + '&password=' + password;
        $.get(url);
    }

    function addToList(username, id, title, type) {
        var url = 'http://watchlist-miikanode.rhcloud.com/addToList?username=' + username + '&id=' + id + '&title=' + title + '&type=' + type;
        $.get(url);
    }

    // Sends username and password to the database (NOT HASHED)
    function addUser(username, password) {
        var url = 'http://watchlist-miikanode.rhcloud.com/addUser?username=' + username + '&password=' + password;
        $.get(url);
        window.location = '../index.html';
    }

    // makes a search api call with title, type, year and page parameters
    function apiCallSearch(title, type, year, page) {
        var url = 'http://www.omdbapi.com/?s=' + title + '&y=' + year + '&type=' + type + '&tomatoes=true&plot=full&page=' + page;
        $.get(url, function (response) {
            displaySearchResults(response);
        });
    }
    // makes a search api call with id
    function apiCallDetails(id) {
        var url = 'http://www.omdbapi.com/?i=' + id + '&tomatoes=true&plot=full';
        $.get(url, function (response) {
            displayData(response);
        });
    }

    // initiates listeners when called
    function initListeners() {
        $('.searchForm').on('submit', function (event) {
            event.preventDefault();
            var page = 1;
            var title = $('form').find('#title').val();
            var type = $('form').find('select').val();
            var year = $('form').find('#year').val();
            apiCallSearch(title, type, year, page);
        });
        $('.signupForm').on('submit', function (event) {
            event.preventDefault();
            var username = $('form').find('#username').val();
            var password = $('form').find('#password').val();
            addUser(username, password);
        });
        $('.loginForm').on('submit', function (event) {
            event.preventDefault();
            var username = $('form').find('#username').val();
            var password = $('form').find('#password').val();
            getUser(username, password);
        });

        $('.result').on('click', function () {
            var id = $(this).attr("id");
            apiCallDetails(id);
        });

        $('.pageNum').on('click', function () {
            var page = $(this).attr("id");
            var title = $('form').find('#title').val();
            var type = $('form').find('select').val();
            var year = $('form').find('#year').val();
            apiCallSearch(title, type, year, page);
        });

        $('#goBack').on('click', function () {
            $('.searchForm').show();
            $('#details').hide();
            $('#searchResults').show();
        });
        $('#addToList').on('click', function () {
            var id = $('#imdbID').attr("value");
            var title = $('#title').attr("value");
            var type = $('#type').attr("value");
            addToList(currentUser, id, title, type);
        });
    }

    //Starts the app
    function start() {
        // hide content on load
        $('#content').hide();
        $('#error').hide();
        initListeners();
    }
    start();
});<|endoftext|>


<commit_before>ajax_url = 'https://kmu43f0xqb.execute-api.us-east-1.amazonaws.com/prod/posts/';
ajax_posts_url = 'posts/';

posting_delay = 10;
button_delay = 3;
auto_refresh_delay = 30000;
bulk_load_amount = 5;

postIds = [];
highest_id = null;
lowest_id = null;

function getLatestPost(){
	loading();
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == XMLHttpRequest.DONE) {
			if (xmlhttp.status == 200) {
				var resp = JSON.parse(xmlhttp.responseText);
				console.log('Latest post: '+resp.postId);
				for (var i = 0; i < bulk_load_amount; i++){
					getPost(resp.postId - i);
				}
			} else if (xmlhttp.status == 400) {
				//TODO alert('There was an error 400');
			} else {
				//TODO alert('something else other than 200 was returned');
			}
		}
	};
	xmlhttp.open("GET", ajax_url, true);
	xmlhttp.send();
}

function getPost(postId){
	console.log('Checking: '+postId);
	if (!postId || postId < 1 || postIds.indexOf(postId) > -1){
		// Too low or already loaded
		return;
	}
	loading();
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == XMLHttpRequest.DONE) {
			if (xmlhttp.status == 200) {
				console.log('Latest post: '+xmlhttp.responseText)
				addPost(JSON.parse(xmlhttp.responseText));
			} else if (xmlhttp.status == 400) {
				console.log('There was an error 400');
				//TODO alert('There was an error 400');
			} else {
				console.log('something else other than 200 was returned');
				//TODO alert('something else other than 200 was returned');
			}
			unloading();
		}
	};
	xmlhttp.open("GET", ajax_posts_url + postId + '.json', true);
	xmlhttp.send();
}

function addPost(postObj){
	// Check post not already exists
	var exist = document.getElementById('post'+postObj.postId);
	if (exist === null){
		// Create post
		var post = document.createElement('div');
		post.className = 'panel transparent';
		post.id = 'post'+postObj.postId;
		// Top info
		var postTop = document.createElement('div');
		post.appendChild(postTop);
		post.appendChild(document.createElement('hr'));
		// Post postId
		if (postObj.postId){
			var postId = document.createElement('a');
			postId.href = '#';
			postId.innerText = '>>' + postObj.postId;
			postId.onclick = function(){
				quote(postObj.postId);
			};
			postTop.appendChild(postId);
		}
		// Date
		if (postObj.time){
			t = new Date(postObj.time);
			var postTime = document.createElement('span');
			postTime.innerText = t.toLocaleString();
			postTime.className = 'right';
			postTop.appendChild(postTime);
		}
		// Image
		if (postObj.img){
			var postImg = document.createElement('img');
			postImg.src = postObj.img;
			postImg.onerror = imageError;
			post.appendChild(postImg);
		}
		// Text
		if (postObj.msg){
			var postTextP = document.createElement('p');
			// Linkify
			var re = />>\d+/g
			postText = postObj.msg;
			var m = postText.match(re)
			var i = -1;
			if (m != null){
				i = postText.indexOf(m[0]);
			}
			while (i != -1){
				var temp;
				var s;
				if (i != 0){
					// Text
					temp = postText.split('');
					s = temp.splice(0, i).join('');
					postText = temp.join('');
					postTextP.appendChild(document.createTextNode(s));
				}
				// Post reference
				var el = document.createElement('a');
				temp = postText.split('');
				s = temp.splice(0, postText.match(re)[0].length).join('');
				postText = temp.join('');
				el.innerText = s;
				elPostId = s.slice(2, s.length);
				el.href = '#post'+elPostId;
				el.onclick = function(){
					// Download post if not on page
					if (postIds.indexOf(elPostId) == -1){
						getPost(elPostId);
					}
					return true;
				}
				postTextP.appendChild(el);
				m = postText.match(re)
				i = -1;
				if (m != null){
					i = postText.indexOf(m[0]);
				}
			}
			if (postText.length > 0){
				postTextP.appendChild(document.createTextNode(postText));
			}
			linkifyElement(postTextP, {
				ignoreTags: ['script', 'a'],
				nl2br: true
			});
			post.appendChild(postTextP);
		}
		// Add post
		var before = 0;
		for (var i = 0; i < postIds.length; i++){
			if (postIds[i] > before && postObj.postId > postIds[i]){
				before = postIds[i];
			}
		}
		var postContainer = document.getElementById('postcontainer');
		if (before <= 0){
			postContainer.appendChild(post);
		} else {
			postContainer.insertBefore(post, document.getElementById('post'+before));
		}
		// Mark added
		postIds.push(postObj.postId);
		if (highest_id == null || postObj.postId > highest_id){
			highest_id = postObj.postId;
		}
		if (lowest_id == null || postObj.postId < lowest_id){
			lowest_id = postObj.postId;
			if (lowest_id <= 1){
				document.getElementById('ancient').className = 'transparent';
			}
		}
		// Transition
		setTimeout(function(){
			post.className = 'panel';
			// Auto-scroll to prevent jumping if not at top
			if (window.scrollY != 0){
				window.scrollTo(window.scrollX, window.scrollY + post.scrollHeight);
			}
		}, 50);
	}
}

function imageError(){
	this.onerror = null;
	this.src = 'img/broken.jpg';
}

// Quote a post
function quote(postId){
	var postMsg = document.getElementById('postMsg');
	pos = postMsg.selectionStart;
	postMsg.value = postMsg.value.substr(0, pos) + '>>' + postId + '\n' + postMsg.value.substr(pos);
	postMsg.focus();
	return false;
}

function makePost(){
	var makePostButton = document.getElementById('makePost');
	makePostButton.disabled = true;

	var post = {};
	var postMsg = document.getElementById('postMsg');
	post.msg = postMsg.value;
	postMsg.value = '';
	var postImg = document.getElementById('postImg');
	post.img = postImg.value;
	postImg.value = '';
	previewImage();

	if (post.msg != '' || post.img != ''){
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == XMLHttpRequest.DONE) {
				if (xmlhttp.status == 200) {
					// Success
				} else if (xmlhttp.status == 400) {
					console.log('There was an error 400');
					//TODO alert('There was an error 400');
				} else {
					console.log('something else other than 200 was returned');
					//TODO alert('something else other than 200 was returned');
				}
				impatientClick();
			}
			buttonTimedDisable(makePostButton, 'Post', posting_delay);
		};

		xmlhttp.open("POST", ajax_url, true);
		xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
		xmlhttp.send(JSON.stringify(post));
	} else {
		makePostButton.disabled = false;
	}
}

// Load newer posts
function impatientClick(){
	var impatient = document.getElementById('impatient');
	impatient.disabled = true;
	if (highest_id == null){
		getLatestPost();
	} else {
		getPost(highest_id+1);
	}
	buttonTimedDisable(impatient, 'Impatient', button_delay);
}

// Load older posts
function ancientClick(){
	var ancient = document.getElementById('ancient');
	ancient.disabled = true;
	for (var i = 1; i <= bulk_load_amount; i++){
		getPost(lowest_id-i);
	}
	buttonTimedDisable(ancient, 'Ancient', button_delay);
}

function buttonTimedDisable(butt, initText, seconds, repeat){
	butt.disabled = true;
	if (repeat == true){
		//butt.innerText = initText;
	}
	if (seconds <= 0){
		butt.disabled = false;
	} else {
		//butt.innerText += ' '+seconds+'...';
		setTimeout(function(){
			buttonTimedDisable(butt, initText, seconds-1, true);
		}, 1000);
	}
}

function loading(){
	document.getElementById('loading').className = '';
	if (document.getElementById('postcontainer').firstElementChild != null &&
			document.getElementById('ancient').className != 'transparent'){
		document.getElementById('loadingLower').className = '';
	}
}

function unloading(){
	document.getElementById('loading').className = 'transparent';
	document.getElementById('loadingLower').className = 'transparent';
}

// Preview post images
function previewImage(){
	var postImgSrc = document.getElementById('postImg').value;
	var previewImg = document.getElementById('postImgPreview');
	if (postImgSrc == ''){
		previewImg.className = 'hidden';
	} else {
		previewImg.className = 'preview';
		previewImg.src = postImgSrc;
		previewImg.onerror = imageError;
	}
}

/* Themes */
var themes = ['', 'Native', 'Amber', 'Cyaneila'];

function initThemes(){
	var themeSelect = document.getElementById('themeSelect');
	for (var i = 0; i < themes.length; i++){
		var opt = document.createElement('option');
		opt.innerText = themes[i];
		opt.value = themes[i];
		themeSelect.appendChild(opt);
	}
	// Default to first non-blank
	themeSelect.selectedIndex = 1;
	toggleTheme();
}

function toggleTheme(){
	var themeSelect = document.getElementById('themeSelect');
	var theme = themeSelect.options[themeSelect.selectedIndex].value;
	document.documentElement.className = theme;
	document.getElementById('themeCss').href = 'css/' + theme.toLowerCase() + '.css';
}

/* Init */
function init(){
	// Set up themes
	initThemes();
	document.getElementById('themeSelect').onchange = toggleTheme;
	// Set up buttons
	document.getElementById('impatient').onclick = impatientClick;
	document.getElementById('ancient').onclick = ancientClick;
	document.getElementById('makePost').onclick = makePost;
	document.getElementById('postImg').onchange = previewImage;
	document.getElementById('postImg').onpaste = function(){
		setTimeout(previewImage, 5);
	};

	// Initial load
	impatientClick();
	// Resolve hash
	var hash = window.location.hash.split('post');
	if (hash.length > 0){
		getPost(hash[1]);
	}
	// Auto refresh
	setInterval(impatientClick, auto_refresh_delay);
}
init();

/* Ads */
function adBlockDetected() {
	document.getElementById('adBlockPlea').className = '';
}

if (typeof blockAdBlock === 'undefined') {
	adBlockDetected();
} else {
	blockAdBlock.onDetected(adBlockDetected);
}
<commit_msg>Randomly select a theme on load<commit_after>ajax_url = 'https://kmu43f0xqb.execute-api.us-east-1.amazonaws.com/prod/posts/';
ajax_posts_url = 'posts/';

posting_delay = 10;
button_delay = 3;
auto_refresh_delay = 30000;
bulk_load_amount = 5;

postIds = [];
highest_id = null;
lowest_id = null;

function getLatestPost(){
	loading();
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == XMLHttpRequest.DONE) {
			if (xmlhttp.status == 200) {
				var resp = JSON.parse(xmlhttp.responseText);
				console.log('Latest post: '+resp.postId);
				for (var i = 0; i < bulk_load_amount; i++){
					getPost(resp.postId - i);
				}
			} else if (xmlhttp.status == 400) {
				//TODO alert('There was an error 400');
			} else {
				//TODO alert('something else other than 200 was returned');
			}
		}
	};
	xmlhttp.open("GET", ajax_url, true);
	xmlhttp.send();
}

function getPost(postId){
	console.log('Checking: '+postId);
	if (!postId || postId < 1 || postIds.indexOf(postId) > -1){
		// Too low or already loaded
		return;
	}
	loading();
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == XMLHttpRequest.DONE) {
			if (xmlhttp.status == 200) {
				console.log('Latest post: '+xmlhttp.responseText)
				addPost(JSON.parse(xmlhttp.responseText));
			} else if (xmlhttp.status == 400) {
				console.log('There was an error 400');
				//TODO alert('There was an error 400');
			} else {
				console.log('something else other than 200 was returned');
				//TODO alert('something else other than 200 was returned');
			}
			unloading();
		}
	};
	xmlhttp.open("GET", ajax_posts_url + postId + '.json', true);
	xmlhttp.send();
}

function addPost(postObj){
	// Check post not already exists
	var exist = document.getElementById('post'+postObj.postId);
	if (exist === null){
		// Create post
		var post = document.createElement('div');
		post.className = 'panel transparent';
		post.id = 'post'+postObj.postId;
		// Top info
		var postTop = document.createElement('div');
		post.appendChild(postTop);
		post.appendChild(document.createElement('hr'));
		// Post postId
		if (postObj.postId){
			var postId = document.createElement('a');
			postId.href = '#';
			postId.innerText = '>>' + postObj.postId;
			postId.onclick = function(){
				quote(postObj.postId);
			};
			postTop.appendChild(postId);
		}
		// Date
		if (postObj.time){
			t = new Date(postObj.time);
			var postTime = document.createElement('span');
			postTime.innerText = t.toLocaleString();
			postTime.className = 'right';
			postTop.appendChild(postTime);
		}
		// Image
		if (postObj.img){
			var postImg = document.createElement('img');
			postImg.src = postObj.img;
			postImg.onerror = imageError;
			post.appendChild(postImg);
		}
		// Text
		if (postObj.msg){
			var postTextP = document.createElement('p');
			// Linkify
			var re = />>\d+/g
			postText = postObj.msg;
			var m = postText.match(re)
			var i = -1;
			if (m != null){
				i = postText.indexOf(m[0]);
			}
			while (i != -1){
				var temp;
				var s;
				if (i != 0){
					// Text
					temp = postText.split('');
					s = temp.splice(0, i).join('');
					postText = temp.join('');
					postTextP.appendChild(document.createTextNode(s));
				}
				// Post reference
				var el = document.createElement('a');
				temp = postText.split('');
				s = temp.splice(0, postText.match(re)[0].length).join('');
				postText = temp.join('');
				el.innerText = s;
				elPostId = s.slice(2, s.length);
				el.href = '#post'+elPostId;
				el.onclick = function(){
					// Download post if not on page
					if (postIds.indexOf(elPostId) == -1){
						getPost(elPostId);
					}
					return true;
				}
				postTextP.appendChild(el);
				m = postText.match(re)
				i = -1;
				if (m != null){
					i = postText.indexOf(m[0]);
				}
			}
			if (postText.length > 0){
				postTextP.appendChild(document.createTextNode(postText));
			}
			linkifyElement(postTextP, {
				ignoreTags: ['script', 'a'],
				nl2br: true
			});
			post.appendChild(postTextP);
		}
		// Add post
		var before = 0;
		for (var i = 0; i < postIds.length; i++){
			if (postIds[i] > before && postObj.postId > postIds[i]){
				before = postIds[i];
			}
		}
		var postContainer = document.getElementById('postcontainer');
		if (before <= 0){
			postContainer.appendChild(post);
		} else {
			postContainer.insertBefore(post, document.getElementById('post'+before));
		}
		// Mark added
		postIds.push(postObj.postId);
		if (highest_id == null || postObj.postId > highest_id){
			highest_id = postObj.postId;
		}
		if (lowest_id == null || postObj.postId < lowest_id){
			lowest_id = postObj.postId;
			if (lowest_id <= 1){
				document.getElementById('ancient').className = 'transparent';
			}
		}
		// Transition
		setTimeout(function(){
			post.className = 'panel';
			// Auto-scroll to prevent jumping if not at top
			if (window.scrollY != 0){
				window.scrollTo(window.scrollX, window.scrollY + post.scrollHeight);
			}
		}, 50);
	}
}

function imageError(){
	this.onerror = null;
	this.src = 'img/broken.jpg';
}

// Quote a post
function quote(postId){
	var postMsg = document.getElementById('postMsg');
	pos = postMsg.selectionStart;
	postMsg.value = postMsg.value.substr(0, pos) + '>>' + postId + '\n' + postMsg.value.substr(pos);
	postMsg.focus();
	return false;
}

function makePost(){
	var makePostButton = document.getElementById('makePost');
	makePostButton.disabled = true;

	var post = {};
	var postMsg = document.getElementById('postMsg');
	post.msg = postMsg.value;
	postMsg.value = '';
	var postImg = document.getElementById('postImg');
	post.img = postImg.value;
	postImg.value = '';
	previewImage();

	if (post.msg != '' || post.img != ''){
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == XMLHttpRequest.DONE) {
				if (xmlhttp.status == 200) {
					// Success
				} else if (xmlhttp.status == 400) {
					console.log('There was an error 400');
					//TODO alert('There was an error 400');
				} else {
					console.log('something else other than 200 was returned');
					//TODO alert('something else other than 200 was returned');
				}
				impatientClick();
			}
			buttonTimedDisable(makePostButton, 'Post', posting_delay);
		};

		xmlhttp.open("POST", ajax_url, true);
		xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
		xmlhttp.send(JSON.stringify(post));
	} else {
		makePostButton.disabled = false;
	}
}

// Load newer posts
function impatientClick(){
	var impatient = document.getElementById('impatient');
	impatient.disabled = true;
	if (highest_id == null){
		getLatestPost();
	} else {
		getPost(highest_id+1);
	}
	buttonTimedDisable(impatient, 'Impatient', button_delay);
}

// Load older posts
function ancientClick(){
	var ancient = document.getElementById('ancient');
	ancient.disabled = true;
	for (var i = 1; i <= bulk_load_amount; i++){
		getPost(lowest_id-i);
	}
	buttonTimedDisable(ancient, 'Ancient', button_delay);
}

function buttonTimedDisable(butt, initText, seconds, repeat){
	butt.disabled = true;
	if (repeat == true){
		//butt.innerText = initText;
	}
	if (seconds <= 0){
		butt.disabled = false;
	} else {
		//butt.innerText += ' '+seconds+'...';
		setTimeout(function(){
			buttonTimedDisable(butt, initText, seconds-1, true);
		}, 1000);
	}
}

function loading(){
	document.getElementById('loading').className = '';
	if (document.getElementById('postcontainer').firstElementChild != null &&
			document.getElementById('ancient').className != 'transparent'){
		document.getElementById('loadingLower').className = '';
	}
}

function unloading(){
	document.getElementById('loading').className = 'transparent';
	document.getElementById('loadingLower').className = 'transparent';
}

// Preview post images
function previewImage(){
	var postImgSrc = document.getElementById('postImg').value;
	var previewImg = document.getElementById('postImgPreview');
	if (postImgSrc == ''){
		previewImg.className = 'hidden';
	} else {
		previewImg.className = 'preview';
		previewImg.src = postImgSrc;
		previewImg.onerror = imageError;
	}
}

/* Themes */
var themes = ['', 'Native', 'Amber', 'Cyaneila'];

function initThemes(){
	var themeSelect = document.getElementById('themeSelect');
	for (var i = 0; i < themes.length; i++){
		var opt = document.createElement('option');
		opt.innerText = themes[i];
		opt.value = themes[i];
		themeSelect.appendChild(opt);
	}
	// Randomly pick a theme on load
	themeSelect.selectedIndex = Math.floor(Math.random() * themes.length);
	toggleTheme();
}

function toggleTheme(){
	var themeSelect = document.getElementById('themeSelect');
	var theme = themeSelect.options[themeSelect.selectedIndex].value;
	document.documentElement.className = theme;
	document.getElementById('themeCss').href = 'css/' + theme.toLowerCase() + '.css';
}

/* Init */
function init(){
	// Set up themes
	initThemes();
	document.getElementById('themeSelect').onchange = toggleTheme;
	// Set up buttons
	document.getElementById('impatient').onclick = impatientClick;
	document.getElementById('ancient').onclick = ancientClick;
	document.getElementById('makePost').onclick = makePost;
	document.getElementById('postImg').onchange = previewImage;
	document.getElementById('postImg').onpaste = function(){
		setTimeout(previewImage, 5);
	};

	// Initial load
	impatientClick();
	// Resolve hash
	var hash = window.location.hash.split('post');
	if (hash.length > 0){
		getPost(hash[1]);
	}
	// Auto refresh
	setInterval(impatientClick, auto_refresh_delay);
}
init();

/* Ads */
function adBlockDetected() {
	document.getElementById('adBlockPlea').className = '';
}

if (typeof blockAdBlock === 'undefined') {
	adBlockDetected();
} else {
	blockAdBlock.onDetected(adBlockDetected);
}
<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Basic model for a push button, including over/down/enabled properties and the derived property "interactionState".
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var PropertySet = require( 'AXON/PropertySet' );

  /**
   * @param {Object} options
   * @constructor
   */
  function ButtonModel( options ) {
    var buttonModel = this;

    options = _.extend( {
      fireOnDown: false,
      listener: null
    }, options );

    PropertySet.call( this, {
      over: false,
      down: false,
      enabled: true
    } );

    this.listeners = [];
    if ( options.listener !== null ) {
      this.listeners.push( options.listener );
    }

    //Create the "interactionState" which is often used to determine how to render the button
    this.addDerivedProperty( 'interactionState', ['over', 'down', 'enabled'], function( over, down, enabled ) {
      return !enabled ? 'disabled' :
             over && !down ? 'over' :
             over && down ? 'pressed' :
             'idle';
    } );

    //If button was pressed and "fire on down" was set, fire the listeners
    this.property( 'down' ).onValue( true, function() {
      if ( options.fireOnDown ) {
        buttonModel.fire();
      }
    } );

    //If button was released and "fire on down" was not set, fire the listeners
    this.property( 'down' ).onValue( false, function() {
      if ( !options.fireOnDown && buttonModel.over ) {
        buttonModel.fire();
      }
    } );

    //If the user was pressing down on a button when the button becomes disabled,
    // clear its down & over flags so it won't appear pressed when the button becomes enabled again.
    this.property( 'enabled' ).onValue( false, function() {
      buttonModel.down = false;
      buttonModel.over = false;
    } );
  }

  return inherit( PropertySet, ButtonModel, {
    // Adds a listener. If already a listener, this is a no-op.
    addListener: function( listener ) {
      if ( this.listeners.indexOf( listener ) === -1 ) {
        this.listeners.push( listener );
      }
    },

    // Remove a listener. If not a listener, this is a no-op.
    removeListener: function( listener ) {
      var i = this.listeners.indexOf( listener );
      if ( i !== -1 ) {
        this.listeners.splice( i, 1 );
      }
    },

    // Fires all listeners.  Should not be called outside of this file with
    // the possible exception of hooking up for accessibility.
    fire: function() {
      var copy = this.listeners.slice( 0 );
      copy.forEach( function( listener ) {
        listener();
      } );
    }
  } );
} );<commit_msg>Make sure the button handles enabled/disabled changes during interaction properly<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Basic model for a push button, including over/down/enabled properties and the derived property "interactionState".
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var PropertySet = require( 'AXON/PropertySet' );

  /**
   * @param {Object} options
   * @constructor
   */
  function ButtonModel( options ) {
    var buttonModel = this;

    options = _.extend( {
      fireOnDown: false,
      listener: null
    }, options );

    PropertySet.call( this, {
      over: false,
      down: false,
      enabled: true
    } );

    this.listeners = [];
    if ( options.listener !== null ) {
      this.listeners.push( options.listener );
    }

    //Create the "interactionState" which is often used to determine how to render the button
    this.addDerivedProperty( 'interactionState', ['over', 'down', 'enabled'], function( over, down, enabled ) {
      return !enabled ? 'disabled' :
             over && !down ? 'over' :
             over && down ? 'pressed' :
             'idle';
    } );

    //If button was pressed and "fire on down" was set, fire the listeners
    this.property( 'down' ).onValue( true, function() {
      if ( options.fireOnDown ) {
        buttonModel.fire();
      }
    } );

    //If button was released and "fire on down" was not set, fire the listeners
    this.property( 'down' ).onValue( false, function() {
      if ( !options.fireOnDown && buttonModel.over ) {
        buttonModel.fire();
      }
    } );

    //If the user was pressing down on a button when the button becomes disabled,
    // clear its down flag so it won't appear pressed when the button becomes enabled again.
    this.property( 'over' ).onValue( false, function() {
      if ( !buttonModel.enabled ) {
        buttonModel.down = false;
      }
    } );
  }

  return inherit( PropertySet, ButtonModel, {
    // Adds a listener. If already a listener, this is a no-op.
    addListener: function( listener ) {
      if ( this.listeners.indexOf( listener ) === -1 ) {
        this.listeners.push( listener );
      }
    },

    // Remove a listener. If not a listener, this is a no-op.
    removeListener: function( listener ) {
      var i = this.listeners.indexOf( listener );
      if ( i !== -1 ) {
        this.listeners.splice( i, 1 );
      }
    },

    // Fires all listeners.  Should not be called outside of this file with
    // the possible exception of hooking up for accessibility.
    fire: function() {
      var copy = this.listeners.slice( 0 );
      copy.forEach( function( listener ) {
        listener();
      } );
    }
  } );
} );<|endoftext|>


<commit_before>angular.module('contatooh', ['ngRoute'])
    .config(function($routeProvider) {

        $routeProvider.when('/contatos', {
            templateUrl: 'partials/contatos.html',
            controller: 'ContatosController'
        });
});
<commit_msg>marcando onde parei<commit_after>angular.module('contatooh', ['ngRoute'])
    .config(function($routeProvider) {

        $routeProvider.when('/contatos', {
            templateUrl: 'partials/contatos.html',
            controller: 'ContatosController'
        });
});

// continuar pagina 88
<|endoftext|>