<commit_before>/*
 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
 */

L.GeoJSON = L.FeatureGroup.extend({

	initialize: function (geojson, options) {
		L.setOptions(this, options);

		this._layers = {};

		if (geojson) {
			this.addData(geojson);
		}
	},

	addData: function (geojson) {
		var features = L.Util.isArray(geojson) ? geojson : geojson.features,
		    i, len, feature;

		if (features) {
			for (i = 0, len = features.length; i < len; i++) {
				// Only add this if geometry or geometries are set and not null
				feature = features[i];
				if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
					this.addData(feature);
				}
			}
			return this;
		}

		var options = this.options;

		if (options.filter && !options.filter(geojson)) { return; }

		var layer = L.GeoJSON.geometryToLayer(geojson, options);
		layer.feature = L.GeoJSON.asFeature(geojson);

		layer.defaultOptions = layer.options;
		this.resetStyle(layer);

		if (options.onEachFeature) {
			options.onEachFeature(geojson, layer);
		}

		return this.addLayer(layer);
	},

	resetStyle: function (layer) {
		// reset any custom styles
		layer.options = layer.defaultOptions;
		this._setLayerStyle(layer, this.options.style);
	},

	setStyle: function (style) {
		this.eachLayer(function (layer) {
			this._setLayerStyle(layer, style);
		}, this);
	},

	_setLayerStyle: function (layer, style) {
		if (typeof style === 'function') {
			style = style(layer.feature);
		}
		if (layer.setStyle) {
			layer.setStyle(style);
		}
	}
});

L.extend(L.GeoJSON, {
	geometryToLayer: function (geojson, options) {
		var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
		    coords = geometry.coordinates,
		    layers = [],
		    coordsToLatLng = options.coordsToLatLng || this.coordsToLatLng,
		    latlng, latlngs, i, len;

		switch (geometry.type) {
		case 'Point':
			latlng = coordsToLatLng(coords);

			return options.pointToLayer ?
					options.pointToLayer(geojson, latlng) :
					new L.Marker(latlng);

		case 'MultiPoint':
			for (i = 0, len = coords.length; i < len; i++) {
				latlng = coordsToLatLng(coords[i]);

				layers.push(options.pointToLayer ?
						options.pointToLayer(geojson, latlng) :
						new L.Marker(latlng));
			}
			return new L.FeatureGroup(layers);

		case 'LineString':
		case 'MultiLineString':
			latlngs = this.coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, coordsToLatLng);
			return new L.Polyline(latlngs, options);

		case 'Polygon':
		case 'MultiPolygon':
			latlngs = this.coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, coordsToLatLng);
			return new L.Polygon(latlngs, options);

		case 'GeometryCollection':
			for (i = 0, len = geometry.geometries.length; i < len; i++) {

				layers.push(this.geometryToLayer({
					geometry: geometry.geometries[i],
					type: 'Feature',
					properties: geojson.properties
				}, options));
			}
			return new L.FeatureGroup(layers);

		default:
			throw new Error('Invalid GeoJSON object.');
		}
	},

	coordsToLatLng: function (coords) {
		return new L.LatLng(coords[1], coords[0], coords[2]);
	},

	coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) {
		var latlngs = [];

		for (var i = 0, len = coords.length, latlng; i < len; i++) {
			latlng = levelsDeep ?
			        this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
			        coordsToLatLng(coords[i]);

			latlngs.push(latlng);
		}

		return latlngs;
	},

	latLngToCoords: function (latlng) {
		return latlng.alt !== undefined ?
				[latlng.lng, latlng.lat, latlng.alt] :
				[latlng.lng, latlng.lat];
	},

	latLngsToCoords: function (latlngs, levelsDeep, closed) {
		var coords = [];

		for (var i = 0, len = latlngs.length; i < len; i++) {
			coords.push(levelsDeep ?
				L.GeoJSON.latLngsToCoords(latlngs[i], levelsDeep - 1, closed):
				L.GeoJSON.latLngToCoords(latlngs[i]));
		}

		if (!levelsDeep && closed) {
			coords.push(coords[0]);
		}

		return coords;
	},

	getFeature: function (layer, newGeometry) {
		return layer.feature ?
				L.extend({}, layer.feature, {geometry: newGeometry}) :
				L.GeoJSON.asFeature(newGeometry);
	},

	asFeature: function (geoJSON) {
		if (geoJSON.type === 'Feature') {
			return geoJSON;
		}

		return {
			type: 'Feature',
			properties: {},
			geometry: geoJSON
		};
	}
});

var PointToGeoJSON = {
	toGeoJSON: function () {
		return L.GeoJSON.getFeature(this, {
			type: 'Point',
			coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
		});
	}
};

L.Marker.include(PointToGeoJSON);
L.Circle.include(PointToGeoJSON);
L.CircleMarker.include(PointToGeoJSON);

L.Polyline.prototype.toGeoJSON = function () {
	var multi = !this._flat(this._latlngs);

	var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 1 : 0);

	return L.GeoJSON.getFeature(this, {
		type: (multi ? 'Multi' : '') + 'LineString',
		coordinates: coords
	});
};

L.Polygon.prototype.toGeoJSON = function () {
	var holes = !this._flat(this._latlngs),
	    multi = holes && !this._flat(this._latlngs[0]);

	var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true);

	if (holes && this._latlngs.length === 1) {
		multi = true;
		coords = [coords];
	}
	if (!holes) {
		coords = [coords];
	}

	return L.GeoJSON.getFeature(this, {
		type: (multi ? 'Multi' : '') + 'Polygon',
		coordinates: coords
	});
};

L.LayerGroup.include({
	toMultiPoint: function () {
		var coords = [];

		this.eachLayer(function (layer) {
			coords.push(layer.toGeoJSON().geometry.coordinates);
		});

		return L.GeoJSON.getFeature(this, {
			type: 'MultiPoint',
			coordinates: coords
		});
	},

	toGeoJSON: function () {

		var type = this.feature && this.feature.geometry && this.feature.geometry.type;

		if (type === 'MultiPoint') {
			return this.toMultiPoint();
		}

		var isGeometryCollection = type === 'GeometryCollection',
			jsons = [];

		this.eachLayer(function (layer) {
			if (layer.toGeoJSON) {
				var json = layer.toGeoJSON();
				jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
			}
		});

		if (isGeometryCollection) {
			return L.GeoJSON.getFeature(this, {
				geometries: jsons,
				type: 'GeometryCollection'
			});
		}

		return {
			type: 'FeatureCollection',
			features: jsons
		};
	}
});

L.geoJson = function (geojson, options) {
	return new L.GeoJSON(geojson, options);
};
<commit_msg>fix GeoJSON coordsToLatLng<commit_after>/*
 * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
 */

L.GeoJSON = L.FeatureGroup.extend({

	initialize: function (geojson, options) {
		L.setOptions(this, options);

		this._layers = {};

		if (geojson) {
			this.addData(geojson);
		}
	},

	addData: function (geojson) {
		var features = L.Util.isArray(geojson) ? geojson : geojson.features,
		    i, len, feature;

		if (features) {
			for (i = 0, len = features.length; i < len; i++) {
				// Only add this if geometry or geometries are set and not null
				feature = features[i];
				if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
					this.addData(feature);
				}
			}
			return this;
		}

		var options = this.options;

		if (options.filter && !options.filter(geojson)) { return; }

		var layer = L.GeoJSON.geometryToLayer(geojson, options);
		layer.feature = L.GeoJSON.asFeature(geojson);

		layer.defaultOptions = layer.options;
		this.resetStyle(layer);

		if (options.onEachFeature) {
			options.onEachFeature(geojson, layer);
		}

		return this.addLayer(layer);
	},

	resetStyle: function (layer) {
		// reset any custom styles
		layer.options = layer.defaultOptions;
		this._setLayerStyle(layer, this.options.style);
	},

	setStyle: function (style) {
		this.eachLayer(function (layer) {
			this._setLayerStyle(layer, style);
		}, this);
	},

	_setLayerStyle: function (layer, style) {
		if (typeof style === 'function') {
			style = style(layer.feature);
		}
		if (layer.setStyle) {
			layer.setStyle(style);
		}
	}
});

L.extend(L.GeoJSON, {
	geometryToLayer: function (geojson, options) {
		var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
		    coords = geometry.coordinates,
		    layers = [],
		    coordsToLatLng = options.coordsToLatLng || this.coordsToLatLng,
		    latlng, latlngs, i, len;

		switch (geometry.type) {
		case 'Point':
			latlng = coordsToLatLng(coords);

			return options.pointToLayer ?
					options.pointToLayer(geojson, latlng) :
					new L.Marker(latlng);

		case 'MultiPoint':
			for (i = 0, len = coords.length; i < len; i++) {
				latlng = coordsToLatLng(coords[i]);

				layers.push(options.pointToLayer ?
						options.pointToLayer(geojson, latlng) :
						new L.Marker(latlng));
			}
			return new L.FeatureGroup(layers);

		case 'LineString':
		case 'MultiLineString':
			latlngs = this.coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, coordsToLatLng);
			return new L.Polyline(latlngs, options);

		case 'Polygon':
		case 'MultiPolygon':
			latlngs = this.coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, coordsToLatLng);
			return new L.Polygon(latlngs, options);

		case 'GeometryCollection':
			for (i = 0, len = geometry.geometries.length; i < len; i++) {

				layers.push(this.geometryToLayer({
					geometry: geometry.geometries[i],
					type: 'Feature',
					properties: geojson.properties
				}, options));
			}
			return new L.FeatureGroup(layers);

		default:
			throw new Error('Invalid GeoJSON object.');
		}
	},

	coordsToLatLng: function (coords) {
		return new L.LatLng(coords[1], coords[0], coords[2]);
	},

	coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) {
		var latlngs = [];

		for (var i = 0, len = coords.length, latlng; i < len; i++) {
			latlng = levelsDeep ?
			        this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
			        (coordsToLatLng || this.coordsToLatLng)(coords[i]);

			latlngs.push(latlng);
		}

		return latlngs;
	},

	latLngToCoords: function (latlng) {
		return latlng.alt !== undefined ?
				[latlng.lng, latlng.lat, latlng.alt] :
				[latlng.lng, latlng.lat];
	},

	latLngsToCoords: function (latlngs, levelsDeep, closed) {
		var coords = [];

		for (var i = 0, len = latlngs.length; i < len; i++) {
			coords.push(levelsDeep ?
				L.GeoJSON.latLngsToCoords(latlngs[i], levelsDeep - 1, closed):
				L.GeoJSON.latLngToCoords(latlngs[i]));
		}

		if (!levelsDeep && closed) {
			coords.push(coords[0]);
		}

		return coords;
	},

	getFeature: function (layer, newGeometry) {
		return layer.feature ?
				L.extend({}, layer.feature, {geometry: newGeometry}) :
				L.GeoJSON.asFeature(newGeometry);
	},

	asFeature: function (geoJSON) {
		if (geoJSON.type === 'Feature') {
			return geoJSON;
		}

		return {
			type: 'Feature',
			properties: {},
			geometry: geoJSON
		};
	}
});

var PointToGeoJSON = {
	toGeoJSON: function () {
		return L.GeoJSON.getFeature(this, {
			type: 'Point',
			coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
		});
	}
};

L.Marker.include(PointToGeoJSON);
L.Circle.include(PointToGeoJSON);
L.CircleMarker.include(PointToGeoJSON);

L.Polyline.prototype.toGeoJSON = function () {
	var multi = !this._flat(this._latlngs);

	var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 1 : 0);

	return L.GeoJSON.getFeature(this, {
		type: (multi ? 'Multi' : '') + 'LineString',
		coordinates: coords
	});
};

