<commit_before>import Ember from 'ember';
import { attrToTitle }        from 'ember-ist-model-builder/display-helpers';
import IstModelDisplayHelpers from 'ember-ist-model-builder/display-helpers';

export default function() {
  return {
    // Returns a list of fields that you can build a form element for.
    // It provies the type of attribute and any associated models.
    editableFields: Ember.computed('modelConfig.attributes', function(){
      var modelConfig = this.get('modelConfig');
      var self = this;
      var fields = [];
      for(var attrName in (modelConfig.attributes || {}) ){
        if(IstModelDisplayHelpers.alwaysHiddenFields.indexOf(attrName) > -1){continue;}
        // pull out the attribute configuration for the one we are working on
        var attrConfig = modelConfig.attributes[attrName];

        var valueType        = 'raw';
        var associationModel = null;// which model the belongsTo or hasMany is refering to.

        // Allow configuring to disable editing.
        if (attrConfig.editable !== undefined && attrConfig.editable === false){
          continue;
        }

        if (attrConfig.belongsTo){
          valueType         = 'belongsTo';
          associationModel  = attrConfig.belongsTo;
        } else if (attrConfig.hasMany){
          valueType         = 'hasMany';
          associationModel  = attrConfig.hasMany;
        } else if (attrConfig.hasOne){
          valueType         = 'hasOne';
          associationModel  = attrConfig.hasOne;
        } else if (attrConfig.type){
          valueType         = attrConfig.type;
        }

        if (attrConfig.title) {
          label = attrConfig.title;
        } else {
          label = attrToTitle(attrName);
        }

        var field = Ember.Object.extend({
          subject:          self,
          attrName:         attrName,
          label:            label,
          value:            Ember.computed.alias('subject.' + attrName),
          valueType:        valueType,
          associationModel: associationModel,
        }).create();
        fields.push(field);
      }
      return fields;
    }),
  };// end return
}// end export
<commit_msg>made editable fields importable<commit_after>import Ember from 'ember';
import { attrToTitle }        from 'ember-ist-model-builder/display-helpers';
import IstModelDisplayHelpers from 'ember-ist-model-builder/display-helpers';

export function editableFieldsFor(object){
  var attrConfigs;
  var attrs;
  var fields = Ember.A();

  if (object.get && objet.get('modelConfig') !== undefined){
    attrConfigs = object.get('modelConfig').attributes;
    attrs       = Ember.keys(attrConfigs);
  } else {
    attrConfigs = Ember.keys(object);// no configs
    attrs       = Ember.keys(object);
  }

  for(var i = 0; i < attrs.length; i++) {
    var attrName = attrs[i];
    if(IstModelDisplayHelpers.alwaysHiddenFields.indexOf(attrName) > -1){continue;}

    // pull out the attribute configuration for the one we are working on
    var attrConfig = modelConfigs[attrName];
    var valueType        = 'raw';
    var associationModel = null;// which model the belongsTo or hasMany is refering to.
    if (attrConfig === undefined){attrConfig = {};}

    // Allow configuring to disable editing.
    if (attrConfig.editable !== undefined && attrConfig.editable === false){
      continue;
    }

    if (attrConfig.belongsTo){
      valueType         = 'belongsTo';
      associationModel  = attrConfig.belongsTo;
    } else if (attrConfig.hasMany){
      valueType         = 'hasMany';
      associationModel  = attrConfig.hasMany;
    } else if (attrConfig.hasOne){
      valueType         = 'hasOne';
      associationModel  = attrConfig.hasOne;
    } else if (attrConfig.type){
      valueType         = attrConfig.type;
    }

    if (attrConfig.title) {
      label = attrConfig.title;
    } else {
      label = attrToTitle(attrName);
    }

    var field = Ember.Object.extend({
      subject:          self,
      attrName:         attrName,
      label:            label,
      value:            Ember.computed.alias('subject.' + attrName),
      valueType:        valueType,
      associationModel: associationModel,
    }).create();

    fields.push(field);
  }
  return fields;
}

export default function() {
  return {
    // Returns a list of fields that you can build a form element for.
    // It provies the type of attribute and any associated models.
    editableFields: Ember.computed('modelConfig.attributes', function(){
      return editableFieldsFor(this);
    }),
  };// end return
}// end export
<|endoftext|>


<commit_before>/**
 * VTK-Web Widget Library.
 *
 * This module extend jQuery object to add support for graphical components
 * related to File Browsing.
 *
 * @class jQuery.vtk.ui.FileBrowser
 */
(function ($) {

    // =======================================================================
    // ==== Defaults constant values =========================================
    // =======================================================================
    var pathSeparator = '/',
    directives = {
         '.vtk-directory': {
            'directory <-': {
                '@path': function(arg) {
                    return pathToStr(arg.item.path);
                },
                '@class+': function(arg) {
                    return (arg.item.path.length === 1) ? ' active' : '';
                },
                '.vtk-label': 'directory.label',
                'li.vtk-files': {
                    'file <- directory.files': {
                        'div': 'file.label'
                    }
                },
                'li.vtk-groups': {
                    'gfile <- directory.groups': {
                        'div': 'gfile.label',
                        '@files': function(arg) {
                            return arg.item.files.join(":");
                        }
                    }
                },
                'li.vtk-dirs': {
                    'dir <- directory.dirs': {
                        'div': 'dir'
                    }
                },
                'li.vtk-path': {
                    'i <- directory.path': {
                        'div': 'i'
                    }//,
                    // filter : function(a) {
                    //     return a.pos < (a.items.length - 1);
                    // }
                }
            }
        }
    },
    fileBrowserGenerator = null;

    $.fn.fileBrowser = function(options) {
        // Handle data with default values
        var opts = $.extend({},$.fn.fileBrowser.defaults, options);

        // Compile template only once
        if(fileBrowserGenerator === null) {
            template = $(opts.template);
            fileBrowserGenerator = template.compile(directives);
        }

        return this.each(function() {
            var me = $(this).empty().addClass('vtk-filebrowser'),
            container = $('<div/>');
            me.append(container);
            me.data('file-list', opts.data);
            me.data('session', opts.session);

            if(opts.data === null) {
                opts.session.call('vtk:listServerDirectory','.').then(function(files) {
                    opts.data = [ files ];
                    me.data('file-list', opts.data);

                    // Generate HTML
                    container.render(opts.data, fileBrowserGenerator);

                    // Initialize pipelineBrowser (Visibility + listeners)
                    initializeListener(me);
                });
            } else {
                // Generate HTML
                container.render(opts.data, fileBrowserGenerator);

                // Initialize pipelineBrowser (Visibility + listeners)
                initializeListener(me);
            }
        });
    };

    $.fn.updateFileBrowser = function(activeDirectory) {

        return this.each(function() {
            var me = $(this).empty(),
            data = me.data('file-list'),
            newData = [],
            container = $('<div/>');

            me.append(container);

            // Delete the cached active directory and fetch again
            if(activeDirectory && me.data('session')){
                var dirArray = activeDirectory.split("/").splice(1);
                for(var i in data) {
                    var item = data[i];
                    var itemArray = item.path;
                    if ( !equals(itemArray, dirArray) ) {
                        newData.push(data[i]);
                    }
                }

                var requestPath =  activeDirectory.substring(1);
                if(requestPath.indexOf('/') == -1) {
                    requestPath = '.';
                }
                me.data('session').call('vtk:listServerDirectory', requestPath)
                    .then(function(newFiles){
                        newData.push(newFiles);
                        me.data('file-list', newData);
                        // Generate HTML
                        container.render(newData, fileBrowserGenerator);

                        // Initialize pipelineBrowser (Visibility + listeners)
                        initializeListener(me, activeDirectory);
                    });

            } else {
                // Generate HTML
                container.render(data, fileBrowserGenerator);

                // Initialize pipelineBrowser (Visibility + listeners)
                initializeListener(me, activeDirectory);
            }
        });
    };

    $.fn.fileBrowser.defaults = {
        template: "#vtk-templates > .vtkweb-widget-filebrowser > div",
        session: null,
        data: null
    };

    // =======================================================================

    function strToPath(pathId) {
        var path = pathId.split(pathSeparator);
        return path.slice(1, path.length);
    }

    // =======================================================================

    function getParent(path) {
        return path.slice(0, path.length - 2);
    }

    // =======================================================================

    function getPath(parentPath, child) {
        return [].concat(parentPath).concat(child);
    }

    // =======================================================================

    function pathToStr(path) {
        //console.log(path);
        var str = pathSeparator + path.join(pathSeparator);
        return str;
    }

    // =======================================================================

    equals = function(array1, array2) {
        if (array1.length != array2.length) {
            return false;
        }

        for (var i in array1) {
            if (array1[i] !== array2[i]) {
                return false;
            }
        }

        return true;
    }

    // =======================================================================

    function getRelativePath(parentPath, fileName) {
        return '.' + pathToStr(getPath(parentPath, fileName).slice(1));
    }

    // =======================================================================

    function initializeListener(container, activePath) {
        $('.action', container).click(function(){
            var me = $(this), item = $('div', me), pathStr = me.closest('.vtk-directory').attr('path'), type = me.closest('ul').attr('data');

            if(type === 'path') {
                // Find out the panel to show
                var newPath = pathToStr(strToPath(pathStr).slice(0, me.index() + 1)),
                selector = '.vtk-directory[path="' + newPath + '"]';
                var newActive = $(selector , container).addClass('active');
                if(newActive.length === 1) {
                     $('.vtk-directory', container).removeClass('active');
                     newActive.addClass('active');
                }
            } else if(type === 'dir') {
                // Swicth active panel
                var str = '.vtk-directory[path="' + pathStr + pathSeparator + item.html() + '"]';
                var newActive = $(str, container);
                if(newActive.length === 1) {
                    $('.vtk-directory', container).removeClass('active');
                    newActive.addClass('active');
                    container.trigger({
                        type: 'directory-click',
                        path: pathStr,
                        name: me.text(),
                        relativePath: getRelativePath(strToPath(pathStr), me.text())
                    });
                } else {
                    if(container.data('session')) {
                        var relativePath = (pathStr + '/' + me.text());
                        container.data('session').call('vtk:listServerDirectory', relativePath.substring(1)).then(function(newFiles){
                            container.data('file-list').push(newFiles);
                            container.updateFileBrowser(relativePath);
                        });

                    }
                    container.trigger({
                        type: 'directory-not-found',
                        path: pathStr,
                        name: me.text(),
                        relativePath: getRelativePath(strToPath(pathStr), me.text())
                    });
                }
            } else if(type === 'files') {
                container.trigger({
                    type: 'file-click',
                    path: pathStr,
                    name: me.text(),
                    relativePathList: [ getRelativePath(strToPath(pathStr), me.text()) ],
                    list: [ me.text() ],
                    relativePath: getRelativePath(strToPath(pathStr), me.text())
                });
            } else if(type === 'groups') {
                var relativePathList = [], fileList = me.attr('files').split(':');
                for(var i in fileList) {
                    relativePathList.push(getRelativePath(strToPath(pathStr), fileList[i]));
                }
                container.trigger({
                    type: 'file-group-click',
                    path: pathStr,
                    name: me.text(),
                    list: fileList,
                    relativePathList: relativePathList,
                    relativePath: getRelativePath(strToPath(pathStr), me.text())
                });
            }
        });
        if(activePath) {
            $('.vtk-directory',container).removeClass('active');
            $('.vtk-directory[path="' + activePath + '"]',container).addClass('active');
        }

    }

}(jQuery));<commit_msg>Added code to support a cache option for filebrowser widget.<commit_after>/**
 * VTK-Web Widget Library.
 *
 * This module extend jQuery object to add support for graphical components
 * related to File Browsing.
 *
 * @class jQuery.vtk.ui.FileBrowser
 */
