<commit_before>$(function() {
  var containers = {}
  var shipments = []
  var dewars = []

  $('.error').dialog({ autoOpen: false, buttons: { 'Close': function() { $(this).dialog('close') } } });
  $('.confirm').dialog({ autoOpen: false, modal: true })

  // Setup beamline puck slots
  function load_blpos() {
    var drop = {
      accept: '.container',
      hoverClass: 'bl_puck_drag',
      drop: _container_drop
    }

    var pucks = (bl == 'i04-1' || bl == 'i24') ? 9 : 10
    for (var i = 1; i <= pucks; i++) {
      $('
'+i+'

').droppable(drop).appendTo('#assigned').data('blcid', i)
    }

    $('#unassigned').droppable({
        accept: '.bl_puck .ac div',
        hoverClass: 'unassigned_drag',
        drop: _unassigned_drop
    })
  }

  function _unassigned_drop(e,ui) {
    var t = $('.shipment[sid='+ui.draggable.attr('sid')+']').children('.dewar[did='+ui.draggable.attr('did')+']').children('.containers')
    _confirm('Unassign Container', 'Are you sure you want to unassign this container?', function() {

      ui.draggable.appendTo(t).position({ my: 'left top', at: 'left top', of: t})
      ui.draggable.removeClass('assigned')

      // assign db callback
      console.log('remove container id ' + ui.draggable.attr('cid'))
      _unassign_container(ui.draggable.attr('cid'))
    })
  }

  // Container Drop
  function _container_drop(e,ui) {
    if (ui.draggable.parent().parent().attr('id') != $(this).attr('id')) {
     var p = $(this)
      _confirm('Assign Container', 'Are you sure you want to assign this container? Any other container assigned to this slot will be unassigned', function() {
      if (p.children('div').has('.container').length > 0){
        prev = p.children('div').children('.container')
        t = $('.shipment[sid='+prev.attr('sid')+']').children('.dewar[did='+prev.attr('did')+']').children('.containers')
        prev.appendTo(t).attr('loc', '').removeClass('assigned')

        // remove prev db call
        console.log('remove container id ' + prev.attr('cid'))
        _unassign_container(prev.attr('cid'))
        containers[prev.attr('cid')] = 0
      }

      p.children('div').html('')
      ui.draggable.appendTo(p.children('div')).position({ my: 'left top', at: 'left top', of: p.children('div')}).addClass('assigned').attr('loc', p.data('blcid'))

      // assign db callback & refresh
      console.log('add container id ' + ui.draggable.attr('cid') + ' to ' + bl +'-'+ p.data('blcid'))
      _assign_container(ui.draggable.attr('cid'), p.data('blcid'))
    })
    }
  }

  function _assign_container(cid, pos) {
    $.ajax({
      url: '/samples/ajax/assign/visit/' + visit + '/cid/' + cid + '/pos/' + pos,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(r){
        _get_containers()
      }
    })
  }

  function _unassign_container(cid) {
    $.ajax({
      url: '/samples/ajax/unassign/visit/' + visit + '/cid/' + cid,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(r){
        _get_containers()
      }
    })
  }

  // Retrieve shipments for visit
  function _get_shipments(fn) {
    $.ajax({
      url: '/samples/ajax/ship/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){
        var ship_opts = ''

        $.each(json, function(i,s) {
            ship_opts += '<option value="'+s['SHIPPINGID']+'">'+s['SHIPPINGNAME']+'</option>';
            if ($.inArray(s['SHIPPINGID'], shipments) == -1) {

              $('

'+s['SHIPPINGNAME']+'

').hide().appendTo('#unassigned').slideDown()

              shipments.push(s['SHIPPINGID'])
            }
        })

        $('select[name=shipment]').html(ship_opts).combobox('value', null)
        if (fn) fn()
        _get_dewars()
      }
    })
  }

  // Retrieve dewars for visit
  function _get_dewars(fn) {
    $.ajax({
      url: '/samples/ajax/dwr/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){
        $.each(json, function(i,d) {
            if ($.inArray(d['DEWARID'], dewars) == -1) {
               $('

'+d['CODE']+'

').hide().appendTo('div[sid='+d['SHIPPINGID']+']').addClass(d['DEWARSTATUS'] == 'processing' ? 'active' : '')

               if (d['DEWARSTATUS'] == 'processing') $('div[did='+d['DEWARID']+']').slideDown()

              dewars.push(d['DEWARID'])
            }
        })

        if (fn) fn()
        _get_containers()
      }
    })
  }

  // Retrieve containers for visit
  function _get_containers() {
    $.ajax({
      url: '/samples/ajax/cnt/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){

        var drag = {
          containment: '#drag_container',
          stack: '#unassigned div',
          /*cursor: 'move',*/
          /*cancel: 'a',*/
          revert: true
        }

        $.each(json, function(i,c) {
            var a = c['SAMPLECHANGERLOCATION']
            //var b = c['BEAMLINELOCATION']
            var assigned = c['SAMPLECHANGERLOCATION'] && (c['BEAMLINELOCATION'] == bl) && (c['DEWARSTATUS'] == 'processing')

            if (!(c['CONTAINERID'] in containers)) {
              sc = $('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')

               $('
View Container
'+c['CODE']+'

').appendTo(assigned ? ($('#blp'+a).children('div')) : sc).addClass(assigned ? 'assigned' : '').draggable(drag)
              containers[c['CONTAINERID']] = a

            } else {
               d = $('div[cid='+c['CONTAINERID']+']')
               var state = c['SAMPLECHANGERLOCATION'] == d.attr('loc') && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing'
               if (!state) {
                 if (c['SAMPLECHANGERLOCATION'] && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing') d.appendTo($('#blp'+a).children('div')).addClass('assigned')
                 else d.appendTo($('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')).removeClass('assigned')
               }

            }
        })

        map_callbacks()
      }
    })
  }

  // Generate a confirmation dialog
  function _confirm(t, q, ok_fn) {
    $('.confirm').html(q).dialog('option', 'title', t)
    $('.confirm').dialog('option', 'buttons', {
      'Ok': function() {
        ok_fn()
        $(this).dialog('close');
      },
      'Cancel': function () {
        $(this).dialog('close');
      }
    });

    $('.confirm').dialog('open');
  }

  // Map callbacks to containers
  function map_callbacks() {
    $('.shipment > h1').unbind('click').click(function() {
      $(this).siblings('.dewar').slideToggle()
      return false
    })

    $('.container a').button({ icons: { primary: 'ui-icon-search' }, text: false })
  }

  load_blpos()
  _get_shipments()

  // Bind links / buttons
  $('#add').button({ icons: { primary: 'ui-icon-plusthick' } }).click(function() {
    _add_container()
  })

  $('.add span a').click(function() {
    $('.add_protein').dialog('open')
    return false
  })

});
<commit_msg>Move from div clear to clear fix<commit_after>$(function() {
  var containers = {}
  var shipments = []
  var dewars = []

  $('.error').dialog({ autoOpen: false, buttons: { 'Close': function() { $(this).dialog('close') } } });
  $('.confirm').dialog({ autoOpen: false, modal: true })

  // Setup beamline puck slots
  function load_blpos() {
    var drop = {
      accept: '.container',
      hoverClass: 'bl_puck_drag',
      drop: _container_drop
    }

    var pucks = (bl == 'i04-1' || bl == 'i24') ? 9 : 10
    for (var i = 1; i <= pucks; i++) {
      $('
'+i+'

').droppable(drop).appendTo('#assigned').data('blcid', i)
    }

    $('#unassigned').droppable({
        accept: '.bl_puck .ac div',
        hoverClass: 'unassigned_drag',
        drop: _unassigned_drop
    })
  }

  function _unassigned_drop(e,ui) {
    var t = $('.shipment[sid='+ui.draggable.attr('sid')+']').children('.dewar[did='+ui.draggable.attr('did')+']').children('.containers')
    _confirm('Unassign Container', 'Are you sure you want to unassign this container?', function() {

      ui.draggable.appendTo(t).position({ my: 'left top', at: 'left top', of: t})
      ui.draggable.removeClass('assigned')

      // assign db callback
      console.log('remove container id ' + ui.draggable.attr('cid'))
      _unassign_container(ui.draggable.attr('cid'))
    })
  }

  // Container Drop
  function _container_drop(e,ui) {
    if (ui.draggable.parent().parent().attr('id') != $(this).attr('id')) {
     var p = $(this)
      _confirm('Assign Container', 'Are you sure you want to assign this container? Any other container assigned to this slot will be unassigned', function() {
      if (p.children('div').has('.container').length > 0){
        prev = p.children('div').children('.container')
        t = $('.shipment[sid='+prev.attr('sid')+']').children('.dewar[did='+prev.attr('did')+']').children('.containers')
        prev.appendTo(t).attr('loc', '').removeClass('assigned')

        // remove prev db call
        console.log('remove container id ' + prev.attr('cid'))
        _unassign_container(prev.attr('cid'))
        containers[prev.attr('cid')] = 0
      }

      p.children('div').html('')
      ui.draggable.appendTo(p.children('div')).position({ my: 'left top', at: 'left top', of: p.children('div')}).addClass('assigned').attr('loc', p.data('blcid'))

      // assign db callback & refresh
      console.log('add container id ' + ui.draggable.attr('cid') + ' to ' + bl +'-'+ p.data('blcid'))
      _assign_container(ui.draggable.attr('cid'), p.data('blcid'))
    })
    }
  }

  function _assign_container(cid, pos) {
    $.ajax({
      url: '/samples/ajax/assign/visit/' + visit + '/cid/' + cid + '/pos/' + pos,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(r){
        _get_containers()
      }
    })
  }

  function _unassign_container(cid) {
    $.ajax({
      url: '/samples/ajax/unassign/visit/' + visit + '/cid/' + cid,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(r){
        _get_containers()
      }
    })
  }

  // Retrieve shipments for visit
  function _get_shipments(fn) {
    $.ajax({
      url: '/samples/ajax/ship/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){
        var ship_opts = ''

        $.each(json, function(i,s) {
            ship_opts += '<option value="'+s['SHIPPINGID']+'">'+s['SHIPPINGNAME']+'</option>';
            if ($.inArray(s['SHIPPINGID'], shipments) == -1) {

              $('

'+s['SHIPPINGNAME']+'

').hide().appendTo('#unassigned').slideDown()

              shipments.push(s['SHIPPINGID'])
            }
        })

        $('select[name=shipment]').html(ship_opts).combobox('value', null)
        if (fn) fn()
        _get_dewars()
      }
    })
  }

  // Retrieve dewars for visit
  function _get_dewars(fn) {
    $.ajax({
      url: '/samples/ajax/dwr/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){
        $.each(json, function(i,d) {
            if ($.inArray(d['DEWARID'], dewars) == -1) {
               $('

'+d['CODE']+'

').hide().appendTo('div[sid='+d['SHIPPINGID']+']').addClass(d['DEWARSTATUS'] == 'processing' ? 'active' : '')

               if (d['DEWARSTATUS'] == 'processing') $('div[did='+d['DEWARID']+']').slideDown()

              dewars.push(d['DEWARID'])
            }
        })

        if (fn) fn()
        _get_containers()
      }
    })
  }

  // Retrieve containers for visit
  function _get_containers() {
    $.ajax({
      url: '/samples/ajax/cnt/visit/' + visit,
      type: 'GET',
      dataType: 'json',
      timeout: 5000,
      success: function(json){

        var drag = {
          containment: '#drag_container',
          stack: '#unassigned div',
          /*cursor: 'move',*/
          /*cancel: 'a',*/
          revert: true
        }

        $.each(json, function(i,c) {
            var a = c['SAMPLECHANGERLOCATION']
            //var b = c['BEAMLINELOCATION']
            var assigned = c['SAMPLECHANGERLOCATION'] && (c['BEAMLINELOCATION'] == bl) && (c['DEWARSTATUS'] == 'processing')

            if (!(c['CONTAINERID'] in containers)) {
              sc = $('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')

               $('
View Container
'+c['CODE']+'

').appendTo(assigned ? ($('#blp'+a).children('div')) : sc).addClass(assigned ? 'assigned' : '').draggable(drag)
              containers[c['CONTAINERID']] = a

            } else {
               d = $('div[cid='+c['CONTAINERID']+']')
               var state = c['SAMPLECHANGERLOCATION'] == d.attr('loc') && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing'
               if (!state) {
                 if (c['SAMPLECHANGERLOCATION'] && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing') d.appendTo($('#blp'+a).children('div')).addClass('assigned')
                 else d.appendTo($('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')).removeClass('assigned')
               }

            }
        })

        map_callbacks()
      }
    })
  }

  // Generate a confirmation dialog
  function _confirm(t, q, ok_fn) {
    $('.confirm').html(q).dialog('option', 'title', t)
    $('.confirm').dialog('option', 'buttons', {
      'Ok': function() {
        ok_fn()
        $(this).dialog('close');
      },
      'Cancel': function () {
        $(this).dialog('close');
      }
    });

    $('.confirm').dialog('open');
  }

  // Map callbacks to containers
  function map_callbacks() {
    $('.shipment > h1').unbind('click').click(function() {
      $(this).siblings('.dewar').slideToggle()
      return false
    })

    $('.container a').button({ icons: { primary: 'ui-icon-search' }, text: false })
  }

  load_blpos()
  _get_shipments()

  // Bind links / buttons
  $('#add').button({ icons: { primary: 'ui-icon-plusthick' } }).click(function() {
    _add_container()
  })

  $('.add span a').click(function() {
    $('.add_protein').dialog('open')
    return false
  })

});
<|endoftext|>


<commit_before>/**
Bootstrap wysihtml5 editor. Based on [bootstrap-wysihtml5](https://github.com/jhollingworth/bootstrap-wysihtml5).
You should include **manually** distributives of `wysihtml5` and `bootstrap-wysihtml5`:

    <link href="js/inputs-ext/wysihtml5/bootstrap-wysihtml5-0.0.2/bootstrap-wysihtml5-0.0.2.css" rel="stylesheet" type="text/css"></link>

And also include `wysihtml5.js` from `inputs-ext` directory of x-editable:

**Note:** It's better to use fresh bootstrap-wysihtml5 from it's [master branch](https://github.com/jhollingworth/bootstrap-wysihtml5/tree/master/src) as there is update for correct image insertion.

@class wysihtml5
@extends abstractinput
@final
@since 1.4.0
@example

awesome
 comment!

**/
(function ($) {
    "use strict";

    var Wysihtml5 = function (options) {
        this.init('wysihtml5', options, Wysihtml5.defaults);

        //extend wysihtml5 manually as $.extend not recursive
        this.options.wysihtml5 = $.extend({}, Wysihtml5.defaults.wysihtml5, options.wysihtml5);
    };

    $.fn.editableutils.inherit(Wysihtml5, $.fn.editabletypes.abstractinput);

    $.extend(Wysihtml5.prototype, {
        render: function () {
            var deferred = $.Deferred(),
            msieOld;

            //generate unique id as it required for wysihtml5
            this.$input.attr('id', 'textarea_'+(new Date()).getTime());

            this.setClass();
            this.setAttr('placeholder');

            //resolve deffered when widget loaded
            $.extend(this.options.wysihtml5, {
                events: {
                  load: function() {
                      deferred.resolve();
                  }
                }
            });

            this.$input.wysihtml5(this.options.wysihtml5);

            /*
             In IE8 wysihtml5 iframe stays on the same line with buttons toolbar (inside popover).
             The only solution I found is to add
. If you fine better way, please send PR.
            */
            msieOld = /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase());
            if(msieOld) {
                this.$input.before('

');
            }

            return deferred.promise();
        },

        valueIsEncoded: true,

        value2html: function(value, element) {
            $(element).html(value);
            this.valueIsEncoded = false;
        },

        html2value: function(html) {
            return html;
        },

        value2input: function(value) {
            value = (this.valueIsEncoded ? this.base65decode(value) : value);
            this.$input.data("wysihtml5").editor.setValue(value, true);
        },

        base65decode: function(value) {
            return decodeURIComponent( escape( atob( value.replace(/\s/g, ''))));
        },

        activate: function() {
            this.$input.data("wysihtml5").editor.focus();
        },

        isEmpty: function($element) {
            if($.trim($element.html()) === '') {
                return true;
            } else if($.trim($element.text()) !== '') {
                return false;
            } else {
                //e.g. '', '
', '

'
                return !$element.height() || !$element.width();
            }
        }
    });

    Wysihtml5.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl
        @default <textarea></textarea>
        **/
        tpl:'<textarea></textarea>',
        /**
        @property inputclass
        @default editable-wysihtml5
        **/
        inputclass: 'editable-wysihtml5',
        /**
        Placeholder attribute of input. Shown when input is empty.

        @property placeholder
        @type string
        @default null
        **/
        placeholder: null,
        /**
        Wysihtml5 default options.
        See https://github.com/jhollingworth/bootstrap-wysihtml5#options

        @property wysihtml5
        @type object
        @default {stylesheets: false}
        **/
        wysihtml5: {
            stylesheets: false //see https://github.com/jhollingworth/bootstrap-wysihtml5/issues/183
        }
    });

    $.fn.editabletypes.wysihtml5 = Wysihtml5;

}(window.jQuery));
<commit_msg>remove whitespaces<commit_after>/**
Bootstrap wysihtml5 editor. Based on [bootstrap-wysihtml5](https://github.com/jhollingworth/bootstrap-wysihtml5).
You should include **manually** distributives of `wysihtml5` and `bootstrap-wysihtml5`:

    <link href="js/inputs-ext/wysihtml5/bootstrap-wysihtml5-0.0.2/bootstrap-wysihtml5-0.0.2.css" rel="stylesheet" type="text/css"></link>

And also include `wysihtml5.js` from `inputs-ext` directory of x-editable:

**Note:** It's better to use fresh bootstrap-wysihtml5 from it's [master branch](https://github.com/jhollingworth/bootstrap-wysihtml5/tree/master/src) as there is update for correct image insertion.

@class wysihtml5
@extends abstractinput
@final
@since 1.4.0
@example

awesome
 comment!

**/
(function ($) {
    "use strict";

    var Wysihtml5 = function (options) {
        this.init('wysihtml5', options, Wysihtml5.defaults);

        //extend wysihtml5 manually as $.extend not recursive
        this.options.wysihtml5 = $.extend({}, Wysihtml5.defaults.wysihtml5, options.wysihtml5);
    };

    $.fn.editableutils.inherit(Wysihtml5, $.fn.editabletypes.abstractinput);

    $.extend(Wysihtml5.prototype, {
        render: function () {
            var deferred = $.Deferred(),
            msieOld;

            //generate unique id as it required for wysihtml5
            this.$input.attr('id', 'textarea_'+(new Date()).getTime());

            this.setClass();
            this.setAttr('placeholder');

            //resolve deffered when widget loaded
            $.extend(this.options.wysihtml5, {
                events: {
                  load: function() {
                      deferred.resolve();
                  }
                }
            });

            this.$input.wysihtml5(this.options.wysihtml5);

            /*
             In IE8 wysihtml5 iframe stays on the same line with buttons toolbar (inside popover).
             The only solution I found is to add
. If you fine better way, please send PR.
            */
            msieOld = /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase());
            if(msieOld) {
                this.$input.before('

');
            }

            return deferred.promise();
        },

        valueIsEncoded: true,

        value2html: function(value, element) {
            $(element).html(value);
            this.valueIsEncoded = false;
        },

        html2value: function(html) {
            return html;
        },

        value2input: function(value) {
            value = (this.valueIsEncoded ? this.base65decode(value) : value);
            this.$input.data("wysihtml5").editor.setValue(value, true);
        },

        base65decode: function(value) {
            return decodeURIComponent( escape( atob( value.replace(/\s/g, ''))));
        },

        activate: function() {
            this.$input.data("wysihtml5").editor.focus();
        },

        isEmpty: function($element) {
            if($.trim($element.html()) === '') {
                return true;
            } else if($.trim($element.text()) !== '') {
                return false;
            } else {
                //e.g. '', '
', '

'
                return !$element.height() || !$element.width();
            }
        }
    });

    Wysihtml5.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        /**
        @property tpl
        @default <textarea></textarea>
        **/
        tpl:'<textarea></textarea>',
        /**
        @property inputclass
        @default editable-wysihtml5
        **/
        inputclass: 'editable-wysihtml5',
        /**
        Placeholder attribute of input. Shown when input is empty.

        @property placeholder
        @type string
        @default null
        **/
        placeholder: null,
        /**
        Wysihtml5 default options.
        See https://github.com/jhollingworth/bootstrap-wysihtml5#options

        @property wysihtml5
        @type object
        @default {stylesheets: false}
        **/
        wysihtml5: {
            stylesheets: false //see https://github.com/jhollingworth/bootstrap-wysihtml5/issues/183
        }
    });

    $.fn.editabletypes.wysihtml5 = Wysihtml5;

}(window.jQuery));
<|endoftext|>


<commit_before>var xglobal = typeof global !== "undefined" ? global : this;

(function (global, name) {
    "use strict";

    var ns = global[name] = function (smth) {},
        isDebug = true;

    ns.ns = function (self, namespace, callbackOnNs) {

        if (!self[namespace]) {
            self[namespace] = {};
        }

        if (typeof callbackOnNs !== "undefined") {
            callbackOnNs.call(self[namespace]);
        }

        return this;
    };

    ns.getEmptyString = function () {return "";};

    /**
     * Formats string with pattern as first argument and values as other ones.
     * E.g.: ns.stringf("%s %s", "hello", "world") -> "hello world"
     * @return {String} formated string
     */
    ns.stringf = function () {

        var pattern = arguments[0],
            args = Array.prototype.slice.call(arguments, 1);

        return pattern.replace(/%s/g,
            function(){ return args.shift()||""; });

    };

    /**
     * Generates random number
     * @return {String} random number
     */
    ns.generateId = function () {
        return String(Math.random()).substr(2);
    };

    ns.map = function (arr, callback) {
        if (ns.isArray(arr) && callback instanceof Function) {
            return arr.map(callback);
        }
    };

    ns.console = {
        slog: function (pattern) {
            this.log( ns.stringf.apply(this, arguments) );
        },

        log: function (smth) {
            if (typeof debug !== "undefined") {
                debug(smth);
            } else if (global.console && global.console.log) {
                global.console.log(smth);
            }
        },

        error: function (txt) {
            throw new Error(txt);
        },

        dir: function (smth) {
            this.log(JSON.stringify(smth));
        }
    };
    ns.log = ns.console.log;
    ns.error = ns.console.error;

    var filterDegradation = function (arr, callback) {
        var res = [];

        x.each(arr, function (item, i) {
            if (callback(item, i, this)) {
                res.push(item);
            }
        });

        return res;
    };

    ns.filter = function (arr, callback) {
        if (!ns.isArray(arr)) {
            ns.error(
                "first argument is expected to be an array instead of " + typeof arr
            );
        }
        if (!ns.isFunc(callback)) {
            ns.error(
                "second argument is expected to be a function instead of " + typeof callback
            );
        }

        if (!arr.filter) {
            ns.error(
                "filter function is not implemented by default"
            );
        }

        return arr.filter ?
            arr.filter(callback) : filterDegradation(callback);

    };

    ns.isArray = function (item) {
        return (item instanceof Array);
    };

    ns.isObject = function (item) {
        return (typeof item === "object");
    };

    ns.eachListItem = function (arr, callback) {
        for (var i = 0, l = arr.length; i < l; i++) {
            callback(arr[i], i, arr);
        }
        return this;
    };

    ns.eachProperty = function (obj, callback) {
        for (var item in obj) {
            if (obj.hasOwnProperty(item)) {
                callback(obj[item], item, obj);
            }
        }
        return this;
    };

    ns.trimRe = (new RegExp()).compile(/^\s+|\s+$/g);
    ns.trim = function (str) {
        var paramsType = typeof str;
        if (paramsType !== "string") {
            ns.error("Argument must be string but" + paramsType + " passed");
        }
        return str.trim instanceof Function ?
            str.trim() :
            str.replace(ns.trimRe, "");
    };

    x.stripSpaces = function (str) {
        return str.split(" ").join("");
    };

    /**
     * Iterates object or array with callback
     * @param  {Object}            array or object for iterate
     * @param  {Function}          callback fired on each item
     * @returns {Object}           context object
     */
    ns.each = ns.forEach = function (smth, callback) {
        var targetFunction = (ns.isArray(smth)) ?
            ns.eachListItem : ns.eachProperty;

        targetFunction(smth, callback);
        return this;
    };

    ns.isFunc = function() {
        return Array.prototype.every.call(
            arguments,
            function(x) { return x instanceof Function;}
        );
    };

    // нативный bind очень медленный в chrome браузерах
    // http://jsperf.com/nativebind-vs-custombind
    ns.bind = function (func, context) {
        return function () {
            return func.apply(context, arguments);
        };
    };

    ns.beget = function (baseObj, newObjectProperties) {
        var obj = {},
            typeBase = typeof baseObj,
            typeProperties = typeof newObjectProperties;

        if (typeBase !== "object") {
            ns.error("Only object allowed to be prototype and tried to work with " + typeBase);
        }
        if (typeProperties !== "undefined" && typeProperties !== "object") {
            ns.error("Only object allowed to be list of properties instead " + typeProperties);
        }
        if (typeof Object.create !== "function") {
            ns.error("Object.create function is required");
        }

        x.each(newObjectProperties, function (value, key) {
            obj[key]= {writable:true, enumerable: true, "value": value};
        });

        return Object.create(baseObj, obj);
    };

    /**
     * Creates interface description
     * @param {string} name Name of interface
     * @param {array} methods List of methods descibed as strings
     * @constructor
     */
    ns.Interface = function (name, methods) {
        var self = this;
        if (arguments.length !== 2) {
            ns.error (
                "Interface constructor called with "+ arguments.length +
                "parameters, but expected exactly 2");
        }

        this.methods = [];
        this.name = name;

        x.each(methods, function (method) {
            if (typeof method !== "string") {
                ns.error("Interface constructor expects method "+
                    "names to be passed in as a string");
            }

            self.methods.push(method);
        });
    };

    /**
     * Checks implementation of interface of interfaces for particular object
     * @param {object} object    Object for check implementation
     * @param {array} interfaces    Array of interfaces for check
     * @returns {boolean}
     */
    ns.Interface.ensureImplements = function (object, interfaces) {

        if (arguments.length !== 2) {
            ns.error (
                "Interface constructor called with "+ arguments.length +
                "parameters, but expected at least 2");
        }

        x.each(interfaces, function (interfaceItem) {
            if (interfaceItem.constructor !== ns.Interface) {
                ns.error("Function Interface.ensureImplements expects arguments two and above to be instances of Interface.");
            }

            x.each(interfaceItem.methods, function (method) {
                if (!object[method] || typeof object[method] !== "function") {
                    ns.error("Function Interface.ensureImplements: object "+
                        "does not implement the " + interfaceItem.name +
                        " interface. Method " + method + " was not found.");
                }
            });
        });
    };

    /**
     * Extends function by another function
     * @param {function} subClass   Function for extend
     * @param {function} superClass Function is used as superClass
     */
    ns.extend = function (subClass, superClass) {
        var F = function () {};
        subClass.superclass = F.prototype = superClass.prototype;
        subClass.prototype = new F();
        subClass.prototype.constructor = subClass;

        if(superClass.prototype.constructor === Object.prototype.constructor) {
            superClass.prototype.constructor = superClass;
        }
    };

    ns.getJPathValue = function(smth, key) {
        var c = smth,
            keys = key.split("."),
            i = 0;

        while(c[keys[i]]) {
            c = c[keys[i++]];
        }

        return c;
    };

    ns.create = function (obj) {

        var F = function () {};
        F.prototype = obj;
        return new F();
    };

    if (isDebug) {
        ns.ViewItem = new x.Interface("View", ["getCustomRender", "ruleFunction", "let", "get"]);
    }

    ns.View = function (view) {
        this.templates = view && view.templates ?
            x.beget(view.templates) :
            {};
    };

    ns.View.prototype = {
        templates: {},

        re: {
            "parse" : /\[%\s([^%]+)\s%\]/g,
            "rule": /\s*:\s*/
        },

        getCustomRender: function () {
            var def = arguments[0] !== "undefined" ?
                arguments[0].split(this.re.rule) :
                null;

            if (def && def.length === 2) {
                return this.parseRules[def[0]] && this.parseRules[def[0]].call(this, def[1]);
            }
        },

        parseRules: {
            l10n: function(key){
                return function (d) {
                    if (isDebug && !d.l10n(key)) {
                        ns.console.error("There is no translation for " + key);
                    }
                    return d.l10n ? d.l10n(key) : key;
                };
            },

            jpath: function(key) {
                return function (d) {
                    return x.getJPathValue(d, key) || "";
                };
            },

            view: function(key) {
                var self = this;

                return function (d) {
                    return self.get(key, d);
                };
            }
        },

        ruleFunction: function (paramName, defaults) {
            return this.getCustomRender(paramName) || function (d) {

                var res = d[paramName] || defaults[paramName];

                if (isDebug && !res) {
                    x.console.log(
                        "Undefined variable" + paramName
                    );
                }
                return res || "";
            };
        },

        "let": function (name, template, defaults) {

            var inTemplates = name in this.templates;

            var result = [],
                superTmpl = name in this.templates ? this.templates[name] : null,
                self = this,
                i = 0;

            result = this.templates[name] = superTmpl ? x.create(superTmpl) : [];
            if (inTemplates) {
                result._super = superTmpl;
            }
            template.replace(this.re.parse, function(matchedExpression, matchedKey, matchedIndex) {
                result.push(
                    template.substr(i, matchedIndex - i),
                    self.ruleFunction(matchedKey, defaults)
                );
                i = matchedIndex + matchedExpression.length;

            });
            if (i < template.length) {
                result.push(template.substr(i));
            }

            return this;
        },
        "get": function (name, data) {
            var template = this.templates[name],
                res = ns.isArray(template) ?
                    x.map(template, function (item) {
                        return typeof item === "string" ?
                            item:
                            item(data);
                    }).join(""):
                    template;
            return res;
        }
    };

    ns.views = new ns.View();
    ns.getObject = function (obj) {
        obj.beget = function (values) {
            return x.beget(this, values);
        };

        return x.beget(obj);
    };

    ns.URLre = /^https?:\/\/\S+/i;

    ns.isURL = function (str) {
        if (typeof str !== "string") {
            ns.error("isURL expects string parameter instead " + typeof str);
        }

        return ns.URLre.test(str);
    };

    var intComponent = new ns.Interface("intComponent",
        ["init", "data"]
    );

    ns.ComponentBase = {
        data: function (name) {
            var el = this.getNodeElement();

            return el ? ns.data(el, name) : undefined;
        },
        getNodeElement: function () {
            var x1 = ns.$("#" + this.id);
            return x1[0];
        },
        setId: function (id) {
            this.id = id;
        }
    };

    ns.Component = (function () {
        var components = [],
            componentsIndex = {},
            appSelector = "*[data-xapp]";
        return {
            extend: function (componentDescription) {
                var i = components.length,
                    app = x.beget(ns.ComponentBase, componentDescription);

                ns.Interface.ensureImplements(app, [intComponent]);

                if (!app.id) {
                    ns.error("extend method expects id field in description object");
                }

                components.push(app);
                // fill index
                componentsIndex[app.id] = i;
                return components[i];
            },

            // инициализация по структуре html
            "initByHTML": function (context) {
                var contextNode = context || document,
                    self = this,
                    apps = ns.$(appSelector, contextNode);

                x.each(apps, function (element) {
                    var names = ns.data(element, "xapp");
                    x.each(names.split(" "), function (appName) {
                        self.initById(appName,
                            ns.getElementId(element)
                        );
                    });
                });
            },

            "initById": function (name, elementId) {
                var app = name in componentsIndex ?
                        components[componentsIndex[name]] : null;

                if (app) {
                    if (typeof elementId !== "undefined") {
                        app.setId(elementId);
                    }
                    app.init();
                }
            }
        };

    })();

    ns.$ = function (expr) {
        var contextNode = arguments[1] || global.document || null;

        return contextNode && ns.isFunc(contextNode.querySelectorAll) ?
            contextNode.querySelectorAll(expr): [];
    };

    ns.data = function (node, dataName) {
        if (!(node instanceof Element)) {
            ns.error("nodeElement expected as first argument instead of " + typeof node);
        }
        return node.getAttribute("data-" + dataName);
    };

    ns.getElementId = function (node) {
        if (!(node instanceof Element)) {
            ns.error("nodeElement expected as first argument instead of " + typeof node);
        }

        var id = node.getAttribute("id");
        if (!id) {
            id = "_" + ns.generateId();
            node.setAttribute("id", id);
        }

        return id;
    };

}(xglobal, "x"));
<commit_msg>check for NodeList traversing<commit_after>var xglobal = typeof global !== "undefined" ? global : this;

(function (global, name) {
    "use strict";

    var ns = global[name] = function (smth) {},
        isDebug = true;

    ns.ns = function (self, namespace, callbackOnNs) {

        if (!self[namespace]) {
            self[namespace] = {};
        }

        if (typeof callbackOnNs !== "undefined") {
            callbackOnNs.call(self[namespace]);
        }

        return this;
    };

    ns.getEmptyString = function () {return "";};

    /**
     * Formats string with pattern as first argument and values as other ones.
     * E.g.: ns.stringf("%s %s", "hello", "world") -> "hello world"
     * @return {String} formated string
     */
    ns.stringf = function () {

        var pattern = arguments[0],
            args = Array.prototype.slice.call(arguments, 1);

        return pattern.replace(/%s/g,
            function(){ return args.shift()||""; });

    };

    /**
     * Generates random number
     * @return {String} random number
     */
    ns.generateId = function () {
        return String(Math.random()).substr(2);
    };

    ns.map = function (arr, callback) {
        if (ns.isArray(arr) && callback instanceof Function) {
            return arr.map(callback);
        }
    };

    ns.console = {
        slog: function (pattern) {
            this.log( ns.stringf.apply(this, arguments) );
        },

        log: function (smth) {
            if (typeof debug !== "undefined") {
                debug(smth);
            } else if (global.console && global.console.log) {
                global.console.log(smth);
            }
        },

        error: function (txt) {
            throw new Error(txt);
        },

        dir: function (smth) {
            this.log(JSON.stringify(smth));
        }
    };
    ns.log = ns.console.log;
    ns.error = ns.console.error;

    var filterDegradation = function (arr, callback) {
        var res = [];

        x.each(arr, function (item, i) {
            if (callback(item, i, this)) {
                res.push(item);
            }
        });

        return res;
    };

    ns.filter = function (arr, callback) {
        if (!ns.isArray(arr)) {
            ns.error(
                "first argument is expected to be an array instead of " + typeof arr
            );
        }
        if (!ns.isFunc(callback)) {
            ns.error(
                "second argument is expected to be a function instead of " + typeof callback
            );
        }

        if (!arr.filter) {
            ns.error(
                "filter function is not implemented by default"
            );
        }

        return arr.filter ?
            arr.filter(callback) : filterDegradation(callback);

    };

    ns.isArray = function (item) {
        return (item instanceof Array);
    };

    ns.isNodeList = function (item) {
        return item instanceof NodeList;
    };

    ns.isObject = function (item) {
        return (typeof item === "object");
    };

    ns.eachListItem = function (arr, callback) {
        for (var i = 0, l = arr.length; i < l; i++) {
            callback(arr[i], i, arr);
        }
        return this;
    };

    ns.eachProperty = function (obj, callback) {
        for (var item in obj) {
            if (obj.hasOwnProperty(item)) {
                callback(obj[item], item, obj);
            }
        }
        return this;
    };

    ns.trimRe = (new RegExp()).compile(/^\s+|\s+$/g);
    ns.trim = function (str) {
        var paramsType = typeof str;
        if (paramsType !== "string") {
            ns.error("Argument must be string but" + paramsType + " passed");
        }
        return str.trim instanceof Function ?
            str.trim() :
            str.replace(ns.trimRe, "");
    };

    x.stripSpaces = function (str) {
        return str.split(" ").join("");
    };

    /**
     * Iterates object or array with callback
     * @param  {Object}            array or object for iterate
     * @param  {Function}          callback fired on each item
     * @returns {Object}           context object
     */
    ns.each = ns.forEach = function (smth, callback) {
        var targetFunction = (ns.isArray(smth) || ns.isNodeList(smth)) ?
            ns.eachListItem : ns.eachProperty;

        targetFunction(smth, callback);
        return this;
    };

    ns.isFunc = function() {
        return Array.prototype.every.call(
            arguments,
            function(x) { return x instanceof Function;}
        );
    };

    // нативный bind очень медленный в chrome браузерах
    // http://jsperf.com/nativebind-vs-custombind
    ns.bind = function (func, context) {
        return function () {
            return func.apply(context, arguments);
        };
    };

    ns.beget = function (baseObj, newObjectProperties) {
        var obj = {},
            typeBase = typeof baseObj,
            typeProperties = typeof newObjectProperties;

        if (typeBase !== "object") {
            ns.error("Only object allowed to be prototype and tried to work with " + typeBase);
        }
        if (typeProperties !== "undefined" && typeProperties !== "object") {
            ns.error("Only object allowed to be list of properties instead " + typeProperties);
        }
        if (typeof Object.create !== "function") {
            ns.error("Object.create function is required");
        }

        x.each(newObjectProperties, function (value, key) {
            obj[key]= {writable:true, enumerable: true, "value": value};
        });

        return Object.create(baseObj, obj);
    };

    /**
     * Creates interface description
     * @param {string} name Name of interface
     * @param {array} methods List of methods descibed as strings
     * @constructor
     */
    ns.Interface = function (name, methods) {
        var self = this;
        if (arguments.length !== 2) {
            ns.error (
                "Interface constructor called with "+ arguments.length +
                "parameters, but expected exactly 2");
        }

        this.methods = [];
        this.name = name;

        x.each(methods, function (method) {
            if (typeof method !== "string") {
                ns.error("Interface constructor expects method "+
                    "names to be passed in as a string");
            }

            self.methods.push(method);
        });
    };

    /**
     * Checks implementation of interface of interfaces for particular object
     * @param {object} object    Object for check implementation
     * @param {array} interfaces    Array of interfaces for check
     * @returns {boolean}
     */
    ns.Interface.ensureImplements = function (object, interfaces) {

        if (arguments.length !== 2) {
            ns.error (
                "Interface constructor called with "+ arguments.length +
                "parameters, but expected at least 2");
        }

        x.each(interfaces, function (interfaceItem) {
            if (interfaceItem.constructor !== ns.Interface) {
                ns.error("Function Interface.ensureImplements expects arguments two and above to be instances of Interface.");
            }

            x.each(interfaceItem.methods, function (method) {
                if (!object[method] || typeof object[method] !== "function") {
                    ns.error("Function Interface.ensureImplements: object "+
                        "does not implement the " + interfaceItem.name +
                        " interface. Method " + method + " was not found.");
                }
            });
        });
    };

    /**
     * Extends function by another function
     * @param {function} subClass   Function for extend
     * @param {function} superClass Function is used as superClass
     */
    ns.extend = function (subClass, superClass) {
        var F = function () {};
        subClass.superclass = F.prototype = superClass.prototype;
        subClass.prototype = new F();
        subClass.prototype.constructor = subClass;

        if(superClass.prototype.constructor === Object.prototype.constructor) {
            superClass.prototype.constructor = superClass;
        }
    };

    ns.getJPathValue = function(smth, key) {
        var c = smth,
            keys = key.split("."),
            i = 0;

        while(c[keys[i]]) {
            c = c[keys[i++]];
        }

        return c;
    };

    ns.create = function (obj) {

        var F = function () {};
        F.prototype = obj;
        return new F();
    };

    if (isDebug) {
        ns.ViewItem = new x.Interface("View", ["getCustomRender", "ruleFunction", "let", "get"]);
    }

    ns.View = function (view) {
        this.templates = view && view.templates ?
            x.beget(view.templates) :
            {};
    };

    ns.View.prototype = {
        templates: {},

        re: {
            "parse" : /\[%\s([^%]+)\s%\]/g,
            "rule": /\s*:\s*/
        },

        getCustomRender: function () {
            var def = arguments[0] !== "undefined" ?
                arguments[0].split(this.re.rule) :
                null;

            if (def && def.length === 2) {
                return this.parseRules[def[0]] && this.parseRules[def[0]].call(this, def[1]);
            }
        },

        parseRules: {
            l10n: function(key){
                return function (d) {
                    if (isDebug && !d.l10n(key)) {
                        ns.console.error("There is no translation for " + key);
                    }
                    return d.l10n ? d.l10n(key) : key;
                };
            },

            jpath: function(key) {
                return function (d) {
                    return x.getJPathValue(d, key) || "";
                };
            },

            view: function(key) {
                var self = this;

                return function (d) {
                    return self.get(key, d);
                };
            }
        },

        ruleFunction: function (paramName, defaults) {
            return this.getCustomRender(paramName) || function (d) {

                var res = d[paramName] || defaults[paramName];

                if (isDebug && !res) {
                    x.console.log(
                        "Undefined variable" + paramName
                    );
                }
                return res || "";
            };
        },

        "let": function (name, template, defaults) {

            var inTemplates = name in this.templates;

            var result = [],
                superTmpl = name in this.templates ? this.templates[name] : null,
                self = this,
                i = 0;

            result = this.templates[name] = superTmpl ? x.create(superTmpl) : [];
            if (inTemplates) {
                result._super = superTmpl;
            }
            template.replace(this.re.parse, function(matchedExpression, matchedKey, matchedIndex) {
                result.push(
                    template.substr(i, matchedIndex - i),
                    self.ruleFunction(matchedKey, defaults)
                );
                i = matchedIndex + matchedExpression.length;

            });
            if (i < template.length) {
                result.push(template.substr(i));
            }

            return this;
        },
        "get": function (name, data) {
            var template = this.templates[name],
                res = ns.isArray(template) ?
                    x.map(template, function (item) {
                        return typeof item === "string" ?
                            item:
                            item(data);
                    }).join(""):
                    template;
            return res;
        }
    };

    ns.views = new ns.View();
    ns.getObject = function (obj) {
        obj.beget = function (values) {
            return x.beget(this, values);
        };

        return x.beget(obj);
    };

    ns.URLre = /^https?:\/\/\S+/i;

    ns.isURL = function (str) {
        if (typeof str !== "string") {
            ns.error("isURL expects string parameter instead " + typeof str);
        }

        return ns.URLre.test(str);
    };

    var intComponent = new ns.Interface("intComponent",
        ["init", "data"]
    );

    ns.ComponentBase = {
        data: function (name) {
            var el = this.getNodeElement();

            return el ? ns.data(el, name) : undefined;
        },
        getNodeElement: function () {
            var x1 = ns.$("#" + this.id);
            return x1[0];
        },
        setId: function (id) {
            this.id = id;
        }
    };

    ns.Component = (function () {
        var components = [],
            componentsIndex = {},
            appSelector = "*[data-xapp]";
        return {
            extend: function (componentDescription) {
                var i = components.length,
                    app = x.beget(ns.ComponentBase, componentDescription);

                ns.Interface.ensureImplements(app, [intComponent]);

                if (!app.id) {
                    ns.error("extend method expects id field in description object");
                }

                components.push(app);
                // fill index
                componentsIndex[app.id] = i;
                return components[i];
            },

            // инициализация по структуре html
            "initByHTML": function (context) {
                var contextNode = context || document,
                    self = this,
                    apps = ns.$(appSelector, contextNode);

                x.each(apps, function (element) {
                    var names = ns.data(element, "xapp");
                    x.each(names.split(" "), function (appName) {
                        self.initById(appName,
                            ns.getElementId(element)
                        );
                    });
                });
            },

            "initById": function (name, elementId) {
                var app = name in componentsIndex ?
                        components[componentsIndex[name]] : null;

                if (app) {
                    if (typeof elementId !== "undefined") {
                        app.setId(elementId);
                    }
                    app.init();
                }
            }
        };

    })();

    ns.$ = function (expr) {
        var contextNode = arguments[1] || global.document || null;

        return contextNode && ns.isFunc(contextNode.querySelectorAll) ?
            contextNode.querySelectorAll(expr): [];
    };

    ns.data = function (node, dataName) {
        if (!(node instanceof Element)) {
            ns.error("nodeElement expected as first argument instead of " + typeof node);
        }
        return node.getAttribute("data-" + dataName);
    };

    ns.getElementId = function (node) {
        if (!(node instanceof Element)) {
            ns.error("nodeElement expected as first argument instead of " + typeof node);
        }

        var id = node.getAttribute("id");
        if (!id) {
            id = "_" + ns.generateId();
            node.setAttribute("id", id);
        }

        return id;
    };

}(xglobal, "x"));
<|endoftext|>


<commit_before>var React = require('react-native');
var ClassStandbyView = require('./classStandbyView.js');
require('./../../utils/userAgent');
var io =require('socket.io-client/socket.io');

var {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Navigator,
} = React;

class JoinClassView extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      enrolledClasses: ['Quick class','CS101', 'CS201'],
      userId: this.props.route.userId
    }
  }

  selectedClass(cls) {
    console.log(cls);
    //perhaps pass class as part of url to socket
    this.socket = io('localhost:3000', {jsonp: false});

    this.socket.emit('studentConnect');

    this.props.navigator.push({
      component: ClassStandbyView,
      className: cls,
      userId: this.state.userId,
      socket: this.socket,
      sceneConfig: {
        ...Navigator.SceneConfigs.FloatFromBottom,
        gestures: {}
      }
    })
  }

  eachClasses(classes){
    return classes.map((cls, index) => {
      return (
        <View style={styles.buttonsContainer} key={index}>
          <TouchableOpacity onPress={this.selectedClass.bind(this, cls)}style={styles.buttonContainer}>
            <Text>{cls}</Text>
          </TouchableOpacity>
        </View>
      )
    })
  }
  render() {
    return (
      <View style={{flex: 1, backgroundColor: '#ededed'}}>
        <View style={styles.textHeader}>
          <Text style={styles.textSize}>Enrollled Classes</Text>
        </View>
        {this.eachClasses(this.state.enrolledClasses)}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  textHeader: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  textSize: {
    fontSize: 20
  },
  buttonsContainer: {
    padding: 20
  },
  buttonContainer: {
    margin: 20
  },
})
module.exports = JoinClassView;<commit_msg>Pass userId with studentConnection socket emission<commit_after>var React = require('react-native');
var ClassStandbyView = require('./classStandbyView.js');
require('./../../utils/userAgent');
var io =require('socket.io-client/socket.io');