L.Polygon.prototype.toGeoJSON = function () {
	var holes = !this._flat(this._latlngs),
	    multi = holes && !this._flat(this._latlngs[0]);

	var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true);

	if (holes && this._latlngs.length === 1) {
		multi = true;
		coords = [coords];
	}
	if (!holes) {
		coords = [coords];
	}

	return L.GeoJSON.getFeature(this, {
		type: (multi ? 'Multi' : '') + 'Polygon',
		coordinates: coords
	});
};

L.LayerGroup.include({
	toMultiPoint: function () {
		var coords = [];

		this.eachLayer(function (layer) {
			coords.push(layer.toGeoJSON().geometry.coordinates);
		});

		return L.GeoJSON.getFeature(this, {
			type: 'MultiPoint',
			coordinates: coords
		});
	},

	toGeoJSON: function () {

		var type = this.feature && this.feature.geometry && this.feature.geometry.type;

		if (type === 'MultiPoint') {
			return this.toMultiPoint();
		}

		var isGeometryCollection = type === 'GeometryCollection',
			jsons = [];

		this.eachLayer(function (layer) {
			if (layer.toGeoJSON) {
				var json = layer.toGeoJSON();
				jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
			}
		});

		if (isGeometryCollection) {
			return L.GeoJSON.getFeature(this, {
				geometries: jsons,
				type: 'GeometryCollection'
			});
		}

		return {
			type: 'FeatureCollection',
			features: jsons
		};
	}
});

L.geoJson = function (geojson, options) {
	return new L.GeoJSON(geojson, options);
};
<|endoftext|>


<commit_before>import { Factory, faker } from 'ember-cli-mirage';

const {name, random, address} = faker;

export default Factory.extend({

  index(i) {
    return i + 1;
  },

  'first-name'(i) {
    return `${name.firstName()}_${i}`;
  },

  'last-name'(i) {
    return `${name.lastName()}_${i}`;
  },

  age(i) {
    return 18 + `${random.number(42)}_${i}`;
  },

  city(i) {
    return `${address.city()}_${i}`;
  }

});
<commit_msg>`age` and `city` may be not unique<commit_after>import { Factory, faker } from 'ember-cli-mirage';

const {name, random, address} = faker;

export default Factory.extend({

  index(i) {
    return i + 1;
  },

  'first-name'(i) {
    return `${name.firstName()}_${i}`;
  },

  'last-name'(i) {
    return `${name.lastName()}_${i}`;
  },

  age() {
    return 18 + random.number(42);
  },

  city(i) {
    return address.city();
  }

});
<|endoftext|>


<commit_before>/* @flow */

import { CompositeDisposable, Disposable } from 'atom'

import Linter from './main'
import type { UI, Linter as LinterProvider } from './types'

// Internal variables
let instance
let subscriptions: CompositeDisposable

export function activate() {
  subscriptions = new CompositeDisposable()

  instance = new Linter()
  subscriptions.add(instance)

  subscriptions.add(
    atom.packages.onDidActivateInitialPackages(function() {
      if (!atom.inSpecMode()) {
        require('atom-package-deps').install('linter', true)
      }
    }),
  )
}
export function consumeLinter(linter: LinterProvider): Disposable {
  const linters = [].concat(linter)
  for (const entry of linters) {
    instance.addLinter(entry)
  }
  return new Disposable(() => {
    for (const entry of linters) {
      instance.deleteLinter(entry)
    }
  })
}
export function consumeUI(ui: UI): Disposable {
  const uis = [].concat(ui)
  for (const entry of uis) {
    instance.addUI(entry)
  }
  return new Disposable(() => {
    for (const entry of uis) {
      instance.deleteUI(entry)
    }
  })
}
export function provideIndie(): Object {
  return indie => instance.addIndie(indie)
}
export function deactivate() {
  subscriptions.dispose()
}
<commit_msg>instance type annotation<commit_after>/* @flow */

import { CompositeDisposable, Disposable } from 'atom'

import Linter from './main'
import type { UI, Linter as LinterProvider } from './types'

// Internal variables
let instance: Linter
let subscriptions: CompositeDisposable

export function activate() {
  subscriptions = new CompositeDisposable()

  instance = new Linter()
  subscriptions.add(instance)

  subscriptions.add(
    atom.packages.onDidActivateInitialPackages(function() {
      if (!atom.inSpecMode()) {
        require('atom-package-deps').install('linter', true)
      }
    }),
  )
}
export function consumeLinter(linter: LinterProvider): Disposable {
  const linters = [].concat(linter)
  for (const entry of linters) {
    instance.addLinter(entry)
  }
  return new Disposable(() => {
    for (const entry of linters) {
      instance.deleteLinter(entry)
    }
  })
}
export function consumeUI(ui: UI): Disposable {
  const uis = [].concat(ui)
  for (const entry of uis) {
    instance.addUI(entry)
  }
  return new Disposable(() => {
    for (const entry of uis) {
      instance.deleteUI(entry)
    }
  })
}
export function provideIndie(): Object {
  return indie => instance.addIndie(indie)
}
export function deactivate() {
  subscriptions.dispose()
}
<|endoftext|>


<commit_before>/*
Score is a Seq(ish) object, with pause, start / stop, rewind, fast-forward.
It's internal phase is

Score has start() method to start it running. next() advances to next element,
regardless of whether or not the score is running, and stats the transport running.
rewind() moves the score index to the first position.
*/

/*
Passed Timing           Result
=============           ======
Numeric literal         place function in timeline and store reference
a Function              callback. register to receive and advance. must use pub/sub.
Score.wait             pause until next() method is called
*/

module.exports = function( Gibber ) {

let Score = {
  wait: -987654321,

  create( data ) {
    let score = Object.create( this )

    Object.assign( score, {
      timeline:   [],
      schedule:   [],
      shouldLoop: false,
      rate:       1,
      loopPause:  0,
      phase:      0,
      index:      0,
      isPaused:   true,
    })

    for( let i = 0; i < data.length; i+=2 ) {
      score.schedule.push( data[ i ] )
      score.timeline.push( data[ i+1 ] )
    }

    let loopPauseFnc = () => {
          score.nextTime = score.phase = 0
          score.index = -1
          score.timeline.pop()
        }

    score.oncomplete.listeners = []
    score.oncomplete.owner = this

    score.nextTime = score.schedule[ 0 ]

    score.start()

    return score
  },

  start() {
    if( !this.isPaused ) return
    this.isPaused = false

    Gibber.Scheduler.addMessage( this, 0 )

    return this
  },

  stop() {
    this.isPaused = true
    return this
  },

  loop( loopPause = 0 ) {
    this.loopPause = loopPause
    this.shouldLoop = !this.shouldLoop

    return this
  },

  pause() {
    this.isPaused = true

    return this
  },

  next() {
    this.isPaused = false

    return this
  },

  combine( ...args ) {
    let score = [ 0, args[ 0 ] ]

    for( let i = 1; i < args.length; i++ ) {
      let timeIndex = i * 2,
          valueIndex = timeIndex +  1,
          previousValueIndex = timeIndex - 1

      score[ timeIndex  ] = score[ previousValueIndex ].oncomplete
      score[ valueIndex ] = args[ i ]
    }

    return Score.create( score )
  },

  tick( scheduler, beat, beatOffset ) {
    if( !this.isPaused ) {
      if( this.phase >= this.nextTime && this.index < this.timeline.length ) {

        let fnc = this.timeline[ this.index ],
            shouldExecute = true

        this.index++

        if( this.index <= this.timeline.length - 1 ) {
          let time = this.schedule[ this.index ]

          if( typeof time === 'number' && time !== Score.wait ) {
            this.nextTime =  time
          } else {
            if( time === Score.wait ) {
              this.isPaused = true
            }else if( time.owner instanceof Score ) {
              this.isPaused = true
              time.owner.oncomplete.listeners.push( self )
              // shouldExecute = false // doesn't do what I think it should do...
            }
          }
        }else{
          if( this.shouldLoop ) {
            if( this.timeline[ this.timeline.length - 1 ] !== loopPauseFnc ) {
              this.timeline.push( loopPauseFnc )
            }
            this.nextTime = this.loopPause
          }else{
            this.isPaused = true
          }
          this.oncomplete()
        }

        if( shouldExecute && fnc ) {
          if( Score.isPrototypeOf( fnc )  ) {
            if( !fnc.codeblock ) { // TODO: what do I replace codeblock with? isRunning?
              fnc.start()
            }else{
              // TODO: what is this for?
              fnc.rewind().next()
              //fnc.rewind().next()
              //fnc()
            }
          }else{
            fnc.call( Gibber.currentTrack )
          }

          let marker      = Gibber.currentTrack.markup.textMarkers[ 'score' ][ this.index - 1 ],
              pos         = marker.find(),
              funcBody    = fnc.toString(),
              isMultiLine = funcBody.includes('\n'),
              code, line

          pos.start = Object.assign( {}, pos.from )
          pos.end   = Object.assign( {}, pos.to   )

          if( isMultiLine ) {
            code  = fnc.toString().split('\n').slice(1,-1).join('\n')
            pos.start.line += 1
            pos.end.line += 1
          } else {
            if( funcBody.endsWith( '}' ) ) {
              line  = marker.lines[ 0 ].text

              let bracketIdx = line.indexOf( '{' ) + 1,
                  commaIdx   = line.indexOf( ',' ),
                  commaAmount = line.endsWith( ',' ) ? 1 : 0

              code = line.substr( bracketIdx, line.length - bracketIdx - 1 - commaAmount )

              pos.horizontalOffset = bracketIdx//pos.start.ch

            }else{
              // TODO: why doesn't this work? acorn seems unable to parse arrow functions?
              line = marker.lines[ 0 ].text

              let arrowIdx = line.indexOf( '>' ) + 1,
                  commaAmount = line.endsWith( ',' ) ? 1 : 0

              code = line.substr( arrowIdx, line.length - arrowIdx - commaAmount )

              pos.horizontalOffset = arrowIdx

            }
          }
          //funcBody = fnc.toString(),
          //code = funcBody.match(/(?:function\s*\(\)*[\s]*[\{\n])([\s\S]*)\}/)[1]
          //code = funcBody.match(/(?:(?:\(\))*(?:_)*(?:=>)\s*(?:\{)*)([\"\'\.\{\}\(\)\w\d\s\n]+)(?:\})/i)[1]

          // TODO: should not be Gibber.currentTrack ?
          Gibber.Environment.codeMarkup.process( code, pos, Gibber.Environment.codemirror, Gibber.currentTrack )

          if( typeof this.onadvance === 'function' ) this.onadvance( this.index - 1 )
        }
      }

      Gibber.Scheduler.addMessage( this, this.nextTime )
      this.phase += this.rate //rate TODO: what if a beat isn't a quarter note?
    }
    return 0
  },

  rewind : function() {
    this.phase = this.index = 0
    this.nextTime = this.schedule[ 0 ]
    return this
  },

  oncomplete: function() {
    // console.log("ON COMPLETE", this.oncomplete.listeners )
    let listeners = this.oncomplete.listeners
    for( let i = listeners.length - 1; i >= 0; i-- ) {
      let listener = listeners[i]
      if( listener instanceof Score ) {
        listener.next()
      }
    }
  }

}

return Score.create.bind( Score )

}

/*
a = Score([
  0, function() { console.log('1') },
  1/4, function() { console.log('2') },
  1/4, function() { console.log('3') },
  1/4, function() { console.log('4') },
  1, function() { console.log('5555') },
]).start()
*/

/*
 *var Score = function( data, opts ) {
 *
 *
 *
 *
 *  var _rate = this.rate,
 *      oldRate  = this.__lookupSetter__( 'rate' )
 *
 *  Object.defineProperty( this, 'rate', {
 *    get : function() { return _rate },
 *    set : function(v) {
 *      _rate = Mul( Gibber.Clock, v )
 *      oldRate.call( this, _rate )
 *    }
 *  })
 *
 *  this.rate = this.rate // trigger meta-programming tie to master clock
 *
 *  Gibber.createProxyProperties( this, {
 *    rate : { min: .1, max: 2, output: 0, timescale: 'audio' },
 *  })
 *}
 *
 *Score.prototype = proto
 *
 *
 *return Score
 *
 *}
 */