(function ($) {

    // =======================================================================
    // ==== Defaults constant values =========================================
    // =======================================================================
    var pathSeparator = '/',
    directives = {
         '.vtk-directory': {
            'directory <-': {
                '@path': function(arg) {
                    return pathToStr(arg.item.path);
                },
                '@class+': function(arg) {
                    return (arg.item.path.length === 1) ? ' active' : '';
                },
                '.vtk-label': 'directory.label',
                'li.vtk-files': {
                    'file <- directory.files': {
                        'div': 'file.label'
                    }
                },
                'li.vtk-groups': {
                    'gfile <- directory.groups': {
                        'div': 'gfile.label',
                        '@files': function(arg) {
                            return arg.item.files.join(":");
                        }
                    }
                },
                'li.vtk-dirs': {
                    'dir <- directory.dirs': {
                        'div': 'dir'
                    }
                },
                'li.vtk-path': {
                    'i <- directory.path': {
                        'div': 'i'
                    }//,
                    // filter : function(a) {
                    //     return a.pos < (a.items.length - 1);
                    // }
                }
            }
        }
    },
    fileBrowserGenerator = null;

    $.fn.fileBrowser = function(options) {
        // Handle data with default values
        var opts = $.extend({},$.fn.fileBrowser.defaults, options);

        // Compile template only once
        if(fileBrowserGenerator === null) {
            template = $(opts.template);
            fileBrowserGenerator = template.compile(directives);
        }

        return this.each(function() {
            var me = $(this).empty().addClass('vtk-filebrowser'),
            container = $('<div/>');
            me.append(container);
            me.data('file-list', opts.data);
            me.data('session', opts.session);
            me.data('cacheFiles', opts.cacheFiles);

            if(opts.data === null) {
                opts.session.call('vtk:listServerDirectory','.').then(function(files) {
                    opts.data = [ files ];
                    me.data('file-list', opts.data);

                    // Generate HTML
                    container.render(opts.data, fileBrowserGenerator);

                    // Initialize pipelineBrowser (Visibility + listeners)
                    initializeListener(me);
                });
            } else {
                // Generate HTML
                container.render(opts.data, fileBrowserGenerator);

                // Initialize pipelineBrowser (Visibility + listeners)
                initializeListener(me);
            }
        });
    };

    $.fn.updateFileBrowser = function(activeDirectory) {

        return this.each(function() {
            var me = $(this).empty(),
            data = me.data('file-list'),
            newData = [],
            container = $('<div/>');

            me.append(container);

            // Delete the cached active directory and fetch again
            if(activeDirectory && me.data('session')){
                var dirArray = activeDirectory.split("/").splice(1);
                for(var i in data) {
                    var item = data[i];
                    var itemArray = item.path;
                    if ( !equals(itemArray, dirArray) ) {
                        newData.push(data[i]);
                    }
                }

                var requestPath =  activeDirectory.substring(1);
                if(requestPath.indexOf('/') == -1) {
                    requestPath = '.';
                }
                me.data('session').call('vtk:listServerDirectory', requestPath)
                    .then(function(newFiles){
                        newData.push(newFiles);
                        me.data('file-list', newData);
                        // Generate HTML
                        container.render(newData, fileBrowserGenerator);

                        // Initialize pipelineBrowser (Visibility + listeners)
                        initializeListener(me, activeDirectory);
                    });

            } else {
                // Generate HTML
                container.render(data, fileBrowserGenerator);

                // Initialize pipelineBrowser (Visibility + listeners)
                initializeListener(me, activeDirectory);
            }
        });
    };

    $.fn.fileBrowser.defaults = {
        template: "#vtk-templates > .vtkweb-widget-filebrowser > div",
        session: null,
        data: null,
        cacheFiles: true
    };

    // =======================================================================

    function strToPath(pathId) {
        var path = pathId.split(pathSeparator);
        return path.slice(1, path.length);
    }

    // =======================================================================

    function getParent(path) {
        return path.slice(0, path.length - 2);
    }

    // =======================================================================

    function getPath(parentPath, child) {
        return [].concat(parentPath).concat(child);
    }

    // =======================================================================

    function pathToStr(path) {
        //console.log(path);
        var str = pathSeparator + path.join(pathSeparator);
        return str;
    }

    // =======================================================================

    equals = function(array1, array2) {
        if (array1.length != array2.length) {
            return false;
        }

        for (var i in array1) {
            if (array1[i] !== array2[i]) {
                return false;
            }
        }

        return true;
    }

    // =======================================================================

    function getRelativePath(parentPath, fileName) {
        return '.' + pathToStr(getPath(parentPath, fileName).slice(1));
    }

    // =======================================================================

    function initializeListener(container, activePath) {
        $('.action', container).click(function(){
            var me = $(this), item = $('div', me), pathStr = me.closest('.vtk-directory').attr('path'), type = me.closest('ul').attr('data');

            if(type === 'path') {
                // Find out the panel to show
                var newPath = pathToStr(strToPath(pathStr).slice(0, me.index() + 1)),
                selector = '.vtk-directory[path="' + newPath + '"]';
                var newActive = $(selector , container).addClass('active');
                if(newActive.length === 1) {
                     $('.vtk-directory', container).removeClass('active');
                     newActive.addClass('active');
                }
                if (container.data('cacheFiles') === false) {
                    container.updateFileBrowser(newPath);
                }
            } else if(type === 'dir') {
                // Swicth active panel
                var str = '.vtk-directory[path="' + pathStr + pathSeparator + item.html() + '"]';
                var newActive = $(str, container);
                if(newActive.length === 1) {
                    $('.vtk-directory', container).removeClass('active');
                    newActive.addClass('active');
                    container.trigger({
                        type: 'directory-click',
                        path: pathStr,
                        name: me.text(),
                        relativePath: getRelativePath(strToPath(pathStr), me.text())
                    });
                } else {
                    if(container.data('session')) {
                        var relativePath = (pathStr + '/' + me.text());
                        container.data('session').call('vtk:listServerDirectory', relativePath.substring(1)).then(function(newFiles){
                            container.data('file-list').push(newFiles);
                            container.updateFileBrowser(relativePath);
                        });

                    }
                    container.trigger({
                        type: 'directory-not-found',
                        path: pathStr,
                        name: me.text(),
                        relativePath: getRelativePath(strToPath(pathStr), me.text())
                    });
                }
            } else if(type === 'files') {
                container.trigger({
                    type: 'file-click',
                    path: pathStr,
                    name: me.text(),
                    relativePathList: [ getRelativePath(strToPath(pathStr), me.text()) ],
                    list: [ me.text() ],
                    relativePath: getRelativePath(strToPath(pathStr), me.text())
                });
            } else if(type === 'groups') {
                var relativePathList = [], fileList = me.attr('files').split(':');
                for(var i in fileList) {
                    relativePathList.push(getRelativePath(strToPath(pathStr), fileList[i]));
                }
                container.trigger({
                    type: 'file-group-click',
                    path: pathStr,
                    name: me.text(),
                    list: fileList,
                    relativePathList: relativePathList,
                    relativePath: getRelativePath(strToPath(pathStr), me.text())
                });
            }
        });
        if(activePath) {
            $('.vtk-directory',container).removeClass('active');
            $('.vtk-directory[path="' + activePath + '"]',container).addClass('active');
        }

    }

}(jQuery));<|endoftext|>