var {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Navigator,
} = React;

class JoinClassView extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      enrolledClasses: ['Quick class','CS101', 'CS201'],
      userId: this.props.route.userId
    }
  }

  selectedClass(cls) {
    console.log(cls);
    //perhaps pass class as part of url to socket
    this.socket = io('localhost:3000', {jsonp: false});

    this.socket.emit('studentConnect', this.state.userId);

    this.props.navigator.push({
      component: ClassStandbyView,
      className: cls,
      userId: this.state.userId,
      socket: this.socket,
      sceneConfig: {
        ...Navigator.SceneConfigs.FloatFromBottom,
        gestures: {}
      }
    })
  }

  eachClasses(classes){
    return classes.map((cls, index) => {
      return (
        <View style={styles.buttonsContainer} key={index}>
          <TouchableOpacity onPress={this.selectedClass.bind(this, cls)}style={styles.buttonContainer}>
            <Text>{cls}</Text>
          </TouchableOpacity>
        </View>
      )
    })
  }
  render() {
    return (
      <View style={{flex: 1, backgroundColor: '#ededed'}}>
        <View style={styles.textHeader}>
          <Text style={styles.textSize}>Enrollled Classes</Text>
        </View>
        {this.eachClasses(this.state.enrolledClasses)}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  textHeader: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  textSize: {
    fontSize: 20
  },
  buttonsContainer: {
    padding: 20
  },
  buttonContainer: {
    margin: 20
  },
})
module.exports = JoinClassView;<|endoftext|>