/*
a = Score([
  0, console.log.bind( null, 'test1'),
  seconds(.5),console.log.bind( null, 'test2'),
  Score.wait, null,
  seconds(.5),console.log.bind( null, 'test3'),
  seconds(.5),console.log.bind( null, 'test4'),
  seconds(.5),function() { a.rewind(); a.next() }
])

b = Score([
  100, console.log.bind(null,"B"),
  100, console.log.bind(null,"F"),
  a.oncomplete, function() {
  	console.log("C")
  }
])
.start()

a.start()

-----
a = Score([
  0, console.log.bind( null, 'test1'),
  seconds(.5),console.log.bind( null, 'test2'),

  Score.wait, null,

  seconds(.5),console.log.bind( null, 'test3'),

  seconds(.5), Score([
    0, console.log.bind(null,"A"),
    beats(2), console.log.bind(null,"B")
  ]),

  Score.wait, null,

  seconds(.5),function() { a.rewind(); a.next() }
]).start()

-----
synth = Synth('bleep')
synth2 = Synth('bleep', {maxVoices:4})

// you need to uncomment the line below after the kick drum comes in
// and execute it

score.next()

score = Score([
  0, synth.note.score( 'c4', 1/4 ),

  measures(1), synth.note.score( ['c4','c5'], 1/8 ),

  measures(1), synth.note.score( ['c2','c3','c4','c5'], 1/16 ),

  measures(1), function() {
    kick = Kick().note.seq( 55,1/4 )
  },

  Score.wait, null,

  0, synth2.note.score('bb4',1/4 ),

  measures(1), synth2.chord.score( [['bb4','g4']], 1/4 ),

  measures(2), synth2.chord.score( [['c5','f4']], 1/4 ),

  measures(2), function() {
    synth2.chord.seq( [['eb4','bb4','d5']], 1/6 )
    synth2.note.seq.stop()
    synth2.fx.add( Delay(1/9,.35) )

    synth2.fadeOut(32)
  },

  measures(4), function() {
    ks = Pluck()
    	.note.seq( Rndi(100,600), 1/16 )
    	.blend.seq( Rndf() )
    	.fx.add( Schizo('paranoid') )

    Clock.rate = Line( 1, 1.1, 8 )
  },

  measures(8), function() {
		Master.fadeOut( 8 )
  },

  measures(8), Gibber.clear

]).start()

------

synth = Synth('bleep')

verse =  Score([ beats(1/2), synth.note.bind( synth, 'c4' ) ])
chorus = Score([ beats(1/2), synth.note.bind( synth, 'd4' ) ])
bridge = Score([ beats(1/2), synth.note.bind( synth, 'e4' ) ])

song = Score([
  0,                 verse,
  verse.oncomplete,  chorus,
  chorus.oncomplete, verse,
  verse.oncomplete,  chorus,
  chorus.oncomplete, bridge,
  bridge.oncomplete, chorus
])

song.start()

*/

<commit_msg>mute and solo working for tracks<commit_after>/*
Score is a Seq(ish) object, with pause, start / stop, rewind, fast-forward.
It's internal phase is

Score has start() method to start it running. next() advances to next element,
regardless of whether or not the score is running, and stats the transport running.
rewind() moves the score index to the first position.
*/

/*
Passed Timing           Result
=============           ======
Numeric literal         place function in timeline and store reference
a Function              callback. register to receive and advance. must use pub/sub.
Score.wait             pause until next() method is called
*/

module.exports = function( Gibber ) {

let Score = {
  wait: -987654321,

  create( data, track = Gibber.currentTrack ) {
    let score = Object.create( this )

    Object.assign( score, {
      track: track,
      timeline:   [],
      schedule:   [],
      shouldLoop: false,
      rate:       1,
      loopPause:  0,
      phase:      0,
      index:      0,
      isPaused:   true,
    })

    for( let i = 0; i < data.length; i+=2 ) {
      score.schedule.push( data[ i ] )
      score.timeline.push( data[ i+1 ] )
    }

    let loopPauseFnc = () => {
          score.nextTime = score.phase = 0
          score.index = -1
          score.timeline.pop()
        }

    score.oncomplete.listeners = []
    score.oncomplete.owner = this

    score.nextTime = score.schedule[ 0 ]

    score.start()

    return score
  },

  start() {
    if( !this.isPaused ) return
    this.isPaused = false

    Gibber.Scheduler.addMessage( this, 0 )

    return this
  },

  stop() {
    this.isPaused = true
    return this
  },

  loop( loopPause = 0 ) {
    this.loopPause = loopPause
    this.shouldLoop = !this.shouldLoop

    return this
  },

  pause() {
    this.isPaused = true

    return this
  },

  next() {
    this.isPaused = false

    return this
  },

  combine( ...args ) {
    let score = [ 0, args[ 0 ] ]

    for( let i = 1; i < args.length; i++ ) {
      let timeIndex = i * 2,
          valueIndex = timeIndex +  1,
          previousValueIndex = timeIndex - 1

      score[ timeIndex  ] = score[ previousValueIndex ].oncomplete
      score[ valueIndex ] = args[ i ]
    }

    return Score.create( score )
  },

  tick( scheduler, beat, beatOffset ) {
    if( !this.isPaused ) {
      if( this.phase >= this.nextTime && this.index < this.timeline.length ) {

        let fnc = this.timeline[ this.index ],
            shouldExecute = true

        this.index++

        if( this.index <= this.timeline.length - 1 ) {
          let time = this.schedule[ this.index ]

          if( typeof time === 'number' && time !== Score.wait ) {
            this.nextTime =  time
          } else {
            if( time === Score.wait ) {
              this.isPaused = true
            }else if( time.owner instanceof Score ) {
              this.isPaused = true
              time.owner.oncomplete.listeners.push( self )
              // shouldExecute = false // doesn't do what I think it should do...
            }
          }
        }else{
          if( this.shouldLoop ) {
            if( this.timeline[ this.timeline.length - 1 ] !== loopPauseFnc ) {
              this.timeline.push( loopPauseFnc )
            }
            this.nextTime = this.loopPause
          }else{
            this.isPaused = true
          }
          this.oncomplete()
        }

        if( shouldExecute && fnc ) {
          if( Score.isPrototypeOf( fnc )  ) {
            if( !fnc.codeblock ) { // TODO: what do I replace codeblock with? isRunning?
              fnc.start()
            }else{
              // TODO: what is this for?
              fnc.rewind().next()
              //fnc.rewind().next()
              //fnc()
            }
          }else{
            fnc.call( Gibber.currentTrack )
          }

          let marker      = Gibber.currentTrack.markup.textMarkers[ 'score' ][ this.index - 1 ],
              pos         = marker.find(),
              funcBody    = fnc.toString(),
              isMultiLine = funcBody.includes('\n'),
              code, line

          pos.start = Object.assign( {}, pos.from )
          pos.end   = Object.assign( {}, pos.to   )

          if( isMultiLine ) {
            code  = fnc.toString().split('\n').slice(1,-1).join('\n')
            pos.start.line += 1
            pos.end.line += 1
          } else {
            if( funcBody.endsWith( '}' ) ) {
              line  = marker.lines[ 0 ].text

              let bracketIdx = line.indexOf( '{' ) + 1,
                  commaIdx   = line.indexOf( ',' ),
                  commaAmount = line.endsWith( ',' ) ? 1 : 0

              code = line.substr( bracketIdx, line.length - bracketIdx - 1 - commaAmount )

              pos.horizontalOffset = bracketIdx//pos.start.ch

            }else{
              // TODO: why doesn't this work? acorn seems unable to parse arrow functions?
              line = marker.lines[ 0 ].text

              let arrowIdx = line.indexOf( '>' ) + 1,
                  commaAmount = line.endsWith( ',' ) ? 1 : 0

              code = line.substr( arrowIdx, line.length - arrowIdx - commaAmount )

              pos.horizontalOffset = arrowIdx

            }
          }
          //funcBody = fnc.toString(),
          //code = funcBody.match(/(?:function\s*\(\)*[\s]*[\{\n])([\s\S]*)\}/)[1]
          //code = funcBody.match(/(?:(?:\(\))*(?:_)*(?:=>)\s*(?:\{)*)([\"\'\.\{\}\(\)\w\d\s\n]+)(?:\})/i)[1]

          // TODO: should not be Gibber.currentTrack ?
          Gibber.Environment.codeMarkup.process( code, pos, Gibber.Environment.codemirror, Gibber.currentTrack )

          if( typeof this.onadvance === 'function' ) this.onadvance( this.index - 1 )
        }
      }

      Gibber.Scheduler.addMessage( this, this.nextTime )
      this.phase += this.rate //rate TODO: what if a beat isn't a quarter note?
    }
    return 0
  },

  rewind : function() {
    this.phase = this.index = 0
    this.nextTime = this.schedule[ 0 ]
    return this
  },

  oncomplete: function() {
    // console.log("ON COMPLETE", this.oncomplete.listeners )
    let listeners = this.oncomplete.listeners
    for( let i = listeners.length - 1; i >= 0; i-- ) {
      let listener = listeners[i]
      if( listener instanceof Score ) {
        listener.next()
      }
    }
  }

}

return Score.create.bind( Score )

}

/*
a = Score([
  0, function() { console.log('1') },
  1/4, function() { console.log('2') },
  1/4, function() { console.log('3') },
  1/4, function() { console.log('4') },
  1, function() { console.log('5555') },
]).start()
*/

/*
 *var Score = function( data, opts ) {
 *
 *
 *
 *
 *  var _rate = this.rate,
 *      oldRate  = this.__lookupSetter__( 'rate' )
 *
 *  Object.defineProperty( this, 'rate', {
 *    get : function() { return _rate },
 *    set : function(v) {
 *      _rate = Mul( Gibber.Clock, v )
 *      oldRate.call( this, _rate )
 *    }
 *  })
 *
 *  this.rate = this.rate // trigger meta-programming tie to master clock
 *
 *  Gibber.createProxyProperties( this, {
 *    rate : { min: .1, max: 2, output: 0, timescale: 'audio' },
 *  })
 *}
 *
 *Score.prototype = proto
 *
 *
 *return Score
 *
 *}
 */

/*
a = Score([
  0, console.log.bind( null, 'test1'),
  seconds(.5),console.log.bind( null, 'test2'),
  Score.wait, null,
  seconds(.5),console.log.bind( null, 'test3'),
  seconds(.5),console.log.bind( null, 'test4'),
  seconds(.5),function() { a.rewind(); a.next() }
])

b = Score([
  100, console.log.bind(null,"B"),
  100, console.log.bind(null,"F"),
  a.oncomplete, function() {
  	console.log("C")
  }
])
.start()

a.start()

-----
a = Score([
  0, console.log.bind( null, 'test1'),
  seconds(.5),console.log.bind( null, 'test2'),

  Score.wait, null,

  seconds(.5),console.log.bind( null, 'test3'),

  seconds(.5), Score([
    0, console.log.bind(null,"A"),
    beats(2), console.log.bind(null,"B")
  ]),

  Score.wait, null,

  seconds(.5),function() { a.rewind(); a.next() }
]).start()

-----
synth = Synth('bleep')
synth2 = Synth('bleep', {maxVoices:4})

// you need to uncomment the line below after the kick drum comes in
// and execute it

score.next()

score = Score([
  0, synth.note.score( 'c4', 1/4 ),

  measures(1), synth.note.score( ['c4','c5'], 1/8 ),

  measures(1), synth.note.score( ['c2','c3','c4','c5'], 1/16 ),

  measures(1), function() {
    kick = Kick().note.seq( 55,1/4 )
  },

  Score.wait, null,

  0, synth2.note.score('bb4',1/4 ),

  measures(1), synth2.chord.score( [['bb4','g4']], 1/4 ),

  measures(2), synth2.chord.score( [['c5','f4']], 1/4 ),

  measures(2), function() {
    synth2.chord.seq( [['eb4','bb4','d5']], 1/6 )
    synth2.note.seq.stop()
    synth2.fx.add( Delay(1/9,.35) )

    synth2.fadeOut(32)
  },

  measures(4), function() {
    ks = Pluck()
    	.note.seq( Rndi(100,600), 1/16 )
    	.blend.seq( Rndf() )
    	.fx.add( Schizo('paranoid') )

    Clock.rate = Line( 1, 1.1, 8 )
  },

  measures(8), function() {
		Master.fadeOut( 8 )
  },

  measures(8), Gibber.clear

]).start()

------

synth = Synth('bleep')

verse =  Score([ beats(1/2), synth.note.bind( synth, 'c4' ) ])
chorus = Score([ beats(1/2), synth.note.bind( synth, 'd4' ) ])
bridge = Score([ beats(1/2), synth.note.bind( synth, 'e4' ) ])

song = Score([
  0,                 verse,
  verse.oncomplete,  chorus,
  chorus.oncomplete, verse,
  verse.oncomplete,  chorus,
  chorus.oncomplete, bridge,
  bridge.oncomplete, chorus
])

song.start()

*/

