<commit_before>var me = {
	id: undefined,
	chosedRoomToEnter: undefined,
	enteredRoom: undefined
};

/**
 * Function from which we demand respond, recall,
 * giving them as parameters functions which need to be recalled
 * after receiving expected data.
 */
var main = {
	/**
	 * @function main.takePicture
	 * Take picture then send it to the server and present on a wall
	 * @param {Number} quality
	 * Quality of photos is in range [1, 100].
	 */
	takePicture: function(quality) {
		devices.camera.takePicture(quality, function(imageSrc) {
			connection.file.upload.photo(imageSrc);

			//main.addNewMyData('image', imageSrc);
			//var image = document.getElementById('myImageCamera');
			//image.style.display = 'block';

			//image.src = imageSrc/*"data:image/jpeg;base64," + */;
		});
	},

	/**
	 * @function main.loadPicture
	 * Load picture then send it to the server and present on a wall
	 * @param {Number} quality
	 * Quality of photos is in range [1, 100].
	 */
	loadPicture: function() {
		devices.photoLibrary.take(function(imageSrc) {
			connection.file.upload.photo(imageSrc);

			var image = document.getElementById('myImageCamera');
			image.style.display = 'block';

			image.src = imageSrc/*"data:image/jpeg;base64," + */;
		});
	},

	 /**
	 * @function main.initialQrCode
	 * Scan QR Code of webmaster, get connection of websocket and save scaned data to input
	 */
	initialQrCode: function() {
		devices.qrCode.scan(function(result) {

			main.setUrl(result);

		}, true);
	},

	 /**
	 * @function main.scanAnyQrCode
	 * Scan QR Code of webmaster and start alert only
	 */
	scanAnyQrCode: function() {
		devices.qrCode.scan(function(result) {
			alert(result);
		});
	},

	 /**
	 * @function main.getMac
	 * Download data of device mac and recall with this mac an alert
	 */
	getMac: function() {
		devices.mac.get(function(result) {
			alert(result);
		});
	},

	 /**
	 * @function main.getRooms
	 * Download data of rooms
	 */
	getRooms: function() {
		connection.action.getRooms(function(received) {
			// received zawiera listę elementów, np. {id: 0, name: 'room', folderName: 'room'}
			// instersuje nas id po którym dołączamy i name które wyświetlamy
			if (received.length > 0) {
				main.choseRoomToEnter(received[0].id);
			}
			storage.showRooms(received);

		});
	},

	/**
	 * @function main.initUrl
	 * Initialize url
	 */
	initUrl: function() {
		load('connecting');
		connection.initUrl(function() {
			connection.action.home(function(data) {
				if (data.id) {
					historyObj.addTohistoryObj('login');
					load('rooms', true);
				} else {
					load('login', true);
				}
			});
        }, function() {
            load('connection');
        });
	},

	 /**
	 * @function main.initSocket
	 * Initialize socket
	 */
	initSocket: function() {
		load('wall');
		connection.socket.init(function() {
			connection.state = connection.states.established;
		}, function() {
			// Here we do not have to type second argument, because
			// It changes *.html page and this new page loads rooms with argument.
			load('rooms');
		});
		connection.socket.ping();
	},

	 /**
	 * @function main.setUrl
	 * Set url to login
	 * @param {String} link
	 * link to login
	 */
	setUrl: function(link) {
        load('connecting');
		var url = document.getElementById('url');
		url.value = link;
		connection.setUrl(link, function() {
			url.value = link;

			load('login', true);
		}, function() {
            load('connection', true);
		});
	},

	 /**
	 * @function main.login
	 * Login to system
	 * @param {String} login
	 * user login
	 * @param {String} password
	 * user password
	 */
	login: function(login, password) {
		connection.action.login(login, password, function(received) {
			if (received.name === login) {//when everything is correct
				me.id = received.id;
				storage.setUserLogin(login);
				storage.setUserPassword(password);
				load('rooms', true);
			}
		}, function(data) { //in case of wrong input data
			alert('Wrong username or password');
		});
	},

	 /**
	 * @function main.login
	 * Register in system
	 * @param {String} login
	 * user login
	 * @param {String} password
	 * user password
	 * @param {String} password2
	 * user password (confirmation)
	 */
	register: function(login, password, password2) {
		connection.action.register(login, password, password2, function(received) {
			if (received) {//when everything is correct
				load('login', true);
			}
		}, function(data) {//in case of wrong input data or data already exist in database
			if (data) {
				alert(data);
			} else {
				alert('Login already registered');
			}
		});
	},

	/**
	 * @function main.createRoom
	 * Create room
	 * @param {String} roomName
	 * Name of the room which user want to createElement
	 */
	createRoom: function(roomName) {
		main.choseRoomToEnter();
		connection.action.createRoom(roomName, function(received) {
			var roomId = received.id;
			console.log(JSON.stringify(received));
			main.joinRoom(received, function(answer) {
				callback(answer);
				if (answer) {
					alert('Room successfully created');
				} else {
					alert('Creating room failed');
				}
			});
		});
	},

	/**
	 * @function main.joinRoom
	 * Join and enter to current room
	 * @param {int} roomId
	 * ID of current room
	 * @param {} callb
	 */
	joinRoom: function(roomId, callb) {
		if (roomId) {
			connection.action.joinRoom(roomId.id, function(received) {
				if (received) {
					storage.addCreatedRoom(roomId);
					if (callb) {
						callb(received);
					}
				}
			});
		}
	},

	/**
	 * @function main.choseRoomToEnter
	 * Set room to which one user want to join
	 * @param {int} choseRoomToEnter
	 * User chosen room
	 */
	choseRoomToEnter: function(chosedRoomToEnter) {
		me.chosedRoomToEnter = chosedRoomToEnter;
	},

	/**
	 * @function main.goToWall
	 * Move to wall view
	 */
	goToWall: function() {
		var roomToEnter = storage.getChosedRoomToEnter();
		main.choseRoomToEnter(roomToEnter);
		if (me.chosedRoomToEnter) {
			window.localStorage.setItem('chosedRoomToEnter', me.chosedRoomToEnter);
			load('wall');
		} else {
			alert('No room is selected');
		}
	},

	/**
	 * @function main.goToOnlineUsers
	 * Present list of online users
	 */
	goToOnlineUsers: function() {
		load('users', true);
	},

	 /**
	 * @function main.enterRoom
	 * Inform the server that user enter to already joined room.
	 * Runned on the wall page, after receiving ping answer.
	 */
	enterRoom: function() {
		var roomId = window.localStorage.getItem('chosedRoomToEnter');
		if (roomId) {
			me.chosedRoomToEnter = roomId;
			connection.socket.enterRoom(roomId);
		} else {
			alert('No room is chosen');
		}
	},

	 /**
	 * @function main.scanRoomQrCode
	 * Scan QR code to current room and join this room.
	 * Immediately goes to wall.
	 */
	scanRoomQrCode: function() {
		// scan
		devices.qrCode.scan(function(roomId) {
			// join
			main.joinRoom({id: roomId, name: 'already scanned room'}, function(answer) {
				main.goToWall();
			});
		});
	},

	 /**
	 * @function main.getRoomData
	 * Download all of current room data
	 */
	getRoomData: function() {
		connection.action.getRoomData(function(data) {
			alert('getRoomData' + JSON.stringify(data));
			storage.addAllRoomData(data);
		});
	}
};

	 /**
	 * @function routing.registerAction
	 * Get rooms
	 * Get room data (wall)
	 * Present wall data
	 */
routing.registerAction('rooms', function() {
	main.getRooms();
});
routing.registerAction('wall', function() {
	// Here should be displaying room name from storage
	// (which was set in connection.socket.receive.onEnterRoom())

	connection.socket.getConnectedUsers();
	main.getRoomData();

    load('wallContent', true);
});
routing.registerAction('wallContent', function() {
	//storage.* - action of setting view after changing view
	// to set it again
});
routing.registerAction('users', function() {
	storage.showOnlineUsers();
});
routing.registerAction('login', function() {
	//storage.initLoginData
});
routing.registerAction('connection', function() {
	// we can add here any additional connection information
	// to connection page
	alert('Connection failed');
});

	 /**
	 * @function connection.socket.receive.onEnterRoom
	 * Load wall to get data while user entered the current room
	 * @param {int, String} data
	 * Data consists of meetingID and name
	 */
connection.socket.receive.onEnterRoom = function(data) {
	// Here we should assign data to storage
	me.enteredRoom = data;
	load('wall', true);
};

	 /**
	 * @function connection.socket.receive.onPing
	 * Get data while user Ping
	 */
connection.socket.receive.onPing = function() {
    main.enterRoom();
};

/**
 * Elements received from websocket is supported by functions below:
 */
 	 /**
	 * @function connection.socket.receive.onUsersOnline
	 * Add new user to OnlineUsers
	 * @param {} data
	 * Data which contain user data
	 */
connection.socket.receive.onUsersOnline = function(data) {
	alert('onUsersOnline ' + JSON.stringify(data));
	storage.getAllOnlineUsers(data);
	// add new users
};

 	 /**
	 * @function connection.socket.receive.onNewUser
	 * Alert about new user online
	 * @param {} data
	 * Data which contain user data
	 */
connection.socket.receive.onNewUser = function(data) {
	alert('onNewUser ' + JSON.stringify(data));
	storage.addNewUser(data);
	// add new user
};

 	 /**
	 * @function connection.socket.receive.onRemoveUser
	 * Delete user from OnlineUsers list
	 * @param {} data
	 * Data which contain user data
	 */
connection.socket.receive.onRemoveUser = function(data) {
	alert('onRemoveUser ' + JSON.stringify(data));
	storage.deleteUser(data);
	// remove user
};

 	 /**
	 * @function connection.socket.receive.onNewPhoto
	 * Alert about new photo
	 * @param {} data
	 * Data which contain information about photo
	 */