<commit_before>goog.provide('ol.format.XSD');

goog.require('goog.string');
goog.require('ol.xml');

/**
 * @const
 * @type {string}
 */
ol.format.XSD.NAMESPACE_URI = 'http://www.w3.org/2001/XMLSchema';

/**
 * @param {Node} node Node.
 * @return {boolean|undefined} Boolean.
 */
ol.format.XSD.readBoolean = function(node) {
  var s = ol.xml.getAllTextContent(node, false);
  var m = /^\s*(true|1)|(false|0)\s*$/.exec(s);
  if (m) {
    return goog.isDef(m[1]) || false;
  } else {
    return undefined;
  }
};

/**
 * @param {Node} node Node.
 * @return {number|undefined} DateTime.
 */
ol.format.XSD.readDateTime = function(node) {
  var s = ol.xml.getAllTextContent(node, false);
  var re =
      /^\s*(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|(?:([+\-])(\d{2})(?::(\d{2}))?))\s*$/;
  var m = re.exec(s);
  if (m) {
    var year = parseInt(m[1], 10);
    var month = parseInt(m[2], 10) - 1;
    var day = parseInt(m[3], 10);
    var hour = parseInt(m[4], 10);
    var minute = parseInt(m[5], 10);
    var second = parseInt(m[6], 10);
    var dateTime = Date.UTC(year, month, day, hour, minute, second) / 1000;
    if (m[7] != 'Z') {
      var sign = m[8] == '-' ? -1 : 1;
      dateTime += sign * 60 * parseInt(m[9], 10);
      if (goog.isDef(m[10])) {
        dateTime += sign * 60 * 60 * parseInt(m[10], 10);
      }
    }
    return dateTime;
  } else {
    return undefined;
  }
};