<|endoftext|>


<commit_before>var os = require('os');
var del = require('del');
var path = require('path');
var exec = require('child_process').exec;
var gulp = require('gulp');
var gutil = require('gulp-util');
var shell = require('gulp-shell');
var gulpFile = require('gulp-file');
var webpack = require('webpack');
var webpackConfig = require('./webpack.config.js');
var runSequence = require('run-sequence');

const LIBRARY_NAME = 'ng2-scrollreveal';

//Helper functions
function platformPath(path) {
    return /^win/.test(os.platform()) ? `${path}.cmd` : path;
}

function webpackCallBack(taskName, gulpDone) {
    return function (err, stats) {
        if (err) throw new gutil.PluginError(taskName, err);
        gutil.log(`[${taskName}]`, stats.toString({
            colors: true
        }));
        gulpDone();
    }
}

// Transpiling & Building

gulp.task('clean:build', function () { return del('dist/'); });

gulp.task('ngc', function (cb) {
    var executable = path.join(__dirname, platformPath('/node_modules/.bin/ngc'));
    exec(`${executable} -p ./src/lib/tsconfig-es2015.json`, (e) => {
        if (e) console.log(e);
        del('./dist/waste');
        cb();
    }).stdout.on('data', function (data) { console.log(data); });
});

gulp.task('umd', function (callback) {
    // run webpack
    webpack(webpackConfig, webpackCallBack);
});

gulp.task('npm', function () {
    var pkgJson = require('./package.json');
    var targetPkgJson = {};
    var fieldsToCopy = ['version', 'description', 'keywords', 'author', 'repository', 'license', 'bugs', 'homepage'];

    targetPkgJson['name'] = LIBRARY_NAME;

    fieldsToCopy.forEach(function (field) { targetPkgJson[field] = pkgJson[field]; });

    targetPkgJson['main'] = `bundles/${LIBRARY_NAME}.min.js`;
    targetPkgJson['module'] = 'index.js';
    targetPkgJson['typings'] = 'index.d.ts';

    targetPkgJson.peerDependencies = {};
    Object.keys(pkgJson.dependencies).forEach(function (dependency) {
        targetPkgJson.peerDependencies[dependency] = `^${pkgJson.dependencies[dependency]}`;
    });

    return gulp.src('README.md')
        .pipe(gulpFile('package.json', JSON.stringify(targetPkgJson, null, 2)))
        .pipe(gulp.dest('dist'));
});

gulp.task('changelog', function () {
    var conventionalChangelog = require('gulp-conventional-changelog');
    return gulp.src('CHANGELOG.md', {})
        .pipe(conventionalChangelog({ preset: 'angular', releaseCount: 1 }, {
            // Override release version to avoid `v` prefix for git comparison
            // See https://github.com/conventional-changelog/conventional-changelog-core/issues/10
            currentTag: require('./package.json').version
        }))
        .pipe(gulp.dest('./'));
});

gulp.task('clean:demo', function () { return del('dist/demo'); });

gulp.task('serve:demo', shell.task('ng serve'));

gulp.task('build:demo', shell.task('ng build --prod'));

gulp.task('push:demo', shell.task('ng gh-pages:deploy'));

// Public Tasks
gulp.task('clean', ['clean:build', 'clean:demo']);

gulp.task('test', shell.task('ng test --watch false'));

gulp.task('lint', shell.task('ng lint'));

gulp.task('build', function (done) {
    runSequence('lint', /*'enforce-format', 'ddescribe-iit', */'test', 'clean:build', 'ngc', 'umd', 'npm', done);
});

gulp.task(
    'deploy-demo', function (done) { runSequence('clean:demo', 'build:demo', 'push:demo', done); });

gulp.task('default', function (done) { runSequence('lint', /*'enforce-format', 'ddescribe-iit', */'test', done); });<commit_msg>chore(build): fix 'gulpDone' callback not called for 'umd' task<commit_after>var os = require('os');
var del = require('del');
var path = require('path');
var exec = require('child_process').exec;
var gulp = require('gulp');
var gutil = require('gulp-util');
var shell = require('gulp-shell');
var gulpFile = require('gulp-file');
var webpack = require('webpack');
var webpackConfig = require('./webpack.config.js');
var runSequence = require('run-sequence');

const LIBRARY_NAME = 'ng2-scrollreveal';

//Helper functions
function platformPath(path) {
    return /^win/.test(os.platform()) ? `${path}.cmd` : path;
}

function webpackCallBack(taskName, gulpDone) {
    return function (err, stats) {
        if (err) throw new gutil.PluginError(taskName, err);
        gutil.log(`[${taskName}]`, stats.toString({
            colors: true
        }));
        gulpDone();
    }
}

// Transpiling & Building

gulp.task('clean:build', function () { return del('dist/'); });

gulp.task('ngc', function (cb) {
    var executable = path.join(__dirname, platformPath('/node_modules/.bin/ngc'));
    exec(`${executable} -p ./src/lib/tsconfig-es2015.json`, (e) => {
        if (e) console.log(e);
        del('./dist/waste');
        cb();
    }).stdout.on('data', function (data) { console.log(data); });
});

gulp.task('umd', function (cb) {
    // run webpack
    webpack(webpackConfig, webpackCallBack('webpack', cb));
});

gulp.task('npm', function () {
    var pkgJson = require('./package.json');
    var targetPkgJson = {};
    var fieldsToCopy = ['version', 'description', 'keywords', 'author', 'repository', 'license', 'bugs', 'homepage'];

    targetPkgJson['name'] = LIBRARY_NAME;

    fieldsToCopy.forEach(function (field) { targetPkgJson[field] = pkgJson[field]; });

    targetPkgJson['main'] = `bundles/${LIBRARY_NAME}.min.js`;
    targetPkgJson['module'] = 'index.js';
    targetPkgJson['typings'] = 'index.d.ts';

    targetPkgJson.peerDependencies = {};
    Object.keys(pkgJson.dependencies).forEach(function (dependency) {
        targetPkgJson.peerDependencies[dependency] = `^${pkgJson.dependencies[dependency]}`;
    });

    return gulp.src('README.md')
        .pipe(gulpFile('package.json', JSON.stringify(targetPkgJson, null, 2)))
        .pipe(gulp.dest('dist'));
});

gulp.task('changelog', function () {
    var conventionalChangelog = require('gulp-conventional-changelog');
    return gulp.src('CHANGELOG.md', {})
        .pipe(conventionalChangelog({ preset: 'angular', releaseCount: 1 }, {
            // Override release version to avoid `v` prefix for git comparison
            // See https://github.com/conventional-changelog/conventional-changelog-core/issues/10
            currentTag: require('./package.json').version
        }))
        .pipe(gulp.dest('./'));
});

gulp.task('clean:demo', function () { return del('dist/demo'); });

gulp.task('serve:demo', shell.task('ng serve'));

gulp.task('build:demo', shell.task('ng build --prod'));

gulp.task('push:demo', shell.task('ng gh-pages:deploy'));

// Public Tasks
gulp.task('clean', ['clean:build', 'clean:demo']);

gulp.task('test', shell.task('ng test --watch false'));

gulp.task('lint', shell.task('ng lint'));

gulp.task('build', function (done) {
    runSequence('lint', /*'enforce-format', 'ddescribe-iit', */'test', 'clean:build', 'ngc', 'umd', 'npm', done);
});

gulp.task(
    'deploy-demo', function (done) { runSequence('clean:demo', 'build:demo', 'push:demo', done); });

gulp.task('default', function (done) { runSequence('lint', /*'enforce-format', 'ddescribe-iit', */'test', done); });<|endoftext|>


<commit_before>'use strict';

var _Jenkins = require('jenkins');
var Job = require('./job');
var Build = require('./build');
var Node_ = require('./node');
var Queue = require('./queue');

// get info

function Jenkins(opts) {
  if (!(this instanceof Jenkins)) {
    return new Jenkins(opts);
  }

  this.jenkins = new _Jenkins(opts);

  this.job = new Job(this.jenkins);
  this.build = new Build(this.jenkins);
  this.node = new Node_(this.jenkins);
  this.queue = new Queue(this.jenkins);
}

Jenkins.prototype.info = function () {
  return new Promise(function(resolve, reject) {
    this.jenkins.info.call(this.jenkins, function(err, res) {
      if (err) reject(err);
      resolve(res);
    });
  });
};

Jenkins.prototype.get = Jenkins.prototype.info;

module.exports = Jenkins;
<commit_msg>fix jenkins.info<commit_after>'use strict';

var _Jenkins = require('jenkins');
var Job = require('./job');
var Build = require('./build');
var Node_ = require('./node');
var Queue = require('./queue');

// get info

function Jenkins(opts) {
  if (!(this instanceof Jenkins)) {
    return new Jenkins(opts);
  }

  this.jenkins = new _Jenkins(opts);

  this.job = new Job(this.jenkins);
  this.build = new Build(this.jenkins);
  this.node = new Node_(this.jenkins);
  this.queue = new Queue(this.jenkins);
}

Jenkins.prototype.info = function () {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.jenkins.info.call(self.jenkins, function(err, res) {
      if (err) reject(err);
      resolve(res);
    });
  });
};

Jenkins.prototype.get = Jenkins.prototype.info;

module.exports = Jenkins;
<|endoftext|>


<commit_before>L.GeoJSON = L.FeatureGroup.extend({
	initialize: function (geojson, options) {
		L.Util.setOptions(this, options);

		this._layers = {};

		if (geojson) {
			this.addData(geojson);
		}
	},

	addData: function (geojson) {
		var features = geojson instanceof Array ? geojson : geojson.features,
		    i, len;

		if (features) {
			for (i = 0, len = features.length; i < len; i++) {
				this.addData(features[i]);
			}
			return this;
		}

		var options = this.options,
		    style = options.style;

		if (options.filter && !options.filter(geojson)) { return; }

		var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer);

		if (style) {
			if (typeof style === 'function') {
				style = style(geojson);
			}
			if (layer.setStyle) {
				layer.setStyle(style);
			}
		}

		if (options.onEachFeature) {
			options.onEachFeature(geojson, layer);
		}

		return this.addLayer(layer);
	}
});

