<commit_before>fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {

  /**
   * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately
   * @param {Object} [options] Options object
   * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
   * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
   * @param {Number} [options.multiplier=1] Multiplier to scale by
   * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
   * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
   * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
   * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
   * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
   * @see {@link http://jsfiddle.net/fabricjs/NfZVb/|jsFiddle demo}
   * @example
Generate jpeg dataURL with lower quality

   * var dataURL = canvas.toDataURL({
   *   format: 'jpeg',
   *   quality: 0.8
   * });
   * @example
Generate cropped png dataURL (clipping of canvas)

   * var dataURL = canvas.toDataURL({
   *   format: 'png',
   *   left: 100,
   *   top: 100,
   *   width: 200,
   *   height: 200
   * });
   * @example
Generate double scaled png dataURL

   * var dataURL = canvas.toDataURL({
   *   format: 'png',
   *   multiplier: 2
   * });
   */
  toDataURL: function (options) {
    options || (options = { });

    var format = options.format || 'png',
        quality = options.quality || 1,
        multiplier = options.multiplier || 1,
        cropping = {
          left: options.left,
          top: options.top,
          width: options.width,
          height: options.height
        };

    if (this._isRetinaScaling()) {
      multiplier *= fabric.devicePixelRatio;
    }

    if (multiplier !== 1) {
      return this.__toDataURLWithMultiplier(format, quality, cropping, multiplier);
    }
    else {
      return this.__toDataURL(format, quality, cropping);
    }
  },

  /**
   * @private
   */
  __toDataURL: function(format, quality, cropping) {

    this.renderAll();

    var canvasEl = this.contextContainer.canvas,
        croppedCanvasEl = this.__getCroppedCanvas(canvasEl, cropping);

    // to avoid common confusion https://github.com/kangax/fabric.js/issues/806
    if (format === 'jpg') {
      format = 'jpeg';
    }

    var data = (fabric.StaticCanvas.supports('toDataURLWithQuality'))
              ? (croppedCanvasEl || canvasEl).toDataURL('image/' + format, quality)
              : (croppedCanvasEl || canvasEl).toDataURL('image/' + format);

    if (croppedCanvasEl) {
      croppedCanvasEl = null;
    }

    return data;
  },

  /**
   * @private
   */
  __getCroppedCanvas: function(canvasEl, cropping) {

    var croppedCanvasEl,
        croppedCtx,
        shouldCrop = 'left' in cropping ||
                     'top' in cropping ||
                     'width' in cropping ||
                     'height' in cropping;

    if (shouldCrop) {

      croppedCanvasEl = fabric.util.createCanvasElement();
      croppedCtx = croppedCanvasEl.getContext('2d');

      croppedCanvasEl.width = cropping.width || this.width;
      croppedCanvasEl.height = cropping.height || this.height;

      croppedCtx.drawImage(canvasEl, -cropping.left || 0, -cropping.top || 0);
    }

    return croppedCanvasEl;
  },

  /**
   * @private
   */
  __toDataURLWithMultiplier: function(format, quality, cropping, multiplier) {

    var origWidth = this.getWidth(),
        origHeight = this.getHeight(),
        origRetinaScaling = this.enableRetinaScaling,
        scaledWidth = origWidth * multiplier,
        scaledHeight = origHeight * multiplier,
        activeObject = this.getActiveObject(),
        activeGroup = this.getActiveGroup(),
        ctx = this.contextContainer;

    this.enableRetinaScaling = false;
    if (multiplier > 1) {
      this.setDimensions({ width: scaledWidth, height: scaledHeight });
    }
    ctx.save();
    ctx.scale(multiplier, multiplier);

    if (cropping.left) {
      cropping.left *= multiplier;
    }
    if (cropping.top) {
      cropping.top *= multiplier;
    }
    if (cropping.width) {
      cropping.width *= multiplier;
    }
    else if (multiplier < 1) {
      cropping.width = scaledWidth;
    }
    if (cropping.height) {
      cropping.height *= multiplier;
    }
    else if (multiplier < 1) {
      cropping.height = scaledHeight;
    }

    if (activeGroup) {
      // not removing group due to complications with restoring it with correct state afterwords
      this._tempRemoveBordersControlsFromGroup(activeGroup);
    }
    else if (activeObject && this.deactivateAll) {
      this.deactivateAll();
    }

    var data = this.__toDataURL(format, quality, cropping);

    // restoring width, height for `renderAll` to draw
    // background properly (while context is scaled)
    this.width = origWidth;
    this.height = origHeight;
    this.enableRetinaScaling = origRetinaScaling;
    this.setDimensions({ width: origWidth, height: origHeight });

    if (activeGroup) {
      this._restoreBordersControlsOnGroup(activeGroup);
    }
    else if (activeObject && this.setActiveObject) {
      this.setActiveObject(activeObject);
    }

    this.contextTop && this.clearContext(this.contextTop);
    this.renderAll();

    return data;
  },

  /**
   * Exports canvas element to a dataurl image (allowing to change image size via multiplier).
   * @deprecated since 1.0.13
   * @param {String} format (png|jpeg)
   * @param {Number} multiplier
   * @param {Number} quality (0..1)
   * @return {String}
   */
  toDataURLWithMultiplier: function (format, multiplier, quality) {
    return this.toDataURL({
      format: format,
      multiplier: multiplier,
      quality: quality
    });
  },

  /**
   * @private
   */
  _tempRemoveBordersControlsFromGroup: function(group) {
    group.origHasControls = group.hasControls;
    group.origBorderColor = group.borderColor;

    group.hasControls = true;
    group.borderColor = 'rgba(0,0,0,0)';

    group.forEachObject(function(o) {
      o.origBorderColor = o.borderColor;
      o.borderColor = 'rgba(0,0,0,0)';
    });
  },

  /**
   * @private
   */
  _restoreBordersControlsOnGroup: function(group) {
    group.hideControls = group.origHideControls;
    group.borderColor = group.origBorderColor;

    group.forEachObject(function(o) {
      o.borderColor = o.origBorderColor;
      delete o.origBorderColor;
    });
  }
});
<commit_msg>Update canvas_dataurl_exporter.mixin.js<commit_after>fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {

  /**
   * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately
   * @param {Object} [options] Options object
   * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
   * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
   * @param {Number} [options.multiplier=1] Multiplier to scale by
   * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
   * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
   * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
   * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
   * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
   * @see {@link http://jsfiddle.net/fabricjs/NfZVb/|jsFiddle demo}
   * @example
Generate jpeg dataURL with lower quality

   * var dataURL = canvas.toDataURL({
   *   format: 'jpeg',
   *   quality: 0.8
   * });
   * @example
Generate cropped png dataURL (clipping of canvas)

   * var dataURL = canvas.toDataURL({
   *   format: 'png',
   *   left: 100,
   *   top: 100,
   *   width: 200,
   *   height: 200
   * });
   * @example
Generate double scaled png dataURL

   * var dataURL = canvas.toDataURL({
   *   format: 'png',
   *   multiplier: 2
   * });
   */
  toDataURL: function (options) {
    options || (options = { });

    var format = options.format || 'png',
        quality = options.quality || 1,
        multiplier = options.multiplier || 1,
        cropping = {
          left: options.left,
          top: options.top,
          width: options.width,
          height: options.height
        };

    if (this._isRetinaScaling()) {
      multiplier *= fabric.devicePixelRatio;
    }

    if (multiplier !== 1) {
      return this.__toDataURLWithMultiplier(format, quality, cropping, multiplier);
    }
    else {
      return this.__toDataURL(format, quality, cropping);
    }
  },

  /**
   * @private
   */
  __toDataURL: function(format, quality, cropping) {

    this.renderAll();

    var canvasEl = this.contextContainer.canvas,
        croppedCanvasEl = this.__getCroppedCanvas(canvasEl, cropping);

    // to avoid common confusion https://github.com/kangax/fabric.js/issues/806
    if (format === 'jpg') {
      format = 'jpeg';
    }

    var data = (fabric.StaticCanvas.supports('toDataURLWithQuality'))
              ? (croppedCanvasEl || canvasEl).toDataURL('image/' + format, quality)
              : (croppedCanvasEl || canvasEl).toDataURL('image/' + format);

    if (croppedCanvasEl) {
      croppedCanvasEl = null;
    }

    return data;
  },

  /**
   * @private
   */
  __getCroppedCanvas: function(canvasEl, cropping) {

    var croppedCanvasEl,
        croppedCtx,
        shouldCrop = 'left' in cropping ||
                     'top' in cropping ||
                     'width' in cropping ||
                     'height' in cropping;

    if (shouldCrop) {

      croppedCanvasEl = fabric.util.createCanvasElement();
      croppedCtx = croppedCanvasEl.getContext('2d');

      croppedCanvasEl.width = cropping.width || this.width;
      croppedCanvasEl.height = cropping.height || this.height;

      croppedCtx.drawImage(canvasEl, -cropping.left || 0, -cropping.top || 0);
    }

    return croppedCanvasEl;
  },

  /**
   * @private
   */
  __toDataURLWithMultiplier: function(format, quality, cropping, multiplier) {

    var origWidth = this.getWidth(),
        origHeight = this.getHeight(),
        scaledWidth = origWidth * multiplier,
        scaledHeight = origHeight * multiplier,
        activeObject = this.getActiveObject(),
        activeGroup = this.getActiveGroup(),
        ctx = this.contextContainer;

    if (multiplier > 1) {
      this.setDimensions({ width: scaledWidth, height: scaledHeight });
    }
    ctx.save();
    ctx.scale(multiplier / fabric.devicePixelRatio, multiplier / fabric.devicePixelRatio);

    if (cropping.left) {
      cropping.left *= multiplier;
    }
    if (cropping.top) {
      cropping.top *= multiplier;
    }
    if (cropping.width) {
      cropping.width *= multiplier;
    }
    else if (multiplier < 1) {
      cropping.width = scaledWidth;
    }
    if (cropping.height) {
      cropping.height *= multiplier;
    }
    else if (multiplier < 1) {
      cropping.height = scaledHeight;
    }

    if (activeGroup) {
      // not removing group due to complications with restoring it with correct state afterwords
      this._tempRemoveBordersControlsFromGroup(activeGroup);
    }
    else if (activeObject && this.deactivateAll) {
      this.deactivateAll();
    }

    var data = this.__toDataURL(format, quality, cropping);

    // restoring width, height for `renderAll` to draw
    // background properly (while context is scaled)
    this.width = origWidth;
    this.height = origHeight;
    this.setDimensions({ width: origWidth, height: origHeight });

    if (activeGroup) {
      this._restoreBordersControlsOnGroup(activeGroup);
    }
    else if (activeObject && this.setActiveObject) {
      this.setActiveObject(activeObject);
    }

    this.contextTop && this.clearContext(this.contextTop);
    this.renderAll();

    return data;
  },

  /**
   * Exports canvas element to a dataurl image (allowing to change image size via multiplier).
   * @deprecated since 1.0.13
   * @param {String} format (png|jpeg)
   * @param {Number} multiplier
   * @param {Number} quality (0..1)
   * @return {String}
   */
  toDataURLWithMultiplier: function (format, multiplier, quality) {
    return this.toDataURL({
      format: format,
      multiplier: multiplier,
      quality: quality
    });
  },

  /**
   * @private
   */
  _tempRemoveBordersControlsFromGroup: function(group) {
    group.origHasControls = group.hasControls;
    group.origBorderColor = group.borderColor;

    group.hasControls = true;
    group.borderColor = 'rgba(0,0,0,0)';

    group.forEachObject(function(o) {
      o.origBorderColor = o.borderColor;
      o.borderColor = 'rgba(0,0,0,0)';
    });
  },

  /**
   * @private
   */
  _restoreBordersControlsOnGroup: function(group) {
    group.hideControls = group.origHideControls;
    group.borderColor = group.origBorderColor;

    group.forEachObject(function(o) {
      o.borderColor = o.origBorderColor;
      delete o.origBorderColor;
    });
  }
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
  users = require('../../controllers/users.server.controller');

var FB = require('fb');

FB.api('4', function (res) {
    if(!res || res.error) {
        console.log(!res ? 'error occurred' : res.error);
        return;
    }
    console.log(res.id);
    console.log(res.name);
});

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;
        FB.setAccessToken('accessToken');
        var body = 'My first post using facebook-node-sdk';
        FB.api('me/feed', 'post', { message: body}, function (res) {
            if(!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }
            console.log('Post Id: ' + res.id);
        });

      // Create the user OAuth profile
      var providerUserProfile = {
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:providerData,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<commit_msg>fb post<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
  users = require('../../controllers/users.server.controller');

var FB = require('fb');

FB.api('4', function (res) {
    if(!res || res.error) {
        console.log(!res ? 'error occurred' : res.error);
        return;
    }
    console.log(res.id);
    console.log(res.name);
});

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;
        FB.setAccessToken('accessToken');
        var body = 'My first post using facebook-node-sdk';
        FB.api('me/feed', 'post', { message: body}, function (res) {
            if(!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }
            console.log('Post Id: ' + res.id);
        });

      // Create the user OAuth profile
      var providerUserProfile = {
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:JSON.stringify(providerData),
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<|endoftext|>


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

    /*jslint
        browser: true
    */
    /*global
        L, reqwest
    */

    var map,
        mapContainer = document.getElementById('journey-overlay'),
        layerGroup = L.layerGroup(),
        tileURL = 'https://maps.bustimes.org/styles/klokantech-basic/{z}/{x}/{y}' + (L.Browser.retina ? '@2x' : '') + '.png';

    function getMarker(latLng, direction) {
        direction = (direction || 0) - 135;
        return L.marker(latLng, {
            icon: L.divIcon({
                iconSize: [16, 16],
                html: '

',
                className: 'just-arrow'
            })
        }).on('mouseover', function () {
            this.openPopup();
        });
    }

    var timeMarkerOptions = {
        radius: 3,
        fillColor: '#000',
        fillOpacity: 1,
        weight: 0,
    };

    function closeMap() {
        mapContainer.style.display = 'none';
        return false;
    }

    window.onkeydown = function(event) {
        if (map && event.keyCode === 27) {
            closeMap();
        }
    };

    var closeButton = L.control();

    closeButton.onAdd = function() {
        var div = document.createElement('div');
        div.className = 'leaflet-bar';
        var a = document.createElement('a');
        a.href = '#';
        a.style.width = 'auto';
        a.style.padding = '0 8px';
        a.setAttribute('role', 'button');
        a.innerHTML = 'Close map';
        a.onclick = closeMap;
        div.appendChild(a);
        return div;
    };

    function openMap(event) {
        var row = event.target.parentElement.parentElement,
            previous = row.previousElementSibling,
            next = row.nextElementSibling,
            details = document.getElementById('details'),
            dateTime,
            popup,
            delta,
            coordinates,
            line = [],
            bounds,
            latDistance,
            lngDistance,
            timeDistance,
            previousTime,
            previousCoordinates;

        mapContainer.style.display = 'block';

        var routeOrVehicle = row.children[0].innerHTML,
            journey = row.children[1].innerHTML,
            destination = row.children[2].innerHTML;

        if (destination) {
            destination = ' to ' + destination;
        }
        details.innerHTML = '
' + routeOrVehicle + ' – ' + journey + destination + '
';

        if (previous && previous.children[3].children[0]) {
            var previousButton = document.createElement('a');
            previousButton.href = '#';
            previousButton.innerHTML = '← ' + previous.children[1].innerHTML;
            previousButton.onclick = function() {
                previous.children[3].children[0].click();
                return false;
            };
            var previousP = document.createElement('p');
            previousP.className = 'previous';
            previousP.appendChild(previousButton);
            details.appendChild(previousP);
        }
        if (next && next.children[3].children[0]) {
            var nextButton = document.createElement('a');
            nextButton.href = '#';
            nextButton.innerHTML = next.children[1].innerHTML + ' →';
            nextButton.onclick = function() {
                next.children[3].children[0].click();
                return false;
            };
            var nextP = document.createElement('p');
            nextP.className = 'next';
            nextP.appendChild(nextButton);
            details.appendChild(nextP);
        }

        reqwest('/journeys/' + event.target.getAttribute('data-journey-id') + '.json', function(locations) {

            if (map) {
                layerGroup.clearLayers();
                map.invalidateSize();
            } else {
                map =  L.map('map');
                layerGroup.addTo(map);

                map.attributionControl.setPrefix('');

                L.tileLayer(tileURL, {
                    attribution: '© MapTiler © OpenStreetMap contributors'
                }).addTo(map);

                closeButton.addTo(map);
            }

            var j,
                minutes,
                latSpeed,
                lngSpeed;

            for (var i = locations.length - 1; i >= 0; i -= 1) {
                dateTime = new Date(locations[i].datetime);
                popup = dateTime.toTimeString().slice(0, 8);
                delta = locations[i].delta;
                if (delta) {
                    popup += '
About ';
                    if (delta > 0) {
                        popup += delta;
                    } else {
                        popup += delta * -1;
                    }
                    popup += ' minute';
                    if (delta !== 1 && delta !== -1) {
                        popup += 's';
                    }
                    if (delta > 0) {
                        popup += ' early';
                    } else {
                        popup += ' late';
                    }
                }
                coordinates = L.latLng(locations[i].coordinates[1], locations[i].coordinates[0]);
                getMarker(coordinates, locations[i].direction).bindPopup(popup).addTo(layerGroup);

                if (previousCoordinates) {
                    latDistance = previousCoordinates.lat - coordinates.lat;
                    lngDistance = previousCoordinates.lng - coordinates.lng;
                    timeDistance = previousTime.getTime() - dateTime.getTime();
                    minutes = timeDistance / 60000;
                    latSpeed = latDistance/minutes;
                    lngSpeed = lngDistance/minutes;
                    for (j = minutes; j >= 0; j -= 1) {
                        L.circleMarker(
                            L.latLng(
                                previousCoordinates.lat - latSpeed * j,
                                previousCoordinates.lng - lngSpeed * j
                            ),
                            timeMarkerOptions
                        ).addTo(layerGroup);
                    }
                }
                line.push(coordinates);
                previousTime = dateTime;
                previousCoordinates = coordinates;
            }
            line = L.polyline(line, {
                style: {
                    weight: 3,
                    color: '#87f'
                }
            });
            line.addTo(layerGroup);
            bounds = line.getBounds();
            map.fitBounds(bounds);
            map.setMaxBounds(bounds.pad(.5));
            line.bringToBack();
        });
    }

    var i,
        buttons = document.getElementsByTagName('button');

    for (i = buttons.length - 1; i >= 0; i -= 1) {
        buttons[i].onclick = openMap;
    }
})();
<commit_msg>markers every minute on the minute<commit_after>(function () {
    'use strict';

    /*jslint
        browser: true
    */
    /*global
        L, reqwest
    */

    var map,
        mapContainer = document.getElementById('journey-overlay'),
        layerGroup = L.layerGroup(),
        tileURL = 'https://maps.bustimes.org/styles/klokantech-basic/{z}/{x}/{y}' + (L.Browser.retina ? '@2x' : '') + '.png';

    function getMarker(latLng, direction) {
        direction = (direction || 0) - 135;
        return L.marker(latLng, {
            icon: L.divIcon({
                iconSize: [16, 16],
                html: '

',
                className: 'just-arrow'
            })
        }).on('mouseover', function () {
            this.openPopup();
        });
    }

    var timeMarkerOptions = {
        radius: 3,
        fillColor: '#000',
        fillOpacity: 1,
        weight: 0,
    };

    function closeMap() {
        mapContainer.style.display = 'none';
        return false;
    }

    window.onkeydown = function(event) {
        if (map && event.keyCode === 27) {
            closeMap();
        }
    };

    var closeButton = L.control();

    closeButton.onAdd = function() {
        var div = document.createElement('div');
        div.className = 'leaflet-bar';
        var a = document.createElement('a');
        a.href = '#';
        a.style.width = 'auto';
        a.style.padding = '0 8px';
        a.setAttribute('role', 'button');
        a.innerHTML = 'Close map';
        a.onclick = closeMap;
        div.appendChild(a);
        return div;
    };

    function openMap(event) {
        var row = event.target.parentElement.parentElement,
            previous = row.previousElementSibling,
            next = row.nextElementSibling,
            details = document.getElementById('details');

        mapContainer.style.display = 'block';

        var routeOrVehicle = row.children[0].innerHTML,
            journey = row.children[1].innerHTML,
            destination = row.children[2].innerHTML;

        if (destination) {
            destination = ' to ' + destination;
        }
        details.innerHTML = '
' + routeOrVehicle + ' – ' + journey + destination + '
';

        if (previous && previous.children[3].children[0]) {
            var previousButton = document.createElement('a');
            previousButton.href = '#';
            previousButton.innerHTML = '← ' + previous.children[1].innerHTML;
            previousButton.onclick = function() {
                previous.children[3].children[0].click();
                return false;
            };
            var previousP = document.createElement('p');
            previousP.className = 'previous';
            previousP.appendChild(previousButton);
            details.appendChild(previousP);
        }
        if (next && next.children[3].children[0]) {
            var nextButton = document.createElement('a');
            nextButton.href = '#';
            nextButton.innerHTML = next.children[1].innerHTML + ' →';
            nextButton.onclick = function() {
                next.children[3].children[0].click();
                return false;
            };
            var nextP = document.createElement('p');
            nextP.className = 'next';
            nextP.appendChild(nextButton);
            details.appendChild(nextP);
        }

        reqwest('/journeys/' + event.target.getAttribute('data-journey-id') + '.json', function(locations) {

            if (map) {
                layerGroup.clearLayers();
                map.invalidateSize();
            } else {
                map =  L.map('map');
                layerGroup.addTo(map);

                map.attributionControl.setPrefix('');

                L.tileLayer(tileURL, {
                    attribution: '© MapTiler © OpenStreetMap contributors'
                }).addTo(map);

                closeButton.addTo(map);
            }

            var j,
                dateTime,
                popup,
                delta,
                coordinates,
                line = [],
                bounds,
                latDistance,
                lngDistance,
                timeDistance,
                previousCoordinates,
                minutes,
                previousTimestamp,
                latSpeed,
                lngSpeed;

            for (var i = locations.length - 1; i >= 0; i -= 1) {
                dateTime = new Date(locations[i].datetime);
                popup = dateTime.toTimeString().slice(0, 8);
                delta = locations[i].delta;
                if (delta) {
                    popup += '
About ';
                    if (delta > 0) {
                        popup += delta;
                    } else {
                        popup += delta * -1;
                    }
                    popup += ' minute';
                    if (delta !== 1 && delta !== -1) {
                        popup += 's';
                    }
                    if (delta > 0) {
                        popup += ' early';
                    } else {
                        popup += ' late';
                    }
                }
                coordinates = L.latLng(locations[i].coordinates[1], locations[i].coordinates[0]);
                getMarker(coordinates, locations[i].direction).bindPopup(popup).addTo(layerGroup);

                if (previousCoordinates) {
                    latDistance = previousCoordinates.lat - coordinates.lat;
                    lngDistance = previousCoordinates.lng - coordinates.lng;
                    minutes = Math.floor(previousTimestamp / 60000) * 60000;
                    timeDistance = previousTimestamp - dateTime.getTime();
                    latSpeed = latDistance / timeDistance;
                    lngSpeed = lngDistance / timeDistance;

                    for (j = previousTimestamp - minutes; j <= timeDistance; j += 60000) {
                        L.circleMarker(L.latLng(
                            previousCoordinates.lat - latSpeed * j,
                            previousCoordinates.lng - lngSpeed * j
                        ), timeMarkerOptions).addTo(layerGroup);
                    }
                }
                line.push(coordinates);
                previousTimestamp = dateTime.getTime();
                previousCoordinates = coordinates;
            }
            line = L.polyline(line, {
                style: {
                    weight: 3,
                    color: '#87f'
                }
            });
            line.addTo(layerGroup);
            bounds = line.getBounds();
            map.fitBounds(bounds);
            map.setMaxBounds(bounds.pad(.5));
            line.bringToBack();
        });
    }

    var i,
        buttons = document.getElementsByTagName('button');

    for (i = buttons.length - 1; i >= 0; i -= 1) {
        buttons[i].onclick = openMap;
    }
})();
<|endoftext|>


<commit_before>var mc = require('../');

var options = { port: 25566 };
var server = mc.createServer(options);
var players = 0;

var zlib=require("zlib");

server.on('login', function(client) {
  players++;
  console.log("Someone connected!");
  var addr = client.socket.remoteAddress + ':' + client.socket.remotePort;

  client.on('end', function() {
    console.log("Someone left!");
    players--;
  });

  client.write('level_initialize', {});

  var map=new Buffer(4194308);
  map.fill(1);
  map.writeInt32BE(256*64*256,0);
  var compressedMap=zlib.gzipSync(map);

  for(var i=0;i<compressedMap.length;i+=1024) {
    client.write('level_data_chunk', {
      chunk_data: compressedMap.slice(i, Math.min(i + 1024, compressedMap.length)),
      percent_complete: i==0 ? 0 : Math.ceil(i/compressedMap.length * 100)
    });
  }

  client.write('level_finalize', {
    x_size: 256,
    y_size: 64,
    z_size: 256
  });
/*
  client.write('player_teleport',{
    player_id:players,
    x:0,
    y:0,
    z:0,
    yaw:0,
    pitch:0
  });*/

  client.write('spawn_player', {
    player_id: -1,
    player_name: "UserXYZ",
    x: 3184,
    y: 1392,
    z: 5712,
    yaw: 0,
    pitch: 0
  });

  client.write('message', {
    player_id: -1,
    message: 'UserXYZ joined the game'
  });

});

server.on('error', function(error) {
  console.log('Oops! Something went wrong, ', error);
});

server.on('listening', function() {
  console.log('Server running on port', server.socketServer.address().port + "!");
});<commit_msg>remove player_teleport from server example<commit_after>var mc = require('../');

var options = { port: 25566 };
var server = mc.createServer(options);
var players = 0;

var zlib=require("zlib");

server.on('login', function(client) {
  players++;
  console.log("Someone connected!");
  var addr = client.socket.remoteAddress + ':' + client.socket.remotePort;

  client.on('end', function() {
    console.log("Someone left!");
    players--;
  });

  client.write('level_initialize', {});

  var map=new Buffer(4194308);
  map.fill(1);
  map.writeInt32BE(256*64*256,0);
  var compressedMap=zlib.gzipSync(map);

  for(var i=0;i<compressedMap.length;i+=1024) {
    client.write('level_data_chunk', {
      chunk_data: compressedMap.slice(i, Math.min(i + 1024, compressedMap.length)),
      percent_complete: i==0 ? 0 : Math.ceil(i/compressedMap.length * 100)
    });
  }

  client.write('level_finalize', {
    x_size: 256,
    y_size: 64,
    z_size: 256
  });

  client.write('spawn_player', {
    player_id: -1,
    player_name: "UserXYZ",
    x: 3184,
    y: 1392,
    z: 5712,
    yaw: 0,
    pitch: 0
  });

  client.write('message', {
    player_id: -1,
    message: 'UserXYZ joined the game'
  });

});

server.on('error', function(error) {
  console.log('Oops! Something went wrong, ', error);
});

server.on('listening', function() {
  console.log('Server running on port', server.socketServer.address().port + "!");
});<|endoftext|>


<commit_before>import { register as registerPushNotifications } from 'flavours/glitch/actions/push_notifications';
import { default as Mastodon, store } from 'flavours/glitch/containers/mastodon';
import React from 'react';
import ReactDOM from 'react-dom';
import ready from './ready';

const perf = require('./performance');

function main() {
  perf.start('main()');

  if (window.history && history.replaceState) {
    const { pathname, search, hash } = window.location;
    const path = pathname + search + hash;
    if (!(/^\/web[$/]/).test(path)) {
      history.replaceState(null, document.title, `/web${path}`);
    }
  }

  ready(() => {
    const mountNode = document.getElementById('mastodon');
    const props = JSON.parse(mountNode.getAttribute('data-props'));

    ReactDOM.render(<Mastodon {...props} />, mountNode);
    if (process.env.NODE_ENV === 'production') {
      // avoid offline in dev mode because it's harder to debug
      require('offline-plugin/runtime').install();
      store.dispatch(registerPushNotifications.register());
    }
    perf.stop('main()');

    // remember the initial URL
    if (window.history && typeof window._mastoInitialHistoryLen === 'undefined') {
      window._mastoInitialHistoryLen = window.history.length;
    }
  });
}

export default main;
<commit_msg>bug fix (tootsuite pr #6120)<commit_after>import * as registerPushNotifications from 'flavours/glitch/actions/push_notifications';
import { default as Mastodon, store } from 'flavours/glitch/containers/mastodon';
import React from 'react';
import ReactDOM from 'react-dom';
import ready from './ready';

const perf = require('./performance');

function main() {
  perf.start('main()');

  if (window.history && history.replaceState) {
    const { pathname, search, hash } = window.location;
    const path = pathname + search + hash;
    if (!(/^\/web[$/]/).test(path)) {
      history.replaceState(null, document.title, `/web${path}`);
    }
  }

  ready(() => {
    const mountNode = document.getElementById('mastodon');
    const props = JSON.parse(mountNode.getAttribute('data-props'));

    ReactDOM.render(<Mastodon {...props} />, mountNode);
    if (process.env.NODE_ENV === 'production') {
      // avoid offline in dev mode because it's harder to debug
      require('offline-plugin/runtime').install();
      store.dispatch(registerPushNotifications.register());
    }
    perf.stop('main()');

    // remember the initial URL
    if (window.history && typeof window._mastoInitialHistoryLen === 'undefined') {
      window._mastoInitialHistoryLen = window.history.length;
    }
  });
}

export default main;
<|endoftext|>


<commit_before>'use strict';

angular.module('angularInputValidator.directives.customValidators', [])
	.directive('nmCustomValidators', function(nmCustomValidators){
		return {
			require: '?ngModel',
			restrict: 'A',
			scope: {
				nmCustomValidators: '=',
			},
			link: function(scope, elm, attrs, ctrl){
				if(!ctrl) return;
				var validations = [],
					allowedFails = 0,
					runValidators = function(modelValue){
						validations.forEach(function(validation){
							validation.value = ctrl.$isEmpty(modelValue) || validation.validator.fn(modelValue);
						});
						var fails = validations.reduce(function(memo, validation){
							return (validation.value) ? memo : memo + 1;
						}, 0);
						validations.forEach(function(validation){
							ctrl.$setValidity(validation.validator.name, (fails <= allowedFails) || validation.value);
						});
						console.log(ctrl.$valid);
				},
					setValidators = function(newValidators){
						if(newValidators){
							validations = [];
							newValidators.forEach(function(validatorName){
								validations.push({validator: nmCustomValidators.getRule(validatorName)});
							});
						}
						runValidators(ctrl.$modelValue);
				};

				scope.$watch('nmCustomValidators', setValidators);
				scope.$watch(function(){return ctrl.$modelValue;}, runValidators);
				attrs.$observe('nmAllowFails', function(newAllowedFails){
					allowedFails = (newAllowedFails) ? parseInt(newAllowedFails) : 0;
				});
			}
		};
	});<commit_msg>removed console log<commit_after>'use strict';

angular.module('angularInputValidator.directives.customValidators', [])
	.directive('nmCustomValidators', function(nmCustomValidators){
		return {
			require: '?ngModel',
			restrict: 'A',
			scope: {
				nmCustomValidators: '=',
			},
			link: function(scope, elm, attrs, ctrl){
				if(!ctrl) return;
				var validations = [],
					allowedFails = 0,
					runValidators = function(modelValue){
						validations.forEach(function(validation){
							validation.value = ctrl.$isEmpty(modelValue) || validation.validator.fn(modelValue);
						});
						var fails = validations.reduce(function(memo, validation){
							return (validation.value) ? memo : memo + 1;
						}, 0);
						validations.forEach(function(validation){
							ctrl.$setValidity(validation.validator.name, (fails <= allowedFails) || validation.value);
						});
				},
					setValidators = function(newValidators){
						if(newValidators){
							validations = [];
							newValidators.forEach(function(validatorName){
								validations.push({validator: nmCustomValidators.getRule(validatorName)});
							});
						}
						runValidators(ctrl.$modelValue);
				};

				scope.$watch('nmCustomValidators', setValidators);
				scope.$watch(function(){return ctrl.$modelValue;}, runValidators);
				attrs.$observe('nmAllowFails', function(newAllowedFails){
					allowedFails = (newAllowedFails) ? parseInt(newAllowedFails) : 0;
				});
			}
		};
	});<|endoftext|>


<commit_before>// Node modules.
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { apiRequest } from 'platform/utilities/api';
import { connect } from 'react-redux';
// Relative imports.
import { toggleLoginModal as toggleLoginModalAction } from 'platform/site-wide/user-nav/actions';

import ServiceProvidersText, {
  ServiceProvidersTextCreateAcct,
} from 'platform/user/authentication/components/ServiceProvidersText';

export const App = ({ loggedIn, toggleLoginModal }) => {
  const [lastUpdated, updateLastUpdated] = useState('');
  const [year, updateYear] = useState(0);
  const [formError, updateFormError] = useState({ error: false, type: '' }); // types: "not found", "download error"
  const [formDownloaded, updateFormDownloaded] = useState({
    downloaded: false,
    timeStamp: '',
  });

  const getPdf = () => {
    return apiRequest(`/form1095_bs/download/${year}`)
      .then(response => response.blob())
      .then(blob => {
        return window.URL.createObjectURL(blob);
      })
      .catch(() => updateFormError({ error: true, type: 'download error' }));
  };

  const getLastUpdatedOn = () => {
    return apiRequest('/form1095_bs/available_forms')
      .then(response => {
        if (response.errors) {
          updateFormError({ error: true, type: 'not found' });
        }

        return response.availableForms[0];
      })
      .catch(() => updateFormError({ error: true, type: 'not found' }));
  };

  const callLastUpdated = () => {
    getLastUpdatedOn().then(result => {
      if (result.lastUpdated && result.year) {
        const date = new Date(result.lastUpdated);
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        // expected output (varies according to local timezone and default locale): December 20, 2012
        updateLastUpdated(date.toLocaleDateString(undefined, options));
        updateYear(result.year);
      } else {
        updateFormError({ error: true, type: 'not found' });
      }
    });
  };

  // VA content time formatting - should be lowercase with periods
  const formatTimeString = string => {
    if (string.includes('AM')) {
      return string.replace('AM', 'a.m.');
    }
    return string.replace('PM', 'p.m.');
  };

  const callGetPDF = () => {
    getPdf().then(result => {
      const a = document.createElement('a');
      a.href = result;
      a.target = '_blank';
      document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
      a.click();
      a.remove(); // removes element from the DOM
      const date = new Date();
      const options = {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        hour12: true,
      };
      updateFormError({ error: false, type: '' });
      updateFormDownloaded({
        downloaded: true,
        timeStamp: formatTimeString(
          date.toLocaleDateString(undefined, options),
        ),
      });
    });
  };

  useEffect(
    () => {
      callLastUpdated();
    },
    [loggedIn],
  );

  const lastUpdatedComponent = (

        Related to: Health care

        Document last updated: {lastUpdated}

  );

  const downloadButton = (

      <button
        className="usa-button-primary va-button-primary"
        onClick={function() {
          callGetPDF();
        }}
        id="download-url"
      >
        Download your 1095-B tax form (PDF){' '}
      </button>

  );

  const notFoundComponent = (
    <va-alert close-btn-aria-label="Close notification" status="info" visible>

        You don’t have a 1095-B tax form available right now

          If you recently enrolled in VA health care, you may not have a 1095-B
          form yet. We process 1095-B forms in early January each year, based on
          your enrollment in VA health care during the past year.

          If you think you should have a 1095-B form, call us at{' '}
          1-877-222-8387 (TTY: 711). We’re here
          Monday through Friday, 8:00 a.m. to 8:00 p.m. ET.

    </va-alert>
  );

  const errorComponent = (
    <>
      {lastUpdatedComponent}
      <va-alert
        close-btn-aria-label="Close notification"
        status="warning"
        visible
      >

We couldn’t download your form

            We’re sorry. Something went wrong when we tried to download your
            form. Please try again. If your form still doesn’t download, call us
            at 800-698-2411 (TTY: 711). We’re
            here 24/7.

      </va-alert>
      {downloadButton}
    </>
  );

  const successComponent = (
    <>
      {lastUpdatedComponent}
      <va-alert
        close-btn-aria-label="Close notification"
        status="success"
        visible
      >

Download Complete

            You successfully downloaded your 1095-B tax form. Please check your
            files.
            {formDownloaded.timeStamp}

      </va-alert>
      {downloadButton}
    </>
  );

  const loggedInComponent = (
    <>
      {lastUpdatedComponent}
      {downloadButton}
    </>
  );

  const loggedOutComponent = (
    <va-alert
      close-btn-aria-label="Close notification"
      status="continue"
      visible
    >

        Please sign in to download your 1095-B tax document

        Sign in with your existing <ServiceProvidersText isBold /> account.{' '}
        <ServiceProvidersTextCreateAcct />

      <button
        type="button"
        onClick={() => toggleLoginModal(true)}
        className="usa-button-primary va-button-primary vads-u-margin-top--2"
      >
        Sign in or create an account
      </button>
    </va-alert>
  );

  if (loggedIn) {
    if (formError.error) {
      if (formError.type === 'not found') {
        return notFoundComponent;
      }
      if (formError.type === 'download error') {
        return errorComponent;
      }
    } else if (formDownloaded.downloaded) {
      return successComponent;
    }
    return loggedInComponent;
  }
  return loggedOutComponent;
};

App.propTypes = {
  loggedIn: PropTypes.bool,
  toggleLoginModal: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  loggedIn: state?.user?.login?.currentlyLoggedIn || null,
});

const mapDispatchToProps = dispatch => ({
  toggleLoginModal: open => dispatch(toggleLoginModalAction(open)),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(App);
<commit_msg>updated 1095B widget to have the TTY number separate and with an aria label (#20808)<commit_after>// Node modules.
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { apiRequest } from 'platform/utilities/api';
import { connect } from 'react-redux';
// Relative imports.
import { toggleLoginModal as toggleLoginModalAction } from 'platform/site-wide/user-nav/actions';

import ServiceProvidersText, {
  ServiceProvidersTextCreateAcct,
} from 'platform/user/authentication/components/ServiceProvidersText';

export const App = ({ loggedIn, toggleLoginModal }) => {
  const [lastUpdated, updateLastUpdated] = useState('');
  const [year, updateYear] = useState(0);
  const [formError, updateFormError] = useState({ error: false, type: '' }); // types: "not found", "download error"
  const [formDownloaded, updateFormDownloaded] = useState({
    downloaded: false,
    timeStamp: '',
  });

  const getPdf = () => {
    return apiRequest(`/form1095_bs/download/${year}`)
      .then(response => response.blob())
      .then(blob => {
        return window.URL.createObjectURL(blob);
      })
      .catch(() => {
        updateFormError({ error: true, type: 'download error' });
        return false;
      });
  };

  const getLastUpdatedOn = () => {
    return apiRequest('/form1095_bs/available_forms')
      .then(response => {
        if (response.errors) {
          updateFormError({ error: true, type: 'not found' });
        }

        return response.availableForms[0];
      })
      .catch(() => updateFormError({ error: true, type: 'not found' }));
  };

  const callLastUpdated = () => {
    getLastUpdatedOn().then(result => {
      if (result.lastUpdated && result.year) {
        const date = new Date(result.lastUpdated);
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        // expected output (varies according to local timezone and default locale): December 20, 2012
        updateLastUpdated(date.toLocaleDateString(undefined, options));
        updateYear(result.year);
      } else {
        updateFormError({ error: true, type: 'not found' });
      }
    });
  };

  // VA content time formatting - should be lowercase with periods
  const formatTimeString = string => {
    if (string.includes('AM')) {
      return string.replace('AM', 'a.m.');
    }
    return string.replace('PM', 'p.m.');
  };

  const callGetPDF = () => {
    getPdf().then(result => {
      if (result) {
        const a = document.createElement('a');
        a.href = result;
        a.target = '_blank';
        document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
        a.click();
        a.remove(); // removes element from the DOM
        const date = new Date();
        const options = {
          year: 'numeric',
          month: 'numeric',
          day: 'numeric',
          hour: 'numeric',
          minute: 'numeric',
          hour12: true,
        };
        updateFormError({ error: false, type: '' });
        updateFormDownloaded({
          downloaded: true,
          timeStamp: formatTimeString(
            date.toLocaleDateString(undefined, options),
          ),
        });
      }
    });
  };

  useEffect(
    () => {
      callLastUpdated();
    },
    [loggedIn],
  );

  const lastUpdatedComponent = (

        Related to: Health care

        Document last updated: {lastUpdated}

  );

  const downloadButton = (

      <button
        className="usa-button-primary va-button-primary"
        onClick={function() {
          callGetPDF();
        }}
        id="download-url"
      >
        Download your 1095-B tax form (PDF){' '}
      </button>

  );

  const notFoundComponent = (
    <va-alert close-btn-aria-label="Close notification" status="info" visible>

        You don’t have a 1095-B tax form available right now

          If you recently enrolled in VA health care, you may not have a 1095-B
          form yet. We process 1095-B forms in early January each year, based on
          your enrollment in VA health care during the past year.

          If you think you should have a 1095-B form, call us at{' '}

            1-877-222-8387
          {' '}
          (

            TTY: 711

          ). We’re here Monday through Friday, 8:00 a.m. to 8:00 p.m. ET.

    </va-alert>
  );

  const errorComponent = (
    <>
      {lastUpdatedComponent}
      <va-alert
        close-btn-aria-label="Close notification"
        status="warning"
        visible
      >

We couldn’t download your form

            We’re sorry. Something went wrong when we tried to download your
            form. Please try again. If your form still doesn’t download, call us
            at{' '}

              1-800-698-2411
            {' '}
            (

              TTY: 711

            ). We’re here 24/7.

      </va-alert>
      {downloadButton}
    </>
  );

  const successComponent = (
    <>
      {lastUpdatedComponent}
      <va-alert
        close-btn-aria-label="Close notification"
        status="success"
        visible
      >

Download Complete

            You successfully downloaded your 1095-B tax form. Please check your
            files.
            {formDownloaded.timeStamp}

      </va-alert>
      {downloadButton}
    </>
  );

  const loggedInComponent = (
    <>
      {lastUpdatedComponent}
      {downloadButton}
    </>
  );

  const loggedOutComponent = (
    <va-alert
      close-btn-aria-label="Close notification"
      status="continue"
      visible
    >

        Please sign in to download your 1095-B tax document

        Sign in with your existing <ServiceProvidersText isBold /> account.{' '}
        <ServiceProvidersTextCreateAcct />

      <button
        type="button"
        onClick={() => toggleLoginModal(true)}
        className="usa-button-primary va-button-primary vads-u-margin-top--2"
      >
        Sign in or create an account
      </button>
    </va-alert>
  );

  if (loggedIn) {
    if (formError.error) {
      if (formError.type === 'not found') {
        return notFoundComponent;
      }
      if (formError.type === 'download error') {
        return errorComponent;
      }
    } else if (formDownloaded.downloaded) {
      return successComponent;
    }
    return loggedInComponent;
  }
  return loggedOutComponent;
};

App.propTypes = {
  loggedIn: PropTypes.bool,
  toggleLoginModal: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  loggedIn: state?.user?.login?.currentlyLoggedIn || null,
});

const mapDispatchToProps = dispatch => ({
  toggleLoginModal: open => dispatch(toggleLoginModalAction(open)),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(App);
<|endoftext|>


<commit_before>var imageAddr = "https://jdc20181.github.io/testpics/tiger-1526704_1920.png";
var downloadSize = 4885771; //bytes
function ShowProgressMessage(msg) {
    if (console) {
        if (typeof msg == "string") {
            console.log(msg);
        } else {
            for (var i = 0; i < msg.length; i++) {
                console.log(msg[i]);
            }
        }
    }

    var oProgress = document.getElementById("progress");
    if (oProgress) {
        var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");
        oProgress.innerHTML = actualHTML;
    }
}
function InitiateSpeedDetection() {
    ShowProgressMessage("Loading the image, please wait...");
    window.setTimeout(MeasureConnectionSpeed, 1);
};
if (window.addEventListener) {
    window.addEventListener('load', InitiateSpeedDetection, false);
} else if (window.attachEvent) {
    window.attachEvent('onload', InitiateSpeedDetection);
}
function MeasureConnectionSpeed() {
    var startTime, endTime;
    var download = new Image();
    download.onload = function () {
        endTime = (new Date()).getTime();
        showResults();
    }

    download.onerror = function (err, msg) {
        ShowProgressMessage("Invalid image, or error downloading");
    }

    startTime = (new Date()).getTime();
    var cacheBuster = "?nnn=" + startTime;
    download.src = imageAddr + cacheBuster;

 function showResults() {
        var duration = (endTime - startTime) / 1000;
        var bitsLoaded = downloadSize * 8;
        var speedBps = (bitsLoaded / duration);
        var speedKbps = (speedBps / 1024);
        var speedMbps = (speedKbps / 1024);
        ShowProgressMessage([
            "Your connection speed is:",
            speedBps.toFixed(2) + " bps",
            speedKbps.toFixed(2) + " kbps",
            speedMbps.toFixed(2) + " Mbps",
        ]);
}
}
<commit_msg>Archives old. Has been removed. <commit_after><|endoftext|>


<commit_before>'use strict';
'require view';
'require poll';
'require ui';
'require uci';
'require rpc';
'require form';

var callInitList, callInitAction, callTimezone,
    callGetLocaltime, callSetLocaltime, CBILocalTime;

callInitList = rpc.declare({
	object: 'luci',
	method: 'getInitList',
	params: [ 'name' ],
	expect: { '': {} },
	filter: function(res) {
		for (var k in res)
			return +res[k].enabled;
		return null;
	}
});

callInitAction = rpc.declare({
	object: 'luci',
	method: 'setInitAction',
	params: [ 'name', 'action' ],
	expect: { result: false }
});

callGetLocaltime = rpc.declare({
	object: 'luci',
	method: 'getLocaltime',
	expect: { result: 0 }
});

callSetLocaltime = rpc.declare({
	object: 'luci',
	method: 'setLocaltime',
	params: [ 'localtime' ],
	expect: { result: 0 }
});

callTimezone = rpc.declare({
	object: 'luci',
	method: 'getTimezones',
	expect: { '': {} }
});

CBILocalTime = form.DummyValue.extend({
	renderWidget: function(section_id, option_id, cfgvalue) {
		return E([], [
			E('input', {
				'id': 'localtime',
				'type': 'text',
				'readonly': true,
				'value': new Date(cfgvalue * 1000).toLocaleString()
			}),
			E('br'),
			E('span', { 'class': 'control-group' }, [
				E('button', {
					'class': 'cbi-button cbi-button-apply',
					'click': ui.createHandlerFn(this, function() {
						return callSetLocaltime(Math.floor(Date.now() / 1000));
					}),
					'disabled': (this.readonly != null) ? this.readonly : this.map.readonly
				}, _('Sync with browser')),
				' ',
				this.ntpd_support ? E('button', {
					'class': 'cbi-button cbi-button-apply',
					'click': ui.createHandlerFn(this, function() {
						return callInitAction('sysntpd', 'restart');
					}),
					'disabled': (this.readonly != null) ? this.readonly : this.map.readonly
				}, _('Sync with NTP-Server')) : ''
			])
		]);
	},
});

return view.extend({
	load: function() {
		return Promise.all([
			callInitList('sysntpd'),
			callTimezone(),
			callGetLocaltime(),
			uci.load('luci'),
			uci.load('system')
		]);
	},

	render: function(rpc_replies) {
		var ntpd_enabled = rpc_replies[0],
		    timezones = rpc_replies[1],
		    localtime = rpc_replies[2],
		    m, s, o;

		m = new form.Map('system',
			_('System'),
			_('Here you can configure the basic aspects of your device like its hostname or the timezone.'));

		m.chain('luci');

		s = m.section(form.TypedSection, 'system', _('System Properties'));
		s.anonymous = true;
		s.addremove = false;

		s.tab('general', _('General Settings'));
		s.tab('logging', _('Logging'));
		s.tab('timesync', _('Time Synchronization'));
		s.tab('language', _('Language and Style'));

		/*
		 * System Properties
		 */

		o = s.taboption('general', CBILocalTime, '_systime', _('Local Time'));
		o.cfgvalue = function() { return localtime };
		o.ntpd_support = ntpd_enabled;

		o = s.taboption('general', form.Value, 'hostname', _('Hostname'));
		o.datatype = 'hostname';

		o = s.taboption('general', form.ListValue, 'zonename', _('Timezone'));
		o.value('UTC');

		var zones = Object.keys(timezones || {}).sort();
		for (var i = 0; i < zones.length; i++)
			o.value(zones[i]);

		o.write = function(section_id, formvalue) {
			var tz = timezones[formvalue] ? timezones[formvalue].tzstring : null;
			uci.set('system', section_id, 'zonename', formvalue);
			uci.set('system', section_id, 'timezone', tz);
		};

		/*
		 * Logging
		 */

		o = s.taboption('logging', form.Value, 'log_size', _('System log buffer size'), "kiB")
		o.optional    = true
		o.placeholder = 16
		o.datatype    = 'uinteger'

		o = s.taboption('logging', form.Value, 'log_ip', _('External system log server'))
		o.optional    = true
		o.placeholder = '0.0.0.0'
		o.datatype    = 'host'

		o = s.taboption('logging', form.Value, 'log_port', _('External system log server port'))
		o.optional    = true
		o.placeholder = 514
		o.datatype    = 'port'

		o = s.taboption('logging', form.ListValue, 'log_proto', _('External system log server protocol'))
		o.value('udp', 'UDP')
		o.value('tcp', 'TCP')

		o = s.taboption('logging', form.Value, 'log_file', _('Write system log to file'))
		o.optional    = true
		o.placeholder = '/tmp/system.log'

		o = s.taboption('logging', form.ListValue, 'conloglevel', _('Log output level'))
		o.value(8, _('Debug'))
		o.value(7, _('Info'))
		o.value(6, _('Notice'))
		o.value(5, _('Warning'))
		o.value(4, _('Error'))
		o.value(3, _('Critical'))
		o.value(2, _('Alert'))
		o.value(1, _('Emergency'))

		o = s.taboption('logging', form.ListValue, 'cronloglevel', _('Cron Log Level'))
		o.default = 8
		o.value(5, _('Debug'))
		o.value(8, _('Normal'))
		o.value(9, _('Warning'))

		/*
		 * Zram Properties
		 */

		if (L.hasSystemFeature('zram')) {
			s.tab('zram', _('ZRam Settings'));

			o = s.taboption('zram', form.Value, 'zram_size_mb', _('ZRam Size'), _('Size of the ZRam device in megabytes'));
			o.optional    = true;
			o.placeholder = 16;
			o.datatype    = 'uinteger';

			o = s.taboption('zram', form.ListValue, 'zram_comp_algo', _('ZRam Compression Algorithm'));
			o.optional    = true;
			o.default     = 'lzo';
			o.value('lzo', 'lzo');
			o.value('lz4', 'lz4');
			o.value('zstd', 'zstd');
		}

		/*
		 * Language & Style
		 */

		o = s.taboption('language', form.ListValue, '_lang', _('Language'))
		o.uciconfig = 'luci';
		o.ucisection = 'main';
		o.ucioption = 'lang';
		o.value('auto');

		var k = Object.keys(uci.get('luci', 'languages') || {}).sort();
		for (var i = 0; i < k.length; i++)
			if (k[i].charAt(0) != '.')
				o.value(k[i], uci.get('luci', 'languages', k[i]));

		o = s.taboption('language', form.ListValue, '_mediaurlbase', _('Design'))
		o.uciconfig = 'luci';
		o.ucisection = 'main';
		o.ucioption = 'mediaurlbase';

		var k = Object.keys(uci.get('luci', 'themes') || {}).sort();
		for (var i = 0; i < k.length; i++)
			if (k[i].charAt(0) != '.')
				o.value(uci.get('luci', 'themes', k[i]), k[i]);

		/*
		 * NTP
		 */

		if (L.hasSystemFeature('sysntpd')) {
			var default_servers = [
				'0.openwrt.pool.ntp.org', '1.openwrt.pool.ntp.org',
				'2.openwrt.pool.ntp.org', '3.openwrt.pool.ntp.org'
			];

			o = s.taboption('timesync', form.Flag, 'enabled', _('Enable NTP client'));
			o.rmempty = false;
			o.ucisection = 'ntp';
			o.default = o.disabled;
			o.write = function(section_id, value) {
				ntpd_enabled = +value;

				if (ntpd_enabled && !uci.get('system', 'ntp')) {
					uci.add('system', 'timeserver', 'ntp');
					uci.set('system', 'ntp', 'server', default_servers);
				}

				if (!ntpd_enabled)
					uci.set('system', 'ntp', 'enabled', 0);
				else
					uci.unset('system', 'ntp', 'enabled');

				return callInitAction('sysntpd', 'enable');
			};
			o.load = function(section_id) {
				return (ntpd_enabled == 1 &&
				        uci.get('system', 'ntp') != null &&
				        uci.get('system', 'ntp', 'enabled') != 0) ? '1' : '0';
			};

			o = s.taboption('timesync', form.Flag, 'enable_server', _('Provide NTP server'));
			o.ucisection = 'ntp';
			o.depends('enabled', '1');

			o = s.taboption('timesync', form.Flag, 'use_dhcp', _('Use DHCP advertised servers'));
			o.ucisection = 'ntp';
			o.default = o.enabled;
			o.depends('enabled', '1');

			o = s.taboption('timesync', form.DynamicList, 'server', _('NTP server candidates'));
			o.datatype = 'host(0)';
			o.ucisection = 'ntp';
			o.depends('enabled', '1');
			o.load = function(section_id) {
				return uci.get('system', 'ntp', 'server');
			};
		}

		return m.render().then(function(mapEl) {
			poll.add(function() {
				return callGetLocaltime().then(function(t) {
					mapEl.querySelector('#localtime').value = new Date(t * 1000).toLocaleString();
				});
			});

			return mapEl;
		});
	}
});
<commit_msg>luci-mod-system: implement system.description, system.notes<commit_after>'use strict';
'require view';
'require poll';
'require ui';
'require uci';
'require rpc';
'require form';

var callInitList, callInitAction, callTimezone,
    callGetLocaltime, callSetLocaltime, CBILocalTime;

callInitList = rpc.declare({
	object: 'luci',
	method: 'getInitList',
	params: [ 'name' ],
	expect: { '': {} },
	filter: function(res) {
		for (var k in res)
			return +res[k].enabled;
		return null;
	}
});

callInitAction = rpc.declare({
	object: 'luci',
	method: 'setInitAction',
	params: [ 'name', 'action' ],
	expect: { result: false }
});

callGetLocaltime = rpc.declare({
	object: 'luci',
	method: 'getLocaltime',
	expect: { result: 0 }
});

callSetLocaltime = rpc.declare({
	object: 'luci',
	method: 'setLocaltime',
	params: [ 'localtime' ],
	expect: { result: 0 }
});

callTimezone = rpc.declare({
	object: 'luci',
	method: 'getTimezones',
	expect: { '': {} }
});

CBILocalTime = form.DummyValue.extend({
	renderWidget: function(section_id, option_id, cfgvalue) {
		return E([], [
			E('input', {
				'id': 'localtime',
				'type': 'text',
				'readonly': true,
				'value': new Date(cfgvalue * 1000).toLocaleString()
			}),
			E('br'),
			E('span', { 'class': 'control-group' }, [
				E('button', {
					'class': 'cbi-button cbi-button-apply',
					'click': ui.createHandlerFn(this, function() {
						return callSetLocaltime(Math.floor(Date.now() / 1000));
					}),
					'disabled': (this.readonly != null) ? this.readonly : this.map.readonly
				}, _('Sync with browser')),
				' ',
				this.ntpd_support ? E('button', {
					'class': 'cbi-button cbi-button-apply',
					'click': ui.createHandlerFn(this, function() {
						return callInitAction('sysntpd', 'restart');
					}),
					'disabled': (this.readonly != null) ? this.readonly : this.map.readonly
				}, _('Sync with NTP-Server')) : ''
			])
		]);
	},
});

return view.extend({
	load: function() {
		return Promise.all([
			callInitList('sysntpd'),
			callTimezone(),
			callGetLocaltime(),
			uci.load('luci'),
			uci.load('system')
		]);
	},

	render: function(rpc_replies) {
		var ntpd_enabled = rpc_replies[0],
		    timezones = rpc_replies[1],
		    localtime = rpc_replies[2],
		    m, s, o;

		m = new form.Map('system',
			_('System'),
			_('Here you can configure the basic aspects of your device like its hostname or the timezone.'));

		m.chain('luci');

		s = m.section(form.TypedSection, 'system', _('System Properties'));
		s.anonymous = true;
		s.addremove = false;

		s.tab('general', _('General Settings'));
		s.tab('logging', _('Logging'));
		s.tab('timesync', _('Time Synchronization'));
		s.tab('language', _('Language and Style'));

		/*
		 * System Properties
		 */

		o = s.taboption('general', CBILocalTime, '_systime', _('Local Time'));
		o.cfgvalue = function() { return localtime };
		o.ntpd_support = ntpd_enabled;

		o = s.taboption('general', form.Value, 'hostname', _('Hostname'));
		o.datatype = 'hostname';

		/* could be used also as a default for LLDP, SNMP "system description" in the future */
		o = s.taboption('general', form.Value, 'description', _('Description'), _('An optional, short description for this device'));
		o.optional = true;

		o = s.taboption('general', form.TextValue, 'notes', _('Notes'), _('Optional, free-form notes about this device'));
		o.optional = true;

		o = s.taboption('general', form.ListValue, 'zonename', _('Timezone'));
		o.value('UTC');

		var zones = Object.keys(timezones || {}).sort();
		for (var i = 0; i < zones.length; i++)
			o.value(zones[i]);

		o.write = function(section_id, formvalue) {
			var tz = timezones[formvalue] ? timezones[formvalue].tzstring : null;
			uci.set('system', section_id, 'zonename', formvalue);
			uci.set('system', section_id, 'timezone', tz);
		};

		/*
		 * Logging
		 */

		o = s.taboption('logging', form.Value, 'log_size', _('System log buffer size'), "kiB")
		o.optional    = true
		o.placeholder = 16
		o.datatype    = 'uinteger'

		o = s.taboption('logging', form.Value, 'log_ip', _('External system log server'))
		o.optional    = true
		o.placeholder = '0.0.0.0'
		o.datatype    = 'host'

		o = s.taboption('logging', form.Value, 'log_port', _('External system log server port'))
		o.optional    = true
		o.placeholder = 514
		o.datatype    = 'port'

		o = s.taboption('logging', form.ListValue, 'log_proto', _('External system log server protocol'))
		o.value('udp', 'UDP')
		o.value('tcp', 'TCP')

		o = s.taboption('logging', form.Value, 'log_file', _('Write system log to file'))
		o.optional    = true
		o.placeholder = '/tmp/system.log'

		o = s.taboption('logging', form.ListValue, 'conloglevel', _('Log output level'))
		o.value(8, _('Debug'))
		o.value(7, _('Info'))
		o.value(6, _('Notice'))
		o.value(5, _('Warning'))
		o.value(4, _('Error'))
		o.value(3, _('Critical'))
		o.value(2, _('Alert'))
		o.value(1, _('Emergency'))

		o = s.taboption('logging', form.ListValue, 'cronloglevel', _('Cron Log Level'))
		o.default = 8
		o.value(5, _('Debug'))
		o.value(8, _('Normal'))
		o.value(9, _('Warning'))

		/*
		 * Zram Properties
		 */

		if (L.hasSystemFeature('zram')) {
			s.tab('zram', _('ZRam Settings'));

			o = s.taboption('zram', form.Value, 'zram_size_mb', _('ZRam Size'), _('Size of the ZRam device in megabytes'));
			o.optional    = true;
			o.placeholder = 16;
			o.datatype    = 'uinteger';

			o = s.taboption('zram', form.ListValue, 'zram_comp_algo', _('ZRam Compression Algorithm'));
			o.optional    = true;
			o.default     = 'lzo';
			o.value('lzo', 'lzo');
			o.value('lz4', 'lz4');
			o.value('zstd', 'zstd');
		}

		/*
		 * Language & Style
		 */

		o = s.taboption('language', form.ListValue, '_lang', _('Language'))
		o.uciconfig = 'luci';
		o.ucisection = 'main';
		o.ucioption = 'lang';
		o.value('auto');

		var k = Object.keys(uci.get('luci', 'languages') || {}).sort();
		for (var i = 0; i < k.length; i++)
			if (k[i].charAt(0) != '.')
				o.value(k[i], uci.get('luci', 'languages', k[i]));

		o = s.taboption('language', form.ListValue, '_mediaurlbase', _('Design'))
		o.uciconfig = 'luci';
		o.ucisection = 'main';
		o.ucioption = 'mediaurlbase';

		var k = Object.keys(uci.get('luci', 'themes') || {}).sort();
		for (var i = 0; i < k.length; i++)
			if (k[i].charAt(0) != '.')
				o.value(uci.get('luci', 'themes', k[i]), k[i]);

		/*
		 * NTP
		 */

		if (L.hasSystemFeature('sysntpd')) {
			var default_servers = [
				'0.openwrt.pool.ntp.org', '1.openwrt.pool.ntp.org',
				'2.openwrt.pool.ntp.org', '3.openwrt.pool.ntp.org'
			];

			o = s.taboption('timesync', form.Flag, 'enabled', _('Enable NTP client'));
			o.rmempty = false;
			o.ucisection = 'ntp';
			o.default = o.disabled;
			o.write = function(section_id, value) {
				ntpd_enabled = +value;

				if (ntpd_enabled && !uci.get('system', 'ntp')) {
					uci.add('system', 'timeserver', 'ntp');
					uci.set('system', 'ntp', 'server', default_servers);
				}

				if (!ntpd_enabled)
					uci.set('system', 'ntp', 'enabled', 0);
				else
					uci.unset('system', 'ntp', 'enabled');

				return callInitAction('sysntpd', 'enable');
			};
			o.load = function(section_id) {
				return (ntpd_enabled == 1 &&
				        uci.get('system', 'ntp') != null &&
				        uci.get('system', 'ntp', 'enabled') != 0) ? '1' : '0';
			};

			o = s.taboption('timesync', form.Flag, 'enable_server', _('Provide NTP server'));
			o.ucisection = 'ntp';
			o.depends('enabled', '1');

			o = s.taboption('timesync', form.Flag, 'use_dhcp', _('Use DHCP advertised servers'));
			o.ucisection = 'ntp';
			o.default = o.enabled;
			o.depends('enabled', '1');

			o = s.taboption('timesync', form.DynamicList, 'server', _('NTP server candidates'));
			o.datatype = 'host(0)';
			o.ucisection = 'ntp';
			o.depends('enabled', '1');
			o.load = function(section_id) {
				return uci.get('system', 'ntp', 'server');
			};
		}

		return m.render().then(function(mapEl) {
			poll.add(function() {
				return callGetLocaltime().then(function(t) {
					mapEl.querySelector('#localtime').value = new Date(t * 1000).toLocaleString();
				});
			});

			return mapEl;
		});
	}
});
<|endoftext|>


<commit_before>//= require qunit/qunit
//= require sinon/sinon-1.1.1
//= require sinon/sinon-qunit-1.0.0
<commit_msg>changing load order of sinon and qunit underscore (and potentially other stuff) breaks if qunit is loaded before sinon<commit_after>//= require sinon/sinon-1.1.1
//= require qunit/qunit
//= require sinon/sinon-qunit-1.0.0
<|endoftext|>


<commit_before>import * as types from '../constants/actionTypes';
import {getRestaurantsApi} from '../api/api';

export function updateFilter(value) {
  return {
    type: types.UPDATE_FILTER,
    value,
    pagerNum:1,
    initialLoad: false
  };
}

export function setActiveItem(id, scroll) {
  return {
    type: types.SET_ACTIVE_ITEM,
    id,
    scroll
  };
}
// TODO: Combine next two actions
// Should be called set pagernum
export function increasePagerNum(value) {
  return {
    type: types.INCREASE_PAGER_NUM,
    value
  };
}

export function decreasePagerNum(value) {
  return {
    type: types.DECREASE_PAGER_NUM,
    value
  };
}

export function loadingRestaurants(isLoading) {
  return {
    type: types.LOADING_RESTAURANTS,
    isLoading
  };
}

export function loadRestaurantsSuccess(restaurants, isLoading) {
  return {
    type: types.LOAD_RESTAURANTS_SUCCESS,
    restaurants,
    isLoading
  };
}

export function loadRestaurantsFail(isLoading, error) {
  return {
    type: types.LOAD_RESTAURANTS_FAIL,
    isLoading,
    error
  };
}

export function loadRestaurants(){
  return function(dispatch){
    dispatch(loadingRestaurants(true));
    return getRestaurantsApi().then((response) => {
      dispatch(loadRestaurantsSuccess(response, false));
    }).catch(error => {
      dispatch(loadRestaurantsFail(false, error));
    });
  };
}
<commit_msg>Adding new actions for searching by city, zip, name<commit_after>import * as types from '../constants/actionTypes';
import {getRestaurantsApi, getRestaurantsByNameApi, getRestaurantsByCityApi, getRestaurantsByZipApi} from '../api/api';

export function updateFilter(value) {
  return {
    type: types.UPDATE_FILTER,
    value,
    pagerNum:1,
    initialLoad: false
  };
}

export function setActiveItem(id, scroll) {
  return {
    type: types.SET_ACTIVE_ITEM,
    id,
    scroll
  };
}
// TODO: Combine next two actions
// Should be called set pagernum
export function increasePagerNum(value) {
  return {
    type: types.INCREASE_PAGER_NUM,
    value
  };
}

export function decreasePagerNum(value) {
  return {
    type: types.DECREASE_PAGER_NUM,
    value
  };
}

export function loadingRestaurants(isLoading) {
  return {
    type: types.LOADING_RESTAURANTS,
    isLoading
  };
}

export function loadRestaurantsSuccess(restaurants, isLoading) {
  return {
    type: types.LOAD_RESTAURANTS_SUCCESS,
    restaurants,
    isLoading
  };
}

export function loadRestaurantsFail(isLoading, error) {
  return {
    type: types.LOAD_RESTAURANTS_FAIL,
    isLoading,
    error
  };
}

export function searchingRestaurantsByName(searchIsLoading) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_NAME,
    searchIsLoading
  };
}

export function searchingRestaurantsByNameSuccess(restaurants, searchIsLoading) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_NAME_SUCCESS,
    restaurants,
    searchIsLoading
  };
}

export function searchingRestaurantsByNameFail(searchIsLoading, error) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_NAME_FAIL,
    searchIsLoading,
    error
  };
}
export function searchingRestaurantsByCity(searchIsLoading) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_CITY,
    searchIsLoading
  };
}