<commit_before>(function() {

  /**
  * URLOfResource
  *  Create URL of the resource on Evernote's server
  * @param  { string } guid - the resource's guid
  * @param  { string } shardId - shard id of the resource owner
  * @return string - URL
  */
  function URLOfResource(guid, shardId){
    return 'https://www.evernote.com/shard/'+shardId+'/res/'+guid;
  }

  /**
  * enmlHashToBodyHash
  *  'bodyHash' returned from Evernote API is not equal to 'enmlHash' (hash string in the notes' content).
  *  'enmlHash' is 'bodyHash' in ascii-hex form
  * @param  { string } enmlHash - (Hash string in notes' content)
  * @return string - bodyHash (Binary hash in Evernote API)
  */
  function BodyHashOfENMLHash(enmlHash){

    var buffer = [];

    for(var i =0 ; i<enmlHash.length; i += 2){
      buffer.push( parseInt(enmlHash[i],16)*16 + parseInt(enmlHash[i+1],16));
    }
     console.log(buffer)
    //console.log(buffer_st);
    var bodyHash = '';
    for(i =0 ; i<buffer.length; i ++){
      if( buffer[i] < 128 )
        bodyHash += String.fromCharCode(buffer[i]);
      else if(buffer[i] < 0xC0)
        bodyHash += String.fromCharCode(65533); // UNKNOWN
      else if((i+1 < buffer.length) && ((buffer[i+1] & 0xC0) == 0x80) ){
        //UTF-8 2-bytes encoding
        var charcode = (buffer[i] & 0x1f)*64 + (buffer[i+1] & 0x3f);
        bodyHash += String.fromCharCode(charcode);
        i += 1;
      }
      else
        bodyHash += String.fromCharCode(65533); // UNKNOWN
    }

    return bodyHash;
  }

  /**
  * ENMLOfPlainText
  * @param  { string } text (Plain)
  * @return string - ENML
  */
  function ENMLOfPlainText(text){

    var writer = new XMLWriter();

    writer.startDocument = writer.startDocument || writer.writeStartDocument;
    writer.endDocument = writer.endDocument || writer.writeEndDocument;
    writer.startDocument = writer.startElement || writer.writeStartElement;
    writer.startDocument = writer.endElement || writer.writeEndElement;

    writer.startDocument('1.0', 'UTF-8', false);
    writer.write('<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">');
    writer.write("\n");
    writer.startElement('en-note');
    writer.writeAttribute('style', 'word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;');

    var lines = text.match(/^.*((\r\n|\n|\r)|$)/gm);

    lines.forEach(function(line) {
      writer.startElement('div');
      writer.text(line.replace(/(\r\n|\n|\r)/,''));
      writer.endElement();

      writer.text("\n");
    });

    writer.endElement();
    writer.endDocument();

    return writer.toString();
  }

  /**
  * PlainTextOfENML
  * @param  { string } text (ENML)
  * @return string - text
  */
  function PlainTextOfENML(enml){

    var text = enml || '';
    text = text.replace(/(<\/(div|ui|li)>)/ig,"\n");
    text = text.replace(/(<(li)>)/ig," - ");
    text = text.replace(/(<([^>]+)>)/ig,"");
    text = text.replace(/(\r\n|\n|\r)/gm," ");
    text = text.replace(/(\s+)/gm," ");

    return text;
  }

  /**
  * HTMLOfENML
  *	Convert ENML into HTML for showing in web browsers.
  *
  * @param { string } text (ENML)
  * @param	{ Map <string (hash), url (string) || { url: (string), title: (string) } >, Optional } resources
  * @return string - HTML
  */
  function HTMLOfENML(text, resources){

    resources = resources || {};
    embedAllResources = embedAllResources || false;
    var writer = new XMLWriter();

    var parser = new SaxParser(function(cb) {

      var mediaTagStarted = false;
      var linkTagStarted = false;
      var linkTitle;

      cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {

        if(elem == 'en-note'){
          writer.startElement('html');
          writer.startElement('head');

          writer.startElement('meta');
          writer.writeAttribute('http-equiv', 'Content-Type');
          writer.writeAttribute('content', 'text/html; charset=UTF-8');
          writer.endElement();

          writer.endElement();

          writer.startElement('body');
          writer.writeAttribute('style', 'word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;');
        } else if(elem == 'en-todo'){

          writer.startElement('input');
          writer.writeAttribute('type', 'checkbox');

        }	else if(elem == 'en-media'){

          var type = null;
          var hash = null;
          var width = 0;
          var height = 0;

          if(attrs) attrs.forEach(function(attr) {
            if(attr[0] == 'type') type = attr[1];
            if(attr[0] == 'hash') hash = attr[1];
            if(attr[0] == 'width') width = attr[1];
            if(attr[0] == 'height') height = attr[1];
          });

          hash = BodyHashOfENMLHash(hash);
          var resource = resources[hash];

          if(!resource) return;
          var resourceUrl = resource.url || resource;
          var resourceTitle = resource.title || resource.url || '';

          if(type.match('image')) {
            writer.startElement('img');
            writer.writeAttribute('title', resourceTitle);

          } else if(type.match('audio')) {

            writer.writeElement('p', resourceTitle);
            writer.startElement('audio');
            writer.writeAttribute('controls', '');
            writer.text('Your browser does not support the audio tag.');
            writer.startElement('source');
            mediaTagStarted = true;

          } else if(type.match('video')) {
            writer.writeElement('p', resourceTitle);
            writer.startElement('video');
            writer.writeAttribute('controls', '');
            writer.text('Your browser does not support the video tag.');
            writer.startElement('source');
            mediaTagStarted = true;
          } else {
            writer.startElement('a');
            linkTagStarted = true;
            linkTitle = resourceTitle;
          }

          if(resourceUrl && linkTagStarted) {
            writer.writeAttribute('href', resourceUrl);
          } else {
            writer.writeAttribute('src', resourceUrl);
          }

          if(width) writer.writeAttribute ('width', width);
          if(height) writer.writeAttribute('height', height);

        }	else {
          writer.startElement(elem);
        }

        if(attrs) attrs.forEach(function(attr) {
          writer.writeAttribute(attr[0], attr[1]);
        });

      });
      cb.onEndElementNS(function(elem, prefix, uri) {

        if(elem == 'en-note'){
          writer.endElement(); //body
          writer.endElement(); //html
        }
        else if(elem == 'en-todo'){

        }
        else if(elem == 'en-media'){
          if(mediaTagStarted) {
            writer.endElement(); // source
            writer.endElement(); // audio or video
            writer.writeElement('br', '');
            mediaTagStarted = false;

          } else if(linkTagStarted) {
            writer.text(linkTitle);
            writer.endElement(); // a
            linkTagStarted = false;
          }

        } else {

          writer.endElement();
        }
      });
      cb.onCharacters(function(chars) {
        writer.text(chars);
      });

    });

    parser.parseString(text);
    return writer.toString();

  }

  /**
  * TodosOfENML
  *	Extract data of all TODO(s) in ENML text.
  *
  * @param { string } text (ENML)
  * @return { Array [ { text: (string), done: (bool) } ] } -
  */
  function TodosOfENML(text){

    var todos = [];

    var parser = new SaxParser(function(cb) {

      var onTodo = false;
      var text = null;
      var checked = false;

      cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {
        var m = elem.match(/b|u|i|font|strong/);
        if(m && elem == m[0]){

        }
        else if(elem == 'en-todo'){

          checked = false;
          text = "";
          onTodo = true;

          if(attrs) attrs.forEach(function(attr) {
            if(attr[0] == 'checked' && attr[1] == 'true') checked = true;
          });

        }	else {
          if(onTodo){
            todos.push({text: text, checked: checked});
          }
          onTodo = false;
        }

      });
      cb.onEndElementNS(function(elem, prefix, uri) {

      });
      cb.onCharacters(function(chars) {
        if(onTodo){
          text += chars;
        }
      });

    });

    parser.parseString(text);
    return todos;
  }

  /**
  * CheckTodoInENML
  *	Rewrite ENML content by changing check/uncheck value of the TODO in given position.
  *
  * @param { string } text (ENML)
  * @param { int }  index
  * @param { bool } check
  * @return string - ENML (the new content)
  */
  function CheckTodoInENML(text, index, check){

    var todo_cout = 0;
    var writer = new XMLWriter();
    var parser = new SaxParser(function(cb) {

      cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {

        writer.startElement(elem);

        if(elem == 'en-todo' && index == todo_cout++){

          if(attrs) attrs.forEach(function(attr) {
            if(attr[0] == 'checked') return;
            writer.writeAttribute(attr[0], attr[1]);
          });

          if(check)  writer.writeAttribute('checked', 'true');
        }else{

          if(attrs) attrs.forEach(function(attr) {
            writer.writeAttribute(attr[0], attr[1]);
          });
        }
      });
      cb.onEndElementNS(function(elem, prefix, uri) {

        writer.endElement();
      });
      cb.onCharacters(function(chars) {
        writer.text(chars);
      });

    });

    parser.parseString(text);
    return writer.toString();
  }

  var XMLWriter;
  var SaxParser;
  if(typeof exports == 'undefined'){

    XMLWriter = window.XMLWriter;
    SaxParser = window.SaxParser;

    //Browser Code
    window.enml = {};
    window.enml.URLOfResource = URLOfResource;
    window.enml.ENMLOfPlainText = ENMLOfPlainText;
    window.enml.HTMLOfENML = HTMLOfENML;
    window.enml.PlainTextOfENML = PlainTextOfENML;
  }
  else{

    //Node JS
    XMLWriter = require('./lib/xml-writer');
    SaxParser = require('./lib/xml-parser').SaxParser;

    exports.URLOfResource = URLOfResource;
    exports.ENMLOfPlainText = ENMLOfPlainText;
    exports.HTMLOfENML = HTMLOfENML;
    exports.PlainTextOfENML = PlainTextOfENML;
    exports.TodosOfENML = TodosOfENML;
    exports.CheckTodoInENML = CheckTodoInENML;
  }

})();<commit_msg>Remove "embedAllResources" attr<commit_after>(function() {

  /**
  * URLOfResource
  *  Create URL of the resource on Evernote's server
  * @param  { string } guid - the resource's guid
  * @param  { string } shardId - shard id of the resource owner
  * @return string - URL
  */
  function URLOfResource(guid, shardId){
    return 'https://www.evernote.com/shard/'+shardId+'/res/'+guid;
  }

  /**
  * enmlHashToBodyHash
  *  'bodyHash' returned from Evernote API is not equal to 'enmlHash' (hash string in the notes' content).
  *  'enmlHash' is 'bodyHash' in ascii-hex form
  * @param  { string } enmlHash - (Hash string in notes' content)
  * @return string - bodyHash (Binary hash in Evernote API)
  */
  function BodyHashOfENMLHash(enmlHash){

    var buffer = [];

    for(var i =0 ; i<enmlHash.length; i += 2){
      buffer.push( parseInt(enmlHash[i],16)*16 + parseInt(enmlHash[i+1],16));
    }
     console.log(buffer)
    //console.log(buffer_st);
    var bodyHash = '';
    for(i =0 ; i<buffer.length; i ++){
      if( buffer[i] < 128 )
        bodyHash += String.fromCharCode(buffer[i]);
      else if(buffer[i] < 0xC0)
        bodyHash += String.fromCharCode(65533); // UNKNOWN
      else if((i+1 < buffer.length) && ((buffer[i+1] & 0xC0) == 0x80) ){
        //UTF-8 2-bytes encoding
        var charcode = (buffer[i] & 0x1f)*64 + (buffer[i+1] & 0x3f);
        bodyHash += String.fromCharCode(charcode);
        i += 1;
      }
      else
        bodyHash += String.fromCharCode(65533); // UNKNOWN
    }

    return bodyHash;
  }

  /**
  * ENMLOfPlainText
  * @param  { string } text (Plain)
  * @return string - ENML
  */
  function ENMLOfPlainText(text){

    var writer = new XMLWriter();

    writer.startDocument = writer.startDocument || writer.writeStartDocument;
    writer.endDocument = writer.endDocument || writer.writeEndDocument;
    writer.startDocument = writer.startElement || writer.writeStartElement;
    writer.startDocument = writer.endElement || writer.writeEndElement;

    writer.startDocument('1.0', 'UTF-8', false);
    writer.write('<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">');
    writer.write("\n");
    writer.startElement('en-note');
    writer.writeAttribute('style', 'word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;');

    var lines = text.match(/^.*((\r\n|\n|\r)|$)/gm);

    lines.forEach(function(line) {
      writer.startElement('div');
      writer.text(line.replace(/(\r\n|\n|\r)/,''));
      writer.endElement();

      writer.text("\n");
    });

    writer.endElement();
    writer.endDocument();

    return writer.toString();
  }

  /**
  * PlainTextOfENML
  * @param  { string } text (ENML)
  * @return string - text
  */
  function PlainTextOfENML(enml){

    var text = enml || '';
    text = text.replace(/(<\/(div|ui|li)>)/ig,"\n");
    text = text.replace(/(<(li)>)/ig," - ");
    text = text.replace(/(<([^>]+)>)/ig,"");
    text = text.replace(/(\r\n|\n|\r)/gm," ");
    text = text.replace(/(\s+)/gm," ");

    return text;
  }

  /**
  * HTMLOfENML
  *	Convert ENML into HTML for showing in web browsers.
  *
  * @param { string } text (ENML)
  * @param	{ Map <string (hash), url (string) || { url: (string), title: (string) } >, Optional } resources
  * @return string - HTML
  */
  function HTMLOfENML(text, resources){

    resources = resources || {};
    var writer = new XMLWriter();

    var parser = new SaxParser(function(cb) {

      var mediaTagStarted = false;
      var linkTagStarted = false;
      var linkTitle;

      cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {

        if(elem == 'en-note'){
          writer.startElement('html');
          writer.startElement('head');

          writer.startElement('meta');
          writer.writeAttribute('http-equiv', 'Content-Type');
          writer.writeAttribute('content', 'text/html; charset=UTF-8');
          writer.endElement();

          writer.endElement();

          writer.startElement('body');
          writer.writeAttribute('style', 'word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;');
        } else if(elem == 'en-todo'){

          writer.startElement('input');
          writer.writeAttribute('type', 'checkbox');

        }	else if(elem == 'en-media'){

          var type = null;
          var hash = null;
          var width = 0;
          var height = 0;

          if(attrs) attrs.forEach(function(attr) {
            if(attr[0] == 'type') type = attr[1];
            if(attr[0] == 'hash') hash = attr[1];
            if(attr[0] == 'width') width = attr[1];
            if(attr[0] == 'height') height = attr[1];
          });

          hash = BodyHashOfENMLHash(hash);
          var resource = resources[hash];

          if(!resource) return;
          var resourceUrl = resource.url || resource;
          var resourceTitle = resource.title || resource.url || '';

          if(type.match('image')) {
            writer.startElement('img');
            writer.writeAttribute('title', resourceTitle);

          } else if(type.match('audio')) {

            writer.writeElement('p', resourceTitle);
            writer.startElement('audio');
            writer.writeAttribute('controls', '');
            writer.text('Your browser does not support the audio tag.');
            writer.startElement('source');
            mediaTagStarted = true;

          } else if(type.match('video')) {
            writer.writeElement('p', resourceTitle);
            writer.startElement('video');
            writer.writeAttribute('controls', '');
            writer.text('Your browser does not support the video tag.');
            writer.startElement('source');
            mediaTagStarted = true;
          } else {
            writer.startElement('a');
            linkTagStarted = true;
            linkTitle = resourceTitle;
          }

          if(resourceUrl && linkTagStarted) {
            writer.writeAttribute('href', resourceUrl);
          } else {
            writer.writeAttribute('src', resourceUrl);
          }

          if(width) writer.writeAttribute ('width', width);
          if(height) writer.writeAttribute('height', height);

        }	else {
          writer.startElement(elem);
        }

        if(attrs) attrs.forEach(function(attr) {
          writer.writeAttribute(attr[0], attr[1]);
        });

      });
      cb.onEndElementNS(function(elem, prefix, uri) {

        if(elem == 'en-note'){
          writer.endElement(); //body
          writer.endElement(); //html
        }
        else if(elem == 'en-todo'){

        }
        else if(elem == 'en-media'){
          if(mediaTagStarted) {
            writer.endElement(); // source
            writer.endElement(); // audio or video
            writer.writeElement('br', '');
            mediaTagStarted = false;

          } else if(linkTagStarted) {
            writer.text(linkTitle);
            writer.endElement(); // a
            linkTagStarted = false;
          }

        } else {

          writer.endElement();
        }
      });
      cb.onCharacters(function(chars) {
        writer.text(chars);
      });

    });

    parser.parseString(text);
    return writer.toString();

  }

  /**
  * TodosOfENML
  *	Extract data of all TODO(s) in ENML text.
  *
  * @param { string } text (ENML)
  * @return { Array [ { text: (string), done: (bool) } ] } -
  */
  function TodosOfENML(text){

    var todos = [];

    var parser = new SaxParser(function(cb) {

      var onTodo = false;
      var text = null;
      var checked = false;

      cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {
        var m = elem.match(/b|u|i|font|strong/);
        if(m && elem == m[0]){

        }
        else if(elem == 'en-todo'){

          checked = false;
          text = "";
          onTodo = true;

          if(attrs) attrs.forEach(function(attr) {
            if(attr[0] == 'checked' && attr[1] == 'true') checked = true;
          });

        }	else {
          if(onTodo){
            todos.push({text: text, checked: checked});
          }
          onTodo = false;
        }

      });
      cb.onEndElementNS(function(elem, prefix, uri) {

      });
      cb.onCharacters(function(chars) {
        if(onTodo){
          text += chars;
        }
      });

    });

    parser.parseString(text);
    return todos;
  }

  /**
  * CheckTodoInENML
  *	Rewrite ENML content by changing check/uncheck value of the TODO in given position.
  *
  * @param { string } text (ENML)
  * @param { int }  index
  * @param { bool } check
  * @return string - ENML (the new content)
  */
  function CheckTodoInENML(text, index, check){

    var todo_cout = 0;
    var writer = new XMLWriter();
    var parser = new SaxParser(function(cb) {

      cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {

        writer.startElement(elem);

        if(elem == 'en-todo' && index == todo_cout++){

          if(attrs) attrs.forEach(function(attr) {
            if(attr[0] == 'checked') return;
            writer.writeAttribute(attr[0], attr[1]);
          });

          if(check)  writer.writeAttribute('checked', 'true');
        }else{

          if(attrs) attrs.forEach(function(attr) {
            writer.writeAttribute(attr[0], attr[1]);
          });
        }
      });
      cb.onEndElementNS(function(elem, prefix, uri) {

        writer.endElement();
      });
      cb.onCharacters(function(chars) {
        writer.text(chars);
      });

    });

    parser.parseString(text);
    return writer.toString();
  }

  var XMLWriter;
  var SaxParser;
  if(typeof exports == 'undefined'){

    XMLWriter = window.XMLWriter;
    SaxParser = window.SaxParser;

    //Browser Code
    window.enml = {};
    window.enml.URLOfResource = URLOfResource;
    window.enml.ENMLOfPlainText = ENMLOfPlainText;
    window.enml.HTMLOfENML = HTMLOfENML;
    window.enml.PlainTextOfENML = PlainTextOfENML;
  }
  else{

    //Node JS
    XMLWriter = require('./lib/xml-writer');
    SaxParser = require('./lib/xml-parser').SaxParser;

    exports.URLOfResource = URLOfResource;
    exports.ENMLOfPlainText = ENMLOfPlainText;
    exports.HTMLOfENML = HTMLOfENML;
    exports.PlainTextOfENML = PlainTextOfENML;
    exports.TodosOfENML = TodosOfENML;
    exports.CheckTodoInENML = CheckTodoInENML;
  }

})();<|endoftext|>


