<commit_before>OV.ThreeImporter = class extends OV.ImporterBase
{
    constructor ()
    {
        super ();
    }

    CanImportExtension (extension)
    {
        return extension === 'fbx';
    }

    GetKnownFileFormats ()
    {
        return {
            'fbx' : OV.FileFormat.Binary
        };
    }

    GetUpDirection ()
    {
        return OV.Direction.Z;
    }

    ClearContent ()
    {

    }

    ResetContent ()
    {

    }

    ImportContent (fileContent, onFinish)
    {
        const libraries = this.GetExternalLibraries ();
        if (libraries === null) {
            onFinish ();
            return;
        }
        Promise.all (libraries).then (() => {
            const loader = this.CreateLoader ();
            this.LoadModel (fileContent, loader, onFinish);
        }).catch (() => {
            onFinish ();
        });
    }

    GetExternalLibraries ()
    {
        if (this.extension === 'fbx') {
            return [
                OV.LoadExternalLibrary ('three_loaders/FBXLoader.js'),
                OV.LoadExternalLibrary ('three_loaders/fflate.min.js')
            ];
        }
        return null;
    }

    CreateLoader ()
    {
        const manager = new THREE.LoadingManager ();
        manager.setURLModifier ((url) => {
            if (url.startsWith ('data:') || url.startsWith ('blob:')) {
                return url;
            }
            const fileBuffer = this.callbacks.getFileBuffer (url);
            const fileUrl = OV.CreateObjectUrl (fileBuffer);
            return fileUrl;
        });
        let loader = null;
        if (this.extension === 'fbx') {
            loader = new THREE.FBXLoader (manager);
        }
        return loader;
    }

    LoadModel (fileContent, loader, onFinish)
    {
        function SetColor (color, threeColor)
        {
            color.Set (
                parseInt (threeColor.r * 255.0, 10),
                parseInt (threeColor.g * 255.0, 10),
                parseInt (threeColor.b * 255.0, 10)
            );
        }

        if (loader === null) {
            onFinish ();
            return;
        }

        // TODO: error handling
        const mainFileUrl = OV.CreateObjectUrl (fileContent);
        loader.load (mainFileUrl, (object) => {
            object.traverse ((child) => {
                if (child.isMesh) {
                    // TODO: merge same materials
                    // TODO: PBR materials
                    console.log (child);
                    let threeMaterial = child.material;
                    let material = new OV.Material (OV.MaterialType.Phong);
                    material.name = threeMaterial.name;
                    SetColor (material.color, threeMaterial.color);
                    if (threeMaterial.type === 'MeshPhongMaterial') {
                        SetColor (material.specular, threeMaterial.specular);
                        material.shininess = threeMaterial.shininess / 100.0;
                    }
                    const materialIndex = this.model.AddMaterial (material);
                    let mesh = OV.ConvertThreeGeometryToMesh (child.geometry, materialIndex);
                    if (child.matrixWorld !== undefined && child.matrixWorld !== null) {
                        const matrix = new OV.Matrix (child.matrixWorld.elements);
                        const transformation = new OV.Transformation (matrix);

                        // TODO: flip to transform mesh
                        let determinant = matrix.Determinant ();
                        let mirrorByX = OV.IsNegative (determinant);
                        if (mirrorByX) {
                            OV.FlipMeshTrianglesOrientation (mesh);
                        }
                        OV.TransformMesh (mesh, transformation);
                    }
                    // TODO: transform
                    this.model.AddMesh (mesh);
                }
            });
            onFinish ();
        });
    }
};
<commit_msg>Handle loader errors.<commit_after>OV.ThreeImporter = class extends OV.ImporterBase
{
    constructor ()
    {
        super ();
    }

    CanImportExtension (extension)
    {
        return extension === 'fbx';
    }

    GetKnownFileFormats ()
    {
        return {
            'fbx' : OV.FileFormat.Binary
        };
    }

    GetUpDirection ()
    {
        return OV.Direction.Z;
    }

    ClearContent ()
    {

    }

    ResetContent ()
    {

    }

    ImportContent (fileContent, onFinish)
    {
        const libraries = this.GetExternalLibraries ();
        if (libraries === null) {
            onFinish ();
            return;
        }
        Promise.all (libraries).then (() => {
            const mainFileUrl = OV.CreateObjectUrl (fileContent);
            const loader = this.CreateLoader (mainFileUrl);
            this.LoadModel (mainFileUrl, loader, onFinish);
        }).catch (() => {
            onFinish ();
        });
    }

    GetExternalLibraries ()
    {
        if (this.extension === 'fbx') {
            return [
                OV.LoadExternalLibrary ('three_loaders/FBXLoader.js'),
                OV.LoadExternalLibrary ('three_loaders/fflate.min.js')
            ];
        }
        return null;
    }

    CreateLoader (mainFileUrl)
    {
        const manager = new THREE.LoadingManager ();
        manager.setURLModifier ((url) => {
            if (url === mainFileUrl) {
                return url;
            }
            if (url.startsWith ('data:')) {
                return url;
            }
            const fileBuffer = this.callbacks.getFileBuffer (url);
            const fileUrl = OV.CreateObjectUrl (fileBuffer);
            return fileUrl;
        });
        let loader = null;
        if (this.extension === 'fbx') {
            loader = new THREE.FBXLoader (manager);
        }
        return loader;
    }

    LoadModel (mainFileUrl, loader, onFinish)
    {
        function SetColor (color, threeColor)
        {
            color.Set (
                parseInt (threeColor.r * 255.0, 10),
                parseInt (threeColor.g * 255.0, 10),
                parseInt (threeColor.b * 255.0, 10)
            );
        }

        if (loader === null) {
            onFinish ();
            return;
        }

        // TODO: error handling
        loader.load (mainFileUrl,
            (object) => {
                object.traverse ((child) => {
                    if (child.isMesh) {
                        // TODO: merge same materials
                        // TODO: PBR materials
                        console.log (child);
                        let threeMaterial = child.material;
                        let material = new OV.Material (OV.MaterialType.Phong);
                        material.name = threeMaterial.name;
                        SetColor (material.color, threeMaterial.color);
                        if (threeMaterial.type === 'MeshPhongMaterial') {
                            SetColor (material.specular, threeMaterial.specular);
                            material.shininess = threeMaterial.shininess / 100.0;
                        }
                        const materialIndex = this.model.AddMaterial (material);
                        let mesh = OV.ConvertThreeGeometryToMesh (child.geometry, materialIndex);
                        if (child.matrixWorld !== undefined && child.matrixWorld !== null) {
                            const matrix = new OV.Matrix (child.matrixWorld.elements);
                            const transformation = new OV.Transformation (matrix);
                            const determinant = matrix.Determinant ();
                            const mirrorByX = OV.IsNegative (determinant);
                            OV.TransformMesh (mesh, transformation);
                            if (mirrorByX) {
                                OV.FlipMeshTrianglesOrientation (mesh);
                            }
                        }
                        this.model.AddMesh (mesh);
                    }
                });
                onFinish ();
            },
            () => {

            },
            (err) => {
                this.SetError ();
                this.SetMessage (err);
                onFinish ();
            }
        );
    }
};
<|endoftext|>


<commit_before>'use strict';

describe('Filter: resolve', function () {

  // load the filter's module
  beforeEach(module('tdpharmaClientApp'));

  // initialize a new instance of the filter before each test
  var resolve;
  beforeEach(inject(function ($filter) {
    resolve = $filter('resolve');
  }));

  it('should return the input prefixed with "resolve filter:"', function () {
    var text = 'angularjs';
    expect(resolve(text)).toBe('http://tdpos.herokuapp.com/angularjs');
  });

});
<commit_msg>Fixed resolve filter test<commit_after>'use strict';

describe('Filter: resolve', function () {

  // load the filter's module
  beforeEach(module('tdpharmaClientApp'));

  // initialize a new instance of the filter before each test
  var resolve;
  beforeEach(inject(function ($filter) {
    resolve = $filter('resolve');
  }));

  it('should return the input prefixed with "resolve filter:"', function () {
    var text = 'angularjs';
    var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
      '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
      '((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
      '(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
      '([?][;&a-z\d%_.~+=-]*)?'+ // query string
      '(\#[-a-z\d_]*)?$','i'); // fragment locater
    expect(resolve(text)).toMatch(pattern);
  });

});
<|endoftext|>


<commit_before>"use strict";

/**
* CONTROLLER - `home`
* - Triggers the `todoListComponent` which renders a list in the `HomeComponent`
*
* @module Component->Home-Controller
* @param {Object} component$ The `component.service` module
* @param {Object} data$ The `data.service` module
*/