export function searchingRestaurantsByCitySuccess(restaurants, searchIsLoading) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_CITY_SUCCESS,
    restaurants,
    searchIsLoading
  };
}

export function searchingRestaurantsByCityFail(searchIsLoading, error) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_CITY_FAIL,
    searchIsLoading,
    error
  };
}
export function searchingRestaurantsByZip(searchIsLoading) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_ZIP,
    searchIsLoading
  };
}

export function searchingRestaurantsByZipSuccess(restaurants, searchIsLoading) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_ZIP_SUCCESS,
    restaurants,
    searchIsLoading
  };
}

export function searchingRestaurantsByZipFail(searchIsLoading, error) {
  return {
    type: types.SEARCHING_RESTAURANTS_BY_ZIP_FAIL,
    searchIsLoading,
    error
  };
}

export function loadRestaurants(){
  return function(dispatch){
    dispatch(loadingRestaurants(true));
    return getRestaurantsApi().then((response) => {
      dispatch(loadRestaurantsSuccess(response, false));
    }).catch(error => {
      dispatch(loadRestaurantsFail(false, error));
    });
  };
}

export function searchRestaurants(name){
  return function(dispatch){
    dispatch(searchingRestaurantsByName(true));
    return getRestaurantsByNameApi(name).then((response) => {
      dispatch(searchingRestaurantsByNameSuccess(response, false));
    }).catch(error => {
      dispatch(searchingRestaurantsByNameFail(false, error));
    });
  };
}
export function searchCity(city){
  return function(dispatch){
    dispatch(searchingRestaurantsByCity(true));
    return getRestaurantsByCityApi(city).then((response) => {
      dispatch(searchingRestaurantsByCitySuccess(response, false));
    }).catch(error => {
      dispatch(searchingRestaurantsByCityFail(false, error));
    });
  };
}
export function searchZip(zip){
  return function(dispatch){
    dispatch(searchingRestaurantsByZip(true));
    return getRestaurantsByZipApi(zip).then((response) => {
      dispatch(searchingRestaurantsByZipSuccess(response, false));
    }).catch(error => {
      dispatch(searchingRestaurantsByZipFail(false, error));
    });
  };
}
<|endoftext|>