<commit_before>// Gruntfile with the configuration of grunt-express and grunt-open. No livereload yet!
module.exports = function(grunt) {

  // Load Grunt tasks declared in the package.json file
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  var scripts = {
        js: [],
        css: []
      };

  Object.keys(grunt.file.readJSON('./bower.json').dependencies).map(
        function(file) {
            scripts.js.push('source/lib/'+file+'.js');
        }
  );

  Object.keys(grunt.file.readJSON('./bower.json').dependencies).map(
        function(file) {
            scripts.css.push('source/css/lib/'+file+'.css');
        }
  );

  // Configure Grunt
  grunt.initConfig({

    htmlbuild: {
        source: {
            src: 'template/source/index.html',
            dest: 'source/index.html',
            options: {
                beautify: true,
                relative: true,
                scripts: {
                    bundle: [
                              scripts.js,
                              'source/lib/**/*.js',
                              'source/scripts/**/*.js'
                            ]
                },
                styles: {
                    bundle: [
                        'source/css/dist/css/bootstrap.css',
                        'source/css/attach.css',
                        scripts.css
                    ]
                },
                sections: {
                    layout: {
                        header: 'template/source/header.html',
                        footer: 'template/source/footer.html'
                    }
                },
            }
        }
    },

    uglify: {
      distro: {
        files: [{
            expand: true,
            cwd: 'distro/js',
            src: '**/*.js',
            dest: 'distro/js'
        }]
      }
    },

    cssmin: {
      distro: {
        files: [{
          expand: true,
          cwd: 'distro/css',
          src: '**/*.css',
          dest: 'distro/css',
        }]
      }
    },

    bower: {
      dev: {
        dest: 'source/',
        js_dest: 'source/lib',
        options: {
          ignorePackages: ['jquery','less'],
          packageSpecific: {
            'angular-material': {
              css_dest: 'source/css/lib/'
            },
            'ngStorage':{
              js_dest:'source/js/lib'
            }
          }
        }
      }
    },

    copy: {
      index: {
        expand: true,
        cwd: 'source/',
        src: 'index.html',
        dest: 'distro/',
      },
      views: {
        expand: true,
        cwd: 'source/views',
        src: '*.html',
        dest: 'distro/views',
      },
      scripts: {
        expand: true,
        cwd: 'source/scripts/',
        src: '**/*.js',
        dest: 'distro/scripts/',
      },
      svg: {
        expand: true,
        cwd: 'source/svg/',
        src: '*.svg',
        dest: 'distro/svg/'
      }
    },

    concat: {
      css:{
        src: ['source/css/attach.css',
              'source/css/lib/**/*.css'],
        dest: 'distro/css/distro.css'

      },
      js:{
        src:['source/lib/**/*.js',
            'source/scripts/**/*.js'],
        dest:'distro/js/distro.js'
      }
    },

    jshint: {

      all: ['source/scripts/**/*.js']
    },

    // compress: {
    //   distro: {
    //     options: {
    //       archive: 'distro/zip/distro.zip'
    //     },
    //     expand: true,
    //     cwd: 'distro',
    //     src: ['**']
    //   }
    // },

    clean: {
      source:["source/lib",
              "source/css/lib"],
      distro:["distro"]
    },

    //*****************************************************

    // grunt-express will serve the files from the folders listed in `bases`
    // on specified `port` and `hostname`
    express: {
      all: {
        options: {
          port: 8080,
          hostname: "0.0.0.0",
          bases: ['source'], // Replace with the directory you want the files served from
                              // Make sure you don't use `.` or `..` in the path as Express
                              // is likely to return 403 Forbidden responses if you do
                              // http://stackoverflow.com/questions/14594121/express-res-sendfile-throwing-forbidden-error
          livereload: true
        }
      }
    },

    // grunt-watch will monitor the projects files
    watch: {
      all: {
        tasks: ['jshint:all','htmlbuild'],
        files: ['template/**/*.html',
                'source/views/**/*.html',
                'source/**/*.js',
                'source/config/**.js',
                'source/scripts/**/*.js',
                'source/css/**/**.css'],
        options: {
          livereload: true
        }
      }
    },

    // grunt-open will open your browser at the project's URL
    open: {
      all: {
        // Gets the port from the connect configuration
        path: 'http://localhost:<%= express.all.options.port%>'
      }
    }
  });

  // Creates the `swam` task
  grunt.registerTask('swam', [
    'clean:source',
    'bower',
    'htmlbuild:source',
    'express',
    'open',
    'watch'
  ]);

  grunt.registerTask('distro', [
    'clean:distro',
    'concat:css',
    'concat:js',
    'copy:index',
    'copy:views',
    'copy:svg',
    'uglify:distro',
    'cssmin:distro'
  ]);

};<commit_msg>changin tasks<commit_after>// Gruntfile with the configuration of grunt-express and grunt-open. No livereload yet!
module.exports = function(grunt) {

  // Load Grunt tasks declared in the package.json file
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  var scripts = {
        js: [],
        css: []
      };

  Object.keys(grunt.file.readJSON('./bower.json').dependencies).map(
        function(file) {
            scripts.js.push('source/lib/'+file+'.js');
        }
  );

  Object.keys(grunt.file.readJSON('./bower.json').dependencies).map(
        function(file) {
            scripts.css.push('source/css/lib/'+file+'.css');
        }
  );

  // Configure Grunt
  grunt.initConfig({

    htmlbuild: {
        source: {
            src: 'template/source/index.html',
            dest: 'source/index.html',
            options: {
                beautify: true,
                relative: true,
                scripts: {
                    bundle: [
                              scripts.js,
                              'source/lib/**/*.js',
                              'source/scripts/**/*.js'
                            ]
                },
                styles: {
                    bundle: [
                        'source/css/dist/css/bootstrap.css',
                        'source/css/attach.css',
                        scripts.css
                    ]
                },
                sections: {
                    layout: {
                        header: 'template/source/header.html',
                        footer: 'template/source/footer.html'
                    }
                },
            }
        },
        distro: {
            src: 'template/source/index.html',
            dest: 'distro/index.html',
            options: {
                scripts: {
                    bundle: [
                              'distro/js/**/*.js'
                            ]
                },
                styles: {
                    bundle: [
                        'distro/css/**/*.css'
                    ]
                },
                sections: {
                    layout: {
                        header: 'template/source/header.html',
                        footer: 'template/source/footer.html'
                    }
                },
            }
        }
    },

    uglify: {
      distro: {
        files: [{
            expand: true,
            cwd: 'distro/js',
            src: '**/*.js',
            dest: 'distro/js'
        }]
      }
    },

    cssmin: {
      distro: {
        files: [{
          expand: true,
          cwd: 'distro/css',
          src: '**/*.css',
          dest: 'distro/css',
        }]
      }
    },

    bower: {
      dev: {
        dest: 'source/',
        js_dest: 'source/lib',
        options: {
          ignorePackages: ['jquery','less'],
          packageSpecific: {
            'angular-material': {
              css_dest: 'source/css/lib/'
            },
            'ngStorage':{
              js_dest:'source/js/lib'
            }
          }
        }
      }
    },

    copy: {
      index: {
        expand: true,
        cwd: 'source/',
        src: 'index.html',
        dest: 'distro/',
      },
      views: {
        expand: true,
        cwd: 'source/views',
        src: '*.html',
        dest: 'distro/views',
      },
      scripts: {
        expand: true,
        cwd: 'source/scripts/',
        src: '**/*.js',
        dest: 'distro/scripts/',
      },
      svg: {
        expand: true,
        cwd: 'source/svg/',
        src: '*.svg',
        dest: 'distro/svg/'
      }
    },

    concat: {
      css:{
        src: ['source/css/attach.css',
              'source/css/lib/**/*.css'],
        dest: 'distro/css/distro.css'

      },
      js:{
        src:['source/lib/**/*.js',
            'source/scripts/**/*.js'],
        dest:'distro/js/distro.js'
      }
    },

    jshint: {

      all: ['source/scripts/**/*.js']
    },

    compress: {
      distro: {
        options: {
          archive: 'export/distro.zip'
        },
        expand: true,
        cwd: 'distro',
        src: ['**']
      }
    },

    clean: {
      source:["source/lib",
              "source/css/lib"],
      distro:["distro"]
    },

    //*****************************************************

    // grunt-express will serve the files from the folders listed in `bases`
    // on specified `port` and `hostname`
    express: {
      all: {
        options: {
          port: 8080,
          hostname: "0.0.0.0",
          bases: ['source'], // Replace with the directory you want the files served from
                              // Make sure you don't use `.` or `..` in the path as Express
                              // is likely to return 403 Forbidden responses if you do
                              // http://stackoverflow.com/questions/14594121/express-res-sendfile-throwing-forbidden-error
          livereload: true
        }
      }
    },

    // grunt-watch will monitor the projects files
    watch: {
      all: {
        tasks: ['jshint:all','htmlbuild'],
        files: ['template/**/*.html',
                'source/views/**/*.html',
                'source/**/*.js',
                'source/config/**.js',
                'source/scripts/**/*.js',
                'source/css/**/**.css'],
        options: {
          livereload: true
        }
      }
    },

    // grunt-open will open your browser at the project's URL
    open: {
      all: {
        // Gets the port from the connect configuration
        path: 'http://localhost:<%= express.all.options.port%>'
      }
    }
  });

  // Creates the `swam` task
  grunt.registerTask('swam', [
    'clean:source',
    'bower',
    'htmlbuild:source',
    'express',
    'open',
    'watch'
  ]);

  grunt.registerTask('distro', [
    'clean:distro',
    'concat:css',
    'concat:js',
    'copy:views',
    'copy:svg',
    'uglify:distro',
    'cssmin:distro',
    'htmlbuild:distro',
    'compress:distro'
  ]);

};<|endoftext|>