export default function HomeComponentController(
	component$,
	data$
) {
	const vm = this;
	vm.projectName = "Rectangular";

	// Immutable todo list
	vm.todo = data$.fromJS([
		"get groceries",
		"mow the lawn",
		"be a ninja"
	]);

	// Updated by TodoList parent (HomeComponentController)
	vm.newTodoListItem = "";

	// Called by TodoList parent (HomeComponentController)
	vm.updateTodoList = () => {
		if (vm.newTodoListItem.length) {
			vm.todo = vm.todo.push(vm.newTodoListItem);
		}
	};

	vm.updateTodoList();
};
<commit_msg>Updated documentation<commit_after>"use strict";

/**
* CONTROLLER - `home`
* - Triggers the `todoListComponent` which renders a list in the `HomeComponent`
*
* @module Component->Home-Controller
* @param {Object} data$ The `data.service` module
*/

export default function HomeComponentController(
	data$
) {
	const vm = this;
	vm.projectName = "Rectangular";

	// Immutable todo list
	vm.todo = data$.fromJS([
		"get groceries",
		"mow the lawn",
		"be a ninja"
	]);

	// Updated by TodoList parent (HomeComponentController)
	vm.newTodoListItem = "";

	// Called by TodoList parent (HomeComponentController)
	vm.updateTodoList = () => {
		if (vm.newTodoListItem.length) {
			vm.todo = vm.todo.push(vm.newTodoListItem);
		}
	};

	vm.updateTodoList();
};
<|endoftext|>


<commit_before>'use strict';

angular.module('emuwebApp')
	.directive('mouseTrackAndCorrectionTool', function (viewState, ConfigProviderService, Ssffdataservice, Drawhelperservice, HistoryService, Soundhandlerservice) {
		return {
			restrict: 'A',
			scope: {},
			link: function (scope, element, atts) {

				var curMouseSample;
				var canvas = element[0];
				var ctx = canvas.getContext('2d');
				var tr, col, sRaSt;
				var trackName;
				var bundleName;

				/////////////////////////////
				// observe attribute
				atts.$observe('ssffTrackname', function (val) {
					if (val) {
						trackName = val;
					}
				});

				// bundleName needed to reset tr, col, sRaSt on bundle change
				atts.$observe('bundleName', function (val) {
					if (val) {
						bundleName = val;
						if (!$.isEmptyObject(Ssffdataservice.data)) {
							if (Ssffdataservice.data.length !== 0) {
								tr = ConfigProviderService.getSsffTrackConfig('FORMANTS');
								if (tr !== undefined) {
									col = Ssffdataservice.getColumnOfTrack(tr.name, tr.columnName);
									sRaSt = Ssffdataservice.getSampleRateAndStartTimeOfTrack(tr.name);
								}
							}
						}
					}
				});

				/////////////////////////////
				// Bindings
				element.bind('mousedown', function (event) {
					if(!event.shiftKey){
						viewState.curViewPort.movingS = Math.round(viewState.getX(event) * viewState.getSamplesPerPixelVal(event) + viewState.curViewPort.sS);
						viewState.curViewPort.movingE = viewState.curViewPort.movingS;
						viewState.select(viewState.curViewPort.movingS, viewState.curViewPort.movingE);
						scope.switchMarkupContext(event);
						scope.$apply();
					}
				});

				element.bind('mouseup', function (event) {
					if(event.shiftKey){
						var curSample = Math.round(viewState.getX(event) * viewState.getSamplesPerPixelVal(event) + viewState.curViewPort.sS);
						var movingDist = viewState.curViewPort.movingE - viewState.curViewPort.movingS;
						if(curSample <= viewState.curViewPort.movingS + movingDist/2){
							viewState.curViewPort.movingS = curSample;
						}
						// expand right
						if(curSample >= viewState.curViewPort.movingE - movingDist/2){
							viewState.curViewPort.movingE = curSample;
						}
						viewState.select(viewState.curViewPort.movingS, viewState.curViewPort.movingE);
						scope.switchMarkupContext(event);
						scope.$apply();
					}
				});

				element.bind('mousemove', function (event) {
					var mbutton = 0;
					if (event.buttons === undefined) {
						mbutton = event.which;
					} else {
						mbutton = event.buttons;
					}
					// perform mouse tracking
					var mouseX = viewState.getX(event);
					viewState.curMousePosSample = Math.round(viewState.curViewPort.sS + mouseX / element[0].width * (viewState.curViewPort.eS - viewState.curViewPort.sS));

					switch (mbutton) {
						case 0:
							if (viewState.getPermission('labelAction')) {
								scope.switchMarkupContext(event);
								if (!$.isEmptyObject(Ssffdataservice.data)) {
									if (Ssffdataservice.data.length !== 0) {
										if (!viewState.getdragBarActive()) {
											if (viewState.curCorrectionToolNr !== undefined && !viewState.getdragBarActive() && !$.isEmptyObject(ConfigProviderService.getAssignment(trackName))) {
												// var col = Ssffdataservice.data[0].Columns[0];
												if (tr === undefined) {
													tr = ConfigProviderService.getSsffTrackConfig('FORMANTS');
												}
												col = Ssffdataservice.getColumnOfTrack(tr.name, tr.columnName);
												sRaSt = Ssffdataservice.getSampleRateAndStartTimeOfTrack(tr.name);
												var startTimeVP = viewState.getViewPortStartTime();
												var endTimeVP = viewState.getViewPortEndTime();
												var colStartSampleNr = Math.round(startTimeVP * sRaSt.sampleRate + sRaSt.startTime);
												var colEndSampleNr = Math.round(endTimeVP * sRaSt.sampleRate + sRaSt.startTime);
												var nrOfSamples = colEndSampleNr - colStartSampleNr;
												var curSampleArrs = col.values.slice(colStartSampleNr, colStartSampleNr + nrOfSamples);
												var curMouseTime = startTimeVP + (viewState.getX(event) / event.originalEvent.target.width) * (endTimeVP - startTimeVP);
												var curMouseSample = Math.round((curMouseTime + sRaSt.startTime) * sRaSt.sampleRate) - 1; //-1 for in view correction
												var curMouseSampleTime = (1 / sRaSt.sampleRate * curMouseSample) + sRaSt.startTime;
												if (curMouseSample - colStartSampleNr < 0 || curMouseSample - colStartSampleNr >= curSampleArrs.length) {
													//console.log('early return');
													return;
												}
												viewState.curPreselColumnSample = curMouseSample - colStartSampleNr;
												var x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
												var y = canvas.height - curSampleArrs[viewState.curPreselColumnSample][viewState.curCorrectionToolNr - 1] / (viewState.spectroSettings.rangeTo - viewState.spectroSettings.rangeFrom) * canvas.height;

												// draw sample
												ctx.strokeStyle = 'black';
												ctx.fillStyle = 'black';
												ctx.beginPath();
												ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
												ctx.closePath();
												ctx.stroke();
												ctx.fill();

												if (event.shiftKey) {
													var oldValue = angular.copy(curSampleArrs[viewState.curPreselColumnSample][viewState.curCorrectionToolNr - 1]);
													var newValue = viewState.spectroSettings.rangeTo - viewState.getY(event) / event.originalEvent.target.height * viewState.spectroSettings.rangeTo; // SIC only using rangeTo

													curSampleArrs[viewState.curPreselColumnSample][viewState.curCorrectionToolNr - 1] = viewState.spectroSettings.rangeTo - viewState.getY(event) / event.originalEvent.target.height * viewState.spectroSettings.rangeTo;
													var updateObj = HistoryService.updateCurChangeObj({
														'type': 'SSFF',
														'trackName': tr.name,
														'sampleBlockIdx': colStartSampleNr + viewState.curPreselColumnSample,
														'sampleIdx': viewState.curCorrectionToolNr - 1,
														'oldValue': oldValue,
														'newValue': newValue
													});

													//draw updateObj as overlay
													for (var key in updateObj) {
														curMouseSampleTime = (1 / sRaSt.sampleRate * updateObj[key].sampleBlockIdx) + sRaSt.startTime;
														x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
														y = canvas.height - updateObj[key].newValue / (viewState.spectroSettings.rangeTo - viewState.spectroSettings.rangeFrom) * canvas.height;

														// draw sample
														ctx.strokeStyle = 'red';
														ctx.fillStyle = 'red';
														// ctx.lineWidth = 4;
														ctx.beginPath();
														ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
														ctx.closePath();
														ctx.stroke();
														ctx.fill();
													}
												}
											}
										}
									}
								}
							}
							break;
						case 1:
							if (!viewState.getdragBarActive()) {
								scope.setSelectDrag(event);
							}
							break;
					}
					scope.$apply();
				});
				/*
				 element.bind('mouseup', function (event) {
				 if (!viewState.getdragBarActive()) {
				 scope.setSelectDrag(event);
				 scope.switchMarkupContext(event, false);
				 }
				 });
				 */
				// on mouse leave clear markup canvas
				element.bind('mouseleave', function (event) {
					if (!$.isEmptyObject(Soundhandlerservice)) {
						if (!$.isEmptyObject(Soundhandlerservice.audioBuffer)) {
							if (!viewState.getdragBarActive()) {
								if (viewState.getPermission('labelAction')) {
									scope.switchMarkupContext(event, false);
								}
							}
						}
					}
				});

				//
				////////////////////
				// Functions

				scope.switchMarkupContext = function (event, leave) {
					ctx.clearRect(0, 0, canvas.width, canvas.height);
					// draw current viewport selected
					if (atts.ssffTrackname === 'OSCI') {
						Drawhelperservice.drawViewPortTimes(ctx, true);
						Drawhelperservice.drawCurViewPortSelected(ctx, true);
					} else if (atts.ssffTrackname === 'SPEC') {
						Drawhelperservice.drawCurViewPortSelected(ctx, false);
						Drawhelperservice.drawMinMaxAndName(ctx, '', viewState.spectroSettings.rangeFrom, viewState.spectroSettings.rangeTo, 2);
					} else {
						var tr = ConfigProviderService.getSsffTrackConfig(atts.ssffTrackname);
						var col = Ssffdataservice.getColumnOfTrack(tr.name, tr.columnName);
						Drawhelperservice.drawCurViewPortSelected(ctx, false);
						Drawhelperservice.drawMinMaxAndName(ctx, atts.ssffTrackname, col._minVal, col._maxVal, 2);
					}
					// draw crossHairs
					if (leave !== false && ConfigProviderService.vals.restrictions.drawCrossHairs) {
						Drawhelperservice.drawCrossHairs(ctx, event, viewState.spectroSettings.rangeFrom, viewState.spectroSettings.rangeTo, 'Hz', atts.ssffTrackname);
					}
					// draw moving boundary line if moving
					Drawhelperservice.drawMovingBoundaryLine(ctx);
				};

				scope.setSelectDrag = function (event) {
					curMouseSample = Math.round(viewState.getX(event) * viewState.getSamplesPerPixelVal(event) + viewState.curViewPort.sS);
					if (curMouseSample > viewState.curViewPort.movingS) {
						viewState.curViewPort.movingE = curMouseSample;
					} else {
						viewState.curViewPort.movingS = curMouseSample;
					}
					viewState.select(viewState.curViewPort.movingS, viewState.curViewPort.movingE);
					scope.$apply();
				};
			}
		};
	});