<commit_before>import React from 'react';

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleKey = this.handleKey.bind(this);
    this.state = {
      value: ''
    }
  }
  handleKey(event) {
    if (event.keyCode === 13) {
      this.props.onCreate(event.target.value);
      this.setState({value: ''});
      return false;
    }
  }
  handleChange(event) {
    event.preventDefault();
    let value = event.target.value;
    this.setState({value});
    this.props.onSearch(value);
  }
  render() {
    return (

        <object type="image/svg+xml" data="/logo.svg" className="sidebar-header__logo">

        </object>
        <input
          className="sidebar-header__input"
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
          onKeyDown={this.handleKey} />

    );
  }
}

export default Header;<commit_msg>updates path to img<commit_after>import React from 'react';

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleKey = this.handleKey.bind(this);
    this.state = {
      value: ''
    }
  }
  handleKey(event) {
    if (event.keyCode === 13) {
      this.props.onCreate(event.target.value);
      this.setState({value: ''});
      return false;
    }
  }
  handleChange(event) {
    event.preventDefault();
    let value = event.target.value;
    this.setState({value});
    this.props.onSearch(value);
  }
  render() {
    return (

        <object type="image/svg+xml" data="/logo.svg" className="sidebar-header__logo">

        </object>
        <input
          className="sidebar-header__input"
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
          onKeyDown={this.handleKey} />

    );
  }
}