/**
 * @param {Node} node Node.
 * @return {number|undefined} Decimal.
 */
ol.format.XSD.readDecimal = function(node) {
  // FIXME check spec
  var s = ol.xml.getAllTextContent(node, false);
  var m = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(s);
  if (m) {
    return parseFloat(m[1]);
  } else {
    return undefined;
  }
};

/**
 * @param {Node} node Node.
 * @return {number|undefined} Decimal.
 */
ol.format.XSD.readNonNegativeInteger = function(node) {
  var s = ol.xml.getAllTextContent(node, false);
  var m = /^\s*(\d+)\s*$/.exec(s);
  if (m) {
    return parseInt(m[1], 10);
  } else {
    return undefined;
  }
};

/**
 * @param {Node} node Node.
 * @return {string|undefined} String.
 */
ol.format.XSD.readString = function(node) {
  var s = ol.xml.getAllTextContent(node, false);
  return goog.string.trim(s);
};
<commit_msg>Better ol.format.XSD.* documentation<commit_after>goog.provide('ol.format.XSD');

goog.require('goog.string');
goog.require('ol.xml');

/**
 * @const
 * @type {string}
 */
ol.format.XSD.NAMESPACE_URI = 'http://www.w3.org/2001/XMLSchema';

/**
 * @param {Node} node Node.
 * @return {boolean|undefined} Boolean.
 */
