text:
function events(args) {
	var Cloud = require('ti.cloud');
	var activityindicator_win = require("activityindicator_win");
	var obj_win = new activityindicator_win();
	var customFont = 'HouschkaAlt';
	var top_event_data = [];
	var search_friend_data = [];
	var friend_details_array = [];
	var arr_bar_name = [];
	var tmp_arr = [];
	var arr_friend_details = [];
	var arr_data = [];
	var photo_url = "/images/profilePlaceholder.png";
	search_friend_data = [{
		title : "None of your friends are currently attending events",
		font : {
			fontFamily : customFont,
			fontSize : 12,
			fontWeight : 'bold'
		}
	}];

	var events = Ti.UI.createWindow({
		barColor : '#3b5e34',
		backgroundColor : '#fff',
		translucent : false
	});
	var tabbedBar = Ti.UI.iOS.createTabbedBar({
		labels : ['Friends', 'Top Events'],
		backgroundColor : '#fff',
		style : Titanium.UI.iPhone.SystemButtonStyle.BAR,
		index : 0
	});
	events.setTitleControl(tabbedBar);

	//END REFRESH BUTTON FOR RELOAD DATA
	var refresh = Titanium.UI.createButton({

	});
	refresh.systemButton = Titanium.UI.iPhone.SystemButton.REFRESH;
	events.leftNavButton = refresh;

	refresh.addEventListener('click', function() {

		try {

			refresh.enabled = false;

			top_event_data = [];
			topEventsFeed.setData(top_event_data);
			friendsFeed.setData(search_friend_data);

			if (tabbedBar.index == 0) {
				search_friend_data = [];
				search_friend_data = [{
					title : "None of your friends are currently attending events",
					font : {
						fontFamily : customFont,
						fontSize : 12,
						fontWeight : 'bold'
					}
				}];
				friendsFeed.setData(search_friend_data);
				load_friends_list(null);

			} else {

				total_events = 0;
				total_events_array = [];
				top_event_data = [];
				top_event_data = [{
					title : "No one is currently attending an event",

					font : {
						fontFamily : customFont,
						fontSize : 12,
						fontWeight : 'bold'
					}
				}];

				topEventsFeed.setData(top_event_data);

				load_event_list(null);
			}

		} catch(ex) {
			refresh.enabled = true;

		}

	});

	//END REFRESH BUTTON FOR RELOAD DATA

	var friendsFeed = Ti.UI.createTableView({
		top : 0,
		height : '100%',
		width : '100%',
		id : 0,
		data : [],
		footerTitle : "",
		minRowHeight : 50

	});

	var topEventsFeed = Ti.UI.createTableView({
		top : 0,
		height : '100%',
		width : '100%',
		id : 1,
		data : [],
		footerTitle : "",
		minRowHeight : 50
	});

	events.add(topEventsFeed);
	events.add(friendsFeed);

	// SEARCH FRIEND SECTION
	function parseISO8601(str) {
		var parts = str.split('T');
		dateParts = parts[0].split('-');
		timeParts = parts[1].split('Z');
		timeSubParts = timeParts[0].split(':');
		timeSecParts = timeSubParts[2].split('.');
		timeHours = Number(timeSubParts[0]);
		var _date = new Date();

		_date.setUTCFullYear(Number(dateParts[0]));
		_date.setUTCMonth(Number(dateParts[1]) - 1);
		_date.setUTCDate(Number(dateParts[2]));
		_date.setUTCHours(Number(timeHours));
		_date.setUTCMinutes(Number(timeSubParts[1]));
		_date.setUTCSeconds(Number(timeSecParts[0]));
		if (timeSecParts[1])
			_date.setUTCMilliseconds(Number(timeSecParts[1]));

		return _date;

	};

	var event_time_calculation = function(date) {

		var offset = -5.0;
		//  parsing event-iso-8601-date-string-to-est-date-time
		var datestring = date;
		var c = datestring.split("+");
		var datestring = c[0] + ".0Z";
		var d = new Date(parseISO8601(datestring));
		var server_utc = d.getTime() + (d.getTimezoneOffset() * 60000);
		var event_create_date = new Date(server_utc + (3600000 * offset));

		var current_event_year = event_create_date.getFullYear();
		var current_event_month = event_create_date.getMonth();
		current_event_month += 1;
		var current_event_day = event_create_date.getDate();
		var current_event_hours = event_create_date.getHours();
		var hh_12_formate = current_event_hours - 12;
		current_event_hours = ((current_event_hours - 12) > -1) ? hh_12_formate : current_event_hours;
		var current_event_minutes = event_create_date.getMinutes();
		var current_event_seconds = event_create_date.getSeconds();

		//  parsing event-iso-8601-date-string-to-est-date-time

		//  parsing current-date-string-to-est-date-time

		var clientDate = new Date();
		var event_time = null;

		var utc = clientDate.getTime() + (clientDate.getTimezoneOffset() * 60000);
		var current_date = new Date(utc + (3600000 * offset));

		var current_date_year = current_date.getFullYear();
		var current_date_mounth = current_date.getMonth();
		var current_date_day = current_date.getDate();
		var current_date_hours = current_date.getHours();
		if (current_date_hours >= 12) {
			current_date_hours = (current_date_hours - 12);
		}

		var current_date_minutes = current_date.getMinutes();
		var current_date_seconds = current_date.getSeconds();

		//  parsing current-date-string-to-est-date-time

		if (current_date_year > current_event_year) {

			var diff_year = (current_date_year - current_event_year);
			if (diff_year && diff_year > 0) {
				if (diff_year > 1) {
					event_time = diff_year + " " + "years ago.";
				} else {
					event_time = diff_year + " " + "year ago.";
				}
			}

		} else if (current_date_year == current_event_year) {

			if ((current_date_mounth + 1) == current_event_month) {

				if (current_date_day == current_event_day) {

					if (current_date_hours == current_event_hours) {

						if (current_date_minutes <= current_event_minutes) {
							event_time = "1" + " " + "minute ago.";

						} else if (current_date_minutes > current_event_minutes) {
							var diff_min = (current_date_minutes - current_event_minutes);
							if (diff_min && diff_min > 1) {
								event_time = diff_min + " " + "minutes ago.";
							} else {
								event_time = diff_min + " " + "minute ago.";

							}
						}
					} else if (current_date_hours > current_event_hours) {

						var diff_hour = current_date_hours - current_event_hours;
						var diff_min = (current_date_minutes - current_event_minutes);
						event_time = ((diff_hour * 60) + diff_min);

						if (event_time < 60) {
							event_time = event_time + " " + "minutes ago.";
						} else if (Math.round(event_time / 60) == 1) {

							event_time = diff_hour + " " + "hour ago.";
						} else {
							event_time = diff_hour + " " + "hours ago.";
						}

					}

				} else if (current_date_day > current_event_day) {

					var diff_day = (current_date_day - current_event_day);
					if (diff_day && diff_day > 1) {
						event_time = diff_day + " " + "days ago.";
					} else {
						event_time = diff_day + " " + "day ago.";
					}

				}

			} else if ((current_date_mounth + 1) > current_event_minutes) {

				var diff_month = ((current_date_mounth + 1) - current_event_minutes);
				event_time = diff_month + " " + "month ago.";

			} else {
				//Ti.API.info("what happamns");
			}
		}

		return event_time;

	};

	var event_timeout = function(dd) {

		var offset = -5.0;
		var active_event = false;
		//  parsing event-iso-8601-date-string-to-est-date-time
		var datestring = dd;

		var c = datestring.split("+");
		var datestring = c[0] + ".0Z";

		var event_create_date = new Date(parseISO8601(datestring));
		///

		var new_date = new Date();
		var localOffset = (new_date.getTimezoneOffset() * 60000);

		var fooUTC = (event_create_date.getTime() + localOffset);

		var EAST = (3600000 * offset);
		event_create_date = new Date(fooUTC + EAST);

		///

		var current_event_year = event_create_date.getFullYear();
		var current_event_month = event_create_date.getMonth();
		current_event_month += 1;
		var current_event_day = event_create_date.getDate();
		var current_event_hours = event_create_date.getHours();

		var hh_12_formate = current_event_hours - 12;
		current_event_hours = ((current_event_hours - 12) > -1) ? hh_12_formate : current_event_hours;
		var current_event_minutes = event_create_date.getMinutes();
		var current_event_seconds = event_create_date.getSeconds();

		//  parsing event-iso-8601-date-string-to-est-date-time

		//  parsing current-date-string-to-est-date-time
		var event_Date = new Date();

		var utc = event_Date.getTime() + (event_Date.getTimezoneOffset() * 60000);
		var current_date = new Date(utc + (3600000 * offset));

		var current_date_year = current_date.getFullYear();
		var current_date_mounth = current_date.getMonth();
		var current_date_day = current_date.getDate();
		var current_date_hours = current_date.getHours();
		var current_date_minutes = current_date.getMinutes();
		var current_date_seconds = current_date.getSeconds();
		// var current_utc_date = new Date(current_date_year, current_date_mounth, current_date_day, current_date_hours, current_date_minutes, current_date_seconds);

		//new changes

		var hh_12_formate_current_date = current_date_hours - 12;
		current_date_hours = ((current_date_hours - 12) > -1) ? hh_12_formate_current_date : current_date_hours;

		///

		// Ti.API.info("Event_created_est="+event_create_date+"||" +"Local_est="+current_date);

		if (current_date_day == current_event_day) {

			if (current_event_hours < 4 && current_event_hours >= 0) {

				if (current_date_hours < 4) {
					active_event = true;
				} else if (current_date_hours == 3 && current_date_minutes > 55) {
					active_event = false;
				} else if (current_date_hours > 4 || current_date_hours == 4) {
					active_event = false;
				}

			} else if (current_event_hours == 3 && current_date_minutes > 55) {

				if (current_date_hours < 4) {
					active_event = true;
				} else if (current_date_hours == 3 && current_date_minutes > 55) {
					active_event = false;
				} else if ((current_date_hours == 4) && current_date_minutes <= 60) {
					active_event = false;
				} else if (current_date_hours > 4) {
					active_event = true;
				}
			} else if (current_event_hours > 4 || current_event_hours == 4) {

				if (current_date_hours < 4) {
					active_event = true;
				} else if (current_date_hours == 3 && current_date_minutes > 55) {
					active_event = false;
				} else if ((current_date_hours == 4) && current_date_minutes <= 60) {

					active_event = true;
				} else if (current_date_hours > 4) {
					active_event = true;
				}
			} else if (current_event_hours == 0) {
				active_event = true;
			}

		} else if (current_date_day > current_event_day) {

			if (current_event_hours < 4) {
				if (current_date_hours < 4) {
					active_event = true;
				} else if (current_date_hours == 3 && current_date_minutes > 55) {
					active_event = false;
				} else if (current_date_hours > 4 || current_date_hours == 4) {
					active_event = false;
				}

			} else if (current_event_hours == 4 || current_event_hours > 4) {
				if (current_date_hours < 4) {
					active_event = true;
				} else if (current_date_hours == 3 && current_date_minutes > 55) {
					active_event = false;
				} else if (current_date_hours > 4 || current_date_hours == 4) {
					active_event = false;
				}
			}
		}

		// Ti.API.info("active_event=" + JSON.stringify(active_event));

		return active_event;

	};

	var get_user_photo = function(user, call_back) {

		var id = user.user_id;
		var user_full_name = user.user_full_name;
		var bar_name = user.bar_name;
		var created_at = user.created_at;

		var photo_url = null;
		Cloud.Photos.search({
			user_id : id
		}, function(e) {
			if (e.success) {

				if (e.photos.length > 0) {
					var photo = e.photos[0];
					photo_url = photo.urls.square_75;

				} else {
					photo_url = "/images/profilePlaceholder.png";
				}
			} else {
				photo_url = "/images/profilePlaceholder.png";

			}
			call_back(user);
		});

	};

	function comp(a, b) {

		var offset = -5.0;

		var datestring_a = a.event_start_time;
		var c_a = datestring_a.split("+");
		var datestring_a = c_a[0] + ".0Z";
		var d_a = new Date(parseISO8601(datestring_a));
		var server_utc_a = d_a.getTime() + (d_a.getTimezoneOffset() * 60000);
		var event_create_date_a = new Date(server_utc_a + (3600000 * offset));

		var datestring_b = b.event_start_time;
		var c_b = datestring_b.split("+");
		var datestring_b = c_b[0] + ".0Z";
		var d_b = new Date(parseISO8601(datestring_b));
		var server_utc_b = d_b.getTime() + (d_b.getTimezoneOffset() * 60000);
		var event_create_date_b = new Date(server_utc_b + (3600000 * offset));

		Ti.API.info("a=" + new Date(event_create_date_a).getTime());
		Ti.API.info("b=" + new Date(event_create_date_b).getTime());

		return new Date(event_create_date_a).getTime() - new Date(event_create_date_b).getTime();

	}

	function compdate(a, b) {

		var offset = -5.0;

		var datestring_a = a.event_start_time;
		var c_a = datestring_a.split("+");
		var datestring_a = c_a[0] + ".0Z";
		var d_a = new Date(parseISO8601(datestring_a));
		var server_utc_a = d_a.getTime() + (d_a.getTimezoneOffset() * 60000);
		var event_create_date_a = new Date(server_utc_a + (3600000 * offset));

		var datestring_b = b.event_start_time;
		var c_b = datestring_b.split("+");
		var datestring_b = c_b[0] + ".0Z";
		var d_b = new Date(parseISO8601(datestring_b));
		var server_utc_b = d_b.getTime() + (d_b.getTimezoneOffset() * 60000);
		var event_create_date_b = new Date(server_utc_b + (3600000 * offset));

		return new Date(event_create_date_a).getTime() < new Date(event_create_date_b).getTime();

	}

	var arr_data = [];
	var load_friends_photo = function(user) {

		Ti.API.info("IN SIDE load_friends_photo");

		Cloud.Photos.search({
			user_id : user.user_id
		}, function(e) {
			if (e.success) {

				if (e.photos.length > 0) {
					var photo = e.photos[0];
					photo_url = photo.urls.square_75;

				} else {
					photo_url = "/images/profilePlaceholder.png";
				}

				var dataSet = {

					user_id : user.user_id,
					photo_url : photo_url,
					user_full_name : user.user_full_name,
					event_name : user.bar_name,
					event_start_time : user.created_at,
					user_event : event_time_calculation(user.created_at)

				};
				var data_tmp=[];
				search_friend_data=[];
				friendsFeed.setData(data_tmp);

				arr_data.push(dataSet);
				arr_data.sort(compdate);

				Ti.API.info("Length after sort="+arr_data.length);

					if (arr_data.length > 0) {

					//alert("helll");
					/*var j = (arr_data.length-1);
					if(j<0){

						j=0;
					}*/

					for( var k=0; k<arr_data.length;k++){

						Ti.API.info("J="+k +"||"+JSON.stringify(arr_data[k]));

						var row = Titanium.UI.createTableViewRow({
						//event_start_time : event_start_time
					});

					var user_image_view = Titanium.UI.createImageView({
						defaultImage : '/images/profilePlaceholder.png',
						image : arr_data[k].photo_url,
						width : 40,
						height : 40,
						left : 5,
						layout : "horizontal"
					});
					var container_view = Ti.UI.createView({
						top : 0,
						width : 270,
						left : 45,
						height : 50,
						layout : "vertical"
					});
					row.add(user_image_view);
					row.add(container_view);

					var user_text = arr_data[k].user_full_name + " " + "is attending" + " " + arr_data[k].event_name + ".";

					var lbl_user_text = Ti.UI.createLabel({
						left : 5,
						top : 2,
						height : 30,
						width : 260,
						text : user_text,
						color : "black",
						font : {
							fontFamily : customFont,
							fontSize : 12,
							fontWeight : 'bold'
						}
					});
					var lbl_user_event_text = Ti.UI.createLabel({
						left : 5,
						top : 0,
						height : 15,
						width : 265,
						text : arr_data[k].user_event,
						color : "#E75480",
						font : {
							fontFamily : customFont,
							fontSize : 12,
							fontWeight : 'normal'
						}
					});
					container_view.add(lbl_user_text);
					container_view.add(lbl_user_event_text);

					search_friend_data.push(row);

					}

					//friendsFeed.appendRow(row);

					//friendsFeed.getData().reverse();

					//alert("friendsFeed.data=" +JSON.stringify(friendsFeed.data[0]));

					friendsFeed.setData(search_friend_data);

				} else {

					Ti.API.info("NO need to check");
				}

			}

		});

	};

	//TODAY

	var load_friends_list = function(win) {

		try {
			if (Ti.Network.online) {
				var arr = [];
				arr_friend_details = [];
				arr_data = [];
				friendsFeed.data = [];
				Cloud.Friends.search({
					user_id : Ti.App.Properties.getString("currentUser_id")
				}, function(e) {
					if (e.success) {
						if (e.users.length > 0) {

							tmp_arr = [];
							for (var j = 0; j < e.users.length; j++) {
								var user = e.users[j];
								arr.push(user.id);
								Cloud.Objects.query({
									classname : 'goingOutTonight',
									where : {
										user_id : user.id

									},
								}, function(e) {
									if (e.success) {

										if (e.goingOutTonight.length == 0) {
										} else {

											for (var i = 0; i < e.goingOutTonight.length; i++) {
												var goingOutTonight = e.goingOutTonight[i];

												var offset = -5.0;
												var current_date = new Date();

												var utc = current_date.getTime() + (current_date.getTimezoneOffset() * 60000);
												var event_Date = new Date(utc + (3600000 * offset));

												var current_utc_date = new Date(event_Date.getFullYear(), event_Date.getMonth(), event_Date.getDate(), event_Date.getHours(), event_Date.getMinutes(), event_Date.getSeconds(), event_Date.getMilliseconds());
												var previous_day_date = new Date(event_Date.getFullYear(), event_Date.getMonth(), (event_Date.getDate() - 1), event_Date.getHours(), event_Date.getMinutes(), event_Date.getSeconds(), event_Date.getMilliseconds());
												var next_day_date = new Date(current_utc_date.getFullYear(), current_utc_date.getMonth(), (current_utc_date.getDate() + 1), current_utc_date.getHours(), current_utc_date.getMinutes(), current_utc_date.getSeconds(), current_utc_date.getMilliseconds());
												var cd = previous_day_date.toISOString().split(".");

												previous_day_date = cd[0] + "+0000";

												Cloud.Events.queryOccurrences({
													where : {
														"start_time" : {
															$gte : previous_day_date
														}

													},
													"order" : "make,-id"

												}, function(e) {

													if (e.success) {

														if (e.event_occurrences.length > 0) {
															search_friend_data = [];
															arr_bar_name = [];
															for (var i = 0; i < e.event_occurrences.length; i++) {
																var event = e.event_occurrences[i].event;

																if ((event.custom_fields.goingOutTonight_custom_id == goingOutTonight.id)) {

																	if (event_timeout(event.created_at) == true) {

																		var user_id = goingOutTonight.user_id;
																		var user_full_name = goingOutTonight.user_full_name;
																		if (goingOutTonight.event_id != 0) {

																			Ti.API.info(i + "=" + JSON.stringify(user));

																			var user = {
																				user_id : user_id,
																				user_full_name : user_full_name,
																				bar_name : goingOutTonight.bar_name,
																				created_at : goingOutTonight.updated_at

																			};

																			load_friends_photo(user);

																		}

																		Ti.API.info("**************FINAL --4***************");

																	} else {
																		//Ti.API.info("Timer out");
																		if (win && win != null) {

																			win.close();
																		}
																	}

																} else {
																	// alert("sf");
																}

															}

															refresh.enabled = true;

															Ti.API.info("**************FINAL --1 ***************");

														} else {
															search_friend_data = [];
															search_friend_data = [{
																title : "None of your friends are currently attending events",
																font : {
																	fontFamily : customFont,
																	fontSize : 12,
																	fontWeight : 'bold'
																}
															}];
															friendsFeed.setData(search_friend_data);
															refresh.enabled = true;

														}

														//

													} else {
														if (win && win != null) {

															win.close();
														}
													}

												});

											}

											Ti.API.info("**************FINAL --2 ***************");

										}
									}

								});

							}
							Ti.API.info("**************FINAL --3 ***************");
						} else {
							refresh.enabled = true;

							return;
						}

					} else {

						Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
					}
				});

			} else {

				alert("No one is currently attending an event");
			}

		} catch(ex) {
			Ti.API.info(ex);
		}

	};

	//END SEARCH FRIEND SECTION

	// TOP EVENT SECTION
	//var create_event_row = function(image, event_num_occurrences, event_name) {

	//FIRST WAY

	var create_event_row_data = function(image, event_num_occurrences, event_name) {

		var row = Titanium.UI.createTableViewRow({
			layout : "horizontal"
		});

		var user_image_view = Titanium.UI.createImageView({
			defaultImage : '/images/profilePlaceholder.png',
			image : encodeURI(image),
			top : 5,
			width : 40,
			height : 40,
			left : 5,
			layout : "horizontal"
		});
		row.add(user_image_view);

		var event_text = null;
		if (event_num_occurrences == 1) {

			event_text = event_num_occurrences + " " + "person attending" + " " + event_name;
		} else {
			event_text = event_num_occurrences + " " + "people attending" + " " + event_name;
		}

		var lbl_event_text = Ti.UI.createLabel({
			left : 10,
			top : 5,
			height : 20,
			text : event_text,
			color : "black",
			font : {
				fontFamily : customFont,
				fontSize : 12,
				fontWeight : 'bold'
			}
		});

		row.add(lbl_event_text);

		top_event_data.push(row);

		//top_event_data = top_event_data.reverse();
		topEventsFeed.setData(top_event_data);

		//Ti.API.info("create_event_row");
		Ti.API.info("Second =" + event_name);

	};

	var create_event_row = function(data) {

		var image = "/image/profilePlaceholder.png";
		var bar_name = "";
		var counter = 0;

		while (data[counter]) {

			Ti.API.info("counter=" + counter + "||" + data[counter].name);

			if (tmp_arr.indexOf(data[counter].name) == -1) {

				tmp_arr.push(data[counter].name);

				//alert("if=" +tmp_arr);

				Ti.API.info("Zero =" + counter + "||" + data[counter].name);

				Cloud.Objects.query({
					classname : 'topEvents',
					where : {
						bar_name : data[counter].name
					}

				}, function(e) {
					if (e.success) {

						Ti.API.info(JSON.stringify(e.topEvents));

						if (e.topEvents.length > 0) {

							var top_event = e.topEvents[0];
							Ti.API.info("First");
							create_event_row_data(top_event.bar_image, e.topEvents.length, top_event.bar_name);
							Ti.API.info("Third");

							/////
							refresh.enabled = true;

						}

					} else {
						Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
					}
				});

				counter++;
			} else {

				Ti.API.info("else=" + tmp_arr);
				break;

			}
		}

	};

	// SECOND WAY

	/*	var create_event_row = function(image, event_num_occurrences, event_name) {

	 var image = "/image/profilePlaceholder.png";

	 Cloud.Objects.query({
	 classname : 'topEvents',
	 where : {
	 bar_name : bar_name // event.custom_fields.bar_name
	 }
	 //"order" : name
	 // "order": "-id"
	 //"order": "make,-id"

	 }, function(e) {
	 if (e.success) {

	 if (e.topEvents.length > 0) {

	 var top_event = e.topEvents[0];
	 Ti.API.info("First");
	 create_event_row_data(top_event.bar_image, e.topEvents.length, top_event.bar_name);
	 Ti.API.info("Third");

	 for (var i = 0; i < e.topEvents.length; i++) {

	 var top_event = e.topEvents[i];

	 if (top_event.bar_name == bar_name) {
	 var counter = e.topEvents.length;

	 var image = top_event.bar_image;
	 var event_num_occurrences = counter;
	 var event_name = top_event.bar_name;

	 if (win && win != null) {
	 // win.close();
	 }

	 } else {

	 alert("?");
	 }

	 }////

	 /////
	 refresh.enabled = true;

	 }

	 } else {
	 Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
	 }
	 });

	 };

	 var load_event_details = function(event, win) {

	 //Ti.API.info("load_event_details");

	 var image = "/image/profilePlaceholder.png";
	 var id = (event.user) ? (event.user.id) : null;

	 Cloud.Objects.query({
	 classname : 'topEvents',
	 where : {
	 bar_name : event.name // event.custom_fields.bar_name
	 },
	 "order" : event.name
	 // "order": "-id"
	 //"order": "make,-id"

	 }, function(e) {
	 if (e.success) {

	 alert("e.topEvents.length="+e.topEvents.length);

	 //Ti.API.info("e.topEvents =" +JSON.stringify(e.topEvents));

	 if (e.topEvents.length > 0) {

	 for (var i = 0; i < e.topEvents.length; i++) {

	 var top_event = e.topEvents[i];

	 if (top_event.bar_name == event.name) {
	 var counter = e.topEvents.length;

	 // Ti.API.info("top_event.bar_name="+ event.name +"||" +JSON.stringify(top_event.bar_name));

	 create_event_row_data(top_event.bar_image, counter, top_event.bar_name);

	 } else {

	 alert("?");
	 }

	 }

	 /////
	 refresh.enabled = true;

	 }

	 } else {
	 Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
	 }
	 });

	 };*/

	var load_event_list = function(win, call_back) {
		try {

			if (Ti.Network.online) {

				var offset = -5.0;
				var current_date = new Date();

				var utc = current_date.getTime() + (current_date.getTimezoneOffset() * 60000);
				var event_Date = new Date(utc + (3600000 * offset));

				var current_utc_date = new Date(event_Date.getFullYear(), event_Date.getMonth(), event_Date.getDate(), event_Date.getHours(), event_Date.getMinutes(), event_Date.getSeconds(), event_Date.getMilliseconds());
				var previous_day_date = new Date(event_Date.getFullYear(), event_Date.getMonth(), (event_Date.getDate() - 1), event_Date.getHours(), event_Date.getMinutes(), event_Date.getSeconds(), event_Date.getMilliseconds());
				var next_day_date = new Date(current_utc_date.getFullYear(), current_utc_date.getMonth(), (current_utc_date.getDate() + 1), current_utc_date.getHours(), current_utc_date.getMinutes(), current_utc_date.getSeconds(), current_utc_date.getMilliseconds());

				var cd = previous_day_date.toISOString().split(".");

				previous_day_date = cd[0] + "+0000";

				Cloud.Events.queryOccurrences({
					where : {
						"start_time" : {
							$gte : previous_day_date
						}

					},
					// "order":"id, created_at"
					"order" : "make,-id"

				}, function(e) {

					if (e.success) {

						friend_details_array = [];

						if (e.event_occurrences.length == 0) {
							top_event_data = [];
							top_event_data = [{
								title : "No one is currently attending an event",

								font : {
									fontFamily : customFont,
									fontSize : 12,
									fontWeight : 'bold'
								}
							}];

							topEventsFeed.setData(top_event_data);

							if (win && win != null) {
								win.close();
							}
							refresh.enabled = true;

						} else {
							top_event_data = [];
							arr_bar_name = [];
							tmp_arr = [];
							var default_rows = e.event_occurrences.length;

							for (var i = 0; i < default_rows; i++) {

								var event = e.event_occurrences[i].event;

								if (event_timeout(event.created_at) == true) {

									if (event && event != null) {

										arr_bar_name.push(event);

										//load_event_details(event);

									}

								} else {

									var event = e.event_occurrences[i].event;

									//// REMOVE EVENTS

									if (event && event != null && (event.custom_fields.user_id == Ti.App.Properties.getString('currentUser_id'))) {

										Cloud.Objects.query({
											classname : 'goingOutTonight',
											where : {
												event_id : event.id
											}
										}, function(e) {
											if (e.success) {

												if (e.goingOutTonight.length > 0) {
													for (var i = 0; i < e.goingOutTonight.length; i++) {

														var goingOutTonight = e.goingOutTonight[i];

														var event_id = goingOutTonight.event_id;
														var top_event_id = goingOutTonight.top_event_id;
														var acl_id = goingOutTonight.acl_id;
														var bar_name = goingOutTonight.bar_name;

														if (goingOutTonight.user_id == Ti.App.Properties.getString("currentUser_id")) {

															Cloud.Objects.update({
																classname : "goingOutTonight",
																id : goingOutTonight.id,
																fields : {
																	event_id : 0,
																	acl_id : 0,
																	here_clicked_time : 0,
																	bar_name : null,
																	going_out : 'No',
																	is_attending : false
																}

															}, function(e) {
																if (e.success) {
																	Ti.API.info('Success goingOutTonight remove');

																	Cloud.ACLs.show({
																		name : bar_name + "_" + Ti.App.Properties.getString('currentUser_id'),
																	}, function(e) {
																		if (e.success) {
																			Cloud.ACLs.remove({
																				name : bar_name + "_" + Ti.App.Properties.getString('currentUser_id'),
																			}, function(e) {
																				if (e.success) {
																					Ti.API.info('Cloud.ACLs remove');
																					Cloud.Objects.remove({
																						classname : 'topEvents',
																						id : top_event_id
																					}, function(e) {
																						if (e.success) {
																							if (Ti.App.Properties.getString('currentUser_id') == event.user.id) {
																								Cloud.Events.remove({
																									event_id : event_id,
																									user_id : Ti.App.Properties.getString('currentUser_id')
																								}, function(e) {
																									if (e.success) {
																										Ti.API.info(' Cloud.Events.remove');
																									} else {
																										if (win && win != null) {
																											//win.close();
																										}
																										Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
																									}
																								});
																							}
																						} else {
																							Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
																						}
																					});

																				}
																			});
																		}
																	});

																} else {

																	if (win && win != null) {
																		win.close();
																	}
																	Ti.API.info('Cloud.Objects.remove Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
																}
															});

														}

													}
												} else {
													refresh.enabled = true;
													top_event_data = [];
													top_event_data = [{
														title : "No one is currently attending an event",

														font : {
															fontFamily : customFont,
															fontSize : 12,
															fontWeight : 'bold'
														}
													}];

													topEventsFeed.setData(top_event_data);

												}

											} else {
												if (win && win != null) {
													win.close();
												}
												Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
											}
										});

									}
									if (win && win != null) {
										win.close();
									}

									//// END REMOVE EVENTS
								}

							}// END FOR LOOP

							// CREATE EVENT ROW CODE
							Ti.API.info("arr_bar_name=" + JSON.stringify(arr_bar_name));

							if (arr_bar_name.length > 0) {

								///

								create_event_row(arr_bar_name);

							}

							// END CREATE EVENT ROW CODE

						}

					} else {

						if (win && win != null) {
							win.close();
						}
						Ti.API.info('Event:\n' + ((e.error && e.message) || JSON.stringify(e)));
					}

				});

			} else {

				top_event_data = [];
				top_event_data = [{
					title : "No one is currently attending an event"
				}];
				topEventsFeed.setData(top_event_data);
				refresh.enabled = true;

			}
		} catch(ex) {
			alert(ex);
		}

	};

	// END TOP EVENT SECTION

	tabbedBar.addEventListener('click', function(e) {
		obj_win.open();
		switch(e.index) {
			case 0:
				events.animate({
					view : friendsFeed,
					transition : Ti.UI.iPhone.AnimationStyle.FLIP_FROM_RIGHT
				});
				search_friend_data = [];
				search_friend_data = [{
					title : "None of your friends are currently attending events",
					font : {
						fontFamily : customFont,
						fontSize : 12,
						fontWeight : 'bold'
					}
				}];

				friendsFeed.setData(search_friend_data);
				load_friends_list(null);
				break;

			case 1:

				events.animate({
					view : topEventsFeed,
					transition : Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT,

				});
				top_event_data = [];

				topEventsFeed.setData(top_event_data);

				load_event_list(null);

				break;
		}
		obj_win.close();
	});
	events.addEventListener("focus", function(e) {
		refresh.enabled = true;
	});

	events.addEventListener("open", function(e) {
		friendsFeed.setData(search_friend_data);
		var act_ind_win = null;
		// default null value
		load_friends_list(act_ind_win);

	});

	return events;
};
module.exports = events;


text:
#include <QObject>

class SpiralTest : public QObject
{
	Q_OBJECT
private slots:
	void testGenerate_data();
	void testGenerate();
	void testPhantom();
};

#endif // SPIRALTEST_H

redpajama_set_name: RedPajamaGithub


text:
var browserSync = require('browser-sync').create()
var reload = browserSync.reload
var gulp = require('gulp')
var gitbook = require('gitbook')
var path = require('path')
var del = require('del')

// path of your *.md book files
var rootPath = path.join(__dirname)

// output path where generated *.html will be stored
var outputPath = path.join(rootPath, '_book')

// gulp.watch instance
var watcher

// rebuild book + start server
gulp.task('default', function (done) {
  rebuildBook(function () {
    browserSync.init({
      server: {
        baseDir: outputPath
      }
    })
    done()
  })
})

// kill watcher + remove/clean output dir + build book
function rebuildBook (done) {

  // pause watcher while building book progress
  if (watcher) {
    watcher.end()
    watcher = undefined;
  }

  // ensure output path is not exists otherwise book won't generated
  return del(path.join(outputPath)).then(paths => {
    buildBook().then(function () {

      // start watcher after built
      startWatch().on('ready', function(){
        done();
      }).on('error', function(e){
        console.error('ERROR: watch error... $s', e)
      })
    })
  })
}

// build book
function buildBook () {
  var fs = gitbook.createNodeFS(rootPath)
  var book = gitbook.Book.createForFS(fs)
  var Parse = gitbook.Parse
  var Output = gitbook.Output
  var Generator = Output.getGenerator('website')

  return Parse.parseBook(book)
    .then(function (resultBook) {
      return Output.generate(Generator, resultBook, {
        root: outputPath
      })
    })
}

// start watching md files + when files changed reload browser
function startWatch() {
  var rp = path.join(rootPath, '/**/*.md')
  watcher = gulp.watch([rp, '!' + rp + '/_book/' ], function () {
    rebuildBook(reload)
  })
  return watcher;
}


text:
<?php
namespace Loevgaard\LockableCommandBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class LoevgaardLockableCommandExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('loevgaard_lockable_command.lock_dir', $config['lock_dir']);

        $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');
    }
}