<commit_before>'use strict';

var peerhandler = angular.module('peerhandler', []);

peerhandler.factory('peerFactory', function($rootScope, $ionicPopup, $ionicHistory, $state, $timeout) {
    // PeerJS object representing the user
    var me                = null;

    // Stream object;
    var localStream       = null;

    // Stream sources
    var remoteVideoSource = null;
    var localVideoSource  = null;

    var currentCall   = null;

    // Private api
    var getLocalStream = function(successCallback) {
        if (localStream && successCallback) {
            successCallback(localStream)
        } else {
            navigator.webkitGetUserMedia(
                {
                    audio: true,
                    video: true
                },
                function (stream) {
                    localStream = stream;
                    setLocalStreamSrc(stream);
                    if (successCallback) {
                        successCallback(stream);
                    }
                },
                function(err){
                    console.log(err);
                }
            )
        }
    };

    var setRemoteStreamSrc = function (stream) {
        console.log('setting remote source!');
        remoteVideoSource = window.URL.createObjectURL(stream);
        console.log(remoteVideoSource);
    };

    var setLocalStreamSrc = function (stream) {
        console.log('setting local source!');
        localVideoSource = window.URL.createObjectURL(stream);
        console.log(localVideoSource);
    };

    var callAlertModal = function(reasonMessage) {
        var callEndedAlert = $ionicPopup.alert({
            title: 'Call over!',
            template: reasonMessage
        });
        callEndedAlert.then(function() {
            endCurrentCall();
            $ionicHistory.goBack();
        });

    };

    var answer = function(call) {
        call.on('stream', setRemoteStreamSrc);
        call.on('close', function() {
            callAlertModal('answercall');
        });

        call.answer(localStream);
    };

    // Public PeerJS api
    return {
        getMe: function() {
            if (!me) {return null;}
            return me;
        },
        getRemoteStreamSrc: function() {
            if (!remoteVideoSource) {console.log('No video remote source!')}
            return remoteVideoSource;
        },
        getLocalStreamSrc: function() {
            if (!localVideoSource) {console.log('No video remote source!')}
            return localVideoSource;
        },
        isConnected: function() {
            if (!me) {return false}
            else {return !me.disconnected}
        },
        connectToPeerJS: function(id)   {
            me = new Peer(id, $rootScope.config.peerjs);

            if (!me) {
              alert('Error creating peer!');
            }
            me.on('open', function(id) {
                console.log('Connection opened: ' + id);
            });

            me.on('call', function(mediaConnection) {
              console.log('Call initiated by ' + mediaConnection.peer );

                var confirmPopup = $ionicPopup.confirm({
                    title: 'Call from ' + mediaConnection.peer,
                    template: 'Incoming call. Answer?'
                });
                confirmPopup.then(function(res) {
                    console.log(res);
                    if(res) {
                        answer(mediaConnection);

                          $timeout(function() {
                            $state.go('call', {user: { displayName: mediaConnection.peer }});
                        }, 500)
                    } else {
                        mediaConnection.close();
                        return false;
                    }
                });
            });

            me.on('connection', function(dataConnection) {
                console.log('dataconnection formed!');
                console.log(dataConnection);
            });

            me.on('close', function() {
               console.log('closed Peerjs connection');
            });

            me.socket._socket.onopen = function() {
              getLocalStream();
            };

            me.on('error', function(error) {
              var errorMsg = error.toString();
              var errorAlert = $ionicPopup.alert({
                  title: 'Something went wrong!',
                  template: errorMsg
              });
             errorAlert.then(function(res) {
                 if (_.contains(errorMsg, 'Lost connection to server')) {
                     $state.go('login');
                 }
              });
            });
        },
        callPeer: function (userToCall) {
            if (!me) {
                console.log("Warning! no peerjs connection")
            };

            getLocalStream(function (stream) {
                currentCall = me.call(userToCall.number, stream, { metadata: me.id});
                currentCall.on('error', function (err) {
                    console.log('Call error');
                });

                currentCall.on('stream', function(stream) {
                    console.log('going to stream from call')
                    setRemoteStreamSrc(stream);

                    $timeout(function() {
                         $state.go('call', {user: userToCall});
                     }, 500)

                });

                currentCall.on('close', function() {
                    callAlertModal('owncall');
                    console.log('call closed');
                });
            });

        },
        endCurrentCall: function() {
            if (currentCall) {
                currentCall.close();
                currentCall = null;
            }
        },
        disconnectFromPeerJS: function() {
            if (me) {
                me.disconnect();
                me.destroy();
            } else {
                console.log("Warning! Attempted to disconnect without ")
            }
        }
    }
});
<commit_msg>Update peerhandler.js<commit_after>'use strict';