<commit_msg>fixed bad shit click selection<commit_after>'use strict';

angular.module('emuwebApp')
	.directive('mouseTrackAndCorrectionTool', function (viewState, ConfigProviderService, Ssffdataservice, Drawhelperservice, HistoryService, Soundhandlerservice) {
		return {
			restrict: 'A',
			scope: {},
			link: function (scope, element, atts) {

				var curMouseSample;
				var canvas = element[0];
				var ctx = canvas.getContext('2d');
				var tr, col, sRaSt;
				var trackName;
				var bundleName;

				/////////////////////////////
				// observe attribute
				atts.$observe('ssffTrackname', function (val) {
					if (val) {
						trackName = val;
					}
				});

				// bundleName needed to reset tr, col, sRaSt on bundle change
				atts.$observe('bundleName', function (val) {
					if (val) {
						bundleName = val;
						if (!$.isEmptyObject(Ssffdataservice.data)) {
							if (Ssffdataservice.data.length !== 0) {
								tr = ConfigProviderService.getSsffTrackConfig('FORMANTS');
								if (tr !== undefined) {
									col = Ssffdataservice.getColumnOfTrack(tr.name, tr.columnName);
									sRaSt = Ssffdataservice.getSampleRateAndStartTimeOfTrack(tr.name);
								}
							}
						}
					}
				});

				/////////////////////////////
				// Bindings
				element.bind('mousedown', function (event) {
					if(!event.shiftKey){
						viewState.curViewPort.movingS = Math.round(viewState.getX(event) * viewState.getSamplesPerPixelVal(event) + viewState.curViewPort.sS);
						viewState.curViewPort.movingE = viewState.curViewPort.movingS;
						viewState.select(viewState.curViewPort.movingS, viewState.curViewPort.movingE);
						scope.switchMarkupContext(event);
						scope.$apply();
					}
				});

				element.bind('mouseup', function (event) {
					if(event.shiftKey){
						var curSample = Math.round(viewState.getX(event) * viewState.getSamplesPerPixelVal(event) + viewState.curViewPort.sS);
						var selectDist = viewState.curViewPort.selectE - viewState.curViewPort.selectS;
						if(curSample <= viewState.curViewPort.selectS + selectDist/2){
							viewState.curViewPort.selectS = curSample;
						}
						// expand right
						if(curSample >= viewState.curViewPort.selectE - selectDist/2){
							viewState.curViewPort.selectE = curSample;
						}
						scope.switchMarkupContext(event);
						scope.$apply();
					}
				});

				element.bind('mousemove', function (event) {
					var mbutton = 0;
					if (event.buttons === undefined) {
						mbutton = event.which;
					} else {
						mbutton = event.buttons;
					}
					// perform mouse tracking
					var mouseX = viewState.getX(event);
					viewState.curMousePosSample = Math.round(viewState.curViewPort.sS + mouseX / element[0].width * (viewState.curViewPort.eS - viewState.curViewPort.sS));

					switch (mbutton) {
						case 0:
							if (viewState.getPermission('labelAction')) {
								scope.switchMarkupContext(event);
								if (!$.isEmptyObject(Ssffdataservice.data)) {
									if (Ssffdataservice.data.length !== 0) {
										if (!viewState.getdragBarActive()) {
											if (viewState.curCorrectionToolNr !== undefined && !viewState.getdragBarActive() && !$.isEmptyObject(ConfigProviderService.getAssignment(trackName))) {
												// var col = Ssffdataservice.data[0].Columns[0];
												if (tr === undefined) {
													tr = ConfigProviderService.getSsffTrackConfig('FORMANTS');
												}
												col = Ssffdataservice.getColumnOfTrack(tr.name, tr.columnName);
												sRaSt = Ssffdataservice.getSampleRateAndStartTimeOfTrack(tr.name);
												var startTimeVP = viewState.getViewPortStartTime();
												var endTimeVP = viewState.getViewPortEndTime();
												var colStartSampleNr = Math.round(startTimeVP * sRaSt.sampleRate + sRaSt.startTime);
												var colEndSampleNr = Math.round(endTimeVP * sRaSt.sampleRate + sRaSt.startTime);
												var nrOfSamples = colEndSampleNr - colStartSampleNr;
												var curSampleArrs = col.values.slice(colStartSampleNr, colStartSampleNr + nrOfSamples);
												var curMouseTime = startTimeVP + (viewState.getX(event) / event.originalEvent.target.width) * (endTimeVP - startTimeVP);
												var curMouseSample = Math.round((curMouseTime + sRaSt.startTime) * sRaSt.sampleRate) - 1; //-1 for in view correction
												var curMouseSampleTime = (1 / sRaSt.sampleRate * curMouseSample) + sRaSt.startTime;
												if (curMouseSample - colStartSampleNr < 0 || curMouseSample - colStartSampleNr >= curSampleArrs.length) {
													//console.log('early return');
													return;
												}
												viewState.curPreselColumnSample = curMouseSample - colStartSampleNr;
												var x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
												var y = canvas.height - curSampleArrs[viewState.curPreselColumnSample][viewState.curCorrectionToolNr - 1] / (viewState.spectroSettings.rangeTo - viewState.spectroSettings.rangeFrom) * canvas.height;

												// draw sample
												ctx.strokeStyle = 'black';
												ctx.fillStyle = 'black';
												ctx.beginPath();
												ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
												ctx.closePath();
												ctx.stroke();
												ctx.fill();

												if (event.shiftKey) {
													var oldValue = angular.copy(curSampleArrs[viewState.curPreselColumnSample][viewState.curCorrectionToolNr - 1]);
													var newValue = viewState.spectroSettings.rangeTo - viewState.getY(event) / event.originalEvent.target.height * viewState.spectroSettings.rangeTo; // SIC only using rangeTo

													curSampleArrs[viewState.curPreselColumnSample][viewState.curCorrectionToolNr - 1] = viewState.spectroSettings.rangeTo - viewState.getY(event) / event.originalEvent.target.height * viewState.spectroSettings.rangeTo;
													var updateObj = HistoryService.updateCurChangeObj({
														'type': 'SSFF',
														'trackName': tr.name,
														'sampleBlockIdx': colStartSampleNr + viewState.curPreselColumnSample,
														'sampleIdx': viewState.curCorrectionToolNr - 1,
														'oldValue': oldValue,
														'newValue': newValue
													});

													//draw updateObj as overlay
													for (var key in updateObj) {
														curMouseSampleTime = (1 / sRaSt.sampleRate * updateObj[key].sampleBlockIdx) + sRaSt.startTime;
														x = (curMouseSampleTime - startTimeVP) / (endTimeVP - startTimeVP) * canvas.width;
														y = canvas.height - updateObj[key].newValue / (viewState.spectroSettings.rangeTo - viewState.spectroSettings.rangeFrom) * canvas.height;

														// draw sample
														ctx.strokeStyle = 'red';
														ctx.fillStyle = 'red';
														// ctx.lineWidth = 4;
														ctx.beginPath();
														ctx.arc(x, y - 1, 2, 0, 2 * Math.PI, false);
														ctx.closePath();
														ctx.stroke();
														ctx.fill();
													}
												}
											}
										}
									}
								}
							}
							break;
						case 1:
							if (!viewState.getdragBarActive()) {
								scope.setSelectDrag(event);
							}
							break;
					}
					scope.$apply();
				});
				/*
				 element.bind('mouseup', function (event) {
				 if (!viewState.getdragBarActive()) {
				 scope.setSelectDrag(event);
				 scope.switchMarkupContext(event, false);
				 }
				 });
				 */
				// on mouse leave clear markup canvas
				element.bind('mouseleave', function (event) {
					if (!$.isEmptyObject(Soundhandlerservice)) {
						if (!$.isEmptyObject(Soundhandlerservice.audioBuffer)) {
							if (!viewState.getdragBarActive()) {
								if (viewState.getPermission('labelAction')) {
									scope.switchMarkupContext(event, false);
								}
							}
						}
					}
				});

				//
				////////////////////
				// Functions

				scope.switchMarkupContext = function (event, leave) {
					ctx.clearRect(0, 0, canvas.width, canvas.height);
					// draw current viewport selected
					if (atts.ssffTrackname === 'OSCI') {
						Drawhelperservice.drawViewPortTimes(ctx, true);
						Drawhelperservice.drawCurViewPortSelected(ctx, true);
					} else if (atts.ssffTrackname === 'SPEC') {
						Drawhelperservice.drawCurViewPortSelected(ctx, false);
						Drawhelperservice.drawMinMaxAndName(ctx, '', viewState.spectroSettings.rangeFrom, viewState.spectroSettings.rangeTo, 2);
					} else {
						var tr = ConfigProviderService.getSsffTrackConfig(atts.ssffTrackname);
						var col = Ssffdataservice.getColumnOfTrack(tr.name, tr.columnName);
						Drawhelperservice.drawCurViewPortSelected(ctx, false);
						Drawhelperservice.drawMinMaxAndName(ctx, atts.ssffTrackname, col._minVal, col._maxVal, 2);
					}
					// draw crossHairs
					if (leave !== false && ConfigProviderService.vals.restrictions.drawCrossHairs) {
						Drawhelperservice.drawCrossHairs(ctx, event, viewState.spectroSettings.rangeFrom, viewState.spectroSettings.rangeTo, 'Hz', atts.ssffTrackname);
					}
					// draw moving boundary line if moving
					Drawhelperservice.drawMovingBoundaryLine(ctx);
				};

				scope.setSelectDrag = function (event) {
					curMouseSample = Math.round(viewState.getX(event) * viewState.getSamplesPerPixelVal(event) + viewState.curViewPort.sS);
					if (curMouseSample > viewState.curViewPort.movingS) {
						viewState.curViewPort.movingE = curMouseSample;
					} else {
						viewState.curViewPort.movingS = curMouseSample;
					}
					viewState.select(viewState.curViewPort.movingS, viewState.curViewPort.movingE);
					scope.$apply();
				};
			}
		};
	});
