<commit_before>(function() {
    // Get application context
    var app = Sammy.apps['#main'];
    var store = app.store;

    /**
     * Helpers
     *
     */
    app.helpers({

        // Serialize an object
        serialize : function(obj) {
          var str = [];
          for(var p in obj)
            if (obj.hasOwnProperty(p)) {
              str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
          return str.join("&");
        },

        // Flash helper to diplay instant notifications
        flash: function (level, message) {
            if (!store.get('flash')) {
                store.set('flash', true);
            }

            // Helper CSS class on main wrapper
            $('#slider').addClass('with-flashMessage');

            // If the line is a bash command
            if (level === 'info' && message.charAt(0) === '+') {
                level = 'log';
            }

            $('#flashMessage .messages')
                .prepend('
'+
                              '
'+ message +'

');
        },

        checkInstall: function(callback) {
            domain = window.location.hostname;
            $.ajax({
                dataType: "json",
                url: 'https://'+ domain +'/yunohost/api/installed',
                timeout: 3000
            })
            .success(function(data) {
                callback(data.installed);
            })
            .fail(function() {
                callback(undefined);
            });
        },

        // API call
        api: function(uri, callback, method, data, websocket) {
            c = this;

            call = function(uri, callback, method, data) {
                method = typeof method !== 'undefined' ? method : 'GET';
                data   = typeof data   !== 'undefined' ? data   : {};
                if (window.navigator && window.navigator.language && (typeof data.locale === 'undefined')) {
                    data.locale = y18n.locale || window.navigator.language.substr(0, 2);
                }

                var args = data;
                if (uri === '/postinstall') {
                    var installing = false;
                    setInterval(function () {
                        installing = true;
                    }, 1500);
                }

                loaded = false;
                if ($('div.loader').length === 0) {
                    $('#main').append('

');
                }

                jQuery.ajax({
                    url: 'https://'+ store.get('url') + uri,
                    type: method,
                    crossdomain: true,
                    data: data,
                    traditional: true,
                    dataType: 'json'
                })
                .always(function(xhr, ts, error) {
                })
                .done(function(data) {
                    data = data || {};
                    callback(data);
                })
                .fail(function(xhr) {
                    if (xhr.status == 200) {
                        // Fail with 200, WTF
                        callback({});
                    } else if (xhr.status == 401) {
                        if (uri === '/login') {
                            c.flash('fail', y18n.t('wrong_password'));
                        } else {
                            c.flash('fail', y18n.t('unauthorized'));
                            c.redirect('#/login');
                        }
                    } else if (typeof xhr.responseJSON !== 'undefined') {
                        c.flash('fail', xhr.responseJSON.error);
                    } else if (typeof xhr.statusText !== 'undefined' && uri !== '/postinstall') {
                        var errorMessage = xhr.status+' '+xhr.statusText;
                        // If some more text is available, display it to user.
                        if (typeof xhr.responseText !== 'undefined') {
                            errorMessage += ' - ' + xhr.responseText;
                        }
                        c.flash('fail', y18n.t('api_not_responding', [errorMessage]));
                    } else {
                        if (uri === '/postinstall') {
                            if (installing) {
                                interval = window.location.hostname === args.domain ? 20000 : 5000;
                                checkInstall = setInterval(function () {
                                    c.checkInstall(function(isInstalled) {
                                        if (isInstalled || typeof isInstalled === 'undefined') {
                                            c.flash('success', y18n.t('installation_complete'));
                                            clearInterval(checkInstall);
                                            window.location.href = 'https://'+ window.location.hostname +'/yunohost/admin/';
                                        }
                                    });
                                }, interval);
                            } else {
                                c.flash('fail', y18n.t('error_occured'));
                            }
                        } else {
                            c.flash('fail', y18n.t('error_server'));
                        }
                    }
                    if (uri !== '/postinstall') {
                        store.clear('slide');
                        c.redirect(store.get('path-1'));
                    }
                });
            };

            websocket = typeof websocket !== 'undefined' ? websocket : true;
            if (websocket) {

                // Open a WebSocket connection to retrieve live messages from the moulinette
                ws = new WebSocket('wss://'+ store.get('url') +'/messages');
                ws.onmessage = function(evt) {
                    // console.log(evt.data);
                    $.each($.parseJSON(evt.data), function(k, v) {
                        c.flash(k, v);
                    });
                };

                // If not connected, WebSocket connection will raise an error, but we do not want to interrupt API request
                ws.onerror = ws.onopen;

                ws.onclose = function() {};

                ws.onopen = call(uri, callback, method, data);
            } else {
                call(uri, callback, method, data);
            }

        },

        // Render view (cross-browser)
        view: function (view, data, callback, enableSlide) {
            callback = typeof callback !== 'undefined' ? callback : function() {};
            rendered = this.render('views/'+ view +'.ms', data);

            enableSlide = (typeof enableSlide !== 'undefined') ? enableSlide : true; // Change to false to disable animation

            loaded = true;
            $('div.loader').remove();
            $('#modal').modal('hide');

            if (enableSlide) {
                var leSwap = function() {
                    rendered.swap(function() {
                        $('.slide, .btn-breadcrumb a:not(:last-child)').on('click', function() {
                            $(this).addClass('active');
                            if ($(this).hasClass('back') || $(this).parent('.btn-breadcrumb').length) {
                                store.set('slide', 'back');
                            } else {
                                store.set('slide', 'to');
                            }
                        });
                        callback();
                        // Force scrollTop on page load
                        $('html, body').scrollTop(0);

                        // Resize body after the animation finishes (0.2s css transition)
                        // https://github.com/YunoHost/yunohost-admin/blob/231aac076a3aa836409b0d33fe02e48975990b7a/src/css/style.less#L92
                        setTimeout(function() {
                            $('body').resize();
                        }, 210);
                    });
                };

                blockSize = $('#slider').width();

                // Slide back effect
                if (store.get('slide') == 'back') {
                    store.clear('slide');
                    $('#slideBack').css('display', 'none');
                    $('#slider-container').removeClass('move').css('margin-left', '-'+ blockSize +'px');
                    $('#slideTo').show().html($('#main').html());
                    leSwap();
                    $('#slider-container').addClass('move').css('margin-left', '0px');

                // Slide to effect
                } else if (store.get('slide') == 'to') {
                    store.clear('slide');
                    $('#slideTo').css('display', 'none');
                    $('#slider-container').removeClass('move').css('margin-left', '-'+ blockSize +'px');
                    $('#slider-container').removeClass('move').css('margin-left', '0px');
                    $('#slideBack').show().html($('#main').html());
                    leSwap();
                    $('#slider-container').addClass('move').css('margin-left', '-'+ blockSize +'px');

                } else {
                    leSwap();
                }
            } else {
                rendered.swap(function(){
                    callback();
                    // Force scrollTop on page load
                    $('html, body').scrollTop(0);
                    $('body').resize();
                });
            }
        },

        confirm: function(title, content, confirmCallback, cancelCallback) {
            // Default callbacks
            confirmCallback = typeof confirmCallback !== 'undefined' ? confirmCallback : function() {};
            cancelCallback = typeof cancelCallback !== 'undefined' ? cancelCallback : function() {};

            // Get modal element
            box = $('#modal');

            // Modal title
            if (typeof title === 'string' && title.length) {
                $('.title', box).html(title);
            }
            else {
                box.addClass('no-title');
            }

            // Modal content
            $('.content', box).html(content);

            // Handle buttons
            $('footer button', box)
                .click(function(e){
                    e.preventDefault();

                    $('#modal footer button').unbind( "click" );
                    // Reset & Hide modal
                    box
                        .removeClass('no-title')
                        .modal('hide');

                    // Do corresponding callback
                    if ($(this).data('action') == 'confirm') {
                        confirmCallback();
                    }
                    else {
                        cancelCallback();
                    }
                });

            // Show modal
            return box.modal('show');
        },

        arraySortById: function(arr) {
            arr.sort(function(a, b){
                if (a.id > b.id) {
                    return 1;
                }
                else if (a.id < b.id) {
                    return -1;
                }
                return 0;
            });
        },

        arrayDiff: function(arr1, arr2) {
            arr1 = arr1 || [];
            arr2 = arr2 || [];
            return arr1.filter(function (a) {
                return ((arr2.indexOf(a) == -1) && (a !== ""));
            });
        },

        groupHooks: function(hooks) {
            data={};
            var rules=[
                {
                    id:'configuration',
                    isIn:function (hook) {
                        return hook.indexOf('conf_')==0
                    }
                }
            ];

            $.each(hooks, function(i, hook) {
                var group_id=hook;
                $.each(rules, function(i, rule) {
                    if (rule.isIn(hook)) {
                        group_id = 'adminjs_group_'+rule.id;
                        return false;
                    }
                });

                if(group_id in data) {
                    data[group_id] = {
                        name:y18n.t('hook_'+group_id),
                        value:data[group_id].value+','+hook,
                        description:data[group_id].description+', '+y18n.t('hook_'+hook)
                    };
                }
                else {
                    data[group_id] = {
                        name:y18n.t('hook_'+group_id),
                        value:hook,
                        description:(group_id==hook)?y18n.t('hook_'+hook+'_desc'):y18n.t('hook_'+hook)
                    };
                }
            });
            return data;
        },

        ungroupHooks: function(hooks,apps) {
            var data={};
            data['apps'] = apps || [];
            data['hooks'] = hooks || [];

            if (data['hooks'].constructor !== Array) {
                data['hooks'] = [data['hooks']];
            }
            if (data['apps'].constructor !== Array) {
                data['apps'] = [data['apps']];
            }

            if (data['hooks'].length == 0) {
                data['ignore_hooks'] = '';
            }
            if (data['apps'].length == 0) {
                data['ignore_apps'] = '';
            }

            // Some hook value contains multiple hooks separated by commas
            var split_hooks = [];
            $.each(data['hooks'], function(i, hook) {
                split_hooks = split_hooks.concat(hook.split(','));
            });
            data['hooks'] = split_hooks;

            return data;
        },
    });

})();<commit_msg>[enh] Scroll to Top to view new messages.<commit_after>(function() {
    // Get application context
    var app = Sammy.apps['#main'];
    var store = app.store;

    /**
     * Helpers
     *
     */
    app.helpers({

        // Serialize an object
        serialize : function(obj) {
          var str = [];
          for(var p in obj)
            if (obj.hasOwnProperty(p)) {
              str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
          return str.join("&");
        },

        // Flash helper to diplay instant notifications
        flash: function (level, message) {
            if (!store.get('flash')) {
                store.set('flash', true);
            }

            // Helper CSS class on main wrapper
            $('#slider').addClass('with-flashMessage');

            // If the line is a bash command
            if (level === 'info' && message.charAt(0) === '+') {
                level = 'log';
            }

            // Add message
            $('#flashMessage .messages')
                .prepend('
'+
                              '
'+ message +'

');

            // Scroll to top to view new messages
            $('#flashMessage').scrollTop(0);
        },

        checkInstall: function(callback) {
            domain = window.location.hostname;
            $.ajax({
                dataType: "json",
                url: 'https://'+ domain +'/yunohost/api/installed',
                timeout: 3000
            })
            .success(function(data) {
                callback(data.installed);
            })
            .fail(function() {
                callback(undefined);
            });
        },

        // API call
        api: function(uri, callback, method, data, websocket) {
            c = this;

            call = function(uri, callback, method, data) {
                method = typeof method !== 'undefined' ? method : 'GET';
                data   = typeof data   !== 'undefined' ? data   : {};
                if (window.navigator && window.navigator.language && (typeof data.locale === 'undefined')) {
                    data.locale = y18n.locale || window.navigator.language.substr(0, 2);
                }

                var args = data;
                if (uri === '/postinstall') {
                    var installing = false;
                    setInterval(function () {
                        installing = true;
                    }, 1500);
                }

                loaded = false;
                if ($('div.loader').length === 0) {
                    $('#main').append('

');
                }

                jQuery.ajax({
                    url: 'https://'+ store.get('url') + uri,
                    type: method,
                    crossdomain: true,
                    data: data,
                    traditional: true,
                    dataType: 'json'
                })
                .always(function(xhr, ts, error) {
                })
                .done(function(data) {
                    data = data || {};
                    callback(data);
                })
                .fail(function(xhr) {
                    if (xhr.status == 200) {
                        // Fail with 200, WTF
                        callback({});
                    } else if (xhr.status == 401) {
                        if (uri === '/login') {
                            c.flash('fail', y18n.t('wrong_password'));
                        } else {
                            c.flash('fail', y18n.t('unauthorized'));
                            c.redirect('#/login');
                        }
                    } else if (typeof xhr.responseJSON !== 'undefined') {
                        c.flash('fail', xhr.responseJSON.error);
                    } else if (typeof xhr.statusText !== 'undefined' && uri !== '/postinstall') {
                        var errorMessage = xhr.status+' '+xhr.statusText;
                        // If some more text is available, display it to user.
                        if (typeof xhr.responseText !== 'undefined') {
                            errorMessage += ' - ' + xhr.responseText;
                        }
                        c.flash('fail', y18n.t('api_not_responding', [errorMessage]));
                    } else {
                        if (uri === '/postinstall') {
                            if (installing) {
                                interval = window.location.hostname === args.domain ? 20000 : 5000;
                                checkInstall = setInterval(function () {
                                    c.checkInstall(function(isInstalled) {
                                        if (isInstalled || typeof isInstalled === 'undefined') {
                                            c.flash('success', y18n.t('installation_complete'));
                                            clearInterval(checkInstall);
                                            window.location.href = 'https://'+ window.location.hostname +'/yunohost/admin/';
                                        }
                                    });
                                }, interval);
                            } else {
                                c.flash('fail', y18n.t('error_occured'));
                            }
                        } else {
                            c.flash('fail', y18n.t('error_server'));
                        }
                    }
                    if (uri !== '/postinstall') {
                        store.clear('slide');
                        c.redirect(store.get('path-1'));
                    }
                });
            };

            websocket = typeof websocket !== 'undefined' ? websocket : true;
            if (websocket) {

                // Open a WebSocket connection to retrieve live messages from the moulinette
                ws = new WebSocket('wss://'+ store.get('url') +'/messages');
                ws.onmessage = function(evt) {
                    // console.log(evt.data);
                    $.each($.parseJSON(evt.data), function(k, v) {
                        c.flash(k, v);
                    });
                };

                // If not connected, WebSocket connection will raise an error, but we do not want to interrupt API request
                ws.onerror = ws.onopen;

                ws.onclose = function() {};

                ws.onopen = call(uri, callback, method, data);
            } else {
                call(uri, callback, method, data);
            }

        },

        // Render view (cross-browser)
        view: function (view, data, callback, enableSlide) {
            callback = typeof callback !== 'undefined' ? callback : function() {};
            rendered = this.render('views/'+ view +'.ms', data);

            enableSlide = (typeof enableSlide !== 'undefined') ? enableSlide : true; // Change to false to disable animation

            loaded = true;
            $('div.loader').remove();
            $('#modal').modal('hide');

            if (enableSlide) {
                var leSwap = function() {
                    rendered.swap(function() {
                        $('.slide, .btn-breadcrumb a:not(:last-child)').on('click', function() {
                            $(this).addClass('active');
                            if ($(this).hasClass('back') || $(this).parent('.btn-breadcrumb').length) {
                                store.set('slide', 'back');
                            } else {
                                store.set('slide', 'to');
                            }
                        });
                        callback();
                        // Force scrollTop on page load
                        $('html, body').scrollTop(0);

                        // Resize body after the animation finishes (0.2s css transition)
                        // https://github.com/YunoHost/yunohost-admin/blob/231aac076a3aa836409b0d33fe02e48975990b7a/src/css/style.less#L92
                        setTimeout(function() {
                            $('body').resize();
                        }, 210);
                    });
                };

                blockSize = $('#slider').width();

                // Slide back effect
                if (store.get('slide') == 'back') {
                    store.clear('slide');
                    $('#slideBack').css('display', 'none');
                    $('#slider-container').removeClass('move').css('margin-left', '-'+ blockSize +'px');
                    $('#slideTo').show().html($('#main').html());
                    leSwap();
                    $('#slider-container').addClass('move').css('margin-left', '0px');

                // Slide to effect
                } else if (store.get('slide') == 'to') {
                    store.clear('slide');
                    $('#slideTo').css('display', 'none');
                    $('#slider-container').removeClass('move').css('margin-left', '-'+ blockSize +'px');
                    $('#slider-container').removeClass('move').css('margin-left', '0px');
                    $('#slideBack').show().html($('#main').html());
                    leSwap();
                    $('#slider-container').addClass('move').css('margin-left', '-'+ blockSize +'px');

                } else {
                    leSwap();
                }
            } else {
                rendered.swap(function(){
                    callback();
                    // Force scrollTop on page load
                    $('html, body').scrollTop(0);
                    $('body').resize();
                });
            }
        },

        confirm: function(title, content, confirmCallback, cancelCallback) {
            // Default callbacks
            confirmCallback = typeof confirmCallback !== 'undefined' ? confirmCallback : function() {};
            cancelCallback = typeof cancelCallback !== 'undefined' ? cancelCallback : function() {};

            // Get modal element
            box = $('#modal');

            // Modal title
            if (typeof title === 'string' && title.length) {
                $('.title', box).html(title);
            }
            else {
                box.addClass('no-title');
            }

            // Modal content
            $('.content', box).html(content);

            // Handle buttons
            $('footer button', box)
                .click(function(e){
                    e.preventDefault();

                    $('#modal footer button').unbind( "click" );
                    // Reset & Hide modal
                    box
                        .removeClass('no-title')
                        .modal('hide');

                    // Do corresponding callback
                    if ($(this).data('action') == 'confirm') {
                        confirmCallback();
                    }
                    else {
                        cancelCallback();
                    }
                });

            // Show modal
            return box.modal('show');
        },

        arraySortById: function(arr) {
            arr.sort(function(a, b){
                if (a.id > b.id) {
                    return 1;
                }
                else if (a.id < b.id) {
                    return -1;
                }
                return 0;
            });
        },

        arrayDiff: function(arr1, arr2) {
            arr1 = arr1 || [];
            arr2 = arr2 || [];
            return arr1.filter(function (a) {
                return ((arr2.indexOf(a) == -1) && (a !== ""));
            });
        },

        groupHooks: function(hooks) {
            data={};
            var rules=[
                {
                    id:'configuration',
                    isIn:function (hook) {
                        return hook.indexOf('conf_')==0
                    }
                }
            ];

            $.each(hooks, function(i, hook) {
                var group_id=hook;
                $.each(rules, function(i, rule) {
                    if (rule.isIn(hook)) {
                        group_id = 'adminjs_group_'+rule.id;
                        return false;
                    }
                });

                if(group_id in data) {
                    data[group_id] = {
                        name:y18n.t('hook_'+group_id),
                        value:data[group_id].value+','+hook,
                        description:data[group_id].description+', '+y18n.t('hook_'+hook)
                    };
                }
                else {
                    data[group_id] = {
                        name:y18n.t('hook_'+group_id),
                        value:hook,
                        description:(group_id==hook)?y18n.t('hook_'+hook+'_desc'):y18n.t('hook_'+hook)
                    };
                }
            });
            return data;
        },

        ungroupHooks: function(hooks,apps) {
            var data={};
            data['apps'] = apps || [];
            data['hooks'] = hooks || [];

            if (data['hooks'].constructor !== Array) {
                data['hooks'] = [data['hooks']];
            }
            if (data['apps'].constructor !== Array) {
                data['apps'] = [data['apps']];
            }

            if (data['hooks'].length == 0) {
                data['ignore_hooks'] = '';
            }
            if (data['apps'].length == 0) {
                data['ignore_apps'] = '';
            }

            // Some hook value contains multiple hooks separated by commas
            var split_hooks = [];
            $.each(data['hooks'], function(i, hook) {
                split_hooks = split_hooks.concat(hook.split(','));
            });
            data['hooks'] = split_hooks;

            return data;
        },
    });

})();<|endoftext|>


<commit_before>import { DocumentChange, getKeyForPath } from 'substance'
import AppState from './AppState'
import SelectionStateReducer from './SelectionStateReducer'
import DocumentObserver from './DocumentObserver'

const ANY = '@any'
const NO_CHANGE = new DocumentChange([], {}, {})
NO_CHANGE._extractInformation()

export default class EditorState extends AppState {
  _initialize (initialState) {
    super._initialize(initialState)

    if (!initialState.document) {
      throw new Error("'document' is required")
    }
    let doc = initialState.document
    let impl = this._getImpl()
    // EXPERIMENTAL:
    // one observer for all slots that watches for document changes and marks paths as dirty
    // this is also used to broadcast other node based changes such as node state updates
    let documentObserver = new DocumentObserver(doc)
    impl.documentObserver = documentObserver

    let selectionStateReducer = new SelectionStateReducer(this)
    selectionStateReducer.update()
    impl._selectionStateReducer = selectionStateReducer
  }

  // Call this to revitalise a previously disposed editor state
  init () {
    this._getImpl().documentObserver.init()
  }

  dispose () {
    super.dispose()

    this._getImpl().documentObserver.dispose()
  }

  getUpdate (name) {
    let update = super.getUpdate(name)
    // HACK: sometimes we fake a document change to trigger document observers
    // In this case, there might be no actual update (change and info)
    // and we provide a NOP change and empty info
    if (!update && name === 'document') {
      update = { change: NO_CHANGE, info: {} }
    }
    return update
  }

  _createSlot (id, stage, deps) {
    const impl = this._getImpl()
    impl.schedule = null
    if (deps.indexOf('document') !== -1) {
      return new DocumentSlot(this, id, stage, deps, impl.documentObserver)
    } else {
      return new Slot(this, id, stage, deps)
    }
  }

  _reset () {
    super._reset()
    this._getImpl().documentObserver.reset()
  }

  _getDocumentObserver () {
    return this._getImpl().documentObserver
  }
}

class Slot {
  constructor (editorState, id, stage, deps) {
    this._id = editorState._getImpl().id
    this.id = id
    this.editorState = editorState
    this.stage = stage
    this.deps = deps

    this.observers = new Set()
  }

  addObserver (observer, spec) {
    observer[this._id].set(this.id, {
      slot: this,
      spec
    })
    this.observers.add(observer)
  }

  removeObserver (observer) {
    this._deleteEntry(observer)
    this.observers.delete(observer)
  }

  needsUpdate () {
    const state = this.editorState
    for (let dep of this.deps) {
      if (state.isDirty(dep)) return true
    }
    return false
  }

  notifyObservers () {
    let observers = this._getObservers()
    for (let o of observers) {
      let entry = this._getEntryForObserver(o)
      // observer might have been disposed in the meantime
      if (!entry) continue
      this._notifyObserver(entry)
    }
  }

  _getObservers () {
    return this.observers
  }

  _getEntryForObserver (observer) {
    let entries = observer[this._id]
    if (entries) {
      return entries.get(this.id)
    }
  }

  _deleteEntry (observer) {
    let entries = observer[this._id]
    if (entries) {
      entries.delete(this.id)
    }
  }

  _getDocumentChange () {
    let { change, info } = this._updates['document']
    change.info = info
    return change
  }

  _notifyObserver (entry) {
    const state = this.editorState
    let spec = entry.spec
    // TODO: we want to drop this auto-arguments completely
    // after having switched to a pure AppState based implementation
    // i.e. without using observers via EditorSession
    if (spec.deps.length === 1) {
      let name = spec.deps[0]
      switch (name) {
        case 'document': {
          let update = state.getUpdate('document') || {}
          spec.handler(update.change, update.info)
          break
        }
        default:
          spec.handler(state.get(name))
      }
    } else {
      spec.handler()
    }
  }
}

class DocumentSlot extends Slot {
  constructor (editorState, id, stage, deps, documentObserver) {
    super(editorState, id, stage, deps)

    this.documentObserver = documentObserver
    this.byPath = { '@any': new Set() }
  }

  addObserver (observer, spec) {
    super.addObserver(observer, spec)

    const index = this.byPath
    let docSpec = spec.options.document
    if (docSpec && docSpec.path) {
      let key = getKeyForPath(docSpec.path)
      let records = index[key]
      if (!records) {
        records = index[key] = new Set()
      }
      records.add(observer)
    } else {
      index[ANY].add(observer)
    }
  }

  removeObserver (observer) {
    const entries = observer[this._id]
    if (entries) {
      const entry = entries.get(this.id)
      const index = this.byPath
      super.removeObserver(observer)
      let docSpec = entry.spec.options.document
      if (docSpec && docSpec.path) {
        let key = getKeyForPath(docSpec.path)
        let records = index[key]
        records.delete(observer)
      } else {
        index[ANY].delete(observer)
      }
    }
  }

  _getObservers () {
    const state = this.editorState
    if (!state.isDirty('document')) return this.observers

    // notify all observers that are affected by the change
    const index = this.byPath
    let { change } = state.getUpdate('document')

    if (!change) {
      console.error('FIXME: expected to find a document change as update for document')
      return index[ANY]
    }

    let updated = this.documentObserver.dirty
    let sets = []
    // observers without a path spec are registered with path=undefined
    sets.push(index[ANY])
    updated.forEach(id => {
      let set = index[id]
      if (set) sets.push(set)
    })
    let observers = new Set()
    sets.forEach(s => {
      s.forEach(o => observers.add(o))
    })
    return observers
  }
}
<commit_msg>Fix NOP document change used for state updates.<commit_after>import { DocumentChange, getKeyForPath } from 'substance'
import AppState from './AppState'
import SelectionStateReducer from './SelectionStateReducer'
import DocumentObserver from './DocumentObserver'

const ANY = '@any'
const NOP = new DocumentChange({
  ops: [],
  info: { action: 'nop' }
})

export default class EditorState extends AppState {
  _initialize (initialState) {
    super._initialize(initialState)

    if (!initialState.document) {
      throw new Error("'document' is required")
    }
    let doc = initialState.document
    let impl = this._getImpl()
    // EXPERIMENTAL:
    // one observer for all slots that watches for document changes and marks paths as dirty
    // this is also used to broadcast other node based changes such as node state updates
    let documentObserver = new DocumentObserver(doc)
    impl.documentObserver = documentObserver

    let selectionStateReducer = new SelectionStateReducer(this)
    selectionStateReducer.update()
    impl._selectionStateReducer = selectionStateReducer
  }

  // Call this to revitalise a previously disposed editor state
  init () {
    this._getImpl().documentObserver.init()
  }

  dispose () {
    super.dispose()

    this._getImpl().documentObserver.dispose()
  }

  getUpdate (name) {
    let update = super.getUpdate(name)
    // HACK: sometimes we fake a document change to trigger document observers
    // In this case, there might be no actual update (change and info)
    // and we provide a NOP change and empty info
    if (!update && name === 'document') {
      let change = NOP
      change._extractInformation()
      update = { change, info: change.info }
    }
    return update
  }

  _createSlot (id, stage, deps) {
    const impl = this._getImpl()
    impl.schedule = null
    if (deps.indexOf('document') !== -1) {
      return new DocumentSlot(this, id, stage, deps, impl.documentObserver)
    } else {
      return new Slot(this, id, stage, deps)
    }
  }

  _reset () {
    super._reset()
    this._getImpl().documentObserver.reset()
  }

  _getDocumentObserver () {
    return this._getImpl().documentObserver
  }
}

class Slot {
  constructor (editorState, id, stage, deps) {
    this._id = editorState._getImpl().id
    this.id = id
    this.editorState = editorState
    this.stage = stage
    this.deps = deps

    this.observers = new Set()
  }

  addObserver (observer, spec) {
    observer[this._id].set(this.id, {
      slot: this,
      spec
    })
    this.observers.add(observer)
  }

  removeObserver (observer) {
    this._deleteEntry(observer)
    this.observers.delete(observer)
  }

  needsUpdate () {
    const state = this.editorState
    for (let dep of this.deps) {
      if (state.isDirty(dep)) return true
    }
    return false
  }

  notifyObservers () {
    let observers = this._getObservers()
    for (let o of observers) {
      let entry = this._getEntryForObserver(o)
      // observer might have been disposed in the meantime
      if (!entry) continue
      this._notifyObserver(entry)
    }
  }

  _getObservers () {
    return this.observers
  }

  _getEntryForObserver (observer) {
    let entries = observer[this._id]
    if (entries) {
      return entries.get(this.id)
    }
  }

  _deleteEntry (observer) {
    let entries = observer[this._id]
    if (entries) {
      entries.delete(this.id)
    }
  }

  _getDocumentChange () {
    let { change, info } = this._updates['document']
    change.info = info
    return change
  }

  _notifyObserver (entry) {
    const state = this.editorState
    let spec = entry.spec
    // TODO: we want to drop this auto-arguments completely
    // after having switched to a pure AppState based implementation
    // i.e. without using observers via EditorSession
    if (spec.deps.length === 1) {
      let name = spec.deps[0]
      switch (name) {
        case 'document': {
          let update = state.getUpdate('document') || {}
          spec.handler(update.change, update.info)
          break
        }
        default:
          spec.handler(state.get(name))
      }
    } else {
      spec.handler()
    }
  }
}

class DocumentSlot extends Slot {
  constructor (editorState, id, stage, deps, documentObserver) {
    super(editorState, id, stage, deps)

    this.documentObserver = documentObserver
    this.byPath = { '@any': new Set() }
  }

  addObserver (observer, spec) {
    super.addObserver(observer, spec)

    const index = this.byPath
    let docSpec = spec.options.document
    if (docSpec && docSpec.path) {
      let key = getKeyForPath(docSpec.path)
      let records = index[key]
      if (!records) {
        records = index[key] = new Set()
      }
      records.add(observer)
    } else {
      index[ANY].add(observer)
    }
  }

  removeObserver (observer) {
    const entries = observer[this._id]
    if (entries) {
      const entry = entries.get(this.id)
      const index = this.byPath
      super.removeObserver(observer)
      let docSpec = entry.spec.options.document
      if (docSpec && docSpec.path) {
        let key = getKeyForPath(docSpec.path)
        let records = index[key]
        records.delete(observer)
      } else {
        index[ANY].delete(observer)
      }
    }
  }

  _getObservers () {
    const state = this.editorState
    if (!state.isDirty('document')) return this.observers

    // notify all observers that are affected by the change
    const index = this.byPath
    let { change } = state.getUpdate('document')

    if (!change) {
      console.error('FIXME: expected to find a document change as update for document')
      return index[ANY]
    }

    let updated = this.documentObserver.dirty
    let sets = []
    // observers without a path spec are registered with path=undefined
    sets.push(index[ANY])
    updated.forEach(id => {
      let set = index[id]
      if (set) sets.push(set)
    })
    let observers = new Set()
    sets.forEach(s => {
      s.forEach(o => observers.add(o))
    })
    return observers
  }
}
<|endoftext|>


<commit_before>/*
 * L.Marker is used to display clickable/draggable icons on the map.
 */

L.Marker = L.Class.extend({

	includes: L.Mixin.Events,

	options: {
		icon: new L.Icon(),
		title: '',
		clickable: true,
		draggable: false
	},

	initialize: function(latlng, options) {
		L.Util.setOptions(this, options);
		this._latlng = latlng;
	},

	onAdd: function(map) {
		this._map = map;

		this._initIcon();

		map.on('viewreset', this._reset, this);
		this._reset();
	},

	onRemove: function(map) {
		this._map = null;

		this._removeIcon();

		// TODO move to Marker.Popup.js
		if (this.closePopup) {
			this.closePopup();
		}

		map.off('viewreset', this._reset, this);
	},

	getLatLng: function() {
		return this._latlng;
	},

	setLatLng: function(latlng) {
		this._latlng = latlng;
		if (this._icon) {
			this._reset();
		}
	},

	setIcon: function(icon) {
		if (this._map) {
			this._removeIcon();
		}

		this.options.icon = icon;

		if (this._map) {
			this._initIcon();
			this._reset();
		}
	},

	_initIcon: function() {
		if (!this._icon) {
			this._icon = this.options.icon.createIcon();

			if (this.options.title) {
				this._icon.title = this.options.title;
			}

			this._initInteraction();
		}
		if (!this._shadow) {
			this._shadow = this.options.icon.createShadow();
		}

		this._map._panes.markerPane.appendChild(this._icon);
		if (this._shadow) {
			this._map._panes.shadowPane.appendChild(this._shadow);
		}
	},

	_removeIcon: function() {
		this._map._panes.markerPane.removeChild(this._icon);
		if (this._shadow) {
			this._map._panes.shadowPane.removeChild(this._shadow);
		}
		this._icon = this._shadow = null;
	},

	_reset: function() {
		var pos = this._map.latLngToLayerPoint(this._latlng).round();

		L.DomUtil.setPosition(this._icon, pos);
		if (this._shadow) {
			L.DomUtil.setPosition(this._shadow, pos);
		}

		this._icon.style.zIndex = pos.y;
	},

	_initInteraction: function() {
		if (this.options.clickable) {
			this._icon.className += ' leaflet-clickable';

			L.DomEvent.addListener(this._icon, 'click', this._onMouseClick, this);

			var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout'];
			for (var i = 0; i < events.length; i++) {
				L.DomEvent.addListener(this._icon, events[i], this._fireMouseEvent, this);
			}
		}

		if (L.Handler.MarkerDrag) {
			this.dragging = new L.Handler.MarkerDrag(this);

			if (this.options.draggable) {
				this.dragging.enable();
			}
		}
	},

	_onMouseClick: function(e) {
		L.DomEvent.stopPropagation(e);
		if (this.dragging && this.dragging.moved()) { return; }
		this.fire(e.type);
	},

	_fireMouseEvent: function(e) {
		this.fire(e.type);
		L.DomEvent.stopPropagation(e);
	}
});
<commit_msg>Fixed marker regression as pointed out by @shramov<commit_after>/*
 * L.Marker is used to display clickable/draggable icons on the map.
 */

L.Marker = L.Class.extend({

	includes: L.Mixin.Events,

	options: {
		icon: new L.Icon(),
		title: '',
		clickable: true,
		draggable: false
	},

	initialize: function(latlng, options) {
		L.Util.setOptions(this, options);
		this._latlng = latlng;
	},

	onAdd: function(map) {
		this._map = map;

		this._initIcon();

		map.on('viewreset', this._reset, this);
		this._reset();
	},

	onRemove: function(map) {
		this._removeIcon();

		this._map = null;

		// TODO move to Marker.Popup.js
		if (this.closePopup) {
			this.closePopup();
		}

		map.off('viewreset', this._reset, this);
	},

	getLatLng: function() {
		return this._latlng;
	},

	setLatLng: function(latlng) {
		this._latlng = latlng;
		if (this._icon) {
			this._reset();
		}
	},

	setIcon: function(icon) {
		if (this._map) {
			this._removeIcon();
		}

		this.options.icon = icon;

		if (this._map) {
			this._initIcon();
			this._reset();
		}
	},

	_initIcon: function() {
		if (!this._icon) {
			this._icon = this.options.icon.createIcon();

			if (this.options.title) {
				this._icon.title = this.options.title;
			}

			this._initInteraction();
		}
		if (!this._shadow) {
			this._shadow = this.options.icon.createShadow();
		}

		this._map._panes.markerPane.appendChild(this._icon);
		if (this._shadow) {
			this._map._panes.shadowPane.appendChild(this._shadow);
		}
	},

	_removeIcon: function() {
		this._map._panes.markerPane.removeChild(this._icon);
		if (this._shadow) {
			this._map._panes.shadowPane.removeChild(this._shadow);
		}
		this._icon = this._shadow = null;
	},

	_reset: function() {
		var pos = this._map.latLngToLayerPoint(this._latlng).round();

		L.DomUtil.setPosition(this._icon, pos);
		if (this._shadow) {
			L.DomUtil.setPosition(this._shadow, pos);
		}

		this._icon.style.zIndex = pos.y;
	},

	_initInteraction: function() {
		if (this.options.clickable) {
			this._icon.className += ' leaflet-clickable';

			L.DomEvent.addListener(this._icon, 'click', this._onMouseClick, this);

			var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout'];
			for (var i = 0; i < events.length; i++) {
				L.DomEvent.addListener(this._icon, events[i], this._fireMouseEvent, this);
			}
		}

		if (L.Handler.MarkerDrag) {
			this.dragging = new L.Handler.MarkerDrag(this);

			if (this.options.draggable) {
				this.dragging.enable();
			}
		}
	},

	_onMouseClick: function(e) {
		L.DomEvent.stopPropagation(e);
		if (this.dragging && this.dragging.moved()) { return; }
		this.fire(e.type);
	},

	_fireMouseEvent: function(e) {
		this.fire(e.type);
		L.DomEvent.stopPropagation(e);
	}
});
<|endoftext|>


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

var config = {
    paths: {
        demo: "../demo",
        ace: "../lib/ace",
        cockpit: "../support/cockpit/lib/cockpit",
        pilot: "../support/pilot/lib/pilot",
    }
};

var deps = [ "pilot/fixoldbrowsers", "pilot/plugin_manager", "pilot/settings",
             "pilot/environment", "demo/startup" ];

var plugins = [ "pilot/index", "cockpit/index", "ace/defaults" ];

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

var config = {
    paths: {
        demo: "../demo",
        ace: "../lib/ace",
        cockpit: "../support/cockpit/lib/cockpit",
        pilot: "../support/pilot/lib/pilot"
    }
};

var deps = [ "pilot/fixoldbrowsers", "pilot/plugin_manager", "pilot/settings",
             "pilot/environment", "demo/startup" ];

var plugins = [ "pilot/index", "cockpit/index", "ace/defaults" ];

require(config);
require(deps, function() {
    var catalog = require("pilot/plugin_manager").catalog;
    catalog.registerPlugins(plugins).then(function() {
        var env = require("pilot/environment").create();
        catalog.startupPlugins({ env: env }).then(function() {
            require("demo/startup").launch(env);
        });
    });
});
<|endoftext|>


<commit_before>
angular.module('NodeForm', [
    'duScroll', 'ui.select', 'cgBusy', 'ngSanitize', 'vButton', 'ngResource',
    'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven'
]);
angular.module('forms', ['ngResource', 'NodeForm.templates']);
angular.module('NodeForm').requires.push('forms');

angular.module('forms').factory('Auth', [
  function() {
    var service = {
      _currentUser: null,
      get currentUser(){
        return this._currentUser;
      },
      ensureHasCurrentUser: function() {
        return null;
      },
      isAuthenticated: function() {
        return false;
      },
      getUserState: function() {
        return '';
      },
      login: function() {
      },
      logout: function() {
      },
    };
    return service;
  }
]);
angular.module('forms').factory('$state', [function() {
    return {
        go: function() {}
    };
}]);
angular.module('forms').factory('myForm', ['Forms', function(Forms) {
    var form = window.form;
    form.visible_form_fields = _.filter(form.form_fields, function(field){
    	return (field.deletePreserved === false);
    });
    return form;
}]);
angular.module('forms').constant('FORM_URL', '/form/:formId');

angular.element(document).ready(function() {
	//Then init the app
	angular.bootstrap(document, ['forms']);
});
<commit_msg>reorder dependencies<commit_after>
angular.module('forms', ['duScroll', 'ngResource', 'NodeForm.templates']);

angular.module('NodeForm', [
    'ui.select', 'cgBusy', 'ngSanitize', 'vButton', 'ngResource',
    'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven', 'forms'
]);

angular.module('forms').factory('Auth', [
  function() {
    var service = {
      _currentUser: null,
      get currentUser(){
        return this._currentUser;
      },
      ensureHasCurrentUser: function() {
        return null;
      },
      isAuthenticated: function() {
        return false;
      },
      getUserState: function() {
        return '';
      },
      login: function() {
      },
      logout: function() {
      },
    };
    return service;
  }
]);
angular.module('forms').factory('$state', [function() {
    return {
        go: function() {}
    };
}]);
angular.module('forms').factory('myForm', ['Forms', function(Forms) {
    var form = window.form;
    form.visible_form_fields = _.filter(form.form_fields, function(field){
    	return (field.deletePreserved === false);
    });
    return form;
}]);
angular.module('forms').constant('FORM_URL', '/form/:formId');

angular.element(document).ready(function() {
	//Then init the app
	angular.bootstrap(document, ['forms']);
});
<|endoftext|>


<commit_before>import './demo.less';

import React, { Component } from 'react';
import Slider from 'react-rangeslider';

class Demo extends Component {
	constructor(props, context) {
		super(props, context);
		this.state = {
			hor: 10,
			ver: 50,
			flo: 10.2,
			neg: -10,
		};
	}

	handleChangeHor = (value) => {
		this.setState({
			hor: value
		});
	}

	handleChangeVer = (value) => {
		this.setState({
			ver: value,
		});
	}

	handleChangeNeg = (value) => {
		this.setState({
			neg: value,
		});
	}

	handleChangeFlo = (value) => {
		this.setState({
			flo: value,
		});
	}

	valueMapper(min, max) {
		return {
			'0': {
				toValue: (percentage, range) => Math.round(
					(percentage < range ? percentage : range) * 100 * 2
				),
				toPos: value => value / 2 / 100,
			},
			'.25': {
				toValue: (percentage, range) => Math.round(
					(percentage < range ? percentage : range) * 100
				),
				toPos: value => value / 100,
			},
			'.5': {
				toValue: (percentage, range, value) => Math.round(
					percentage / range * (max - value)
				),
				toPos: (value, range, span) => (
					value / span * range
				),
			}
		};
	}

	render() {
		let { hor, ver, neg, flo } = this.state;
		return (

React Rangeslider

A lightweight react component that acts as a HTML5 input range slider polyfill. Shown below are just examples, please refer Github for docs.

Examples

Basic Slider

					<Slider
						min={0}
						max={1000}
						value={hor}
						onChange={this.handleChangeHor}
						valueMapping={this.valueMapper} />

Value: {hor}

Negative Values

					<Slider
						min={-20}
						max={0}
						value={neg}
						onChange={this.handleChangeNeg} />

Value: {neg}

Floating Point

					<Slider
						min={10}
						max={11}
						step={0.1}
						value={flo}
						onChange={this.handleChangeFlo} />

Value: {flo}

Orientation & Custom Styles

					<Slider
						min={0}
						max={100}
						value={ver}
						orientation="vertical"
						onChange={this.handleChangeVer} />

Value: {ver}

Project is under Open Source MIT License

Built with ♥ • 2015 © whoisandie

		);
	}
}

export default Demo;
<commit_msg>Updated demo.<commit_after>import './demo.less';

import React, { Component } from 'react';
import Slider from 'react-rangeslider';

class Demo extends Component {
	constructor(props, context) {
		super(props, context);
		this.state = {
			hor: 10,
			seg: 20,
			ver: 50,
			flo: 10.2,
			neg: -10,
		};
	}

	handleChangeHor = (value) => {
		this.setState({
			hor: value
		});
	}

	handleChangeSeg = (value) => {
		this.setState({
			seg: value
		});
	}

	handleChangeVer = (value) => {
		this.setState({
			ver: value,
		});
	}

	handleChangeNeg = (value) => {
		this.setState({
			neg: value,
		});
	}

	handleChangeFlo = (value) => {
		this.setState({
			flo: value,
		});
	}

	valueMapper(min, max) {
		return {
			'0': {
				toValue: (percentage, range) => Math.round(
					(percentage < range ? percentage : range) * 100 * 2
				),
				toPos: value => value / 2 / 100,
			},
			'.25': {
				toValue: (percentage, range) => Math.round(
					(percentage < range ? percentage : range) * 100
				),
				toPos: value => value / 100,
			},
			'.5': {
				toValue: (percentage, range, value) => Math.round(
					percentage / range * (max - value)
				),
				toPos: (value, range, span) => (
					value / span * range
				),
			}
		};
	}

	valueToCurr = (value) => {
	  let formatted = Math.round(parseFloat(value) * 100) / 100;
	  const segments = (`${formatted}`).split('.');
	  if (segments.length === 1) segments.push('00');
	  if (segments[1].length < 2) segments[1] += '0'.repeat(2 - segments[1].length);
	  formatted = segments.join(',');
	  return formatted;
	}

	render() {
		let { hor, seg, ver, neg, flo } = this.state;
		return (

React Rangeslider

A lightweight react component that acts as a HTML5 input range slider polyfill. Shown below are just examples, please refer Github for docs.

Examples

Basic Slider

					<Slider
						min={0}
						max={100}
						value={hor}
						onChange={this.handleChangeHor} />

Value: {hor}

Segmented Slider with Custom Value Mapping per Segment

					<Slider
						min={0}
						max={1000}
						value={seg}
						onChange={this.handleChangeSeg}
						valueMapping={this.valueMapper} />

Value: {seg}

Negative Values

					<Slider
						min={-20}
						max={0}
						value={neg}
						onChange={this.handleChangeNeg} />

Value: {neg}

Floating Point

					<Slider
						min={10}
						max={11}
						step={0.1}
						value={flo}
						onChange={this.handleChangeFlo} />

Value: {flo}

Orientation & Custom Styles

					<Slider
						min={0}
						max={100}
						value={ver}
						orientation="vertical"
						onChange={this.handleChangeVer} />

Value: {ver}

Project is under Open Source MIT License

Built with ♥ • 2015 © whoisandie

		);
	}
}

export default Demo;
<|endoftext|>


<commit_before>$(function() {
  $('input[type=file]').change(function() {
    var $parent = $(this).parent();
    var file = this.files[0];
    console.log('selected file', file);

    var options = {endpoint: 'http://localhost:1080/files'};
    tus
      .upload(file, options)
      .fail(function(error) {
        console.log('upload failed', error);
      })
      .progress(function(e, bytesUploaded, bytesTotal) {
        console.log(bytesUploaded, bytesTotal);
      })
      .done(function(url) {
        var $download = $('Download uploaded file').appendTo($parent);
        $download.attr('href', url);
        $download.addClass('btn').addClass('btn-success');
      });
  });
});
<commit_msg>Implement progress percentage<commit_after>$(function() {
  $('input[type=file]').change(function() {
    var $parent = $(this).parent();
    var file = this.files[0];
    console.log('selected file', file);

    var options = {endpoint: 'http://localhost:1080/files'};
    tus
      .upload(file, options)
      .fail(function(error) {
        console.log('upload failed', error);
      })
      .progress(function(e, bytesUploaded, bytesTotal) {
        var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
        console.log(bytesUploaded, bytesTotal, percentage + '%');
      })
      .done(function(url) {
        var $download = $('Download uploaded file').appendTo($parent);
        $download.attr('href', url);
        $download.addClass('btn').addClass('btn-success');
      });
  });
});
<|endoftext|>


<commit_before>try {
    var Spooky = require('spooky');
} catch (e) {
    var Spooky = require('../lib/spooky');
}

console.log("Hi.")

var spooky = new Spooky({
        child: {
            transport: 'http'
        },
        casper: {
            clientScripts: [ "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"],
            logLevel: 'debug',
            verbose: true
        }
    }, function (err) {
        if (err) {
            e = new Error('Failed to initialize SpookyJS');
            e.details = err;
            console.log("Error, could not initialize SpookyJS.")
            throw e;
        }

        spooky.start(
            'http://en.wikipedia.org/wiki/Spooky_the_Tuff_Little_Ghost');

        spooky.then(function () {
            //Get ready to hand off to link scanner.
            queue = []
            visited = []

            var queue = this.evaluate(function(){
              var innerqueue = []
              $("a").each(function(index){innerqueue.push( $("a:nth-child("+index+")").attr("href") )});
              return innerqueue;
            });

            this.emit('hello', "\n-O-" + queue + "-O-");
        });
        spooky.run();
    }
);

spooky.on('hello', function (greeting) {
    console.log(greeting);
});

spooky.on('error', function (e, stack) {
    console.error(e);

    if (stack) {
        console.log(stack);
    }
});

<commit_msg>Repository fix.<commit_after><|endoftext|>


<commit_before>class HomeController {
  constructor(images, $ionicPlatform, $http, Photos, AppConstants, Location, Mixpanel) {
    'ngInject';
    // Aliases
    this.name = "HomeController";
    this._$ionicPlatform = $ionicPlatform;
    this._$http = $http;
    this._Location = Location;
    this._Photos = Photos;

    // Var
    this.list = [];
    this.modalState = false;
    this.URI = "";
    this.photoExists = false;

    //On Load Functions
    if (AppConstants.production){
      Mixpanel.trackLoad();
    }

  }

  cancelImage() {
    this.photoExists = false;
    this.URI = "";
  };

  toggleModal(view) {
    this.modalState = view === 'show';
  };

  addImage(source) {
    //hides modal
    this.modalState = false;
    // Take The photo
    this._Photos.newPhoto(source).then((imageURI) => {

      this.photoExists = true;
      this.URI = imageURI;
      this.photoExists = true;

    }, function(err) {
      console.err(err);
    });
  }

  upload() {
    this._Photos.uploadPhoto(imageURI, this._Location.getLocation()).then((res) =>
    console.log('resolution',res)
    );
  }
  testList() {
    this._Photos.getPhotos().then((res) => console.log(res))
  }

}
  export default HomeController;
<commit_msg>refactor<commit_after>class HomeController {
  constructor(images, $ionicPlatform, $http, Photos, AppConstants, Location, Mixpanel) {
    'ngInject';

    this.name = "HomeController";
    this._$ionicPlatform = $ionicPlatform;
    this._$http = $http;
    this._Location = Location;
    this._Photos = Photos;

    if (AppConstants.production){
      Mixpanel.trackLoad();
    }

    this.list = [];
    this.modalState = false;
    this.URI = "";
    this.photoExists = false;
  }

  cancelImage() {
    this.photoExists = false;
    this.URI = "";
  };

  toggleModal(view) {
    this.modalState = view === 'show';
  };

  addImage(source) {
    //hides modal
    this.modalState = false;
    // Take The photo
    this._Photos.newPhoto(source).then((imageURI) => {

      this.photoExists = true;
      this.URI = imageURI;
      this.photoExists = true;

    }, function(err) {
      console.err(err);
    });
  }

  upload() {
    this._Photos.uploadPhoto(imageURI, this._Location.getLocation()).then((res) =>
    console.log('resolution',res)
    );
  }
  testList() {
    this._Photos.getPhotos().then((res) => console.log(res))
  }

}
  export default HomeController;
<|endoftext|>


<commit_before>;(function(exports) {
  var Game = function(canvasId, width, height) {
    this.coquette = new Coquette(this, canvasId, width, height);

    this.maths = new Maths();
    this.STATE = {
      INTRO: 0,
      PLAYING: 1,
      OVER: 2
    };

    this.state = this.STATE.INTRO;

    this.introImage = new Image();
    this.introImage.src = 'intro.png';
  };

  Game.prototype = {
    player: null,
    maxScore: 30,

    init: function() {
      var self = this;
      this.coquette.entities.create(Player, {
        pos: { x:0, y:0 }
      }, function(player) {
        self.player = player;
      });
    },

	  update: function() {
      if (this.state === this.STATE.PLAYING) {
        if (this.score() <= 0) {
          this.state = this.STATE.OVER;
        }
      } else if (this.state === this.STATE.INTRO || this.state === this.STATE.OVER) {
        if(this.coquette.inputter.state(Coquette.Inputter.SPACE)) {
          var asteroids = this.coquette.entities.all(Asteroid);
          for (var i = 0; i < asteroids.length; i++) {
            asteroids[i].kill();
          }

          for (var i = 0; i < 3; i++) {
            this.coquette.entities.create(Asteroid, {
              pos: {
                x: Math.random() * this.coquette.renderer.width,
                y: Math.random() * this.coquette.renderer.height
              }
            });
          }

          this.state = this.STATE.PLAYING;
        }
      }
	  },

	  draw: function() {
      this.coquette.renderer.clear("#000");

      if (this.state === this.STATE.PLAYING) {
        for (var i = 0; i < this.maxScore; i++) {
          var rAngle = this.maths.degToRad(360 / this.maxScore * i);
          var pos = {
            x: this.coquette.renderer.width / 2 + Math.sin(rAngle) * 30,
            y: this.coquette.renderer.height / 2 + Math.cos(rAngle) * 30
          };

          if (i > this.score() - 1) {
            this.circle(pos, 0.5, "#222");
          } else {
            this.circle(pos, 0.5, "#666");
          }
        }
      } else {
        this.coquette.renderer.getCtx().drawImage(this.introImage,
                                                  this.coquette.renderer.width / 2 - 100,
                                                  this.coquette.renderer.height / 2 - 50);
      }
	  },

    circle: function(pos, radius, color) {
      var ctx = this.coquette.renderer.getCtx();
      ctx.strokeStyle = color;
      ctx.beginPath();
      ctx.arc(pos.x + radius, pos.y + radius, radius, 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.stroke();
      ctx.fillRect(10, 10, 10, 10)
    },

    startClip: function() {
      var ctx = this.coquette.renderer.getCtx();
      ctx.save();
      ctx.beginPath();
      ctx.arc(this.coquette.renderer.width / 2, this.coquette.renderer.height / 2,
              this.coquette.renderer.width / 2 , 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.clip();
    },

    endClip: function() {
      this.coquette.renderer.getCtx().restore();
    },

    score: function() {
      return this.maxScore - this.coquette.entities.all(Asteroid).length;
    },
  };

  exports.Game = Game;
})(this);
<commit_msg>Remove debug code.<commit_after>;(function(exports) {
  var Game = function(canvasId, width, height) {
    this.coquette = new Coquette(this, canvasId, width, height);

    this.maths = new Maths();
    this.STATE = {
      INTRO: 0,
      PLAYING: 1,
      OVER: 2
    };

    this.state = this.STATE.INTRO;

    this.introImage = new Image();
    this.introImage.src = 'intro.png';
  };

  Game.prototype = {
    player: null,
    maxScore: 30,

    init: function() {
      var self = this;
      this.coquette.entities.create(Player, {
        pos: { x:0, y:0 }
      }, function(player) {
        self.player = player;
      });
    },

	  update: function() {
      if (this.state === this.STATE.PLAYING) {
        if (this.score() <= 0) {
          this.state = this.STATE.OVER;
        }
      } else if (this.state === this.STATE.INTRO || this.state === this.STATE.OVER) {
        if(this.coquette.inputter.state(Coquette.Inputter.SPACE)) {
          var asteroids = this.coquette.entities.all(Asteroid);
          for (var i = 0; i < asteroids.length; i++) {
            asteroids[i].kill();
          }

          for (var i = 0; i < 3; i++) {
            this.coquette.entities.create(Asteroid, {
              pos: {
                x: Math.random() * this.coquette.renderer.width,
                y: Math.random() * this.coquette.renderer.height
              }
            });
          }

          this.state = this.STATE.PLAYING;
        }
      }
	  },

	  draw: function() {
      this.coquette.renderer.clear("#000");

      if (this.state === this.STATE.PLAYING) {
        for (var i = 0; i < this.maxScore; i++) {
          var rAngle = this.maths.degToRad(360 / this.maxScore * i);
          var pos = {
            x: this.coquette.renderer.width / 2 + Math.sin(rAngle) * 30,
            y: this.coquette.renderer.height / 2 + Math.cos(rAngle) * 30
          };

          if (i > this.score() - 1) {
            this.circle(pos, 0.5, "#222");
          } else {
            this.circle(pos, 0.5, "#666");
          }
        }
      } else {
        this.coquette.renderer.getCtx().drawImage(this.introImage,
                                                  this.coquette.renderer.width / 2 - 100,
                                                  this.coquette.renderer.height / 2 - 50);
      }
	  },

    circle: function(pos, radius, color) {
      var ctx = this.coquette.renderer.getCtx();
      ctx.strokeStyle = color;
      ctx.beginPath();
      ctx.arc(pos.x + radius, pos.y + radius, radius, 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.stroke();
    },

    startClip: function() {
      var ctx = this.coquette.renderer.getCtx();
      ctx.save();
      ctx.beginPath();
      ctx.arc(this.coquette.renderer.width / 2, this.coquette.renderer.height / 2,
              this.coquette.renderer.width / 2 , 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.clip();
    },

    endClip: function() {
      this.coquette.renderer.getCtx().restore();
    },

    score: function() {
      return this.maxScore - this.coquette.entities.all(Asteroid).length;
    },
  };

  exports.Game = Game;
})(this);
<|endoftext|>


<commit_before>var fs = require('fs');  //puesto por ahora

var request = require('request');
var express = require('express'),
      app = express(),
      server = require('http').createServer(app),

      elemParadas = [],
      paradas = [];

var paradasant = [];
var _recorridos = [];

done = false;

var io = require('socket.io')(server);  //funciona

app.use( express.static(__dirname + '/public'));

app.use(function(req,res,next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-Width");
}
  )
// Redireccionamiento a https
  // Enable reverse proxy support in Express. This causes the
  // the "X-Forwarded-Proto" header field to be trusted so its
  // value can be used to determine the protocol. See
  // http://expressjs.com/api#app-settings for more details.
  app.enable('trust proxy');

  // Add a handler to inspect the req.secure flag (see
  // http://expressjs.com/api#req.secure). This allows us
  // to know whether the request was via http or https.
  app.use (function (req, res, next) {
          if (req.secure) {
                  // request was via https, so do no special handling
                  next();
          } else {
                  // request was via http, so redirect to https
                  res.redirect('https://' + req.headers.host + req.url);
          }
  });

var arrayRecorridos = [
						   ["Cordón a Sayago","public/Recorridos/CordonSayago.js"],
						   ["Sayago a Cordón","public/Recorridos/sayagoCordon.js"],
						   ["Reducto a FIng","public/Recorridos/reductoFing.js"],
						   ["Toledo a FIng","public/Recorridos/toledoFing.js"],
						   ["Ciudad Vieja a Prado","public/Recorridos/cViejaPrado.js"],
						   ["Prado a Ciudad Vieja","public/Recorridos/pradoCVieja.js"],
						   ["Pque Rodó a Prado","public/Recorridos/pqeRodoPrado.js"],
						   ["Ciudad Vieja a Pque Rodó","public/Recorridos/cvpr.js"],
						   ["Pque Rodó a Ciudad Vieja","public/Recorridos/prcv.js"],
						   ["Pocitos a Ciudad Vieja","public/Recorridos/pocitosCVieja.js"],
						   ["CVieja a Pocitos","public/Recorridos/cViejaPocitos.js"],
						   ["Ciudad Vieja a Obelisco","public/Recorridos/cvObelisco.js"],
						   ["Comercial a Pcio. Legislativo","public/Recorridos/comercialPcioLeg.js"],
						   ["Comercial a CV","public/Recorridos/ComercialCV.js"]
					   ];

var intReq, intSend;

//provisorio
  var biciamigos = null;
  var infladores = null;
  var bicipuntos = null;
  var bicicleterias = null;
  var repechos = null;
  var seccionales = null;
  var talleres = null;
  var paseoRambla = null;
  var paseoPeniarol = null;
  var paseoPrado = null;

  fs.readFile('public/Mapas/biciamigos.js', 'utf8', function (err,data1) {

        if (err) {
          return console.log(err);
        }

        biciamigos = data1;
        //console.log(data1);
    });
  fs.readFile('public/Mapas/infladores3.js', 'utf8', function (err,data2) {

        if (err) {
          return console.log(err);
        }

        infladores = data2;

    });

  fs.readFile('public/Mapas/bicipuntos.js', 'utf8', function (err,data3) {

        if (err) {
          return console.log(err);
        }

        bicipuntos = data3;

    });
  fs.readFile('public/Mapas/bicicleterias.js', 'utf8', function (err,data4) {

        if (err) {
          return console.log(err);
        }

        bicicleterias = data4;
        //console.log(data2);
    });
  fs.readFile('public/Mapas/repechos.js', 'utf8', function (err,data5) {

        if (err) {
          return console.log(err);
        }
        repechos = data5;

    });
  fs.readFile('public/Mapas/seccionales.js', 'utf8', function (err,data6) {

        if (err) {
          return console.log(err);
        }

        seccionales = data6;
        //console.log(data2);
    });

  fs.readFile('public/Mapas/talleres.js', 'utf8', function (err,data7) {

        if (err) {
          return console.log(err);
        }

        talleres = data7;
        //console.log(data2);
    });

  fs.readFile('public/Mapas/CVyrambla.js', 'utf8', function (err,data8) {

        if (err) {
          return console.log(err);
        }
        paseoRambla = data8;
    });

  fs.readFile('public/Mapas/paseoPeniarol.js', 'utf8', function (err,data9) {

        if (err) {
          return console.log(err);
        }

        paseoPeniarol = data9;

    });

  fs.readFile('public/Mapas/paseoPrado.js', 'utf8', function (err,data10) {

        if (err) {
          return console.log(err);
        }

        paseoPrado = data10;

    });

  io.sockets.on('connection', function (socket) {
    socket.emit('biciamigos', biciamigos);
    socket.emit('bicipuntos', bicipuntos);
    socket.emit('bicicleterias', bicicleterias);
    socket.emit('infladores', infladores);
    socket.emit('talleres', talleres);
    socket.emit('repechos', repechos);
    socket.emit('seccionales',seccionales);
    socket.emit('paseoRambla',paseoRambla);
    socket.emit('paseoPeniarol',paseoPeniarol);
    socket.emit('paseoPrado',paseoPrado);

    io.sockets.on('error', function() {
      io.connect(host, {
          'force new connection': true
      });
    });

  });

 //Recorridos

 // enviar recorrido

 fs.readFile(arrayRecorridos[13][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[13] = data;
     });

 fs.readFile(arrayRecorridos[12][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[12] = data;
     });

fs.readFile(arrayRecorridos[11][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[11] = data;

     });

fs.readFile(arrayRecorridos[10][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[10] = data;

     });
fs.readFile(arrayRecorridos[9][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[9] = data;

     });

 fs.readFile(arrayRecorridos[8][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[8] = data;

     });

fs.readFile(arrayRecorridos[7][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[7] = data;

     });

fs.readFile(arrayRecorridos[6][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[6] = data;

     });

fs.readFile(arrayRecorridos[5][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[5] = data;

 });

fs.readFile(arrayRecorridos[4][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[4] = data;

 });

 fs.readFile(arrayRecorridos[3][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[3] = data;

 });

 fs.readFile(arrayRecorridos[2][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[2] = data;

 });

fs.readFile(arrayRecorridos[1][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[1] = data;

     });

fs.readFile(arrayRecorridos[0][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[0] = data;

     });

io.sockets.on("connection", function(socket) {

   socket.on("recorridos0", function(data0){

      socket.emit("recorridos0", _recorridos[0]);

     });

     socket.on("recorridos1", function(data1){

        socket.emit("recorridos1",_recorridos[1]);

    });

    socket.on("recorridos2", function(data2){
		socket.emit("recorridos2",_recorridos[2]);
    });

    socket.on("recorridos3", function(data3){
		socket.emit("recorridos3",_recorridos[3]);
    });

    socket.on("recorridos4", function(data4){
		socket.emit("recorridos4",_recorridos[4]);
    });

    socket.on("recorridos5", function(data5){
		socket.emit("recorridos5",_recorridos[5]);
    });

    socket.on("recorridos6", function(data6){
		socket.emit("recorridos6",_recorridos[6]);
    });

	socket.on("recorridos7", function(data7){
		socket.emit("recorridos7",_recorridos[7]);
    });

    socket.on("recorridos8", function(data8){
		socket.emit("recorridos8",_recorridos[8]);
    });

    socket.on("recorridos9", function(data9){
		socket.emit("recorridos9",_recorridos[9]);
    });

    socket.on("recorridos10", function(data10){
		socket.emit("recorridos10",_recorridos[10]);
    });

    socket.on("recorridos11", function(data11){
		socket.emit("recorridos11",_recorridos[11]);
    });

    socket.on("recorridos12", function(data12){

     socket.emit("recorridos12",_recorridos[12]);
    });

    socket.on("recorridos13", function(data13){

        socket.emit("recorridos13",_recorridos[13]);

    });

  });
//});

var d = new Date();
var h = d.getHours();

// Hora de de funcionamiento de las estaciones Plan Movete 7-21hs
//if ((h < 21) && (h >= 7))
//{
  io.sockets.on("connection", function(socket) {

    socket.on("paradas", function(data){
		request('http://movete.montevideo.gub.uy/index.php?option=com_content&view=article&id=1&Itemid=2', function (error, response, html) {
			if (!error && response.statusCode == 200) {
			  html = html.replace(/(\n|\r)/g,'');

			  /* Con esta exp reg obtengo solo el vector, índice 2 del array */

			  var re = /(var\s*paradas\s*=(\s*\[(.*?)\]));/;  //Funciona!!

			  var res = re.exec(html);  //obtenemos un string
			  // res[0] - todo el string var paradas = [..]
			  // res[2] - solo la parte entre [], los más externos

			  //saco [] más externos
			  var paradas1 = res[2].trim();
			  var paradas1 = paradas1.slice(0,res[2].length-1);  //desde 1 y mo 0

				if (paradas1.length > 0)
					{
						socket.emit('paradas', paradas1);
					}

			}
			else
				console.log("sin datos");

		  });  //request

	}); //socket paradas

  }); //socket connection

//} //if hora

 io.sockets.on('error', function() {
	  io.connect(host, {
		'force new connection': true
	  });
	 });

io.sockets.on('disconnect', function(){

});

 server.listen(process.env.PORT || 5000);
<commit_msg>con certificado SSL<commit_after>var fs = require('fs');  //puesto por ahora

var request = require('request');
var express = require('express'),
      app = express(),
      server = require('http').createServer(app),

      elemParadas = [],
      paradas = [];

var paradasant = [];
var _recorridos = [];

done = false;

var io = require('socket.io')(server);  //funciona

app.use( express.static(__dirname + '/public'));

app.use(function(req,res,next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-Width");
  // Nuevo

  // if (req.header('x-forwarded-proto') == 'http') {
  //   res.redirect(301, 'https://' + 'www.bicumap.uy' + req.url);
  //   return;
  // }
  //next();
  if (req.headers['x-forwarded-proto'] !== 'https') {
        return res.redirect(['https://', req.get('Host'), req.url].join(''));
    }
  next();
}
  )
// Redireccionamiento a https
  // Enable reverse proxy support in Express. This causes the
  // the "X-Forwarded-Proto" header field to be trusted so its
  // value can be used to determine the protocol. See
  // http://expressjs.com/api#app-settings for more details.
  app.enable('trust proxy');

  // Add a handler to inspect the req.secure flag (see
  // http://expressjs.com/api#req.secure). This allows us
  // to know whether the request was via http or https.
  app.use (function (req, res, next) {
          if (req.secure) {
                  // request was via https, so do no special handling
                  next();
          } else {
                  // request was via http, so redirect to https
                  res.redirect('https://' + req.headers.host + req.url);
          }
  });

var arrayRecorridos = [
						   ["Cordón a Sayago","public/Recorridos/CordonSayago.js"],
						   ["Sayago a Cordón","public/Recorridos/sayagoCordon.js"],
						   ["Reducto a FIng","public/Recorridos/reductoFing.js"],
						   ["Toledo a FIng","public/Recorridos/toledoFing.js"],
						   ["Ciudad Vieja a Prado","public/Recorridos/cViejaPrado.js"],
						   ["Prado a Ciudad Vieja","public/Recorridos/pradoCVieja.js"],
						   ["Pque Rodó a Prado","public/Recorridos/pqeRodoPrado.js"],
						   ["Ciudad Vieja a Pque Rodó","public/Recorridos/cvpr.js"],
						   ["Pque Rodó a Ciudad Vieja","public/Recorridos/prcv.js"],
						   ["Pocitos a Ciudad Vieja","public/Recorridos/pocitosCVieja.js"],
						   ["CVieja a Pocitos","public/Recorridos/cViejaPocitos.js"],
						   ["Ciudad Vieja a Obelisco","public/Recorridos/cvObelisco.js"],
						   ["Comercial a Pcio. Legislativo","public/Recorridos/comercialPcioLeg.js"],
						   ["Comercial a CV","public/Recorridos/ComercialCV.js"]
					   ];

var intReq, intSend;

//provisorio
  var biciamigos = null;
  var infladores = null;
  var bicipuntos = null;
  var bicicleterias = null;
  var repechos = null;
  var seccionales = null;
  var talleres = null;
  var paseoRambla = null;
  var paseoPeniarol = null;
  var paseoPrado = null;

  fs.readFile('public/Mapas/biciamigos.js', 'utf8', function (err,data1) {

        if (err) {
          return console.log(err);
        }

        biciamigos = data1;
        //console.log(data1);
    });
  fs.readFile('public/Mapas/infladores3.js', 'utf8', function (err,data2) {

        if (err) {
          return console.log(err);
        }

        infladores = data2;

    });

  fs.readFile('public/Mapas/bicipuntos.js', 'utf8', function (err,data3) {

        if (err) {
          return console.log(err);
        }

        bicipuntos = data3;

    });
  fs.readFile('public/Mapas/bicicleterias.js', 'utf8', function (err,data4) {

        if (err) {
          return console.log(err);
        }

        bicicleterias = data4;
        //console.log(data2);
    });
  fs.readFile('public/Mapas/repechos.js', 'utf8', function (err,data5) {

        if (err) {
          return console.log(err);
        }
        repechos = data5;

    });
  fs.readFile('public/Mapas/seccionales.js', 'utf8', function (err,data6) {

        if (err) {
          return console.log(err);
        }

        seccionales = data6;
        //console.log(data2);
    });

  fs.readFile('public/Mapas/talleres.js', 'utf8', function (err,data7) {

        if (err) {
          return console.log(err);
        }

        talleres = data7;
        //console.log(data2);
    });

  fs.readFile('public/Mapas/CVyrambla.js', 'utf8', function (err,data8) {

        if (err) {
          return console.log(err);
        }
        paseoRambla = data8;
    });

  fs.readFile('public/Mapas/paseoPeniarol.js', 'utf8', function (err,data9) {

        if (err) {
          return console.log(err);
        }

        paseoPeniarol = data9;

    });

  fs.readFile('public/Mapas/paseoPrado.js', 'utf8', function (err,data10) {

        if (err) {
          return console.log(err);
        }

        paseoPrado = data10;

    });

  io.sockets.on('connection', function (socket) {
    socket.emit('biciamigos', biciamigos);
    socket.emit('bicipuntos', bicipuntos);
    socket.emit('bicicleterias', bicicleterias);
    socket.emit('infladores', infladores);
    socket.emit('talleres', talleres);
    socket.emit('repechos', repechos);
    socket.emit('seccionales',seccionales);
    socket.emit('paseoRambla',paseoRambla);
    socket.emit('paseoPeniarol',paseoPeniarol);
    socket.emit('paseoPrado',paseoPrado);

    io.sockets.on('error', function() {
      io.connect(host, {
          'force new connection': true
      });
    });

  });

 //Recorridos

 // enviar recorrido

 fs.readFile(arrayRecorridos[13][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[13] = data;
     });

 fs.readFile(arrayRecorridos[12][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[12] = data;
     });

fs.readFile(arrayRecorridos[11][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[11] = data;

     });

fs.readFile(arrayRecorridos[10][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[10] = data;

     });
fs.readFile(arrayRecorridos[9][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[9] = data;

     });

 fs.readFile(arrayRecorridos[8][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[8] = data;

     });

fs.readFile(arrayRecorridos[7][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[7] = data;

     });

fs.readFile(arrayRecorridos[6][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[6] = data;

     });

fs.readFile(arrayRecorridos[5][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[5] = data;

 });

fs.readFile(arrayRecorridos[4][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[4] = data;

 });

 fs.readFile(arrayRecorridos[3][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[3] = data;

 });

 fs.readFile(arrayRecorridos[2][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[2] = data;

 });

fs.readFile(arrayRecorridos[1][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[1] = data;

     });

fs.readFile(arrayRecorridos[0][1], 'utf8', function (err,data) {
        if (err) {
          return console.log(err);
        }
        _recorridos[0] = data;

     });

io.sockets.on("connection", function(socket) {

   socket.on("recorridos0", function(data0){

      socket.emit("recorridos0", _recorridos[0]);

     });

     socket.on("recorridos1", function(data1){

        socket.emit("recorridos1",_recorridos[1]);

    });

    socket.on("recorridos2", function(data2){
		socket.emit("recorridos2",_recorridos[2]);
    });

    socket.on("recorridos3", function(data3){
		socket.emit("recorridos3",_recorridos[3]);
    });

    socket.on("recorridos4", function(data4){
		socket.emit("recorridos4",_recorridos[4]);
    });

    socket.on("recorridos5", function(data5){
		socket.emit("recorridos5",_recorridos[5]);
    });

    socket.on("recorridos6", function(data6){
		socket.emit("recorridos6",_recorridos[6]);
    });

	socket.on("recorridos7", function(data7){
		socket.emit("recorridos7",_recorridos[7]);
    });

    socket.on("recorridos8", function(data8){
		socket.emit("recorridos8",_recorridos[8]);
    });

    socket.on("recorridos9", function(data9){
		socket.emit("recorridos9",_recorridos[9]);
    });

    socket.on("recorridos10", function(data10){
		socket.emit("recorridos10",_recorridos[10]);
    });

    socket.on("recorridos11", function(data11){
		socket.emit("recorridos11",_recorridos[11]);
    });

    socket.on("recorridos12", function(data12){

     socket.emit("recorridos12",_recorridos[12]);
    });

    socket.on("recorridos13", function(data13){

        socket.emit("recorridos13",_recorridos[13]);

    });

  });
//});

var d = new Date();
var h = d.getHours();

// Hora de de funcionamiento de las estaciones Plan Movete 7-21hs
//if ((h < 21) && (h >= 7))
//{
  io.sockets.on("connection", function(socket) {

    socket.on("paradas", function(data){
		request('http://movete.montevideo.gub.uy/index.php?option=com_content&view=article&id=1&Itemid=2', function (error, response, html) {
			if (!error && response.statusCode == 200) {
			  html = html.replace(/(\n|\r)/g,'');

			  /* Con esta exp reg obtengo solo el vector, índice 2 del array */

			  var re = /(var\s*paradas\s*=(\s*\[(.*?)\]));/;  //Funciona!!

			  var res = re.exec(html);  //obtenemos un string
			  // res[0] - todo el string var paradas = [..]
			  // res[2] - solo la parte entre [], los más externos

			  //saco [] más externos
			  var paradas1 = res[2].trim();
			  var paradas1 = paradas1.slice(0,res[2].length-1);  //desde 1 y mo 0

				if (paradas1.length > 0)
					{
						socket.emit('paradas', paradas1);
					}

			}
			else
				console.log("sin datos");

		  });  //request

	}); //socket paradas

  }); //socket connection

//} //if hora

 io.sockets.on('error', function() {
	  io.connect(host, {
		'force new connection': true
	  });
	 });

io.sockets.on('disconnect', function(){

});

 server.listen(process.env.PORT || 5000);
<|endoftext|>