var peerhandler = angular.module('peerhandler', []);

peerhandler.factory('peerFactory', function($rootScope, $ionicPopup, $ionicHistory, $state, $timeout) {
    // PeerJS object representing the user
    var me                = null;

    // Stream object;
    var localStream       = null;

    // Stream sources
    var remoteVideoSource = null;
    var localVideoSource  = null;

    var currentCall   = null;

    // Private api
    var getLocalStream = function(successCallback) {
        if (localStream && successCallback) {
            successCallback(localStream)
        } else {
            navigator.webkitGetUserMedia(
                {
                    audio: true,
                    video: true
                },
                function (stream) {
                    localStream = stream;
                    setLocalStreamSrc(stream);
                    if (successCallback) {
                        successCallback(stream);
                    }
                },
                function(err){
                    console.log(err);
                }
            )
        }
    };

    var setRemoteStreamSrc = function (stream) {
        console.log('setting remote source!');
        remoteVideoSource = window.URL.createObjectURL(stream);
        console.log(remoteVideoSource);
    };

    var setLocalStreamSrc = function (stream) {
        console.log('setting local source!');
        localVideoSource = window.URL.createObjectURL(stream);
        console.log(localVideoSource);
    };

    var callAlertModal = function(reasonMessage) {
        var callEndedAlert = $ionicPopup.alert({
            title: 'Call over!',
            template: reasonMessage
        });
        callEndedAlert.then(function() {
            endCurrentCall();
            $ionicHistory.goBack();
        });

    };

    var answer = function(call) {
        call.on('stream', setRemoteStreamSrc);
        call.on('close', function() {
            callAlertModal('answercall');
        });

        call.answer(localStream);
    };

    // Public PeerJS api
    return {
        getMe: function() {
            if (!me) {return null;}
            return me;
        },
        getRemoteStreamSrc: function() {
            if (!remoteVideoSource) {console.log('No video remote source!')}
            return remoteVideoSource;
        },
        getLocalStreamSrc: function() {
            if (!localVideoSource) {console.log('No video remote source!')}
            return localVideoSource;
        },
        isConnected: function() {
            if (!me) {return false}
            else {return !me.disconnected}
        },
        connectToPeerJS: function(id)   {
            me = new Peer(id, $rootScope.config.peerjs);

            if (!me) {
              alert('Error creating peer!');
            }
            me.on('open', function(id) {
                console.log('Connection opened: ' + id);
            });

            me.on('call', function(mediaConnection) {
              console.log('Call initiated by ' + mediaConnection.peer );

                var confirmPopup = $ionicPopup.confirm({
                    title: 'Call from ' + mediaConnection.peer,
                    template: 'Incoming call. Answer?'
                });
                confirmPopup.then(function(res) {
                    console.log(res);
                    if(res) {
                        answer(mediaConnection);

                          $timeout(function() {
                            $state.go('call', {user: { displayName: mediaConnection.peer }});
                        }, 500)
                    } else {
                        mediaConnection.close();
                        return false;
                    }
                });
            });

            me.on('connection', function(dataConnection) {
                console.log('dataconnection formed!');
                console.log(dataConnection);
            });

            me.on('close', function() {
               console.log('closed Peerjs connection');
            });

            me.socket._socket.onopen = function() {
              getLocalStream();
            };

            me.on('error', function(error) {
              var errorMsg = error.toString();
              var errorAlert = $ionicPopup.alert({
                  title: 'Something went wrong!',
                  template: errorMsg
              });
             errorAlert.then(function(res) {
                 if (_.contains(errorMsg, 'Lost connection to server')) {
                     $state.go('login');
                 }
              });
            });
        },
        callPeer: function (userToCall) {
            if (!me) {
                console.log("Warning! no peerjs connection")
            };

            getLocalStream(function (stream) {
                currentCall = me.call(userToCall.number, stream, { metadata: me.id});
                currentCall.on('error', function (err) {
                    console.log('Call error');
                });

                currentCall.on('stream', function(stream) {
                    console.log('going to stream from call')
                    setRemoteStreamSrc(stream);

                    $timeout(function() {
                         $state.go('call', {user: userToCall});
                     }, 500)

                });

                currentCall.on('close', function() {
                    callAlertModal('owncall');
                    console.log('call closed');
                });
            });

        },
        endCurrentCall: function() {
            if (currentCall) {
                currentCall.close();
                currentCall = null;
            }
        },
        disconnectFromPeerJS: function() {
            if (me) {
                me.disconnect();
                me.destroy();
                me = null;
                endCurrentCall();
            } else {
                console.log("Warning! Attempted to disconnect without ")
            }
        }
    }
});
<|endoftext|>


<commit_before>var services = angular.module('services.request', ['ionic']);

services.factory('RequestService', function (AccountsService, $q, $window, $http) {

    var service = {

        token: false,

        request: function (method, url, data) {

            var deferred = $q.defer();

            var pro = AccountsService.getPro();

                // Get token wheather Pro or not
                var domain, host;

                if (pro === true || pro === "true") {
                    domain = "https://api.travis-ci.com";
                    host = "api.travis-ci.com";
                    console.log("REQUEST: IS PRO");
                } else if (pro === false || pro === "false") {
                    console.log("REQUEST: IS NOT PRO");
                    domain = "https://api.travis-ci.org";
                    host = "api.travis-ci.org";
                } else {
                    alert("ERROR. No domain. Pro is: " + pro);
                }

                var headers = {
                    'Accept': 'application/vnd.travis-ci.2+json',
                    // 'User-Agent': 'MyClient/1.0.0',
                    // 'Host': host,
                    // 'Content-Type': 'application/json',
                    // 'Content-Length': 37
                };

                if (url != "/auth/github") {
                    headers['Authorization'] = "token " + service.token;
                }

                if (url.indexOf("logs") > -1) {
                    headers['Accept'] = "text/plain";
                    console.log(headers);
                }

                $http({
                    url: domain + url,
                    method: method,
                    headers: headers,
                    data : data })
                    .success(function (data) {
                        // Success
                        deferred.resolve(data);
                    }).error(function (data){
                        // Failure
                        deferred.reject(data);
                    });

            return deferred.promise;

        }

    };

    return service;

});<commit_msg>Remove Log<commit_after>var services = angular.module('services.request', ['ionic']);

services.factory('RequestService', function (AccountsService, $q, $window, $http) {

    var service = {

        token: false,

        request: function (method, url, data) {

            var deferred = $q.defer();

            var pro = AccountsService.getPro();

                // Get token wheather Pro or not
                var domain, host;

                if (pro === true || pro === "true") {
                    domain = "https://api.travis-ci.com";
                    host = "api.travis-ci.com";
                    console.log("REQUEST: IS PRO");
                } else if (pro === false || pro === "false") {
                    console.log("REQUEST: IS NOT PRO");
                    domain = "https://api.travis-ci.org";
                    host = "api.travis-ci.org";
                } else {
                    alert("ERROR. No domain. Pro is: " + pro);
                }

                var headers = {
                    'Accept': 'application/vnd.travis-ci.2+json',
                    // 'User-Agent': 'MyClient/1.0.0',
                    // 'Host': host,
                    // 'Content-Type': 'application/json',
                    // 'Content-Length': 37
                };

                if (url != "/auth/github") {
                    headers['Authorization'] = "token " + service.token;
                }

                if (url.indexOf("logs") > -1) {
                    headers['Accept'] = "text/plain";
                }

                $http({
                    url: domain + url,
                    method: method,
                    headers: headers,
                    data : data })
                    .success(function (data) {
                        // Success
                        deferred.resolve(data);
                    }).error(function (data){
                        // Failure
                        deferred.reject(data);
                    });

            return deferred.promise;

        }

    };

    return service;

});<|endoftext|>


