<commit_before>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$(document).ready(function(){
		    $(".toggle-modal").click(function(){
		        $("#myModal").modal('toggle');
		    });
		});

		$scope.submit = function(phone) {
		 	$scope.user.phone = phone;
		 	localStorage.phone = phone;
		 	$scope.update();
		};

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			$scope.userGetPath = '/users/' + localStorage.id;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = data[0];
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = localStorage.phone;

					} else {
						$scope.put();
					}
				});
		};

		$scope.update = function() {
			$scope.userPutPath = '/users/update/' + $scope.user.fbUserId + '/' + $scope.user.email + '/' + $scope.user.phone;// + '/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.loggedIn;

			$http({method: 'POST', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', '$http', function($scope, $http){

		$scope.facilityId = 0;

		$scope.facility = {
			name: "",
			hours: "",
			phone: "",
			image: ""

		}

		/*$scope.initFac = function(){
			$scope.facilityId = sessionStorage.facId;

			for(var i = 0; i < 4; i++)
				var fac = $scope.facilities[i];
				if(fac.id === $scope.facilityId){
					$scope.facility.name = fac.name;
					$scope.facility.hours = fac.hours;
					$scope.facility.phone = fac.phone;
					$scope.facility.image = fac.image;
				}

		};*/

		var fac = $scope;
 		fac.facilities = [];

 		$scope.facilities = [];

 		$scope.get = function() {
			$http({method: 'GET', url: '/facilities/'}).
						success(function(data, status) {
							fac.facilities = data;
						});
						return fac.facilities;
 		};

 		$scope.initGet = function(){
 			$scope.facilities = $scope.get();
 			console.log($scope.facilities);
 		};

 		$scope.setFac = function(){
 			var fac = $scope.getFac();
 			$scope.facility.name = fac.name;
			$scope.facility.hours = fac.hours;
			$scope.facility.phone = fac.phone;
			$scope.facility.image = fac.image;
 		};

		$scope.getFac = function() {
			var path = '/facilities/' + sessionStorage.facId;		// need to fix this; dynamically add facility number
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var facVals = data[0];
						fac.name = facVals.name;
						fac.hours = facVals.hours;
						fac.phone = facVals.phone;
						fac.image = facVals.image;
						return fac;
					}
				});
		};

        $scope.courts = [{name: "test"}];

        $scope.initCourts = function(facId){
            console.log(facId);
            var url = '/courts/fac/'+facId;
            $http({method:'GET',url:url}).
                success(function(data,status){
                    console.log(data);

                for(var x in data){
                    $scope.courts.push(data[x]);

                     $('.courtBox').append(
                     	'
'+
  							'
'+
  								'
'+
	      							''+
	      							'
'+
	        							'
'+
	          								'
'+
	                  							'
'+data[x].name+'
'+
	                    					'
'+
	                    				'
'+
	                    			'
'+
	                    			'
'+
	                    				'
'+
	                                    	'
'+
<<<<<<< HEAD
	                                    		''+
	                  						'
'+
	                  					'
'+
	                  				'
'+
			                  		'
'+
			                  			'
'+
<<<<<<< HEAD
			          						'
Availability
'+
			          						'
Time slots available
'+
			          					'
'+
			          				'
'+
		          				'
'+
		          			'
'+
		          		'
');
                    console.log(data[x].image);
                }
                console.log($scope.courts);
            });
        };

        console.log($scope.courts);

	}]);

	app.controller('CourtController', ['$scope', function($scope){
 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Falcon Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Shark Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Courgar Court',
				image: "../assets/bulldog.png"
			}

		];
	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();
<commit_msg>courts<commit_after>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$(document).ready(function(){
		    $(".toggle-modal").click(function(){
		        $("#myModal").modal('toggle');
		    });
		});

		$scope.submit = function(phone) {
		 	$scope.user.phone = phone;
		 	localStorage.phone = phone;
		 	$scope.update();
		};

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			$scope.userGetPath = '/users/' + localStorage.id;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = data[0];
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = localStorage.phone;

					} else {
						$scope.put();
					}
				});
		};

		$scope.update = function() {
			$scope.userPutPath = '/users/update/' + $scope.user.fbUserId + '/' + $scope.user.email + '/' + $scope.user.phone;// + '/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.loggedIn;

			$http({method: 'POST', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', '$http', function($scope, $http){

		$scope.facilityId = 0;

		$scope.facility = {
			name: "",
			hours: "",
			phone: "",
			image: ""

		}

		/*$scope.initFac = function(){
			$scope.facilityId = sessionStorage.facId;

			for(var i = 0; i < 4; i++)
				var fac = $scope.facilities[i];
				if(fac.id === $scope.facilityId){
					$scope.facility.name = fac.name;
					$scope.facility.hours = fac.hours;
					$scope.facility.phone = fac.phone;
					$scope.facility.image = fac.image;
				}

		};*/

		var fac = $scope;
 		fac.facilities = [];

 		$scope.facilities = [];

 		$scope.get = function() {
			$http({method: 'GET', url: '/facilities/'}).
						success(function(data, status) {
							fac.facilities = data;
						});
						return fac.facilities;
 		};

 		$scope.initGet = function(){
 			$scope.facilities = $scope.get();
 			console.log($scope.facilities);
 		};

 		$scope.setFac = function(){
 			var fac = $scope.getFac();
 			$scope.facility.name = fac.name;
			$scope.facility.hours = fac.hours;
			$scope.facility.phone = fac.phone;
			$scope.facility.image = fac.image;
 		};

		$scope.getFac = function() {
			var path = '/facilities/' + sessionStorage.facId;		// need to fix this; dynamically add facility number
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var facVals = data[0];
						fac.name = facVals.name;
						fac.hours = facVals.hours;
						fac.phone = facVals.phone;
						fac.image = facVals.image;
						return fac;
					}
				});
		};

        $scope.courts = [{name: "test"}];

        $scope.initCourts = function(facId){
            console.log(facId);
            var url = '/courts/fac/'+facId;
            $http({method:'GET',url:url}).
                success(function(data,status){
                    console.log(data);

                for(var x in data){
                    $scope.courts.push(data[x]);

                     $('.courtBox').append(
                     	'
'+
  							'
'+
  								'
'+
	      							''+
	      							'
'+
	        							'
'+
	          								'
'+
	                  							'
'+data[x].name+'
'+
	                    					'
'+
	                    				'
'+
	                    			'
'+
	                    			'
'+
	                    				'
'+
	                                    	'
'+
	                                    		''+
	                  						'
'+
	                  					'
'+
	                  				'
'+
			                  		'
'+
			                  			'
'+
			          						'
Availability
'+
			          						'
Time slots available
'+
			          					'
'+
			          				'
'+
		          				'
'+
		          			'
'+
		          		'
');
                    console.log(data[x].image);
                }
                console.log($scope.courts);
            });
        };

        console.log($scope.courts);

	}]);

	app.controller('CourtController', ['$scope', function($scope){
 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Falcon Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Shark Court',
				image: "../assets/bulldog.png"
			},
			{
				name: 'Courgar Court',
				image: "../assets/bulldog.png"
			}

		];
	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();
<|endoftext|>


<commit_before>//----------------------------------------------------------------------
//
// This source file is part of the furipota project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

module.exports = (furipota) => {
  const { nativeModule, native, nativeThunk, tagged, stream, textToPath, pathToText } = furipota.primitives;
  const fsw = require('../../wrappers/fs');
  const { compact } = require('../../utils');
  const fs = require('fs');
  const Maybe = require('folktale/data/maybe');

  return nativeModule('core:filesystem', {
    find:
    native('find', [['^Path'], {
        'base-directory?': '^Path',
        'silent?': 'Boolean',
        'strict?': 'Boolean',
        'match-directories?': 'Boolean',
        'ignore?': 'Vector',
        'follow-symlinks?': 'Boolean',
        'return-absolute-paths?': 'Boolean'
      }],
      'finds files with a glob pattern',
      (ctx, pattern, options) => {
        return stream(async (producer) => {
          try {
            const cwd = Maybe.fromNullable(options['base-directory']).map(pathToText).getOrElse(process.cwd());
            const files = await fsw.glob(pathToText(pattern), compact({
              cwd,
              silent: options.silent,
              strict: options.strict,
              nodir: !options['match-directories'],
              ignore: Maybe.fromNullable(options.ignore).map(x => x.map(pathToText)).getOrElse(null),
              follow: options['follow-symlinks'],
              absolute: options['return-absolute-paths']
            }));

            for (const file of files) {
              await producer.pushValue(textToPath(file));
            }

            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        });
      }
    ),

    'make-directory':
    native('make-directory', [['^Path'], { 'mode?': 'Number' }],
      'creates a path in a file system',
      (ctx, path, { mode }) => {
        return stream(async (producer) => {
          try {
            const made = await fsw.makeDirectory(pathToText(path), compact({ mode }));
            await producer.pushValue(Boolean(made));
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        })
      }
    ),

    'remove':
    native('remove', [['^Path'], {}],
      'removes a path from the file system',
      (ctx, path, options) => {
        return stream(async (producere) => {
          try {
            await fsw.remove(pathToText(path), { disableGlob: true });
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        })
      }
    ),

    'copy':
    native('copy', [['^Path'], { to: '^Path', 'overwrite?': 'Boolean' }],
      'copies a tree to another destination',
      (ctx, path, { to, overwrite }) => {
        return stream(async (producer) => {
          try {
            await fsw.copy(pathToText(path), pathToText(to), compact({ overwrite }));
            await producer.pushValue({ from: path, to });
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        })
      }
    ),

    'list-directory':
    native('list-directory', [['^Path'], {}],
      'lists the immediate contents of a directory',
      (ctx, path, _options) => {
        return stream(async (producer) => {
          try {
            const files = fsw.listDirectory(pathToText(path));
            await producer.pushValue(files);
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        });
      }
    ),

    'exists':
    native('exists', [['^Path'], {}],
      'checks if a path exists',
      (ctx, path, _options) => {
        return fs.existsSync(pathToText(path));
      }
    ),

    'read':
    native('read', [['^Path'], {
        'encoding?': '^Encoding',
        'mode?': 'Number',
        'start-at-byte?': 'Number',
        'end-at-byte?': 'Number'
      }],
      'reads the contents of a file in chunks',
      (ctx, path, options) => {
        return stream(async (producer) => {
          const data = fs.createReadStream(pathToText(path), compact({
            encoding: Maybe.fromNullable(options.encoding).map(x => x.value._).getOrElse(null),
            mode: options.mode,
            start: options['start-at-byte'],
            end: options['end-at-byte']
          }));

          data.on('close', () => {
            producer.close();
          });

          data.on('data', async (chunk) => {
            data.pause();
            await producer.pushValue(chunk);
            data.resume();
          });

          data.on('end', () => {
            producer.close();
          });

          data.on('error', async (error) => {
            data.pause();
            await producer.pushError(error);
            await producer.close();
          });
        });
      }
    ),

    'write':
    native('write', [['^Path', 'Stream'], {
        'default-encoding?': '^Encoding',
        'mode': 'Number',
        'start-at-byte': 'Number'
      }],
      'Writes data to a path',
      (ctx, path, sourceStream, options) => {
        return stream(async (producer) => {
          const output = fs.createWriteStream(pathToText(path), {
            defaultEncoding: Maybe.fromNullable(options['default-encoding']).map(x => x.value._).getOrElse(null),
            mode: options.mode,
            start: options['start-at-byte']
          });

          const die = async () => {
            output.end();
            await producer.close();
          };

          sourceStream.subscribe({
            Value: async (chunk) => {
              return new Promise((resolve, reject) => {
                if (!output.write(chunk)) {
                  output.once('drain', resolve);
                } else {
                  resolve();
                }
              });
            },

            Error: async (error) => {
              await producer.pushError(error);
              await die();
            },

            Close: async () => {
              await die();
            }
          });

          await sourceStream.run();
        });
      }
    ),

    'symbolic-link':
    native('symbolic-link', [['^Path'], { to: '^Path' }],
      'creates a symbolic link',
      (ctx, from, { to }) => {
        return stream(async (producer) => {
          try {
            await fsw.link(pathToText(to), pathToText(from));
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        });
      }
    ),

    'unlink':
    native('unlink', [['^Path'], {}],
      'removes a symbolic link',
      (ctx, path, _options) => {
        return stream(async (producer) => {
          try {
            await fsw.unlink(pathToText(path));
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        });
      }
    ),

    'Encoding': {
      'utf-8': nativeThunk('utf-8', 'an encoding for multibyte encoded Unicode characters',
        (ctx) => tagged('Encoding', {_: 'utf8'})
      ),

      'ascii': nativeThunk('ascii', 'an encoding for 7-bit ASCII data only',
        (ctx) => tagged('Encoding', {_: 'ascii'})
      ),

      'utf-16-little-endian': nativeThunk('utf-16-little-endian', '2 or 4 bytes, little-endian encoded Unicode characters',
        (ctx) => tagged('Encoding', {_: 'utf16le'})
      ),

      'base64': nativeThunk('base64', 'an encoding in base 64',
        (ctx) => tagged('Encoding', {_: 'base64'})
      ),

      'latin1': nativeThunk('latin1', 'a way of encoding th Buffer into a one-byte encoded string',
        (ctx) => tagged('Encoding', {_: 'latin1'})
      ),

      'hex': nativeThunk('hex', 'encode each byte as two hexadecimal characters',
        (ctx) => tagged('Encoding', {_: 'hex'})
      )
    }
  });
};<commit_msg>Updates snapshot<commit_after>//----------------------------------------------------------------------
//
// This source file is part of the furipota project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

module.exports = (furipota) => {
  const { nativeModule, native, nativeThunk, tagged, stream, textToPath, pathToText } = furipota.primitives;
  const fsw = require('../../wrappers/fs');
  const { compact } = require('../../utils');
  const fs = require('fs');
  const Maybe = require('folktale/data/maybe');

  return nativeModule('core:filesystem', {
    find:
    native('find', [['^Path'], {
        'base-directory?': '^Path',
        'silent?': 'Boolean',
        'strict?': 'Boolean',
        'match-directories?': 'Boolean',
        'ignore?': 'Vector',
        'follow-symlinks?': 'Boolean',
        'return-absolute-paths?': 'Boolean'
      }],
      'finds files with a glob pattern',
      (ctx, pattern, options) => {
        return stream(async (producer) => {
          try {
            const cwd = Maybe.fromNullable(options['base-directory']).map(pathToText).getOrElse(process.cwd());
            const files = await fsw.glob(pathToText(pattern), compact({
              cwd,
              silent: options.silent,
              strict: options.strict,
              nodir: !options['match-directories'],
              ignore: Maybe.fromNullable(options.ignore).map(x => x.map(pathToText)).getOrElse(null),
              follow: options['follow-symlinks'],
              absolute: options['return-absolute-paths']
            }));

            for (const file of files) {
              await producer.pushValue(textToPath(file));
            }

            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        });
      }
    ),

    'make-directory':
    native('make-directory', [['^Path'], { 'mode?': 'Number' }],
      'creates a path in a file system',
      (ctx, path, { mode }) => {
        return stream(async (producer) => {
          try {
            const made = await fsw.makeDirectory(pathToText(path), compact({ mode }));
            await producer.pushValue(Boolean(made));
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        })
      }
    ),

    'remove':
    native('remove', [['^Path'], {}],
      'removes a path from the file system',
      (ctx, path, options) => {
        return stream(async (producer) => {
          try {
            await fsw.remove(pathToText(path), { disableGlob: true });
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        })
      }
    ),

    'copy':
    native('copy', [['^Path'], { to: '^Path', 'overwrite?': 'Boolean' }],
      'copies a tree to another destination',
      (ctx, path, { to, overwrite }) => {
        return stream(async (producer) => {
          try {
            await fsw.copy(pathToText(path), pathToText(to), compact({ overwrite }));
            await producer.pushValue({ from: path, to });
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        })
      }
    ),

    'list-directory':
    native('list-directory', [['^Path'], {}],
      'lists the immediate contents of a directory',
      (ctx, path, _options) => {
        return stream(async (producer) => {
          try {
            const files = fsw.listDirectory(pathToText(path));
            await producer.pushValue(files);
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        });
      }
    ),

    'exists':
    native('exists', [['^Path'], {}],
      'checks if a path exists',
      (ctx, path, _options) => {
        return fs.existsSync(pathToText(path));
      }
    ),

    'read':
    native('read', [['^Path'], {
        'encoding?': '^Encoding',
        'mode?': 'Number',
        'start-at-byte?': 'Number',
        'end-at-byte?': 'Number'
      }],
      'reads the contents of a file in chunks',
      (ctx, path, options) => {
        return stream(async (producer) => {
          const data = fs.createReadStream(pathToText(path), compact({
            encoding: Maybe.fromNullable(options.encoding).map(x => x.value._).getOrElse(null),
            mode: options.mode,
            start: options['start-at-byte'],
            end: options['end-at-byte']
          }));

          data.on('close', () => {
            producer.close();
          });

          data.on('data', async (chunk) => {
            data.pause();
            await producer.pushValue(chunk);
            data.resume();
          });

          data.on('end', () => {
            producer.close();
          });

          data.on('error', async (error) => {
            data.pause();
            await producer.pushError(error);
            await producer.close();
          });
        });
      }
    ),

    'write':
    native('write', [['^Path', 'Stream'], {
        'default-encoding?': '^Encoding',
        'mode': 'Number',
        'start-at-byte': 'Number'
      }],
      'Writes data to a path',
      (ctx, path, sourceStream, options) => {
        return stream(async (producer) => {
          const output = fs.createWriteStream(pathToText(path), {
            defaultEncoding: Maybe.fromNullable(options['default-encoding']).map(x => x.value._).getOrElse(null),
            mode: options.mode,
            start: options['start-at-byte']
          });

          const die = async () => {
            output.end();
            await producer.close();
          };

          sourceStream.subscribe({
            Value: async (chunk) => {
              return new Promise((resolve, reject) => {
                if (!output.write(chunk)) {
                  output.once('drain', resolve);
                } else {
                  resolve();
                }
              });
            },

            Error: async (error) => {
              await producer.pushError(error);
              await die();
            },

            Close: async () => {
              await die();
            }
          });

          await sourceStream.run();
        });
      }
    ),

    'symbolic-link':
    native('symbolic-link', [['^Path'], { to: '^Path' }],
      'creates a symbolic link',
      (ctx, from, { to }) => {
        return stream(async (producer) => {
          try {
            await fsw.link(pathToText(to), pathToText(from));
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        });
      }
    ),

    'unlink':
    native('unlink', [['^Path'], {}],
      'removes a symbolic link',
      (ctx, path, _options) => {
        return stream(async (producer) => {
          try {
            await fsw.unlink(pathToText(path));
            await producer.close();
          } catch (error) {
            await producer.pushError(error);
            await producer.close();
          }
        });
      }
    ),

    'Encoding': {
      'utf-8': nativeThunk('utf-8', 'an encoding for multibyte encoded Unicode characters',
        (ctx) => tagged('Encoding', {_: 'utf8'})
      ),

      'ascii': nativeThunk('ascii', 'an encoding for 7-bit ASCII data only',
        (ctx) => tagged('Encoding', {_: 'ascii'})
      ),

      'utf-16-little-endian': nativeThunk('utf-16-little-endian', '2 or 4 bytes, little-endian encoded Unicode characters',
        (ctx) => tagged('Encoding', {_: 'utf16le'})
      ),

      'base64': nativeThunk('base64', 'an encoding in base 64',
        (ctx) => tagged('Encoding', {_: 'base64'})
      ),

      'latin1': nativeThunk('latin1', 'a way of encoding th Buffer into a one-byte encoded string',
        (ctx) => tagged('Encoding', {_: 'latin1'})
      ),

      'hex': nativeThunk('hex', 'encode each byte as two hexadecimal characters',
        (ctx) => tagged('Encoding', {_: 'hex'})
      )
    }
  });
};<|endoftext|>


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

  angular.module('app', ['ngRoute', 'appControllers', 'appFilters']).
    config(['$routeProvider', function ($routeProvider) {
      $routeProvider.
      when('/blocks', {
        templateUrl: 'partials/blocks.html',
        controller: 'BlocksController'
      }).
      when('/blocks/:blockID', {
        templateUrl: 'partials/block.html',
        controller: 'BlockController'
      }).
      otherwise({
        redirectTo: '/blocks'
      });
    }]).

    directive('badge', [function () {
      return {
        restrict: 'A',
        // template: '<canvas></canvas>',
        link: function (scope, element, attrs) {
          var canvas = element[0];
          var ctx = canvas.getContext('2d');

          // hidpi handling
          var devicePixelRatio = window.devicePixelRatio || 1;
          var backingStoreRatio = ctx.backingStorePixelRatio ||
            ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio || 1;
          if (devicePixelRatio !== backingStoreRatio) {
            var pixelRatio = devicePixelRatio / backingStoreRatio;

            canvas.style.width = '' + canvas.width + 'px';
            canvas.style.height = '' + canvas.height + 'px';

            canvas.width = canvas.width * pixelRatio;
            canvas.height = canvas.height * pixelRatio;
            ctx.scale(pixelRatio, pixelRatio);
          }

          var drawFallback = function () {
            var img = new Image();
            img.onerror = function () {
              ctx.fillStyle = 'rgb(255, 0, 0)';
              ctx.fillRect(0, 0, attrs.width, attrs.height);
            };
            img.onload = function () {
              ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, attrs.width, attrs.height);
              ctx.globalCompositeOperation = 'multiply';
              var colors = ['rgb(255, 255, 0)', 'rgb(255, 0, 255)', 'rgb(0, 255, 255)'];
              ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
              ctx.fillRect(0, 0, attrs.width, attrs.height);
            };
            img.src = 'img/block.png';
          };

          if (!attrs.imageUrl) {
            drawFallback();
          } else {
            var img = new Image();
            img.onerror = function () {
              drawFallback();
            };
            img.onload = function () {
              // aspect fill and center
              var x = 0, y = 0, w = img.width, h = img.height;
              var aspectRatio = (img.width / img.height) / (attrs.width / attrs.height);
              if (aspectRatio > 1) {
                w /= aspectRatio;
                x = (img.width - w) / 2;
              } else if (aspectRatio < 1) {
                h *= aspectRatio;
                y = (img.height - h) / 2;
              }
              ctx.drawImage(img, x, y, w, h, 0, 0, attrs.width, attrs.height);
            };
            img.src = attrs.imageUrl;
          }
        }
      };
    }]);

})();
<commit_msg>disable the block route for now<commit_after>(function() {
  'use strict';

  angular.module('app', ['ngRoute', 'appControllers', 'appFilters']).
    config(['$routeProvider', function ($routeProvider) {
      $routeProvider.
      when('/blocks', {
        templateUrl: 'partials/blocks.html',
        controller: 'BlocksController'
      }).
      // when('/blocks/:blockID', {
      //   templateUrl: 'partials/block.html',
      //   controller: 'BlockController'
      // }).
      otherwise({
        redirectTo: '/blocks'
      });
    }]).

    directive('badge', [function () {
      return {
        restrict: 'A',
        // template: '<canvas></canvas>',
        link: function (scope, element, attrs) {
          var canvas = element[0];
          var ctx = canvas.getContext('2d');

          // hidpi handling
          var devicePixelRatio = window.devicePixelRatio || 1;
          var backingStoreRatio = ctx.backingStorePixelRatio ||
            ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio || 1;
          if (devicePixelRatio !== backingStoreRatio) {
            var pixelRatio = devicePixelRatio / backingStoreRatio;

            canvas.style.width = '' + canvas.width + 'px';
            canvas.style.height = '' + canvas.height + 'px';

            canvas.width = canvas.width * pixelRatio;
            canvas.height = canvas.height * pixelRatio;
            ctx.scale(pixelRatio, pixelRatio);
          }

          var drawFallback = function () {
            var img = new Image();
            img.onerror = function () {
              ctx.fillStyle = 'rgb(255, 0, 0)';
              ctx.fillRect(0, 0, attrs.width, attrs.height);
            };
            img.onload = function () {
              ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, attrs.width, attrs.height);
              ctx.globalCompositeOperation = 'multiply';
              var colors = ['rgb(255, 255, 0)', 'rgb(255, 0, 255)', 'rgb(0, 255, 255)'];
              ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
              ctx.fillRect(0, 0, attrs.width, attrs.height);
            };
            img.src = 'img/block.png';
          };

          if (!attrs.imageUrl) {
            drawFallback();
          } else {
            var img = new Image();
            img.onerror = function () {
              drawFallback();
            };
            img.onload = function () {
              // aspect fill and center
              var x = 0, y = 0, w = img.width, h = img.height;
              var aspectRatio = (img.width / img.height) / (attrs.width / attrs.height);
              if (aspectRatio > 1) {
                w /= aspectRatio;
                x = (img.width - w) / 2;
              } else if (aspectRatio < 1) {
                h *= aspectRatio;
                y = (img.height - h) / 2;
              }
              ctx.drawImage(img, x, y, w, h, 0, 0, attrs.width, attrs.height);
            };
            img.src = attrs.imageUrl;
          }
        }
      };
    }]);

})();
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs'),
    util = require('util'),
    readline = require('readline');

var opts = require('commander');

opts.version('0.0.1')
    .option('-f, --file [value]', 'File to parse')
    .option('-l, --line [value]', 'Examine file at line number.  Prints fields and values vertically and other stats.')
    .option('-d, --debug', 'Debug mode, writing problematic rows to stdout')
    .option('-i, --insert-at-column [value]', 'Insert after the specified column for problematic rows')
    .option('-value, --insert-value [value]', 'Value to insert at line of "--insert-at"')
    .option('-h, --fix-header [value]', 'Write file with recommended header')
    .option('-s, --split [value]', 'Split file into smaller files ingnoring ')
    .parse(process.argv);

if (!opts.file) {
    console.error('Must supply a file using --file (-f) option');
    return;
}

if (opts.debug && opts.insert) {
    console.error('Can specify both debug and insert-tab mode');
    return;
}

if ( (opts.insertAtColumn && !opts.insertValue) ||
    (!opts.insertAtColumn && opts.insertValue) ) {
    console.error('Must specify both "insert-value" and "insert-at-column"');
    return;
}

console.error('\n\x1b[36m'+'parsing file:'+'\x1b[0m', opts.file)

// if header option is give, fix header and quit
if (opts.fixHeader) {
    var lineNumber = 0;
    var header;

    var rl = readline.createInterface({
        terminal: false,
        input: fs.createReadStream(opts.file)
    });

    rl.on('line', function (line) {
        if (lineNumber === 0) {
            header = line.split('\t');

            // use default suggested header if none supplied
            if (opts.fixHeader === true)
                var suggestedHeader = getSuggestedHeader(header);
            else
                var suggestedHeader = opts.fixHeader.split(',')

            // write new header
            console.log(suggestedHeader.join('\t'))
        } else {
            // write file stream line
            console.log(line)
        }

        lineNumber += 1;
    });

    rl.on('close', function (line) {
        console.error('\n\x1b[36m'+'Replaced header with:'+'\x1b[0m', suggestedHeader.join('\t'));
    });

} else if (opts.split) {
    console.error('\n\x1b[36m'+'Spliting file into rows of:'+'\x1b[0m', opts.split);

    var lineNumber = 0;
    var header;

    var rl = readline.createInterface({
        terminal: false,
        input: fs.createReadStream(opts.file)
    });

    rl.on('line', function (line) {
        if (lineNumber === 0) {
            header = line.split('\t');

            // use default suggested header if a comma-separated list is not supplied
            // otherwise, use list
            if (opts.fixHeader && opts.fixHeader === true)
                var suggestedHeader = getSuggestedHeader(header);
            else if (opts.fixHeader)
                var suggestedHeader = opts.fixHeader.split(',');
            else
                var suggestedHeader = line.split('\t');

            // write new header
            console.log(suggestedHeader.join('\t'))
        } else {
            // write file stream line
            console.log(line)
        }

        if (lineNumber > opts.split - 1) {
            console.error('****Stoping at line', lineNumber);
            rl.pause(); rl.close()
            process.exit(0);
        }
        lineNumber += 1;
    });

    rl.on('close', function (line) {
        console.error('\n\x1b[36m'+'Split files.'+'\x1b[0m');
    });
} else {
    var lineNumber = 0;
    var header;

    var rl = readline.createInterface({
        terminal: false,
        input: fs.createReadStream(opts.file)
    });

    rl.on('line', function (line) {

        // print info on header
        if (lineNumber === 0) {
            header = line.split('\t');
            suggestedHeader = getSuggestedHeader(header);

            if (!opts.debug && !opts.insertValue) {
                console.log('\n\x1b[36m'+'column count:'+'\x1b[0m', header.length)
                console.log('\n\x1b[36m'+'Raw column names:'+'\x1b[0m',header.join(','))
                console.log('\n\x1b[36m'+'Suggested column names:'+'\x1b[0m', suggestedHeader.join(','))
                console.log('\n\x1b[36m'+'Suggested header:'+'\x1b[0m', suggestedHeader.join('\t'), '\n')
            }
        }

        // if line is supplied, only print info on that line
        if (opts.line && opts.line == lineNumber) {
            var cols = line.split('\t');

            for (var i=0; i<cols.length; i++) {
                console.log(util.format('%s:     %s', header[i], cols[i] ))
            }
            rl.pause();
            rl.close()
            process.exit(0);
        }

        // if --debug, print any issues with columns to stdout
        if (opts.debug) {
            var cols = line.split('\t');

            if (cols.length !== header.length)
                console.log('\x1b[36m'+'At line:', lineNumber, ': unmatching columns of length',
                              cols.length, 'and', header.length,'\x1b[0m:', line);
        }

        // if inserting something print issues to stdout,
        if (opts.insertValue) {
            var cols = line.split('\t');

            if (cols.length !== header.length) {
                console.error('At line:', lineNumber, ': unmatching columns of length',
                              cols.length, 'and', header.length, '\x1b[36m(fixed)\x1b[0m')

                cols.splice(opts.insertAtColumn, 0, opts.insertValue);
                console.error('new column:', cols.join('\t'))
                console.log( cols.join('\t') );
            } else {
                console.log( line );
            }
        }

        lineNumber += 1;
    });
}

// Default for suggested header.
// --fix-header will use this if a comma-delimited list is not provided.
function getSuggestedHeader(header) {
    var suggestedHeader = [];
    for (var i=0; i<header.length; i++) {
        suggestedHeader.push( header[i].toLowerCase().replace(/ /g, '_') )
    }
    return suggestedHeader;
}
<commit_msg>revert helper script<commit_after>#!/usr/bin/env node

var fs = require('fs'),
    util = require('util'),
    readline = require('readline');

var opts = require('commander');

opts.version('0.0.1')
    .option('-f, --file [value]', 'File to parse')
    .option('-l, --line [value]', 'Line number to examine')
    .option('-d, --debug', 'Debug mode, writing problematic rows to stdout')
    .option('-i, --insert-at-column [value]', 'Insert after the specified column for problematic rows')
    .option('-value, --insert-value [value]', 'Value to insert at line of "--insert-at"')
    .option('-h, --fix-header [value]', 'Write file with recommended header')
    .parse(process.argv);

if (!opts.file) {
    console.error('Must supply a file using --file (-f) option');
    return;
}

if (opts.debug && opts.insert) {
    console.error('Can specify both debug and insert-tab mode');
    return;
}

if ( (opts.insertAtColumn && !opts.insertValue) ||
    (!opts.insertAtColumn && opts.insertValue) ) {
    console.error('Must specify both "insert-value" and "insert-at-column"');
    return;
}

console.error('\n\x1b[36m'+'parsing file:'+'\x1b[0m', opts.file)

// if header option is give, fix header and quit
if (opts.fixHeader) {
    var lineNumber = 0;
    var header;

    var rl = readline.createInterface({
        terminal: false,
        input: fs.createReadStream(opts.file)
    });

    rl.on('line', function (line) {
        if (lineNumber === 0) {
            header = line.split('\t');

            // use default suggested header if none supplied
            if (opts.fixHeader === true)
                suggestedHeader = getSuggestedHeader(header);
            else
                suggestedHeader = opts.fixHeader.split(',')

            // write new header
            console.log(suggestedHeader.join('\t'))
        } else {
            // write file stream line
            console.log(line)
        }

        lineNumber += 1;
    });

    rl.on('close', function (line) {
        console.error('\n\x1b[36m'+'Replaced header with:'+'\x1b[0m', suggestedHeader.join('\t'));
    });

} else {
    var lineNumber = 0;
    var header;

    var rl = readline.createInterface({
        terminal: false,
        input: fs.createReadStream(opts.file)
    });

    rl.on('line', function (line) {

        // print info on header
        if (lineNumber === 0) {
            header = line.split('\t');
            suggestedHeader = getSuggestedHeader(header);

            if (!opts.debug && !opts.insertValue) {
                console.log('\n\x1b[36m'+'column count:'+'\x1b[0m', header.length)
                console.log('\n\x1b[36m'+'Raw column names:'+'\x1b[0m',header.join(','))
                console.log('\n\x1b[36m'+'Suggested column names:'+'\x1b[0m', suggestedHeader.join(','))
                console.log('\n\x1b[36m'+'Suggested header:'+'\x1b[0m', suggestedHeader.join('\t'), '\n')
            }
        }

        // if line is supplied, only print info on that line
        if (opts.line && opts.line == lineNumber) {
            var cols = line.split('\t');

            for (var i=0; i<cols.length; i++) {
                console.log(util.format('%s:     %s', header[i], cols[i] ))
            }
            rl.pause();
            rl.close()
            process.exit(0);
        }

        // if --debug, print any issues with columns to stdout
        if (opts.debug) {
            var cols = line.split('\t');

            if (cols.length !== header.length)
                console.log('\x1b[36m'+'At line:', lineNumber, ': unmatching columns of length',
                              cols.length, 'and', header.length,'\x1b[0m:', line);
        }

        // if inserting something print issues to stdout,
        if (opts.insertValue) {
            var cols = line.split('\t');

            if (cols.length !== header.length) {
                console.error('At line:', lineNumber, ': unmatching columns of length',
                              cols.length, 'and', header.length, '\x1b[36m(fixed)\x1b[0m')

                cols.splice(opts.insertAtColumn, 0, opts.insertValue);
                console.error('new column:', cols.join('\t'))
                console.log( cols.join('\t') );
            } else {
                console.log( line );
            }
        }

        lineNumber += 1;
    });
}

// Default for suggested header.
// --fix-header will use this if a comma-delimited list is not provided.
function getSuggestedHeader(header) {
    var suggestedHeader = [];
    for (var i=0; i<header.length; i++) {
        suggestedHeader.push( header[i].toLowerCase().replace(/ /g, '_') )
    }
    return suggestedHeader;
}
<|endoftext|>


<commit_before>var searchApp = angular.module('searchApp');

searchApp

	.controller('searchController', function ($scope, $http, pagination, $location, $sce) {

		$scope.search = {
			words: '',
			phrase: '',
			anyWords:'',
			without:'',
			fuzzy: false,
			rank: false,
			startRecord:'1',
			recordCount: '10'
		};

		var index = - 1;
		var prevNextCheck = 0;
		var baseUrl = '/csp/docsearch/rest/';
		var check = '';

		$scope.sce = $sce;
		$scope.mylocation = location.host;
		$scope.inputToggle = false;
		$scope.resultToggle = true;
		$scope.preloadToggle = false;
		$scope.prevToggle = false;
		$scope.nextToggle = false;
		$scope.checkToggle = false;
		$scope.title = "DocSearch";
		$scope.phraseShow = false;
		$scope.anyWordsShow = false;
		$scope.withoutShow = false;
		$scope.errorToggle = false;

		$scope.phraseClear = function() {
			$scope.search.phrase = "";
			$scope.makeSearch();
		}

		$scope.anyWordsClear = function() {
			$scope.search.anyWords = "";
			$scope.makeSearch();
		}

		$scope.withoutClear = function() {
			$scope.search.without = "";
			$scope.makeSearch();
		}

		$scope.clearAll = function() {
			$scope.search.words = "";
			$scope.search.phrase = "";
			$scope.search.anyWords = "";
			$scope.search.without = "";
		}

		$scope.change = function () {

			if ($scope.search.words != "")
			{
				$http.get(baseUrl + 'GetSimilar/' + $scope.search.words)
					.then(function(response) {
						$scope.searchItems = response.data.entities;
				});
				$scope.inputToggle = false;
			}

			if(angular.isDefined($scope.searchItems)){
				if (($scope.searchItems[0].value == " ") || ($scope.search.words == ""))
					$scope.inputToggle = false;
				else
					$scope.inputToggle = true;
			}
		}

		$scope.handleClick = function (item) {

			$scope.currrentSearchItem = item;
			$scope.search.words = $scope.currrentSearchItem.value;
			$scope.makeSearch();

			$scope.inputToggle = false;
		}

		$scope.handleArrows = function (event) {

			if(event.keyCode  === 40) // up
				index += 1;
			if(event.keyCode  === 38) // down
				index -= 1;

			if (index < 0)
				index = 9;
			if (index > 9)
				index = 0;
			if 	((event.keyCode === 40) || (event.keyCode === 38))
			{
				$scope.search.words = $scope.searchItems[index].value;
				$scope.currrentSearchItem = $scope.searchItems[index];
			}

			if (event.keyCode === 13)
					$scope.inputToggle = false;
		}

		$scope.makeSearch = function () {
			$scope.inputToggle = false;
			$scope.errorToggle = false;

			$scope.search.phrase == '' ? $scope.phraseShow = false : $scope.phraseShow = true;
			$scope.search.anyWords == '' ? $scope.anyWordsShow = false : $scope.anyWordsShow = true;
			$scope.search.without == '' ? $scope.withoutShow = false : $scope.withoutShow = true;

			$scope.title = $scope.search.words;

			if ($scope.search.words != '' || $scope.search.phrase != '' || $scope.search.anyWords != '')
			{
				$scope.showPage(0);
				$location.path("/DocResults");

			}
			else
				if ( $scope.search.without != '')
					$scope.errorToggle = true;
				else
					if ( $scope.search.without == '')
						$location.path("/DocSearch");
		}

		$scope.showPage = function (page) {

			$scope.resultToggle = true;

			$scope.currentPage = page;

			if(check != $scope.search.words)
			{
				$scope.checkToggle = true;
				check = $scope.search.words;
			}
			else
				$scope.checkToggle = false;

			$scope.preloadToggle = true;

			if(!isNaN(page))
					prevNextCheck = page;

			if (page == 'prev') {
					$scope.results = pagination.getPrevPageProducts();
					prevNextCheck -= 1;
					if (prevNextCheck < 0)
						prevNextCheck = 0;
			} else if (page == 'next') {
					$scope.results = pagination.getNextPageProducts($scope.totalCount, $scope.search.recordCount);
					prevNextCheck += 1;
					if (prevNextCheck > $scope.pagesNum - 1)
						prevNextCheck = $scope.pagesNum;
			} else {
				$scope.results = pagination.getPageProducts(page);
			}

			$scope.search.startRecord = (pagination.getCurrentPageNum()) * $scope.search.recordCount + 1;

			$http.post(baseUrl + 'Search', $scope.search)
				.then(function(response) {
					$scope.results = response.data.sources;

					$scope.totalCount = response.data.totalCount[0].total;

					if ($scope.totalCount != 0)
					{	$scope.resultToggle = true;
						$scope.pagesNum = pagination.getTotalPagesNum($scope.totalCount, $scope.search.recordCount);
						$scope.paginationList = pagination.getPaginationList($scope.currentPage, $scope.pagesNum, $scope.checkToggle);

						if (prevNextCheck != $scope.pagesNum - 1)
							$scope.nextToggle = true;
						else
							$scope.nextToggle = false;

						if ($scope.pagesNum == undefined)
							$scope.nextToggle = false;
					}
					else
						$scope.resultToggle = false;

					$scope.preloadToggle = false;
			});

			if (prevNextCheck != 0)
				$scope.prevToggle = true;
			else
				$scope.prevToggle = false;
		}

		$scope.currentPageNum = function() {

				return pagination.getCurrentPageNum();
		}

	})/* END of controller - searchController */<commit_msg>Инжект кнопки<commit_after>var searchApp = angular.module('searchApp');

searchApp

	.controller('searchController', function ($scope, $http, pagination, $location, $sce) {

		$scope.search = {
			words: '',
			phrase: '',
			anyWords:'',
			without:'',
			fuzzy: false,
			rank: false,
			startRecord:'1',
			recordCount: '10'
		};

		var index = - 1;
		var prevNextCheck = 0;
		var baseUrl = '/csp/docsearch/rest/';
		var check = '';
		var input = location.hash;

		$scope.sce = $sce;
		$scope.mylocation = location.host;
		$scope.inputToggle = false;
		$scope.resultToggle = true;
		$scope.preloadToggle = false;
		$scope.prevToggle = false;
		$scope.nextToggle = false;
		$scope.checkToggle = false;
		$scope.title = "DocSearch";
		$scope.phraseShow = false;
		$scope.anyWordsShow = false;
		$scope.withoutShow = false;
		$scope.errorToggle = false;

		angular.element(document).ready(function(){
			if ( (input != "#!/DocSearch") || (input != "#!/DocResults") || (input != "#!/SearchAdvance"))
			{
				var linkStr = input.split('#');
				$scope.search.words = linkStr[2];
				$scope.makeSearch();
			}
		});

		$scope.phraseClear = function() {
			$scope.search.phrase = "";
			$scope.makeSearch();
		}

		$scope.anyWordsClear = function() {
			$scope.search.anyWords = "";
			$scope.makeSearch();
		}

		$scope.withoutClear = function() {
			$scope.search.without = "";
			$scope.makeSearch();
		}

		$scope.clearAll = function() {
			$scope.search.words = "";
			$scope.search.phrase = "";
			$scope.search.anyWords = "";
			$scope.search.without = "";
		}

		$scope.change = function () {

			if ($scope.search.words != "")
			{
				$http.get(baseUrl + 'GetSimilar/' + $scope.search.words)
					.then(function(response) {
						$scope.searchItems = response.data.entities;
				});
				$scope.inputToggle = false;
			}

			if(angular.isDefined($scope.searchItems)){
				if (($scope.searchItems[0].value == " ") || ($scope.search.words == ""))
					$scope.inputToggle = false;
				else
					$scope.inputToggle = true;
			}
		}

		$scope.handleClick = function (item) {

			$scope.currrentSearchItem = item;
			$scope.search.words = $scope.currrentSearchItem.value;
			$scope.makeSearch();

			$scope.inputToggle = false;
		}

		$scope.handleArrows = function (event) {

			if(event.keyCode  === 40) // up
				index += 1;
			if(event.keyCode  === 38) // down
				index -= 1;

			if (index < 0)
				index = 9;
			if (index > 9)
				index = 0;
			if 	((event.keyCode === 40) || (event.keyCode === 38))
			{
				$scope.search.words = $scope.searchItems[index].value;
				$scope.currrentSearchItem = $scope.searchItems[index];
			}

			if (event.keyCode === 13)
					$scope.inputToggle = false;
		}

		$scope.makeSearch = function () {
			$scope.inputToggle = false;
			$scope.errorToggle = false;

			$scope.search.phrase == '' ? $scope.phraseShow = false : $scope.phraseShow = true;
			$scope.search.anyWords == '' ? $scope.anyWordsShow = false : $scope.anyWordsShow = true;
			$scope.search.without == '' ? $scope.withoutShow = false : $scope.withoutShow = true;

			$scope.title = $scope.search.words;

			if ($scope.search.words != '' || $scope.search.phrase != '' || $scope.search.anyWords != '')
			{
				$scope.showPage(0);
				$location.path("/DocResults");

			}
			else
				if ( $scope.search.without != '')
					$scope.errorToggle = true;
				else
					if ( $scope.search.without == '')
						$location.path("/DocSearch");
		}

		$scope.showPage = function (page) {

			$scope.resultToggle = true;

			$scope.currentPage = page;

			if(check != $scope.search.words)
			{
				$scope.checkToggle = true;
				check = $scope.search.words;
			}
			else
				$scope.checkToggle = false;

			$scope.preloadToggle = true;

			if(!isNaN(page))
					prevNextCheck = page;

			if (page == 'prev') {
					$scope.results = pagination.getPrevPageProducts();
					prevNextCheck -= 1;
					if (prevNextCheck < 0)
						prevNextCheck = 0;
			} else if (page == 'next') {
					$scope.results = pagination.getNextPageProducts($scope.totalCount, $scope.search.recordCount);
					prevNextCheck += 1;
					if (prevNextCheck > $scope.pagesNum - 1)
						prevNextCheck = $scope.pagesNum;
			} else {
				$scope.results = pagination.getPageProducts(page);
			}

			$scope.search.startRecord = (pagination.getCurrentPageNum()) * $scope.search.recordCount + 1;

			$http.post(baseUrl + 'Search', $scope.search)
				.then(function(response) {
					$scope.results = response.data.sources;

					$scope.totalCount = response.data.totalCount[0].total;

					if ($scope.totalCount != 0)
					{	$scope.resultToggle = true;
						$scope.pagesNum = pagination.getTotalPagesNum($scope.totalCount, $scope.search.recordCount);
						$scope.paginationList = pagination.getPaginationList($scope.currentPage, $scope.pagesNum, $scope.checkToggle);

						if (prevNextCheck != $scope.pagesNum - 1)
							$scope.nextToggle = true;
						else
							$scope.nextToggle = false;

						if ($scope.pagesNum == undefined)
							$scope.nextToggle = false;
					}
					else
						$scope.resultToggle = false;

					$scope.preloadToggle = false;
			});

			if (prevNextCheck != 0)
				$scope.prevToggle = true;
			else
				$scope.prevToggle = false;
		}

		$scope.currentPageNum = function() {

				return pagination.getCurrentPageNum();
		}

	})/* END of controller - searchController */<|endoftext|>


<commit_before>const compileTemplateExpression = function(expression, exclude, dependencies) {
  let props = dependencies.props;
  let methods = dependencies.methods;
  let dynamic = false;
  let info;

  while((info = expressionRE.exec(expression)) !== null) {
    let match = info[0];
    let name = info[1];
    if(name !== undefined && exclude.indexOf(name) === -1) {
      if(match[match.length - 1] === "(") {
        if(methods.indexOf(name) === -1) {
          methods.push(name);
        }
      } else if(props.indexOf(name) === -1) {
        props.push(name);
        dynamic = true;
      }
    }
  }

  return dynamic;
}

const compileTemplate = function(template, exclude, dependencies) {
  const length = template.length;
  let current = 0;
  let dynamic = false;
  let output = '';

  while(current < length) {
    // Match text
    const textTail = template.substring(current);
    const textMatch = textTail.match(openRE);

    if(textMatch === null) {
      output += `"${textTail}"`;
      break;
    } else {
      const textIndex = textMatch.index;
      if(textIndex !== 0) {
        output += `"${textTail.substring(0, textIndex)}"`;
        current += textIndex;
      }

      dynamic = true;
    }

    // Concatenate if not at the start
    if(current !== 0) {
      output += concatenationSymbol;
    }

    // Exit opening delimiter
    current += textMatch[0].length;

    // Get expression, and exit closing delimiter
    const expressionTail = template.substring(current);
    const expressionMatch = expressionTail.match(closeRE);

    if("__ENV__" !== "production" && expressionMatch === null) {
      error(`Expected closing delimiter after "${expressionTail}"`);
    } else {
      const expressionIndex = expressionMatch.index;
      const expression = expressionTail.substring(0, expressionIndex);
      compileTemplateExpression(expression, exclude, dependencies);
      output += `(${expression})`;
      current += expression.length + expressionMatch[0].length;

      // Concatenate if not at the end
      if(current !== length) {
        output += concatenationSymbol;
      }
    }
  }

  return {
    output: output,
    dynamic: dynamic
  };
}
<commit_msg>fix: allow empty attributes (closes #157)<commit_after>const compileTemplateExpression = function(expression, exclude, dependencies) {
  let props = dependencies.props;
  let methods = dependencies.methods;
  let dynamic = false;
  let info;

  while((info = expressionRE.exec(expression)) !== null) {
    let match = info[0];
    let name = info[1];
    if(name !== undefined && exclude.indexOf(name) === -1) {
      if(match[match.length - 1] === "(") {
        if(methods.indexOf(name) === -1) {
          methods.push(name);
        }
      } else if(props.indexOf(name) === -1) {
        props.push(name);
        dynamic = true;
      }
    }
  }

  return dynamic;
}

const compileTemplate = function(template, exclude, dependencies) {
  const length = template.length;
  let current = 0;
  let dynamic = false;
  let output = '';

  if(length === 0) {
    output = "\"\"";
  } else {
    while(current < length) {
      // Match text
      const textTail = template.substring(current);
      const textMatch = textTail.match(openRE);

      if(textMatch === null) {
        output += `"${textTail}"`;
        break;
      } else {
        const textIndex = textMatch.index;
        if(textIndex !== 0) {
          output += `"${textTail.substring(0, textIndex)}"`;
          current += textIndex;
        }

        dynamic = true;
      }

      // Concatenate if not at the start
      if(current !== 0) {
        output += concatenationSymbol;
      }

      // Exit opening delimiter
      current += textMatch[0].length;

      // Get expression, and exit closing delimiter
      const expressionTail = template.substring(current);
      const expressionMatch = expressionTail.match(closeRE);

      if("__ENV__" !== "production" && expressionMatch === null) {
        error(`Expected closing delimiter after "${expressionTail}"`);
      } else {
        const expressionIndex = expressionMatch.index;
        const expression = expressionTail.substring(0, expressionIndex);
        compileTemplateExpression(expression, exclude, dependencies);
        output += `(${expression})`;
        current += expression.length + expressionMatch[0].length;

        // Concatenate if not at the end
        if(current !== length) {
          output += concatenationSymbol;
        }
      }
    }
  }

  return {
    output: output,
    dynamic: dynamic
  };
}
<|endoftext|>


<commit_before>"use strict";
(function() {
  var app = angular.module("gemStore", []);

  app.controller("StoreController", function () {
    this.product = gems;
  });

  app.controller("TabController", function () {
    this.tab = 1;

    this.setTab = function (setTab) {
      this.tab = setTab;
    };

    this.isSet = function (setValue) {
      return this.tab === setValue;
    };

    this.setActive = function (activeValue) {
      return this.tab === activeValue;
    };
  });

  app.controller("GalleryController", function() {
    this.currentImage = 0;

    this.setCurrent = function (currentValue) {
      this.currentImage = currentValue || 0;
    };

    this.toggleCurrent = function (toggleValue) {
      if (this.currentImage === toggleValue) {
        return false;
      }

      this.currentImage = toggleValue || 0;
    };

    this.setActive = function (activeValue) {
      return this.currentImage === activeValue;
    };
  });

  app.controller("ReviewController", function () {
    this.review = {};

    this.setDate = function () {
      return Date.parse(new Date());
    };

    this.addReview = function(product) {
      product.reviews.push(this.review);

      this.review = {};
    };
  });

  var gems = [
    {
      name: 'Azurite',
      description: "Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems. Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems. Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems.",
      shine: 8,
      price: 110.50,
      rarity: 7,
      color: '#CCC',
      faces: 14,
      images: [
        "public/images/gem-02.gif",
        "public/images/gem-05.gif",
        "public/images/gem-09.gif"
      ],
      reviews: [{
        stars: 5,
        body: "I love this gem!",
        author: "joe@example.org",
        createdOn: 1397490980837
      }, {
        stars: 1,
        body: "This gem sucks.",
        author: "tim@example.org",
        createdOn: 1397490980837
      }],
      canPurchase: true
    },
    {
      name: 'Bloodstone',
      description: "Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however. Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however. Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however.",
      shine: 9,
      price: 22.90,
      rarity: 6,
      color: '#EEE',
      faces: 12,
      images: [
        "public/images/gem-01.gif",
        "public/images/gem-03.gif",
        "public/images/gem-04.gif"
      ],
      reviews: [{
        stars: 3,
        body: "I think this gem was just OK, could honestly use more shine, IMO.",
        author: "JimmyDean@example.org",
        createdOn: 1397490980837
      }, {
        stars: 4,
        body: "Any gem with 12 faces is for me!",
        author: "gemsRock@example.org",
        createdOn: 1397490980837
      }],
      canPurchase: true
    },
    {
      name: 'Zircon',
      description: "Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem. Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem. Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem.",
      shine: 70,
      price: 1100,
      rarity: 2,
      color: '#000',
      faces: 6,
      images: [
        "public/images/gem-06.gif",
        "public/images/gem-07.gif",
        "public/images/gem-10.gif"
      ],
      reviews: [{
        stars: 1,
        body: "This gem is WAY too expensive for its rarity value.",
        author: "turtleguyy@example.org",
        createdOn: 1397490980837
      }, {
        stars: 1,
        body: "BBW: High Shine != High Quality.",
        author: "LouisW407@example.org",
        createdOn: 1397490980837
      }, {
        stars: 1,
        body: "Don't waste your rubles!",
        author: "nat@example.org",
        createdOn: 1397490980837
      }],
      canPurchase: true
    }];
})();
<commit_msg>Delete unuseful method setDate. Edit addReview<commit_after>"use strict";
(function() {
  var app = angular.module("gemStore", []);

  app.controller("StoreController", function () {
    this.product = gems;
  });

  app.controller("TabController", function () {
    this.tab = 1;

    this.setTab = function (setTab) {
      this.tab = setTab;
    };

    this.isSet = function (setValue) {
      return this.tab === setValue;
    };

    this.setActive = function (activeValue) {
      return this.tab === activeValue;
    };
  });

  app.controller("GalleryController", function() {
    this.currentImage = 0;

    this.setCurrent = function (currentValue) {
      this.currentImage = currentValue || 0;
    };

    this.toggleCurrent = function (toggleValue) {
      if (this.currentImage === toggleValue) {
        return false;
      }

      this.currentImage = toggleValue || 0;
    };

    this.setActive = function (activeValue) {
      return this.currentImage === activeValue;
    };
  });

  app.controller("ReviewController", function () {
    this.review = {};

    this.addReview = function(product) {
      this.review.createdOn = Date.now(); //  returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC
      product.reviews.push(this.review);

      this.review = {};
    };
  });

  var gems = [
    {
      name: 'Azurite',
      description: "Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems. Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems. Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems.",
      shine: 8,
      price: 110.50,
      rarity: 7,
      color: '#CCC',
      faces: 14,
      images: [
        "public/images/gem-02.gif",
        "public/images/gem-05.gif",
        "public/images/gem-09.gif"
      ],
      reviews: [{
        stars: 5,
        body: "I love this gem!",
        author: "joe@example.org",
        createdOn: 1397490980837
      }, {
        stars: 1,
        body: "This gem sucks.",
        author: "tim@example.org",
        createdOn: 1397490980837
      }],
      canPurchase: true
    },
    {
      name: 'Bloodstone',
      description: "Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however. Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however. Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however.",
      shine: 9,
      price: 22.90,
      rarity: 6,
      color: '#EEE',
      faces: 12,
      images: [
        "public/images/gem-01.gif",
        "public/images/gem-03.gif",
        "public/images/gem-04.gif"
      ],
      reviews: [{
        stars: 3,
        body: "I think this gem was just OK, could honestly use more shine, IMO.",
        author: "JimmyDean@example.org",
        createdOn: 1397490980837
      }, {
        stars: 4,
        body: "Any gem with 12 faces is for me!",
        author: "gemsRock@example.org",
        createdOn: 1397490980837
      }],
      canPurchase: true
    },
    {
      name: 'Zircon',
      description: "Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem. Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem. Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem.",
      shine: 70,
      price: 1100,
      rarity: 2,
      color: '#000',
      faces: 6,
      images: [
        "public/images/gem-06.gif",
        "public/images/gem-07.gif",
        "public/images/gem-10.gif"
      ],
      reviews: [{
        stars: 1,
        body: "This gem is WAY too expensive for its rarity value.",
        author: "turtleguyy@example.org",
        createdOn: 1397490980837
      }, {
        stars: 1,
        body: "BBW: High Shine != High Quality.",
        author: "LouisW407@example.org",
        createdOn: 1397490980837
      }, {
        stars: 1,
        body: "Don't waste your rubles!",
        author: "nat@example.org",
        createdOn: 1397490980837
      }],
      canPurchase: true
    }];
})();
<|endoftext|>


<commit_before>// =============================================================================
// Import
// =============================================================================

// React
import PropTypes from 'prop-types';

// Styles
import glamorous from 'glamorous';
import { color, border } from '../utils/styles';

// =============================================================================
// Tab buttons
// =============================================================================

export const TabButtons = glamorous.div(
  {
    display:      'flex',
    padding:      '0.125rem',
    border:       `1px solid ${color.grey.lighter}`,
    borderRadius: border.radius.small,
  },
  ({ marginBottom }) => ({
    marginBottom,
  }),
);

export const TabButton = glamorous.div(
  {
    flex:         '1',
    cursor:       'pointer',
    padding:      '1rem',
    textAlign:    'center',
    borderRadius: 'inherit',
  },
  ({ isActive }) =>
    isActive && {
      fontWeight:      '900',
      backgroundColor: color.grey.lighter,
    },
);

TabButton.propTypes = {
  isActive: PropTypes.bool,
};

TabButton.defaultProps = {
  isActive: false,
};
<commit_msg>add button component<commit_after>// =============================================================================
// Import
// =============================================================================

// React
import PropTypes from 'prop-types';

// Styles
import glamorous from 'glamorous';
import { color, border } from '../utils/styles';

// =============================================================================
// Button
// =============================================================================

export const Button = glamorous.button({
  fontFamily:      'inherit',
  color:           'inherit',
  border:          'none',
  outline:         '0',
  display:         'inline-flex',
  padding:         '0.5rem 1rem',
  cursor:          'pointer',
  backgroundColor: color.grey.lighter,
  borderRadius:    border.radius.small,
  '& + &':         {
    marginLeft: '0.25rem',
  },
  '&:hover': {
    backgroundColor: color.grey.light,
  },
});

// =============================================================================
// Tab buttons
// =============================================================================

export const TabButtons = glamorous.div(
  {
    display:      'flex',
    padding:      '0.125rem',
    border:       `1px solid ${color.grey.lighter}`,
    borderRadius: border.radius.small,
  },
  ({ marginBottom }) => ({
    marginBottom,
  }),
);

export const TabButton = glamorous.div(
  {
    flex:         '1',
    cursor:       'pointer',
    padding:      '1rem',
    textAlign:    'center',
    borderRadius: 'inherit',
  },
  ({ isActive }) =>
    isActive && {
      fontWeight:      '900',
      backgroundColor: color.grey.lighter,
    },
);

TabButton.propTypes = {
  isActive: PropTypes.bool,
};

TabButton.defaultProps = {
  isActive: false,
};
<|endoftext|>