connection.socket.receive.onNewPhoto = function(data) {
	alert('onNewPhoto: ' + JSON.stringify(data));
    storage.addNewData(data);
};

 	 /**
	 * @function connection.socket.receive.onNewNote
	 * Alert about new note
	 * @param {} data
	 * Data which contain information about note
	 */
connection.socket.receive.onNewNote = function(data) {
	alert('onNewNote: ' + JSON.stringify(data));
    storage.addNewData(data);
};

 	 /**
	 * @function connection.socket.receive.onNewComment
	 * Alert about new comment
	 * @param {} data
	 * Data which contain information about comment
	 */
connection.socket.receive.onNewComment = function(data) {
	alert('onNewComment: ' + JSON.stringify(data));
	storage.addNewData(data);
    // add new comment
};
<commit_msg>client: backend wejscia do pokoju poprzez wpisanie jego id<commit_after>var me = {
	id: undefined,
	chosedRoomToEnter: undefined,
	enteredRoom: undefined
};

/**
 * Function from which we demand respond, recall,
 * giving them as parameters functions which need to be recalled
 * after receiving expected data.
 */
var main = {
	/**
	 * @function main.takePicture
	 * Take picture then send it to the server and present on a wall
	 * @param {Number} quality
	 * Quality of photos is in range [1, 100].
	 */
	takePicture: function(quality) {
		devices.camera.takePicture(quality, function(imageSrc) {
			connection.file.upload.photo(imageSrc);

			//main.addNewMyData('image', imageSrc);
			//var image = document.getElementById('myImageCamera');
			//image.style.display = 'block';

			//image.src = imageSrc/*"data:image/jpeg;base64," + */;
		});
	},

	/**
	 * @function main.loadPicture
	 * Load picture then send it to the server and present on a wall
	 * @param {Number} quality
	 * Quality of photos is in range [1, 100].
	 */
	loadPicture: function() {
		devices.photoLibrary.take(function(imageSrc) {
			connection.file.upload.photo(imageSrc);

			var image = document.getElementById('myImageCamera');
			image.style.display = 'block';

			image.src = imageSrc/*"data:image/jpeg;base64," + */;
		});
	},

	 /**
	 * @function main.initialQrCode
	 * Scan QR Code of webmaster, get connection of websocket and save scaned data to input
	 */
	initialQrCode: function() {
		devices.qrCode.scan(function(result) {

			main.setUrl(result);

		}, true);
	},

	 /**
	 * @function main.scanAnyQrCode
	 * Scan QR Code of webmaster and start alert only
	 */
	scanAnyQrCode: function() {
		devices.qrCode.scan(function(result) {
			alert(result);
		});
	},

	 /**
	 * @function main.getMac
	 * Download data of device mac and recall with this mac an alert
	 */
	getMac: function() {
		devices.mac.get(function(result) {
			alert(result);
		});
	},

	 /**
	 * @function main.getRooms
	 * Download data of rooms
	 */
	getRooms: function() {
		connection.action.getRooms(function(received) {
			// received zawiera listę elementów, np. {id: 0, name: 'room', folderName: 'room'}
			// instersuje nas id po którym dołączamy i name które wyświetlamy
			if (received.length > 0) {
				main.choseRoomToEnter(received[0].id);
			}
			storage.showRooms(received);

		});
	},

	/**
	 * @function main.initUrl
	 * Initialize url
	 */
	initUrl: function() {
		load('connecting');
		connection.initUrl(function() {
			connection.action.home(function(data) {
				if (data.id) {
					historyObj.addTohistoryObj('login');
					load('rooms', true);
				} else {
					load('login', true);
				}
			});
        }, function() {
            load('connection');
        });
	},

	 /**
	 * @function main.initSocket
	 * Initialize socket
	 */
	initSocket: function() {
		load('wall');
		connection.socket.init(function() {
			connection.state = connection.states.established;
		}, function() {
			// Here we do not have to type second argument, because
			// It changes *.html page and this new page loads rooms with argument.
			load('rooms');
		});
		connection.socket.ping();
	},

	 /**
	 * @function main.setUrl
	 * Set url to login
	 * @param {String} link
	 * link to login
	 */
	setUrl: function(link) {
        load('connecting');
		var url = document.getElementById('url');
		url.value = link;
		connection.setUrl(link, function() {
			url.value = link;

			load('login', true);
		}, function() {
            load('connection', true);
		});
	},

	 /**
	 * @function main.login
	 * Login to system
	 * @param {String} login
	 * user login
	 * @param {String} password
	 * user password
	 */
	login: function(login, password) {
		connection.action.login(login, password, function(received) {
			if (received.name === login) {//when everything is correct
				me.id = received.id;
				storage.setUserLogin(login);
				storage.setUserPassword(password);
				load('rooms', true);
			}
		}, function(data) { //in case of wrong input data
			alert('Wrong username or password');
		});
	},

	 /**
	 * @function main.login
	 * Register in system
	 * @param {String} login
	 * user login
	 * @param {String} password
	 * user password
	 * @param {String} password2
	 * user password (confirmation)
	 */
	register: function(login, password, password2) {
		connection.action.register(login, password, password2, function(received) {
			if (received) {//when everything is correct
				load('login', true);
			}
		}, function(data) {//in case of wrong input data or data already exist in database
			if (data) {
				alert(data);
			} else {
				alert('Login already registered');
			}
		});
	},

	/**
	 * @function main.createRoom
	 * Create room
	 * @param {String} roomName
	 * Name of the room which user want to createElement
	 */
	createRoom: function(roomName) {
		main.choseRoomToEnter();
		connection.action.createRoom(roomName, function(received) {
			var roomId = received.id;
			console.log(JSON.stringify(received));
			main.joinRoom(received, function(answer) {
				callback(answer);
				if (answer) {
					alert('Room successfully created');
				} else {
					alert('Creating room failed');
				}
			});
		});
	},

	/**
	 * @function main.joinRoom
	 * Join and enter to current room
	 * @param {int} roomId
	 * ID of current room
	 * @param {} callb
	 */
	joinRoom: function(roomId, callb) {
		if (roomId) {
			connection.action.joinRoom(roomId.id, function(received) {
				if (received) {
					storage.addCreatedRoom(roomId);
					if (callb) {
						callb(received);
					}
				}
			});
		}
	},

	/**
	 * @function main.joinRoomById
	 * Join and and go to wall of typed room
	 * @param {int} roomId
	 * ID of selected room
	 */
	joinRoomById: function(roomId) {
		main.joinRoom({id: roomId, name: 'already typed room'}, function(answer) {
			main.goToWall();
		});
	},

	/**
	 * @function main.choseRoomToEnter
	 * Set room to which one user want to join
	 * @param {int} choseRoomToEnter
	 * User chosen room
	 */
	choseRoomToEnter: function(chosedRoomToEnter) {
		me.chosedRoomToEnter = chosedRoomToEnter;
	},

	/**
	 * @function main.goToWall
	 * Move to wall view
	 */
	goToWall: function() {
		var roomToEnter = storage.getChosedRoomToEnter();
		main.choseRoomToEnter(roomToEnter);
		if (me.chosedRoomToEnter) {
			window.localStorage.setItem('chosedRoomToEnter', me.chosedRoomToEnter);
			load('wall');
		} else {
			alert('No room is selected');
		}
	},

	/**
	 * @function main.goToOnlineUsers
	 * Present list of online users
	 */
	goToOnlineUsers: function() {
		load('users', true);
	},

	 /**
	 * @function main.enterRoom
	 * Inform the server that user enter to already joined room.
	 * Runned on the wall page, after receiving ping answer.
	 */
	enterRoom: function() {
		var roomId = window.localStorage.getItem('chosedRoomToEnter');
		if (roomId) {
			me.chosedRoomToEnter = roomId;
			connection.socket.enterRoom(roomId);
		} else {
			alert('No room is chosen');
		}
	},

	 /**
	 * @function main.scanRoomQrCode
	 * Scan QR code to current room and join this room.
	 * Immediately goes to wall.
	 */
	scanRoomQrCode: function() {
		// scan
		devices.qrCode.scan(function(roomId) {
			main.joinRoomById(roomId);
		});
	},

	 /**
	 * @function main.getRoomData
	 * Download all of current room data
	 */
	getRoomData: function() {
		connection.action.getRoomData(function(data) {
			alert('getRoomData' + JSON.stringify(data));
			storage.addAllRoomData(data);
		});
	}
};

	 /**
	 * @function routing.registerAction
	 * Get rooms
	 * Get room data (wall)
	 * Present wall data
	 */
routing.registerAction('rooms', function() {
	main.getRooms();
});
routing.registerAction('wall', function() {
	// Here should be displaying room name from storage
	// (which was set in connection.socket.receive.onEnterRoom())

	connection.socket.getConnectedUsers();
	main.getRoomData();

    load('wallContent', true);
});
routing.registerAction('wallContent', function() {
	//storage.* - action of setting view after changing view
	// to set it again
});
routing.registerAction('users', function() {
	storage.showOnlineUsers();
});
routing.registerAction('login', function() {
	//storage.initLoginData
});
routing.registerAction('connection', function() {
	// we can add here any additional connection information
	// to connection page
	alert('Connection failed');
});

	 /**
	 * @function connection.socket.receive.onEnterRoom
	 * Load wall to get data while user entered the current room
	 * @param {int, String} data
	 * Data consists of meetingID and name
	 */
connection.socket.receive.onEnterRoom = function(data) {
	// Here we should assign data to storage
	me.enteredRoom = data;
	load('wall', true);
};

	 /**
	 * @function connection.socket.receive.onPing
	 * Get data while user Ping
	 */
connection.socket.receive.onPing = function() {
    main.enterRoom();
};