<commit_before>module.exports = {
  "botinfo" :
  {
    "auth" : "auth+live+xxxxxxxxxxxxxxxxxxxxxx",
    "userid" : "xxxxxxxxxxxxxxxxxxxxxx",
    "botname" : "boombot"
  },
  "roomid" : "xxxxxxxxxxxxxxxxxxxxxx",
  "admin" :
  {
    "userid" : "xxxxxxxxxxxxxxxxxxxxxx"
  },
  "queue" : true,
  "consolelog" : true,
  "moderatorControl" : true,
  "stats" : true,
  "responses" :
  {
    "rules" : "There is only one rule. I RULE! OK 2 rules: the lame button does exist, but don't ever touch it.You've been warned...",
    "botwelcome" : "WHO DARES SUMMON BOOMBOT?!",
    "adminwelcome" : "My master has arrived!",
    "modwelcome" : "Welcome back XXX.",
    "welcome" : "Welcome to the room XXX! Type /help to learn how to control me!",
    "welcomepm" : "Welcome to the room. Please read the rules. Or, don't and get thrown out.",
    "botdjmode" : "Aural destruction mode activated.",
    "masterdjmode" : "The Master has taken the stage! Bow before XXX!",
    "djmode" : "XXX has taken the stage to amuse my master."
  },
  "twitter" :
  {
    "tweet" : false,
    "consumer_key" : "xxxxxxxxxxxxxxxxxxxxxx",
    "consumer_secret" : "xxxxxxxxxxxxxxxxxxxxxx",
    "access_token_key" : "xxxxxxxxxxxxxxxxxxxxxx",
    "access_token_secret" : "xxxxxxxxxxxxxxxxxxxxxx"
  }
}<commit_msg>updated test fixture<commit_after>module.exports = {
  "botinfo" :
  {
    "auth" : "auth+live+xxxxxxxxxxxxxxxxxxxxxx",
    "userid" : "xxxxxxxxxxxxxxxxxxxxxx",
    "botname" : "boombot"
  },
  "roomid" : "xxxxxxxxxxxxxxxxxxxxxx",
  "admin" :
  {
    "userid" : "xxxxxxxxxxxxxxxxxxxxxx"
  },
  "queue" : true,
  "consolelog" : true,
  "moderatorControl" : true,
  "stats" : true,
  "responses" :
  {
    "rules": "There is only one rule. I RULE! OK 2 rules: the lame button does exist, but don't ever touch it.You've been warned...",
    "botwelcome": "WHO DARES SUMMON BOOMBOT?!",
    "adminwelcome": "My master has arrived!",
    "modwelcome": "Welcome back XXX.",
    "welcome": "Welcome to the room XXX! Type /help to learn how to control me!",
    "welcomepm": "Welcome to the room. Please read the rules. Or, don't and get thrown out.",
    "botdjmode": "Aural destruction mode activated.",
    "masterdjmode": "The Master has taken the stage! Bow before XXX!",
    "djmode": "XXX has taken the stage to amuse my master.",
    "qon": "Alright ladies and gents. Get in line, watch your step, no shirts or pants allowed.",
    "qoff": "FREE FOR ALL! THIS IS MADNESS! THIS IS SPARTA!",
    "onesong": "One song then GTFO the decks....",
    "twosongs": "Two songs then GTFO the decks....",
    "threesongs": "Three song then GTFO the decks....",
    "nolimit": "No limit to songs....",
    "emptyq": "No ones waiting.",
    "onstagealready": "Didn't notice you're on stage already?",
    "notinroom": "You can't join the queue if you're not in the room!",
    "alreadyinq": "You're already in the queue. Stop being greedy.....",
    "freeforall": "free for all, hop up!",
    "blacklisted": "You were blacklisted. Please don't come back.",
    "unnamedlame": "Ouch. Someone thinks you're lame.....",
    "namedlame": "XXXX thinks your song sucks..",
    "booteduser": "So glad they are gone.....",
    "autodjup": "Forget the whales! SAVE THE BEATS!",
    "autodjdown": "Looks like the rooms a rockin, I'll step down.",
    "notyourturn": "Not your turn @XXXX type q to see the order, or q+ to add yourself.",
    "djsteppeddown": "Everyone give it up for XXXX!"
  },
  "twitter" :
  {
    "tweet" : false,
    "consumer_key" : "xxxxxxxxxxxxxxxxxxxxxx",
    "consumer_secret" : "xxxxxxxxxxxxxxxxxxxxxx",
    "access_token_key" : "xxxxxxxxxxxxxxxxxxxxxx",
    "access_token_secret" : "xxxxxxxxxxxxxxxxxxxxxx"
  }
}<|endoftext|>


<commit_before>/**
 * React Native Playground
 * https://github.com/jsierles/rnplay
 */

'use strict';

var React = require('react-native');

var {
  ActivityIndicatorIOS,
  AppRegistry,
  StyleSheet,
  Text,
  ListView,
  View,
  Image,
  TouchableOpacity
} = React;

var ReactART = require('ReactIOSART');
var AppReloader = require('NativeModules').AppReloader;
var Camera = require('react-native-camera');
var Overlay = require('react-native-overlay');

var REQUEST_URL = 'http://rnplay.org/plays.json';

var RNPlayNative = React.createClass({
  getInitialState: function() {
    return {
      loaded: false,
      isModalOpen: false,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
    };
  },

  componentDidMount: function() {
    this.fetchApps();
  },

  fetchApps: function() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(data),
          loaded: true
        });
      })
      .done();
  },

  renderAppList: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.header}>React Native Playground</Text>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderApp}
          style={styles.listView}
        />
        <TouchableOpacity onPress={() => this.setState({isModalOpen: true})}>
          <Image style={styles.cameraButton} resizeMode="contain" source={require("image!photo-camera5")} />
        </TouchableOpacity>
        <Overlay isVisible={this.state.isModalOpen}>
          <Camera
            ref="cam"
            style={styles.container}
            onBarCodeRead={this.onBarCodeRead}>
            <TouchableOpacity onPress={() => this.setState({isModalOpen: false})}>
              <Text style={styles.cancelButton}>X</Text>
            </TouchableOpacity>
          </Camera>
        </Overlay>
      </View>
    );
  },

  renderApp: function(app) {
    return (
      <TouchableOpacity onPress={() => this.selectApp(app)}>
        <Text style={styles.app}>{app.name || app.module_name}</Text>
      </TouchableOpacity>
    );
  },

  selectApp: function(app) {
    console.log(app);
    AppReloader.reloadAppWithURLString(app.bundle_url, app.module_name);
  },

  renderLoading: function() {
    return (
      <View style={styles.container}>
        <ActivityIndicatorIOS size="large" />
      </View>
    );
  },

  onBarCodeRead(data) {
    if (!this.barCodeRead) {
      this.barCodeRead = true
      var appdata = JSON.parse(data.data)
      AppReloader.reloadAppWithURLString(appdata.url, appdata.module_name);
    }
  },

  render: function() {
    if (!this.state.loaded) {
      return this.renderLoading();
    } else {
      return this.renderAppList();
    }
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 30
  },
  cameraButton: {
    height: 60,
    width: 20,
    alignSelf: 'center',
    marginLeft: 5
  },
  cancelButton: {
    color: '#fff',
    flex: 1,
    fontSize: 25,
    marginLeft: 20
  },
  header: {
    textAlign: "center",
    fontSize: 25,
    paddingBottom: 20,
    color: '#888'
  },
  app: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: '#2B608A'
  }
});

AppRegistry.registerComponent('RNPlayNative', () => RNPlayNative);
<commit_msg>load a list of recent plays<commit_after>/**
 * React Native Playground
 * https://github.com/jsierles/rnplay
 */

'use strict';

var React = require('react-native');

var {
  ActivityIndicatorIOS,
  AppRegistry,
  StyleSheet,
  Text,
  ListView,
  View,
  Image,
  TouchableOpacity
} = React;

var ReactART = require('ReactNativeART');
var AppReloader = require('NativeModules').AppReloader;
var Camera = require('react-native-camera');
var Overlay = require('react-native-overlay');

var REQUEST_URL = 'http://rnplay.org/plays/public.json';

var RNPlayNative = React.createClass({
  getInitialState: function() {
    return {
      loaded: false,
      isModalOpen: false,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
    };
  },

  componentDidMount: function() {
    this.fetchApps();
  },

  fetchApps: function() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(data),
          loaded: true
        });
      })
      .done();
  },

  renderAppList: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.header}>React Native Playground</Text>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderApp}
          style={styles.listView}
        />
        <TouchableOpacity onPress={() => this.setState({isModalOpen: true})}>
          <Image style={styles.cameraButton} resizeMode="contain" source={require("image!photo-camera5")} />
        </TouchableOpacity>
        <Overlay isVisible={this.state.isModalOpen}>
          <Camera
            ref="cam"
            style={styles.container}
            onBarCodeRead={this.onBarCodeRead}>
            <TouchableOpacity onPress={() => this.setState({isModalOpen: false})}>
              <Text style={styles.cancelButton}>X</Text>
            </TouchableOpacity>
          </Camera>
        </Overlay>
      </View>
    );
  },

  renderApp: function(app) {
    return (
      <TouchableOpacity onPress={() => this.selectApp(app)}>
        <Text style={styles.app}>{app.name || app.module_name}</Text>
      </TouchableOpacity>
    );
  },

  selectApp: function(app) {
    console.log(app);
    AppReloader.reloadAppWithURLString(app.bundle_url, app.module_name);
  },

  renderLoading: function() {
    return (
      <View style={styles.container}>
        <ActivityIndicatorIOS size="large" />
      </View>
    );
  },

  onBarCodeRead(data) {
    if (!this.barCodeRead) {
      this.barCodeRead = true
      var appdata = JSON.parse(data.data)
      AppReloader.reloadAppWithURLString(appdata.url, appdata.module_name);
    }
  },

  render: function() {
    if (!this.state.loaded) {
      return this.renderLoading();
    } else {
      return this.renderAppList();
    }
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 30
  },
  cameraButton: {
    height: 60,
    width: 20,
    alignSelf: 'center',
    marginLeft: 5
  },
  cancelButton: {
    color: '#fff',
    flex: 1,
    fontSize: 25,
    marginLeft: 20
  },
  header: {
    textAlign: "center",
    fontSize: 25,
    paddingBottom: 20,
    color: '#888'
  },
  app: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: '#2B608A'
  }
});

AppRegistry.registerComponent('RNPlayNative', () => RNPlayNative);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Sankarsan Kampa
 *                    https://sankarsankampa.com/contact
 *
 * This file is a part of Bastion Discord BOT.
 *                        https://github.com/snkrsnkampa/Bastion
 *
 * This code is licensed under the SNKRSN Shared License. It is free to
 * download, copy, compile, use, study and refer under the terms of the
 * SNKRSN Shared License. You can modify the code only for personal or
 * internal use only. However, you can not redistribute the code without
 * explicitly getting permission fot it.
 *
 * Bastion BOT is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY. See the SNKRSN Shared License for
 * more details.
 *
 * You should have received a copy of the SNKRSN Shared License along
 * with this program. If not, see <https://github.com/snkrsnkampa/Bastion/LICENSE>.
 */

const imdb = require('imdb-api');