text:
/*
 * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
 *
 * push(x) -- Push element x onto stack.
 * pop() -- Removes the element on top of the stack.
 * top() -- Get the top element.
 * getMin() -- Retrieve the minimum element in the stack.
 */
public class MinStack {
	private Stack<Integer> stack, minstack;

	public MinStack() {
		stack = new Stack();
		minstack = new Stack();
	}

	public void push(int x) {
		if(minstack.empty()) {
			minstack.push(x);
		} else {
			minstack.push(Math.min(x, minstack.peek()));
		}
		stack.push(x);
	}

	public void pop() {
		stack.pop();
		minstack.pop();
	}

	public int top() {
		return stack.peek();
	}

	public int getMin() {
		return minstack.peek();
	}
};

// v2
public class MinStack {
    // 10:20 - 10:25

    /** initialize your data structure here. */
    private Stack<Integer> stack, minstack;

    public MinStack() {
        stack = new Stack();
        minstack = new Stack();
    }

    public void push(int x) {
        stack.push(x);
        if(minstack.empty()) {
            minstack.push(x);
        } else {
            minstack.push(Math.min(x, minstack.peek()));
        }
    }

    public void pop() {
        stack.pop();
        minstack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minstack.peek();
    }
}

// v3
public class MinStack {
    // 11:34 - 11:37
    Stack<Integer> stack = new Stack();
    Stack<Integer> minstack = new Stack();

