<commit_before>/* Magic Mirror
 * Module: MMM-cryptocoin
 *
 * By Christian Handorf (mmm@kodejak.de)
 * MIT Licensed.
 *
 * Based on MMM-bitcoin module by valmassoi.
 */

Module.register("MMM-cryptocoin", {

  result: {},
  defaults: {
    transCurrency: 'EUR',
    updateInterval: 60000,
    fadeSpeed: 3000,
    coins: [
        {
          label: 'Ether',
          coin: 'ETH',
          output: '%x €',
        },
        {
          label: 'Bitcoin',
          coin: 'BTC',
          output: '%x €',
        },
    ],
  },

  start: function() {
    this.getTickers();
    this.scheduleUpdate();
  },

  getDom: function() {
    var wrapper = document.createElement("ticker");
    wrapper.className = 'medium bright';
    var data = this.result;
    var output = '
';
    for (var key in data) {
      if (data.hasOwnProperty(key)) {
        for (var c in this.config.coins) {
          var coinEntry = this.config.coins[c];
          if (coinEntry.coin == key) {
            var str = '
' + coinEntry.label + '	' + coinEntry.output + '
';
            var val = data[key][this.config.transCurrency];
            str = str.replace("%x", val.toFixed(2));
            output += str;
            break;
          }
        }
      }
    }
    output += '
';
    var outputElement =  document.createElement("span");
    outputElement.innerHTML = output;
    wrapper.appendChild(outputElement);

    return wrapper;
  },

  scheduleUpdate: function(delay) {
    var nextLoad = this.config.updateInterval;
    if (nextLoad < 10000) {
      nextLoad = 10000;
    }
    if (typeof delay !== "undefined" && delay >= 0) {
      nextLoad = delay;
    }

    var self = this;
    setInterval(function() {
      self.getTickers();
    }, nextLoad);
  },

  getTickers: function () {
    var coinAdd = ""; //"ETH,BTC";

    for (var c in this.config.coins) {
      var coinEntry = this.config.coins[c];
      if (coinEntry.coin.length < 1) {continue;}
      if (coinAdd.length > 0) {coinAdd += ",";}
      coinAdd += coinEntry.coin.trim();
    }
    var url = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=' + coinAdd + '&tsyms=' + this.config.transCurrency;
    this.sendSocketNotification('GET_TICKERS', url);
  },

  socketNotificationReceived: function(notification, payload) {
    if (notification === "TICKERS_RESULT") {
      var self = this;
      this.result = payload;
      this.updateDom(self.config.fadeSpeed);
    }
  },

});
<commit_msg>old comment removed<commit_after>/* Magic Mirror
 * Module: MMM-cryptocoin
 *
 * By Christian Handorf (mmm@kodejak.de)
 * MIT Licensed.
 *
 * Based on MMM-bitcoin module by valmassoi.
 */

Module.register("MMM-cryptocoin", {

  result: {},
  defaults: {
    transCurrency: 'EUR',
    updateInterval: 60000,
    fadeSpeed: 3000,
    coins: [
        {
          label: 'Ether',
          coin: 'ETH',
          output: '%x €',
        },
        {
          label: 'Bitcoin',
          coin: 'BTC',
          output: '%x €',
        },
    ],
  },

  start: function() {
    this.getTickers();
    this.scheduleUpdate();
  },

  getDom: function() {
    var wrapper = document.createElement("ticker");
    wrapper.className = 'medium bright';
    var data = this.result;
    var output = '
';
    for (var key in data) {
      if (data.hasOwnProperty(key)) {
        for (var c in this.config.coins) {
          var coinEntry = this.config.coins[c];
          if (coinEntry.coin == key) {
            var str = '
' + coinEntry.label + '	' + coinEntry.output + '
';
            var val = data[key][this.config.transCurrency];
            str = str.replace("%x", val.toFixed(2));
            output += str;
            break;
          }
        }
      }
    }
    output += '
';
    var outputElement =  document.createElement("span");
    outputElement.innerHTML = output;
    wrapper.appendChild(outputElement);

    return wrapper;
  },

  scheduleUpdate: function(delay) {
    var nextLoad = this.config.updateInterval;
    if (nextLoad < 10000) {
      nextLoad = 10000;
    }
    if (typeof delay !== "undefined" && delay >= 0) {
      nextLoad = delay;
    }

    var self = this;
    setInterval(function() {
      self.getTickers();
    }, nextLoad);
  },

  getTickers: function () {
    var coinAdd = "";

    for (var c in this.config.coins) {
      var coinEntry = this.config.coins[c];
      if (coinEntry.coin.length < 1) {continue;}
      if (coinAdd.length > 0) {coinAdd += ",";}
      coinAdd += coinEntry.coin.trim();
    }
    var url = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=' + coinAdd + '&tsyms=' + this.config.transCurrency;
    this.sendSocketNotification('GET_TICKERS', url);
  },

  socketNotificationReceived: function(notification, payload) {
    if (notification === "TICKERS_RESULT") {
      var self = this;
      this.result = payload;
      this.updateDom(self.config.fadeSpeed);
    }
  },

});
<|endoftext|>


<commit_before>// BRICOLEUR
var stream = require('stream')

module.exports = Bricoleur

function Bricoleur (opts) {
  if (!opts) opts = {}
  this.readable = true
  this.writable = true
  this._buffer = []

  var self = this
  , MAP = null
  , ENV = {}
  , _ = {} // module scope

  _.brico = new stream.Stream
  _.brico.readable = true
  _.brico.writable = true
  _.brico._read = function (size) {}
  _.brico.write = function (chunk) {
    var d = JSON.parse(chunk)
    d.k = self.key
    self.socSend(d)
  }

  this.addMap = function (map) {
    MAP = map
  }
  this.socAdd = function (key, cb) { // user socket connection
    self.key = key
    self[key] = new stream.Stream
    self[key].writable = true
    self[key].readable = true
    self[key].write = function (chunk) {
      var d = JSON.parse(chunk)
      self.socRecv(d)
    }
    self[key]._read = function (size) {}
    self[key].on('error', function (e) {
      console.error(e)
    })
    self[key].end = function () {
      console.log('closed')
    }
    cb()
  }
  this.socSend = function (d) {// out to brico
    if (!d.k) console.error('no client id')
    if (d.k) self[d.k].emit('data', JSON.stringify(d))
  }
  this.socRecv = function (d) {// in from brico
    if (d.k) console.log(d) // handle input from console
    if (d.r&&d.v) handleRoute(d)
    if (d.id&&d.process) make(d)
  }
  this.socRm = function (key) {
    self[key].emit('close')
    delete self[key]
  }

  function handleRoute (d) { // direct function call map
    switch (d.r) {
      case 'key' : self.ID = d.v; console.log(self.ID); break;
      case 'con' : conn(d.v); break;
      default : console.error('route not recognized'); break;
    }
  }
  function make (mod) {
    if (process.browser&&mod.html) {
      var m = require(mod.id.toUpperCase())
      _[mod.id] = new m(mod.html)
    }
  }
  function unmake (mod) {
    if (process.browser) mod.destroy()
  }
  function conn (conns) {
    conns.forEach(function handleConnection (conn) {
      if (conn.match(/\+/) !== null) {
        var modA = conn.split('+')[0]
        , modB = conn.split('+')[1]
        _[modA].pipe(_[modB])
      }
      if (conn.match(/\-/) !== null) {
        var modA = conn.split('-')[0]
        , modB = conn.split('-')[1]
        modA.unpipe(modB)
      }
    })
  }
}
<commit_msg>refactoring brico<commit_after>var stream = require('stream')

module.exports = Bricoleur

function Bricoleur (opts) {
  if (!opts) opts = {}

  var self = this
  , MAP = null
  , ENV = {}
  , _ = {} // module scope

  _.brico = new stream.Stream
  _.brico.readable = true
  _.brico.writable = true
  _.brico._read = function (size) {}
  _.brico.write = function (chunk) {
    var d = JSON.parse(chunk)
    d.k = self.key
    self.socSend(d)
  }

  this.socSend = function (d) {// out to brico
    if (!d.k) console.error('no client id')
    if (d.k) self[d.k].emit('data', JSON.stringify(d))
  }
  this.socRecv = function (d) {// in from brico
    if (d.k) console.log(d) // handle input from console
    if (d.r&&d.v) handleRoute(d)
    if (d.id&&d.process) make(d)
  }
  this.socRm = function (key) {
    self[key].emit('close')
    delete self[key]
  }

  function handleRoute (d) { // direct function call map
    switch (d.r) {
      case 'key' : self.ID = d.v; console.log(self.ID); break;
      case 'con' : conn(d.v); break;
      default : console.error('route not recognized'); break;
    }
  }
  function make (mod) {
    if (process.browser&&mod.html) {
      var m = require(mod.id.toUpperCase())
      _[mod.id] = new m(mod.html)
    }
  }
  function unmake (mod) {
    if (process.browser) mod.destroy()
  }
  function conn (conns) {
    conns.forEach(function handleConnection (conn) {
      if (conn.match(/\+/) !== null) {
        var modA = conn.split('+')[0]
        , modB = conn.split('+')[1]
        _[modA].pipe(_[modB])
      }
      if (conn.match(/\-/) !== null) {
        var modA = conn.split('-')[0]
        , modB = conn.split('-')[1]
        modA.unpipe(modB)
      }
    })
  }
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $('form').on('submit', function(event) {
        event.preventDefault();
        submit_form();
    });

    $('a.edit').on('click', function(event) {
        event.preventDefault();
        device = load_device($(this).closest('tr').attr('data-id'));
    });

    $('a.delete').on('click', function(event) {
        event.preventDefault();
        confirm_delete_device($(this).closest('tr').attr('data-id'));
    });

    $('button#prefill-mac').on('click', function(event) {
        $('form#device-form').find('input#mac').val(
            $(this).attr('data-mac')
        );
    });
});

function set_errors(errors) {
    $.each(errors, function (name, text) {
        $('form').find('label[for=' + name + ']').first().after(
            '' + text + '');
    });
}

function submit_form() {
    form = $('form');

    form.find('span.error').remove();
    form_error = $('#form-error');
    form_error.slideUp(200, 'easeInQuart');

    var post_data = form.find(':input').serializeArray();
    post_data['csrfmiddlewaretoken'] =
        $('#metadata').attr('data-csrfmiddlewaretoken');

    $('img#loading').css('display', 'inline');
    $.post(document.pathname, post_data, function(data) {
        location.reload();
    }, 'json').fail(function(data) {
        $('img#loading').css('display', 'none');
        if (data.status == 422) {
            set_errors(data.responseJSON);
        } else {
            form_error.html('A server error occurred.');
            form_error.slideDown(200, 'easeInQuart');
        };
    });
}