<|endoftext|>


<commit_before>// ==UserScript==
// @name          PHPBB thread mute
// @namespace     http://pirati.cz/
// @version       0.24
// @author        Lukas -krtek.net- Novy <zmrd@krtek.net>
// @description   Delists muted threads for 7 days
// @match         https://forum.pirati.cz/*
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// @require       http://coruvar.cz/jquery.cookie.js
// ==/UserScript==

$(function () {
	var muted = $.cookie('mute-threads');
	if (!muted) {
		muted = {};
	} else {
		muted = JSON.parse(muted);
	}
	var now = new Date().valueOf() / 1000;
	var n = {};
	for (var i in muted) {
		var e = muted[i];
		if (now - e < 60 * 60 * 24 * 14) {
			n[i] = e;
		}
	}
	muted = n;

	$('ul.topiclist.topics li dl dt a.topictitle').each(function() {
		var url = this.href;

		url = url.replace(/\.html$/, '');
		var topic_id = url.replace(/.+t/g, '');

		if ('t-' + topic_id in muted) {
			$(this).parent().parent().parent().remove();
		} else {
			var button = $("<button>MUTE</button>");
			button.click(function() {
				muted['t-' + topic_id] = now;
				$.cookie('mute-threads', JSON.stringify(muted), {expires: 365, path: '/'});
				$(this).parent().parent().parent().remove();
			});
			button.css("font-size", "50%");
			button.css("font-weight", "bold");
			button.css("border", "1px solid gray");
			button.css("margin", "1px 10px 0 0");
			button.css("float", "right");
			button.css("background", "rgb(230,230,230)");
			button.css("color", "blue");
			button.css("border-radius", "3px");
			button.css("padding", "0px 2px");
			button.css("cursor", "pointer");
			$(this).parent().append(button);
		}
	});
})();
<commit_msg>undo mute after mutting<commit_after>// ==UserScript==
// @name          PHPBB thread mute
// @namespace     http://pirati.cz/
// @version       0.25
// @author        Lukas -krtek.net- Novy <zmrd@krtek.net>
// @description   Delists muted threads for 7 days
// @match         https://forum.pirati.cz/*
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// @require       http://coruvar.cz/jquery.cookie.js
// ==/UserScript==

$(function () {
	var muted = $.cookie('mute-threads');
	if (!muted) {
		muted = {};
	} else {
		muted = JSON.parse(muted);
	}
	var now = new Date().valueOf() / 1000;
	var n = {};
	for (var i in muted) {
		var e = muted[i];
		if (now - e < 60 * 60 * 24 * 14) {
			n[i] = e;
		}
	}
	muted = n;

	$('ul.topiclist.topics li dl dt a.topictitle').each(function() {
		var url = this.href;

		url = url.replace(/\.html$/, '');
		var topic_id = url.replace(/.+t/g, '');

		if ('t-' + topic_id in muted) {
			$(this).parent().parent().parent().hide();
		} else {
			var button = $("<button>MUTE</button>");
			var unmutefun;
			var mutefun = function() {
				muted['t-' + topic_id] = now;
				$.cookie('mute-threads', JSON.stringify(muted), {expires: 365, path: '/'});
				$(this).html('UNMUTE');
				$(this).unbind('click', mutefun);
				$(this).click(unmutefun);
			};
			var unmutefun = function () {
				delete muted['t-' + topic_id];
				$.cookie('mute-threads', JSON.stringify(muted), {expires: 365, path: '/'});
				$(this).html('MUTE');
				$(this).unbind('click', unmutefun);
				$(this).click(mutefun);
			};
			button.click(mutefun);
			button.css("font-size", "50%");
			button.css("font-weight", "bold");
			button.css("border", "1px solid gray");
			button.css("margin", "1px 10px 0 0");
			button.css("float", "right");
			button.css("background", "rgb(230,230,230)");
			button.css("color", "blue");
			button.css("border-radius", "3px");
			button.css("padding", "0px 2px");
			button.css("cursor", "pointer");
			$(this).parent().append(button);
		}
	});
})();
<|endoftext|>


<commit_before>/*global React ReactDOM __ Immutable __Element*/

//const __Element = require("timeengine-react");
//this code is required to transpile babel site

"use strict";

var _slicedToArray = (function() {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;
    try {
      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);
        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d)
          throw _e;
      }
    }
    return _arr;
  }
  return function(arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
})();