export default Header;<|endoftext|>


<commit_before>module.exports = {

    http_error: function(req, res, info)
    {
        switch (info.code)
        {
            case 401:
                res.status(401).send({ error: true, message: "Unauthorized" });
                break;

            case 403:
                res.status(403).send({ error: true, message: "Forbidden" });
                break;

            case 404:
                res.status(404).send({ error: true, message: "Not Found" });
                break;

            case 409:
                res.status(409).send({ error: true, message: "Conflict" });
                break;

            case 500:
                res.status(500).send({ error: true, message: "Internal Server Error" });
                break;

            default:
                res.status(400).send({ error: true, message: "Bad Request" });
                //console.log(colors.error('GET > ' + req.url + ' - 400 - auth:'), req.session.username);
        }
    },

    http_success: function(req, res, info)
    {
        switch (info.code)
        {
            case 201:
                res.status(201).send({ error: false, message: info.message });
                //console.log(colors.error('GET > ' + req.url + ' - 400 - auth:'), req.session.username);
                break;

            default:
                res.status(200).send({ error: false, message: info.message, data: info.data });

        }
    }
};<commit_msg>~ Update class error, no commentary<commit_after>module.exports = {

    http_error: function(req, res, info)
    {
        switch (info.code)
        {
            case 401:
                res.status(401).send({ error: true, message: "Unauthorized" });
                break;

            case 403:
                res.status(403).send({ error: true, message: "Forbidden" });
                break;

            case 404:
                res.status(404).send({ error: true, message: "Not Found" });
                break;

            case 409:
                res.status(409).send({ error: true, message: "Conflict" });
                break;

            case 500:
                res.status(500).send({ error: true, message: "Internal Server Error" });
                break;

            default:
                res.status(400).send({ error: true, message: "Bad Request" });
        }
    },

    http_success: function(req, res, info)
    {
        switch (info.code)
        {
            case 201:
                res.status(201).send({ error: false, message: info.message });
                break;

            default:
                res.status(200).send({ error: false, message: info.message, data: info.data });
        }
    }
};<|endoftext|>