ol.format.XSD.readBoolean = function(node) {
  var s = ol.xml.getAllTextContent(node, false);
  var m = /^\s*(true|1)|(false|0)\s*$/.exec(s);
  if (m) {
    return goog.isDef(m[1]) || false;
  } else {
    return undefined;
  }
};

/**
 * @param {Node} node Node.
 * @return {number|undefined} DateTime in seconds.
 */
ol.format.XSD.readDateTime = function(node) {
  var s = ol.xml.getAllTextContent(node, false);
  var re =
      /^\s*(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|(?:([+\-])(\d{2})(?::(\d{2}))?))\s*$/;
  var m = re.exec(s);
  if (m) {
    var year = parseInt(m[1], 10);
    var month = parseInt(m[2], 10) - 1;
    var day = parseInt(m[3], 10);
    var hour = parseInt(m[4], 10);
    var minute = parseInt(m[5], 10);
    var second = parseInt(m[6], 10);
    var dateTime = Date.UTC(year, month, day, hour, minute, second) / 1000;
    if (m[7] != 'Z') {
      var sign = m[8] == '-' ? -1 : 1;
      dateTime += sign * 60 * parseInt(m[9], 10);
      if (goog.isDef(m[10])) {
        dateTime += sign * 60 * 60 * parseInt(m[10], 10);
      }
    }
    return dateTime;
  } else {
    return undefined;
  }
};

/**
 * @param {Node} node Node.
 * @return {number|undefined} Decimal.
 */
ol.format.XSD.readDecimal = function(node) {
  // FIXME check spec
  var s = ol.xml.getAllTextContent(node, false);
  var m = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(s);
  if (m) {
    return parseFloat(m[1]);
  } else {
    return undefined;
  }
};

/**
 * @param {Node} node Node.
 * @return {number|undefined} Non negative integer.
 */
ol.format.XSD.readNonNegativeInteger = function(node) {
  var s = ol.xml.getAllTextContent(node, false);
  var m = /^\s*(\d+)\s*$/.exec(s);
  if (m) {
    return parseInt(m[1], 10);
  } else {
    return undefined;
  }
};

/**
 * @param {Node} node Node.
 * @return {string|undefined} String.
 */
ol.format.XSD.readString = function(node) {
  var s = ol.xml.getAllTextContent(node, false);
  return goog.string.trim(s);
};
<|endoftext|>


<commit_before>require("ember-data/core");
require('ember-data/system/adapter');

require('ember-data/serializers/rest_serializer');

/**
  @module ember-data
*/

var get = Ember.get, set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;