/**
 * Elements received from websocket is supported by functions below:
 */
 	 /**
	 * @function connection.socket.receive.onUsersOnline
	 * Add new user to OnlineUsers
	 * @param {} data
	 * Data which contain user data
	 */
connection.socket.receive.onUsersOnline = function(data) {
	alert('onUsersOnline ' + JSON.stringify(data));
	storage.getAllOnlineUsers(data);
	// add new users
};

 	 /**
	 * @function connection.socket.receive.onNewUser
	 * Alert about new user online
	 * @param {} data
	 * Data which contain user data
	 */
connection.socket.receive.onNewUser = function(data) {
	alert('onNewUser ' + JSON.stringify(data));
	storage.addNewUser(data);
	// add new user
};

 	 /**
	 * @function connection.socket.receive.onRemoveUser
	 * Delete user from OnlineUsers list
	 * @param {} data
	 * Data which contain user data
	 */
connection.socket.receive.onRemoveUser = function(data) {
	alert('onRemoveUser ' + JSON.stringify(data));
	storage.deleteUser(data);
	// remove user
};

 	 /**
	 * @function connection.socket.receive.onNewPhoto
	 * Alert about new photo
	 * @param {} data
	 * Data which contain information about photo
	 */
connection.socket.receive.onNewPhoto = function(data) {
	alert('onNewPhoto: ' + JSON.stringify(data));
    storage.addNewData(data);
};

 	 /**
	 * @function connection.socket.receive.onNewNote
	 * Alert about new note
	 * @param {} data
	 * Data which contain information about note
	 */
connection.socket.receive.onNewNote = function(data) {
	alert('onNewNote: ' + JSON.stringify(data));
    storage.addNewData(data);
};

 	 /**
	 * @function connection.socket.receive.onNewComment
	 * Alert about new comment
	 * @param {} data
	 * Data which contain information about comment
	 */
connection.socket.receive.onNewComment = function(data) {
	alert('onNewComment: ' + JSON.stringify(data));
	storage.addNewData(data);
    // add new comment
};
<|endoftext|>


<commit_before>import React from 'react';

const Projectile = (props) => {
  return (
    <a-mixin
    id='projectile'
    dynamic-body
    geometry='primitive: sphere; radius: 0.25;'
    // velocity='0 0 -10'
    material='color: black;' />
  )
}

module.exports = Projectile;
<commit_msg>Add explode to projectile mixin<commit_after>import React from 'react';

const Projectile = (props) => {
  return (
    <a-mixin
    id='projectile'
    dynamic-body
    geometry='primitive: sphere; radius: 0.25;'
    explode
    // velocity='0 0 -10'
    material='color: black;' />
  )
}

module.exports = Projectile;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import createResume from './ResumeGenerator';
import UserProfile from './UserProfile';
import { NavLink } from 'react-router-dom';
const moment = require('moment');
const moment = require('moment');
const FileSaver = require('file-saver');

class ClientData extends Component {
  constructor(props){
    super(props);
    this.getClients = this.getClients.bind(this);
    this.downResume = this.downResume.bind(this);
    this.state = {
      clientData: [],
    }
  }

  getClients = () =>{
    fetch("/api/clients", {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'JWT '+localStorage.getItem("token")
      },
      method: 'GET'
    })
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        clientData: responseJson,
        fetchDone: true,
      });
    });
  };

  componentDidMount(){
    this.getClients();
  }

  render() {

    console.log("inside render", this.state.clientData);
    const persons = this.state.clientData.map(item => (

         {moment(item.registration_date).format('MM/DD/YY')}
         {item.first_name}
         {item.last_name}
         {item.dob}

          <NavLink id="toUser"
              to={`/user/${item.id}`}
              activeClassName="selected"
              >View</NavLink>

    ))

    return (

              Reg. Date
              First Name
              Last Name
              DOB
              View
              Download PDF

            {persons}

    )
  }
}

export default (ClientData);
<commit_msg>adding pdf download functionality<commit_after>import React, { Component } from 'react';
import createResume from './ResumeGenerator';
import UserProfile from './UserProfile';
import { NavLink } from 'react-router-dom';
const moment = require('moment');
const FileSaver = require('file-saver');

class ClientData extends Component {
  constructor(props){
    super(props);
    this.getClients = this.getClients.bind(this);
    this.downResume = this.downResume.bind(this);
    this.state = {
      clientData: [],
    }
  }

  getClients = () =>{
    fetch("/api/clients", {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'JWT '+localStorage.getItem("token")
      },
      method: 'GET'
    })
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        clientData: responseJson,
        fetchDone: true,
      });
    });
  };

  downResume = (id) =>{
    fetch(`/api/pdf/${id}`, {
      headers: {
        'Accept': 'application/pdf',
        'Content-Type': 'application/pdf',
        'Authorization': 'JWT '+localStorage.getItem("token")
      },
      method: 'GET'
    })
    .then((response) => response.blob())
    .then((responseBlob) => {
       FileSaver.saveAs(responseBlob, 'nameFile.pdf');
    });
  };

  componentDidMount(){
    this.getClients();
  }

  render() {

    console.log("inside render", this.state.clientData);
    const persons = this.state.clientData.map(item => (

         {moment(item.registration_date).format('MM/DD/YY')}
         {item.first_name}
         {item.last_name}
         {item.dob}

          <NavLink id="toUser"
              to={`/user/${item.id}`}
              activeClassName="selected"
              >View</NavLink>

        <button onClick={()=>this.downResume(item.id)}> Download Resume </button>

    ))

    return (

              Reg. Date
              First Name
              Last Name
              DOB
              View
              Download PDF

            {persons}

    )
  }
}

export default (ClientData);
<|endoftext|>


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

    function listAgenciesDirective() {
        return {
            restrict: 'EA',
            replace: true,
            templateUrl: './src/app/agencies/template.html',
            scope: {},
            controllerAs: 'vm',
            bindToController: true,
            /* jshint unused:false*/
            controller: function($log, AgenciesService) {
                var vm=this;
                AgenciesService.getAgencies()
                    .then(function(agencies) {
                        console.log('agencies in directives :',agencies.data);
                        vm.agencies = agencies.data;

                    }, function(error){
                        $log.error('Error agencies', error);
                    });

            },
            link: function(scope, elm, attrs){
            }
        };
    }

angular.module('app.directives.agencies', ['app.services.agencies'])
    .directive('listAgencies', listAgenciesDirective);

})();<commit_msg>comments<commit_after>(function() {
    'use strict';

    function listAgenciesDirective() {
        return {
            restrict: 'EA',
            replace: true,
            templateUrl: './src/app/agencies/template.html',
            scope: {},
            controllerAs: 'vm',
            bindToController: true,
            /* jshint unused:false*/
            controller: function($log, AgenciesService) {
                var vm=this;
                AgenciesService.getAgencies()
                    .then(function(agencies) {
                        //console.log('agencies in directives :',agencies.data);
                        vm.agencies = agencies.data;

                    }, function(error){
                        $log.error('Error agencies', error);
                    });

            },
            link: function(scope, elm, attrs){
            }
        };
    }

angular.module('app.directives.agencies', ['app.services.agencies'])
    .directive('listAgencies', listAgenciesDirective);

})();<|endoftext|>


<commit_before>import canvg from 'canvg-browser';

// list of defined encodings
const ENCODINGS = [
  'image/png',
  'image/jpeg'
];

export default function generateImage(type, svg) {
  const encoding = 'image/' + type;

  let context,
      canvas;

  if (ENCODINGS.indexOf(encoding) === -1) {
    throw new Error('<' + type + '> is an unknown type for converting svg to image');
  }

  canvas = document.createElement('canvas');

  canvg(canvas, svg);

  // make the background white for every format
  context = canvas.getContext('2d');

  context.globalCompositeOperation = 'destination-over';

  context.fillStyle = 'white';

  context.fillRect(0, 0, canvas.width, canvas.height);

  return canvas.toDataURL(encoding);
}
<commit_msg>chore(export): scale exported images<commit_after>import canvg from 'canvg-browser';

// list of defined encodings
const ENCODINGS = [
  'image/png',
  'image/jpeg'
];

const SCALE = 3;

export default function generateImage(type, svg) {
  const encoding = 'image/' + type;

  let context,
      canvas;

  if (ENCODINGS.indexOf(encoding) === -1) {
    throw new Error('<' + type + '> is an unknown type for converting svg to image');
  }

  canvas = document.createElement('canvas');

  svg = svg.replace(/width="([^"]+)" height="([^"]+)"/, function(_, widthStr, heightStr) {
    return `width="${parseInt(widthStr, 10) * SCALE}" height="${parseInt(heightStr, 10) * SCALE}"`;
  });

  canvg(canvas, svg);

  // make the background white for every format
  context = canvas.getContext('2d');

  context.globalCompositeOperation = 'destination-over';

  context.fillStyle = 'white';

  context.fillRect(0, 0, canvas.width, canvas.height);

  return canvas.toDataURL(encoding);
}<|endoftext|>


<commit_before>import React, { Component } from "react";
import "./MembersView.css";
import Client from "../Client";
import MembersList from "./MembersList";
import ConfirmMessage from "./ConfirmMessage";
import PropTypes from "prop-types";

class MembersView extends Component {
  state = {
    members: [],
    updated: [],
    popup: {
      pop: false,
      msg: "",
      onYesClick: this.onYesClick,
    },
  }
  componentWillMount() {
    const uri = "/api/admin/manageableUsers";

    Client.get(uri)
      .then(members => {
        this.setState({members})
      })
  }

  onFormSubmit(event) {
    event.preventDefault();
    let updated = this.state.updated.map(user => user["email"]);
    updated = updated.join(", ");
    const popup = {
      pop: true,
      msg: `${this.context.language.MembersView.accMsg} ${updated}`,
    }

    this.setState({ popup });
  }