<commit_before>import Autoresize from '../../mixins/autoresize';
import Component from '@ember/component';
import { set, get } from '@ember/object';
import { tryInvoke, isBlank } from '@ember/utils';
import { later } from '@ember/runloop';
import moment from 'moment';
import layout from './template';

const UP = 38;
const DOWN = 40;

export default Component.extend(Autoresize, {
  layout,
  classNames: ['date-field'],

  /**
    Called whenever the user changes the value.

    @event onchange
    @param {String} value The string
   */

  /**
    The `name` property of the `input` element.

    @property name
    @type String
    @default null
   */
  name: null,

  /**
    The `format` that the date should be displayed in.

    @property format
    @type String
    @default 'M/D/YYYY h:mma'
   */
  format: 'M/D/YYYY h:mma',

  /**
    The `timezone` that the date should be displayed in.

    @property timezone
    @type String
    @default 'America/New_York'
   */
  timezone: 'America/New_York',

  /**
    Whether or not the field is disabled.

    @property disabled
    @type Boolean
    @default false
   */
  disabled: false,

  _getValue() {
    if (get(this, 'isFocused')) {
      let input = get(this, 'element').querySelector('input');
      return input.value;
    } else {
      let value = get(this, 'value');
      return value ? moment(value).format(get(this, 'format')) : '';
    }
  },

  _setValue(value) {
    let date = moment.tz(value, get(this, 'format'), get(this, 'timezone'));
    if (isBlank(value) || value == null) {
      get(this, 'onchange')(null);
    } else if (date.isValid()) {
      set(this, 'center', date);
      get(this, 'onchange')(date.toDate());
    }
    this._updateDisplayValue(value);
  },

  _updateDisplayValue(displayValue) {
    let input = get(this, 'element').querySelector('input');
    let selectionStart = input.selectionStart;
    let selectionEnd = input.selectionEnd;

    set(this, 'displayValue', displayValue || '');
    input.value = displayValue || '';
    if (get(this, 'isFocused')) {
      input.selectionStart = selectionStart;
      input.selectionEnd = selectionEnd;
    }
  },

  actions: {
    handleArrowKeys(evt) {
      if (evt.which === UP || evt.which === DOWN) {
        let input = get(this, 'element').querySelector('input');
        let cursor = input.selectionStart;

        let direction = evt.which === UP ? 1 : -1;
        let date = moment(get(this, 'value'));
        let format = get(this, 'format');
        let formattedDate = date.format(format);
        let separators = formattedDate.replace(/\d+/g, '0').split('0');
        let parts = [];

        let numberStart = 0;
        let formatStart = 0;
        separators.forEach(function (separator) {
          if (separator !== '') {
            let formatEnd = format.indexOf(separator, formatStart);
            let numberEnd = formattedDate.indexOf(separator, numberStart);
            let meridian = '';

            if (formatEnd === -1) {
              formatEnd = format.indexOf('a', formatStart);
            }
            if (formatEnd === -1) {
              formatEnd = format.indexOf('A', formatStart);
            }

            if (format.slice(formatEnd) === 'a' || format.slice(formatEnd) === 'A') {
              meridian = separator;
              separator = '';
            }

            parts.push({
              start: numberStart,
              end: numberEnd + separator.length,
              format: format.slice(formatStart, formatEnd),
              value: formattedDate.slice(numberStart, numberEnd)
            });
            formatStart = formatEnd + separator.length;
            numberStart = numberEnd + separator.length;

            if (meridian) {
              parts.push({
                start: numberStart,
                end: numberStart + meridian.length,
                format: format.slice(formatStart, formatStart + 1),
                value: meridian
              });
              numberStart = numberStart + meridian.length;
              formatStart = formatStart + 1;
            }

          } else if (numberStart !== 0) {
            parts.push({
              start: numberStart,
              end: formattedDate.length + 1,
              format: format.slice(formatStart),
              value: formattedDate.slice(numberStart)
            });
          }
        });

        // Adjust the last item
        parts[parts.length - 1].end++;

        let unit = parts.find(function (part) {
          return cursor >= part.start && cursor < part.end;
        });

        if (unit.format === 'YYYY') {
          date.add(direction, 'year');
        } else if (unit.format === 'M' || unit.fomrat === 'MM') {
          date.add(direction, 'month');
        } else if (unit.format === 'D' || unit.format === 'DD') {
          date.add(direction, 'day');
        } else if (unit.format.match(/h+|k+/i)) {
          date.add(direction, 'hour');
        } else if (unit.format === 'mm') {
          date.add(direction, 'minute');
        } else if (unit.format === 'a' || unit.format === 'A') {
          if (date.hour() < 12) {
            date.add(12, 'hours');
          } else {
            date.subtract(12, 'hours');
          }
        }

        this._setValue(date.format(get(this, 'format')));
        return false;
      }
    },

    restrict(evt) {
      if (evt.shiftKey && evt.which !== 58) {
        return false;
      }

      if (evt.which <= 40) {
        return true;
      }

      return /[:\d\w/apm]/.test(String.fromCharCode(evt.which));
    },

    reformat() {
      let input = get(this, 'element').querySelector('input');
      this._setValue(input.value);
    },

    focus() {
      set(this, 'isFocused', true);
    },

    blur() {
      set(this, 'isFocused', false);
      tryInvoke(this, 'onblur');
    },

    updateCenter({ date }) {
      set(this, 'center', date);
      set(this, 'isFocused', true);
    },

    onchange({ moment }) {
      set(this, 'isActive', false);
      this._setValue(moment.format('MM/DD/YYYY h:mma'));
    }
  }
});
<commit_msg>use 12pm as default instead of 12am<commit_after>import Autoresize from '../../mixins/autoresize';
import Component from '@ember/component';
import { set, get } from '@ember/object';
import { tryInvoke, isBlank } from '@ember/utils';
import { later } from '@ember/runloop';
import moment from 'moment';
import layout from './template';