/**
  The REST adapter allows your store to communicate with an HTTP server by
  transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
  should use the REST adapter.

  This adapter is designed around the idea that the JSON exchanged with
  the server should be conventional.

  ## JSON Structure

  The REST adapter expects the JSON returned from your server to follow
  these conventions.

  ### Object Root

  The JSON payload should be an object that contains the record inside a
  root property. For example, in response to a `GET` request for
  `/posts/1`, the JSON should look like this:

  ```js
  {
    "post": {
      title: "I'm Running to Reform the W3C's Tag",
      author: "Yehuda Katz"
    }
  }
  ```

  ### Conventional Names

  Attribute names in your JSON payload should be the underscored versions of
  the attributes in your Ember.js models.

  For example, if you have a `Person` model:

  ```js
  App.Person = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    occupation: DS.attr('string')
  });
  ```

  The JSON returned should look like this:

  ```js
  {
    "person": {
      "first_name": "Barack",
      "last_name": "Obama",
      "occupation": "President"
    }
  }
  ```

  ## Customization

  ### Endpoint path customization

  Endpoint paths can be prefixed with a `namespace` by setting the namespace
  property on the adapter:

  ```js
  DS.RESTAdapter.reopen({
    namespace: 'api/1'
  });
  ```
  Requests for `App.Person` would now target `/api/1/people/1`.

  ### Host customization

  An adapter can target other hosts by setting the `host` property.

  ```js
  DS.RESTAdapter.reopen({
    host: 'https://api.example.com'
  });
  ```

  ### Headers customization

  Some APIs require HTTP headers, eg to provide an API key. An array of
  headers can be added to the adapter which are passed with every request:

  ```js
  DS.RESTAdapter.reopen({
    headers: {
      "API_KEY": "secret key",
      "ANOTHER_HEADER": "asdsada"
    }
  });
  ```

  @class RESTAdapter
  @constructor
  @namespace DS
  @extends DS.Adapter
*/
DS.RESTAdapter = DS.Adapter.extend({
  defaultSerializer: '_rest',

  /**
    Called by the store in order to fetch the JSON for a given
    type and ID.

    It makes an Ajax request to a URL computed by `buildURL`, and returns a
    promise for the resulting payload.

    @method find
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {String} id
    @returns Promise
  */
  find: function(store, type, id) {
    return this.ajax(this.buildURL(type.typeKey, id), 'GET');
  },

  /**
    Called by the store in order to fetch a JSON array for all
    of the records for a given type.

    It makes an Ajax request to a URL computed by `buildURL`, and returns a
    promise for the resulting payload.

    @method findAll
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {String} sinceToken
    @returns Promise
  */
  findAll: function(store, type, sinceToken) {
    var query;

    if (sinceToken) {
      query = { since: sinceToken };
    }

    return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
  },

  /**
    Called by the store in order to fetch a JSON array for
    the records that match a particular query.

    The query is a simple JavaScript object that will be passed directly
    to the server as parameters.

    It makes an Ajax request to a URL computed by `buildURL`, and returns a
    promise for the resulting payload.

    @method findQuery
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {Object} query
    @returns Promise
  */
  findQuery: function(store, type, query) {
    return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
  },

  /**
    Called by the store in order to fetch a JSON array for
    the unloaded records in a has-many relationship that were originally
    specified as IDs.

    For example, if the original payload looks like:

    ```js
    {
      "id": 1,
      "title": "Rails is omakase",
      "comments": [ 1, 2, 3 ]
    }
    ```

    The IDs will be passed as a URL-encoded Array of IDs, in this form:

    ```
    ids[]=1&ids[]=2&ids[]=3
    ```

    Many servers, such as Rails and PHP, will automatically convert this
    into an Array for you on the server-side. If you want to encode the
    IDs, differently, just override this (one-line) method.

    It makes an Ajax request to a URL computed by `buildURL`, and returns a
    promise for the resulting payload.

    @method findMany
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {Array<String>} ids
    @returns Promise
  */
  findMany: function(store, type, ids, owner) {
    return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } });
  },

  /**
    Called by the store in order to fetch a JSON array for
    the unloaded records in a has-many relationship that were originally
    specified as a URL (inside of `links`).

    For example, if your original payload looks like this:

    ```js
    {
      "post": {
        "id": 1,
        "title": "Rails is omakase",
        "links": { "comments": "/posts/1/comments" }
      }
    }
    ```

    This method will be called with the parent record and `/posts/1/comments`.

    It will make an Ajax request to the originally specified URL.

    @method findHasMany
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {DS.Model} record
    @param {String} url
    @returns Promise
  */
  findHasMany: function(store, record, url) {
    return this.ajax(url, 'GET');
  },

  /**
    Called by the store when a newly created record is
    `save`d.

    It serializes the record, and `POST`s it to a URL generated by `buildURL`.

    See `serialize` for information on how to customize the serialized form
    of a record.

    @method createRecord
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @see RESTAdapter/serialize
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {DS.Model} record
    @returns Promise
  */
  createRecord: function(store, type, record) {
    var data = {};
    var serializer = store.serializerFor(type.typeKey);

    serializer.serializeIntoHash(data, type, record, { includeId: true });

    return this.ajax(this.buildURL(type.typeKey), "POST", { data: data });
  },

  /**
    Called by the store when an existing record is `save`d.

    It serializes the record, and `POST`s it to a URL generated by `buildURL`.

    See `serialize` for information on how to customize the serialized form
    of a record.

    @method updateRecord
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @see RESTAdapter/serialize
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {DS.Model} record
    @returns Promise
  */
  updateRecord: function(store, type, record) {
    var data = {};
    var serializer = store.serializerFor(type.typeKey);

    serializer.serializeIntoHash(data, type, record);

    var id = get(record, 'id');

    return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data });
  },

  /**
    Called by the store when an deleted record is `save`d.

    It serializes the record, and `POST`s it to a URL generated by `buildURL`.

    @method deleteRecord
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @see RESTAdapter/serialize
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {DS.Model} record
    @returns Promise
  */
  deleteRecord: function(store, type, record) {
    var id = get(record, 'id');

    return this.ajax(this.buildURL(type.typeKey, id), "DELETE");
  },

  /**
    Builds a URL for a given type and optional ID.

    By default, it pluralizes the type's name (for example,
    'post' becomes 'posts' and 'person' becomes 'people').

    If an ID is specified, it adds the ID to the path generated
    for the type, separated by a `/`.

    @method buildURL
    @param {String} type
    @param {String} id
    @returns String
  */
  buildURL: function(type, id) {
    var host = get(this, 'host'),
        namespace = get(this, 'namespace'),
        url = [];

    if (host) { url.push(host); }
    if (namespace) { url.push(namespace); }

    url.push(this.pathForType(type));
    if (id) { url.push(id); }

    url = url.join('/');
    if (!host) { url = '/' + url; }

    return url;
  },

  /**
    Determines the pathname for a given type.

    By default, it pluralizes the type's name (for example,
    'post' becomes 'posts' and 'person' becomes 'people').

    ### Pathname customization

    For example if you have an object LineItem with an
    endpoint of "/line_items/".

    ```js
    DS.RESTAdapter.reopen({
      pathForType: function(type) {
        var decamelized = Ember.String.decamelize(type);
        return Ember.String.pluralize(decamelized);
      };
    });
    ```

    @method pathForType
    @param {String} type
    @returns String
  **/
  pathForType: function(type) {
    return Ember.String.pluralize(type);
  },

  /**
    Takes a URL, an HTTP method and a hash of data, and makes an
    HTTP request.

    When the server responds with a payload, Ember Data will call into `extractSingle`
    or `extractArray` (depending on whether the original query was for one record or
    many records).

    By default, it has the following behavior:

    * It sets the response `dataType` to `"json"`
    * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
      `application/json; charset=utf-8`
    * If the HTTP method is not `"GET"`, it stringifies the data passed in. The
      data is the serialized record in the case of a save.
    * Registers success and failure handlers.

    @method ajax
    @private
    @param  url
    @param  type
    @param  hash
  */
  ajax: function(url, type, hash) {
    var adapter = this;

    return new Ember.RSVP.Promise(function(resolve, reject) {
      hash = hash || {};
      hash.url = url;
      hash.type = type;
      hash.dataType = 'json';
      hash.context = adapter;

      if (hash.data && type !== 'GET') {
        hash.contentType = 'application/json; charset=utf-8';
        hash.data = JSON.stringify(hash.data);
      }

      if (adapter.headers !== undefined) {
        var headers = adapter.headers;
        hash.beforeSend = function (xhr) {
          forEach.call(Ember.keys(headers), function(key) {
            xhr.setRequestHeader(key, headers[key]);
          });
        };
      }

      hash.success = function(json) {
        Ember.run(null, resolve, json);
      };

      hash.error = function(jqXHR, textStatus, errorThrown) {
        if (jqXHR) {
          jqXHR.then = null;
        }

        Ember.run(null, reject, jqXHR);
      };

      Ember.$.ajax(hash);
    });
  }

});
<commit_msg>Fix docs<commit_after>require("ember-data/core");
require('ember-data/system/adapter');

require('ember-data/serializers/rest_serializer');

/**
  @module ember-data
*/

var get = Ember.get, set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;