// helper function to get reference to a given device's table row
function get_tr(id) {
    return $("tr[data-id=" + id + "]");
}

function load_device(id) {
    $('#form-error').slideUp(200, 'easeInQuart');
    $('#device-list-server-error').slideUp(200, 'easeInQuart');
    $(':input').attr('disabled', false);

    $('#form-title').html('Change a device');

    // the data is already on the page, so we pull it from there
    tr = get_tr(id);
    $('form#device-form').find('input#id').val(tr.attr('data-id'));
    $('form#device-form').find('input#description').val(tr.find('td.device-description').text());
    $('form#device-form').find('input#mac').val(tr.find('td.device-mac').text());
}

function confirm_delete_device(id) {
    $('#device-list-server-error').slideUp(200, 'easeInQuart');

    btn = $('button#deleteDevice');
    btn.attr('data-id', id);
    btn.on('click', function(event) {
        event.preventDefault();
        $('img#loadingDelete').css('display', 'inline');
        delete_device($(this).attr('data-id'));
    });

    $("#deleteDeviceModal").modal();
}

function delete_device(id) {
    $('#device-list-server-error').slideUp(200, 'easeInQuart');

    post_data = {
        'id': id,
        'csrfmiddlewaretoken': $('#metadata').attr('data-csrfmiddlewaretoken')
    };

    $.post('/delete_device', post_data, function(data) {
        //location.reload();
        tr = get_tr(id);
        tr.fadeOut(200, function(){ tr.remove(); });
        num_span = $('span#number-of-devices');
        num_span.text(parseInt(num_span.text()) - 1);
        $('img#loadingDelete').css('display', 'none');
    }).fail(function() {
        $('img#loadingDelete').css('display', 'none');
        $('#device-list-server-error').slideDown(200, 'easeInQuart');
    });
    $("#deleteDeviceModal").modal('hide');
}
<commit_msg>Add duplicate hardware address error<commit_after>$(document).ready(function() {
    $('form').on('submit', function(event) {
        event.preventDefault();
        submit_form();
    });

    $('a.edit').on('click', function(event) {
        event.preventDefault();
        device = load_device($(this).closest('tr').attr('data-id'));
    });

    $('a.delete').on('click', function(event) {
        event.preventDefault();
        confirm_delete_device($(this).closest('tr').attr('data-id'));
    });

    $('button#prefill-mac').on('click', function(event) {
        $('form#device-form').find('input#mac').val(
            $(this).attr('data-mac')
        );
    });
});

function set_errors(errors) {
    $.each(errors, function (name, text) {
        $('form').find('label[for=' + name + ']').first().after(
            '' + text + '');
    });
}

function submit_form() {
    form = $('form');

    form.find('span.error').remove();
    form_error = $('#form-error');
    form_error.slideUp(200, 'easeInQuart');

    var post_data = form.find(':input').serializeArray();

    if ($('input#id').val() == "") {
        var form_mac = $('input#mac').val();
        var conflict = $('td.device-mac').filter(
            function() { return this.innerHTML == form_mac; }).length != 0;
        if (conflict) {
            form_error.html(
                'A device with this hardware address is already registered!');
            form_error.slideDown(200, 'easeInQuart');
            return;
        }
    }

    post_data['csrfmiddlewaretoken'] =
        $('#metadata').attr('data-csrfmiddlewaretoken');

    $('img#loading').css('display', 'inline');
    $.post(document.pathname, post_data, function(data) {
        location.reload();
    }, 'json').fail(function(data) {
        $('img#loading').css('display', 'none');
        if (data.status == 422) {
            set_errors(data.responseJSON);
        } else {
            form_error.html('A server error occurred.');
            form_error.slideDown(200, 'easeInQuart');
        };
    });
}

// helper function to get reference to a given device's table row
function get_tr(id) {
    return $("tr[data-id=" + id + "]");
}

function load_device(id) {
    $('#form-error').slideUp(200, 'easeInQuart');
    $('#device-list-server-error').slideUp(200, 'easeInQuart');
    $(':input').attr('disabled', false);

    $('#form-title').html('Change a device');

    // the data is already on the page, so we pull it from there
    tr = get_tr(id);
    $('form#device-form').find('input#id').val(tr.attr('data-id'));
    $('form#device-form').find('input#description').val(tr.find('td.device-description').text());
    $('form#device-form').find('input#mac').val(tr.find('td.device-mac').text());
}

function confirm_delete_device(id) {
    $('#device-list-server-error').slideUp(200, 'easeInQuart');

    btn = $('button#deleteDevice');
    btn.attr('data-id', id);
    btn.on('click', function(event) {
        event.preventDefault();
        $('img#loadingDelete').css('display', 'inline');
        delete_device($(this).attr('data-id'));
    });

    $("#deleteDeviceModal").modal();
}

function delete_device(id) {
    $('#device-list-server-error').slideUp(200, 'easeInQuart');

    post_data = {
        'id': id,
        'csrfmiddlewaretoken': $('#metadata').attr('data-csrfmiddlewaretoken')
    };

    $.post('/delete_device', post_data, function(data) {
        //location.reload();
        tr = get_tr(id);
        tr.fadeOut(200, function(){ tr.remove(); });
        num_span = $('span#number-of-devices');
        num_span.text(parseInt(num_span.text()) - 1);
        $('img#loadingDelete').css('display', 'none');
    }).fail(function() {
        $('img#loadingDelete').css('display', 'none');
        $('#device-list-server-error').slideDown(200, 'easeInQuart');
    });
    $("#deleteDeviceModal").modal('hide');
}
<|endoftext|>


<commit_before>exports.definition = {
  mixinCallback: function(){
    var self = this

    this.scope('totalCount', function(field){
      var key = field || self.primaryKeys[0] || '*'
      this
      .count(self.store.utils.toAttributeName(key, [self.getName()]), true)
      .limit()
      .offset()
      .order(null)
    }, true)
  }
}
<commit_msg>escape attribute for oracle<commit_after>exports.definition = {
  mixinCallback: function(){
    var self = this

    this.scope('totalCount', function(field){
      var key = field || self.primaryKeys[0] || '*'
      this
      .count(this.escapeAttribute(self.store.utils.toAttributeName(key, [self.getName()])), true)
      .limit()
      .offset()
      .order(null)
    }, true)
  }
}
<|endoftext|>


<commit_before>/* Just a simple Zaraz dummy that spits stuff to console */
"use strict";

class Zaraz {
  set (key, value, options= null) {
    console.log("Zaraz Set: %s = %s %O", key, value, options)
  }

  track (event, parameters= null) {
    console.log("Zaraz Track: %s %O", event, parameters)
  }

  ecommerce (event, parameters) {
    console.log("Zaraz Ecommerce: %s %O", event, parameters)
  }
}

/* Dummy Zaraz */
let zaraz= new Zaraz()
window.zaraz= new Zaraz()

/* Dummy Microsoft */
window.uetq= [];

/* Dummy Pinterest */
class Pinterest {
  pintrk (action, event, parameters) {
    console.log("Pinterest %s: %s %O", action, event, parameters)
  }
}

window.pintrk= new Pinterest()
<commit_msg>Fix dummy Pinterest tracking<commit_after>/* Just a simple Zaraz dummy that spits stuff to console */
"use strict";

class Zaraz {
  set (key, value, options= null) {
    console.log("Zaraz Set: %s = %s %O", key, value, options)
  }

  track (event, parameters= null) {
    console.log("Zaraz Track: %s %O", event, parameters)
  }

  ecommerce (event, parameters) {
    console.log("Zaraz Ecommerce: %s %O", event, parameters)
  }
}

/* Dummy Zaraz */
let zaraz= new Zaraz()
window.zaraz= new Zaraz()

/* Dummy Microsoft */
window.uetq= [];

/* Dummy Pinterest */
window.pintrk= (action, event, parameters) => {
  console.log("Pinterest %s: %s %O", action, event, parameters)
}
<|endoftext|>


<commit_before>

/**
 * Module dependencies.
 */

var jade = require('./../lib/jade'),
    Compiler = jade.Compiler,
    nodes = jade.nodes;

var options = {
    pretty: true,
    locals: {
        user: {
            name: 'Tobi',
            email: 'vision-media.ca',
            summary: 'Tobi is a ferret, he is supes cool.',
            errors: { email: 'Invalid email' },
            new: false
        }
    }
};

jade.renderFile(__dirname + '/model.jade', options, function(err, html){
    if (err) throw err;
    console.log(html);
});

// First define a filter named "model",
// which accepts a node (a Block node),
// and the parent Compiler

jade.filters.model = function(block, compiler){
    // pass the block / previous options to our new Visitor
    return new Visitor(block, compiler.options).compile();
};

function Visitor(node, options) {
    // "super" to the Compiler() constructor
    Compiler.call(this, node, options);
}

// Inherit from Compiler

Visitor.prototype.__proto__ = Compiler.prototype;

// Overwrite visitTag method