(function() {
  'use strict';

  // `.intervalSeq` is to map Immutable-js infinite Sequence
  //                       on TimeEngine infinite Sequence
  // map natural numbers sequence on intervalSeq(1000)
  var TimerElement = function TimerElement() {
    return __Element(__.intervalSeq(Immutable.Range(), 1000).__(function(count) {
      return __.log.t = count;
    }) //console.log
      .__(function(count) {
        return React.createElement(
          "div",
          null,
          "Timer : ",
          count
        );
      }));
  };

  var CounterElementStateHistory = function CounterElementStateHistory() {
    var __updn = __(true); //1 or -1 or initially 0
    var __seqEl = __([__updn]).__(function(_ref) {
      var _ref2 = _slicedToArray(_ref, 1);

      var updn = _ref2[0];
      return __updn.reduce(function(a, b) {
        return a + b;
      });
    }) //js Array.reduce
      .__(function(count) {
        return React.createElement(
          "span",
          null,
          count
        );
      });
    var init = function init() {
      return __updn.t = 0;
    }; //just trigger to view the init
    var __runNow = __.intervalSeq(Immutable.Seq.of(true), 0).__(init);
    return React.createElement(
      "span",
      null,
      React.createElement(
        "button",
        {
          onClick: function() {
            return __updn.t = 1;
          }
        },
        "Up"
      ),
      React.createElement(
        "button",
        {
          onClick: function() {
            return __updn.t = -1;
          }
        },
        "Down"
      ),
      "  ",
      __Element(__seqEl),
      "  "
    );
  };

  var CounterReloadElement = function CounterReloadElement() {
    var __clicked = __();
    var onClick = function onClick() {
      __clicked.t = true;
    };
    var __runNow = __.intervalSeq(Immutable.Seq.of(true), 0).__(onClick);
    var __seqEl = __([__clicked]).__(function() {
      return React.createElement(
        "span",
        null,
        CounterElementStateHistory()
      );
    });
    return React.createElement(
      "div",
      null,
      __Element(__seqEl),
      React.createElement(
        "button",
        {
          onClick: onClick
        },
        "Reload"
      )
    );
  };

  var CounterElement = function CounterElement() {
    var __updn = __();
    var __count = __([__updn]).__(function(_ref3) {
      var _ref32 = _slicedToArray(_ref3, 1);

      var updn = _ref32[0];
      return updn === 0 ? 0 : __count.t + updn;
    });
    var init = function init() {
      return __updn.t = 0;
    }; //initial value of count
    var __runNow = __.intervalSeq(Immutable.Seq.of(true), 0).__(init);
    var __seqEl = __([__count]).__(function(_ref4) {
      var _ref42 = _slicedToArray(_ref4, 1);

      var count = _ref42[0];
      return React.createElement(
        "span",
        null,
        count
      );
    });
    return React.createElement(
      "div",
      null,
      React.createElement(
        "button",
        {
          onClick: function() {
            return __updn.t = 1;
          }
        },
        "Up"
      ),
      React.createElement(
        "button",
        {
          onClick: function() {
            return __updn.t = -1;
          }
        },
        "Down"
      ),
      "  ",
      __Element(__seqEl),
      "  ",
      React.createElement(
        "button",
        {
          onClick: init
        },
        "Reset"
      )
    );
  };

  var PhysicsElement = function PhysicsElement() {
    //MKS system of units
    var V0 = 90.0; // m/s
    var DEG = 45; //degree
    var THETA = DEG / 180 * Math.PI; //radian
    var G = 9.8; //gravity const
    //t seconds elapsed 0msec time resolution
    var t = __.intervalSeq(Immutable.Range(), 10).__(function(count) {
      return count * 10 / 1000;
    });
    var x = __([t]).__(function(_ref5) {
      var _ref52 = _slicedToArray(_ref5, 1);

      var t = _ref52[0];
      return V0 * Math.cos(THETA) * t;
    });
    var y = __([t]).__(function(_ref6) {
      var _ref62 = _slicedToArray(_ref6, 1);

      var t = _ref62[0];
      return V0 * Math.sin(THETA) * t - 1 / 2 * G * Math.pow(t, 2);
    });
    //==================================
    var Drawscale = 1; //1 dot = 1 meter
    var __seqEl = __([x, y]) //atomic update
      .__(function(_ref7) {
        var _ref72 = _slicedToArray(_ref7, 2);

        var x = _ref72[0];
        var y = _ref72[1];
        return React.createElement(
          "div",
          null,
          React.createElement(
            "svg",
            {
              height: "250",
              width: "100%"
            },
            React.createElement("circle", {
              r: "2",
              fill: "red",
              cx: 50 + x * Drawscale,
              cy: 250 - y * Drawscale
            })
          )
        );
      });
    return __Element(__seqEl);
  };

  var WorldElement = function WorldElement() {
    var __clicked = __();
    var onClick = function onClick() {
      __clicked.t = true;
    };
    var __seqEl = __([__clicked]).__(function() {
      return React.createElement(
        "div",
        null,
        PhysicsElement()
      );
    });

    return React.createElement(
      "div",
      null,
      React.createElement(
        "div",
        null,
        React.createElement(
          "button",
          {
            onClick: onClick
          },
          "Physics Start"
        )
      ),
      __Element(__seqEl)
    );
  };

  var mount0 = ReactDOM.render(React.createElement(
    "h3",
    null,
    TimerElement()
  ), document.getElementById('div0'));

  var mount1 = ReactDOM.render(React.createElement(
    "div",
    null,
    CounterElement()
  ), document.getElementById('div1'));

  var mount2 = ReactDOM.render(React.createElement(
    "div",
    null,
    WorldElement()
  ), document.getElementById('div2'));
})();

console.log('test');
onload = () => {
  console.log('onload!!');
  const canvas = document.getElementById('canvas1');
  const ctx = canvas.getContext('2d');
  const __mouseDown = __();
  const __drawFrom = __();
  const __drawTo = __()
    .__(
      (val) => {
        ctx.beginPath();
        ctx.moveTo(__drawFrom.t.x, __drawFrom.t.y);
        ctx.lineTo(val.x, val.y);
        ctx.closePath();
        ctx.stroke();
        return val;
      }
  );
  canvas.onmousedown = (e) => {
    __mouseDown.t = 1;
    __drawFrom.t = {
      x: e.clientX,
      y: e.clientY
    };
  };
  canvas.onmouseup = (e) => {
    __mouseDown.t = 0;
  };
  canvas.onmousemove = (e) => {
    if (__mouseDown.t === 1) {
      __drawTo.t = {
        x: e.clientX,
        y: e.clientY
      };
      __drawFrom.t = __drawTo.t;

      __.log.t = __drawFrom.t;
    }
  };
};
<commit_msg>commit<commit_after>/*global React ReactDOM __ Immutable __Element*/

//const __Element = require("timeengine-react");
//this code is required to transpile babel site

"use strict";

var _slicedToArray = (function() {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;
    try {
      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);
        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d)
          throw _e;
      }
    }
    return _arr;
  }
  return function(arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
})();