/**
  The REST adapter allows your store to communicate with an HTTP server by
  transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
  should use the REST adapter.

  This adapter is designed around the idea that the JSON exchanged with
  the server should be conventional.

  ## JSON Structure

  The REST adapter expects the JSON returned from your server to follow
  these conventions.

  ### Object Root

  The JSON payload should be an object that contains the record inside a
  root property. For example, in response to a `GET` request for
  `/posts/1`, the JSON should look like this:

  ```js
  {
    "post": {
      title: "I'm Running to Reform the W3C's Tag",
      author: "Yehuda Katz"
    }
  }
  ```

  ### Conventional Names

  Attribute names in your JSON payload should be the camelcased versions of
  the attributes in your Ember.js models.

  For example, if you have a `Person` model:

  ```js
  App.Person = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    occupation: DS.attr('string')
  });
  ```

  The JSON returned should look like this:

  ```js
  {
    "person": {
      "firstName": "Barack",
      "lastName": "Obama",
      "occupation": "President"
    }
  }
  ```

  ## Customization

  ### Endpoint path customization

  Endpoint paths can be prefixed with a `namespace` by setting the namespace
  property on the adapter:

  ```js
  DS.RESTAdapter.reopen({
    namespace: 'api/1'
  });
  ```
  Requests for `App.Person` would now target `/api/1/people/1`.

  ### Host customization

  An adapter can target other hosts by setting the `host` property.

  ```js
  DS.RESTAdapter.reopen({
    host: 'https://api.example.com'
  });
  ```

  ### Headers customization

  Some APIs require HTTP headers, eg to provide an API key. An array of
  headers can be added to the adapter which are passed with every request:

  ```js
  DS.RESTAdapter.reopen({
    headers: {
      "API_KEY": "secret key",
      "ANOTHER_HEADER": "asdsada"
    }
  });
  ```

  @class RESTAdapter
  @constructor
  @namespace DS
  @extends DS.Adapter
*/
DS.RESTAdapter = DS.Adapter.extend({
  defaultSerializer: '_rest',

  /**
    Called by the store in order to fetch the JSON for a given
    type and ID.

    It makes an Ajax request to a URL computed by `buildURL`, and returns a
    promise for the resulting payload.

    @method find
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {String} id
    @returns Promise
  */
  find: function(store, type, id) {
    return this.ajax(this.buildURL(type.typeKey, id), 'GET');
  },

  /**
    Called by the store in order to fetch a JSON array for all
    of the records for a given type.

    It makes an Ajax request to a URL computed by `buildURL`, and returns a
    promise for the resulting payload.

    @method findAll
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {String} sinceToken
    @returns Promise
  */
  findAll: function(store, type, sinceToken) {
    var query;

    if (sinceToken) {
      query = { since: sinceToken };
    }

    return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
  },

  /**
    Called by the store in order to fetch a JSON array for
    the records that match a particular query.

    The query is a simple JavaScript object that will be passed directly
    to the server as parameters.

    It makes an Ajax request to a URL computed by `buildURL`, and returns a
    promise for the resulting payload.

    @method findQuery
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {Object} query
    @returns Promise
  */
  findQuery: function(store, type, query) {
    return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
  },

  /**
    Called by the store in order to fetch a JSON array for
    the unloaded records in a has-many relationship that were originally
    specified as IDs.

    For example, if the original payload looks like:

    ```js
    {
      "id": 1,
      "title": "Rails is omakase",
      "comments": [ 1, 2, 3 ]
    }
    ```

    The IDs will be passed as a URL-encoded Array of IDs, in this form:

    ```
    ids[]=1&ids[]=2&ids[]=3
    ```

    Many servers, such as Rails and PHP, will automatically convert this
    into an Array for you on the server-side. If you want to encode the
    IDs, differently, just override this (one-line) method.

    It makes an Ajax request to a URL computed by `buildURL`, and returns a
    promise for the resulting payload.

    @method findMany
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {Array<String>} ids
    @returns Promise
  */
  findMany: function(store, type, ids, owner) {
    return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } });
  },

  /**
    Called by the store in order to fetch a JSON array for
    the unloaded records in a has-many relationship that were originally
    specified as a URL (inside of `links`).

    For example, if your original payload looks like this:

    ```js
    {
      "post": {
        "id": 1,
        "title": "Rails is omakase",
        "links": { "comments": "/posts/1/comments" }
      }
    }
    ```

    This method will be called with the parent record and `/posts/1/comments`.

    It will make an Ajax request to the originally specified URL.

    @method findHasMany
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @param {DS.Store} store
    @param {DS.Model} record
    @param {String} url
    @returns Promise
  */
  findHasMany: function(store, record, url) {
    return this.ajax(url, 'GET');
  },

  /**
    Called by the store when a newly created record is
    `save`d.

    It serializes the record, and `POST`s it to a URL generated by `buildURL`.

    See `serialize` for information on how to customize the serialized form
    of a record.

    @method createRecord
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @see RESTAdapter/serialize
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {DS.Model} record
    @returns Promise
  */
  createRecord: function(store, type, record) {
    var data = {};
    var serializer = store.serializerFor(type.typeKey);

    serializer.serializeIntoHash(data, type, record, { includeId: true });

    return this.ajax(this.buildURL(type.typeKey), "POST", { data: data });
  },

  /**
    Called by the store when an existing record is `save`d.

    It serializes the record, and `POST`s it to a URL generated by `buildURL`.

    See `serialize` for information on how to customize the serialized form
    of a record.

    @method updateRecord
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @see RESTAdapter/serialize
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {DS.Model} record
    @returns Promise
  */
  updateRecord: function(store, type, record) {
    var data = {};
    var serializer = store.serializerFor(type.typeKey);

    serializer.serializeIntoHash(data, type, record);

    var id = get(record, 'id');

    return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data });
  },

  /**
    Called by the store when an deleted record is `save`d.

    It serializes the record, and `POST`s it to a URL generated by `buildURL`.

    @method deleteRecord
    @see RESTAdapter/buildURL
    @see RESTAdapter/ajax
    @see RESTAdapter/serialize
    @param {DS.Store} store
    @param {subclass of DS.Model} type
    @param {DS.Model} record
    @returns Promise
  */
  deleteRecord: function(store, type, record) {
    var id = get(record, 'id');

    return this.ajax(this.buildURL(type.typeKey, id), "DELETE");
  },

  /**
    Builds a URL for a given type and optional ID.

    By default, it pluralizes the type's name (for example,
    'post' becomes 'posts' and 'person' becomes 'people').

    If an ID is specified, it adds the ID to the path generated
    for the type, separated by a `/`.

    @method buildURL
    @param {String} type
    @param {String} id
    @returns String
  */
  buildURL: function(type, id) {
    var host = get(this, 'host'),
        namespace = get(this, 'namespace'),
        url = [];

    if (host) { url.push(host); }
    if (namespace) { url.push(namespace); }

    url.push(this.pathForType(type));
    if (id) { url.push(id); }

    url = url.join('/');
    if (!host) { url = '/' + url; }

    return url;
  },

  /**
    Determines the pathname for a given type.

    By default, it pluralizes the type's name (for example,
    'post' becomes 'posts' and 'person' becomes 'people').

    ### Pathname customization

    For example if you have an object LineItem with an
    endpoint of "/line_items/".

    ```js
    DS.RESTAdapter.reopen({
      pathForType: function(type) {
        var decamelized = Ember.String.decamelize(type);
        return Ember.String.pluralize(decamelized);
      };
    });
    ```

    @method pathForType
    @param {String} type
    @returns String
  **/
  pathForType: function(type) {
    return Ember.String.pluralize(type);
  },

  /**
    Takes a URL, an HTTP method and a hash of data, and makes an
    HTTP request.

    When the server responds with a payload, Ember Data will call into `extractSingle`
    or `extractArray` (depending on whether the original query was for one record or
    many records).

    By default, it has the following behavior:

    * It sets the response `dataType` to `"json"`
    * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
      `application/json; charset=utf-8`
    * If the HTTP method is not `"GET"`, it stringifies the data passed in. The
      data is the serialized record in the case of a save.
    * Registers success and failure handlers.

    @method ajax
    @private
    @param  url
    @param  type
    @param  hash
  */
  ajax: function(url, type, hash) {
    var adapter = this;

    return new Ember.RSVP.Promise(function(resolve, reject) {
      hash = hash || {};
      hash.url = url;
      hash.type = type;
      hash.dataType = 'json';
      hash.context = adapter;

      if (hash.data && type !== 'GET') {
        hash.contentType = 'application/json; charset=utf-8';
        hash.data = JSON.stringify(hash.data);
      }

      if (adapter.headers !== undefined) {
        var headers = adapter.headers;
        hash.beforeSend = function (xhr) {
          forEach.call(Ember.keys(headers), function(key) {
            xhr.setRequestHeader(key, headers[key]);
          });
        };
      }

      hash.success = function(json) {
        Ember.run(null, resolve, json);
      };

      hash.error = function(jqXHR, textStatus, errorThrown) {
        if (jqXHR) {
          jqXHR.then = null;
        }

        Ember.run(null, reject, jqXHR);
      };

      Ember.$.ajax(hash);
    });
  }

});
<|endoftext|>


<commit_before>/** internal, section: Plugins
 *  Renderers.html(NDoc) -> Void
 *
 *  Registers HTML renderer as `html`.
 *
 *
 *  ##### Example
 *
 *      NDoc.render('html', ast, options, function (err) {
 *        // ...
 *      });
 *
 *
 *  ##### Options
 *
 *  - **output** (String): Directory where to output rendered documentation.
 *  - **title** (String): Page title template. You can use `{package.*}`
 *    variables here.
 *    Default: `'{package.name} {package.version} API documentation'`
 *  - **index** (String): Intro text.
 *  - **github** (String): URL to a project on GitHub. If given, a nice ribbon
 *    with link to given URL will be added. You can use `{package.*}`
 *    variables here.
 *    Default: `Null`
 *  - **brokenLinks** (show|hide|throw): What to do if broken link occurred.
 *    Default: `'show'`
 **/

'use strict';

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

// 3rd-party
var _       = require('lodash');
var FsTools = require('fs-tools');
var Jade    = require('jade');
var marked  = require('marked');
var hljs    = require('highlight.js');

// internal
var assets    = require('./html/assets');
var template  = require('../../common').template;

// Markdown highlighter callback function
var marked_highlight = function (code, lang) {
  if (lang) {
    return hljs.highlight(lang, code).value;
  } else {
    return hljs.highlightAuto(code).value;
  }
};

////////////////////////////////////////////////////////////////////////////////