L.Util.extend(L.GeoJSON, {
	geometryToLayer: function (geojson, pointToLayer) {
		var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
		    coords = geometry.coordinates,
		    layers = [],
		    latlng, latlngs, i, len, layer;

		switch (geometry.type) {
		case 'Point':
			latlng = this.coordsToLatLng(coords);
			return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);

		case 'MultiPoint':
			for (i = 0, len = coords.length; i < len; i++) {
				latlng = this.coordsToLatLng(coords[i]);
				layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
				layers.push(layer);
			}
			return new L.FeatureGroup(layers);

		case 'LineString':
			latlngs = this.coordsToLatLngs(coords);
			return new L.Polyline(latlngs);

		case 'Polygon':
			latlngs = this.coordsToLatLngs(coords, 1);
			return new L.Polygon(latlngs);

		case 'MultiLineString':
			latlngs = this.coordsToLatLngs(coords, 1);
			return new L.MultiPolyline(latlngs);

		case "MultiPolygon":
			latlngs = this.coordsToLatLngs(coords, 2);
			return new L.MultiPolygon(latlngs);

		case "GeometryCollection":
			for (i = 0, len = geometry.geometries.length; i < len; i++) {
				layer = this.geometryToLayer(geometry.geometries[i], pointToLayer);
				layers.push(layer);
			}
			return new L.FeatureGroup(layers);

		default:
			throw new Error('Invalid GeoJSON object.');
		}
	},

	coordsToLatLng: function (coords, reverse) { // (Array, Boolean) -> LatLng
		var lat = parseFloat(coords[reverse ? 0 : 1]),
		    lng = parseFloat(coords[reverse ? 1 : 0]);

		return new L.LatLng(lat, lng, true);
	},

	coordsToLatLngs: function (coords, levelsDeep, reverse) { // (Array, Number, Boolean) -> Array
		var latlng,
		    latlngs = [],
		    i, len;

		for (i = 0, len = coords.length; i < len; i++) {
			latlng = levelsDeep ?
					this.coordsToLatLngs(coords[i], levelsDeep - 1, reverse) :
					this.coordsToLatLng(coords[i], reverse);

			latlngs.push(latlng);
		}

		return latlngs;
	}
});

L.geoJson = function (geojson, options) {
	return new L.GeoJSON(geojson, options);
};<commit_msg>Add geojson setStyle and resetStyle methods, layer feature property<commit_after>L.GeoJSON = L.FeatureGroup.extend({
	initialize: function (geojson, options) {
		L.Util.setOptions(this, options);

		this._layers = {};

		if (geojson) {
			this.addData(geojson);
		}
	},

	addData: function (geojson) {
		var features = geojson instanceof Array ? geojson : geojson.features,
		    i, len;

		if (features) {
			for (i = 0, len = features.length; i < len; i++) {
				this.addData(features[i]);
			}
			return this;
		}

		var options = this.options;

		if (options.filter && !options.filter(geojson)) { return; }

		var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer);
		layer.feature = geojson;

		this.resetStyle(layer);

		if (options.onEachFeature) {
			options.onEachFeature(geojson, layer);
		}

		return this.addLayer(layer);
	},

	resetStyle: function (layer) {
		var style = this.options.style;
		if (style) {
			this._setLayerStyle(layer, style);
		}
	},

	setStyle: function (style) {
		this.eachLayer(function (layer) {
			this._setLayerStyle(layer, style);
		}, this);
	},

	_setLayerStyle: function (layer, style) {
		if (typeof style === 'function') {
			style = style(layer.feature);
		}
		if (layer.setStyle) {
			layer.setStyle(style);
		}
	}
});

L.Util.extend(L.GeoJSON, {
	geometryToLayer: function (geojson, pointToLayer) {
		var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
		    coords = geometry.coordinates,
		    layers = [],
		    latlng, latlngs, i, len, layer;

		switch (geometry.type) {
		case 'Point':
			latlng = this.coordsToLatLng(coords);
			return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);

		case 'MultiPoint':
			for (i = 0, len = coords.length; i < len; i++) {
				latlng = this.coordsToLatLng(coords[i]);
				layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
				layers.push(layer);
			}
			return new L.FeatureGroup(layers);

		case 'LineString':
			latlngs = this.coordsToLatLngs(coords);
			return new L.Polyline(latlngs);

		case 'Polygon':
			latlngs = this.coordsToLatLngs(coords, 1);
			return new L.Polygon(latlngs);

		case 'MultiLineString':
			latlngs = this.coordsToLatLngs(coords, 1);
			return new L.MultiPolyline(latlngs);

		case "MultiPolygon":
			latlngs = this.coordsToLatLngs(coords, 2);
			return new L.MultiPolygon(latlngs);

		case "GeometryCollection":
			for (i = 0, len = geometry.geometries.length; i < len; i++) {
				layer = this.geometryToLayer(geometry.geometries[i], pointToLayer);
				layers.push(layer);
			}
			return new L.FeatureGroup(layers);

		default:
			throw new Error('Invalid GeoJSON object.');
		}
	},

	coordsToLatLng: function (coords, reverse) { // (Array, Boolean) -> LatLng
		var lat = parseFloat(coords[reverse ? 0 : 1]),
		    lng = parseFloat(coords[reverse ? 1 : 0]);

		return new L.LatLng(lat, lng, true);
	},

	coordsToLatLngs: function (coords, levelsDeep, reverse) { // (Array, Number, Boolean) -> Array
		var latlng,
		    latlngs = [],
		    i, len;

		for (i = 0, len = coords.length; i < len; i++) {
			latlng = levelsDeep ?
					this.coordsToLatLngs(coords[i], levelsDeep - 1, reverse) :
					this.coordsToLatLng(coords[i], reverse);

			latlngs.push(latlng);
		}

		return latlngs;
	}
});

L.geoJson = function (geojson, options) {
	return new L.GeoJSON(geojson, options);
};
<|endoftext|>


<commit_before>'use strict';

var timeout = setImmediate || setTimeout;

function isFunction(fn) {
  return typeof fn === 'function';
}

module.exports = {

  deferred: function deferred() {
    return {
      resolve: function resolve(data) {
        var args = Array.prototype.slice.call(arguments);
        if (this.promise.fulfilled) {
          this.promise.data = data;
          this.promise.fulfilled.forEach(function(fulfilled) {
            if (args.length > 0) {
              return fulfilled && timeout(fulfilled, data);
            }
          });
          this.promise.fulfilled = null;
        }
      },
      reject: function reject(error) {
        if (this.promise.fulfilled) {
          this.promise.fulfilled = null;
        }
        if (this.promise.rejected) {
          this.promise.err = error;
          this.promise.rejected.forEach(function(rejected) {
            return rejected && timeout(rejected, error);
          });
          //this.promise.rejected = null;
        }
      },
      promise: {
        fulfilled: [],
        rejected: [],
        /**
         * Resolves a promise
         * @param {function} onFulfilled
         * @param {function} onRejected
         *
         * @return {object} promise It is chainable
         **/
        then: function then(onFulfilled, onRejected) {
          if (this.fulfilled) {
            if (isFunction(onFulfilled)) {
              this.fulfilled.push(onFulfilled);
            }
          } else if (this.rejected && isFunction(onRejected)) {
            this.rejected.push(onRejected);
            if (this.err) {
              onRejected(this.err);
            }
          } else if (isFunction(onFulfilled)) {
            this.data = onFulfilled(this.data);
          }
          return this;
        },
        fail: function fail(onRejected) {
          if (this.rejected && isFunction(onRejected)) {
            this.rejected.push(onRejected);
          } else if (isFunction(onRejected)){
            return onRejected(this.err);
          }
        }
      }
    };
  }
};
<commit_msg>updating for browser use as well<commit_after>'use strict';

// If it's not node
if (window && !require) {

}

var timeout = setImmediate || setTimeout;

function isFunction(fn) {
  return typeof fn === 'function';
}

var PlainPrm = {

  deferred: function deferred() {
    return {
      resolve: function resolve(data) {
        var args = Array.prototype.slice.call(arguments);
        if (this.promise.fulfilled) {
          this.promise.data = data;
          this.promise.fulfilled.forEach(function(fulfilled) {
            if (args.length > 0) {
              return fulfilled && timeout(fulfilled, data);
            }
          });
          this.promise.fulfilled = null;
        }
      },
      reject: function reject(error) {
        if (this.promise.fulfilled) {
          this.promise.fulfilled = null;
        }
        if (this.promise.rejected) {
          this.promise.err = error;
          this.promise.rejected.forEach(function(rejected) {
            return rejected && timeout(rejected, error);
          });
          //this.promise.rejected = null;
        }
      },
      promise: {
        fulfilled: [],
        rejected: [],
        /**
         * Resolves a promise
         * @param {function} onFulfilled
         * @param {function} onRejected
         *
         * @return {object} promise It is chainable
         **/
        then: function then(onFulfilled, onRejected) {
          if (this.fulfilled) {
            if (isFunction(onFulfilled)) {
              this.fulfilled.push(onFulfilled);
            }
          } else if (this.rejected && isFunction(onRejected)) {
            this.rejected.push(onRejected);
            if (this.err) {
              onRejected(this.err);
            }
          } else if (isFunction(onFulfilled)) {
            this.data = onFulfilled(this.data);
          }
          return this;
        },
        fail: function fail(onRejected) {
          if (this.rejected && isFunction(onRejected)) {
            this.rejected.push(onRejected);
          } else if (isFunction(onRejected)){
            return onRejected(this.err);
          }
        }
      }
    };
  }
};

if (!window && module && require) {
  module.exports = PlainPrm;
} else {
  (function(win, lib) {
    return window[lib];
  })(window, PlainPrm);
}

<|endoftext|>


<commit_before>/**
 * Created by hejun on 15/4/15.
 *  纯前端配置-微信分享
 *  1.加载js后 请先执行init方法
 *  2.当前只能在socialpark.com.cn 域名下使用 其他域名使用无效(受公众账号设置限制)
 *  3.本组件依赖 http://res.wx.qq.com/open/js/jweixin-1.0.0.js 自动加载 自动依赖
 *  4.支持 cmd amd 引用
 *  5.全局对象 window.tp.wx
 *  6.返回对象中wechat为微信jssdk方法
 */