  onInputChange(event) {
    const updated = this.state.updated;
    const members = this.state.members.filter((member) => {
      if (event.target.name === member.id) {
        updated.push({
          id: event.target.name,
          role: event.target.value,
          email: member.email
        });

        member.userLevel = event.target.value;
        return member;
      } else {
        return member;
      }
    });

    this.setState({ members, updated });
  }

  onConfirmClick() {
    const updated = this.state.updated;

    while (updated.length > 0) {
      const user = updated.shift();
      let uri = "";

      if (user.role === "USER") {
        uri = "/api/admin/make_user";
      }

      if (user.role === "ADMIN") {
        uri = "/api/admin/make_admin";
      }

      if (user.role === "SUPER_ADMIN") {
        uri = "/api/super_admin/make_super_admin";
      }

      Client.post({id: user.id}, uri)
    }

    this.setState({updated});
  }

  render() {

    const language = this.context.language.MembersView;

    return (

{language.members}

        <form onSubmit={this.onFormSubmit.bind(this)}>
          <MembersList members={this.state.members} onChange={this.onInputChange.bind(this)}/>
          <input type="submit" value={language.save} className="btn-primary"></input>
        </form>
        <ConfirmMessage popup={this.state.popup} onClick={this.onConfirmClick.bind(this)}/>

    );
  }
}

MembersView.contextTypes = {
  language: PropTypes.object,
}

export default MembersView;
<commit_msg>fixed bug with popup poping even when no action selected<commit_after>import React, { Component } from "react";
import "./MembersView.css";
import Client from "../Client";
import MembersList from "./MembersList";
import ConfirmMessage from "./ConfirmMessage";
import PropTypes from "prop-types";

class MembersView extends Component {
  state = {
    members: [],
    updated: [],
    popup: {
      pop: false,
      msg: "",
      onYesClick: this.onYesClick,
    },
  }
  componentWillMount() {
    const uri = "/api/admin/manageableUsers";

    Client.get(uri)
      .then(members => {
        this.setState({members})
      })
  }

  onFormSubmit(event) {
    event.preventDefault();

    if (this.state.updated.length > 0) {
      let updated = this.state.updated.map(user => user["email"]);
      updated = updated.join(", ");
      const popup = {
        pop: true,
        msg: `${this.context.language.MembersView.accMsg} ${updated}`,
      }

      this.setState({ popup });
    }

  }

  onInputChange(event) {
    const updated = this.state.updated;
    const members = this.state.members.filter((member) => {
      if (event.target.name === member.id) {
        updated.push({
          id: event.target.name,
          role: event.target.value,
          email: member.email
        });

        member.userLevel = event.target.value;
        return member;
      } else {
        return member;
      }
    });

    this.setState({ members, updated });
  }

  onConfirmClick() {
    let updated = this.state.updated;

    while (updated.length > 0) {
      const user = updated.shift();
      let uri = "";

      if (user.role === "USER") {
        uri = "/api/admin/make_user";
      }

      if (user.role === "ADMIN") {
        uri = "/api/admin/make_admin";
      }

      if (user.role === "SUPER_ADMIN") {
        uri = "/api/super_admin/make_super_admin";
      }

      Client.post({id: user.id}, uri)
    }

    updated = [];
    this.setState({updated});
  }

  render() {

    const language = this.context.language.MembersView;

    return (

{language.members}

        <form onSubmit={this.onFormSubmit.bind(this)}>
          <MembersList members={this.state.members} onChange={this.onInputChange.bind(this)}/>
          <input type="submit" value={language.save} className="btn-primary"></input>
        </form>
        <ConfirmMessage popup={this.state.popup} onClick={this.onConfirmClick.bind(this)}/>

    );
  }
}

MembersView.contextTypes = {
  language: PropTypes.object,
}

export default MembersView;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import SelectedProjectView from './SelectedProjectView';
import Progress from 'react-progressbar';
import PrimesVisualView from './PrimesVisualView';
import NQueensVisualView from './NQueensVisualView';
import UserView from '../Components/UserView';
import _ from 'lodash';
import Promise from 'bluebird';
import {
        createWebWorkersPool,
        resetWebWorkersPool
       } from '../actions/actions';

class ProjectView extends Component {

  connectToProject() {
    this.props.socket.emit('userReady', {
      projectId: this.props.selectedProject.projectId,
      projectType: this.props.selectedProject.projectType,
      socketId: '/#' + this.props.socket.id,
      maxWorkerJobs: this.props.webWorkersPool === null ? 1 : this.props.webWorkersPool.length
    });
  }

  disconnectFromProject() {
    console.log(`Disconnecting from project: ${this.props.selectedProject['title']}`);
    this.props.socket.emit('userDisconnect');
    console.log(this.props);
    this.props.resetWebWorkersPool({
      webWorkersPool: this.props.webWorkersPool,
      socket: this.props.socket
    });
    this.props.createWebWorkersPool({
      webWorkersPool: this.props.webWorkersPool,
      socket: this.props.socket
    });
  }

  render() {
    // Check that a project is currently selected
    if (this.props.selectedProject === null) {
      this.context.router.push('menu');
      return null;

    // This the actual project view
    } else {
      let visualization, thisProject;
      const projectId = this.props.selectedProject.projectId;

      this.props.projects.forEach( (item) => {
        if (item.projectId === projectId) {
          thisProject = item;
        }
      });

      // Display Custom Visualization
      if (this.props.selectedProject.projectType === 'primes') {
        visualization = <PrimesVisualView />;
      } else if (this.props.selectedProject.projectType === 'nqueens') {
        visualization = <NQueensVisualView />;
      } else {
        visualization =

;
      }

      // Change stats depending on the type of project (ANN or otherwise)
      let stats;
      if (this.props.selectedProject.projectType === 'ANN') {
        stats = (

            This is a Neural Network Project

            Total Number of Training Data Available: {thisProject.availableJobsNum}

        );
      } else {
        stats = (

              Progress: {this.props.results[projectId].length === 0 ? '0': Math.floor(this.props.results[projectId].length / this.props.selectedProject.jobsLength * 100 || 100)}
              %
              <Progress color='#3CC76A' completed={this.props.results[projectId].length === 0 ? 0 : this.props.results[projectId].length / this.props.selectedProject.jobsLength * 100 } />

            Final Result: {thisProject.finalResult}

            Final Time: {thisProject.projectTime ? Math.round((thisProject.projectTime / 1000), 1) + ' seconds' : ''}

        );
      }

      // Display Project Data
      return (

              <SelectedProjectView />

              <button
                className="btn-success btn-lg createProject btn-padding btn-size"
                onClick={this.connectToProject.bind(this)}>
                Join
              </button>
              <button
                className="btn-danger btn-lg createProject btn-padding btn-size"
                onClick={this.disconnectFromProject.bind(this)}>
                Abandon
              </button>

              {visualization}

         {stats}

              <UserView workerArray={thisProject.workers}/>

      );
    }
  }
}

// Attach router to context
ProjectView.contextTypes = {
  router: PropTypes.object.isRequired
};