function render_html(ndoc, options, callback) {
  var file, str, fn, list, id, obj;

  // prepare rendering function
  // TODO: store it for further reuse, and get rid of jade dependency?
  file = path.join(__dirname, 'html', 'templates', 'layout.jade');
  str = fs.readFileSync(file, 'utf8');
  fn = Jade.compile(str, {
    filename: file,
    pretty: false
  });

  options.github = template(options.github || '', {package: options.package});

  // it's illegal to have slashes in HTML elements ids.
  // replace them with dashes
  list = ndoc.list;

  for (id in list) {
    if (list.hasOwnProperty(id)) {
      obj = list[id];
      // path should be HTML valid id
      obj.path = obj.path.replace(/\//g, '-');
    }
  }

  // render link
  // N.B. logic is way tricky to move to templates.
  // beside, this function is used as parameter in some Array#map() operations
  function link(obj, short, classes) {
    if (typeof obj === 'string') {
      obj = list[obj] || {id: obj};
    }
    // broken link. `options.brokenLinks` define action
    if (!obj.path) {
      return obj.id;
      /*if (options.brokenLinks === 'throw') {
        throw 'Link is broken: ' + obj.id;
      }
      return options.brokenLinks === 'show' ? '[[' + obj.id + ']]' : obj.id;*/
    }
    //
    var r = '';
    r += typeof short === 'string' ? short : short ? obj.name : obj.id;
    r += '';
    return r;
  }

  // convert markdown to HTML
  function markdown(text, nohl) {
    var r, codes;

    marked.setOptions({
      gfm: true,
      pedantic: false,
      sanitize: false,
      highlight: nohl ? null : marked_highlight
    });

    r = marked(text);

    // FIXME
    // desugar [[foo#bar]] tokens into local links
    // N.B. in order to not apply conversion in  blocks,
    // we first store replace code blocks with nonces
    codes = {};
    r = r.replace(/([\s\S]*?<\/code>)/g, function (all, def) {
      var nonce = Math.random().toString().substring(2);
      codes[nonce] = def;
      return '@-=@=-@' + nonce + '@-=@=-@';
    });
    // convert [[link]] to links
    r = r.replace(/\[\[([\s\S]+?)\]\]/g, function (all, def) {
      def = def.split(/\s+/);
      id = def.shift();
      // invalid references don't produce links
      if (!list[id]) {
        if (options.brokenLinks === 'throw') {
          throw 'Link is broken: ' + all + '\n' + r;
        }
        return options.brokenLinks === 'show' ? all : id;
      }

      var obj = _.extend({name: def.join(' ') || id}, list[id]);
      return link(obj, true, ['link-short']);
    });
    // restore code blocks, given previously stored nonces
    r = r.replace(/@-=@=-@(\d+)@-=@=-@/g, function (all, nonce) {
      return codes[nonce];
    });
    //
    return r;
  }

  // given signature object, recompose its textual representation
  function signature(obj, sig) {
    if (typeof obj === 'string') {
      obj = list[obj];
    }
    var r = obj.id;
    if (sig.args) {
      r += '(';
      sig.args.forEach(function (arg, idx) {
        var skip_first, a, value;
        // skip the first bound argument for prototype methods
        skip_first = obj.bound && obj.id.indexOf('#') >= 0;
        a = arg.name;
        // argument can be callback
        if (arg.args) {
          a = signature({id: a}, arg);
        }
        if (!idx && skip_first) {
          return; //a = '@' + a;
        }
        if (typeof arg.default_value !== 'undefined') {
          // apply custom stringifier
          value = JSON.stringify(arg.default_value, function (k, v) {
            if (v instanceof RegExp) {
              // FIXME: get rid of quotes, if possible
              v = v.source;
            } else if (v === 'null') {
              v = null;
            }
            return v;
          });
          a = a + ' = ' + value;
        }
        // compensate for possibly skipped first argument
        if (idx > (skip_first ? 1 : 0)) {
          a = ', ' + a;
        }
        if (arg.ellipsis) {
          a += '...';
        }
        if (arg.optional) {
          a = '[' + a + ']';
        }
        r += a;
      });
      r += ')';
    }
    return r;
  }

  assets.prepare(function (err, env) {
    var vars, html;

    if (err) {
      if (err.originalError) {
        err = (err.message || err.toString()) + ':\n' +
              (err.originalError.message || err.originalError.message);
      }

      callback(err);
      return;
    }

    // collect context for rendering function
    vars = _.extend({}, options, {
      list: ndoc.list,
      tree: ndoc.tree,
      date: (new Date()).toUTCString(),
      //--
      link:           link,
      markdown:       markdown,
      signature:      signature,
      showInternals:  !!options.showInternals,
      // mincer rocks
      inline_asset: function (pathname) {
        var asset = env.findAsset(pathname);
        return asset ? asset.toString() : "";
      }
    });

    // render HTML
    html = fn(vars);

    fs.exists(options.output, function (exists) {
      if (exists) {
        callback("Output directory '" + options.output + "' already exists");
        return;
      }

      FsTools.mkdir(options.output, function (err) {
        if (err) {
          callback(err);
          return;
        }

        fs.writeFile(path.join(options.output, 'index.html'), html, callback);
      });
    });
  });
}

////////////////////////////////////////////////////////////////////////////////

module.exports = function html(NDoc) {
  NDoc.registerRenderer('html', render_html);

  NDoc.cli.addArgument(['--gh-ribbon'], {
    help:         'Add "Fork me on GitHub" ribbon with given URL. You can use ' +
                  'any of `{package.*}` variables for interpolation.',
    dest:         'github',
    metavar:      'URL',
    defaultValue: null
  });

  NDoc.cli.addArgument(['--broken-links'], {
    dest:         'brokenLinks',
    help:         'What to do if broken link occurred (show, hide, throw). ' +
                  'DEFAULT: `show`.',
    choices:      ['show', 'hide', 'throw'],
    metavar:      'ACTION',
    defaultValue: 'show'
  });
};
<commit_msg>Prevented highlighting for unsupported language<commit_after>/** internal, section: Plugins
 *  Renderers.html(NDoc) -> Void
 *
 *  Registers HTML renderer as `html`.
 *
 *
 *  ##### Example
 *
 *      NDoc.render('html', ast, options, function (err) {
 *        // ...
 *      });
 *
 *
 *  ##### Options
 *
 *  - **output** (String): Directory where to output rendered documentation.
 *  - **title** (String): Page title template. You can use `{package.*}`
 *    variables here.
 *    Default: `'{package.name} {package.version} API documentation'`
 *  - **index** (String): Intro text.
 *  - **github** (String): URL to a project on GitHub. If given, a nice ribbon
 *    with link to given URL will be added. You can use `{package.*}`
 *    variables here.
 *    Default: `Null`
 *  - **brokenLinks** (show|hide|throw): What to do if broken link occurred.
 *    Default: `'show'`
 **/

'use strict';

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

// 3rd-party
var _       = require('lodash');
var FsTools = require('fs-tools');
var Jade    = require('jade');
var marked  = require('marked');
var hljs    = require('highlight.js');

// internal
var assets    = require('./html/assets');
var template  = require('../../common').template;

// Markdown highlighter callback function
var marked_highlight = function (code, lang) {
  if (lang && hljs.LANGUAGES[lang]) {
    return hljs.highlight(lang, code).value;
  } else {
    return hljs.highlightAuto(code).value;
  }
};

////////////////////////////////////////////////////////////////////////////////

function render_html(ndoc, options, callback) {
  var file, str, fn, list, id, obj;

  // prepare rendering function
  // TODO: store it for further reuse, and get rid of jade dependency?
  file = path.join(__dirname, 'html', 'templates', 'layout.jade');
  str = fs.readFileSync(file, 'utf8');
  fn = Jade.compile(str, {
    filename: file,
    pretty: false
  });

  options.github = template(options.github || '', {package: options.package});

  // it's illegal to have slashes in HTML elements ids.
  // replace them with dashes
  list = ndoc.list;

  for (id in list) {
    if (list.hasOwnProperty(id)) {
      obj = list[id];
      // path should be HTML valid id
      obj.path = obj.path.replace(/\//g, '-');
    }
  }

  // render link
  // N.B. logic is way tricky to move to templates.
  // beside, this function is used as parameter in some Array#map() operations
  function link(obj, short, classes) {
    if (typeof obj === 'string') {
      obj = list[obj] || {id: obj};
    }
    // broken link. `options.brokenLinks` define action
    if (!obj.path) {
      return obj.id;
      /*if (options.brokenLinks === 'throw') {
        throw 'Link is broken: ' + obj.id;
      }
      return options.brokenLinks === 'show' ? '[[' + obj.id + ']]' : obj.id;*/
    }
    //
    var r = '';
    r += typeof short === 'string' ? short : short ? obj.name : obj.id;
    r += '';
    return r;
  }

  // convert markdown to HTML
  function markdown(text, nohl) {
    var r, codes;

    marked.setOptions({
      gfm: true,
      pedantic: false,
      sanitize: false,
      highlight: nohl ? null : marked_highlight
    });

    r = marked(text);

    // FIXME
    // desugar [[foo#bar]] tokens into local links
    // N.B. in order to not apply conversion in  blocks,
    // we first store replace code blocks with nonces
    codes = {};
    r = r.replace(/([\s\S]*?<\/code>)/g, function (all, def) {
      var nonce = Math.random().toString().substring(2);
      codes[nonce] = def;
      return '@-=@=-@' + nonce + '@-=@=-@';
    });
    // convert [[link]] to links
    r = r.replace(/\[\[([\s\S]+?)\]\]/g, function (all, def) {
      def = def.split(/\s+/);
      id = def.shift();
      // invalid references don't produce links
      if (!list[id]) {
        if (options.brokenLinks === 'throw') {
          throw 'Link is broken: ' + all + '\n' + r;
        }
        return options.brokenLinks === 'show' ? all : id;
      }

      var obj = _.extend({name: def.join(' ') || id}, list[id]);
      return link(obj, true, ['link-short']);
    });
    // restore code blocks, given previously stored nonces
    r = r.replace(/@-=@=-@(\d+)@-=@=-@/g, function (all, nonce) {
      return codes[nonce];
    });
    //
    return r;
  }

  // given signature object, recompose its textual representation
  function signature(obj, sig) {
    if (typeof obj === 'string') {
      obj = list[obj];
    }
    var r = obj.id;
    if (sig.args) {
      r += '(';
      sig.args.forEach(function (arg, idx) {
        var skip_first, a, value;
        // skip the first bound argument for prototype methods
        skip_first = obj.bound && obj.id.indexOf('#') >= 0;
        a = arg.name;
        // argument can be callback
        if (arg.args) {
          a = signature({id: a}, arg);
        }
        if (!idx && skip_first) {
          return; //a = '@' + a;
        }
        if (typeof arg.default_value !== 'undefined') {
          // apply custom stringifier
          value = JSON.stringify(arg.default_value, function (k, v) {
            if (v instanceof RegExp) {
              // FIXME: get rid of quotes, if possible
              v = v.source;
            } else if (v === 'null') {
              v = null;
            }
            return v;
          });
          a = a + ' = ' + value;
        }
        // compensate for possibly skipped first argument
        if (idx > (skip_first ? 1 : 0)) {
          a = ', ' + a;
        }
        if (arg.ellipsis) {
          a += '...';
        }
        if (arg.optional) {
          a = '[' + a + ']';
        }
        r += a;
      });
      r += ')';
    }
    return r;
  }

  assets.prepare(function (err, env) {
    var vars, html;

    if (err) {
      if (err.originalError) {
        err = (err.message || err.toString()) + ':\n' +
              (err.originalError.message || err.originalError.message);
      }

      callback(err);
      return;
    }

    // collect context for rendering function
    vars = _.extend({}, options, {
      list: ndoc.list,
      tree: ndoc.tree,
      date: (new Date()).toUTCString(),
      //--
      link:           link,
      markdown:       markdown,
      signature:      signature,
      showInternals:  !!options.showInternals,
      // mincer rocks
      inline_asset: function (pathname) {
        var asset = env.findAsset(pathname);
        return asset ? asset.toString() : "";
      }
    });

    // render HTML
    html = fn(vars);

    fs.exists(options.output, function (exists) {
      if (exists) {
        callback("Output directory '" + options.output + "' already exists");
        return;
      }

      FsTools.mkdir(options.output, function (err) {
        if (err) {
          callback(err);
          return;
        }

        fs.writeFile(path.join(options.output, 'index.html'), html, callback);
      });
    });
  });
}

////////////////////////////////////////////////////////////////////////////////

module.exports = function html(NDoc) {
  NDoc.registerRenderer('html', render_html);

  NDoc.cli.addArgument(['--gh-ribbon'], {
    help:         'Add "Fork me on GitHub" ribbon with given URL. You can use ' +
                  'any of `{package.*}` variables for interpolation.',
    dest:         'github',
    metavar:      'URL',
    defaultValue: null
  });

  NDoc.cli.addArgument(['--broken-links'], {
    dest:         'brokenLinks',
    help:         'What to do if broken link occurred (show, hide, throw). ' +
                  'DEFAULT: `show`.',
    choices:      ['show', 'hide', 'throw'],
    metavar:      'ACTION',
    defaultValue: 'show'
  });
};
<|endoftext|>