    /** initialize your data structure here. */
    public MinStack() {

    }

    public void push(int x) {
        int min = minstack.size() == 0 ? x : Math.min(x, minstack.peek());
        stack.push(x);
        minstack.push(min);
    }

    public void pop() {
        stack.pop();
        minstack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minstack.peek();
    }
}

// v4
public class MinStack {
    // 11:37 - 11:41 minor optimization
    Stack<Integer> stack = new Stack();
    Stack<Integer> minstack = new Stack();

    /** initialize your data structure here. */
    public MinStack() {

    }

    public void push(int x) {
        stack.push(x);
        if(minstack.size() == 0 || minstack.peek() >= x) {
            minstack.push(x);
        }
    }

    public void pop() {
        int val = stack.pop();
        if(val == minstack.peek()) {
            minstack.pop();
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minstack.peek();
    }
}


text:
package org.apache.tinkerpop.gremlin.neo4j.process.traversal.strategy.optimization;

import org.apache.tinkerpop.gremlin.neo4j.process.traversal.step.sideEffect.Neo4jGraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.step.HasContainerHolder;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.NoOpBarrierStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.AbstractTraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;

/**
 * @author Pieter Martin
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public final class Neo4jGraphStepStrategy extends AbstractTraversalStrategy<TraversalStrategy.ProviderOptimizationStrategy> implements TraversalStrategy.ProviderOptimizationStrategy {

    private static final Neo4jGraphStepStrategy INSTANCE = new Neo4jGraphStepStrategy();

    private Neo4jGraphStepStrategy() {
    }

    @Override
    public void apply(final Traversal.Admin<?, ?> traversal) {
        for (final GraphStep originalGraphStep : TraversalHelper.getStepsOfClass(GraphStep.class, traversal)) {
            final Neo4jGraphStep<?, ?> neo4jGraphStep = new Neo4jGraphStep<>(originalGraphStep);
            TraversalHelper.replaceStep(originalGraphStep, neo4jGraphStep, traversal);
            Step<?, ?> currentStep = neo4jGraphStep.getNextStep();
            while (currentStep instanceof HasStep || currentStep instanceof NoOpBarrierStep) {
                if (currentStep instanceof HasStep) {
                    for (final HasContainer hasContainer : ((HasContainerHolder) currentStep).getHasContainers()) {
                        if (!GraphStep.processHasContainerIds(neo4jGraphStep, hasContainer))
                            neo4jGraphStep.addHasContainer(hasContainer);
                    }
                    TraversalHelper.copyLabels(currentStep, currentStep.getPreviousStep(), false);
                    traversal.removeStep(currentStep);
                }
                currentStep = currentStep.getNextStep();
            }
        }
    }

    public static Neo4jGraphStepStrategy instance() {
        return INSTANCE;
    }

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	/**
	 * View
	 * Display at /view
	 * Display information about the shortened URL
	 */
	class View extends CI_Controller {