!(function () {

    var WX = {
        version: '2.0.3'
    };
    var shareData = {
        title: '',
        desc: '',
        link: '',
        imgUrl: '',
        success: function () {
        },
        cancel: function () {
        }
    };
    var isDebug = false;
    var isInit=false;
    var _currShareData=null;
    var initcallback = null;
    var wechatSdkUrl="http://res.wx.qq.com/open/js/jweixin-1.0.0.js";
    WX.wechat=null;
    WX.setWechat= function (wechat) {
        WX.wechat=wechat;
    };
    /**
     * 分享初始化
     * @param  {[type]} defaultshareData  默认分享文案
     * @param  {[type]} callback          初始化成功后回调函数
     * @param  {[type]} debug             调试是否打开 默认false
     */
    WX.init = function (defaultshareData, callback, debug) {
        defaultshareData = defaultshareData || {};
        shareData = extend(shareData, defaultshareData);
        debug = debug || isDebug;
        initcallback = typeof(callback) === "function" ? callback : null;
        isDebug = !!debug;
        var url = "http://www.socialpark.com.cn/wechat/getshare.php?t=" + new Date().getTime() + "&callback=tp.wx.config&url=" + encodeURIComponent(location.href.replace(location.hash, ""));

        if("function" == typeof define){
            require(["http://www.socialpark.com.cn/wechat/getshare.php?t=" + new Date().getTime() + "&callback=define&url=" + encodeURIComponent(location.href.replace(location.hash, ""))], function (data) {
                WX.config(data);
            });
        }
        else if(window.wx){
            WX.setWechat(window.wx);
            loadScript(url);
        }else{
            loadScript(wechatSdkUrl, function () {
                WX.setWechat(window.wx);
                loadScript(url);
            })
        }

    };
    WX.config = function (d) {
        if (d.ret != 200){
            if(isDebug)alert(JSON.stringify(d));
            return;
        }
        WX.wechat.config({
            debug: isDebug,
            appId: d.appid,
            timestamp: d.timestamp,
            nonceStr: d.noncestr,
            signature: d.signature,
            jsApiList: [
                'checkJsApi',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone',
                'hideMenuItems',
                'showMenuItems',
                'hideAllNonBaseMenuItem',
                'showAllNonBaseMenuItem',
                'translateVoice',
                'startRecord',
                'stopRecord',
                'onRecordEnd',
                'playVoice',
                'pauseVoice',
                'stopVoice',
                'uploadVoice',
                'downloadVoice',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'getNetworkType',
                'openLocation',
                'getLocation',
                'hideOptionMenu',
                'showOptionMenu',
                'closeWindow',
                'scanQRCode',
                'chooseWXPay',
                'openProductSpecificView',
                'addCard',
                'chooseCard',
                'openCard'
            ]
        });

        WX.wechat.ready(function () {
            WX.wechat.checkJsApi({
                jsApiList: [
                    'checkJsApi',
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone',
                    'hideMenuItems',
                    'showMenuItems',
                    'hideAllNonBaseMenuItem',
                    'showAllNonBaseMenuItem',
                    'translateVoice',
                    'startRecord',
                    'stopRecord',
                    'onRecordEnd',
                    'playVoice',
                    'pauseVoice',
                    'stopVoice',
                    'uploadVoice',
                    'downloadVoice',
                    'chooseImage',
                    'previewImage',
                    'uploadImage',
                    'downloadImage',
                    'getNetworkType',
                    'openLocation',
                    'getLocation',
                    'hideOptionMenu',
                    'showOptionMenu',
                    'closeWindow',
                    'scanQRCode',
                    'chooseWXPay',
                    'openProductSpecificView',
                    'addCard',
                    'chooseCard',
                    'openCard'
                ],
                success: function checkJsApisuccess(res) {
                    typeof (initcallback) === "function" && initcallback();
                    WX.wechat.hideMenuItems({
                        menuList: ['menuItem:share:weiboApp', 'menuItem:share:facebook']
                    });
                    WX.wechat.showMenuItems({
                        menuList: ['menuItem:profile', 'menuItem:addContact']
                    });
                    isInit=true;
                    WX.setshare(_currShareData);
                }
            });
        });
    };

    WX.setshare = function (d) {
        _currShareData=  d || {};

        if(!isInit){
            return;
        }
        var currShareData=extend(shareData, _currShareData);
        // 分享到微信朋友圈
        WX.wechat.onMenuShareTimeline({
            title: currShareData.title,
            link: currShareData.link,
            imgUrl: currShareData.imgUrl,
            success: function () {
                currShareData.success && currShareData.success();
                try {
                    _hmt.push(['_trackEvent', "分享成功", '分享到朋友圈']);
                } catch (e) {
                }
            },
            cancel: function () {
                currShareData.cancel && currShareData.cancel();
                try {
                    _hmt.push(['_trackEvent', "取消分享", '取消分享']);
                } catch (e) {
                }
            }
        });
        // 发送给指定微信好友
        WX.wechat.onMenuShareAppMessage({
            title: currShareData.title,
            desc: currShareData.desc,
            link: currShareData.link,
            imgUrl: currShareData.imgUrl,
            success: function () {
                currShareData.success && currShareData.success();
                try {
                    _hmt.push(['_trackEvent', "分享成功", '分享给好友']);
                } catch (e) {
                }
            },
            cancel: function () {
                currShareData.cancel && currShareData.cancel();
                try {
                    _hmt.push(['_trackEvent', "取消分享", '取消分享']);
                } catch (e) {
                }
            }
        });
        WX.wechat.onMenuShareQQ({
            title: currShareData.title, // 分享标题
            desc: currShareData.desc, // 分享描述
            link: currShareData.link, // 分享链接
            imgUrl: currShareData.imgUrl, // 分享图标
            success: function () {
                currShareData.success && currShareData.success();
                try {
                    _hmt.push(['_trackEvent', "分享成功", '分享成功']);
                } catch (e) {
                }
            },
            cancel: function () {
                currShareData.cancel && currShareData.cancel();
                try {
                    _hmt.push(['_trackEvent', "取消分享", '取消分享']);
                } catch (e) {
                }
            }
        });
    };

    function loadScript(url, callback) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" ||
                    script.readyState == "complete") {
                    script.onreadystatechange = null;
                    typeof (callback) === "function" && callback();
                }
            };
        } else { //Others: Firefox, Safari, Chrome, and Opera
            script.onload = function () {
                typeof (callback) === "function" && callback();
            };
        }
        script.src = url;
        DOMReady(function () {
            document.body.appendChild(script);
        });

    }
    var isDOMReady=false;
    function DOMReady(callback){
        if(isDOMReady){
            typeof (callback) === "function" && callback();
        }else{
            setTimeout(function () {
                if(document.body){
                    isDOMReady=true;
                }
                DOMReady(callback);
            },1);
        }

    }

    function extend(target, source) {
        target = target || {};
        var result = {};
        for (var p in target) {
            if (source.hasOwnProperty(p)) {
                result[p] = source[p];
            } else {
                result[p] = target[p];
            }
        }
        return result;
    }

    "function" == typeof define ? define([wechatSdkUrl],function (wx) {
        WX.setWechat(wx);
        return WX;
    }) : (function () {
        window.tp = window.tp || {};
        window.tp['wx'] = WX;
    })();

})();<commit_msg>微信分享添加   广告跟踪<commit_after>/**
 * Created by hejun on 15/4/15.
 *  纯前端配置-微信分享
 *  1.加载js后 请先执行init方法
 *  2.当前只能在socialpark.com.cn 域名下使用 其他域名使用无效(受公众账号设置限制)
 *  3.本组件依赖 http://res.wx.qq.com/open/js/jweixin-1.0.0.js 自动加载 自动依赖
 *  4.支持 cmd amd 引用
 *  5.全局对象 window.tp.wx
 *  6.返回对象中wechat为微信jssdk方法
 */
!(function () {

    var WX = {
        version: '2.0.3'
    };
    var shareData = {
        title: '',
        desc: '',
        link: '',
        imgUrl: '',
        success: function () {
        },
        cancel: function () {
        }
    };
    var isDebug = false;
    var isInit = false;
    var _currShareData = null;
    var initcallback = null;
    var wechatSdkUrl = "http://res.wx.qq.com/open/js/jweixin-1.0.0.js";
    WX.wechat = null;
    WX.setWechat = function (wechat) {
        WX.wechat = wechat;
    };
    /**
     * 分享初始化
     * @param  {[type]} defaultshareData  默认分享文案
     * @param  {[type]} callback          初始化成功后回调函数
     * @param  {[type]} debug             调试是否打开 默认false
     */
    WX.init = function (defaultshareData, callback, debug) {
        defaultshareData = defaultshareData || {};
        shareData = extend(shareData, defaultshareData);
        debug = debug || isDebug;
        initcallback = typeof(callback) === "function" ? callback : null;
        isDebug = !!debug;
        var url = "http://www.socialpark.com.cn/wechat/getshare.php?t=" + new Date().getTime() + "&callback=tp.wx.config&url=" + encodeURIComponent(location.href.replace(location.hash, ""));

        if ("function" == typeof define) {
            require(["http://www.socialpark.com.cn/wechat/getshare.php?t=" + new Date().getTime() + "&callback=define&url=" + encodeURIComponent(location.href.replace(location.hash, ""))], function (data) {
                WX.config(data);
            });
        }
        else if (window.wx) {
            WX.setWechat(window.wx);
            loadScript(url);
        } else {
            loadScript(wechatSdkUrl, function () {
                WX.setWechat(window.wx);
                loadScript(url);
            })
        }

    };
    WX.config = function (d) {
        if (d.ret != 200) {
            if (isDebug)alert(JSON.stringify(d));
            return;
        }
        WX.wechat.config({
            debug: isDebug,
            appId: d.appid,
            timestamp: d.timestamp,
            nonceStr: d.noncestr,
            signature: d.signature,
            jsApiList: [
                'checkJsApi',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone',
                'hideMenuItems',
                'showMenuItems',
                'hideAllNonBaseMenuItem',
                'showAllNonBaseMenuItem',
                'translateVoice',
                'startRecord',
                'stopRecord',
                'onRecordEnd',
                'playVoice',
                'pauseVoice',
                'stopVoice',
                'uploadVoice',
                'downloadVoice',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'getNetworkType',
                'openLocation',
                'getLocation',
                'hideOptionMenu',
                'showOptionMenu',
                'closeWindow',
                'scanQRCode',
                'chooseWXPay',
                'openProductSpecificView',
                'addCard',
                'chooseCard',
                'openCard'
            ]
        });

        WX.wechat.ready(function () {
            WX.wechat.checkJsApi({
                jsApiList: [
                    'checkJsApi',
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone',
                    'hideMenuItems',
                    'showMenuItems',
                    'hideAllNonBaseMenuItem',
                    'showAllNonBaseMenuItem',
                    'translateVoice',
                    'startRecord',
                    'stopRecord',
                    'onRecordEnd',
                    'playVoice',
                    'pauseVoice',
                    'stopVoice',
                    'uploadVoice',
                    'downloadVoice',
                    'chooseImage',
                    'previewImage',
                    'uploadImage',
                    'downloadImage',
                    'getNetworkType',
                    'openLocation',
                    'getLocation',
                    'hideOptionMenu',
                    'showOptionMenu',
                    'closeWindow',
                    'scanQRCode',
                    'chooseWXPay',
                    'openProductSpecificView',
                    'addCard',
                    'chooseCard',
                    'openCard'
                ],
                success: function checkJsApisuccess(res) {
                    typeof (initcallback) === "function" && initcallback();
                    WX.wechat.hideMenuItems({
                        menuList: ['menuItem:share:weiboApp', 'menuItem:share:facebook']
                    });
                    WX.wechat.showMenuItems({
                        menuList: ['menuItem:profile', 'menuItem:addContact']
                    });
                    isInit = true;
                    WX.setshare(_currShareData);
                }
            });
        });
    };

    WX.setshare = function (d) {

        var hmsrpyq = "hmsr=%E5%BE%AE%E4%BF%A1%E5%A5%BD%E5%8F%8B";//微信朋友圈

        var hmsrhy = "hmsr=%E5%BE%AE%E4%BF%A1%E6%9C%8B%E5%8F%8B%E5%9C%88";//微信好友

        _currShareData = d || {};

        if (!isInit) {
            return;
        }

        var currShareData = extend(shareData, _currShareData);

        if (currShareData.link.indexOf("?") != -1) {

            //if (currShareData.link.indexOf("#") != -1) {
            //
            //    currShareData.link.replace("#", '&') + hmsrpyq;
            //}

            // 分享到微信朋友圈
            WX.wechat.onMenuShareTimeline({
                title: currShareData.title,
                link: currShareData.link+ "&" + hmsrpyq,
                imgUrl: currShareData.imgUrl,
                success: function () {
                    currShareData.success && currShareData.success();
                    try {
                        _hmt.push(['_trackEvent', "分享成功", '分享到朋友圈']);
                    } catch (e) {
                    }
                },
                cancel: function () {
                    currShareData.cancel && currShareData.cancel();
                    try {
                        _hmt.push(['_trackEvent', "取消分享", '取消分享']);
                    } catch (e) {
                    }
                }
            });

            // 发送给指定微信好友
            WX.wechat.onMenuShareAppMessage({
                title: currShareData.title,
                desc: currShareData.desc,
                link: currShareData.link+"&" + hmsrhy,
                imgUrl: currShareData.imgUrl,
                success: function () {
                    currShareData.success && currShareData.success();
                    try {
                        _hmt.push(['_trackEvent', "分享成功", '分享给好友']);
                    } catch (e) {
                    }
                },
                cancel: function () {
                    currShareData.cancel && currShareData.cancel();
                    try {
                        _hmt.push(['_trackEvent', "取消分享", '取消分享']);
                    } catch (e) {
                    }
                }
            });

        } else {

            // 发送给指定微信好友
            WX.wechat.onMenuShareAppMessage({
                title: currShareData.title,
                desc: currShareData.desc,
                link: currShareData.link+"?" + hmsrhy,
                imgUrl: currShareData.imgUrl,
                success: function () {
                    currShareData.success && currShareData.success();
                    try {
                        _hmt.push(['_trackEvent', "分享成功", '分享给好友']);
                    } catch (e) {
                    }
                },
                cancel: function () {
                    currShareData.cancel && currShareData.cancel();
                    try {
                        _hmt.push(['_trackEvent', "取消分享", '取消分享']);
                    } catch (e) {
                    }
                }
            });

            // 分享到微信朋友圈
            WX.wechat.onMenuShareTimeline({
                title: currShareData.title,
                link: currShareData.link+"?" + hmsrpyq,
                imgUrl: currShareData.imgUrl,
                success: function () {
                    currShareData.success && currShareData.success();
                    try {
                        _hmt.push(['_trackEvent', "分享成功", '分享到朋友圈']);
                    } catch (e) {
                    }
                },
                cancel: function () {
                    currShareData.cancel && currShareData.cancel();
                    try {
                        _hmt.push(['_trackEvent', "取消分享", '取消分享']);
                    } catch (e) {
                    }
                }
            });
        }

        WX.wechat.onMenuShareQQ({
            title: currShareData.title, // 分享标题
            desc: currShareData.desc, // 分享描述
            link: currShareData.link, // 分享链接
            imgUrl: currShareData.imgUrl, // 分享图标
            success: function () {
                currShareData.success && currShareData.success();
                try {
                    _hmt.push(['_trackEvent', "分享成功", '分享成功']);
                } catch (e) {
                }
            },
            cancel: function () {
                currShareData.cancel && currShareData.cancel();
                try {
                    _hmt.push(['_trackEvent', "取消分享", '取消分享']);
                } catch (e) {
                }
            }
        });
    };

    function loadScript(url, callback) {

        var script = document.createElement("script");
        script.type = "text/javascript";
        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" ||
                    script.readyState == "complete") {
                    script.onreadystatechange = null;
                    typeof (callback) === "function" && callback();
                }
            };
        } else { //Others: Firefox, Safari, Chrome, and Opera
            script.onload = function () {
                typeof (callback) === "function" && callback();
            };
        }
        script.src = url;
        DOMReady(function () {
            document.body.appendChild(script);
        });

    }

    var isDOMReady = false;

    function DOMReady(callback) {
        if (isDOMReady) {
            typeof (callback) === "function" && callback();
        } else {
            setTimeout(function () {
                if (document.body) {
                    isDOMReady = true;
                }
                DOMReady(callback);
            }, 1);
        }

    }

    function extend(target, source) {
        target = target || {};
        var result = {};
        for (var p in target) {
            if (source.hasOwnProperty(p)) {
                result[p] = source[p];
            } else {
                result[p] = target[p];
            }
        }
        return result;
    }

    "function" == typeof define ? define([wechatSdkUrl], function (wx) {
        WX.setWechat(wx);
        return WX;
    }) : (function () {
        window.tp = window.tp || {};
        window.tp['wx'] = WX;
    })();

})();<|endoftext|>