exports.run = function(Bastion, message, args) {
  imdb.get(args.join(' '), (err, movie) => {
    if(err) return message.channel.sendMessage('', {embed: {
      color: 13380644,
      description: `No movie or TV series found with the name **${args.join(' ')}**. Please check the name and try again. Type \`${Bastion.config.prefix}help imdb\` for help on imdb command.`
    }}).catch(e => {
      Bastion.log.error(e.stack);
    });
    message.channel.sendMessage('', {embed: {
      color: 6651610,
      title: movie.series ? `${movie.title} (TV Series)` : movie.title,
      url: movie.imdburl,
      description: movie.plot,
      fields: [
        {
          name: 'Genre',
          value: movie.genres,
          inline: true
        },
        {
          name: 'Release',
          value: movie.released.toDateString(),
          inline: true
        },
        {
          name: 'Duration',
          value: movie.runtime,
          inline: true
        },
        {
          name: 'Rated',
          value: movie.rated,
          inline: true
        },
        {
          name: 'Rating',
          value: movie.rating,
          inline: true
        },
        {
          name: 'Votes',
          value: movie.votes,
          inline: true
        },
        {
          name: 'Awards',
          value: movie.awards.split(', ').join('\n'),
          inline: true
        },
        {
          name: 'Starring',
          value: movie.actors.split(', ').join('\n'),
          inline: true
        },
        {
          name: 'Directors',
          value: movie.director.split(', ').join('\n'),
          inline: true
        }
      ],
      image: {
        url: movie.poster
      },
      footer: {
        icon_url: 'https://pbs.twimg.com/profile_images/780796992611942405/qj7ytv9v.jpg',
        text: 'Powered by IMDb'
      }
    }}).catch(e => {
      Bastion.log.error(e.stack);
    });
  });
};

exports.conf = {
  aliases: []
};

exports.help = {
  name: 'imdb',
  description: 'Shows details of a movie or a TV series.',
  permission: '',
  usage: 'imdb <movie/tv series>',
  example: ['imdb Snowden', 'imdb The Blacklist']
};
<commit_msg>Fixed issue with imdb if the movie has no image<commit_after>/*
 * Copyright (C) 2017 Sankarsan Kampa
 *                    https://sankarsankampa.com/contact
 *
 * This file is a part of Bastion Discord BOT.
 *                        https://github.com/snkrsnkampa/Bastion
 *
 * This code is licensed under the SNKRSN Shared License. It is free to
 * download, copy, compile, use, study and refer under the terms of the
 * SNKRSN Shared License. You can modify the code only for personal or
 * internal use only. However, you can not redistribute the code without
 * explicitly getting permission fot it.
 *
 * Bastion BOT is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY. See the SNKRSN Shared License for
 * more details.
 *
 * You should have received a copy of the SNKRSN Shared License along
 * with this program. If not, see <https://github.com/snkrsnkampa/Bastion/LICENSE>.
 */

const imdb = require('imdb-api');

exports.run = function(Bastion, message, args) {
  imdb.get(args.join(' '), (err, movie) => {
    if(err) return message.channel.sendMessage('', {embed: {
      color: 13380644,
      description: `No movie or TV series found with the name **${args.join(' ')}**. Please check the name and try again. Type \`${Bastion.config.prefix}help imdb\` for help on imdb command.`
    }}).catch(e => {
      Bastion.log.error(e.stack);
    });
    message.channel.sendMessage('', {embed: {
      color: 6651610,
      title: movie.series ? `${movie.title} (TV Series)` : movie.title,
      url: movie.imdburl,
      description: movie.plot,
      fields: [
        {
          name: 'Genre',
          value: movie.genres,
          inline: true
        },
        {
          name: 'Release',
          value: movie.released.toDateString(),
          inline: true
        },
        {
          name: 'Duration',
          value: movie.runtime,
          inline: true
        },
        {
          name: 'Rated',
          value: movie.rated,
          inline: true
        },
        {
          name: 'Rating',
          value: movie.rating,
          inline: true
        },
        {
          name: 'Votes',
          value: movie.votes,
          inline: true
        },
        {
          name: 'Awards',
          value: movie.awards.split(', ').join('\n'),
          inline: true
        },
        {
          name: 'Starring',
          value: movie.actors.split(', ').join('\n'),
          inline: true
        },
        {
          name: 'Directors',
          value: movie.director.split(', ').join('\n'),
          inline: true
        }
      ],
      image: {
        url: movie.poster != 'N/A' ? movie.poster : 'https://pbs.twimg.com/profile_images/780796992611942405/qj7ytv9v.jpg'
      },
      footer: {
        icon_url: 'https://pbs.twimg.com/profile_images/780796992611942405/qj7ytv9v.jpg',
        text: 'Powered by IMDb'
      }
    }}).catch(e => {
      Bastion.log.error(e.stack);
    });
  });
};

exports.conf = {
  aliases: []
};

exports.help = {
  name: 'imdb',
  description: 'Shows details of a movie or a TV series.',
  permission: '',
  usage: 'imdb <movie/tv series>',
  example: ['imdb Snowden', 'imdb The Blacklist']
};
<|endoftext|>


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

    /**
     * @ngdoc controller
     * @name data-prep.datagrid.preview:DatasetPreviewCtrl
     * @description Dataset preview grid controller.
     * @requires data-prep.services.dataset.service:DatasetRestService
     */
    function DatasetPreviewCtrl($scope,$state,$log,$stateParams,DatasetRestService) {

        var self = this;
        self.datasetid=
        self.visible = false;
        self.metadata;
        self.selectedSheetName;
        self.records;
        self.columns;

        self.close = function() {
          $state.go('nav.home.datasets');
        };

        self.updateSheetName = function(){
          return DatasetRestService.getContent(self.datasetid, true,true,self.selectedSheetName)
              .then(function(data) {
                      drawGrid(data)
                    });
        };

        self.updateDataset = function(){
          $log.debug('updateDataset');
          DatasetRestService.update();
        };

        var drawGrid = function(data){
          self.metadata = data.metadata;
          self.selectedSheetName=data.metadata.sheetName;

          var options = {
            enableColumnReorder: false,
            editable: false,
            enableAddRow: false,
            enableCellNavigation: true,
            enableTextSelectionOnCells: false
          };

          self.columns = [];
          angular.forEach(data.columns, function(value, key) {
            this.push({id: value.id, name: value.id, field: value.id});
          }, self.columns);
          self.records=data.records;
          var grid = new Slick.Grid( $('#previewdatagrid'), self.records, self.columns, options);
          self.visible=true;
        };

        var loadPreview = function(){
            if($stateParams.datasetid) {
                self.datasetid = $stateParams.datasetid;
                return DatasetRestService.getContent(self.datasetid, true,true)
                    .then(function(data) {
                            drawGrid(data)
                          });
            }

        };

        loadPreview();

    }

    Object.defineProperty(DatasetPreviewCtrl.prototype,
                          'showPreview', {
            enumerable: true,
            configurable: false,
            get: function () {
                return this.visible;
            },
            set: function(value) {
                this.visible = value;
            }
        });

    angular.module('data-prep.dataset-preview')
        .controller('DatasetPreviewCtrl', DatasetPreviewCtrl);

})();<commit_msg>add js doc<commit_after>(function() {
    'use strict';

    /**
     * @ngdoc controller
     * @name data-prep.datagrid.preview:DatasetPreviewCtrl
     * @description Dataset preview grid controller.
     * @requires data-prep.services.dataset.service:DatasetRestService
     */
    function DatasetPreviewCtrl($scope,$state,$log,$stateParams,DatasetRestService) {

        var self = this;
        self.datasetid;
        self.visible = false;
        self.metadata;
        self.selectedSheetName;
        self.records;
        self.columns;
        self.grid;

        /**
         * @ngdoc method
         * @name close
         * @methodOf data-prep.dataset-list.controller:DatasetPreviewCtrl
         * @description triggered on closing dataset preview modal to to /datasets view
         */
        self.close = function() {
          $state.go('nav.home.datasets');
        };

        /**
         * @ngdoc method
         * @name updateSheetName
         * @methodOf data-prep.dataset-list.controller:DatasetPreviewCtrl
         * @description triggered on sheet name change (trigger redisplaying preview grid)
         */
        self.updateSheetName = function(){
          return DatasetRestService.getContent(self.datasetid, true,true,self.selectedSheetName)
              .then(function(data) {
                      drawGrid(data)
                    });
        };

        /**
         * @ngdoc method
         * @name updateDataset
         * @methodOf data-prep.dataset-list.controller:DatasetPreviewCtrl
         * @description responsible for sending update dataset rest call to the backend
         */
        self.updateDataset = function(){
          $log.debug('updateDataset');
          DatasetRestService.update();
        };

        /**
         * @ngdoc method
         * @name drawGrid
         * @methodOf data-prep.dataset-list.controller:DatasetPreviewCtrl
         * @description [PRIVATE] draw the slick grid for data preview
         */
        var drawGrid = function(data){
          self.metadata = data.metadata;
          self.selectedSheetName=data.metadata.sheetName;

          var options = {
            enableColumnReorder: false,
            editable: false,
            enableAddRow: false,
            enableCellNavigation: true,
            enableTextSelectionOnCells: false
          };

          self.columns = [];
          angular.forEach(data.columns, function(value, key) {
            this.push({id: value.id, name: value.id, field: value.id});
          }, self.columns);
          self.records=data.records;
          self.grid = new Slick.Grid( $('#previewdatagrid'), self.records, self.columns, options);
          self.visible=true;
        };

        /**
         * @ngdoc method
         * @name loadPreview
         * @methodOf data-prep.dataset-list.controller:DatasetPreviewCtrl
         * @description [PRIVATE] find the dataset id in params then trigged grid draw
         */
        var loadPreview = function(){
            if($stateParams.datasetid) {
                self.datasetid = $stateParams.datasetid;
                return DatasetRestService.getContent(self.datasetid, true,true)
                    .then(function(data) {
                            drawGrid(data)
                          });
            }

        };

        // load the preview
        loadPreview();

    }

    Object.defineProperty(DatasetPreviewCtrl.prototype,
                          'showPreview', {
            enumerable: true,
            configurable: false,
            get: function () {
                return this.visible;
            },
            set: function(value) {
                this.visible = value;
            }
        });

    angular.module('data-prep.dataset-preview')
        .controller('DatasetPreviewCtrl', DatasetPreviewCtrl);

})();<|endoftext|>


<commit_before>#!/usr/bin/env node
// module: buffer-stream, method: parse

const BufferStream = require('../').BufferStream;
<commit_msg>fix buffer breakup example<commit_after>#!/usr/bin/env node
// module: buffer-stream, method: parse

const BufferStream = require('../').BufferStream;

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

fs.createReadStream(path.resolve(__dirname, "./data/in-nasdaq.bin"))           // read input data
    .pipe(new BufferStream())                                                   // pipe to the transforming stream
    .breakup(13)                                                                // breakup into 13-byte chunks (remember! this is an Object stream!)
    .on("data", (data) => {
        console.log("data.length should be at most 13 and is", data.length);
    })
    .on("error",
        (e) => {
            console.error(e && e.stack);
            process.exit(100);
        }
    );
<|endoftext|>