(function() {
  'use strict';

  // `.intervalSeq` is to map Immutable-js infinite Sequence
  //                       on TimeEngine infinite Sequence
  // map natural numbers sequence on intervalSeq(1000)
  var TimerElement = function TimerElement() {
    return __Element(__.intervalSeq(Immutable.Range(), 1000).__(function(count) {
      return __.log.t = count;
    }) //console.log
      .__(function(count) {
        return React.createElement(
          "div",
          null,
          "Timer : ",
          count
        );
      }));
  };

  var CounterElementStateHistory = function CounterElementStateHistory() {
    var __updn = __(true); //1 or -1 or initially 0
    var __seqEl = __([__updn]).__(function(_ref) {
      var _ref2 = _slicedToArray(_ref, 1);

      var updn = _ref2[0];
      return __updn.reduce(function(a, b) {
        return a + b;
      });
    }) //js Array.reduce
      .__(function(count) {
        return React.createElement(
          "span",
          null,
          count
        );
      });
    var init = function init() {
      return __updn.t = 0;
    }; //just trigger to view the init
    var __runNow = __.intervalSeq(Immutable.Seq.of(true), 0).__(init);
    return React.createElement(
      "span",
      null,
      React.createElement(
        "button",
        {
          onClick: function() {
            return __updn.t = 1;
          }
        },
        "Up"
      ),
      React.createElement(
        "button",
        {
          onClick: function() {
            return __updn.t = -1;
          }
        },
        "Down"
      ),
      "  ",
      __Element(__seqEl),
      "  "
    );
  };

  var CounterReloadElement = function CounterReloadElement() {
    var __clicked = __();
    var onClick = function onClick() {
      __clicked.t = true;
    };
    var __runNow = __.intervalSeq(Immutable.Seq.of(true), 0).__(onClick);
    var __seqEl = __([__clicked]).__(function() {
      return React.createElement(
        "span",
        null,
        CounterElementStateHistory()
      );
    });
    return React.createElement(
      "div",
      null,
      __Element(__seqEl),
      React.createElement(
        "button",
        {
          onClick: onClick
        },
        "Reload"
      )
    );
  };

  var CounterElement = function CounterElement() {
    var __updn = __();
    var __count = __([__updn]).__(function(_ref3) {
      var _ref32 = _slicedToArray(_ref3, 1);

      var updn = _ref32[0];
      return updn === 0 ? 0 : __count.t + updn;
    });
    var init = function init() {
      return __updn.t = 0;
    }; //initial value of count
    var __runNow = __.intervalSeq(Immutable.Seq.of(true), 0).__(init);
    var __seqEl = __([__count]).__(function(_ref4) {
      var _ref42 = _slicedToArray(_ref4, 1);

      var count = _ref42[0];
      return React.createElement(
        "span",
        null,
        count
      );
    });
    return React.createElement(
      "div",
      null,
      React.createElement(
        "button",
        {
          onClick: function() {
            return __updn.t = 1;
          }
        },
        "Up"
      ),
      React.createElement(
        "button",
        {
          onClick: function() {
            return __updn.t = -1;
          }
        },
        "Down"
      ),
      "  ",
      __Element(__seqEl),
      "  ",
      React.createElement(
        "button",
        {
          onClick: init
        },
        "Reset"
      )
    );
  };

  var PhysicsElement = function PhysicsElement() {
    //MKS system of units
    var V0 = 90.0; // m/s
    var DEG = 45; //degree
    var THETA = DEG / 180 * Math.PI; //radian
    var G = 9.8; //gravity const
    //t seconds elapsed 0msec time resolution
    var t = __.intervalSeq(Immutable.Range(), 10).__(function(count) {
      return count * 10 / 1000;
    });
    var x = __([t]).__(function(_ref5) {
      var _ref52 = _slicedToArray(_ref5, 1);

      var t = _ref52[0];
      return V0 * Math.cos(THETA) * t;
    });
    var y = __([t]).__(function(_ref6) {
      var _ref62 = _slicedToArray(_ref6, 1);

      var t = _ref62[0];
      return V0 * Math.sin(THETA) * t - 1 / 2 * G * Math.pow(t, 2);
    });
    //==================================
    var Drawscale = 1; //1 dot = 1 meter
    var __seqEl = __([x, y]) //atomic update
      .__(function(_ref7) {
        var _ref72 = _slicedToArray(_ref7, 2);

        var x = _ref72[0];
        var y = _ref72[1];
        return React.createElement(
          "div",
          null,
          React.createElement(
            "svg",
            {
              height: "250",
              width: "100%"
            },
            React.createElement("circle", {
              r: "2",
              fill: "red",
              cx: 50 + x * Drawscale,
              cy: 250 - y * Drawscale
            })
          )
        );
      });
    return __Element(__seqEl);
  };

  var WorldElement = function WorldElement() {
    var __clicked = __();
    var onClick = function onClick() {
      __clicked.t = true;
    };
    var __seqEl = __([__clicked]).__(function() {
      return React.createElement(
        "div",
        null,
        PhysicsElement()
      );
    });

    return React.createElement(
      "div",
      null,
      React.createElement(
        "div",
        null,
        React.createElement(
          "button",
          {
            onClick: onClick
          },
          "Physics Start"
        )
      ),
      __Element(__seqEl)
    );
  };

  var mount0 = ReactDOM.render(React.createElement(
    "h3",
    null,
    TimerElement()
  ), document.getElementById('div0'));

  var mount1 = ReactDOM.render(React.createElement(
    "div",
    null,
    CounterElement()
  ), document.getElementById('div1'));

  var mount2 = ReactDOM.render(React.createElement(
    "div",
    null,
    WorldElement()
  ), document.getElementById('div2'));
})();

console.log('test');
setTimeout(() => {
  console.log('onload!!');
  const canvas = document.getElementById('canvas1');
  const ctx = canvas.getContext('2d');
  const __mouseDown = __();
  const __drawFrom = __();
  const __drawTo = __()
    .__(
      (val) => {
        ctx.beginPath();
        ctx.moveTo(__drawFrom.t.x, __drawFrom.t.y);
        ctx.lineTo(val.x, val.y);
        ctx.closePath();
        ctx.stroke();
        return val;
      }
  );
  canvas.onmousedown = (e) => {
    __mouseDown.t = 1;
    __drawFrom.t = {
      x: e.clientX,
      y: e.clientY
    };
  };
  canvas.onmouseup = (e) => {
    __mouseDown.t = 0;
  };
  canvas.onmousemove = (e) => {
    if (__mouseDown.t === 1) {
      __drawTo.t = {
        x: e.clientX,
        y: e.clientY
      };
      __drawFrom.t = __drawTo.t;

      __.log.t = __drawFrom.t;
    }
  };
}, 1000);
<|endoftext|>


<commit_before>'use strict';
const patternlab = require('@pattern-lab/core');
const _ = require('lodash');

const isValidConfig = require('./validate-config');
const { error, info } = require('./utils');

/**
 * @func serve
 * @desc Start a browser-sync server in the PatternLab public dir
 * @param {object} config - The passed PatternLab config
 */
function serve(config) {
	if (!isValidConfig) {
		throw new TypeError(
			'serve: Expects config not to be empty and of type object.'
		);
	}

	if (
		!_.has(config, 'paths.public.root') ||
		_.isEmpty(config.paths.public.root)
	) {
		throw new TypeError(
			'serve: config.paths.public.root is empty or does not exist. Please check your PatternLab config.'
		);
	}
	if (
		!_.has(config, 'paths.source.root') ||
		_.isEmpty(config.paths.source.root)
	) {
		throw new TypeError(
			'serve: config.paths.source.root is empty or does not exist. Please check your PatternLab config.'
		);
	}

	try {
		info(`serve: Serving your files …`);
		const pl = patternlab(config);
		pl.serve({});
	} catch (err) {
		error(err);
	}
}

module.exports = serve;
<commit_msg>feat(serve): change calling method<commit_after>'use strict';
const patternlab = require('@pattern-lab/core');
const _ = require('lodash');

const isValidConfig = require('./validate-config');
const { error, info } = require('./utils');

/**
 * @func serve
 * @desc Start a browser-sync server in the PatternLab public dir
 * @param {object} config - The passed PatternLab config
 */
function serve(config) {
	if (!isValidConfig) {
		throw new TypeError(
			'serve: Expects config not to be empty and of type object.'
		);
	}

	if (
		!_.has(config, 'paths.public.root') ||
		_.isEmpty(config.paths.public.root)
	) {
		throw new TypeError(
			'serve: config.paths.public.root is empty or does not exist. Please check your PatternLab config.'
		);
	}
	if (
		!_.has(config, 'paths.source.root') ||
		_.isEmpty(config.paths.source.root)
	) {
		throw new TypeError(
			'serve: config.paths.source.root is empty or does not exist. Please check your PatternLab config.'
		);
	}

	try {
		info(`serve: Serving your files …`);
		const pl = patternlab(config);
		pl.server.serve({});
	} catch (err) {
		error(err);
	}
}

module.exports = serve;
<|endoftext|>


<commit_before>//for livereload purposes - dam you dan :D
graph.innerHTML = '';