<commit_before>const exec = require('child_process').exec;
const command = "vncsnapshot 192.168.0.3:5 export.jpg";
const Discord = require("discord.js");

module.exports = function screenshot(message) {
	exec(command, function(error, stdout, stderr) {
		 message.channel.sendFile('./export.jpg', '.jpg', stdout);
	});
}
<commit_msg>Changed screen<commit_after>const exec = require('child_process').exec;
const command = "vncsnapshot 192.168.0.3:3 export.jpg";
const Discord = require("discord.js");

module.exports = function screenshot(message) {
	exec(command, function(error, stdout, stderr) {
		 message.channel.sendFile('./export.jpg', '.jpg', stdout);
	});
}
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');

gulp.paths = {
  src: 'src',
  tmp: '.tmp',
  e2e: 'e2e'
};

require('require-dir')('./gulp');

gulp.task('default', ['clean'], function () {
    gulp.start('watch');
});
<commit_msg>Cleaned gulpfile.js<commit_after>'use strict';

var gulp = require('gulp');

gulp.paths = {
  src: 'src',
  tmp: '.tmp',
  e2e: 'e2e'
};

require('require-dir')('./gulp');

gulp.task('default', function () {
    gulp.start('watch');
});
<|endoftext|>


<commit_before>import _ from 'lodash';
import patterns from './data/patterns.json';
import {getThingViaTimeLimit} from './getThingViaTimeLimit';
import {repeatIntervals} from './repeatIntervals';
import {createSwimsFromPattern} from './createPattern';

function doubleLengths(pattern) {
  console.log('doubleLengths');

  pattern.seconds *= 2;

  _.forEach(pattern.intervals, interval => {
    interval.length *= 2;
    interval.time *= 2;
  });
}

function doubleIntervals(pattern) {
  console.log('doubleIntervals');
  pattern.seconds *= 2;

  _.forEach(pattern.intervals, interval => {
    interval.number *= 2;
  });
}

function condenseWorkout(pattern) {
  console.log(pattern);
}

export function generatePattern(seconds, generatedPattern = { seconds: 0, intervals: [] }) {
  if (seconds < 20) {
    console.log(`weird amount of time left: ${seconds}. returning generated pattern`);
    return generatedPattern;
  }

  console.log('generatePattern');

  let timeLeft = seconds - generatedPattern.seconds;
  let selectedPattern = getThingViaTimeLimit("minTime", timeLeft, patterns);

  console.log(`attempting to generate ${selectedPattern.name} pattern, which needs ${selectedPattern.minTime}, and has ${timeLeft}`)

  if (selectedPattern.repeat === true) {
    return repeatIntervals(timeLeft, generatedPattern);
  } else {
    return createSwimsFromPattern(timeLeft, generatedPattern, selectedPattern);
  }
}

export function generateWorkout(seconds) {
  if (!seconds) { throw new Error('Give me time!'); }

  let pattern = generatePattern(seconds);

  while ((pattern.seconds < (seconds / 2)) && (pattern.seconds >= 20)) {
    switch(_.random(1,3)) {
      case 1:
        doubleLengths(pattern);
        break;
      case 2:
        doubleIntervals(pattern);
        break;
      case 3:
        // add new workout to pattern
        generatePattern(seconds, pattern);
        break;
    }
  }

  while (seconds - pattern.seconds >= 20) {
    generatePattern(seconds, pattern);
  }

  condenseWorkout(pattern);

  return pattern;
}
<commit_msg>add condense function to combine like intervals<commit_after>import _ from 'lodash';
import patterns from './data/patterns.json';
import {getThingViaTimeLimit} from './getThingViaTimeLimit';
import {repeatIntervals} from './repeatIntervals';
import {createSwimsFromPattern} from './createPattern';

function isSameType(intervalA, intervalB) {
  return intervalA.type === intervalB.type
    && intervalA.length === intervalB.length
    && intervalA.time === intervalB.time;
}

function doubleLengths(pattern) {
  console.log('doubleLengths');
  pattern.seconds *= 2;

  _.forEach(pattern.intervals, interval => {
    interval.length *= 2;
    interval.time *= 2;
  });
}

function doubleIntervals(pattern) {
  console.log('doubleIntervals');
  pattern.seconds *= 2;

  _.forEach(pattern.intervals, interval => {
    interval.number *= 2;
  });
}

function condenseWorkout(pattern) {
  pattern.intervals = pattern.intervals.reduce((memo, interval) => {
    let intervalsLength = memo.length;

    if(intervalsLength === 0) {
      memo.push(interval);
      return memo;
    }

    if (isSameType(memo[intervalsLength -1], interval)) {
      console.log('condensing', memo[intervalsLength - 1], interval);
      memo[intervalsLength - 1].number += interval.number;
    } else {
      memo.push(interval)
    }

    return memo;
  }, []);

  console.log(pattern);

  return pattern;
}

export function generatePattern(seconds, generatedPattern = { seconds: 0, intervals: [] }) {
  if (seconds < 20) {
    console.log(`weird amount of time left: ${seconds}. returning generated pattern`);
    return generatedPattern;
  }

  console.log('generatePattern');

  let timeLeft = seconds - generatedPattern.seconds;
  let selectedPattern = getThingViaTimeLimit("minTime", timeLeft, patterns);

  console.log(`attempting to generate ${selectedPattern.name} pattern, which needs ${selectedPattern.minTime}, and has ${timeLeft}`)

  if (selectedPattern.repeat === true) {
    return repeatIntervals(timeLeft, generatedPattern);
  } else {
    return createSwimsFromPattern(timeLeft, generatedPattern, selectedPattern);
  }
}

export function generateWorkout(seconds) {
  if (!seconds) { throw new Error('Give me time!'); }

  let pattern = generatePattern(seconds);

  while ((pattern.seconds < (seconds / 2)) && (pattern.seconds >= 20)) {
    switch(_.random(1,3)) {
      case 1:
        doubleLengths(pattern);
        break;
      case 2:
        doubleIntervals(pattern);
        break;
      case 3:
        // add new workout to pattern
        generatePattern(seconds, pattern);
        break;
    }
  }

  while (seconds - pattern.seconds >= 20) {
    generatePattern(seconds, pattern);
  }

  pattern = condenseWorkout(pattern);

  return pattern;
}
<|endoftext|>


<commit_before>var htmlParser = require('htmlparser2'),
    AST2Html = require('htmlparser-to-html'),
    _ = require('lodash'),
    HtmlDiff = require('./HtmlDiff'),
    utils = require('./utils');

/**
 * Tokenizes the given string
 * @param {String} value
 * @returns {Array}
 */
HtmlDiff.prototype.tokenize = function (value) {
    var options = this.options,
        ASTTree = htmlToAST(value, options);

    ASTTree = modifyASTTree(ASTTree, options);

    /*
     * Bug in 'html-parser-to-html'
     * String '"' is converted into '&quot;'
     * Added issue => github.com/mixu/htmlparser-to-html/issues/1
     */
    value = AST2Html(ASTTree).replace(/&quot;/g, '"');

    return _.filter(value.split(/(\s+|\b)/));
};

/**
 * Converts the HTML document to the AST Tree
 * @param {String} HTMLDoc
 * @returns {AST}
 */
function htmlToAST(HTMLDoc) {
    var parser,
        parserHandler;

    parserHandler = new htmlParser.DomHandler(function (err) {
        if (err) { console.log(err); }
    });

    parser = new htmlParser.Parser(parserHandler);
    parser.parseComplete(HTMLDoc);

    return parserHandler.dom;
}

/**
 * Recursively modifies the tree depending on the given options
 * @param {AST} tree
 * @param {Object} options
 * @returns {AST}
 */