Visitor.prototype.visitTag = function(node){
    var parent = Compiler.prototype.visitTag;
    switch (node.name) {
        case 'form':
            // Store the record variable name,
            // in our case "user" is our first
            // anonymous attribute
            this.record = node.attrs[0].name;
            // remove the record name attribute
            node.removeAttribute(this.record);
            node.setAttribute('id', '"' + this.record + '-model-form"');
            node.setAttribute('method', '"post"');

            // when the record is not new, we probably want a _method hidden
            // field to tell our server to use PUT with frameworks like Express
            var code = new nodes.Code('if (!' + this.record + '.new)');
            var put = new nodes.Tag('input');
            put.setAttribute('type', '"hidden"');
            put.setAttribute('name', '"_method"');
            put.setAttribute('value', '"put"');
            code.block = new nodes.Block(put);
            node.block.push(code);

            parent.call(this, node);
            break;
        case 'field':
            // Grab "as" attribute, defaulting it to "text"
            // perform some surgery on it since it IS literal JavaScript
            var name = node.attrs[0].name,
                as = (node.getAttribute('as') || 'text').trim().replace(/'/g, ''),
                capitalized = name.charAt(0).toUpperCase() + name.slice(1);

            // Field label
            var label = new nodes.Tag('label');
            label.setAttribute('for', '"' + this.record + '[' + name + ']"');
            label.block.push(new nodes.Text(capitalized + ':'));
            parent.call(this, label);

            // Field input
            switch (as) {
                case 'textarea':
                    var code = new nodes.Code(this.record + '.' + name, true, true);
                    node = new nodes.Tag('textarea');
                    node.block.push(code);
                    break;
                case 'text':
                    node = new nodes.Tag('input');
                    node.setAttribute('type', '"text"');
                    node.setAttribute('value', this.record + '.' + name);
            }
            node.setAttribute('name', '"' + this.record + '[' + name + ']"');
            parent.call(this, node);

            // Potential error tag
            var err = this.record + '.errors.' + name;
            node = new nodes.Code('if (' + err + ')');
            node.block = new nodes.Block;
            var p = new nodes.Tag('p', new nodes.Block(new nodes.Code(err, true, true)));
            node.block.push(p);

            Visitor.prototype.visitCode.call(this, node);
            break;
        case 'buttons':
            // Generate context sensative buttons which
            // check the record's state.
            node = new nodes.Tag('input');
            node.setAttribute('type', '"submit"');
            node.setAttribute('value', this.record + '.new ? "Save" : "Update"');
            var p = new nodes.Tag('p', new nodes.Block(node));
            p.setAttribute('class', '"buttons"');
            parent.call(this, p);
            break;
        default:
            parent.call(this, node);
    }
};
<commit_msg>error class for model example<commit_after>

/**
 * Module dependencies.
 */

var jade = require('./../lib/jade'),
    Compiler = jade.Compiler,
    nodes = jade.nodes;

var options = {
    pretty: true,
    locals: {
        user: {
            name: 'Tobi',
            email: 'vision-media.ca',
            summary: 'Tobi is a ferret, he is supes cool.',
            errors: { email: 'Invalid email' },
            new: false
        }
    }
};

jade.renderFile(__dirname + '/model.jade', options, function(err, html){
    if (err) throw err;
    console.log(html);
});

// First define a filter named "model",
// which accepts a node (a Block node),
// and the parent Compiler

jade.filters.model = function(block, compiler){
    // pass the block / previous options to our new Visitor
    return new Visitor(block, compiler.options).compile();
};

function Visitor(node, options) {
    // "super" to the Compiler() constructor
    Compiler.call(this, node, options);
}

// Inherit from Compiler

Visitor.prototype.__proto__ = Compiler.prototype;

// Overwrite visitTag method

Visitor.prototype.visitTag = function(node){
    var parent = Compiler.prototype.visitTag;
    switch (node.name) {
        case 'form':
            // Store the record variable name,
            // in our case "user" is our first
            // anonymous attribute
            this.record = node.attrs[0].name;
            // remove the record name attribute
            node.removeAttribute(this.record);
            node.setAttribute('id', '"' + this.record + '-model-form"');
            node.setAttribute('method', '"post"');

            // when the record is not new, we probably want a _method hidden
            // field to tell our server to use PUT with frameworks like Express
            var code = new nodes.Code('if (!' + this.record + '.new)');
            var put = new nodes.Tag('input');
            put.setAttribute('type', '"hidden"');
            put.setAttribute('name', '"_method"');
            put.setAttribute('value', '"put"');
            code.block = new nodes.Block(put);
            node.block.push(code);

            parent.call(this, node);
            break;
        case 'field':
            // Grab "as" attribute, defaulting it to "text"
            // perform some surgery on it since it IS literal JavaScript
            var name = node.attrs[0].name,
                as = (node.getAttribute('as') || 'text').trim().replace(/'/g, ''),
                capitalized = name.charAt(0).toUpperCase() + name.slice(1);

            // Field label
            var label = new nodes.Tag('label');
            label.setAttribute('for', '"' + this.record + '[' + name + ']"');
            label.block.push(new nodes.Text(capitalized + ':'));
            parent.call(this, label);

            // Field input
            switch (as) {
                case 'textarea':
                    var code = new nodes.Code(this.record + '.' + name, true, true);
                    node = new nodes.Tag('textarea');
                    node.block.push(code);
                    break;
                case 'text':
                    node = new nodes.Tag('input');
                    node.setAttribute('type', '"text"');
                    node.setAttribute('value', this.record + '.' + name);
            }
            node.setAttribute('name', '"' + this.record + '[' + name + ']"');
            parent.call(this, node);

            // Potential error tag
            var err = this.record + '.errors.' + name;
            node = new nodes.Code('if (' + err + ')');
            node.block = new nodes.Block;
            var p = new nodes.Tag('p', new nodes.Block(new nodes.Code(err, true, true)));
            p.setAttribute('class', '"error"');
            node.block.push(p);

            Visitor.prototype.visitCode.call(this, node);
            break;
        case 'buttons':
            // Generate context sensative buttons which
            // check the record's state.
            node = new nodes.Tag('input');
            node.setAttribute('type', '"submit"');
            node.setAttribute('value', this.record + '.new ? "Save" : "Update"');
            var p = new nodes.Tag('p', new nodes.Block(node));
            p.setAttribute('class', '"buttons"');
            parent.call(this, p);
            break;
        default:
            parent.call(this, node);
    }
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    init();
});

var map, controls;
var stands;
var currentStep = 1;
var steps = [undefined]; // start with a blank to make it 1-indexed

function init() {
    map = new OpenLayers.Map();
    var switcher = new OpenLayers.Control.LayerSwitcher();
    map.addControl(switcher);

    map.addControl(new OpenLayers.Control.Navigation({
            dragPanOptions: {
                enableKinetic: false
            }
        }));

    map.addControl(new OpenLayers.Control.Attribution());

    //map.addControl(new OpenLayers.Control.Zoom());

    var gphy = new OpenLayers.Layer.Google( "Google Physical", {type: google.maps.MapTypeId.TERRAIN});
    var ghyb = new OpenLayers.Layer.Google( "Google Hybrid", {type: google.maps.MapTypeId.HYBRID, numZoomLevels: 21});
    var gsat = new OpenLayers.Layer.Google( "Google Satellite", {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22});
    var arrayOSM = ["http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
                "http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
                "http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
                "http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg"];

    var arrayMapboxTerrain = [
        "http://a.tiles.mapbox.com/v3/examples.map-4l7djmvo/${z}/${x}/${y}.jpg",
        "http://b.tiles.mapbox.com/v3/examples.map-4l7djmvo/${z}/${x}/${y}.jpg",
        "http://c.tiles.mapbox.com/v3/examples.map-4l7djmvo/${z}/${x}/${y}.jpg"];

    var arrayAerial = ["http://oatile1.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://oatile2.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://oatile3.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://oatile4.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg"];

    var baseAerial = new OpenLayers.Layer.OSM("MapQuest Open Aerial", arrayAerial);
    var baseOSM = new OpenLayers.Layer.OSM("Mapbox OSM Terrain", arrayMapboxTerrain);
    var nhd = new OpenLayers.Layer.XYZ( "EPA NHD",
        "http://watersgeo.epa.gov/ARCGIS/REST/services/OW/NHD_Med_Detailed_WMERC/MapServer/tile/${z}/${y}/${x}",
        //"/tile/${z}/${y}/${x}",
        {sphericalMercator: true, isBaseLayer: false, visibility: false, opacity: 0.75}
    );
    var huc = new OpenLayers.Layer.XYZ( "EPA HUCs",
        //"/tile/${z}/${y}/${x}",
        "http://watersgeo.epa.gov/ArcGIS/rest/services/OW/WBD_WMERC/MapServer/tile/${z}/${y}/${x}",
        {sphericalMercator: true, isBaseLayer: false, visibility: false}
    );
    var soils = new OpenLayers.Layer.XYZ( "Soil Survey Map",
        //"/tile/${z}/${y}/${x}",
        "http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/tile/${z}/${y}/${x}",
        {sphericalMercator: true, isBaseLayer: false, visibility: false, opacity: 0.75}
    );

    /*
     * TODO legend for soils data
     * http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/legend
     *
     * TODO query for soils data
     * http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/1/query?f=json&returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=%7B%22xmin%22%3A-13673363.281068286%2C%22ymin%22%3A6024153.000358967%2C%22xmax%22%3A-13669694.3037106%2C%22ymax%22%3A6027821.977716654%2C%22spatialReference%22%3A%7B%22wkid%22%3A102100%7D%7D&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*&outSR=102100&callback=dojo.io.script.jsonp_dojoIoScript20._jsonpCallback
     * http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/0/query?f=json&returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=%7B%22xmin%22%3A-13635374.078010553%2C%22ymin%22%3A5702238.455736051%2C%22xmax%22%3A-13634456.833671134%2C%22ymax%22%3A5703155.700075472%2C%22spatialReference%22%3A%7B%22wkid%22%3A102100%7D%7D&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*&outSR=102100&callback=dojo.io.script.jsonp_dojoIoScript28._jsonpCallback
     */

    var esri_base = new OpenLayers.Layer.XYZ( "ESRI Topo Maps",
        /*
        ESRI_Imagery_World_2D (MapServer)
        ESRI_StreetMap_World_2D (MapServer)
        NatGeo_World_Map (MapServer)
        NGS_Topo_US_2D (MapServer)
        Ocean_Basemap (MapServer)
        USA_Topo_Maps (MapServer)
        World_Imagery (MapServer)
        World_Physical_Map (MapServer)
        World_Shaded_Relief (MapServer)
        World_Street_Map (MapServer)
        World_Terrain_Base (MapServer)
        World_Topo_Map (MapServer)
        */
        "http://server.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer/tile/${z}/${y}/${x}",
        {sphericalMercator: true}
    );

    var apiKey = "AhYe6O-7ejQ1fsFbztwu7PScwp2b1U1vM47kArB_8P2bZ0jiyJua2ssOLrU4pH70";

    var road = new OpenLayers.Layer.Bing({
        name: "Bing Road",
        key: apiKey,
        type: "Road"
    });
    var hybrid = new OpenLayers.Layer.Bing({
        name: "Bing Hybrid",
        key: apiKey,
        type: "AerialWithLabels"
    });
    var aerial = new OpenLayers.Layer.Bing({
        name: "Bing Aerial",
        key: apiKey,
        type: "Aerial"
    });

    map.addLayer(baseOSM);
    map.addLayers([hybrid, road]);
    map.addLayers([ghyb, gphy]);
    map.addLayer(baseAerial);
    map.addLayer(esri_base);
    map.addLayer(soils);
    map.addLayer(nhd);
    map.addLayer(huc);

    for (var i=map.layers.length-1; i>=0; --i) {
        map.layers[i].animationEnabled = true;
    }

    app.markers = new OpenLayers.Layer.Markers("search", {displayInLayerSwitcher: false});
    map.addLayer(app.markers);

    // Add stands
    var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
    app.renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;

    new_features = new OpenLayers.Layer.Vector("New Features",
            {
                renderers: app.renderer,
                styleMap: map_styles.drawn,
                displayInLayerSwitcher: false
            }
    );
    map.addLayer(new_features);
    app.new_features = new_features;

    app.geojson_format = new OpenLayers.Format.GeoJSON(),
    app.property_layer = new OpenLayers.Layer.Vector("Properties",  {
                renderers: app.renderer,
                styleMap: map_styles.forestProperty
            });
    map.addLayer(app.property_layer);

    // add controls, save references
    app.selectFeature = new OpenLayers.Control.SelectFeature(app.property_layer,
        { "clickout": false});

    // reenable click and drag in vectors
    app.selectFeature.handlers.feature.stopDown = false;

    map.addControl(app.selectFeature);
    app.modifyFeature = new OpenLayers.Control.ModifyFeature(app.property_layer);
    map.addControl(app.modifyFeature);
    // draw is in tree.js TODO: move)
    // activate select now
    app.selectFeature.activate();

    new_snap = new OpenLayers.Control.Snapping({
                layer: app.new_features,
                targets: [app.property_layer],
                greedy: false
            });
    new_snap.activate();
    existing_snap = new OpenLayers.Control.Snapping({
                layer: app.property_layer,
                targets: [app.property_layer],
                greedy: false
            });
    existing_snap.activate();

    draw = new OpenLayers.Control.DrawFeature(new_features, OpenLayers.Handler.Polygon);
    map.addControl(draw);
    app.drawFeature = draw;

    // new app methods
    app.cleanupForm = function ($form) {
      // remove the submit button, strip out the geometry
      $form
        .find('input:submit').remove().end()
        .find('#id_geometry_final').closest('.field').remove();

      // put the form in a well and focus the first field
      $form.addClass('well');
      $form.find('.field').each(function () {
        var $this = $(this);
        // add the bootstrap classes
        $this.addClass('control-group');
        $this.find('label').addClass('control-label');
        $this.find('input').wrap($('<div/>', { "class": "controls"}));
        $this.find('.controls').append($('<p/>', { "class": "help-block"}));

      });
      $form.find('input:visible').first().focus();
    };
} //end init

<commit_msg>layer names<commit_after>$(document).ready(function() {
    init();
});

var map, controls;
var stands;
var currentStep = 1;
var steps = [undefined]; // start with a blank to make it 1-indexed

function init() {
    map = new OpenLayers.Map();
    var switcher = new OpenLayers.Control.LayerSwitcher();
    map.addControl(switcher);

    map.addControl(new OpenLayers.Control.Navigation({
            dragPanOptions: {
                enableKinetic: false
            }
        }));

    map.addControl(new OpenLayers.Control.Attribution());

    //map.addControl(new OpenLayers.Control.Zoom());

    var gphy = new OpenLayers.Layer.Google( "Google Physical", {type: google.maps.MapTypeId.TERRAIN});
    var ghyb = new OpenLayers.Layer.Google( "Google Hybrid", {type: google.maps.MapTypeId.HYBRID, numZoomLevels: 21});
    var gsat = new OpenLayers.Layer.Google( "Google Satellite", {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22});
    var arrayOSM = ["http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
                "http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
                "http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg",
                "http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.jpg"];

    var arrayMapboxTerrain = [
        "http://a.tiles.mapbox.com/v3/examples.map-4l7djmvo/${z}/${x}/${y}.jpg",
        "http://b.tiles.mapbox.com/v3/examples.map-4l7djmvo/${z}/${x}/${y}.jpg",
        "http://c.tiles.mapbox.com/v3/examples.map-4l7djmvo/${z}/${x}/${y}.jpg"];

    var arrayAerial = ["http://oatile1.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://oatile2.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://oatile3.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg",
                    "http://oatile4.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.jpg"];

    var baseAerial = new OpenLayers.Layer.OSM("MapQuest Open Aerial", arrayAerial);
    var baseOSM = new OpenLayers.Layer.OSM("Mapbox OSM Terrain", arrayMapboxTerrain);
    var nhd = new OpenLayers.Layer.XYZ( "Streams",
        "http://watersgeo.epa.gov/ARCGIS/REST/services/OW/NHD_Med_Detailed_WMERC/MapServer/tile/${z}/${y}/${x}",
        //"/tile/${z}/${y}/${x}",
        {sphericalMercator: true, isBaseLayer: false, visibility: false, opacity: 0.75}
    );
    var huc = new OpenLayers.Layer.XYZ( "Watershed Boundaries",
        //"/tile/${z}/${y}/${x}",
        "http://watersgeo.epa.gov/ArcGIS/rest/services/OW/WBD_WMERC/MapServer/tile/${z}/${y}/${x}",
        {sphericalMercator: true, isBaseLayer: false, visibility: false}
    );
    var soils = new OpenLayers.Layer.XYZ( "Soil Survey",
        //"/tile/${z}/${y}/${x}",
        "http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/tile/${z}/${y}/${x}",
        {sphericalMercator: true, isBaseLayer: false, visibility: false, opacity: 0.75}
    );

    /*
     * TODO legend for soils data
     * http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/legend
     *
     * TODO query for soils data
     * http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/1/query?f=json&returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=%7B%22xmin%22%3A-13673363.281068286%2C%22ymin%22%3A6024153.000358967%2C%22xmax%22%3A-13669694.3037106%2C%22ymax%22%3A6027821.977716654%2C%22spatialReference%22%3A%7B%22wkid%22%3A102100%7D%7D&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*&outSR=102100&callback=dojo.io.script.jsonp_dojoIoScript20._jsonpCallback
     * http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/0/query?f=json&returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=%7B%22xmin%22%3A-13635374.078010553%2C%22ymin%22%3A5702238.455736051%2C%22xmax%22%3A-13634456.833671134%2C%22ymax%22%3A5703155.700075472%2C%22spatialReference%22%3A%7B%22wkid%22%3A102100%7D%7D&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*&outSR=102100&callback=dojo.io.script.jsonp_dojoIoScript28._jsonpCallback
     */

    var esri_base = new OpenLayers.Layer.XYZ( "ESRI Topo Maps",
        /*
        ESRI_Imagery_World_2D (MapServer)
        ESRI_StreetMap_World_2D (MapServer)
        NatGeo_World_Map (MapServer)
        NGS_Topo_US_2D (MapServer)
        Ocean_Basemap (MapServer)
        USA_Topo_Maps (MapServer)
        World_Imagery (MapServer)
        World_Physical_Map (MapServer)
        World_Shaded_Relief (MapServer)
        World_Street_Map (MapServer)
        World_Terrain_Base (MapServer)
        World_Topo_Map (MapServer)
        */
        "http://server.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer/tile/${z}/${y}/${x}",
        {sphericalMercator: true}
    );

    var apiKey = "AhYe6O-7ejQ1fsFbztwu7PScwp2b1U1vM47kArB_8P2bZ0jiyJua2ssOLrU4pH70";

    var road = new OpenLayers.Layer.Bing({
        name: "Bing Road",
        key: apiKey,
        type: "Road"
    });
    var hybrid = new OpenLayers.Layer.Bing({
        name: "Bing Hybrid",
        key: apiKey,
        type: "AerialWithLabels"
    });
    var aerial = new OpenLayers.Layer.Bing({
        name: "Bing Aerial",
        key: apiKey,
        type: "Aerial"
    });

    map.addLayer(baseOSM);
    map.addLayers([hybrid, road]);
    map.addLayers([ghyb, gphy]);
    map.addLayer(baseAerial);
    map.addLayer(esri_base);
    map.addLayer(soils);
    map.addLayer(nhd);
    map.addLayer(huc);

    for (var i=map.layers.length-1; i>=0; --i) {
        map.layers[i].animationEnabled = true;
    }

    app.markers = new OpenLayers.Layer.Markers("search", {displayInLayerSwitcher: false});
    map.addLayer(app.markers);

    // Add stands
    var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
    app.renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;

    new_features = new OpenLayers.Layer.Vector("New Features",
            {
                renderers: app.renderer,
                styleMap: map_styles.drawn,
                displayInLayerSwitcher: false
            }
    );
    map.addLayer(new_features);
    app.new_features = new_features;

    app.geojson_format = new OpenLayers.Format.GeoJSON(),
    app.property_layer = new OpenLayers.Layer.Vector("Properties",  {
                renderers: app.renderer,
                styleMap: map_styles.forestProperty
            });
    map.addLayer(app.property_layer);

    // add controls, save references
    app.selectFeature = new OpenLayers.Control.SelectFeature(app.property_layer,
        { "clickout": false});

    // reenable click and drag in vectors
    app.selectFeature.handlers.feature.stopDown = false;

    map.addControl(app.selectFeature);
    app.modifyFeature = new OpenLayers.Control.ModifyFeature(app.property_layer);
    map.addControl(app.modifyFeature);
    // draw is in tree.js TODO: move)
    // activate select now
    app.selectFeature.activate();

    new_snap = new OpenLayers.Control.Snapping({
                layer: app.new_features,
                targets: [app.property_layer],
                greedy: false
            });
    new_snap.activate();
    existing_snap = new OpenLayers.Control.Snapping({
                layer: app.property_layer,
                targets: [app.property_layer],
                greedy: false
            });
    existing_snap.activate();

    draw = new OpenLayers.Control.DrawFeature(new_features, OpenLayers.Handler.Polygon);
    map.addControl(draw);
    app.drawFeature = draw;

    // new app methods
    app.cleanupForm = function ($form) {
      // remove the submit button, strip out the geometry
      $form
        .find('input:submit').remove().end()
        .find('#id_geometry_final').closest('.field').remove();

      // put the form in a well and focus the first field
      $form.addClass('well');
      $form.find('.field').each(function () {
        var $this = $(this);
        // add the bootstrap classes
        $this.addClass('control-group');
        $this.find('label').addClass('control-label');
        $this.find('input').wrap($('<div/>', { "class": "controls"}));
        $this.find('.controls').append($('<p/>', { "class": "help-block"}));

      });
      $form.find('input:visible').first().focus();
    };
} //end init

<|endoftext|>


<commit_before>var UI = require('ui');
var ajax = require( 'ajax' );

var Cards = {
	gettingLocation: new UI.Card( {
		title: 'Nearby',
		subtitle: 'Getting location…'
	} ),

	loadingArticles: new UI.Card( {
		title: 'Nearby',
		subtitle: 'Loading Wikipedia articles…'
	} ),

	error: new UI.Card( {
		title: 'Error',
		subtitle: 'There was some problem'
	} )
};

var Location = {
	options: {
		enableHighAccuracy: true,
		maximumAge: 10000,
		timeout: 10000
	},

	successCallback: function ( pos ) {
		console.log('lat= ' + pos.coords.latitude + ' lon= ' + pos.coords.longitude);
		Cards.loadingArticles.show();
		Cards.gettingLocation.hide();
		WP.loadArticles( pos.coords.latitude, pos.coords.longitude );
	},

	errorCallback: function ( err ) {
		console.log('location error (' + err.code + '): ' + err.message);
		Cards.error.show();
	},

	getCurrentLocation: function () {
		Cards.gettingLocation.show();
		console.log( 'getting location ');
		navigator.geolocation.getCurrentPosition(
			Location.successCallback,
			Location.errorCallback,
			Location.options
		);
	}
};

var WP = {
	loadArticles: function ( lat, lon ) {
		var url = 'https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gscoord=' + lat + '|' + lon + '&gslimit=10&format=json';
		ajax( { url: url, type: 'json' },
							function(json) {
								WP.showPlaces( json.query.geosearch, { latitude: lat, longitude: lon } );
							},
							function(error) {
								Cards.error.show();
							}
						);
	},

	showArticle: function ( title, distance, pageid ) {
		// open a card
		var loadingCard = new UI.Card( {
			title: title,
			subtitle: 'Loading…'
		} ).show();

		// make ajax call
		var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&pageids=' + pageid + '&prop=extracts&explaintext=true&exintro=true&exsentences=2';
		ajax( { url: url, type: 'json' },
							function ( json ) {
								new UI.Card( {
									title: title,
									subtitle: distance,
									body: json.query.pages[ pageid ].extract,
									scrollable: true,
									style: 'small'
								} ).show();
								loadingCard.hide();
							},
							function ( error ) {
								Cards.error.show();
							}
		);
	},

	showPlaces: function ( places, currentLocation ) {
		var items = [], placeMenu;
		for( var i = 0; i < places.length; i ++) {
			var place = places[ i ];
			items.push( {
				title: place.title,
				subtitle: Math.ceil( place.dist / 1000 ) + ' km',
				pageid: place.pageid
			} );
		}
		placeMenu = new UI.Menu( {
			sections: [
				{
					title: 'Get new places',
					items: [ {
						title: 'Refresh',
						subtitle: 'Get your current location…'
					} ]
				},
				{
					title: 'Places',
					items: items
				}
			]
		} );

		placeMenu.on( 'select', function ( e ) {
			if ( e.itemIndex === 0 && e.sectionIndex === 0 ){
				Location.getCurrentLocation();
			} else {
				WP.showArticle( e.item.title, e.item.subtitle, e.item.pageid );
			}
		} );

		placeMenu.show();
		Cards.loadingArticles.hide();
	}
};

// Init
Location.getCurrentLocation();
<commit_msg>Use formatversion=2 in API call<commit_after>var UI = require('ui');
var ajax = require( 'ajax' );

var Cards = {
	gettingLocation: new UI.Card( {
		title: 'Nearby',
		subtitle: 'Getting location…'
	} ),

	loadingArticles: new UI.Card( {
		title: 'Nearby',
		subtitle: 'Loading Wikipedia articles…'
	} ),

	error: new UI.Card( {
		title: 'Error',
		subtitle: 'There was some problem'
	} )
};

var Location = {
	options: {
		enableHighAccuracy: true,
		maximumAge: 10000,
		timeout: 10000
	},

	successCallback: function ( pos ) {
		console.log('lat= ' + pos.coords.latitude + ' lon= ' + pos.coords.longitude);
		Cards.loadingArticles.show();
		Cards.gettingLocation.hide();
		WP.loadArticles( pos.coords.latitude, pos.coords.longitude );
	},

	errorCallback: function ( err ) {
		console.log('location error (' + err.code + '): ' + err.message);
		Cards.error.show();
	},

	getCurrentLocation: function () {
		Cards.gettingLocation.show();
		console.log( 'getting location ');
		navigator.geolocation.getCurrentPosition(
			Location.successCallback,
			Location.errorCallback,
			Location.options
		);
	}
};

var WP = {
	loadArticles: function ( lat, lon ) {
		var url = 'https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gscoord=' + lat + '|' + lon + '&gslimit=10&format=json&formatversion=2';
		ajax( { url: url, type: 'json' },
							function(json) {
								WP.showPlaces( json.query.geosearch, { latitude: lat, longitude: lon } );
							},
							function(error) {
								Cards.error.show();
							}
						);
	},

	showArticle: function ( title, distance, pageid ) {
		// open a card
		var loadingCard = new UI.Card( {
			title: title,
			subtitle: 'Loading…'
		} ).show();

		// make ajax call
		var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&pageids=' + pageid + '&prop=extracts&explaintext=true&exintro=true&exsentences=2';
		ajax( { url: url, type: 'json' },
							function ( json ) {
								new UI.Card( {
									title: title,
									subtitle: distance,
									body: json.query.pages[ pageid ].extract,
									scrollable: true,
									style: 'small'
								} ).show();
								loadingCard.hide();
							},
							function ( error ) {
								Cards.error.show();
							}
		);
	},

	showPlaces: function ( places, currentLocation ) {
		var items = [], placeMenu;
		for( var i = 0; i < places.length; i ++) {
			var place = places[ i ];
			items.push( {
				title: place.title,
				subtitle: Math.ceil( place.dist / 1000 ) + ' km',
				pageid: place.pageid
			} );
		}
		placeMenu = new UI.Menu( {
			sections: [
				{
					title: 'Get new places',
					items: [ {
						title: 'Refresh',
						subtitle: 'Get your current location…'
					} ]
				},
				{
					title: 'Places',
					items: items
				}
			]
		} );

		placeMenu.on( 'select', function ( e ) {
			if ( e.itemIndex === 0 && e.sectionIndex === 0 ){
				Location.getCurrentLocation();
			} else {
				WP.showArticle( e.item.title, e.item.subtitle, e.item.pageid );
			}
		} );

		placeMenu.show();
		Cards.loadingArticles.hide();
	}
};

// Init
Location.getCurrentLocation();
<|endoftext|>


<commit_before>define('login', ['notification'], function(notification) {

    var requestedLogin = false;

    $(window).bind('login', function() {
        $('#login').addClass('show');
    }).on('click', '.browserid', function(e) {
        var $this = $(this);
        $this.addClass('loading-submit');
        requestedLogin = true;
        navigator.id.request({
            forceIssuer: z.body.data('persona-unverified-issuer') || null,
            allowUnverified: true,
            termsOfService: '/terms-of-use',
            privacyPolicy: '/privacy-policy',
            oncancel: function() {
                $this.removeClass('loading-submit').blur();
            }
        });
        e.preventDefault();
    });
    z.body.on('click', '.logout', function() {
        // NOTE: Real logout operations happen on the action of the Logout
        // link/button. This just tells Persona to clean up its data.
        if (navigator.id) {
            navigator.id.logout();
        }
    });
    function gotVerifiedEmail(assertion) {
        if (assertion) {
            var data = {assertion: assertion};
            // When id._shimmed is false we know that Persona is
            // native on the device. Even though this seems fragile
            // it is well supported by Persona (for now).
            data.is_native = navigator.id._shimmed ? 0 : 1;

            $.post(z.body.data('login-url'), data)
             .success(finishLogin)
             .error(function(jqXHR, textStatus, error) {
                var err = jqXHR.responseText;
                if (!err) {
                    err = gettext("Persona login failed. Maybe you don't have an account under that email address?") + " " + textStatus + " " + error;
                }
                z.page.trigger('notify', {msg: err});
             });
        } else {
            $('.loading-submit').removeClass('loading-submit');
        }
    }

    function finishLogin() {
        var to = z.getVars().to;
        if (to && to[0] == '/') {
            // Browsers may helpfully add "http:" to URIs that begin with double
            // slashes. This converts instances of double slashes to single to
            // avoid other helpfullness. It's a bit of extra paranoia.
            to = decodeURIComponent(to.replace(/\/*/, '/'));
            // Convert a local URI to a fully qualified local URL.
            window.location = window.location.protocol + '//'  +
                window.location.host + to;
        } else {
            console.log('finished login');
            if (requestedLogin) {
                window.location.reload();
            } else {
                notification({
                    message: gettext('Successfully signed in. Click here to reload.')
                }).then(window.location.reload);
            }
        }
    }

    function init_persona() {
        $('.browserid').css('cursor', 'pointer');
        var user = z.body.data('user');
        var email = user ? user.email : '';
        console.log('detected user', email);
        navigator.id.watch({
            loggedInUser: email,
            onlogin: gotVerifiedEmail,
            onlogout: function() {}
        });
    }

    // Load `include.js` from persona.org, and drop login hotness like it's hot.
    var s = document.createElement('script');
    s.onload = init_persona;
    if (z.capabilities.firefoxOS) {
        // Load the Firefox OS include that knows how to handle native Persona.
        // Once this functionality lands in the normal include we can stop
        // doing this special case. See bug 821351.
        s.src = z.body.data('native-persona-url');
    } else {
        s.src = z.body.data('persona-url');
    }
    document.body.appendChild(s);
    $('.browserid').css('cursor', 'wait');

});
<commit_msg>not all error messages are made the same (bug 829692)<commit_after>define('login', ['notification'], function(notification) {

    var requestedLogin = false;

    $(window).bind('login', function() {
        $('#login').addClass('show');
    }).on('click', '.browserid', function(e) {
        var $this = $(this);
        $this.addClass('loading-submit');
        requestedLogin = true;
        navigator.id.request({
            forceIssuer: z.body.data('persona-unverified-issuer') || null,
            allowUnverified: true,
            termsOfService: '/terms-of-use',
            privacyPolicy: '/privacy-policy',
            oncancel: function() {
                $this.removeClass('loading-submit').blur();
            }
        });
        e.preventDefault();
    });
    z.body.on('click', '.logout', function() {
        // NOTE: Real logout operations happen on the action of the Logout
        // link/button. This just tells Persona to clean up its data.
        if (navigator.id) {
            navigator.id.logout();
        }
    });
    function gotVerifiedEmail(assertion) {
        if (assertion) {
            var data = {assertion: assertion};
            // When id._shimmed is false we know that Persona is
            // native on the device. Even though this seems fragile
            // it is well supported by Persona (for now).
            data.is_native = navigator.id._shimmed ? 0 : 1;

            $.post(z.body.data('login-url'), data)
             .success(finishLogin)
             .error(function(jqXHR, textStatus, error) {
                var err = jqXHR.responseText;
                if (!err) {
                    err = gettext("Persona login failed. Maybe you don't have an account under that email address?") + " " + textStatus + " " + error;
                }
                // Catch-all for XHR errors otherwise we'll trigger 'notify'
                // with its message as one of the error templates.
                if (jqXHR.status != 200) {
                    err = gettext('Persona login failed. A server error was encountered.');
                }
                z.page.trigger('notify', {msg: err});
             });
        } else {
            $('.loading-submit').removeClass('loading-submit');
        }
    }

    function finishLogin() {
        var to = z.getVars().to;
        if (to && to[0] == '/') {
            // Browsers may helpfully add "http:" to URIs that begin with double
            // slashes. This converts instances of double slashes to single to
            // avoid other helpfullness. It's a bit of extra paranoia.
            to = decodeURIComponent(to.replace(/\/*/, '/'));
            // Convert a local URI to a fully qualified local URL.
            window.location = window.location.protocol + '//'  +
                window.location.host + to;
        } else {
            console.log('finished login');
            if (requestedLogin) {
                window.location.reload();
            } else {
                notification({
                    message: gettext('Successfully signed in. Click here to reload.')
                }).then(window.location.reload);
            }
        }
    }

    function init_persona() {
        $('.browserid').css('cursor', 'pointer');
        var user = z.body.data('user');
        var email = user ? user.email : '';
        console.log('detected user', email);
        navigator.id.watch({
            loggedInUser: email,
            onlogin: gotVerifiedEmail,
            onlogout: function() {}
        });
    }

    // Load `include.js` from persona.org, and drop login hotness like it's hot.
    var s = document.createElement('script');
    s.onload = init_persona;
    if (z.capabilities.firefoxOS) {
        // Load the Firefox OS include that knows how to handle native Persona.
        // Once this functionality lands in the normal include we can stop
        // doing this special case. See bug 821351.
        s.src = z.body.data('native-persona-url');
    } else {
        s.src = z.body.data('persona-url');
    }
    document.body.appendChild(s);
    $('.browserid').css('cursor', 'wait');

});
<|endoftext|>


<commit_before>'use babel';
'use strict';

import fs from 'fs';
import path from 'path';
import EventEmitter from 'events';
import { CompositeDisposable } from 'atom';
import { GAMES, GAME_UNKNOWN, GAME_SKYRIM, ERROR_MATCH, loadConfigFile, validateGameCompiler } from './util';

export default class PapyrusBuildProvider extends EventEmitter {
	constructor(cwd) {
		super();

		// Initialise all the things
		this.cwd = cwd;
		this.game = GAME_UNKNOWN;
		this.configFile = null;
		this.projectFile = null;
		this.disposables = new CompositeDisposable();
		this.fileWatchers = [];

		// Add listeners for game compiler settings to refresh the build targets
		GAMES.forEach((game, index, array) => {
			if(index === 0) return;
			this.disposables.add(atom.config.onDidChange('build-papyrus.' + game.slug + 'CompilerPath', (newValue) => {
				if(this.game === index && this.validateGameCompiler(false)) this.emit('refresh');
			}));
		});

		// Listen for the default game changing for projects
		this.disposables.add(atom.config.onDidChange('build-papyrus.defaultGame', (newValue) => {
			if(this.projectFile) this.emit('refresh');
		}));
	}

	destructor() {
		this.disposables.dispose();
		this.closeFileWatchers();
	}

	getNiceName() {
		return 'Papyrus';
	}

	isEligible() {
		this.configFile = null;
		this.projectFile = null;
		this.closeFileWatchers();

		// Search for .papyrus.json and Papyrus project files
		const files = fs.readdirSync(this.cwd);
		for(const fileName of files) {
			const filePath = path.join(this.cwd, fileName);
			if(fs.statSync(filePath).isFile()) {
				const baseName = path.basename(fileName);
				if(!this.configFile && (baseName === '.build-papyrus.json' || baseName === '.build-papyrus.cson' || baseName === '.build-papyrus.yml')) {
					this.configFile = filePath;
					this.fileWatchers.push(fs.watch(this.configFile, () => this.emit('refresh')));
				} else if(!this.projectFile && path.extname(fileName).toLowerCase() === '.ppj') {
					this.projectFile = filePath;
				}
			}
		}

		this.game = GAME_UNKNOWN;
		if(this.projectFile || this.configFile) return true;
		return false;
	}

	settings() {
		return new Promise((resolve, reject) => {
			if(this.configFile) this.config = loadConfigFile(this.configFile);
			if(this.config) {
				if(!this.projectFile && !this.config.game && !this.config.compiler) return reject(new Error('Either "game" or "compiler" must be specified in the Papyrus config file.'));

				// Get the game from the config
				if(this.config.game) {
					this.config.game = this.config.game.toLowerCase();
					this.game = GAMES.findIndex(game => game.slug === this.config.game);
					if(this.game === -1) {
						this.game = GAME_UNKNOWN;
						return reject(new Error('Invalid "game" specified in the Papyrus config file. Must be one of "skyrim" or "fallout4".'));
					}
				}

				// Get the default game for projects
				if(this.game === GAME_UNKNOWN && this.projectFile) {
					if(!this.setGameFromDefault()) return reject(new Error('Invalid default game in build-papyrus settings'));
				}

				// If the game is still unknown or the compiler setting is set, validate the custom compiler
				if(this.game === GAME_UNKNOWN || this.config.compiler) {
					try {
						if(!this.config.compiler || !fs.statSync(this.config.compiler).isFile()) {
							return reject(new Error('"compiler" must be specified and a valid path to a file in the Papyrus config file since "game" isn\'t specified.'));
						}
					} catch(e) {
						return reject(new Error('"compiler" must be a valid path to a file in the Papyrus config file.'));
					}
				}
			} else {
				this.config = {};
				if(this.projectFile && !this.setGameFromDefault()) return reject(new Error('Invalid default game in build-papyrus settings.'));
			}

			if(this.game === GAME_UNKNOWN || this.validateGameCompiler()) {
				const buildConfigs = [];

				// Add the project file build configurations
				if(this.projectFile && this.game !== GAME_SKYRIM) {
					buildConfigs.push(this.makeBuildConfig('Papyrus: default (Project file)', [ this.projectFile ]));
					buildConfigs.push(this.makeBuildConfig('Papyrus: release (Project file)', [ this.projectFile, '-release' ]));
					buildConfigs.push(this.makeBuildConfig('Papyrus: final release (Project file)', [ this.projectFile, '-release', '-final' ]));
				}

				// Add the config file build configuration
				try {
					if(this.isConfigBuildable()) {
						const args = [
							'{FILE_ACTIVE}',
							'-import=' + this.config.imports.join(';'),
							'-output=' + (this.config.output ? this.config.output : '.'),
							'-flags=' + (this.game === GAME_UNKNOWN || this.config.flags ? this.config.flags : GAMES[this.game].flags)
						];
						if(typeof this.config.optimize === 'undefined' || this.config.optimize) args.push('-optimize');
						if(this.config.release) args.push('-release');
						if(this.config.final) args.push('-final');

						buildConfigs.push(this.makeBuildConfig('Papyrus: default (Configuration file)', args));
						if(this.game !== GAME_SKYRIM) {
							buildConfigs.push(this.makeBuildConfig('Papyrus: release (Configuration file)', args.concat(['-release'])));
							buildConfigs.push(this.makeBuildConfig('Papyrus: final release (Configuration file)', args.concat(['-release', '-final'])));
						}
					}
				} catch(e) {
					if(buildConfigs.length === 0) return reject(e);
				}

				return resolve(buildConfigs);
			} else {
				return reject(new Error('Invalid ' + GAMES[this.game].title + ' compiler path.'));
			}
		});
	}

	makeBuildConfig(name, args) {
		return {
			name: name,
			exec: this.game === GAME_UNKNOWN || this.config.compiler ? this.config.compiler : atom.config.get('build-papyrus.' + GAMES[this.game].slug + 'CompilerPath'),
			args: args,
			cwd: this.cwd,
			sh: false,
			errorMatch: ERROR_MATCH
		};
	}

	isConfigBuildable() {
		if(!this.config.game && !this.config.compiler) throw new Error('Either "game" or "compiler" must be specified in the Papyrus config file.');
		if(!Array.isArray(this.config.imports)) throw new Error('"imports" must be specified as an array in the Papyrus config file.');
		if(this.config.output && !fs.statSync(this.config.output).isDirectory()) throw new Error('"output" must be a valid directory in the Papyrus config file.');
		if(this.game === GAME_UNKNOWN && !this.config.flags) throw new Error('"flags" must be specified in the Papyrus config file since "game" isn\'t specified.');
		return true;
	}

	validateGameCompiler(showNotification = true) {
		return validateGameCompiler(this.game, showNotification);
	}

	setGameFromDefault() {
		const defaultGame = atom.config.get('build-papyrus.defaultGame');
		this.game = GAMES.findIndex(obj => obj.slug === defaultGame);
		if(this.game === -1) {
			this.game = GAME_UNKNOWN;
			return false;
		}
		return true;
	}

	closeFileWatchers() {
		this.fileWatchers.forEach((watcher, index, array) => {
			watcher.close();
			delete array[index];
		});
	}
}
<commit_msg>Made the config release and final not affect the release and final build configs<commit_after>'use babel';
'use strict';

import fs from 'fs';
import path from 'path';
import EventEmitter from 'events';
import { CompositeDisposable } from 'atom';
import { GAMES, GAME_UNKNOWN, GAME_SKYRIM, ERROR_MATCH, loadConfigFile, validateGameCompiler } from './util';

export default class PapyrusBuildProvider extends EventEmitter {
	constructor(cwd) {
		super();

		// Initialise all the things
		this.cwd = cwd;
		this.game = GAME_UNKNOWN;
		this.configFile = null;
		this.projectFile = null;
		this.disposables = new CompositeDisposable();
		this.fileWatchers = [];

		// Add listeners for game compiler settings to refresh the build targets
		GAMES.forEach((game, index, array) => {
			if(index === 0) return;
			this.disposables.add(atom.config.onDidChange('build-papyrus.' + game.slug + 'CompilerPath', (newValue) => {
				if(this.game === index && this.validateGameCompiler(false)) this.emit('refresh');
			}));
		});

		// Listen for the default game changing for projects
		this.disposables.add(atom.config.onDidChange('build-papyrus.defaultGame', (newValue) => {
			if(this.projectFile) this.emit('refresh');
		}));
	}

	destructor() {
		this.disposables.dispose();
		this.closeFileWatchers();
	}

	getNiceName() {
		return 'Papyrus';
	}

	isEligible() {
		this.configFile = null;
		this.projectFile = null;
		this.closeFileWatchers();

		// Search for .papyrus.json and Papyrus project files
		const files = fs.readdirSync(this.cwd);
		for(const fileName of files) {
			const filePath = path.join(this.cwd, fileName);
			if(fs.statSync(filePath).isFile()) {
				const baseName = path.basename(fileName);
				if(!this.configFile && (baseName === '.build-papyrus.json' || baseName === '.build-papyrus.cson' || baseName === '.build-papyrus.yml')) {
					this.configFile = filePath;
					this.fileWatchers.push(fs.watch(this.configFile, () => this.emit('refresh')));
				} else if(!this.projectFile && path.extname(fileName).toLowerCase() === '.ppj') {
					this.projectFile = filePath;
				}
			}
		}

		this.game = GAME_UNKNOWN;
		if(this.projectFile || this.configFile) return true;
		return false;
	}

	settings() {
		return new Promise((resolve, reject) => {
			if(this.configFile) this.config = loadConfigFile(this.configFile);
			if(this.config) {
				if(!this.projectFile && !this.config.game && !this.config.compiler) return reject(new Error('Either "game" or "compiler" must be specified in the Papyrus config file.'));

				// Get the game from the config
				if(this.config.game) {
					this.config.game = this.config.game.toLowerCase();
					this.game = GAMES.findIndex(game => game.slug === this.config.game);
					if(this.game === -1) {
						this.game = GAME_UNKNOWN;
						return reject(new Error('Invalid "game" specified in the Papyrus config file. Must be one of "skyrim" or "fallout4".'));
					}
				}

				// Get the default game for projects
				if(this.game === GAME_UNKNOWN && this.projectFile) {
					if(!this.setGameFromDefault()) return reject(new Error('Invalid default game in build-papyrus settings'));
				}

				// If the game is still unknown or the compiler setting is set, validate the custom compiler
				if(this.game === GAME_UNKNOWN || this.config.compiler) {
					try {
						if(!this.config.compiler || !fs.statSync(this.config.compiler).isFile()) {
							return reject(new Error('"compiler" must be specified and a valid path to a file in the Papyrus config file since "game" isn\'t specified.'));
						}
					} catch(e) {
						return reject(new Error('"compiler" must be a valid path to a file in the Papyrus config file.'));
					}
				}
			} else {
				this.config = {};
				if(this.projectFile && !this.setGameFromDefault()) return reject(new Error('Invalid default game in build-papyrus settings.'));
			}

			if(this.game === GAME_UNKNOWN || this.validateGameCompiler()) {
				const buildConfigs = [];

				// Add the project file build configurations
				if(this.projectFile && this.game !== GAME_SKYRIM) {
					buildConfigs.push(this.makeBuildConfig('Papyrus: default (Project file)', [ this.projectFile ]));
					buildConfigs.push(this.makeBuildConfig('Papyrus: release (Project file)', [ this.projectFile, '-release' ]));
					buildConfigs.push(this.makeBuildConfig('Papyrus: final release (Project file)', [ this.projectFile, '-release', '-final' ]));
				}

				// Add the config file build configuration
				try {
					if(this.isConfigBuildable()) {
						const args = [
							'{FILE_ACTIVE}',
							'-import=' + this.config.imports.join(';'),
							'-output=' + (this.config.output ? this.config.output : '.'),
							'-flags=' + (this.game === GAME_UNKNOWN || this.config.flags ? this.config.flags : GAMES[this.game].flags)
						];
						if(typeof this.config.optimize === 'undefined' || this.config.optimize) args.push('-optimize');

						const defaultArgs = args.slice();
						if(this.config.release) defaultArgs.push('-release');
						if(this.config.final) defaultArgs.push('-final');
						buildConfigs.push(this.makeBuildConfig('Papyrus: default (Configuration file)', defaultArgs));

						if(this.game !== GAME_SKYRIM) {
							buildConfigs.push(this.makeBuildConfig('Papyrus: release (Configuration file)', args.concat(['-release'])));
							buildConfigs.push(this.makeBuildConfig('Papyrus: final release (Configuration file)', args.concat(['-release', '-final'])));
						}
					}
				} catch(e) {
					if(buildConfigs.length === 0) return reject(e);
				}

				return resolve(buildConfigs);
			} else {
				return reject(new Error('Invalid ' + GAMES[this.game].title + ' compiler path.'));
			}
		});
	}

	makeBuildConfig(name, args) {
		return {
			name: name,
			exec: this.game === GAME_UNKNOWN || this.config.compiler ? this.config.compiler : atom.config.get('build-papyrus.' + GAMES[this.game].slug + 'CompilerPath'),
			args: args,
			cwd: this.cwd,
			sh: false,
			errorMatch: ERROR_MATCH
		};
	}

	isConfigBuildable() {
		if(!this.config.game && !this.config.compiler) throw new Error('Either "game" or "compiler" must be specified in the Papyrus config file.');
		if(!Array.isArray(this.config.imports)) throw new Error('"imports" must be specified as an array in the Papyrus config file.');
		if(this.config.output && !fs.statSync(this.config.output).isDirectory()) throw new Error('"output" must be a valid directory in the Papyrus config file.');
		if(this.game === GAME_UNKNOWN && !this.config.flags) throw new Error('"flags" must be specified in the Papyrus config file since "game" isn\'t specified.');
		return true;
	}

	validateGameCompiler(showNotification = true) {
		return validateGameCompiler(this.game, showNotification);
	}

	setGameFromDefault() {
		const defaultGame = atom.config.get('build-papyrus.defaultGame');
		this.game = GAMES.findIndex(obj => obj.slug === defaultGame);
		if(this.game === -1) {
			this.game = GAME_UNKNOWN;
			return false;
		}
		return true;
	}

	closeFileWatchers() {
		this.fileWatchers.forEach((watcher, index, array) => {
			watcher.close();
			delete array[index];
		});
	}
}
<|endoftext|>


<commit_before>#!/bin/false
// common functions for parsing the JSON comments out of
// the C wrapper files (like common.py)

var fs = require('fs');
var path = require('path');

/// Object representing each builtin
function Builtin(j) {
  // remove arrays of description - folw it down with newlines
  if ("description" in j)
    if (j.description instanceof Array)
      j.description = j.description.join("\n\n");
  for (var k in j)
    this[k] = j[k];
}

Builtin.prototype.getDescription = function() {
  var d = "";
  if ("description" in this)
    d = this.description;
  if (d instanceof Array)
      d = d.join("\n\n");
  return d;
};

Builtin.prototype.getURL = function() {
  if (this.type == "class")
    anchor = this.class;
  else if ("class" in this)
    anchor = "l_"+this.class+"_"+this.name;
  else
    anchor = "l__global_"+this.name;
  return "http://www.espruino.com/Reference#"+anchor;
};

/// Tern types - for tern.js json format
function getBasicTernType(t) {
  if (["int","float","int32"].indexOf(t)>=0) return "number";
  if (t=="pin") return "+Pin";
  if (t=="bool") return "bool";
  if (t=="JsVarArray") return "?"; // TODO: not right. Should be variable arg count
  return "?";
}

/// Get full Tern type - for tern.js json format
Builtin.prototype.getTernType = function() {
  if (["class","library"].indexOf(this.type)>=0) {
    return "fn()";
  } else if (["function","method","staticmethod","constructor"].indexOf(this.type)>=0) {
    // it's a function
    var args = [];
    if ("params" in this)
      args = this.params.map(function (p) {
        return p[0]+": "+getBasicTernType(p[1]);
      });
    var ret = "";
    if ("return_object" in this)
      ret = " -> +"+this.return_object
    else if ("return" in this)
      ret = " -> "+getBasicTernType(this.return[0]);
    return "fn("+args.join("\, ")+")"+ret;
  } else {
    return getBasicTernType(this.return[0]);
  }
};

/// Get any files that we think might contain 'JSON' tags
exports.getWrapperFiles = function (callback) {
  var BASEDIR = path.resolve(__dirname, "..");
  require('child_process').exec("find "+BASEDIR+" -name jswrap*.c", function(error, stdout, stderr) {
    callback(stdout.toString().trim().split("\n"));
  });
}

/// Extract the /*JSON ... */ comments from a file and parse them
exports.readWrapperFile = function(filename) {
  var contents = fs.readFileSync(filename).toString();
  var builtins = [];
  var comments = contents.match( /\/\*JSON(?:(?!\*\/).|[\n\r])*\*\//g );
  if (comments) comments.forEach(function(comment) {
    var j = new Builtin(JSON.parse(comment.slice(6,-2)));
    j.implementation = filename;
    builtins.push(j);
  });
  return builtins;
}

/// Extract all parsed /*JSON ... */ comments from all files
exports.readAllWrapperFiles = function(callback) {
  exports.getWrapperFiles(function(files) {
    var builtins = [];
    files.forEach(function(filename) {
      builtins = builtins.concat(exports.readWrapperFile(filename));
    });
    callback(builtins);
  });
}

<commit_msg>hack for pin args to digitalWrite/etc<commit_after>#!/bin/false
// common functions for parsing the JSON comments out of
// the C wrapper files (like common.py)

var fs = require('fs');
var path = require('path');

/// Object representing each builtin
function Builtin(j) {
  // remove arrays of description - folw it down with newlines
  if ("description" in j)
    if (j.description instanceof Array)
      j.description = j.description.join("\n\n");
  for (var k in j)
    this[k] = j[k];
}

Builtin.prototype.getDescription = function() {
  var d = "";
  if ("description" in this)
    d = this.description;
  if (d instanceof Array)
      d = d.join("\n\n");
  return d;
};

Builtin.prototype.getURL = function() {
  if (this.type == "class")
    anchor = this.class;
  else if ("class" in this)
    anchor = "l_"+this.class+"_"+this.name;
  else
    anchor = "l__global_"+this.name;
  return "http://www.espruino.com/Reference#"+anchor;
};

/// Tern types - for tern.js json format
function getBasicTernType(t) {
  if (["int","float","int32"].indexOf(t)>=0) return "number";
  if (t=="pin") return "+Pin";
  if (t=="bool") return "bool";
  if (t=="JsVarArray") return "?"; // TODO: not right. Should be variable arg count
  return "?";
}

/// Get full Tern type - for tern.js json format
Builtin.prototype.getTernType = function() {
  if (["class","library"].indexOf(this.type)>=0) {
    return "fn()";
  } else if (["function","method","staticmethod","constructor"].indexOf(this.type)>=0) {
    // it's a function
    var args = [];
    if ("params" in this)
      args = this.params.map(function (p) {
        if (p[0]=="pin" && p[1]=="JsVar")
          return "pin: +Pin"; // hack because digitalRead/Write can also take arrays/objects (but most use cases are Pins)
        return p[0]+": "+getBasicTernType(p[1]);
      });
    var ret = "";
    if ("return_object" in this)
      ret = " -> +"+this.return_object
    else if ("return" in this)
      ret = " -> "+getBasicTernType(this.return[0]);
    return "fn("+args.join("\, ")+")"+ret;
  } else {
    return getBasicTernType(this.return[0]);
  }
};

/// Get any files that we think might contain 'JSON' tags
exports.getWrapperFiles = function (callback) {
  var BASEDIR = path.resolve(__dirname, "..");
  require('child_process').exec("find "+BASEDIR+" -name jswrap*.c", function(error, stdout, stderr) {
    callback(stdout.toString().trim().split("\n"));
  });
}

/// Extract the /*JSON ... */ comments from a file and parse them
exports.readWrapperFile = function(filename) {
  var contents = fs.readFileSync(filename).toString();
  var builtins = [];
  var comments = contents.match( /\/\*JSON(?:(?!\*\/).|[\n\r])*\*\//g );
  if (comments) comments.forEach(function(comment) {
    var j = new Builtin(JSON.parse(comment.slice(6,-2)));
    j.implementation = filename;
    builtins.push(j);
  });
  return builtins;
}

/// Extract all parsed /*JSON ... */ comments from all files
exports.readAllWrapperFiles = function(callback) {
  exports.getWrapperFiles(function(files) {
    var builtins = [];
    files.forEach(function(filename) {
      builtins = builtins.concat(exports.readWrapperFile(filename));
    });
    callback(builtins);
  });
}

<|endoftext|>


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

var padeditbar = (function(){

  var syncAnimation = (function() {
    var SYNCING = -100;
    var DONE = 100;
    var state = DONE;
    var fps = 25;
    var step = 1/fps;
    var T_START = -0.5;
    var T_FADE = 1.0;
    var T_GONE = 1.5;
    var animator = padutils.makeAnimationScheduler(function() {
      if (state == SYNCING || state == DONE) {
        return false;
      }
      else if (state >= T_GONE) {
        state = DONE;
        $("#syncstatussyncing").css('display', 'none');
        $("#syncstatusdone").css('display', 'none');
        return false;
      }
      else if (state < 0) {
        state += step;
        if (state >= 0) {
          $("#syncstatussyncing").css('display', 'none');
          $("#syncstatusdone").css('display', 'block').css('opacity', 1);
        }
        return true;
      }
      else {
        state += step;
        if (state >= T_FADE) {
          $("#syncstatusdone").css('opacity', (T_GONE - state) / (T_GONE - T_FADE));
        }
        return true;
      }
    }, step*1000);
    return {
      syncing: function() {
        state = SYNCING;
        $("#syncstatussyncing").css('display', 'block');
        $("#syncstatusdone").css('display', 'none');
      },
      done: function() {
        state = T_START;
        animator.scheduleAnimation();
      }
    };
  }());

  var self = {
    init: function() {
      $("#editbar .editbarbutton").attr("unselectable", "on"); // for IE
      $("#editbar").removeClass("disabledtoolbar").addClass("enabledtoolbar");
    },
    isEnabled: function() {
      return ! $("#editbar").hasClass('disabledtoolbar');
    },
    disable: function() {
      $("#editbar").addClass('disabledtoolbar').removeClass("enabledtoolbar");
    },
    toolbarClick: function(cmd) {
      if (self.isEnabled()) {
        if (cmd == 'showusers') {
        // get current height
        var editbarheight = $('#editbar').css('height');
          if (editbarheight == "36px"){
            // increase the size of the editbar
            $('#editbar').animate({height:'72px'});
            $('#editorcontainerbox').animate({top:'72px'});
          }
          else
          {
            // increase the size of the editbar
            $('#editbar').animate({height:'36px'});
            $('#editorcontainerbox').animate({top:'36px'});
          }
        }
        if (cmd == 'embed') {
        // get current height
        var editbarheight = $('#editbar').css('height');
          if (editbarheight == "36px"){
            // increase the size of the editbar
            $('#editbar').animate({height:'72px'});
            $('#editorcontainerbox').animate({top:'72px'});
            padurl = document.location;
            $('#embed').html('
Embed code:<input id="embedinput" type="text" value="
">');
            $('#embed').show();
          }
          else
          {
            // increase the size of the editbar
            $('#editbar').animate({height:'36px'});
            $('#editorcontainerbox').animate({top:'36px'});
            $('#embed').hide();
          }
        }
        if (cmd == 'save') {
          padsavedrevs.saveNow();
        } else {
	  padeditor.ace.callWithAce(function (ace) {
	    if (cmd == 'bold' || cmd == 'italic' || cmd == 'underline' || cmd == 'strikethrough')
	      ace.ace_toggleAttributeOnSelection(cmd);
            else if (cmd == 'undo' || cmd == 'redo')
	      ace.ace_doUndoRedo(cmd);
            else if (cmd == 'insertunorderedlist')
	      ace.ace_doInsertUnorderedList();
            else if (cmd == 'indent') {
	      if (! ace.ace_doIndentOutdent(false)) {
	       ace.ace_doInsertUnorderedList();
	      }
	    } else if (cmd == 'outdent') {
              ace.ace_doIndentOutdent(true);
	    } else if (cmd == 'clearauthorship') {
	      if ((!(ace.ace_getRep().selStart && ace.ace_getRep().selEnd)) || ace.ace_isCaret()) {
		if (window.confirm("Clear authorship colors on entire document?")) {
		  ace.ace_performDocumentApplyAttributesToCharRange(0, ace.ace_getRep().alltext.length,
							    [['author', '']]);
		}
	      } else {
		ace.ace_setAttributeOnSelection('author', '');
	      }
	    }
	  }, cmd, true);
        }
      }
      padeditor.ace.focus();
    },
    setSyncStatus: function(status) {
      if (status == "syncing") {
        syncAnimation.syncing();
      }
      else if (status == "done") {
        syncAnimation.done();
      }
    }
  };
  return self;
}());
<commit_msg>Fix minor css bug in embed part 2<commit_after>/**
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var padeditbar = (function(){

  var syncAnimation = (function() {
    var SYNCING = -100;
    var DONE = 100;
    var state = DONE;
    var fps = 25;
    var step = 1/fps;
    var T_START = -0.5;
    var T_FADE = 1.0;
    var T_GONE = 1.5;
    var animator = padutils.makeAnimationScheduler(function() {
      if (state == SYNCING || state == DONE) {
        return false;
      }
      else if (state >= T_GONE) {
        state = DONE;
        $("#syncstatussyncing").css('display', 'none');
        $("#syncstatusdone").css('display', 'none');
        return false;
      }
      else if (state < 0) {
        state += step;
        if (state >= 0) {
          $("#syncstatussyncing").css('display', 'none');
          $("#syncstatusdone").css('display', 'block').css('opacity', 1);
        }
        return true;
      }
      else {
        state += step;
        if (state >= T_FADE) {
          $("#syncstatusdone").css('opacity', (T_GONE - state) / (T_GONE - T_FADE));
        }
        return true;
      }
    }, step*1000);
    return {
      syncing: function() {
        state = SYNCING;
        $("#syncstatussyncing").css('display', 'block');
        $("#syncstatusdone").css('display', 'none');
      },
      done: function() {
        state = T_START;
        animator.scheduleAnimation();
      }
    };
  }());

  var self = {
    init: function() {
      $("#editbar .editbarbutton").attr("unselectable", "on"); // for IE
      $("#editbar").removeClass("disabledtoolbar").addClass("enabledtoolbar");
    },
    isEnabled: function() {
      return ! $("#editbar").hasClass('disabledtoolbar');
    },
    disable: function() {
      $("#editbar").addClass('disabledtoolbar').removeClass("enabledtoolbar");
    },
    toolbarClick: function(cmd) {
      if (self.isEnabled()) {
        if (cmd == 'showusers') {
        // get current height
        var editbarheight = $('#editbar').css('height');
          if (editbarheight == "36px"){
            // increase the size of the editbar
            $('#editbar').animate({height:'72px'});
            $('#editorcontainerbox').animate({top:'72px'});
          }
          else
          {
            // increase the size of the editbar
            $('#editbar').animate({height:'36px'});
            $('#editorcontainerbox').animate({top:'36px'});
          }
        }
        if (cmd == 'embed') {
        // get current height
        var editbarheight = $('#editbar').css('height');
          if (editbarheight == "36px"){
            // increase the size of the editbar
            $('#editbar').animate({height:'72px'});
            $('#editorcontainerbox').animate({top:'72px'});
            padurl = document.location;
            $('#embed').html('
Embed code:<input id="embedinput" type="text" value="">
');
            $('#embed').show();
          }
          else
          {
            // increase the size of the editbar
            $('#editbar').animate({height:'36px'});
            $('#editorcontainerbox').animate({top:'36px'});
            $('#embed').hide();
          }
        }
        if (cmd == 'save') {
          padsavedrevs.saveNow();
        } else {
	  padeditor.ace.callWithAce(function (ace) {
	    if (cmd == 'bold' || cmd == 'italic' || cmd == 'underline' || cmd == 'strikethrough')
	      ace.ace_toggleAttributeOnSelection(cmd);
            else if (cmd == 'undo' || cmd == 'redo')
	      ace.ace_doUndoRedo(cmd);
            else if (cmd == 'insertunorderedlist')
	      ace.ace_doInsertUnorderedList();
            else if (cmd == 'indent') {
	      if (! ace.ace_doIndentOutdent(false)) {
	       ace.ace_doInsertUnorderedList();
	      }
	    } else if (cmd == 'outdent') {
              ace.ace_doIndentOutdent(true);
	    } else if (cmd == 'clearauthorship') {
	      if ((!(ace.ace_getRep().selStart && ace.ace_getRep().selEnd)) || ace.ace_isCaret()) {
		if (window.confirm("Clear authorship colors on entire document?")) {
		  ace.ace_performDocumentApplyAttributesToCharRange(0, ace.ace_getRep().alltext.length,
							    [['author', '']]);
		}
	      } else {
		ace.ace_setAttributeOnSelection('author', '');
	      }
	    }
	  }, cmd, true);
        }
      }
      padeditor.ace.focus();
    },
    setSyncStatus: function(status) {
      if (status == "syncing") {
        syncAnimation.syncing();
      }
      else if (status == "done") {
        syncAnimation.done();
      }
    }
  };
  return self;
}());
<|endoftext|>