function mapStateToProps(state) {
  return {
    selectedProject: state.selectedProject,
    projects: state.projects,
    socket: state.createdSocket,
    results: state.updateResults,
    job: state.updateJob,
    webWorkersPool: state.webWorkersPool
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      createWebWorkersPool,
      resetWebWorkersPool
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(ProjectView);
<commit_msg>Change typo in path to UserView<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import SelectedProjectView from './SelectedProjectView';
import Progress from 'react-progressbar';
import PrimesVisualView from './PrimesVisualView';
import NQueensVisualView from './NQueensVisualView';
import UserView from '../components/UserView';
import _ from 'lodash';
import Promise from 'bluebird';
import {
        createWebWorkersPool,
        resetWebWorkersPool
       } from '../actions/actions';

class ProjectView extends Component {

  connectToProject() {
    this.props.socket.emit('userReady', {
      projectId: this.props.selectedProject.projectId,
      projectType: this.props.selectedProject.projectType,
      socketId: '/#' + this.props.socket.id,
      maxWorkerJobs: this.props.webWorkersPool === null ? 1 : this.props.webWorkersPool.length
    });
  }

  disconnectFromProject() {
    console.log(`Disconnecting from project: ${this.props.selectedProject['title']}`);
    this.props.socket.emit('userDisconnect');
    console.log(this.props);
    this.props.resetWebWorkersPool({
      webWorkersPool: this.props.webWorkersPool,
      socket: this.props.socket
    });
    this.props.createWebWorkersPool({
      webWorkersPool: this.props.webWorkersPool,
      socket: this.props.socket
    });
  }

  render() {
    // Check that a project is currently selected
    if (this.props.selectedProject === null) {
      this.context.router.push('menu');
      return null;

    // This the actual project view
    } else {
      let visualization, thisProject;
      const projectId = this.props.selectedProject.projectId;

      this.props.projects.forEach( (item) => {
        if (item.projectId === projectId) {
          thisProject = item;
        }
      });

      // Display Custom Visualization
      if (this.props.selectedProject.projectType === 'primes') {
        visualization = <PrimesVisualView />;
      } else if (this.props.selectedProject.projectType === 'nqueens') {
        visualization = <NQueensVisualView />;
      } else {
        visualization =

;
      }

      // Change stats depending on the type of project (ANN or otherwise)
      let stats;
      if (this.props.selectedProject.projectType === 'ANN') {
        stats = (

            This is a Neural Network Project

            Total Number of Training Data Available: {thisProject.availableJobsNum}

        );
      } else {
        stats = (

              Progress: {this.props.results[projectId].length === 0 ? '0': Math.floor(this.props.results[projectId].length / this.props.selectedProject.jobsLength * 100 || 100)}
              %
              <Progress color='#3CC76A' completed={this.props.results[projectId].length === 0 ? 0 : this.props.results[projectId].length / this.props.selectedProject.jobsLength * 100 } />

            Final Result: {thisProject.finalResult}

            Final Time: {thisProject.projectTime ? Math.round((thisProject.projectTime / 1000), 1) + ' seconds' : ''}

        );
      }

      // Display Project Data
      return (

              <SelectedProjectView />

              <button
                className="btn-success btn-lg createProject btn-padding btn-size"
                onClick={this.connectToProject.bind(this)}>
                Join
              </button>
              <button
                className="btn-danger btn-lg createProject btn-padding btn-size"
                onClick={this.disconnectFromProject.bind(this)}>
                Abandon
              </button>

              {visualization}

         {stats}

              <UserView workerArray={thisProject.workers}/>

      );
    }
  }
}

// Attach router to context
ProjectView.contextTypes = {
  router: PropTypes.object.isRequired
};

function mapStateToProps(state) {
  return {
    selectedProject: state.selectedProject,
    projects: state.projects,
    socket: state.createdSocket,
    results: state.updateResults,
    job: state.updateJob,
    webWorkersPool: state.webWorkersPool
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      createWebWorkersPool,
      resetWebWorkersPool
    }, dispatch);
}

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


<commit_before>
define(['ResultHeadersView', 'ResultRowsView'], function(ResultHeadersView, ResultRowsView) {

  var ResultsView = Backbone.Marionette.LayoutView.extend({
    initialize: function(options) {
      this.options = options
      this.resultsCollection = this.options.results
      this.resultHeaders = new Backbone.Collection()
      // this.resultRows = new Backbone.Collection()
      this.model = new Backbone.Model()
      this.resultHeadersView = new ResultHeadersView({
        collection: this.resultHeaders
      })
      this.resultRowsView = new ResultRowsView({
        collection: this.resultsCollection
      })

      this.listenTo(this.resultsCollection, 'reset', this.setHeadersAndOrderRowData)
      this.listenTo(this.resultsCollection, 'sendCurrentWidth', this.setGreatestWidthForHeader)
      this.listenTo(this.resultRowsView, 'resultsChange', this.dynamicResize)
    },

    template: Handlebars.templates['query/results_layout'],

    className: 'results-table',

    regions: {
      'headers': '.result-headers',
      'rows': '.result-rows'
    },

    events: {

    },

    bindings: {

    },

    setGreatestWidthForHeader(width, index) {
      var currentHeader = this.resultHeaders.at(index)

      if (currentHeader.get("width") < width) currentHeader.set("width", width)
    },

    assignHeaderModelsInitialWidths: function() {
      this.resultHeaders.each(function(header, index) {
        var currentHeaderWidth = $(this.resultHeadersView.el.childNodes[index]).outerWidth()
        header.set("width", currentHeaderWidth)
      }, this)
    },

    dynamicResize: function() {
      // FIRST LOOP THROUGH AND GET GREATEST WIDTH & SET HEADER WIDTH
      _.each(this.resultRowsView.el.childNodes, function(tr) {
        this.resultHeaders.each(function(header, index) {
          var currentRowDataWidth = $($(tr).children()[index]).outerWidth()
          if (header.get("width") < currentRowDataWidth)
            header.set("width", currentRowDataWidth)
        }, this)
      }, this)
      // SECOND LOOP THROUGH AND SET WIDTH TO DATA
      this.resultsCollection.each(function(result) {
        this.resultHeaders.each(function(header, index) {
          result.get("tableDataCollection").at(index).set("width", header.get("width"))
        })
      }, this)
    },

    setHeadersAndOrderRowData: function() {
      var view = this

      var setHeadersCollection = function() {
        view.resultsCollection.each(function(result) {
          result.get("tableDataCollection").each(function(data) {
            var dataHeader = data.get("header")
            if (!view.resultHeaders.findWhere({header: dataHeader}))
              view.resultHeaders.add(new Backbone.Model({header: dataHeader}))
          })
        })
      }
      setHeadersCollection()

      var fillInResultRowBlanks = function () {
        view.resultsCollection.each(function(row) {
          view.resultHeaders.each(function(header, index) {
            var currentHeaderDataModel = row.get("tableDataCollection").findWhere({header: header.get("header")})
            if (!(currentHeaderDataModel && row.get("tableDataCollection").indexOf(currentHeaderDataModel) == index)) {
              row.get("tableDataCollection").add(new Backbone.Model({
                header: header.get("header"),
                value: "Undefined"
              }), { at: index })
            }
          })
        })
      }
      fillInResultRowBlanks()
      this.assignHeaderModelsInitialWidths()
    },

    onDestroy: function() {

    },

    render: function() {
      this.unstickit()
      Backbone.Marionette.LayoutView.prototype.render.call(this)
      this.headers.show(this.resultHeadersView)
      this.rows.show(this.resultRowsView)
      this.stickit()
    }
  })

  return ResultsView
})<commit_msg>Removes methods that I'm no longer using<commit_after>
define(['ResultHeadersView', 'ResultRowsView'], function(ResultHeadersView, ResultRowsView) {

  var ResultsView = Backbone.Marionette.LayoutView.extend({
    initialize: function(options) {
      this.options = options
      this.resultsCollection = this.options.results
      this.resultHeaders = new Backbone.Collection()
      // this.resultRows = new Backbone.Collection()
      this.model = new Backbone.Model()
      this.resultHeadersView = new ResultHeadersView({
        collection: this.resultHeaders
      })
      this.resultRowsView = new ResultRowsView({
        collection: this.resultsCollection
      })

      this.listenTo(this.resultsCollection, 'reset', this.setHeadersAndOrderRowData)
      this.listenTo(this.resultsCollection, 'sendCurrentWidth', this.setGreatestWidthForHeader)
      this.listenTo(this.resultRowsView, 'resultsChange', this.dynamicResize)
    },

    template: Handlebars.templates['query/results_layout'],

    className: 'results-table',

    regions: {
      'headers': '.result-headers',
      'rows': '.result-rows'
    },

    events: {

    },

    bindings: {

    },

    setGreatestWidthForHeader(width, index) {
      var currentHeader = this.resultHeaders.at(index)

      if (currentHeader.get("width") < width) currentHeader.set("width", width)
    },

    assignHeaderModelsInitialWidths: function() {
      this.resultHeaders.each(function(header, index) {
        var currentHeaderWidth = $(this.resultHeadersView.el.childNodes[index]).outerWidth()
        header.set("width", currentHeaderWidth)
      }, this)
    },

    dynamicResize: function() {
      this.resultsCollection.each(function(result) {
        this.resultHeaders.each(function(header, index) {
          result.get("tableDataCollection").at(index).set("width", header.get("width"))
        })
      }, this)
    },

    setHeadersAndOrderRowData: function() {
      var view = this

      var setHeadersCollection = function() {
        view.resultsCollection.each(function(result) {
          result.get("tableDataCollection").each(function(data) {
            var dataHeader = data.get("header")
            if (!view.resultHeaders.findWhere({header: dataHeader}))
              view.resultHeaders.add(new Backbone.Model({header: dataHeader}))
          })
        })
      }
      setHeadersCollection()

      var fillInResultRowBlanks = function () {
        view.resultsCollection.each(function(row) {
          view.resultHeaders.each(function(header, index) {
            var currentHeaderDataModel = row.get("tableDataCollection").findWhere({header: header.get("header")})
            if (!(currentHeaderDataModel && row.get("tableDataCollection").indexOf(currentHeaderDataModel) == index)) {
              row.get("tableDataCollection").add(new Backbone.Model({
                header: header.get("header"),
                value: "Undefined"
              }), { at: index })
            }
          })
        })
      }
      fillInResultRowBlanks()
      this.assignHeaderModelsInitialWidths()
    },

    onDestroy: function() {

    },

    render: function() {
      this.unstickit()
      Backbone.Marionette.LayoutView.prototype.render.call(this)
      this.headers.show(this.resultHeadersView)
      this.rows.show(this.resultRowsView)
      this.stickit()
    }
  })

  return ResultsView
})<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import SelectedProjectView from './SelectedProjectView';
import Progress from 'react-progressbar';
import PrimesVisualView from './PrimesVisual';

class ProjectView extends Component {
  componentDidMount() {
    console.log('Fetching results for this project');
    this.props.socket.emit('fetchProjectResults', this.props.project.projectId);
  }

  connectToProject() {
    console.log('Joining...');
    this.props.socket.emit('userReady', this.props.project.projectId);
  }

  disconnectFromProject() {
    console.log(`Disconnecting from project: ${this.props.project['title']}`);
    this.props.socket.emit('userDisconnect');
    // TODO: terminate the existing worker
  }

  render() {

    let visualization;
    console.log('Project is:', this.props.project);
    console.log('Project type:', this.props.project.projectType);
    console.log('Project total number of jobs:', this.props.project.jobsLength);
    if (this.props.project.projectType === 'primes') {
      visualization = <PrimesVisualView />
    } else {
      visualization = undefined;
    }

    return (

        {visualization}
        <SelectedProjectView />
        Project View

        <button className="btn-success btn-lg" onClick={this.connectToProject.bind(this)}>Join</button>
        <button className="btn-danger btn-lg" onClick={this.disconnectFromProject.bind(this)}>Leave</button>

          Current number of jobs: {this.props.results.length === 0  ? 'Project is currently not in progress' : this.props.results.length}

          Total number of jobs: {this.props.results.length === 0 ? 'Project is currently not in progress': this.props.job.totalJobs}

          Progress: {this.props.results.length === 0 ? '0': Math.floor(this.props.results.length / this.props.job.totalJobs * 100 || 100)}
          %
          <Progress color='#3CC76A' completed={this.props.results.length === 0 ? 0 : this.props.results.length / this.props.job.totalJobs * 100 } />

        Final Result: {Array.isArray(this.props.results)? '' : this.props.results}

    );
  }
}

function mapStateToProps(state) {
  return {
    project: state.selectedProject,
    socket: state.createdSocket,
    results: state.updateResults,
    job: state.updateJob
  }
}

export default connect(mapStateToProps)(ProjectView);
<commit_msg>added router<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import SelectedProjectView from './SelectedProjectView';
import Progress from 'react-progressbar';
import PrimesVisualView from './PrimesVisual';

class ProjectView extends Component {
  componentDidMount() {
    console.log('Fetching results for this project');
    this.props.socket.emit('fetchProjectResults', this.props.project.projectId);
  }

  connectToProject() {
    console.log('Joining...');
    this.props.socket.emit('userReady', this.props.project.projectId);
  }

  disconnectFromProject() {
    console.log(`Disconnecting from project: ${this.props.project['title']}`);
    this.props.socket.emit('userDisconnect');
    // TODO: terminate the existing worker
  }

  render() {

    if (this.props.project === null) {
      this.context.router.push('menu');
    } else {
      let visualization;
      console.log('Project is:', this.props.project);
      console.log('Project type:', this.props.project.projectType);
      console.log('Project total number of jobs:', this.props.project.jobsLength);
      if (this.props.project.projectType === 'primes') {
        visualization = <PrimesVisualView />
      } else {
        visualization = undefined;
      }
      return (

          {visualization}
          <SelectedProjectView />
          Project View

          <button className="btn-success btn-lg" onClick={this.connectToProject.bind(this)}>Join</button>
          <button className="btn-danger btn-lg" onClick={this.disconnectFromProject.bind(this)}>Leave</button>

            Current number of jobs: {this.props.results.length === 0  ? 'Project is currently not in progress' : this.props.results.length}

            Total number of jobs: {this.props.results.length === 0 ? 'Project is currently not in progress': this.props.job.totalJobs}

            Progress: {this.props.results.length === 0 ? '0': Math.floor(this.props.results.length / this.props.job.totalJobs * 100 || 100)}
            %
            <Progress color='#3CC76A' completed={this.props.results.length === 0 ? 0 : this.props.results.length / this.props.job.totalJobs * 100 } />

          Final Result: {Array.isArray(this.props.results)? '' : this.props.results}

      );
    }
  }
}

// Attach router to context
ProjectView.contextTypes = {
  router: PropTypes.object.isRequired
};

function mapStateToProps(state) {
  return {
    project: state.selectedProject,
    socket: state.createdSocket,
    results: state.updateResults,
    job: state.updateJob
  }
}

export default connect(mapStateToProps)(ProjectView);
<|endoftext|>


<commit_before>/*
 * dependencies: jquery, backbonejs, window.sliMpd.modules.PageView
 */
(function() {
    "use strict";

    var $ = window.jQuery;
    window.sliMpd = $.extend(true, window.sliMpd, {
        modules : {}
    });
    window.sliMpd.modules.Router = window.Backbone.Router.extend({

    	rendered : false,
    	ajaxLoading : false,

        currentView : null,
        previousView : null,
        $content : null,
        $body : null,

        routes : {
            '' : 'generic',
            '*generic' : 'generic',
            // 'albums/(*generic)' : 'album'
        },

        initialize : function(options) {
            this.$content = $('#main');
            this.$body = $('body');
        },

        navigate : function(fragment, options) {

        	if (this.ajaxLoading) {
        		return;
        	}

        	/*
        	 * work against backbone's default behaviour - begin
        	 *
        	 * force rendering of view - even if we request the same (current) route again
        	 * without pushing this to history
        	 */
        	var pathStripper = /#.*$/;

			// Normalize the fragment.
			fragment = Backbone.history.getFragment(fragment || '');

			// Don't include a trailing slash on the root.
			var rootPath = Backbone.history.root;
			if (fragment === '' || fragment.charAt(0) === '?') {
				rootPath = rootPath.slice(0, -1) || '/';
			}
			var url = rootPath + fragment;

			// Strip the hash and decode for matching.
			fragment = Backbone.history.decodeFragment(fragment.replace(pathStripper, ''));
			if (Backbone.history.fragment === fragment) {
				Backbone.history.loadUrl(fragment);
				return;
			}
			/* work against backbone's default behaviour - end */

        	window.Backbone.Router.prototype.navigate.call(this, fragment, options);
        },

        generic : function(route, queryString) {
        	var name = ((route === null) ? 'home' : route + '?' + queryString),
        		url = '/' + ((route === null) ? '' : route + '?' + queryString);

            // remove view on ajax-done
            this.previousView = (this.currentView) ? this.currentView : null;

            // first time page loaded markup is delivered by backend, no need for ajax call!
            if (!this.rendered) {
	            this.currentView = new window.sliMpd.modules.PageView({
	                name : name,
	                templateString : '',
	                el : '#main>.main-content'
	            });
	            this.currentView.render(false); // renderMarkup flag false, to prevent markup re-rendering
	            this.rendered = true;
	            return;
            }

            // TODO: add proper loading animation
            this.$body.addClass('is-loading');
			$('

').appendTo(this.$body);
			this.ajaxLoading = true;
			$.ajax({
				url: window.sliMpd.setGetParameter(url, 'nosurrounding', '1')
			}).done(function(response) {
				if(this.previousView) {
					this.previousView.remove()
				}
	            this.currentView = new window.sliMpd.modules.PageView({
	                name : name,
	                templateString : response
	            });
	            this.currentView.render(true);
	            this.$content.html(this.currentView.$el);
	            this.$body.removeClass('is-loading');
				$("#loading-backdrop").remove();
				this.ajaxLoading = false;
			}.bind(this))
			.fail(function() {
				this.$body.removeClass('is-loading');
				$("#loading-backdrop").remove();
				this.ajaxLoading = false;
				window.sliMpd.notifyError(url);
    			return;
  			}.bind(this));
        },

        album : function(album) {
            if (this.currentView && this.currentView.name === 'album/' + album) {
                return;
            }
            if (this.currentView) {
                this.currentView.remove();
            }

            this.currentView = new window.sliMpd.modules.AlbumView({
                name : 'album/' + album,
                templateString : '' // TODO : get content via ajax
            });
            this.currentView.render();
            this.$content.html(this.currentView.$el);
        },
        // FIXME: how to refresh #main view without pushing anything to history?
        refreshIfName : function(routename) {
        	return;
        	if(this.currentView.name !== routename) {
        		console.log('Router::refreshIfName(' + routename + ') does not match ' + this.currentView.name);
        		return;
        	}
        	this.currentView.rendered = false;
        	this.navigate($el.attr(sliMpd.router.$body.context.location.pathname), {
                trigger : true
            });
        	//this.currentView.rendered = false;
        	//this.currentView.render(true);
        },

        // replacing backbones _extractParameters() method
        //    original method: "%2B" gets replaced with "+"
        //    overidden method: "%2B" gets preserved
        // TODO: combinations of "%" and "#" and "\" in urls still does not work
        // @see: issue #3
        _extractParameters: function(route, fragment) {
	      var params = route.exec(fragment).slice(1);
	      return _.map(params, function(param, i) {
	        // Don't decode the search params.
	        if (i === params.length - 1) return param || null;

	        return param
	        	? decodeURIComponent(param)
	        		.replace('%', '%25')
	        		.replace('#', '%23')
	        		.replace('+', '%2B')
	        		.replace('?', '%3F')
	        	: null;
	      });
	    }
    });

})();<commit_msg>BUGFIX multiple occurences of specific special chars in dirnames<commit_after>/*
 * dependencies: jquery, backbonejs, window.sliMpd.modules.PageView
 */
(function() {
    "use strict";

    var $ = window.jQuery;
    window.sliMpd = $.extend(true, window.sliMpd, {
        modules : {}
    });
    window.sliMpd.modules.Router = window.Backbone.Router.extend({

    	rendered : false,
    	ajaxLoading : false,

        currentView : null,
        previousView : null,
        $content : null,
        $body : null,

        routes : {
            '' : 'generic',
            '*generic' : 'generic',
            // 'albums/(*generic)' : 'album'
        },

        initialize : function(options) {
            this.$content = $('#main');
            this.$body = $('body');
        },

        navigate : function(fragment, options) {

        	if (this.ajaxLoading) {
        		return;
        	}

        	/*
        	 * work against backbone's default behaviour - begin
        	 *
        	 * force rendering of view - even if we request the same (current) route again
        	 * without pushing this to history
        	 */
        	var pathStripper = /#.*$/;

			// Normalize the fragment.
			fragment = Backbone.history.getFragment(fragment || '');

			// Don't include a trailing slash on the root.
			var rootPath = Backbone.history.root;
			if (fragment === '' || fragment.charAt(0) === '?') {
				rootPath = rootPath.slice(0, -1) || '/';
			}
			var url = rootPath + fragment;

			// Strip the hash and decode for matching.
			fragment = Backbone.history.decodeFragment(fragment.replace(pathStripper, ''));
			if (Backbone.history.fragment === fragment) {
				Backbone.history.loadUrl(fragment);
				return;
			}
			/* work against backbone's default behaviour - end */

        	window.Backbone.Router.prototype.navigate.call(this, fragment, options);
        },

        generic : function(route, queryString) {
        	var name = ((route === null) ? 'home' : route + '?' + queryString),
        		url = '/' + ((route === null) ? '' : route + '?' + queryString);

            // remove view on ajax-done
            this.previousView = (this.currentView) ? this.currentView : null;

            // first time page loaded markup is delivered by backend, no need for ajax call!
            if (!this.rendered) {
	            this.currentView = new window.sliMpd.modules.PageView({
	                name : name,
	                templateString : '',
	                el : '#main>.main-content'
	            });
	            this.currentView.render(false); // renderMarkup flag false, to prevent markup re-rendering
	            this.rendered = true;
	            return;
            }

            // TODO: add proper loading animation
            this.$body.addClass('is-loading');
			$('

').appendTo(this.$body);
			this.ajaxLoading = true;
			$.ajax({
				url: window.sliMpd.setGetParameter(url, 'nosurrounding', '1')
			}).done(function(response) {
				if(this.previousView) {
					this.previousView.remove()
				}
	            this.currentView = new window.sliMpd.modules.PageView({
	                name : name,
	                templateString : response
	            });
	            this.currentView.render(true);
	            this.$content.html(this.currentView.$el);
	            this.$body.removeClass('is-loading');
				$("#loading-backdrop").remove();
				this.ajaxLoading = false;
			}.bind(this))
			.fail(function() {
				this.$body.removeClass('is-loading');
				$("#loading-backdrop").remove();
				this.ajaxLoading = false;
				window.sliMpd.notifyError(url);
    			return;
  			}.bind(this));
        },

        album : function(album) {
            if (this.currentView && this.currentView.name === 'album/' + album) {
                return;
            }
            if (this.currentView) {
                this.currentView.remove();
            }

            this.currentView = new window.sliMpd.modules.AlbumView({
                name : 'album/' + album,
                templateString : '' // TODO : get content via ajax
            });
            this.currentView.render();
            this.$content.html(this.currentView.$el);
        },
        // FIXME: how to refresh #main view without pushing anything to history?
        refreshIfName : function(routename) {
        	return;
        	if(this.currentView.name !== routename) {
        		console.log('Router::refreshIfName(' + routename + ') does not match ' + this.currentView.name);
        		return;
        	}
        	this.currentView.rendered = false;
        	this.navigate($el.attr(sliMpd.router.$body.context.location.pathname), {
                trigger : true
            });
        	//this.currentView.rendered = false;
        	//this.currentView.render(true);
        },

        // replacing backbones _extractParameters() method
        //    original method: "%2B" gets replaced with "+"
        //    overidden method: "%2B" gets preserved
        // TODO: combinations of "%" and "#" and "\" in urls still does not work
        // @see: issue #3
        _extractParameters: function(route, fragment) {
	      var params = route.exec(fragment).slice(1);
	      return _.map(params, function(param, i) {
	        // Don't decode the search params.
	        if (i === params.length - 1) return param || null;

	        return param
	        	? decodeURIComponent(param)
	        		.replace(/%/g, '%25')
	        		.replace(/#/g, '%23')
	        		.replace(/\+/g, '%2B')
	        		.replace(/\?/g, '%3F')
	        	: null;
	      });
	    }
    });

})();<|endoftext|>


<commit_before>/**
 * Manager's plugin, which tracks amount of energy in a world and updates it.
 *
 * @author flatline
 */
const Helper  = require('./../../../../common/src/Helper');
const Config  = require('./../../share/Config').Config;
const Console = require('./../../share/Console');
const EVENTS  = require('./../../share/Events').EVENTS;

const POSID   = Helper.posId;

class Energy {
    constructor(manager) {
        this._manager       = manager;
        this._lastX         = -1;
        this._lastY         = -1;
        this._onIterationCb = this._onIteration.bind(this);

        Helper.override(manager, 'onIteration', this._onIterationCb);
    }

    destroy() {
        Helper.unoverride(this._manager, 'onIteration', this._onIterationCb);
        this._manager       = null;
        this._onIterationCb = null;
    }

    _onIteration(counter) {
        this._updateAliveEnergy();
        if (counter % Config.worldEnergyCheckPeriod !== 0 || Config.worldEnergyCheckPeriod === 0) {return}
        if (counter === 0) {
            this._updateEnergy(Config.worldEnergyDots, Config.worldEnergyInDot);
            return;
        }
        let   energy = 0;
        const world  = this._manager.world;
        const width  = Config.worldWidth;
        const height = Config.worldHeight;

        for (let x = 0; x < width; x++) {
            for (let y = 0; y < height; y++) {
                if (world.getDot(x, y) > 0) {energy++}
            }
        }

        if (energy / (width * height) <= Config.worldEnergyCheckPercent) {
            this._updateEnergy(Config.worldEnergyDots, Config.worldEnergyInDot);
        }
    }

    _updateEnergy(dotAmount, energyInDot) {
        const world  = this._manager.world;
        const width  = Config.worldWidth;
        const height = Config.worldHeight;
        const rand   = Helper.rand;
        let   x;
        let   y;

        Console.info('Creating random energy');
        for (let dot = 0; dot < dotAmount; dot++) {
            x = rand(width);
            y = rand(height);
            if (world.getDot(x, y) < 1) {
                world.setDot(x, y, energyInDot);
            }
        }
        this._manager.fire(EVENTS.UPDATE_ENERGY);
    }

    _updateAliveEnergy() {
        const x         = this._lastX >= 0 ? this._lastX : Helper.rand(Config.worldWidth);
        const y         = this._lastY >= 0 ? this._lastY : Helper.rand(Config.worldHeight);
        const world     = this._manager.world;
        const positions = this._manager.positions;
        const dot       = world.getDot(x, y);

        if (typeof(positions[POSID(x, y)]) === 'undefined') {
            dot === 0 && world.setDot(x, y, Config.worldEnergyInDot);
            this._lastX = x + Helper.rand(3) - 1;
            this._lastY = y + Helper.rand(3) - 1;
            if (world.getDot(this._lastX, this._lastY) === 0) {world.setDot(this._lastX, this._lastY, dot)}
            return;
        }
        this._lastX = this._lastY = -1;
    }
}

module.exports = Energy;<commit_msg>fixed an issue of out of world energy<commit_after>/**
 * Manager's plugin, which tracks amount of energy in a world and updates it.
 *
 * @author flatline
 */
const Helper  = require('./../../../../common/src/Helper');
const Config  = require('./../../share/Config').Config;
const Console = require('./../../share/Console');
const EVENTS  = require('./../../share/Events').EVENTS;

const POSID   = Helper.posId;

class Energy {
    constructor(manager) {
        this._manager       = manager;
        this._lastX         = -1;
        this._lastY         = -1;
        this._onIterationCb = this._onIteration.bind(this);

        Helper.override(manager, 'onIteration', this._onIterationCb);
    }

    destroy() {
        Helper.unoverride(this._manager, 'onIteration', this._onIterationCb);
        this._manager       = null;
        this._onIterationCb = null;
    }

    _onIteration(counter) {
        this._updateAliveEnergy();
        if (counter % Config.worldEnergyCheckPeriod !== 0 || Config.worldEnergyCheckPeriod === 0) {return}
        if (counter === 0) {
            this._updateEnergy(Config.worldEnergyDots, Config.worldEnergyInDot);
            return;
        }
        let   energy = 0;
        const world  = this._manager.world;
        const width  = Config.worldWidth;
        const height = Config.worldHeight;

        for (let x = 0; x < width; x++) {
            for (let y = 0; y < height; y++) {
                if (world.getDot(x, y) > 0) {energy++}
            }
        }

        if (energy / (width * height) <= Config.worldEnergyCheckPercent) {
            this._updateEnergy(Config.worldEnergyDots, Config.worldEnergyInDot);
        }
    }

    _updateEnergy(dotAmount, energyInDot) {
        const world  = this._manager.world;
        const width  = Config.worldWidth;
        const height = Config.worldHeight;
        const rand   = Helper.rand;
        let   x;
        let   y;

        Console.info('Creating random energy');
        for (let dot = 0; dot < dotAmount; dot++) {
            x = rand(width);
            y = rand(height);
            if (world.getDot(x, y) < 1) {
                world.setDot(x, y, energyInDot);
            }
        }
        this._manager.fire(EVENTS.UPDATE_ENERGY);
    }

    _updateAliveEnergy() {
        const x         = this._lastX >= 0 ? this._lastX : Helper.rand(Config.worldWidth);
        const y         = this._lastY >= 0 ? this._lastY : Helper.rand(Config.worldHeight);
        const world     = this._manager.world;
        const positions = this._manager.positions;
        const dot       = world.getDot(x, y);

        if (x < 0 || x >= Config.worldWidth)  {this._lastX = -1; return}
        if (y < 0 || y >= Config.worldHeight) {this._lastY = -1; return}

        if (typeof(positions[POSID(x, y)]) === 'undefined') {
            dot === 0 && world.setDot(x, y, Config.worldEnergyInDot);
            this._lastX = x + Helper.rand(3) - 1;
            this._lastY = y + Helper.rand(3) - 1;
            if (world.getDot(this._lastX, this._lastY) === 0) {world.setDot(this._lastX, this._lastY, dot)}
            return;
        }
        this._lastX = this._lastY = -1;
    }
}

module.exports = Energy;<|endoftext|>


<commit_before>/* =========================================================
 * bootstrap-pincode-input.js
 *
 * =========================================================
 * Created by Ferry Kranenburg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

;(function ( $, window, document, undefined ) {

	"use strict";

		// Create the defaults once
		var pluginName = "pincodeInput";
		var defaults = {
		    	inputs:4,									    // 4 input boxes = code of 4 digits long
		    	hideDigits:true,								// hide digits
		    	keydown : function(e){},
		        complete : function(value, e, errorElement){// callback when all inputs are filled in (keyup event)
		    		//value = the entered code
		    		//e = last keyup event
		    		//errorElement = error span next to to this, fill with html e.g. : $(errorElement).html("Code not correct");
		    	}
		    };

		// The actual plugin constructor
		function Plugin ( element, options ) {
				this.element = element;
				this.settings = $.extend( {}, defaults, options );
				this._defaults = defaults;
				this._name = pluginName;
				this.init();
		}

		// Avoid Plugin.prototype conflicts
		$.extend(Plugin.prototype, {
				init: function () {
					this.buildInputBoxes();
				},
		        updateOriginalInput:function(){
		        	var newValue = "";
		        	$('.pincode-input-text',this._container).each(function( index, value ) {
		        		newValue += $(value).val().toString();
		        	});
		        	$(this.element).val(newValue);
		        },
		        check: function(){
		        	var isComplete = true;
		        	$('.pincode-input-text',this._container).each(function( index, value ) {
		        		if(!$(value).val()){
		        			isComplete = false;
		        		}
		        	});

		        	return isComplete;
		        },
				buildInputBoxes: function () {

		        	this._container = $('<div />').addClass('pincode-input-container');

							var currentValue = [];
							// If we do not hide digits, we need to include the current value of the input box
							// This will only work if the current value is not longer than the number of input boxes.
							if( this.settings.hideDigits == false && $(this.element).val() !=""){
								currentValue = $(this.element).val().split("");
							}

							// make sure this is the first password field here
							if(this.settings.hideDigits){
									this._pwcontainer = $('<div />').css("display", "none").appendTo(this._container);
									this._pwfield = $('<input>').attr({'type':'password','id':'preventautofill','autocomplete':'off'}).appendTo(this._pwcontainer);
							}

		        	for (var i = 0; i <  this.settings.inputs; i++) {

		        		var input = $('<input>').attr({'type':'text','maxlength':"1",'autocomplete':'off'}).addClass('form-control pincode-input-text').appendTo(this._container);
		        		if(this.settings.hideDigits){
									// hide digits
		        			input.attr('type','password');
		        		}else{
									// show digits, also include default value
									input.val(currentValue[i]);
								}

		        		if(i==0){
		        			input.addClass('first');
		        		}else if(i==(this.settings.inputs-1)){
		        			input.addClass('last');
		        		}else{
		        			input.addClass('mid');
		        		}

		        		input.on('focus',function(e){
		        			 this.select();  //automatically select current value
		            });

		        		input.on('keydown', $.proxy(function(e){
										if(this._pwfield){
											// Because we need to prevent password saving by browser
											// remove the value here and change the type!
											// we do this every time the user types
											$(this._pwfield).attr({'type':'text'});
											$(this._pwfield).val("");
										}

									 this.settings.keydown(e);
		            },this));

		        		input.on('keyup', $.proxy(function(e){
				        			// after every keystroke we check if all inputs have a value, if yes we call complete callback

				        			// on backspace go to previous input box
				        			if(e.keyCode == 8 || e.keyCode == 48){
				        				// goto previous
				        				$(e.currentTarget).prev().select();
				    					$(e.currentTarget).prev().focus();
				        			}else{
				        				if($(e.currentTarget).val()!=""){
				            				$(e.currentTarget).next().select();
				        					$(e.currentTarget).next().focus();
				        				}
				        			}

											// update original input box
				        			this.updateOriginalInput();

				        			if(this.check()){
				        				this.settings.complete($(this.element).val(), e, this._error);
				        			}
				        },this));

		        	}

		        	// error box
		        	this._error = $('<div />').addClass('text-danger pincode-input-error').appendTo(this._container);

		        	//hide original element and place this before it
		        	$(this.element).css( "display", "none" );
		            this._container.insertBefore(this.element);
				},
				enable:function(){
					 $('.pincode-input-text',this._container).each(function( index, value ) {
								$(value).prop('disabled', false);
					});
				},
				disable:function(){
					 $('.pincode-input-text',this._container).each(function( index, value ) {
								$(value).prop('disabled', true);
					});
				},
				focus:function(){
					$('.pincode-input-text',this._container).first().select().focus();
				},
				clear:function(){
					 $('.pincode-input-text',this._container).each(function( index, value ) {
		         		$(value).val("");
		         	});
		         	this.updateOriginalInput();
				}

		});

		// A really lightweight plugin wrapper around the constructor,
		// preventing against multiple instantiations
		$.fn[ pluginName ] = function ( options ) {
				return this.each(function() {
						if ( !$.data( this, "plugin_" + pluginName ) ) {
								$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
						}
				});
		};

})( jQuery, window, document );
<commit_msg>For mobile devices use normal text input<commit_after>/* =========================================================
 * bootstrap-pincode-input.js
 *
 * =========================================================
 * Created by Ferry Kranenburg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

;(function ( $, window, document, undefined ) {

	"use strict";

		// Create the defaults once
		var pluginName = "pincodeInput";
		var defaults = {
		    	inputs:4,									    // 4 input boxes = code of 4 digits long
		    	hideDigits:true,								// hide digits
		    	keydown : function(e){},
		        complete : function(value, e, errorElement){// callback when all inputs are filled in (keyup event)
		    		//value = the entered code
		    		//e = last keyup event
		    		//errorElement = error span next to to this, fill with html e.g. : $(errorElement).html("Code not correct");
		    	}
		    };

		// The actual plugin constructor
		function Plugin ( element, options ) {
				this.element = element;
				this.settings = $.extend( {}, defaults, options );
				this._defaults = defaults;
				this._name = pluginName;
				this.init();
		}

		// Avoid Plugin.prototype conflicts
		$.extend(Plugin.prototype, {
				init: function () {
					this.buildInputBoxes();
				},
		        updateOriginalInput:function(){
		        	var newValue = "";
		        	$('.pincode-input-text',this._container).each(function( index, value ) {
		        		newValue += $(value).val().toString();
		        	});
		        	$(this.element).val(newValue);
		        },
		        check: function(){
		        	var isComplete = true;
		        	$('.pincode-input-text',this._container).each(function( index, value ) {
		        		if(!$(value).val()){
		        			isComplete = false;
		        		}
		        	});

		        	return isComplete;
		        },
				buildInputBoxes: function () {

		        	this._container = $('<div />').addClass('pincode-input-container');

					var currentValue = [];
					// If we do not hide digits, we need to include the current value of the input box
					// This will only work if the current value is not longer than the number of input boxes.
					if( this.settings.hideDigits == false && $(this.element).val() !=""){
						currentValue = $(this.element).val().split("");
					}

					// make sure this is the first password field here
					if(this.settings.hideDigits){
							this._pwcontainer = $('<div />').css("display", "none").appendTo(this._container);
							this._pwfield = $('<input>').attr({'type':'password','id':'preventautofill','autocomplete':'off'}).appendTo(this._pwcontainer);
					}

					if(this._isTouchDevice()){
						var input = $('<input>').attr({'type':'text','maxlength':this.settings.inputs,'autocomplete':'off'}).addClass('form-control pincode-input-text first last').appendTo(this._container);
		        		if(this.settings.hideDigits){
									// hide digits
		        			input.attr('type','password');
		        		}else{
							// show digits, also include default value
							input.val(currentValue[i]);
						}

		        		// add events
		        		this._addEventsToInput(input);

					}else{
						// for desktop mode we build one input for each digit
			        	for (var i = 0; i <  this.settings.inputs; i++) {

			        		var input = $('<input>').attr({'type':'text','maxlength':"1",'autocomplete':'off'}).addClass('form-control pincode-input-text').appendTo(this._container);
			        		if(this.settings.hideDigits){
										// hide digits
			        			input.attr('type','password');
			        		}else{
								// show digits, also include default value
								input.val(currentValue[i]);
							}

			        		if(i==0){
			        			input.addClass('first');
			        		}else if(i==(this.settings.inputs-1)){
			        			input.addClass('last');
			        		}else{
			        			input.addClass('mid');
			        		}

			        		// add events
			        		this._addEventsToInput(input);
			        	}
					}

		        	// error box
		        	this._error = $('<div />').addClass('text-danger pincode-input-error').appendTo(this._container);

		        	//hide original element and place this before it
		        	$(this.element).css( "display", "none" );
		            this._container.insertBefore(this.element);
				},
				enable:function(){
					 $('.pincode-input-text',this._container).each(function( index, value ) {
								$(value).prop('disabled', false);
					});
				},
				disable:function(){
					 $('.pincode-input-text',this._container).each(function( index, value ) {
								$(value).prop('disabled', true);
					});
				},
				focus:function(){
					$('.pincode-input-text',this._container).first().select().focus();
				},
				clear:function(){
					 $('.pincode-input-text',this._container).each(function( index, value ) {
		         		$(value).val("");
		         	});
		         	this.updateOriginalInput();
				},
				_isTouchDevice:function(){
					// I know, sniffing is a really bad idea, but it works 99% of the times
					if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
					 	return true;
					}
				},
				_addEventsToInput:function(input){

	        		input.on('focus',function(e){
	        			 this.select();  //automatically select current value
	        		});

	        		input.on('keydown', $.proxy(function(e){
							if(this._pwfield){
								// Because we need to prevent password saving by browser
								// remove the value here and change the type!
								// we do this every time the user types
								$(this._pwfield).attr({'type':'text'});
								$(this._pwfield).val("");
							}

						 this.settings.keydown(e);
		            },this));

	        		input.on('keyup', $.proxy(function(e){
			        	// after every keystroke we check if all inputs have a value, if yes we call complete callback

	        			// on backspace go to previous input box
	        			if(e.keyCode == 8 || e.keyCode == 48){
	        				// goto previous
	        				$(e.currentTarget).prev().select();
	    					$(e.currentTarget).prev().focus();
	        			}else{
	        				if($(e.currentTarget).val()!=""){
	            				$(e.currentTarget).next().select();
	        					$(e.currentTarget).next().focus();
	        				}
	        			}

								// update original input box
	        			this.updateOriginalInput();

	        			if(this.check()){
	        				this.settings.complete($(this.element).val(), e, this._error);
	        			}
			        },this));
				}

		});

		// A really lightweight plugin wrapper around the constructor,
		// preventing against multiple instantiations
		$.fn[ pluginName ] = function ( options ) {
				return this.each(function() {
						if ( !$.data( this, "plugin_" + pluginName ) ) {
								$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
						}
				});
		};

})( jQuery, window, document );
<|endoftext|>