const UP = 38;
const DOWN = 40;

export default Component.extend(Autoresize, {
  layout,
  classNames: ['date-field'],

  /**
    Called whenever the user changes the value.

    @event onchange
    @param {String} value The string
   */

  /**
    The `name` property of the `input` element.

    @property name
    @type String
    @default null
   */
  name: null,

  /**
    The `format` that the date should be displayed in.

    @property format
    @type String
    @default 'M/D/YYYY h:mma'
   */
  format: 'M/D/YYYY h:mma',

  /**
    The `timezone` that the date should be displayed in.

    @property timezone
    @type String
    @default 'America/New_York'
   */
  timezone: 'America/New_York',

  /**
    Whether or not the field is disabled.

    @property disabled
    @type Boolean
    @default false
   */
  disabled: false,

  _getValue() {
    if (get(this, 'isFocused')) {
      let input = get(this, 'element').querySelector('input');
      return input.value;
    } else {
      let value = get(this, 'value');
      return value ? moment(value).format(get(this, 'format')) : '';
    }
  },

  _setValue(value) {
    let date = moment.tz(value, get(this, 'format'), get(this, 'timezone'));
    if (isBlank(value) || value == null) {
      get(this, 'onchange')(null);
    } else if (date.isValid()) {
      set(this, 'center', date);
      get(this, 'onchange')(date.toDate());
    }
    this._updateDisplayValue(value);
  },

  _updateDisplayValue(displayValue) {
    let input = get(this, 'element').querySelector('input');
    let selectionStart = input.selectionStart;
    let selectionEnd = input.selectionEnd;

    set(this, 'displayValue', displayValue || '');
    input.value = displayValue || '';
    if (get(this, 'isFocused')) {
      input.selectionStart = selectionStart;
      input.selectionEnd = selectionEnd;
    }
  },

  actions: {
    handleArrowKeys(evt) {
      if (evt.which === UP || evt.which === DOWN) {
        let input = get(this, 'element').querySelector('input');
        let cursor = input.selectionStart;

        let direction = evt.which === UP ? 1 : -1;
        let date = moment(get(this, 'value'));
        let format = get(this, 'format');
        let formattedDate = date.format(format);
        let separators = formattedDate.replace(/\d+/g, '0').split('0');
        let parts = [];

        let numberStart = 0;
        let formatStart = 0;
        separators.forEach(function (separator) {
          if (separator !== '') {
            let formatEnd = format.indexOf(separator, formatStart);
            let numberEnd = formattedDate.indexOf(separator, numberStart);
            let meridian = '';

            if (formatEnd === -1) {
              formatEnd = format.indexOf('a', formatStart);
            }
            if (formatEnd === -1) {
              formatEnd = format.indexOf('A', formatStart);
            }

            if (format.slice(formatEnd) === 'a' || format.slice(formatEnd) === 'A') {
              meridian = separator;
              separator = '';
            }

            parts.push({
              start: numberStart,
              end: numberEnd + separator.length,
              format: format.slice(formatStart, formatEnd),
              value: formattedDate.slice(numberStart, numberEnd)
            });
            formatStart = formatEnd + separator.length;
            numberStart = numberEnd + separator.length;

            if (meridian) {
              parts.push({
                start: numberStart,
                end: numberStart + meridian.length,
                format: format.slice(formatStart, formatStart + 1),
                value: meridian
              });
              numberStart = numberStart + meridian.length;
              formatStart = formatStart + 1;
            }

          } else if (numberStart !== 0) {
            parts.push({
              start: numberStart,
              end: formattedDate.length + 1,
              format: format.slice(formatStart),
              value: formattedDate.slice(numberStart)
            });
          }
        });

        // Adjust the last item
        parts[parts.length - 1].end++;

        let unit = parts.find(function (part) {
          return cursor >= part.start && cursor < part.end;
        });

        if (unit.format === 'YYYY') {
          date.add(direction, 'year');
        } else if (unit.format === 'M' || unit.fomrat === 'MM') {
          date.add(direction, 'month');
        } else if (unit.format === 'D' || unit.format === 'DD') {
          date.add(direction, 'day');
        } else if (unit.format.match(/h+|k+/i)) {
          date.add(direction, 'hour');
        } else if (unit.format === 'mm') {
          date.add(direction, 'minute');
        } else if (unit.format === 'a' || unit.format === 'A') {
          if (date.hour() < 12) {
            date.add(12, 'hours');
          } else {
            date.subtract(12, 'hours');
          }
        }

        this._setValue(date.format(get(this, 'format')));
        return false;
      }
    },

    restrict(evt) {
      if (evt.shiftKey && evt.which !== 58) {
        return false;
      }

      if (evt.which <= 40) {
        return true;
      }

      return /[:\d\w/apm]/.test(String.fromCharCode(evt.which));
    },

    reformat() {
      let input = get(this, 'element').querySelector('input');
      this._setValue(input.value);
    },

    focus() {
      set(this, 'isFocused', true);
    },

    blur() {
      set(this, 'isFocused', false);
      tryInvoke(this, 'onblur');
    },

    updateCenter({ date }) {
      set(this, 'center', date);
      set(this, 'isFocused', true);
    },

    onchange({ moment }) {
      set(this, 'isActive', false);
      moment.add(12, 'hours');
      this._setValue(moment.format('MM/DD/YYYY h:mma'));
    }
  }
});
<|endoftext|>