//graph setup
var margin = {top: 20, right: 50, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format("%d/%m/%y").parse;

var x = d3.time.scale()
    .range([0, width]);

var y0 = d3.scale.linear()
    .range([height, 0]);
var y1 = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxisLeft = d3.svg.axis()
    .scale(y0)
    .orient("left");
var yAxisRight = d3.svg.axis()
    .scale(y1)
    .orient("right");

var line0 = d3.svg.line()
    .x(function(d) { return x(d.Date); })
    .y(function(d) { return y0(d.TWI); })
var line1 = d3.svg.line()
    .x(function(d) { return x(d.Date); })
    .y(function(d) { return y1(d['90Day']); })
var line2 = d3.svg.line()
    .x(function(d) { return x(d.Date); })
    .y(function(d) { return y1(d.OCR); })

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

//csv parsing and graph building
d3.csv("../data/OCR_Test_2014.csv", function(error, data) {

    data.forEach(function(d) {
      d.Date = parseDate(d.Date);
      d['90Day'] = +d['90Day'];
      d.OCR = +d.OCR;
      d.TWI = +d.TWI;
    });

    //domains determine how large the range is for the axis.
    //generally, extracted from the data as min-max (extent)
    //ideally, programatically 'pad' the extent rather than hardcode?
    x.domain(d3.extent(data, function(d) { return d.Date; }));
    // y0.domain(d3.extent(data, function(d) { return d.TWI; }));
    y0.domain([70,85]);
    // y1.domain(d3.extent(data, function(d) { return d['90Day']; }));
    y1.domain([2,5]);

    // console.log(d3.extent(data, function(d) { return d['90Day']; }));

    //draw x axis
    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    //draw both y axes
    svg.append("g")
        .attr("class", "yLeft axis")
        .call(yAxisLeft)
      .append("text");
        // .attr("transform", "rotate(-90)")
        // .attr("y", 6)
        // .attr("dy", ".71em")
        // .style("text-anchor", "end")
        // .text("$b");
    svg.append("g")
        .attr("class", "yRight axis")
        .attr("transform", "translate(" + width + " ,0)")
        .call(yAxisRight)
      .append("text");

    //draw TWI
    svg.append("path")
        .datum(data)
        .attr("class", "line0")
        .transition()
        .ease("linear")
        .duration(1000)
        //SMOOTH ANIMATIONs
        .attrTween("d", function(d){
          var i = d3.scale.linear()
            .domain([0,1])
            .range([1, data.length + 1]);

          return function(t) {
            var flooredX = Math.floor(i(t));
            var interpolatedLine = data.slice(0, flooredX);
            // console.log(interpolatedLine);

            if(flooredX > 0 && flooredX < data.length) {
              var weight = i(t) - flooredX;
              var weightedY = data[flooredX].TWI * weight + data[flooredX-1].TWI * (1-weight);
              var weightedX = data[flooredX].Date * weight + data[flooredX-1].Date * (1-weight);
              // console.log(weightedX, weightedY)
              // console.log(data)
              interpolatedLine.push( {"Date":weightedX, "TWI":weightedY} );
            }

            // console.log(interpolatedLine)

            return line0(interpolatedLine);
          }

        });

    //draw 90Day
    svg.append("path")
        .datum(data)
        .attr("class", "line1")
        .transition()
        .delay(1000)
        .ease("linear")
        .duration(1000)
        //SMOOTH ANIMATIONs
        .attrTween("d", function(d){
          var i = d3.scale.linear()
            .domain([0,1])
            .range([1, data.length + 1]);

          return function(t) {
            var flooredX = Math.floor(i(t));
            var interpolatedLine = data.slice(0, flooredX);
            // console.log(interpolatedLine);

            if(flooredX > 0 && flooredX < data.length) {
              var weight = i(t) - flooredX;
              var weightedY = data[flooredX]['90Day'] * weight + data[flooredX-1]['90Day'] * (1-weight);
              var weightedX = data[flooredX].Date * weight + data[flooredX-1].Date * (1-weight);
              // console.log(weightedX, weightedY)
              // console.log(data)
              interpolatedLine.push( {"Date":weightedX, "90Day":weightedY} );
            }

            // console.log(interpolatedLine)

            return line1(interpolatedLine);
          }

        });

    //draw OCR
    svg.append("path")
        .datum(data)
        .attr("class", "line1")
        .transition()
        .delay(1000)
        .ease("linear")
        .duration(1000)
        //SMOOTH ANIMATIONs
        .attrTween("d", function(d){
          var i = d3.scale.linear()
            .domain([0,1])
            .range([1, data.length + 1]);

          return function(t) {
            var flooredX = Math.floor(i(t));
            var interpolatedLine = data.slice(0, flooredX);
            // console.log(interpolatedLine);

            if(flooredX > 0 && flooredX < data.length) {
              var weight = i(t) - flooredX;
              var weightedY = data[flooredX].OCR * weight + data[flooredX-1].OCR * (1-weight);
              var weightedX = data[flooredX].Date * weight + data[flooredX-1].Date * (1-weight);
              // console.log(weightedX, weightedY)
              // console.log(data)
              interpolatedLine.push( {"Date":weightedX, "OCR":weightedY} );
            }

            // console.log(interpolatedLine)

            return line2(interpolatedLine);
          }

        });
});
<commit_msg>OCR line draws right to left<commit_after>//for livereload purposes - dam you dan :D
graph.innerHTML = '';

//graph setup
var margin = {top: 20, right: 50, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format("%d/%m/%y").parse;

var x = d3.time.scale()
    .range([0, width]);

var y0 = d3.scale.linear()
    .range([height, 0]);
var y1 = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxisLeft = d3.svg.axis()
    .scale(y0)
    .orient("left");
var yAxisRight = d3.svg.axis()
    .scale(y1)
    .orient("right");

var line0 = d3.svg.line()
    .x(function(d) { return x(d.Date); })
    .y(function(d) { return y0(d.TWI); })
var line1 = d3.svg.line()
    .x(function(d) { return x(d.Date); })
    .y(function(d) { return y1(d['90Day']); })
var line2 = d3.svg.line()
    .x(function(d) { return x(d.Date); })
    .y(function(d) { return y1(d.OCR); })

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

//csv parsing and graph building
d3.csv("../data/OCR_Test_2014.csv", function(error, data) {

    data.forEach(function(d) {
      d.Date = parseDate(d.Date);
      d['90Day'] = +d['90Day'];
      d.OCR = +d.OCR;
      d.TWI = +d.TWI;
    });

    //domains determine how large the range is for the axis.
    //generally, extracted from the data as min-max (extent)
    //ideally, programatically 'pad' the extent rather than hardcode?
    x.domain(d3.extent(data, function(d) { return d.Date; }));
    // y0.domain(d3.extent(data, function(d) { return d.TWI; }));
    y0.domain([70,85]);
    // y1.domain(d3.extent(data, function(d) { return d['90Day']; }));
    y1.domain([2,5]);

    // console.log(d3.extent(data, function(d) { return d['90Day']; }));

    //draw x axis
    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    //draw both y axes
    svg.append("g")
        .attr("class", "yLeft axis")
        .call(yAxisLeft)
      .append("text");
        // .attr("transform", "rotate(-90)")
        // .attr("y", 6)
        // .attr("dy", ".71em")
        // .style("text-anchor", "end")
        // .text("$b");
    svg.append("g")
        .attr("class", "yRight axis")
        .attr("transform", "translate(" + width + " ,0)")
        .call(yAxisRight)
      .append("text");

    //draw TWI
    svg.append("path")
        .datum(data)
        .attr("class", "line0")
        .transition()
        .ease("linear")
        .duration(1000)
        //SMOOTH ANIMATIONs
        .attrTween("d", function(d){
          var i = d3.scale.linear()
            .domain([0,1])
            .range([1, data.length + 1]);

          return function(t) {
            var flooredX = Math.floor(i(t));
            var interpolatedLine = data.slice(0, flooredX);
            // console.log(interpolatedLine);

            if(flooredX > 0 && flooredX < data.length) {
              var weight = i(t) - flooredX;
              var weightedY = data[flooredX].TWI * weight + data[flooredX-1].TWI * (1-weight);
              var weightedX = data[flooredX].Date * weight + data[flooredX-1].Date * (1-weight);
              // console.log(weightedX, weightedY)
              // console.log(data)
              interpolatedLine.push( {"Date":weightedX, "TWI":weightedY} );
            }

            // console.log(interpolatedLine)

            return line0(interpolatedLine);
          }

        });

    //draw 90Day
    svg.append("path")
        .datum(data)
        .attr("class", "line1")
        .transition()
        .delay(1000)
        .ease("linear")
        .duration(1000)
        //SMOOTH ANIMATIONs
        .attrTween("d", function(d){
          var i = d3.scale.linear()
            .domain([0,1])
            .range([1, data.length + 1]);

          return function(t) {
            var flooredX = Math.floor(i(t));
            var interpolatedLine = data.slice(0, flooredX);
            // console.log(interpolatedLine);
            // console.log(i(t), flooredX);

            if(flooredX > 0 && flooredX < data.length) {
              var weight = i(t) - flooredX;
              var weightedY = data[flooredX]['90Day'] * weight + data[flooredX-1]['90Day'] * (1-weight);
              var weightedX = data[flooredX].Date * weight + data[flooredX-1].Date * (1-weight);
              // console.log(data[flooredX]['90Day'] * weight, data[flooredX-1]['90Day'] * (1-weight))
              // console.log(data)
              interpolatedLine.push( {"Date":weightedX, "90Day":weightedY} );
            }

            // console.log(interpolatedLine)

            return line1(interpolatedLine);
          }

        });

    //draw OCR
    svg.append("path")
        .datum(data)
        .attr("class", "line1")
        .transition()
        .delay(1000)
        .ease("linear")
        .duration(1000)
        //SMOOTH ANIMATIONs
        .attrTween("d", function(d){
          var i = d3.scale.linear()
            .domain([0,1])
            .range([1, data.length + 1]);

          return function(t) {
            var flooredX = Math.floor(i(t));
            var interpolatedLine = data.slice(-flooredX);
            // console.log(i(t), flooredX);

            if(flooredX > 0 && flooredX < data.length) {
              var weight = i(t) - flooredX;
              var weightedY = data[data.length - flooredX].OCR * weight + data[data.length - flooredX+1].OCR * (1-weight);
              var weightedX = data[data.length - flooredX].Date * weight + data[data.length - flooredX+1].Date * (1-weight);
              // console.log(weightedX, weightedY)
              // console.log(data[data.length - flooredX])
              // console.log(weight)
              interpolatedLine.unshift( {"Date":weightedX, "OCR":weightedY} );
            }

            // console.log(interpolatedLine)

            return line2(interpolatedLine);
          }

        });
});
<|endoftext|>


<commit_before>var passport = require('passport');
var StravaStrategy = require('passport-strava-oauth2').Strategy;

var mongoose = require('mongoose');

var User = mongoose.model('User');
var log = require('loglevel');

var config = require('../config');
var email = require('../utils/email');

module.exports = {

    init: (app) => {

        // http://strava.github.io/api/v3/oauth/

        var STRAVA_CLIENT_ID = config.STRAVA_CLIENT_ID;
        var STRAVA_CLIENT_SECRET = config.STRAVA_CLIENT_SECRET;

        // Use the StravaStrategy within Passport.
        //   Strategies in Passport require a `verify` function, which accept
        //   credentials (in this case, an accessToken, refreshToken, and Strava
        //   profile), and invoke a callback with a user object.
        passport.use(new StravaStrategy({
            clientID: STRAVA_CLIENT_ID,
            clientSecret: STRAVA_CLIENT_SECRET,
            callbackURL: "http://127.0.0.1:9000/auth/strava/callback"
        },
        (accessToken, refreshToken, profile, done) => {
            // asynchronous verification, for effect...
            //process.nextTick(() => {

                // create user if email doesn't exist in database

                var email = profile._json.email;
                var first_name = profile._json.firstname;
                var last_name = profile._json.lastname;
                var apilogin = {strava: profile._json}

                User.findOne({email}, (err, user) => {
                    if (err) {
                        log.error("User search error")
                        log.error(err);
                    } else {

                        if (!user) {
                            // create user if it doesn't exist
                            user = new User({email, first_name, last_name, apilogin});
                            User.create(user, (err,user)=>{
                                email(
                                    `"${first_name} ${last_name}" <${email}>`,
                                    "Welcome to careers.bike!",
                                    "Thanks for registering!\n\nYou can now save jobs or post jobs for free!\n\nhttp://careers.bike/profile/",
                                    "",
                                    (err,info) => {
                                        if (err) {
                                            log.error("Error logging in with strava");
                                            log.error(err);
                                        } else {
                                            log.debug(`email sent succesfully ${info.messageId}`)
                                        }
                                    })
                                return done(null, user);
                            })
                        } else {
                            // if user exists & has never signed on with strava before
                            // add strava profile to apilogin and update user

                            apilogin = user.apilogin || {};

                            if (!apilogin.strava) {
                                apilogin.strava = profile._json;
                                User.update(user, {apilogin}, (err,user) => {
                                    return done(err,user)
                                })
                            } else {

                                return done(null, user);
                            }
                        }
                    }
                })
            //});
        }
        ));

    }
}<commit_msg>fix naming conflict<commit_after>var passport = require('passport');
var StravaStrategy = require('passport-strava-oauth2').Strategy;

var mongoose = require('mongoose');

var User = mongoose.model('User');
var log = require('loglevel');

var config = require('../config');
var sendemail = require('../utils/email');

module.exports = {

    init: (app) => {

        // http://strava.github.io/api/v3/oauth/

        var STRAVA_CLIENT_ID = config.STRAVA_CLIENT_ID;
        var STRAVA_CLIENT_SECRET = config.STRAVA_CLIENT_SECRET;

        // Use the StravaStrategy within Passport.
        //   Strategies in Passport require a `verify` function, which accept
        //   credentials (in this case, an accessToken, refreshToken, and Strava
        //   profile), and invoke a callback with a user object.
        passport.use(new StravaStrategy({
            clientID: STRAVA_CLIENT_ID,
            clientSecret: STRAVA_CLIENT_SECRET,
            callbackURL: "http://127.0.0.1:9000/auth/strava/callback"
        },
        (accessToken, refreshToken, profile, done) => {
            // asynchronous verification, for effect...
            //process.nextTick(() => {

                // create user if email doesn't exist in database

                var email = profile._json.email;
                var first_name = profile._json.firstname;
                var last_name = profile._json.lastname;
                var apilogin = {strava: profile._json}

                User.findOne({email}, (err, user) => {
                    if (err) {
                        log.error("User search error")
                        log.error(err);
                    } else {

                        if (!user) {
                            // create user if it doesn't exist
                            user = new User({email, first_name, last_name, apilogin});
                            User.create(user, (err,user)=>{
                                sendemail(
                                    `"${first_name} ${last_name}" <${email}>`,
                                    "Welcome to careers.bike!",
                                    "Thanks for registering!\n\nYou can now save jobs or post jobs for free!\n\nhttp://careers.bike/profile/",
                                    "",
                                    (err,info) => {
                                        if (err) {
                                            log.error("Error logging in with strava");
                                            log.error(err);
                                        } else {
                                            log.debug(`email sent succesfully ${info.messageId}`)
                                        }
                                    })
                                return done(null, user);
                            })
                        } else {
                            // if user exists & has never signed on with strava before
                            // add strava profile to apilogin and update user

                            apilogin = user.apilogin || {};

                            if (!apilogin.strava) {
                                apilogin.strava = profile._json;
                                User.update(user, {apilogin}, (err,user) => {
                                    return done(err,user)
                                })
                            } else {

                                return done(null, user);
                            }
                        }
                    }
                })
            //});
        }
        ));

    }
}<|endoftext|>


<commit_before>import errorHelper from '../../src/helpers/formErrorHelper';

describe('Symfony Form Error Helper', () => {

  it('handles empty objects', () => {
    expect(errorHelper({}, 'any.path')).toEqual(undefined);
  });

  it('handles object with data but the requested path is not found', () => {
    let errors = {
      children: {}
    };
    expect(errorHelper(errors, 'some.path')).toEqual(undefined);
  });

  it('returns errors if found', () => {
    let errors = {
      children: {
        current_password: {
          errors: [
            "This value is invalid"
          ]
        }
      }
    };
    expect(
      errorHelper(errors, 'children.current_password.errors')
    ).toEqual('This value is invalid');
  });

  it('returns errors if found', () => {
    let errors = {
      children: {
        current_password: {
          errors: [
            "This value is invalid",
            "Some other issue",
            "A third issue"
          ]
        }
      }
    };
    expect(
      errorHelper(errors, 'children.current_password.errors')
    ).toEqual('This value is invalid, Some other issue, and A third issue');
  });

  it('handles very deeply nested errors', () => {
    let errors = {
      children: {
        current_password: {
          errors: [
            "This value is invalid"
          ]
        },
        plainPassword: {
          children: {
            first: {
              errors: [
                "These do not match"
              ]
            },
            second: {}
          }
        }
      }
    };
    expect(
      errorHelper(errors, 'children.plainPassword.children.first.errors')
    ).toEqual('These do not match');
  })

});
<commit_msg>Update formErrorHelpers.react-test.js<commit_after>import errorHelper from '../../src/helpers/formErrorHelper';

describe('Symfony Form Error Helper', () => {

  it('handles empty objects', () => {
    expect(errorHelper({}, 'any.path')).toEqual(undefined);
  });

  it('handles object with data but the requested path is not found', () => {
    let errors = {
      children: {}
    };
    expect(errorHelper(errors, 'some.path')).toEqual(undefined);
  });

  it('returns errors if found', () => {
    let errors = {
      children: {
        current_password: {
          errors: [
            "This value is invalid"
          ]
        }
      }
    };
    expect(
      errorHelper(errors, 'children.current_password.errors')
    ).toEqual('This value is invalid');
  });

  it('returns multiple errors if found', () => {
    let errors = {
      children: {
        current_password: {
          errors: [
            "This value is invalid",
            "Some other issue",
            "A third issue"
          ]
        }
      }
    };
    expect(
      errorHelper(errors, 'children.current_password.errors')
    ).toEqual('This value is invalid, Some other issue, and A third issue');
  });

  it('handles very deeply nested errors', () => {
    let errors = {
      children: {
        current_password: {
          errors: [
            "This value is invalid"
          ]
        },
        plainPassword: {
          children: {
            first: {
              errors: [
                "These do not match"
              ]
            },
            second: {}
          }
        }
      }
    };
    expect(
      errorHelper(errors, 'children.plainPassword.children.first.errors')
    ).toEqual('These do not match');
  })

});
<|endoftext|>