		// default method that lists all of the shortened URLs
		public function index()
		{
				// get the list of URLs and load it into data array for use in the view
				$list = $this->shorten->get_list($this->shorten->list_urls(0), "No URLs have been added yet");
				$data = array( 'list' => $list );

				// load header, body and footer views
				$this->load->view('templates/header');
				$this->load->view('view_list', $data);
				$this->load->view('templates/footer');
		}

		// method to use when viewing information for a specific shortened URL
		public function info()
		{
			// segment_2 is the shortened URL in question
			$segment_2 = $this->uri->segment(2);

			if ( $segment_2 != '')
			{
				// pull data related to this shortened_url
				$query = $this->db->get_where('urls', array('short_url' => $segment_2));

				if ( $query->num_rows() > 0 )
				{
					$row = $query->row();
					$data = array(
							'id'			=> $row->id,
			                'orig_url'     	=> $row->orig_url,
			                'short_url'		=> $row->short_url,
			                'insert_dt'     => $row->insert_dt,
							'tracking_data'	=> $this->shorten->get_tracking_data($row->short_url),
			        );
				}
			}

			// load header, body and footer views
			$this->load->view('templates/header');
			$this->load->view('view', $data);
			$this->load->view('templates/footer');
		}
	}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Forecast
{
    public class ForecastParsingException : Exception
    {
        public ForecastParsingException(string message) : base(message) { }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Export Common Cartridge</title>

<link type="text/css" href="/library/skin/tool_base.css" media="all" rel="stylesheet" />
<link type="text/css" href="/library/skin/default/tool.css" media="all" rel="stylesheet" />

Export Common Cartridge

 This function allows you to save (download) a file in IMS Common Cartridge
Format containing the contents of the current site.
Other course management
systems such as Blackboard can load the contents of a course
in Common Cartridge format. So this can be used to move content
between course management systems. It can also be used if you simply want
to save the contents of your site in a form that can be used later.

Use the "More Tools" pull-down and choose Export CC.

 Note that the Common Cartidge format only handles some aspects of
a site. Details will be lost. E.g. only the most common types of quiz
question will be saved. And items that Lessons would put inline on the page
(e.g. blocks of text added with "Add Text" and movies added with "Add Multimedia")
will appear as links when the Common Cartridge file is loaded. This is a limitation
of the Common Cartridge standard, and not a Sakai problem.

 The export will contain a file in the resources area called
cc-objects/export-errors. It will contain a list of any problems in
exporting, including questions and Lessons content that can't be
handled by the Common Cartridge format.

 Here are the types of content that will be included:

 Lessons pages

 Quizes in Samigo. (Mneme is currently not exported.)

 Assignments in Assignments or Assignments 2.

 Forum topics in Forums and jForum

 Note that most other systems do not recognize assignments. They
simply import the text of the assignmentn as a document.

 Currently Sakai can save in Common Cartridge versions 1.1 and 1.2.
1.2 is the default. We've seen problems trying to load 1.2 files into
Moodle and Blackboard, so we recommend using version 1.1 for them.
The only significant difference is that 1.2 is supposed to understand
Assignments, and also quiz questions of type "Multiple Correct, Single Answer."
However no implementation we've found other than Sakai actually treats
these types correctly.


text:
module.exports = {
  'default e2e tests': function (browser) {
    browser
    .url('http://localhost:8080/main.html')
      .waitForElementVisible('#app', 5000)
      .assert.elementPresent('.logo')
      .assert.containsText('h1', 'Hello World')
      .assert.elementCount('p', 3)
      .end()
  }
}


text:
using System;

namespace Graphite
{
    public class GraphiteException : Exception
    {
        public GraphiteException(string message) : base(message) { }
        public GraphiteException(string message, Exception innerException) :
            base(message, innerException) { }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using System.ComponentModel.Design.Serialization;
using System.Globalization;

namespace XenAdmin.Commands
{
    /// <summary>
    /// This is used so that the Command property on CommandToolStripButton and CommandToolStripMenuItem can be set with the Designer.
    /// </summary>
    public class CommandConverter : TypeConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(string) || destinationType == typeof(InstanceDescriptor);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return value == null ? string.Empty : value.GetType().Name;
            }
            else if (destinationType == typeof(InstanceDescriptor))
            {
                ConstructorInfo ctor = value.GetType().GetConstructor(new Type[0]);
                return new InstanceDescriptor(ctor, new object[0]);
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}


text:
Squeeze
=======

Proof of concept code spike to run commands in isolated, one-time LXC containers.

Prerequisites
-------------

- Linux with LXC and AUFS support in kernel
- libvirt, avahi and debootstrap userspace tools

On Ubuntu Precise vanilla distro this is satisfied by just:

    sudo apt-get install libvirt-bin debootstrap avahi-daemon
    sudo modprobe aufs

Example usage
-------------

Create container template first usign helper script:

    wget -O - https://raw.github.com/gist/3155902/efb7e57e13b475ddeb363525fb96ca9cac81a277/bootstrap.sh | sh

Run `hostname` concurrently in 4 containers:

    squeeze -t template -k template.key -n 4 -- hostname

Trying development version
--------------------------

You can find Vagrantfile with url to Ubuntu machine I use. To get it running:

    vagrant up
    vagrant ssh

Run binary as `RUBYLUB=~/squeeze/lib ~/squeeze/bin/squeeze`. Remember to satisfy prerequisites.

Performance
-----------

On Ubuntu running under Vagrant and Macbook Air hardware:

- container start takes about 3s
- container stop takes about 2s

LXC performance hit compared to native system is about 1-3% according to documentation.


text:
package org.springframework.boot.docs.test.web;

// tag::test-mock-web-test-client[]

import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureWebTestClient
public class MockWebTestClientExampleTests {

	@Autowired
	private WebTestClient webClient;

	@Test
	public void exampleTest() {
		this.webClient.get().uri("/").exchange().expectStatus().isOk()
				.expectBody(String.class).isEqualTo("Hello World");
	}

}
// end::test-mock-web-test-client[]


text:
describe("Timeline: Testing the module", function(){
	describe("Timeline Module:", function(){
		var module;
		beforeEach(function(){
			module = angular.module("uniTimeline");
		});

		it("should be registered", function(){
			expect(module).not.toBe(null);
		});
	});
});

describe("Timeline Directive: ", function() {
	var scope, $compile, $templateCache, sandboxEl;

	beforeEach(module('uniTimeline'));

	beforeEach(inject(function(_$compile_, _$rootScope_, _$templateCache_){
		scope = _$rootScope_.$new();
		sandboxEl = $('<div>').attr('id', 'sandbox').appendTo($('body'));
		$compile = _$compile_;
		$templateCache = _$templateCache_;
	}));

	afterEach(function(){
		scope.$destroy();
		sandboxEl.remove();
	});

	function compileDirective(tpl){
		if(!tpl) tpl = '<uni-timeline class="uni-time" start="1600" end="2000" current="1750"></uni-timeline>';
		var element = $(tpl).appendTo(sandboxEl);
		element = $compile(element)(scope);
		scope.$digest();
		return jQuery(element[0]);
	}

	describe("initialisation", function(){
		it("The template should have been compiled", function(){
			var elm = compileDirective();
			expect(elm.children('div').hasClass('uni-time-container'));
		});

	});
});


text:
package com.vzw.wallet.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.vzw.wallet.model.Payee;
import com.vzw.wallet.model.Response;
import com.vzw.wallet.services.CoreBankingService;

@RestController("CoreBankingController")
@RequestMapping("/banking")
public class CoreBankingController {

	@Autowired
	CoreBankingService coreBankingService;

	@RequestMapping(value = "/loadCash/{amount:.*}", method = RequestMethod.POST)
	public ResponseEntity<?> loadCash(@PathVariable float amount){
		return new ResponseEntity<Response>(this.coreBankingService.loadCash(amount), HttpStatus.OK);
	}

	@RequestMapping(value = "/getBalance", method = RequestMethod.GET)
	public ResponseEntity<?> getBalance(){
		return new ResponseEntity<Response>(this.coreBankingService.getBalance(), HttpStatus.OK);
	}

	@RequestMapping(value = "/registerPayee", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> registerPayee(@Valid @RequestBody Payee payee){
		System.out.println("in registerPayee controller");
		return new ResponseEntity<Response>(this.coreBankingService.registerPayee(payee), HttpStatus.OK);
	}

	@RequestMapping(value = "/getPayees", method = RequestMethod.GET)
	public ResponseEntity<?> getPayees(){
		return new ResponseEntity<Response>(this.coreBankingService.getPayees(), HttpStatus.OK);
	}

	@RequestMapping(value = "/transfer/{id}/{amount:.*}", method = RequestMethod.POST)
	public ResponseEntity<?> transfer(@PathVariable int id, @PathVariable float amount){
		return new ResponseEntity<Response>(this.coreBankingService.transfer(id, amount), HttpStatus.OK);
	}

	@RequestMapping(value = "/payBills/{amount:.*}", method = RequestMethod.POST)
	public ResponseEntity<?> payBills(@Valid @RequestBody Payee payee, @PathVariable float amount){
		return new ResponseEntity<Response>(this.coreBankingService.payBill(payee, amount), HttpStatus.OK);
	}

	@RequestMapping(value = "/getStatements", method = RequestMethod.GET)
	public ResponseEntity<?> getStatements(){
		return new ResponseEntity<Response>(this.coreBankingService.getTranactionStatements(), HttpStatus.OK);
	}

	@RequestMapping(value = "/getLoyaltyBalance", method = RequestMethod.GET)
	public ResponseEntity<?> getLoyaltyBalance(){
		return new ResponseEntity<Response>(this.coreBankingService.getLoyaltyBalance(), HttpStatus.OK);
	}

	@RequestMapping(value = "/encashLoyaltyPoints", method = RequestMethod.GET)
	public ResponseEntity<?> encashLoyaltyPoints(){
		return new ResponseEntity<Response>(this.coreBankingService.encashLoyaltyPoints(), HttpStatus.OK);
	}
}


text:
var sockly 		= require('./../lib/sockly')
  , expect 		= require('chai').expect

describe('sockly', function() {

	describe('exports', function() {

		it('should have start function', function() {
			expect(sockly.start).to.exist;
		});
	});

});


text:
package org.apache.arrow.algorithm.sort;

import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.VarCharVector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Test cases for {@link StableVectorComparator}.
 */
public class TestStableVectorComparator {

  private BufferAllocator allocator;

  @Before
  public void prepare() {
    allocator = new RootAllocator(1024 * 1024);
  }

  @After
  public void shutdown() {
    allocator.close();
  }

  @Test
  public void testCompare() {
    try (VarCharVector vec = new VarCharVector("", allocator)) {
      vec.allocateNew(100, 5);
      vec.setValueCount(10);

      // fill data to sort
      vec.set(0, "ba".getBytes());
      vec.set(1, "abc".getBytes());
      vec.set(2, "aa".getBytes());
      vec.set(3, "abc".getBytes());
      vec.set(4, "a".getBytes());

      VectorValueComparator<VarCharVector> comparator = new TestVarCharSorter();
      VectorValueComparator<VarCharVector> stableComparator = new StableVectorComparator<>(comparator);
      stableComparator.attachVector(vec);

      assertTrue(stableComparator.compare(0, 1) > 0);
      assertTrue(stableComparator.compare(1, 2) < 0);
      assertTrue(stableComparator.compare(2, 3) < 0);
      assertTrue(stableComparator.compare(1, 3) < 0);
      assertTrue(stableComparator.compare(3, 1) > 0);
      assertTrue(stableComparator.compare(3, 3) == 0);
    }
  }

  @Test
  public void testStableSortString() {
    try (VarCharVector vec = new VarCharVector("", allocator)) {
      vec.allocateNew(100, 10);
      vec.setValueCount(10);

      // fill data to sort
      vec.set(0, "a".getBytes());
      vec.set(1, "abc".getBytes());
      vec.set(2, "aa".getBytes());
      vec.set(3, "a1".getBytes());
      vec.set(4, "abcdefg".getBytes());
      vec.set(5, "accc".getBytes());
      vec.set(6, "afds".getBytes());
      vec.set(7, "0".getBytes());
      vec.set(8, "01".getBytes());
      vec.set(9, "0c".getBytes());

      // sort the vector
      VariableWidthOutOfPlaceVectorSorter sorter = new VariableWidthOutOfPlaceVectorSorter();
      VectorValueComparator<VarCharVector> comparator = new TestVarCharSorter();
      VectorValueComparator<VarCharVector> stableComparator = new StableVectorComparator<>(comparator);

      try (VarCharVector sortedVec =
              (VarCharVector) vec.getField().getFieldType().createNewSingleVector("", allocator, null)) {
        sortedVec.allocateNew(vec.getByteCapacity(), vec.getValueCount());
        sortedVec.setLastSet(vec.getValueCount() - 1);
        sortedVec.setValueCount(vec.getValueCount());

        sorter.sortOutOfPlace(vec, sortedVec, stableComparator);

        // verify results
        // the results are stable
        assertEquals("0", new String(sortedVec.get(0)));
        assertEquals("01", new String(sortedVec.get(1)));
        assertEquals("0c", new String(sortedVec.get(2)));
        assertEquals("a", new String(sortedVec.get(3)));
        assertEquals("abc", new String(sortedVec.get(4)));
        assertEquals("aa", new String(sortedVec.get(5)));
        assertEquals("a1", new String(sortedVec.get(6)));
        assertEquals("abcdefg", new String(sortedVec.get(7)));
        assertEquals("accc", new String(sortedVec.get(8)));
        assertEquals("afds", new String(sortedVec.get(9)));
      }
    }
  }

  /**
   * Utility comparator that compares varchars by the first character.
   */
  private static class TestVarCharSorter extends VectorValueComparator<VarCharVector> {

    @Override
    public int compareNotNull(int index1, int index2) {
      byte b1 = vector1.get(index1)[0];
      byte b2 = vector2.get(index2)[0];
      return b1 - b2;
    }
  }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>actuator.infra.ResourceGroup</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

Actuator

        Package actuator ::
        Module infra ::
        Class ResourceGroup

[hide private]

[frames] | no frames]

Class ResourceGroup

source code

                      object --+
                               |
 modeling.AbstractModelingEntity --+
                                   |
                      object --+   |
                               |   |
modeling._ComputeModelComponents --+
                                   |
             modeling.ComponentGroup --+
                                       |
                                      ResourceGroup

A specialization of the ComponentGroup class

        Instance Methods
        [hide private]

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

      Inherited from modeling.ComponentGroup

          __init__(self,
        name,
        **kwargs)

      Create a new ComponentGroup

            source code

          _comp_source(self)

            source code

          _fix_arguments(self)

      Derived classes override this to fix any arguments to themselves.

            source code

          _validate_args(self,
        referenceable)

      CURRENTLY UNUSED: certain problems with finding references keep this
      private method out of use

            source code

          get_init_args(self)

      Returns the arguments that were used to create this object

            source code

      Inherited from modeling.AbstractModelingEntity

          _container(self)

      This returns the entity that contains self

            source code

          _get_arg_value(self,
        arg)

            source code

          _set_model_instance(self,
        inst)

            source code

          clone(self,
        clone_into_class=None)

      Make a copy of this object

            source code

          fix_arguments(self)

      Called internally when it time to fix arguments on the entity

            source code

          get_class(self)

      Returns the class of the object (or another class if desired)

            source code

          get_model_instance(self)

      Returns the model instance this entity is a part of (if any)

            source code

          refix_arguments(self)

      Allows arguments to be fixed again.

            source code

      Inherited from modeling._ComputeModelComponents

          components(self)

      Returns a set of component entities (instances of ModelComponent) in
      self

            source code

          refs_for_components(self,
        my_ref=None)

      Returns a set of model references for all ModelComponents within
      self.

            source code

        Class Variables
        [hide private]

      Inherited from modeling.AbstractModelingEntity

        clone_attrs = True

        Instance Variables
        [hide private]

      Inherited from modeling.AbstractModelingEntity

        _id

      public; internally generated unique id for this instance, a
      uuid.uuid4

        fixed

      public, read only.

        name

      publically available name attr for this entity

        Properties
        [hide private]

Inherited from object:
      __class__

      Inherited from modeling.AbstractModelingEntity

        container

      This returns the entity that contains self

         Home

         Trees

         Indices

         Help

Actuator

    Generated by Epydoc 3.0.1 on Mon Feb  9 18:19:52 2015

      http://epydoc.sourceforge.net


text:
<?php

namespace model;

class Email {

	private $email;

	public function __construct($email) {
		if ($this->emailIsOK($email)) {
			$this->email = $email;
		} else {
			throw new \Exception("UserName::__construct : Bad email");
		}
	}

	public function emailIsOK($email) {
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			return false;
		}
		return true;
	}

	public function __toString() {
		return urlencode($this->email);
	}

}


text:
<Type Name="CCKeyState" FullName="CocosSharp.CCKeyState">
  <TypeSignature Language="C#" Value="public enum CCKeyState" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi sealed CCKeyState extends System.Enum" />
  <AssemblyInfo>
    <AssemblyName>CocosSharp</AssemblyName>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Enum</BaseTypeName>
  </Base>
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName="Down">
      <MemberSignature Language="C#" Value="Down" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype CocosSharp.CCKeyState Down = int32(1)" />
      <MemberType>Field</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCKeyState</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="Up">
      <MemberSignature Language="C#" Value="Up" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype CocosSharp.CCKeyState Up = int32(0)" />
      <MemberType>Field</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCKeyState</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
  </Members>
</Type>


text:
/** @prettier */
import { ObservableInput, OperatorFunction, ObservedValueUnionFromArray, MonoTypeOperatorFunction, SchedulerLike } from '../types';
import { operate } from '../util/lift';
import { concatAll } from './concatAll';
import { fromArray } from '../observable/fromArray';
import { isScheduler } from '../util/isScheduler';

export function concatWith<T>(): OperatorFunction<T, T>;
export function concatWith<T, A extends ObservableInput<any>[]>(
  ...otherSources: A
): OperatorFunction<T, ObservedValueUnionFromArray<A> | T>;

/**
 * Emits all of the values from the source observable, then, once it completes, subscribes
 * to each observable source provided, one at a time, emitting all of their values, and not subscribing
 * to the next one until it completes.
 *
 * `concat(a$, b$, c$)` is the same as `a$.pipe(concatWith(b$, c$))`.
 *
 * ## Example
 *
 * Listen for one mouse click, then listen for all mouse moves.
 *
 * ```ts
 * import { fromEvent } from 'rxjs';
 * import { concatWith } from 'rxjs/operators';
 *
 * const clicks$ = fromEvent(document, 'click');
 * const moves$ = fromEvent(document, 'mousemove');
 *
 * clicks$.pipe(
 *   map(() => 'click'),
 *   take(1),
 *   concatWith(
 *     moves$.pipe(
 *       map(() => 'move')
 *     )
 *   )
 * )
 * .subscribe(x => console.log(x));
 *
 * // 'click'
 * // 'move'
 * // 'move'
 * // 'move'
 * // ...
 * ```
 *
 * @param otherSources Other observable sources to subscribe to, in sequence, after the original source is complete.
 */
export function concatWith<T, A extends ObservableInput<any>[]>(
  ...otherSources: A
): OperatorFunction<T, ObservedValueUnionFromArray<A> | T> {
  return concat(...otherSources);
}

/** @deprecated remove in v8. Use {@link concatWith} */
export function concat<T>(scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;
/** @deprecated remove in v8. Use {@link concatWith} */
export function concat<T, T2>(v2: ObservableInput<T2>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2>;
/** @deprecated remove in v8. Use {@link concatWith} */
export function concat<T, T2, T3>(
  v2: ObservableInput<T2>,
  v3: ObservableInput<T3>,
  scheduler?: SchedulerLike
): OperatorFunction<T, T | T2 | T3>;
/** @deprecated remove in v8. Use {@link concatWith} */
export function concat<T, T2, T3, T4>(
  v2: ObservableInput<T2>,
  v3: ObservableInput<T3>,
  v4: ObservableInput<T4>,
  scheduler?: SchedulerLike
): OperatorFunction<T, T | T2 | T3 | T4>;
/** @deprecated remove in v8. Use {@link concatWith} */
export function concat<T, T2, T3, T4, T5>(
  v2: ObservableInput<T2>,
  v3: ObservableInput<T3>,
  v4: ObservableInput<T4>,
  v5: ObservableInput<T5>,
  scheduler?: SchedulerLike
): OperatorFunction<T, T | T2 | T3 | T4 | T5>;
/** @deprecated remove in v8. Use {@link concatWith} */
export function concat<T, T2, T3, T4, T5, T6>(
  v2: ObservableInput<T2>,
  v3: ObservableInput<T3>,
  v4: ObservableInput<T4>,
  v5: ObservableInput<T5>,
  v6: ObservableInput<T6>,
  scheduler?: SchedulerLike
): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6>;
/** @deprecated remove in v8. Use {@link concatWith} */
export function concat<T>(...observables: Array<ObservableInput<T> | SchedulerLike>): MonoTypeOperatorFunction<T>;
/** @deprecated remove in v8. Use {@link concatWith} */
export function concat<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike>): OperatorFunction<T, R>;

/**
 * @deprecated remove in v8. Use {@link concatWith}
 */
export function concat<T, R>(...args: any[]): OperatorFunction<T, R> {
  let scheduler: SchedulerLike | undefined;

  if (isScheduler(args[args.length - 1])) {
    scheduler = args.pop() as SchedulerLike;
  }

  return operate((source, subscriber) => {
    concatAll()(fromArray([source, ...args], scheduler)).subscribe(subscriber as any);
  });
}


text:
namespace blink {

class HTMLLinkElementSizesAttributeTest : public testing::Test {};

TEST(HTMLLinkElementSizesAttributeTest,
     setSizesPropertyValue_updatesAttribute) {
  ScopedNullExecutionContext execution_context;
  auto* document =
      Document::CreateForTest(execution_context.GetExecutionContext());
  auto* link =
      MakeGarbageCollected<HTMLLinkElement>(*document, CreateElementFlags());
  DOMTokenList* sizes = link->sizes();
  EXPECT_EQ(g_null_atom, sizes->value());
  sizes->setValue("   a b  c ");
  EXPECT_EQ("   a b  c ", link->FastGetAttribute(html_names::kSizesAttr));
  EXPECT_EQ("   a b  c ", sizes->value());
}

TEST(HTMLLinkElementSizesAttributeTest,
     setSizesAttribute_updatesSizesPropertyValue) {
  ScopedNullExecutionContext execution_context;
  auto* document =
      Document::CreateForTest(execution_context.GetExecutionContext());
  auto* link =
      MakeGarbageCollected<HTMLLinkElement>(*document, CreateElementFlags());
  DOMTokenList* sizes = link->sizes();
  EXPECT_EQ(g_null_atom, sizes->value());
  link->setAttribute(html_names::kSizesAttr, "y  x ");
  EXPECT_EQ("y  x ", sizes->value());
}

}  // namespace blink


text:
#ifndef QBENCHMARKMETRIC_H
#define QBENCHMARKMETRIC_H

#include <QtTest/qtest_global.h>

QT_BEGIN_HEADER

QT_BEGIN_NAMESPACE

QT_MODULE(Test)

namespace QTest {

enum QBenchmarkMetric {
    FramesPerSecond,
    BitsPerSecond,
    BytesPerSecond,
    WalltimeMilliseconds,
    CPUTicks,
    InstructionReads,
    Events
};

}

QT_END_NAMESPACE

QT_END_HEADER

#endif // QBENCHMARK_H


text:
/**
 * Created by vlad on 22/09/16.
 */
;
(function () {
    'use strict';

    angular.module('cityGetApp.cityInfo.directive', [])
        .directive('cCityInfo', cCityInfo);

    cCityInfo.$inject = ['$log'];

    function cCityInfo($log) {
        $log.info('cCityInfo loaded!');
        return {
            restrict: 'AE',
            scope: {
                city: '=city'
            },
            templateUrl: 'partials/cityInfo.directive.tpl.html'
        };
    }

}());


text:
#ifndef __ARCH_RISCV_REMOTE_GDB_HH__
#define __ARCH_RISCV_REMOTE_GDB_HH__

#include "base/remote_gdb.hh"

namespace RiscvISA
{

class RemoteGDB : public BaseRemoteGDB
{
  public:
    RemoteGDB(System *system, ThreadContext *context)
        : BaseRemoteGDB(system, context, 1)
    {
    }

    bool
    acc(Addr, size_t)
    {
        panic("acc not implemented for Riscv!");
    }

    void
    getregs()
    {
        panic("getregs not implemented for Riscv!");
    }

    void
    setregs()
    {
        panic("setregs not implemented for Riscv!");
    }
};

} // namespace RiscvISA

#endif /* __ARCH_RISCV_REMOTE_GDB_H__ */


text:
from __future__ import unicode_literals

import os

from django import forms
from django.test import TestCase, override_settings
from django.test.client import RequestFactory
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.formtools.wizard.views import CookieWizardView
from django.utils._os import upath
from django.contrib.formtools.tests.models import Poet, Poem

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = '__all__'

UserFormSet = forms.models.modelformset_factory(User, form=UserForm, extra=2)
PoemFormSet = forms.models.inlineformset_factory(Poet, Poem, fields="__all__")

class WizardTests(object):

    def setUp(self):
        self.testuser, created = User.objects.get_or_create(username='testuser1')
        self.wizard_step_data[0]['form1-user'] = self.testuser.pk

    def test_initial_call(self):
        response = self.client.get(self.wizard_url)
        wizard = response.context['wizard']
        self.assertEqual(response.status_code, 200)
        self.assertEqual(wizard['steps'].current, 'form1')
        self.assertEqual(wizard['steps'].step0, 0)
        self.assertEqual(wizard['steps'].step1, 1)
        self.assertEqual(wizard['steps'].last, 'form4')
        self.assertEqual(wizard['steps'].prev, None)
        self.assertEqual(wizard['steps'].next, 'form2')
        self.assertEqual(wizard['steps'].count, 4)

    def test_form_post_error(self):
        response = self.client.post(self.wizard_url, self.wizard_step_1_data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form1')
        self.assertEqual(response.context['wizard']['form'].errors,
                         {'name': ['This field is required.'],
                          'user': ['This field is required.']})

    def test_form_post_success(self):
        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        wizard = response.context['wizard']
        self.assertEqual(response.status_code, 200)
        self.assertEqual(wizard['steps'].current, 'form2')
        self.assertEqual(wizard['steps'].step0, 1)
        self.assertEqual(wizard['steps'].prev, 'form1')
        self.assertEqual(wizard['steps'].next, 'form3')

    def test_form_stepback(self):
        response = self.client.get(self.wizard_url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form1')

        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form2')

        response = self.client.post(self.wizard_url, {
            'wizard_goto_step': response.context['wizard']['steps'].prev})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form1')

    def test_template_context(self):
        response = self.client.get(self.wizard_url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form1')
        self.assertEqual(response.context.get('another_var', None), None)

        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form2')
        self.assertEqual(response.context.get('another_var', None), True)

        # ticket #19025: `form` should be included in context
        form = response.context_data['wizard']['form']
        self.assertEqual(response.context_data['form'], form)

    def test_form_finish(self):
        response = self.client.get(self.wizard_url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form1')

        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form2')

        post_data = self.wizard_step_data[1]
        post_data['form2-file1'] = open(upath(__file__), 'rb')
        response = self.client.post(self.wizard_url, post_data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form3')

        response = self.client.post(self.wizard_url, self.wizard_step_data[2])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form4')

        response = self.client.post(self.wizard_url, self.wizard_step_data[3])
        self.assertEqual(response.status_code, 200)

        all_data = response.context['form_list']
        with open(upath(__file__), 'rb') as f:
            self.assertEqual(all_data[1]['file1'].read(), f.read())
        all_data[1]['file1'].close()
        del all_data[1]['file1']
        self.assertEqual(all_data, [
            {'name': 'Pony', 'thirsty': True, 'user': self.testuser},
            {'address1': '123 Main St', 'address2': 'Djangoland'},
            {'random_crap': 'blah blah'},
            [{'random_crap': 'blah blah'},
             {'random_crap': 'blah blah'}]])

    def test_cleaned_data(self):
        response = self.client.get(self.wizard_url)
        self.assertEqual(response.status_code, 200)

        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        self.assertEqual(response.status_code, 200)

        post_data = self.wizard_step_data[1]
        with open(upath(__file__), 'rb') as post_file:
            post_data['form2-file1'] = post_file
            response = self.client.post(self.wizard_url, post_data)
        self.assertEqual(response.status_code, 200)

        response = self.client.post(self.wizard_url, self.wizard_step_data[2])
        self.assertEqual(response.status_code, 200)

        response = self.client.post(self.wizard_url, self.wizard_step_data[3])
        self.assertEqual(response.status_code, 200)

        all_data = response.context['all_cleaned_data']
        with open(upath(__file__), 'rb') as f:
            self.assertEqual(all_data['file1'].read(), f.read())
        all_data['file1'].close()
        del all_data['file1']
        self.assertEqual(all_data, {
            'name': 'Pony', 'thirsty': True, 'user': self.testuser,
            'address1': '123 Main St', 'address2': 'Djangoland',
            'random_crap': 'blah blah', 'formset-form4': [
                {'random_crap': 'blah blah'},
                {'random_crap': 'blah blah'}]})

    def test_manipulated_data(self):
        response = self.client.get(self.wizard_url)
        self.assertEqual(response.status_code, 200)

        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        self.assertEqual(response.status_code, 200)

        post_data = self.wizard_step_data[1]
        post_data['form2-file1'].close()
        post_data['form2-file1'] = open(upath(__file__), 'rb')
        response = self.client.post(self.wizard_url, post_data)
        self.assertEqual(response.status_code, 200)

        response = self.client.post(self.wizard_url, self.wizard_step_data[2])
        self.assertEqual(response.status_code, 200)
        self.client.cookies.pop('sessionid', None)
        self.client.cookies.pop('wizard_cookie_contact_wizard', None)

        response = self.client.post(self.wizard_url, self.wizard_step_data[3])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form1')

    def test_form_refresh(self):
        response = self.client.get(self.wizard_url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form1')

        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form2')

        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form2')

        post_data = self.wizard_step_data[1]
        post_data['form2-file1'].close()
        post_data['form2-file1'] = open(upath(__file__), 'rb')
        response = self.client.post(self.wizard_url, post_data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form3')

        response = self.client.post(self.wizard_url, self.wizard_step_data[2])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form4')

        response = self.client.post(self.wizard_url, self.wizard_step_data[0])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['wizard']['steps'].current, 'form2')

        response = self.client.post(self.wizard_url, self.wizard_step_data[3])
        self.assertEqual(response.status_code, 200)

@skipIfCustomUser
@override_settings(ROOT_URLCONF='django.contrib.formtools.tests.wizard.wizardtests.urls')
class SessionWizardTests(WizardTests, TestCase):
    wizard_url = '/wiz_session/'
    wizard_step_1_data = {
        'session_contact_wizard-current_step': 'form1',
    }
    wizard_step_data = (
        {
            'form1-name': 'Pony',
            'form1-thirsty': '2',
            'session_contact_wizard-current_step': 'form1',
        },
        {
            'form2-address1': '123 Main St',
            'form2-address2': 'Djangoland',
            'session_contact_wizard-current_step': 'form2',
        },
        {
            'form3-random_crap': 'blah blah',
            'session_contact_wizard-current_step': 'form3',
        },
        {
            'form4-INITIAL_FORMS': '0',
            'form4-TOTAL_FORMS': '2',
            'form4-MAX_NUM_FORMS': '0',
            'form4-0-random_crap': 'blah blah',
            'form4-1-random_crap': 'blah blah',
            'session_contact_wizard-current_step': 'form4',
        }
    )

@skipIfCustomUser
@override_settings(ROOT_URLCONF='django.contrib.formtools.tests.wizard.wizardtests.urls')
class CookieWizardTests(WizardTests, TestCase):
    wizard_url = '/wiz_cookie/'
    wizard_step_1_data = {
        'cookie_contact_wizard-current_step': 'form1',
    }
    wizard_step_data = (
        {
            'form1-name': 'Pony',
            'form1-thirsty': '2',
            'cookie_contact_wizard-current_step': 'form1',
        },
        {
            'form2-address1': '123 Main St',
            'form2-address2': 'Djangoland',
            'cookie_contact_wizard-current_step': 'form2',
        },
        {
            'form3-random_crap': 'blah blah',
            'cookie_contact_wizard-current_step': 'form3',
        },
        {
            'form4-INITIAL_FORMS': '0',
            'form4-TOTAL_FORMS': '2',
            'form4-MAX_NUM_FORMS': '0',
            'form4-0-random_crap': 'blah blah',
            'form4-1-random_crap': 'blah blah',
            'cookie_contact_wizard-current_step': 'form4',
        }
    )

@skipIfCustomUser
@override_settings(ROOT_URLCONF='django.contrib.formtools.tests.wizard.wizardtests.urls')
class WizardTestKwargs(TestCase):
    wizard_url = '/wiz_other_template/'
    wizard_step_1_data = {
        'cookie_contact_wizard-current_step': 'form1',
    }
    wizard_step_data = (
        {
            'form1-name': 'Pony',
            'form1-thirsty': '2',
            'cookie_contact_wizard-current_step': 'form1',
        },
        {
            'form2-address1': '123 Main St',
            'form2-address2': 'Djangoland',
            'cookie_contact_wizard-current_step': 'form2',
        },
        {
            'form3-random_crap': 'blah blah',
            'cookie_contact_wizard-current_step': 'form3',
        },
        {
            'form4-INITIAL_FORMS': '0',
            'form4-TOTAL_FORMS': '2',
            'form4-MAX_NUM_FORMS': '0',
            'form4-0-random_crap': 'blah blah',
            'form4-1-random_crap': 'blah blah',
            'cookie_contact_wizard-current_step': 'form4',
        }
    )

    def setUp(self):
        self.testuser, created = User.objects.get_or_create(username='testuser1')
        self.wizard_step_data[0]['form1-user'] = self.testuser.pk

    def test_template(self):
        templates = os.path.join(os.path.dirname(upath(__file__)), 'templates')
        with self.settings(
                TEMPLATE_DIRS=list(settings.TEMPLATE_DIRS) + [templates]):
            response = self.client.get(self.wizard_url)
            self.assertTemplateUsed(response, 'other_wizard_form.html')

class WizardTestGenericViewInterface(TestCase):
    def test_get_context_data_inheritance(self):
        class TestWizard(CookieWizardView):
            """
            A subclass that implements ``get_context_data`` using the standard
            protocol for generic views (accept only **kwargs).

            See ticket #17148.
            """
            def get_context_data(self, **kwargs):
                context = super(TestWizard, self).get_context_data(**kwargs)
                context['test_key'] = 'test_value'
                return context

        factory = RequestFactory()
        view = TestWizard.as_view([forms.Form])

        response = view(factory.get('/'))
        self.assertEqual(response.context_data['test_key'], 'test_value')

    def test_get_context_data_with_mixin(self):
        class AnotherMixin(object):
            def get_context_data(self, **kwargs):
                context = super(AnotherMixin, self).get_context_data(**kwargs)
                context['another_key'] = 'another_value'
                return context

        class TestWizard(AnotherMixin, CookieWizardView):
            """
            A subclass that implements ``get_context_data`` using the standard
            protocol for generic views (accept only **kwargs).

            See ticket #17148.
            """
            def get_context_data(self, **kwargs):
                context = super(TestWizard, self).get_context_data(**kwargs)
                context['test_key'] = 'test_value'
                return context

        factory = RequestFactory()

        view = TestWizard.as_view([forms.Form])

        response = view(factory.get('/'))
        self.assertEqual(response.context_data['test_key'], 'test_value')
        self.assertEqual(response.context_data['another_key'], 'another_value')

@skipIfCustomUser
class WizardFormKwargsOverrideTests(TestCase):
    def setUp(self):
        super(WizardFormKwargsOverrideTests, self).setUp()
        self.rf = RequestFactory()

        # Create two users so we can filter by is_staff when handing our
        # wizard a queryset keyword argument.
        self.normal_user = User.objects.create(username='test1', email='normal@example.com')
        self.staff_user = User.objects.create(username='test2', email='staff@example.com', is_staff=True)

    def test_instance_is_maintained(self):
        self.assertEqual(2, User.objects.count())
        queryset = User.objects.get(pk=self.staff_user.pk)

        class InstanceOverrideWizard(CookieWizardView):
            def get_form_kwargs(self, step):
                return {'instance': queryset}

        view = InstanceOverrideWizard.as_view([UserForm])
        response = view(self.rf.get('/'))

        form = response.context_data['wizard']['form']

        self.assertNotEqual(form.instance.pk, None)
        self.assertEqual(form.instance.pk, self.staff_user.pk)
        self.assertEqual('staff@example.com', form.initial.get('email', None))

    def test_queryset_is_maintained(self):
        queryset = User.objects.filter(pk=self.staff_user.pk)

        class QuerySetOverrideWizard(CookieWizardView):
            def get_form_kwargs(self, step):
                return {'queryset': queryset}

        view = QuerySetOverrideWizard.as_view([UserFormSet])
        response = view(self.rf.get('/'))

        formset = response.context_data['wizard']['form']

        self.assertNotEqual(formset.queryset, None)
        self.assertEqual(formset.initial_form_count(), 1)
        self.assertEqual(['staff@example.com'],
            list(formset.queryset.values_list('email', flat=True)))

class WizardInlineFormSetTests(TestCase):
    def setUp(self):
        self.rf = RequestFactory()
        self.poet = Poet.objects.create(name='test')
        self.poem = self.poet.poem_set.create(name='test poem')

    def test_set_instance(self):
        # Regression test for #21259
        poet = self.poet

        class InlineFormSetWizard(CookieWizardView):
            instance = None

            def get_form_instance(self, step):
                if self.instance is None:
                    self.instance = poet
                return self.instance

        view = InlineFormSetWizard.as_view([PoemFormSet])
        response = view(self.rf.get('/'))
        formset = response.context_data['wizard']['form']
        self.assertEqual(formset.instance, self.poet)


text:
package com.adobe.acs.nrl.ooyala;

import com.siteworx.cq5.ooyala.client.OoyalaApiCredential;
import com.siteworx.cq5.ooyala.service.OoyalaConfigurationException;
import com.siteworx.cq5.ooyala.service.OoyalaService;
import org.apache.felix.scr.annotations.*;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @author prajesh
 *         Date: 17/9/13
 *         Time: 12:55 PM
 *         To change this template use File | Settings | File Templates.
 */

@Component(immediate=true, metatype=false, description="Ooyala Query Servlet")
@Service
@Properties({
        @Property(name="sling.servlet.paths", value="/bin/nrl/ooyala")
})

public class OoyalaNRLServlet extends SlingSafeMethodsServlet {

    private Logger logger = LoggerFactory.getLogger(OoyalaNRLServlet.class);

    private static final int DEFAULT_LIMIT = 10;

    @Reference
    private OoyalaConfigurationService ooyalaConfigurationService;

    @Reference
    private OoyalaService ooyalaService;

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {

        String path = request.getParameter("path");

        path = path.substring(1);

        logger.info("Path = " +path);
        int siteNameIndex = path.indexOf("/content/");

        String siteNameStart = path.substring(siteNameIndex+9);

        int indexOfSlash = siteNameStart.indexOf("/");

        String siteName = siteNameStart.substring(0,indexOfSlash);

        final String queryString = request.getParameter("query");
        final String searchBy = request.getParameter("searchBy");
        final int[] offsetAndLimit = getLimit(request);

        if(logger.isDebugEnabled()){
            logger.debug("PATH = " + path);
            logger.debug("QUERY = " + queryString);
            logger.debug("TYPE = " + searchBy);
        }

        OoyalaApiCredential oolayaCredentials = null;
        try {
            oolayaCredentials = ooyalaConfigurationService.getCredentialsForSite(siteName);

            logger.info("key = "+ oolayaCredentials.getApiKey());
            logger.info("secret = "+ oolayaCredentials.getApiSecret());

        } catch (OoyalaConfigurationException e) {
            logger.error("Ooyala Configuration Exception occured for site = "+siteName);
        }

        logger.info("**** Oolaya NRL servlet ****");
        logger.info("configuration site Path = "+path);
        logger.info("siteName = "+siteName);

        //section 2 getting videos

        try {
            String jsonResponse = "";
            if (queryString == null || "".equals(queryString.trim())) {
                jsonResponse = getJSON(ooyalaService.getAllVideos(oolayaCredentials, offsetAndLimit[0], offsetAndLimit[1]));
            }
            else if (queryString != null && queryString.trim().length() > 2) {
                jsonResponse = getJSON(ooyalaService.getVideos(oolayaCredentials , searchBy, queryString, offsetAndLimit[0], offsetAndLimit[1]));
            } else if (queryString.trim().length() < 2) {
                jsonResponse = "{}";
            }
            response.setContentType("application/json");
            response.getWriter().write(jsonResponse);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            response.sendError(500, e.getMessage());
        }

    }

    /**
     * Manipulates the response JSON from Ooyala to fit the needs of built-in CQ functionality.
     *
     * @param rawResponse The raw JSON response from Ooyala.
     * @return A well formed JSON response.
     * @throws org.apache.sling.commons.json.JSONException
     */
    private String getJSON(String rawResponse) throws JSONException {
        // move embedCode into path to use existing extjs drag-drop
        JSONObject jsonFixed = new JSONObject(rawResponse);
        JSONArray items = (JSONArray) jsonFixed.get("items");
        if (logger.isDebugEnabled()) {
            logger.debug("Response length = " + items.length());
        }
        for(int i=0; i < items.length(); i++){
            final JSONObject currItem = (JSONObject) items.get(i);
            final String embedCode = (String) currItem.get("embed_code");
            int duration = (Integer) currItem.get("duration");
            String durationString = String.format("%d min, %d sec",
                    TimeUnit.MILLISECONDS.toMinutes(duration),
                    TimeUnit.MILLISECONDS.toSeconds(duration) -
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))
            );
            currItem.put("duration", durationString);
            if(embedCode != null){
                currItem.put("path", embedCode);
            }else{
                logger.error("embedCode is null");
            }
        }

        jsonFixed = new JSONObject().put("hits", items);
        return jsonFixed.toString();
    }

    /**
     * Parses the limit and offset string from CQ into integers.
     *
     * @param request The request from which to fetch the limit parameter.
     * @return An integer array containing the offset and limit for the Ooyala request.
     */
    private int[] getLimit(SlingHttpServletRequest request) {
        // limit string format : 10..20
        // [0] = offset
        // [1] = limit
        final String limitString = request.getParameter("limit");
        if(limitString != null){
            try{
                int offset = Integer.parseInt(limitString.substring(0, limitString.indexOf(".")));
                int limit = Integer.parseInt(limitString.substring(limitString.lastIndexOf(".") + 1, limitString.length())) - offset;
                return new int[] {offset, limit};
            }catch(NumberFormatException nfe){
                nfe.printStackTrace();
            }
        }
        return new int[] {0, DEFAULT_LIMIT};
    }

}


text:
package org.powlab.jeye.tests.other;

import java.io.IOException;
import java.io.StringWriter;

public class EnhancedTryTestStrobel1 {
    public void testEnhancedTryEmpty() throws IOException {
        try (final StringWriter writer = new StringWriter()) {
            writer.write("This is only a test.");
        }
    }
}


text:
// Scintilla source code edit control
/** @file Position.h
 ** Defines global type name Position in the Sci internal namespace.
 **/
// Copyright 2015 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#ifndef POSITION_H
#define POSITION_H

/**
 * A Position is a position within a document between two characters or at the beginning or end.
 * Sometimes used as a character index where it identifies the character after the position.
 */

namespace Sci {

typedef int Position;
typedef int Line;

// A later version (4.x) of this file may:
//#if defined(SCI_LARGE_FILE_SUPPORT)
//typedef std::ptrdiff_t Position;
// or may allow runtime choice between different position sizes.

const Position invalidPosition = -1;

}

#endif