function modifyASTTree(tree, options) {
    var delComments = [];

    _.forEach(tree, function (node) {
        if (options.ignoreWhitespaces && node.type === 'text') {
            node.data = node.data
                .replace(/(\n|\r|\t|\v|\f)+/g, '')
                .replace(/\s+/g, ' ')
                .trim();

            return;
        }

        if (options.ignoreHtmlComments && node.type === 'comment') {
            delComments.push(tree.indexOf(node));

            return;
        }

        if (node.hasOwnProperty('attribs')) {
            var attrs = utils.sortObj(node.attribs);

            if (attrs.hasOwnProperty('class')) {
                attrs['class'] = utils.sortCssClasses(attrs['class']);
            }

            _.forEach(options.compareHtmlAttrsAsJSON, function (attr) {
                var attrValue,
                    isFunction = (attr === 'onclick' || attr === 'ondblclick'); // @FIXME: should be configurable

                if (attrs.hasOwnProperty(attr)) {
                    attrValue = utils.parseAttr(attrs[attr].replace(/"/g, '"'), isFunction);
                    attrValue = utils.sortObj(attrValue);
                    attrValue = JSON.stringify(attrValue);

                    attrs[attr] = (isFunction ? 'return ' : '') + attrValue.replace(/"/g, '"');
                }
            });

            _.forEach(options.ignoreHtmlAttrs, function (attr) {
                attrs.hasOwnProperty(attr) && (attrs[attr] = '');
            });

            node.attribs = attrs;
        }

        if (node.hasOwnProperty('children')) {
            modifyASTTree(node.children, options);
        }
    });

    for (var i = 0; i < delComments.length; i++) {
        tree.splice(delComments[i] - i, 1);
    }

    return tree;
}

/**
 *
 * @param {Object} [options]
 * @param {String[]} [options.ignoreHtmlAttrs]
 * @param {String[]} [options.compareHtmlAttrsAsJSON]
 * @param {Boolean} [options.verbose]
 * @param {Boolean} [options.ignoreWhitespaces=true]
 * @param {Boolean} [options.bem=false]
 * @constructor
 */
var HtmlDiffer = function (options) {
    options = utils.defaults(options);

    if (options.bem) {
        options.ignoreHtmlAttrs = ['id', 'for'];
        options.compareHtmlAttrsAsJSON = ['data-bem', 'onclick', 'ondblclick'];
    }

    this.options = options;
};

/**
 *
 * @param {String} html1
 * @param {String} html2
 * @param {Object} [options]
 * @returns {Diff}
 */
HtmlDiffer.prototype.diffHtml = function (html1, html2, options) {
    if (options) {
        console.warn('WARNING! The third param of \'diffHtml\' method is deprecated!'.bold.red);
    }

    options = _.defaults(this.options, options);

    var htmlDiffer = new HtmlDiff(options);

    return htmlDiffer.diff(html1, html2);
};

/**
 * Compares two given chunks of HTML
 * @param {String} html1
 * @param {String} html2
 * @param {Object} [options]
 * @returns {Boolean}
 */
HtmlDiffer.prototype.isEqual = function (html1, html2, options) {
    if (options) {
        console.warn('WARNING! The third param of \'isEqual\' method is deprecated!'.bold.red);
    }

    options = _.defaults(this.options, options);

    var htmlDiffer = new HtmlDiff(options),
        diff = htmlDiffer.diff(html1, html2);

    return (diff.length === 1 && !diff[0].added && !diff[0].removed);
};

/**
 * @deprecated
 * @param {String} html1
 * @param {String} html2
 */
function bemDiff(html1, html2) {
    console.warn('WARNING! You use deprecated method \'bemDiff\'!'.bold.red);

    var logger = require('./diff-logger'),
        options = {
            ignoreHtmlAttrs: ['id', 'for'],
            compareHtmlAttrsAsJSON: ['data-bem', 'onclick', 'ondblclick']
        },
        loggerOptions = {
            showCharacters: 40
        },
        htmlDiffer = new HtmlDiff(options);

    logger.log(htmlDiffer.diff(html1, html2), loggerOptions);
}

var htmlDiffer = new HtmlDiffer();

module.exports = {
    HtmlDiffer: HtmlDiffer,
    diffHtml: htmlDiffer.diffHtml.bind(htmlDiffer),
    isEqual: htmlDiffer.isEqual.bind(htmlDiffer),

    bemDiff: bemDiff
};
<commit_msg>Get rid of deprecated method 'bemDiff'<commit_after>var htmlParser = require('htmlparser2'),
    AST2Html = require('htmlparser-to-html'),
    _ = require('lodash'),
    HtmlDiff = require('./HtmlDiff'),
    utils = require('./utils');

/**
 * Tokenizes the given string
 * @param {String} value
 * @returns {Array}
 */
HtmlDiff.prototype.tokenize = function (value) {
    var options = this.options,
        ASTTree = htmlToAST(value, options);

    ASTTree = modifyASTTree(ASTTree, options);

    /*
     * Bug in 'html-parser-to-html'
     * String '"' is converted into '&quot;'
     * Added issue => github.com/mixu/htmlparser-to-html/issues/1
     */
    value = AST2Html(ASTTree).replace(/&quot;/g, '"');

    return _.filter(value.split(/(\s+|\b)/));
};

/**
 * Converts the HTML document to the AST Tree
 * @param {String} HTMLDoc
 * @returns {AST}
 */
function htmlToAST(HTMLDoc) {
    var parser,
        parserHandler;

    parserHandler = new htmlParser.DomHandler(function (err) {
        if (err) { console.log(err); }
    });

    parser = new htmlParser.Parser(parserHandler);
    parser.parseComplete(HTMLDoc);

    return parserHandler.dom;
}

/**
 * Recursively modifies the tree depending on the given options
 * @param {AST} tree
 * @param {Object} options
 * @returns {AST}
 */
function modifyASTTree(tree, options) {
    var delComments = [];

    _.forEach(tree, function (node) {
        if (options.ignoreWhitespaces && node.type === 'text') {
            node.data = node.data
                .replace(/(\n|\r|\t|\v|\f)+/g, '')
                .replace(/\s+/g, ' ')
                .trim();

            return;
        }

        if (options.ignoreHtmlComments && node.type === 'comment') {
            delComments.push(tree.indexOf(node));

            return;
        }

        if (node.hasOwnProperty('attribs')) {
            var attrs = utils.sortObj(node.attribs);

            if (attrs.hasOwnProperty('class')) {
                attrs['class'] = utils.sortCssClasses(attrs['class']);
            }

            _.forEach(options.compareHtmlAttrsAsJSON, function (attr) {
                var attrValue,
                    isFunction = (attr === 'onclick' || attr === 'ondblclick'); // @FIXME: should be configurable

                if (attrs.hasOwnProperty(attr)) {
                    attrValue = utils.parseAttr(attrs[attr].replace(/"/g, '"'), isFunction);
                    attrValue = utils.sortObj(attrValue);
                    attrValue = JSON.stringify(attrValue);

                    attrs[attr] = (isFunction ? 'return ' : '') + attrValue.replace(/"/g, '"');
                }
            });

            _.forEach(options.ignoreHtmlAttrs, function (attr) {
                attrs.hasOwnProperty(attr) && (attrs[attr] = '');
            });

            node.attribs = attrs;
        }

        if (node.hasOwnProperty('children')) {
            modifyASTTree(node.children, options);
        }
    });

    for (var i = 0; i < delComments.length; i++) {
        tree.splice(delComments[i] - i, 1);
    }

    return tree;
}

/**
 *
 * @param {Object} [options]
 * @param {String[]} [options.ignoreHtmlAttrs]
 * @param {String[]} [options.compareHtmlAttrsAsJSON]
 * @param {Boolean} [options.verbose]
 * @param {Boolean} [options.ignoreWhitespaces=true]
 * @param {Boolean} [options.bem=false]
 * @constructor
 */
var HtmlDiffer = function (options) {
    options = utils.defaults(options);

    if (options.bem) {
        options.ignoreHtmlAttrs = ['id', 'for'];
        options.compareHtmlAttrsAsJSON = ['data-bem', 'onclick', 'ondblclick'];
    }

    this.options = options;
};

/**
 *
 * @param {String} html1
 * @param {String} html2
 * @param {Object} [options]
 * @returns {Diff}
 */
HtmlDiffer.prototype.diffHtml = function (html1, html2, options) {
    if (options) {
        console.warn('WARNING! The third param of \'diffHtml\' method is deprecated!'.bold.red);
    }

    options = _.defaults(this.options, options);

    var htmlDiffer = new HtmlDiff(options);

    return htmlDiffer.diff(html1, html2);
};

/**
 * Compares two given chunks of HTML
 * @param {String} html1
 * @param {String} html2
 * @param {Object} [options]
 * @returns {Boolean}
 */
HtmlDiffer.prototype.isEqual = function (html1, html2, options) {
    if (options) {
        console.warn('WARNING! The third param of \'isEqual\' method is deprecated!'.bold.red);
    }

    options = _.defaults(this.options, options);

    var htmlDiffer = new HtmlDiff(options),
        diff = htmlDiffer.diff(html1, html2);

    return (diff.length === 1 && !diff[0].added && !diff[0].removed);
};

var htmlDiffer = new HtmlDiffer();

module.exports = {
    HtmlDiffer: HtmlDiffer,
    diffHtml: htmlDiffer.diffHtml.bind(htmlDiffer),
    isEqual: htmlDiffer.isEqual.bind(htmlDiffer)
};
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Link, { navigateTo } from 'gatsby-link'
import Helmet from 'react-helmet'
import Konami from 'react-konami'

// React components
import Header from '../components/Header/Header'
import Footer from '../components/Footer'
import Container from '../components/Container'
import SecretsModal from '../components/SecretsModal'

import 'normalize.css'
import '../fonts/pxplus_ibm_vga8.css'
import '../styles/globals.css'

import styles from './index.module.css'

class TemplateWrapper extends React.Component {
  constructor () {
    super()
  }

  render () {
    const { siteMetadata, buildTime } = this.props.data.site
    const { children } = this.props

    return (

        <Container>

            <Helmet
              title={siteMetadata.title}
              meta={[
                { name: 'description', content: siteMetadata.description },
                { name: 'keywords', content: 'aquellex, gameboy, musician, chiptune, osu!' },
                { property: 'og:site_name', content: data.site.siteMetadata.title },
                { property: 'og:type', content: 'website' },
                { property: 'og:title', content: data.site.siteMetadata.title },
                { property: 'og:description', content: data.site.siteMetadata.description },
              ]}
            />
            <Konami konami={[76, 79, 67, 82, 73, 65, 78]} easterEgg={() => window.open("https://twitter.com/locrian_memes")} />
            <Konami konami={[77, 85, 70, 71, 79]} easterEgg={() => window.location.href = 'https://www.youtube.com/watch?v=NtSgWZbL_kE'
} />
            <SecretsModal />

              {children()}

        </Container>

    )
  }
}

TemplateWrapper.propTypes = {
  data: PropTypes.object,
  children: PropTypes.func
}

export default TemplateWrapper

export const query = graphql`
  query IndexLayoutQuery {
    site {
      siteMetadata {
        title
        description
        author {
          name
          url
          email
        }
      }
      buildTime
    }
  }
`
<commit_msg>fixed helmet implementation on homepage<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Link, { navigateTo } from 'gatsby-link'
import Helmet from 'react-helmet'
import Konami from 'react-konami'

// React components
import Header from '../components/Header/Header'
import Footer from '../components/Footer'
import Container from '../components/Container'
import SecretsModal from '../components/SecretsModal'

import 'normalize.css'
import '../fonts/pxplus_ibm_vga8.css'
import '../styles/globals.css'

import styles from './index.module.css'

class TemplateWrapper extends React.Component {
  constructor () {
    super()
  }

  render () {
    const { siteMetadata, buildTime } = this.props.data.site
    const { children } = this.props

    return (

        <Container>

            <Helmet>
              <title>{siteMetadata.title}</title>
              <meta name="description" content={siteMetadata.description} />
              <meta name="keywords" content="aquellex, gameboy, musician, chiptune, osu" />
              <meta property="og:site_name" content={siteMetadata.title} />
              <meta property="og:type" content="website" />
              <meta property="og:title" content={siteMetadata.title} />
              <meta property="og:description" content={siteMetadata.description} />
            </Helmet>
            <Konami konami={[76, 79, 67, 82, 73, 65, 78]} easterEgg={() => window.open("https://twitter.com/locrian_memes")} />
            <Konami konami={[77, 85, 70, 71, 79]} easterEgg={() => window.location.href = 'https://www.youtube.com/watch?v=NtSgWZbL_kE'} />
            <SecretsModal />

              {children()}

        </Container>

    )
  }
}

TemplateWrapper.propTypes = {
  data: PropTypes.object,
  children: PropTypes.func
}

export default TemplateWrapper

export const query = graphql`
  query IndexLayoutQuery {
    site {
      siteMetadata {
        title
        description
        author {
          name
          url
          email
        }
      }
      buildTime
    }
  }
`
<|endoftext|>