text:
import sys
import os
from subprocess import PIPE, Popen, call
from gi.repository import Gtk, GObject, Pango, Gdk, Gio, GLib
from manager import BupManager
from sudo import Worker as SudoWorker
from scheduler import schedulers
from version import __version__
import threading
import config
import traceback
import gettext
import getpass

GObject.threads_init() # Important: enable multi-threading support in GLib

# l10n
if gettext.find('bups', os.path.dirname(__file__)+'/../locale'):
	gettext.install('bups', os.path.dirname(__file__)+'/../locale')
else: # Try global translation
	gettext.install('bups')

class BackupWindow(Gtk.Window):
	def __init__(self, manager, parent=None):
		Gtk.Window.__init__(self, title=_("Backup"))
		self.set_border_width(10)
		self.set_icon_name("drive-harddisk")
		self.set_position(Gtk.WindowPosition.CENTER)

		if parent is not None:
			self.set_transient_for(parent)

		vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
		self.add(vbox)

		self.label = Gtk.Label(_("Ready."), xalign=0)
		self.label.set_justify(Gtk.Justification.LEFT)
		vbox.pack_start(self.label, False, False, 0)

		self.progressbar = Gtk.ProgressBar()
		vbox.pack_start(self.progressbar, False, False, 0)

		self.textview = Gtk.TextView()
		#self.textview.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(0, 0, 0))
		#self.textview.modify_text(Gtk.StateType.NORMAL, Gdk.Color(255, 255, 255))
		fontdesc = Pango.FontDescription("monospace")
		self.textview.modify_font(fontdesc)
		self.textview.set_editable(False)
		sw = Gtk.ScrolledWindow()
		sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
		sw.set_min_content_height(200)
		sw.add(self.textview)
		exp = Gtk.Expander()
		exp.set_label(_("Details"))
		exp.add(sw)
		vbox.pack_start(exp, True, True, 0)

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		self.close_button = Gtk.Button(_("Close"))
		self.close_button.connect("clicked", self.on_close_clicked)
		hbox.pack_end(self.close_button, False, False, 0)

		self.manager = manager

	def backup(self):
		manager = self.manager

		finished = False

		def set_window_deletable(deletable):
			self.set_deletable(deletable)
			parent = self.get_transient_for()
			if parent is not None:
				parent.set_deletable(deletable)

			if not deletable:
				self.close_button.hide()
				self.resize(1, 1) # Make window as small as possible
			else:
				self.close_button.show()

		def onstatus(status, ctx):
			GLib.idle_add(self.set_label, status)

		def onprogress(progress, ctx):
			if finished:
				return

			#print("PROGRESS", progress)
			if "percentage" in progress:
				if type(progress["percentage"]) == int or type(progress["percentage"]) == float:
					GLib.idle_add(self.progressbar.set_fraction, progress["percentage"]/100)
				else:
					GLib.idle_add(self.progressbar.pulse)

			lbl = _("Backing up {name}: ").format(name=ctx["name"])

			if not "status" in progress:
				return

			if progress["status"] == "indexing":
				lbl += _("indexing files")
			elif progress["status"] == "saving":
				lbl += _("saving files")
			elif progress["status"] == "reading_index":
				lbl += _("reading indexes")
			else:
				return

			lbl += " ("

			if "files_done" in progress:
				lbl += str(progress["files_done"])
				if "files_total" in progress:
					lbl += "/"+str(progress["files_total"])
				lbl += " "+_("files")
			if "bytes_done" in progress:
				lbl += ", "+str(int(progress["bytes_done"]/1024))+"/"+str(int(progress["bytes_total"]/1024))+" "+_("KiB")
			if "remaining_time" in progress and progress["remaining_time"]:
				lbl += ", "+_("{remaining_time} remaining").format(remaining_time=progress["remaining_time"])
			if "speed" in progress and progress["speed"]:
				lbl += ", "+str(progress["speed"])+" "+_("KiB/s")
			if progress["status"] == "indexing":
				if "paths_per_sec" in progress:
					lbl += str(int(progress["paths_per_sec"]))+" "+_("paths/s")
				if "total_paths" in progress:
					lbl += ", "+str(progress["total_paths"])+" "+_("paths indexed")

			if lbl[-1] == "(":
				lbl = lbl[:-2]
			else:
				lbl += ")"
			lbl += "..."

			GLib.idle_add(self.set_label, lbl, False)

		def onerror(err, ctx):
			GLib.idle_add(self.append_log, err)

		def onfinish(data, ctx):
			GLib.idle_add(set_window_deletable, True)
			GLib.idle_add(self.progressbar.set_fraction, 1)
			finished = True

		def onabord(data, ctx):
			GLib.idle_add(set_window_deletable, True)
			GLib.idle_add(self.set_label, _("Backup canceled."), False)

		callbacks = {
			"onstatus": onstatus,
			"onprogress": onprogress,
			"onerror": onerror,
			"onfinish": onfinish,
			"onabord": onabord
		}

		self.set_label(_("Backup started..."))

		# Lock window
		set_window_deletable(False)

		def do_backup(manager, callbacks):
			try:
				return manager.backup(callbacks)
			except Exception, e:
				callbacks["onerror"](traceback.format_exc(), {})
				callbacks["onabord"]({}, {})

		t = threading.Thread(target=do_backup, args=(manager, callbacks))
		t.start()

	def set_label(self, txt, logLabel=True):
		if txt == "":
			return
		self.label.set_text(txt)

		if logLabel:
			self.append_log(txt+"\n")

	def append_log(self, txt):
		buf = self.textview.get_buffer()
		buf.insert(buf.get_end_iter(), txt)
		#buf.insert_at_cursor(txt)
		print(txt.strip())

	def on_close_clicked(self, btn):
		self.destroy()

class RestoreWindow(Gtk.Window):
	def __init__(self, manager, parent):
		Gtk.Window.__init__(self, title=_("Restore"))
		self.set_border_width(10)
		self.set_icon_name("view-refresh")
		self.set_position(Gtk.WindowPosition.CENTER)
		self.set_transient_for(parent)

		cfg = parent.load_config()

		vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
		self.add(vbox)

		backups_store = Gtk.ListStore(str)
		for d in cfg["dirs"]:
			backups_store.append([d["name"]])

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Backup name"), xalign=0)
		self.backup_name_combo = Gtk.ComboBox.new_with_model_and_entry(backups_store)
		self.backup_name_combo.set_entry_text_column(0)
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.backup_name_combo, False, True, 0)

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Backup date"), xalign=0)
		self.backup_date_entry = Gtk.Entry()
		self.backup_date_entry.set_text("latest")
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.backup_date_entry, False, True, 0)

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Backup path"), xalign=0)
		self.backup_path_entry = Gtk.Entry()
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.backup_path_entry, False, True, 0)

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Destination"), xalign=0)
		self.dest_folder_btn = Gtk.FileChooserButton.new(_("Choose a destination folder"), Gtk.FileChooserAction.SELECT_FOLDER)
		self.dest_folder_btn.set_filename("/")
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.dest_folder_btn, False, True, 0)

		hbox = Gtk.HButtonBox()
		vbox.add(hbox)

		button = Gtk.Button(_("Cancel"))
		button.connect("clicked", self.on_close_clicked)
		hbox.pack_end(button, False, False, 0)

		button = Gtk.Button(_("Restore"))
		if hasattr(Gtk, "STYLE_CLASS_SUGGESTED_ACTION"): # Since GTK 3.10
			button.get_style_context().add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)
		button.connect("clicked", self.on_restore_clicked)
		hbox.pack_end(button, False, False, 0)

		self.manager = manager

	def restore(self):
		manager = self.manager

		backup_name = self.backup_name_combo.get_child().get_text()
		backup_date = self.backup_date_entry.get_text()
		backup_path = self.backup_path_entry.get_text()
		if backup_name == "":
			return
		from_path = "/" + backup_name +  "/" + backup_date + "/" + backup_path
		to_path = self.dest_folder_btn.get_filename()
		if to_path is None:
			to_path = "/"

		progress_win = Gtk.Dialog(title=_("Restoring..."))
		progress_win.set_default_size(150, 50)
		progress_win.set_border_width(10)
		progress_win.set_transient_for(self)
		progress_win.set_modal(True)
		progress_win.set_position(Gtk.WindowPosition.CENTER)

		box = progress_win.get_content_area()

		label = Gtk.Label(_("Ready."), xalign=0)
		label.set_justify(Gtk.Justification.LEFT)
		box.pack_start(label, False, False, 0)

		progress_win.show_all()

		def set_label(msg):
			label.set_text(msg)

		def close_progress_win(btn):
			progress_win.destroy()

		def add_close_btn():
			hbox = Gtk.HButtonBox()
			box.add(hbox)

			button = Gtk.Button(_("Close"))
			button.connect("clicked", close_progress_win)
			hbox.pack_end(button, False, False, 0)

			progress_win.show_all()
			self.resize(1, 1) # Make window as small as possible

			# Close restore window too
			progress_win.connect("destroy", self.on_close_clicked)

		has_error = False

		def onstatus(status):
			print(status)
			if not has_error:
				GLib.idle_add(set_label, status)

		def onprogress(progress):
			GLib.idle_add(set_label, _("Restoring, "+str(progress["files_done"])+" files done..."))

		def onerror(err):
			print(err) # TODO
			has_error = True

		def onfinish():
			if not has_error:
				GLib.idle_add(set_label, _("Restoration finished."))
			GLib.idle_add(add_close_btn)

		def onabord():
			GLib.idle_add(add_close_btn)

		callbacks = {
			"onstatus": onstatus,
			"onprogress": onprogress,
			"onerror": onerror,
			"onfinish": onfinish,
			"onabord": onabord
		}

		def do_restore(manager, callbacks, from_path, to_path):
			try:
				return manager.restore({
					"from": from_path,
					"to": to_path
				}, callbacks)
			except Exception, e:
				callbacks["onerror"](traceback.format_exc())
				callbacks["onabord"]()

		t = threading.Thread(target=do_restore, args=(manager, callbacks, from_path, to_path))
		t.start()

	def on_restore_clicked(self, btn):
		self.restore()

	def on_close_clicked(self, btn):
		self.destroy()

class SettingsWindow(Gtk.Window):
	def __init__(self, parent):
		Gtk.Window.__init__(self, title=_("Settings"))
		self.set_default_size(150, 100)
		self.set_border_width(10)
		self.set_transient_for(parent)
		self.set_modal(True)
		self.set_icon_name("drive-harddisk")
		self.set_position(Gtk.WindowPosition.CENTER)

		self.cfg = parent.load_config()

		box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
		self.add(box)

		stack, nb = None, None
		if hasattr(Gtk, "Stack"): # Use Stack if available
			stack = Gtk.Stack()
			stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)

			stack_switcher = Gtk.StackSwitcher()
			stack_switcher.set_stack(stack)
			stack_switcher.set_halign(Gtk.Align.CENTER)

			box.pack_start(stack_switcher, False, False, 0)
			box.pack_start(stack, True, True, 0)
		else:
			nb = Gtk.Notebook()
			box.add(nb)

		vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
		if stack is not None:
			stack.add_titled(vbox, "destination", _("Destination"))
		else:
			nb.append_page(vbox, Gtk.Label(_("Destination")))

		# Filesystem type
		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Filesystem type"), xalign=0)

		mount_types = ["", "cifs", "sshfs", "google_drive"]
		mount_types_names = [_("Local"), _("SAMBA"), _("SSH"), _("Google Drive")]
		mount_type_store = Gtk.ListStore(str, str)
		i = 0
		for t in mount_types:
			mount_type_store.append([t, mount_types_names[i]])
			i += 1
		self.mount_type_combo = Gtk.ComboBox.new_with_model(mount_type_store)
		renderer_text = Gtk.CellRendererText()
		self.mount_type_combo.pack_start(renderer_text, True)
		self.mount_type_combo.add_attribute(renderer_text, "text", 1)
		self.mount_type_combo.set_active(mount_types.index(self.cfg["mount"]["type"]))
		self.mount_type_combo.connect("changed", self.on_mount_type_changed)
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.mount_type_combo, False, True, 0)

		self.mount_boxes = {}

		# SAMBA
		samba_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
		vbox.add(samba_box)
		# Samba hostname
		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		samba_box.add(hbox)
		label = Gtk.Label(_("Hostname"), xalign=0)
		self.samba_host_entry = Gtk.Entry()
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.samba_host_entry, False, True, 0)

		# Samba share
		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		samba_box.add(hbox)
		label = Gtk.Label(_("Samba share"), xalign=0)
		self.samba_share_entry = Gtk.Entry()
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.samba_share_entry, False, True, 0)

		# Login
		# TODO: not implemented
		self.samba_guest_check = Gtk.CheckButton(_("Anonymous login"))
		self.samba_guest_check.set_sensitive(False)
		self.samba_guest_check.set_active(True)
		samba_box.add(self.samba_guest_check)

		self.mount_boxes["cifs"] = samba_box

		# SSH
		sshfs_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
		vbox.add(sshfs_box)
		# Samba hostname
		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		sshfs_box.add(hbox)
		label = Gtk.Label(_("Host"), xalign=0)
		self.sshfs_host_entry = Gtk.Entry()
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.sshfs_host_entry, False, True, 0)

		self.mount_boxes["sshfs"] = sshfs_box

		# Path
		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Backup path"), xalign=0)
		self.path_prefix_entry = Gtk.Entry()
		self.path_prefix_entry.set_text(self.cfg["mount"]["path"])
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.path_prefix_entry, False, True, 0)

		# Load mount settings
		if self.cfg["mount"]["type"] == "cifs": # SAMBA
			host = ""
			share = ""
			target = self.cfg["mount"]["target"]
			if target.startswith("//"):
				target = target[2:]
			host, share = target.split("/", 1)

			self.samba_host_entry.set_text(host)
			self.samba_share_entry.set_text(share)
		if self.cfg["mount"]["type"] == "sshfs": # SSH
			self.sshfs_host_entry.set_text(self.cfg["mount"]["target"])

		# Encrypt filesystem?
		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		self.encrypt_check = Gtk.CheckButton(_("Encrypt filesystem"))
		self.encrypt_check.set_active(self.cfg["mount"].get("encrypt", False))
		hbox.add(self.encrypt_check)

		vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
		if stack is not None:
			stack.add_titled(vbox, "schedule", _("Schedule"))
		else:
			nb.append_page(vbox, Gtk.Label(_("Schedule")))

		# Schedulers
		i = 0
		job = None
		active_scheduler = 0 # By default, activate the first one
		for name in schedulers:
			s = schedulers[name]
			try:
				job = s.get_job("bups")
			except IOError, e:
				i += 1
				continue
			active_scheduler = i
			break

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Schedule backups"), xalign=0)
		self.schedule_switch = Gtk.Switch()
		self.schedule_switch.set_active(job is not None)
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.schedule_switch, False, True, 0)

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Scheduler"), xalign=0)
		schedulers_store = Gtk.ListStore(str, str, bool)
		available_schedulers_nbr = 0
		for name in schedulers:
			avail = schedulers[name].is_available()
			if avail:
				available_schedulers_nbr += 1
			schedulers_store.append([name, name, avail])
		self.scheduler_combo = Gtk.ComboBox.new_with_model(schedulers_store)
		renderer_text = Gtk.CellRendererText()
		self.scheduler_combo.pack_start(renderer_text, True)
		self.scheduler_combo.add_attribute(renderer_text, "text", 1)
		self.scheduler_combo.add_attribute(renderer_text, "sensitive", 2)
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.scheduler_combo, False, True, 0)

		if available_schedulers_nbr > 0:
			self.scheduler_combo.set_active(active_scheduler)

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		vbox.add(hbox)
		label = Gtk.Label(_("Interval (days)"), xalign=0)
		period = 1
		if job is not None and "period" in job:
			period = int(job["period"])
		adjustment = Gtk.Adjustment(period, 1, 100, 1, 7, 0)
		self.schedule_period_spin = Gtk.SpinButton()
		self.schedule_period_spin.set_adjustment(adjustment)
		hbox.pack_start(label, True, True, 0)
		hbox.pack_start(self.schedule_period_spin, False, True, 0)

		# if not anacron_available:
		# 	self.schedule_switch.set_sensitive(False)
		# 	self.schedule_period_spin.set_sensitive(False)
		# 	label = Gtk.Label("Could not read anacron config.\nPlease check that anacron is installed and that you can read "+anacron.config_file+".")
		# 	vbox.add(label)

		if available_schedulers_nbr == 0:
			self.schedule_switch.set_sensitive(False)
			self.schedule_period_spin.set_sensitive(False)
			label = Gtk.Label(_("No scheduler available. Please install one of:")+" " + ", ".join(schedulers.keys())+".")
			vbox.add(label)

		# Buttons
		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
		box.add(hbox)
		button = Gtk.Button(_("About"))
		button.connect("clicked", parent.on_about_clicked)
		hbox.pack_start(button, False, False, 0)
		button = Gtk.Button(_("Close"))
		button.connect("clicked", self.on_close_clicked)
		hbox.pack_end(button, False, False, 0)

	def show_all(self):
		Gtk.Window.show_all(self)
		self.on_mount_type_changed()

	def on_close_clicked(self, btn):
		#self.response(Gtk.ResponseType.OK)
		#win.connect("delete-event", win.quit)
		self.hide()

	def on_mount_type_changed(self, combo=None):
		mount_type = self.get_mount_type()

		for t in self.mount_boxes:
			box = self.mount_boxes[t]
			if t == mount_type:
				box.show()
			else:
				box.hide()

		self.resize(1, 1) # Make window as smaller as possible

		if combo is not None: # Not init
			if mount_type == "":
				self.path_prefix_entry.set_text("~/.bup")
			else:
				self.path_prefix_entry.set_text("")

	def get_mount_type(self):
		mount_type_iter = self.mount_type_combo.get_active_iter()
		if mount_type_iter != None:
			model = self.mount_type_combo.get_model()
			return model[mount_type_iter][0]
		else:
			return ""

	def get_config(self):
		self.cfg["mount"]["type"] = self.get_mount_type()
		self.cfg["mount"]["path"] = self.path_prefix_entry.get_text()
		self.cfg["mount"]["encrypt"] = self.encrypt_check.get_active()

		if self.cfg["mount"]["type"] == "cifs": # SAMBA
			self.cfg["mount"]["target"] = "//"+self.samba_host_entry.get_text()+"/"+self.samba_share_entry.get_text()
			opts = ""
			if self.samba_guest_check.get_active():
				opts = "guest"
			self.cfg["mount"]["options"] = opts
		if self.cfg["mount"]["type"] == "sshfs": # SAMBA
			self.cfg["mount"]["target"] = self.sshfs_host_entry.get_text()
		if self.cfg["mount"]["type"] == "": # No fs mounting
			self.cfg["mount"]["target"] = ""
			self.cfg["mount"]["options"] = ""

		return self.cfg

	def get_scheduler_name(self):
		scheduler_iter = self.scheduler_combo.get_active_iter()
		if scheduler_iter != None:
			model = self.scheduler_combo.get_model()
			return model[scheduler_iter][0]
		else:
			return ""

	def get_scheduler_config(self):
		if not self.schedule_switch.get_active():
			return None

		dirname = os.path.realpath(os.path.dirname(__file__))
		logfile = dirname+"/scheduler-log.log"
		cmd = sys.executable+" "+dirname+"/scheduler_worker.py "+config.file_path()
		cmd += " > "+logfile+" 2>&1"

		cfg = {
			"period": self.schedule_period_spin.get_value_as_int(),
			"delay": 15,
			"id": "bups",
			"command": cmd
		}

		return cfg

class BupWindow(Gtk.ApplicationWindow):
	def __init__(self, app):
		Gtk.Window.__init__(self, title="Bups", application=app)
		self.set_default_size(800, 400)
		self.set_icon_name("drive-harddisk")
		self.set_position(Gtk.WindowPosition.CENTER)

		vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
		self.add(vbox)

		if hasattr(Gtk, "HeaderBar"): # Use HeaderBar if available
			hb = Gtk.HeaderBar(title="Bups")
			hb.set_show_close_button(True)
			self.set_titlebar(hb)

			# Add/remove
			box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
			Gtk.StyleContext.add_class(box.get_style_context(), "linked")

			button = Gtk.Button()
			icon = Gio.ThemedIcon(name="list-add-symbolic")
			image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
			button.add(image)
			button.set_tooltip_text(_("Add a directory"))
			button.connect("clicked", self.on_add_clicked)
			box.add(button)

			button = Gtk.Button()
			icon = Gio.ThemedIcon(name="list-remove-symbolic")
			image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
			button.add(image)
			button.set_tooltip_text(_("Remove this directory"))
			button.connect("clicked", self.on_remove_clicked)
			box.add(button)

			if hasattr(Gtk, "Revealer"):
				button = Gtk.ToggleButton()
			else:
				button = Gtk.Button()
			icon = Gio.ThemedIcon(name="document-properties-symbolic")
			image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
			button.add(image)
			button.set_tooltip_text(_("Properties"))
			button.connect("clicked", self.on_properties_clicked)
			box.add(button)
			self.sidebar_btn = button

			hb.pack_start(box)

			# Backup/browse/restore
			box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
			Gtk.StyleContext.add_class(box.get_style_context(), "linked")

			button = Gtk.Button()
			icon = Gio.ThemedIcon(name="drive-harddisk-symbolic")
			image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
			button.add(image)
			button.set_tooltip_text(_("Backup now"))
			button.connect("clicked", self.on_backup_clicked)
			box.add(button)

			button = Gtk.Button()
			icon = Gio.ThemedIcon(name="view-refresh-symbolic")
			image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
			button.add(image)
			button.set_tooltip_text(_("Restore a backup"))
			button.connect("clicked", self.on_restore_clicked)
			box.add(button)

			button = Gtk.Button()
			icon = Gio.ThemedIcon(name="document-open-symbolic")
			image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
			button.add(image)
			button.set_tooltip_text(_("Browse backups"))
			button.connect("clicked", self.on_mount_clicked)
			box.add(button)

			hb.pack_start(box)

			# Settings
			button = Gtk.Button()
			icon = Gio.ThemedIcon(name="emblem-system-symbolic")
			image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
			button.add(image)
			button.set_tooltip_text(_("Settings"))
			button.connect("clicked", self.on_settings_clicked)
			hb.pack_end(button)
		else: # Fallback to Toolbar if HeaderBar is not available
			tb = Gtk.Toolbar()
			tb.set_style(Gtk.ToolbarStyle.ICONS)
			vbox.pack_start(tb, False, False, 0)

			button = Gtk.ToolButton(Gtk.STOCK_ADD)
			button.set_tooltip_text(_("Add a directory"))
			button.connect("clicked", self.on_add_clicked)
			tb.add(button)

			button = Gtk.ToolButton(Gtk.STOCK_REMOVE)
			button.set_tooltip_text(_("Remove this directory"))
			button.connect("clicked", self.on_remove_clicked)
			tb.add(button)

			sep = Gtk.SeparatorToolItem()
			tb.add(sep)

			button = Gtk.ToolButton(Gtk.STOCK_HARDDISK)
			button.set_tooltip_text(_("Backup now"))
			button.connect("clicked", self.on_backup_clicked)
			tb.add(button)

			button = Gtk.ToolButton(Gtk.STOCK_REFRESH)
			button.set_tooltip_text(_("Restore a backup"))
			button.connect("clicked", self.on_restore_clicked)
			tb.add(button)

			button = Gtk.ToolButton(Gtk.STOCK_OPEN)
			button.set_tooltip_text(_("Browse backups"))
			button.connect("clicked", self.on_mount_clicked)
			tb.add(button)

			sep = Gtk.SeparatorToolItem()
			sep.set_draw(False)
			sep.set_expand(True)
			tb.add(sep)

			button = Gtk.ToolButton(Gtk.STOCK_PROPERTIES)
			button.set_tooltip_text(_("Settings"))
			button.connect("clicked", self.on_settings_clicked)
			tb.add(button)

		self.liststore = Gtk.ListStore(str, str)

		self.treeview = Gtk.TreeView(model=self.liststore)

		renderer_text = Gtk.CellRendererText()
		column = Gtk.TreeViewColumn(_("Directory"), renderer_text, text=0)
		column.set_sort_column_id(0)
		self.treeview.append_column(column)

		renderer_text = Gtk.CellRendererText()
		renderer_text.set_property("editable", True)
		renderer_text.connect("edited", self.on_backup_name_edited)
		column = Gtk.TreeViewColumn(_("Name"), renderer_text, text=1)
		column.set_sort_column_id(1)
		self.treeview.append_column(column)

		hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
		vbox.pack_start(hbox, True, True, 0)

		scrolled = Gtk.ScrolledWindow()
		scrolled.add(self.treeview)

		hbox.pack_start(scrolled, True, True, 0)

		self.sidebar = None
		if hasattr(Gtk, "Revealer"): # Gtk.Revealer is available since GTK 3.10
			self.sidebar = Gtk.Revealer()
			self.sidebar.set_transition_type(Gtk.RevealerTransitionType.SLIDE_LEFT)

			self.create_properties(self.sidebar)

			hbox.pack_start(self.sidebar, False, False, 0)

			selection = self.treeview.get_selection()
			selection.connect("changed", self.on_treeview_selection_changed)

		self.config = None
		self.load_config()
		for dirpath in self.config["dirs"]:
			self.add_dir_ui(dirpath)

		sudo_worker = SudoWorker()
		self.manager = BupManager(self.load_config(), sudo_worker)

	def create_properties(self, outer):
		sidebar_ctn = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
		outer.add(sidebar_ctn)

		sidebar_ctn.pack_start(Gtk.VSeparator(), False, False, 0)

		sidebar_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
		sidebar_vbox.set_border_width(10)
		sidebar_ctn.pack_start(sidebar_vbox, True, True, 0)

		sidebar_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
		sidebar_vbox.add(sidebar_hbox)
		label = Gtk.Label(_("Backup name"), xalign=0)
		self.sidebar_name_entry = Gtk.Entry()
		sidebar_hbox.pack_start(label, True, True, 0)
		sidebar_hbox.pack_start(self.sidebar_name_entry, False, True, 0)

		sidebar_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
		sidebar_vbox.add(sidebar_hbox)
		label = Gtk.Label(_("Exclude paths"), xalign=0)
		self.sidebar_exclude_entry = Gtk.Entry()
		sidebar_hbox.pack_start(label, True, True, 0)
		sidebar_hbox.pack_start(self.sidebar_exclude_entry, False, True, 0)

		sidebar_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
		sidebar_vbox.add(sidebar_hbox)
		label = Gtk.Label(_("Exclude patterns"), xalign=0)
		self.sidebar_excluderx_entry = Gtk.Entry()
		sidebar_hbox.pack_start(label, True, True, 0)
		sidebar_hbox.pack_start(self.sidebar_excluderx_entry, False, True, 0)

		label = Gtk.Label()
		label.set_markup("<small>"+_("Enter a comma-separated list of paths and patterns to exclude.")+
			"\n<a href=\"https://github.com/bup/bup/blob/master/Documentation/bup-index.md\">"+_("Read the docs")+"</a></small>")
		sidebar_vbox.add(label)

		self.sidebar_onefilesystem_check = Gtk.CheckButton(_("Don't cross filesystem boundaries"))
		sidebar_vbox.add(self.sidebar_onefilesystem_check)

		sidebar_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
		sidebar_vbox.pack_end(sidebar_hbox, False, False, 0)
		button = Gtk.Button(_("Save"))
		if hasattr(Gtk, "STYLE_CLASS_SUGGESTED_ACTION"): # Since GTK 3.10
			button.get_style_context().add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)
		button.connect("clicked", self.on_sidebar_save)
		sidebar_hbox.pack_end(button, False, False, 0)
		button = Gtk.Button(_("Cancel"))
		button.connect("clicked", self.on_sidebar_cancel)
		sidebar_hbox.pack_end(button, False, False, 0)

	def get_selected_row_index(self):
		selection = self.treeview.get_selection()
		model, treeiter = selection.get_selected()
		if treeiter is None:
			return None
		path = model[treeiter].path
		index = path.get_indices()[0]

		return index

	def show_sidebar(self):
		if type(self.sidebar) == Gtk.Revealer:
			self.sidebar.set_reveal_child(True)
			self.sidebar_btn.set_active(True)

	def hide_sidebar(self):
		if type(self.sidebar) == Gtk.Revealer:
			self.sidebar.set_reveal_child(False)
			self.sidebar_btn.set_active(False)
		if type(self.sidebar) == Gtk.Window:
			self.sidebar.close()
			self.sidebar = None

	def update_sidebar(self):
		index = self.get_selected_row_index()
		if index is None:
			return
		cfg = self.config["dirs"][index]

		self.sidebar_name_entry.set_text(cfg["name"])

		exclude = ""
		if "exclude" in cfg:
			exclude = ", ".join(cfg["exclude"])
		self.sidebar_exclude_entry.set_text(exclude)

		excluderx = ""
		if "excluderx" in cfg:
			excluderx = ", ".join(cfg["excluderx"])
		self.sidebar_excluderx_entry.set_text(excluderx)

		onefilesystem = cfg.get("onefilesystem", False)
		self.sidebar_onefilesystem_check.set_active(onefilesystem)

	def on_treeview_selection_changed(self, selection):
		if self.sidebar.get_reveal_child():
			self.update_sidebar()

	def on_properties_clicked(self, btn):
		index = self.get_selected_row_index()
		is_row_selected = (index is not None)

		if hasattr(Gtk, "Revealer") and type(self.sidebar) == Gtk.Revealer:
			if not self.sidebar_btn.get_active() or not is_row_selected:
				self.hide_sidebar()
				return

			self.update_sidebar()
			self.show_sidebar()
		else:
			if not is_row_selected:
				return

			self.sidebar = Gtk.Window(title=_("Properties"))
			self.sidebar.set_position(Gtk.WindowPosition.CENTER)
			self.sidebar.set_transient_for(self)
			self.sidebar.set_modal(True)
			self.sidebar.set_resizable(False)

			self.create_properties(self.sidebar)
			self.update_sidebar()

			self.sidebar.show_all()

	def on_sidebar_cancel(self, btn):
		self.hide_sidebar()

	def on_sidebar_save(self, btn):
		index = self.get_selected_row_index()

		cfg = self.config["dirs"][index]

		cfg["name"] = self.sidebar_name_entry.get_text()

		exclude = self.sidebar_exclude_entry.get_text()
		cfg["exclude"] = [x.strip() for x in exclude.split(',')]
		if "" in cfg["exclude"]: cfg["exclude"].remove("")

		excluderx = self.sidebar_excluderx_entry.get_text()
		cfg["excluderx"] = [x.strip() for x in excluderx.split(',')]
		if "" in cfg["excluderx"]: cfg["excluderx"].remove("")

		cfg["onefilesystem"] = self.sidebar_onefilesystem_check.get_active()

		self.config["dirs"][index] = cfg
		self.save_config()

		self.hide_sidebar()

	def on_add_clicked(self, btn):
		dialog = Gtk.FileChooserDialog(_("Please choose a directory"), self,
			Gtk.FileChooserAction.SELECT_FOLDER,
			(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
			Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

		response = dialog.run()
		if response == Gtk.ResponseType.OK:
			dirpath = dialog.get_filename()
			print("Dir selected: " + dirpath)

			self.add_dir(dirpath)
		elif response == Gtk.ResponseType.CANCEL:
			print("Cancel clicked")

		dialog.destroy()

	def on_remove_clicked(self, btn):
		selection = self.treeview.get_selection()
		model, treeiter = selection.get_selected()
		if treeiter != None:
			dirpath = model[treeiter][0]
			print("Removing dir "+dirpath)

			model.remove(treeiter)
			i = 0
			for d in self.config["dirs"]:
				dir_data = self.normalize_dir(d)
				if dir_data["path"] == dirpath:
					del self.config["dirs"][i]
				i += 1
			self.save_config()

			self.on_sidebar_cancel(None)

	def get_default_backup_name(self, dirpath):
		login = getpass.getuser()
		dirname = os.path.basename(dirpath).lower()
		return login+"-"+dirname

	def normalize_dir(self, dir_data):
		if type(dir_data) == str or type(dir_data) == unicode:
			dir_data = {
				"path": dir_data,
				"name": self.get_default_backup_name(dir_data)
			}
		return dir_data

	def add_dir(self, dirpath):
		self.config["dirs"].append({
			"path": dirpath,
			"name": self.get_default_backup_name(dirpath)
		})
		self.save_config()
		self.add_dir_ui(dirpath)

	def add_dir_ui(self, dir_data):
		dir_data = self.normalize_dir(dir_data)
		self.liststore.append([dir_data["path"], dir_data["name"]])

	def on_backup_name_edited(self, widget, path, text):
		self.config["dirs"][int(path)]["name"] = text
		self.save_config()
		self.liststore[path][1] = text

	def on_backup_clicked(self, btn):
		win = BackupWindow(self.manager, parent=self)
		win.show_all()

		win.backup()

	def on_restore_clicked(self, btn):
		win = RestoreWindow(self.manager, parent=self)
		win.show_all()

	def on_mount_clicked(self, btn):
		dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO, 0, _("Mounting filesystem..."))

		def open_mounted(data):
			print("Open dir:", data["path"])
			call("xdg-open "+data["path"], shell=True)

		def show_error(e):
			print("ERR: could not mount bup filesystem: "+str(e))
			dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR,
				Gtk.ButtonsType.OK, _("Could not mount filesystem"))
			dialog.format_secondary_text(str(e))
			dialog.run()
			dialog.destroy()

		def onstatus(status):
			GLib.idle_add(dialog.format_secondary_text, status)
			print(status)
		def onready(data):
			GLib.idle_add(dialog.destroy)
			GLib.idle_add(open_mounted, data)
		def onerror(err):
			GLib.idle_add(show_error, err)
		def onabord():
			GLib.idle_add(dialog.destroy)

		dialog.show_all()

		callbacks = {
			"onready": onready,
			"onstatus": onstatus,
			"onerror": onerror,
			"onabord": onabord
		}

		def do_mount(manager, callbacks):
			try:
				manager.mount(callbacks)
			except Exception, e:
				callbacks["onabord"]()
				callbacks["onerror"](traceback.format_exc())

		t = threading.Thread(target=do_mount, args=(self.manager, callbacks))
		t.start()

	def on_settings_clicked(self, btn):
		win = SettingsWindow(self)
		win.connect("hide", self.on_settings_closed)

		win.show_all()

	def on_settings_closed(self, win):
		self.config = win.get_config()
		self.save_config()

		new_scheduler_name = win.get_scheduler_name()
		new_cfg = win.get_scheduler_config()
		win.destroy()

		for name in schedulers:
			try:
				current_scheduler_name = name
				current_cfg = schedulers[name].get_job("bups")
				break
			except IOError, e:
				current_cfg = None

		current_scheduler = schedulers[current_scheduler_name]
		new_scheduler = schedulers[new_scheduler_name]

		def remove_job():
			print("Removing scheduler job "+current_cfg["id"])
			current_scheduler.remove_job(current_cfg["id"])
		def update_job():
			print("Updating scheduler job "+new_cfg["id"])
			new_scheduler.update_job(new_cfg)
		def remove_update_job():
			if current_cfg is not None:
				remove_job()
			update_job()

		def show_error(e):
			print("ERR: could not update scheduler config: "+str(e))
			dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR,
				Gtk.ButtonsType.OK, _("Could not update scheduler config"))
			dialog.format_secondary_text(str(e))
			dialog.run()
			dialog.destroy()

		task = None
		if new_cfg is None and current_cfg is not None: # Remove config
			task = remove_job
		elif new_cfg is not None:
			cfg_changed = True
			if current_scheduler_name != new_scheduler_name:
				task = remove_update_job
			else:
				if current_cfg is not None:
					cfg_changed = int(current_cfg["period"]) != int(new_cfg["period"])
				if cfg_changed: # Add/update config
					task = update_job

		if task is not None: # Run task with a loading dialog
			def run_task(task, onexit):
				try:
					task()
				except Exception, e:
					GLib.idle_add(show_error, e)
				onexit()

			dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO, 0, _("Updating configuration..."))
			def onexit():
				GLib.idle_add(dialog.destroy)

			dialog.show_all()

			t = threading.Thread(target=run_task, args=(task,onexit))
			t.start()

	def on_about_clicked(self, btn):
		dialog = Gtk.AboutDialog()
		dialog.set_transient_for(self)
		dialog.set_title('Bups')
		dialog.set_name('Bups')
		dialog.set_program_name('Bups')
		dialog.set_version(__version__)
		dialog.set_authors(['Emersion'])
		dialog.set_comments(_('Simple GUI for Bup, a very efficient backup system.'))
		dialog.set_website('https://github.com/emersion/bups')
		dialog.set_logo_icon_name('drive-harddisk')
		dialog.set_license(_('Distributed under the MIT license.')+'\nhttp://opensource.org/licenses/MIT')
		dialog.run()
		dialog.destroy()

	def load_config(self):
		if self.config is None:
			self.config = config.read()
		return self.config

	def save_config(self):
		if self.config is None:
			print("INFO: save_config() called but no config set")
			return

		print("Saving config")

		try:
			config.write(self.config)
		except IOError, e:
			print("ERR: could not update config: "+str(e))
			dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR,
				Gtk.ButtonsType.OK, _("Could not update config"))
			dialog.format_secondary_text(str(e))
			dialog.run()
			dialog.destroy()

	def quit(self, *args):
		if self.manager.mounted:
			dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO, 0, _("Unmounting filesystem..."))

			def onstatus(status):
				GLib.idle_add(dialog.format_secondary_text, status)
				print(status)
			def onfinish(data):
				GLib.idle_add(dialog.destroy)
				#GLib.idle_add(Gtk.main_quit)

			dialog.show_all()

			callbacks = {
				"onfinish": onfinish,
				"onstatus": onstatus
			}

			t = threading.Thread(target=self.manager.unmount, args=(callbacks,))
			t.start()
		else:
			pass #Gtk.main_quit()

class BupApp(Gtk.Application):
	def __init__(self):
		Gtk.Application.__init__(self)

	def do_activate(self):
		win = BupWindow(self)
		win.connect("delete-event", win.quit)
		win.show_all()

	def do_startup(self):
		Gtk.Application.do_startup(self)


text:
package com.binaryedu.business.model;

import java.util.ArrayList;

public interface IAnsweredQuestion
{

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#getQuestionNumber()
	 */
	public abstract int getQuestionNumber();

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#setQuestionNumber(int)
	 */
	public abstract void setQuestionNumber(int questionNumber);

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#getDirections()
	 */
	public abstract String getDirections();

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#setDirections(java.lang.String)
	 */
	public abstract void setDirections(String directions);

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#getQuestionText()
	 */
	public abstract String getQuestionText();

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#setQuestionText(java.lang.String)
	 */
	public abstract void setQuestionText(String questionText);

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#getOptions()
	 */
	public abstract ArrayList<String> getOptions();

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#setOptions(java.util.ArrayList)
	 */
	public abstract void setOptions(ArrayList<String> options);

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#getCorrectOption()
	 */
	public abstract int getCorrectOption();

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#setCorrectOption(int)
	 */
	public abstract void setCorrectOption(int correctOption);

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#getSection()
	 */
	public abstract String getSection();

	/* (non-Javadoc)
	 * @see com.binaryedu.business.model.impl.IAnsweredQuestion#setSection(java.lang.String)
	 */
	public abstract void setSection(String section);

	/**
	 * @return the userOption
	 */
	public abstract int getUserOption();

	/**
	 * @param userOption the userOption to set
	 */
	public abstract void setUserOption(int userOption);

	/**
	 * @return the solution
	 */
	public String getSolution();

	/**
	 * @param solution the solution to set
	 */
	public void setSolution(String solution);

}

redpajama_set_name: RedPajamaGithub


text:
using Qoollo.PerformanceCounters.CompositeCounters.Counters;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Qoollo.PerformanceCounters.CompositeCounters.Categories
{
    /// <summary>
    /// Создание категории поддерживающей многочисленные инстансы для CompositeCounters
    /// </summary>
    public class CompositeMultiInstanceCategory: MultiInstanceCategory
    {
        private readonly List<Category> _childCategories;
        private readonly List<MultiInstanceCategory> _wrappedCategories;
        private readonly ConcurrentDictionary<string, CompositeInstanceInMultiInstanceCategory> _instances;
        private readonly ConcurrentDictionary<string, CompositeCounterDescriptor> _counters;

        /// <summary>
        /// Конструктор категории CompositeMultiInstanceCategory
        /// </summary>
        /// <param name="name">Имя категории</param>
        /// <param name="description">Описание категории</param>
        /// <param name="wrappedCategories">Оборачиваемые категории</param>
        public CompositeMultiInstanceCategory(string name, string description, IEnumerable<MultiInstanceCategory> wrappedCategories)
            : base(name, description)
        {
            if (wrappedCategories == null)
                throw new ArgumentNullException("wrappedCategories");

            _childCategories = new List<Category>();
            _counters = new ConcurrentDictionary<string, CompositeCounterDescriptor>();
            _instances = new ConcurrentDictionary<string, CompositeInstanceInMultiInstanceCategory>();
            _wrappedCategories = new List<MultiInstanceCategory>(wrappedCategories);
        }

        /// <summary>
        /// Перечень дочерних категорий
        /// </summary>
        public IEnumerable<Category> ChildCategories { get { return _childCategories; } }
        /// <summary>
        /// Обёрнутые категории
        /// </summary>
        public IEnumerable<MultiInstanceCategory> WrappedCategories { get { return _wrappedCategories; } }

        /// <summary>
        /// Перечень инстансов
        /// </summary>
        public IEnumerable<InstanceInMultiInstanceCategory> Instances { get { return _instances.Values; } }

        /// <summary>
        /// Словарь дескрипторов счётчиков (для внутреннего использования)
        /// </summary>
        internal ConcurrentDictionary<string, CompositeCounterDescriptor> Counters { get { return _counters; } }

        /// <summary>
        /// Получение или создание инстанса
        /// </summary>
        /// <param name="instanceName">Имя инстанса</param>
        /// <returns>Инстанс</returns>
        public override InstanceInMultiInstanceCategory this[string instanceName]
        {
            get
            {
                CompositeInstanceInMultiInstanceCategory result = null;
                if (!_instances.TryGetValue(instanceName, out result))
                    result = _instances.GetOrAdd(instanceName, new CompositeInstanceInMultiInstanceCategory(this, instanceName, _wrappedCategories.Select(wc => wc[instanceName])));

                return result;
            }
        }

        /// <summary>
        /// Существует ли инстанс счётчиков
        /// </summary>
        /// <param name="instanceName">Имя инстанса</param>
        /// <returns>Существует ли</returns>
        public override bool HasInstance(string instanceName)
        {
            return _instances.ContainsKey(instanceName);
        }

        /// <summary>
        /// Удалить инстанс
        /// </summary>
        /// <param name="instanceName">Имя инстанса</param>
        /// <returns>Существал ли</returns>
        public override bool RemoveInstance(string instanceName)
        {
            CompositeInstanceInMultiInstanceCategory inst = null;
            if (_instances.TryRemove(instanceName, out inst))
            {
                inst.OnRemoveFromMultiInstanceCategory();

                foreach (var wrappedCat in _wrappedCategories)
                    wrappedCat.RemoveInstance(instanceName);

                return true;
            }

            return false;
        }

        /// <summary>
        /// Создать счётчик определённого типа
        /// </summary>
        /// <param name="type">Тип счётчика</param>
        /// <param name="counterName">Имя счетчика</param>
        /// <param name="counterDescription">Описание счетчика</param>
        public override void CreateCounter(CounterTypes type, string counterName, string counterDescription)
        {
            if (counterName == null)
                throw new ArgumentNullException("counterName");
            if (counterDescription == null)
                throw new ArgumentNullException("counterDescription");

            if (_instances.Count != 0)
            {
                throw new PerformanceCounterCreationException(
                    string.Format("Can't create counter in multiInstanceCategory ({0}) when it has created instances", this.Name));
            }

            if (_counters.ContainsKey(counterName))
                throw new DuplicateCounterNameException("Counter with the same name is already existed. Name: " + counterName);

            CompositeCounterDescriptor res = null;

            switch (type)
            {
                case CounterTypes.NumberOfItems:
                    res = CompositeNumberOfItemsCounter.CreateDescriptor(counterName, counterDescription);
                    break;
                case CounterTypes.Delta:
                    res = CompositeDeltaCounter.CreateDescriptor(counterName, counterDescription);
                    break;
                case CounterTypes.AverageTime:
                    res = CompositeAverageTimeCounter.CreateDescriptor(counterName, counterDescription);
                    break;
                case CounterTypes.AverageCount:
                    res = CompositeAverageCountCounter.CreateDescriptor(counterName, counterDescription);
                    break;
                case CounterTypes.OperationsPerSecond:
                    res = CompositeOperationsPerSecondCounter.CreateDescriptor(counterName, counterDescription);
                    break;
                case CounterTypes.ElapsedTime:
                    res = CompositeElapsedTimeCounter.CreateDescriptor(counterName, counterDescription);
                    break;
                case CounterTypes.MomentTime:
                    res = CompositeMomentTimeCounter.CreateDescriptor(counterName, counterDescription);
                    break;
                default:
                    throw new InvalidOperationException("Unknown CounterTypes value: " + type.ToString());
            }

            if (!_counters.TryAdd(counterName, res))
                throw new DuplicateCounterNameException("Counter with the same name is already existed. Name: " + counterName);

            foreach (var wrappedCat in _wrappedCategories)
                wrappedCat.CreateCounter(type, counterName, counterDescription);
        }

        /// <summary>
        /// Создание пустой подкатегории
        /// Для добавления элемента в названии категории - Name.SubName.SubSubName
        /// </summary>
        /// <param name="categoryName">Имя подкатегории</param>
        /// <param name="categoryDescription">Описание категории</param>
        /// <returns>Созданная подкатегория</returns>
        public override EmptyCategory CreateEmptySubCategory(string categoryName, string categoryDescription)
        {
            if (categoryName == null)
                throw new ArgumentNullException("categoryName");
            if (categoryDescription == null)
                throw new ArgumentNullException("categoryDescription");

            lock (_childCategories)
            {
                if (_childCategories.Any(o => o.Name == categoryName))
                    throw new DuplicateCategoryNameException("Category with the same name is already registered. Name: " + categoryName);

                var res = new CompositeEmptyCategory(categoryName, categoryDescription, _wrappedCategories.Select(wc => wc.CreateEmptySubCategory(categoryName, categoryDescription)));
                _childCategories.Add(res);
                return res;
            }
        }

        /// <summary>
        /// Создание подкатегории c многими инстансами
        /// </summary>
        /// <param name="categoryName">Имя категории</param>
        /// <param name="categoryDescription">Описание категории</param>
        /// <returns>Созданная подкатегория</returns>
        public override MultiInstanceCategory CreateMultiInstanceSubCategory(string categoryName, string categoryDescription)
        {
            if (categoryName == null)
                throw new ArgumentNullException("categoryName");
            if (categoryDescription == null)
                throw new ArgumentNullException("categoryDescription");

            lock (_childCategories)
            {
                if (_childCategories.Any(o => o.Name == categoryName))
                    throw new DuplicateCategoryNameException("Category with the same name is already registered. Name: " + categoryName);

                var res = new CompositeMultiInstanceCategory(categoryName, categoryDescription, _wrappedCategories.Select(wc => wc.CreateMultiInstanceSubCategory(categoryName, categoryDescription)));
                _childCategories.Add(res);
                return res;
            }
        }

        /// <summary>
        /// Создание простой подкатегории
        /// </summary>
        /// <param name="categoryName">Имя категории</param>
        /// <param name="categoryDescription">Описание категории</param>
        /// <returns>Созданная подкатегория</returns>
        public override SingleInstanceCategory CreateSingleInstanceSubCategory(string categoryName, string categoryDescription)
        {
            if (categoryName == null)
                throw new ArgumentNullException("categoryName");
            if (categoryDescription == null)
                throw new ArgumentNullException("categoryDescription");

            lock (_childCategories)
            {
                if (_childCategories.Any(o => o.Name == categoryName))
                    throw new DuplicateCategoryNameException("Category with the same name is already registered. Name: " + categoryName);

                var res = new CompositeSingleInstanceCategory(categoryName, categoryDescription, _wrappedCategories.Select(wc => wc.CreateSingleInstanceSubCategory(categoryName, categoryDescription)));
                _childCategories.Add(res);
                return res;
            }
        }

        /// <summary>
        /// Инициализация счетчиков (создание категорий, инстанцирование самих счетчиков)
        /// </summary>
        protected internal override void Init()
        {
            foreach (var wrappedCat in WrappedCategories)
                wrappedCat.Init();
        }

        /// <summary>
        /// Освобождение ресурсов
        /// </summary>
        /// <param name="isUserCall">Было ли инициировано пользователем</param>
        protected override void Dispose(bool isUserCall)
        {
            if (isUserCall)
            {
                foreach (var wrappedCat in WrappedCategories)
                    wrappedCat.Dispose();
            }

            base.Dispose(isUserCall);
        }
    }
}


text:
/**
 *
 */
package uk.co.jemos.podam.test.unit.pdm3;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import uk.co.jemos.podam.api.AbstractExternalFactory;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;
import uk.co.jemos.podam.test.dto.*;
import uk.co.jemos.podam.test.dto.pdm3.Pdm3Pojo;
import uk.co.jemos.podam.test.dto.pdm3.Pdm3PojoConstructor;
import uk.co.jemos.podam.test.dto.pdm3.Pdm3PojoGenericsConstructor;

import java.lang.reflect.Type;
import java.util.*;

import static org.junit.Assert.*;

/**
 * @author Marco Tedone
 *
 */
public class Pdm3PojoUnitTest {

	public static class TrackingExternalFactory extends AbstractExternalFactory {

		List<Class<?>> failures = new ArrayList<Class<?>>();

		@Override
		public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) {
			failures.add(pojoClass);
			return null;
		}

		@Override
		public <T> T populatePojo(T pojo, Type... genericTypeArgs) {
			return pojo;
		}
	}

	private static final TrackingExternalFactory trackingFactory
			= new TrackingExternalFactory();

	private static final PodamFactory factory = new PodamFactoryImpl(trackingFactory);

	@Before
	public void start() {
		trackingFactory.failures.clear();
	}

	@After
	public void end() {
		assertEquals(trackingFactory.failures.toString(), 0, trackingFactory.failures.size());
	}

	@Test
	public void testPdm3Pojo() {

		Pdm3Pojo pojo = factory.manufacturePojo(Pdm3Pojo.class);
		assertNotNull(pojo);
		assertCollection(pojo.getSomething(), Object.class);
		assertCollection(pojo.getDescendants(), RuntimeException.class);
		assertCollection(pojo.getAncestors(), NullPointerException.class);
	}

	@Test
	public void testPdm3PojoConstructor() {

		Pdm3PojoConstructor<?> pojo = factory.manufacturePojo(Pdm3PojoConstructor.class, String.class);
		assertNotNull(pojo);
		assertNotNull(pojo.getName());
	}

	@Test
	public void testPdm3ListOfPojos() {

		List<?> pojos =
			factory.manufacturePojo(ArrayList.class, Pdm3PojoConstructor.class, String.class);
		assertCollection(pojos, Pdm3PojoConstructor.class);
	}

	@Test
	public void testPdm3MapOfPojos() {

		Map<?, ?> pojos =
			factory.manufacturePojo(HashMap.class, Integer.class, Pdm3PojoConstructor.class, String.class);
		assertMap(pojos, Integer.class, Pdm3PojoConstructor.class);
	}

	@Test
	public void testPdm3ExtendingListOfPojos() {

		Collection<?> pojos = factory.manufacturePojo(CollectionExtendingGenericsPojo.class);
		assertCollection(pojos, String.class);
	}

	@Test
	public void testPdm3ExtendingRawListOfPojos() {

		Collection<?> pojos = factory.manufacturePojo(CollectionExtendingNoGenericsPojo.class);
		assertCollection(pojos, Object.class);
	}

	@Test
	public void testPdm3IndirectImplementingListOfPojos() {

		Collection<?> pojos = factory.manufacturePojo(CollectionIndirectRawImplPojo.class);
		assertCollection(pojos, Object.class);
	}

	@Test
	public void testPdm3ImplementingListOfPojos() {

		Collection<?> pojos = factory.manufacturePojo(CollectionImplementingGenericsInterface.class);
		assertCollection(pojos, String.class);
	}

	@Test
	public void testPdm3ExtendingImplementingListOfPojos() {

		Collection<?> pojos = factory.manufacturePojo(CollectionExtendingImplementingPojo.class);
		assertCollection(pojos, String.class);
	}

	@Test
	public void testPdm3ExtendingMapOfPojos() {

		Map<?,?> pojos = factory.manufacturePojo(MapExtendingGenericsPojo.class);
		assertMap(pojos, Integer.class, String.class);
	}

	@Test
	public void testPdm3ExtendingNonRawMapOfPojos() {

		Map<?,?> pojos = factory.manufacturePojo(MapExtendingNoGenericsPojo.class);
		assertMap(pojos, Object.class, Object.class);
	}

	@Test
	public void testPdm3IndirectImplementingMapOfPojos() {

		Map<?,?> pojos = factory.manufacturePojo(MapIndirectRawImplPojo.class);
		assertMap(pojos, Object.class, Object.class);
	}

	@Test
	public void testPdm3ImplementingMapOfPojos() {

		Map<?,?> pojos = factory.manufacturePojo(MapImplementingGenericInterface.class);
		assertMap(pojos, Integer.class, String.class);
	}

	@Test
	public void testPdm3ExtendingImplementingMapOfPojos() {

		Map<?,?> pojos = factory.manufacturePojo(MapExtendingImplementingPojo.class);
		assertMap(pojos, Integer.class, String.class);
	}

	@Test
	public void testPdm3PojoGenericsConstructor() {

		Pdm3PojoGenericsConstructor pojo = factory.manufacturePojo(Pdm3PojoGenericsConstructor.class);
		assertNotNull(pojo);
		assertCollection(pojo.getSomething(), Object.class);
		assertCollection(pojo.getDescendants(), RuntimeException.class);
		assertCollection(pojo.getAncestors(), NullPointerException.class);
	}

	@Test
	public void testPdm3ListOfGenericPojos() {

		List<?> pojos =
			factory.manufacturePojo(ArrayList.class, Pdm3PojoGenericsConstructor.class);
		assertCollection(pojos, Pdm3PojoGenericsConstructor.class);
	}

	@Test
	public void testPdm3MapOfGenericPojos() {

		Map<?, ?> pojos =
			factory.manufacturePojo(HashMap.class, String.class, Pdm3PojoGenericsConstructor.class);
		assertMap(pojos, String.class, Pdm3PojoGenericsConstructor.class);
	}

	private void assertCollection(Collection<?> collection, Class<?> elementType) {

		assertNotNull("The collection should not be null", collection);
		assertFalse("The collection should not be empty", collection.isEmpty());
		for (Object obj : collection) {
			assertNotNull("Collection element should not be null", obj);
			assertEquals("Wrong element's type", elementType, obj.getClass());
			if (obj instanceof Pdm3PojoConstructor) {
				Pdm3PojoConstructor<?> pojo = (Pdm3PojoConstructor<?>)obj;
				assertNotNull("Element's field should not be empty", pojo.getName());
				assertEquals("Element's type is String", RuntimeException.class, pojo.getName().getClass());
			}
		}
	}

	private void assertMap(Map<?,?> map, Class<?> keyType, Class<?> valueType) {

		assertNotNull("The map should not be null", map);
		assertFalse("The map should not be empty", map.isEmpty());
		for (Object key : map.keySet()) {
			assertNotNull("Key should not be empty", key);
			assertEquals("Wrong element's type", keyType, key.getClass());
			Object value = map.get(key);
			assertNotNull("Value should not be empty", value);
			assertEquals("Wrong element's type", valueType, value.getClass());
			if (value instanceof Pdm3PojoConstructor) {
				Pdm3PojoConstructor<?> pojo = (Pdm3PojoConstructor<?>)value;
				assertNotNull("Element's field should not be empty", pojo.getName());
				assertEquals("Element's type is String", RuntimeException.class, pojo.getName().getClass());
			}
		}
	}
}


text:
using System;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Nintendo.N64.NativeApi;

namespace BizHawk.Emulation.Cores.Nintendo.N64
{
	class N64Audio : IDisposable
	{
		/// <summary>
		/// mupen64 DLL Api
		/// </summary>
		private mupen64plusAudioApi api;

		private mupen64plusApi coreAPI;

		/// <summary>
		/// Buffer for audio data
		/// </summary>
		private short[] audioBuffer = new short[0];
		private uint _samplingRate = 0;
		/// <summary>
		/// Currently active sampling rate
		/// </summary>
		public uint SamplingRate
		{
			get
			{
				return _samplingRate;
			}
			private set
			{
				_samplingRate = value;
				Resampler.ChangeRate(_samplingRate, 44100, _samplingRate, 44100);
			}
		}
		/// <summary>
		/// Resampler for audio output
		/// </summary>
		public SpeexResampler Resampler { get; private set; }
		public bool RenderSound { get; set; }

		/// <summary>
		/// Creates a N64 Audio subsystem
		/// </summary>
		/// <param name="api">Mupen64 api which is used for fetching sound</param>
		public N64Audio(mupen64plusApi core)
		{
			this.api = new mupen64plusAudioApi(core);

			_samplingRate = api.GetSamplingRate();
			Resampler = new SpeexResampler((SpeexResampler.Quality)6, SamplingRate, 44100,
				SamplingRate, 44100);

			coreAPI = core;
			coreAPI.VInterrupt += DoAudioFrame;
		}

		/// <summary>
		/// Fetches the audio buffer from mupen64plus and pushes it into the
		/// Resampler for audio output
		/// </summary>
		public void DoAudioFrame()
		{
			uint m64pSamplingRate = api.GetSamplingRate();
			if (m64pSamplingRate != SamplingRate)
				SamplingRate = m64pSamplingRate;

			int audioBufferSize = api.GetAudioBufferSize();
			if (audioBuffer.Length < audioBufferSize)
				audioBuffer = new short[audioBufferSize];

			if (audioBufferSize > 0)
			{
				api.GetAudioBuffer(audioBuffer);
				if (RenderSound)
					Resampler.EnqueueSamples(audioBuffer, audioBufferSize / 2);
			}
		}

		public void Dispose()
		{
			coreAPI.VInterrupt -= DoAudioFrame;
			if(Resampler != null)
				Resampler.Dispose();
			Resampler = null;
			api = null;
		}
	}
}


text:
#include "config.h"
#include "core/html/HTMLOutputElement.h"

#include "HTMLNames.h"
#include "core/dom/ExceptionCodePlaceholder.h"

namespace WebCore {

inline HTMLOutputElement::HTMLOutputElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
    : HTMLFormControlElement(tagName, document, form)
    , m_isDefaultValueMode(true)
    , m_isSetTextContentInProgress(false)
    , m_defaultValue("")
    , m_tokens(DOMSettableTokenList::create())
{
    ScriptWrappable::init(this);
}

PassRefPtr<HTMLOutputElement> HTMLOutputElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
{
    return adoptRef(new HTMLOutputElement(tagName, document, form));
}

const AtomicString& HTMLOutputElement::formControlType() const
{
    DEFINE_STATIC_LOCAL(const AtomicString, output, ("output", AtomicString::ConstructFromLiteral));
    return output;
}

bool HTMLOutputElement::supportsFocus() const
{
    return HTMLElement::supportsFocus();
}

void HTMLOutputElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    if (name == HTMLNames::forAttr)
        setFor(value);
    else
        HTMLFormControlElement::parseAttribute(name, value);
}

DOMSettableTokenList* HTMLOutputElement::htmlFor() const
{
    return m_tokens.get();
}

void HTMLOutputElement::setFor(const String& value)
{
    m_tokens->setValue(value);
}

void HTMLOutputElement::childrenChanged(bool createdByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
    HTMLFormControlElement::childrenChanged(createdByParser, beforeChange, afterChange, childCountDelta);

    if (createdByParser || m_isSetTextContentInProgress) {
        m_isSetTextContentInProgress = false;
        return;
    }

    if (m_isDefaultValueMode)
        m_defaultValue = textContent();
}

void HTMLOutputElement::reset()
{
    // The reset algorithm for output elements is to set the element's
    // value mode flag to "default" and then to set the element's textContent
    // attribute to the default value.
    m_isDefaultValueMode = true;
    if (m_defaultValue == value())
        return;
    setTextContentInternal(m_defaultValue);
}

String HTMLOutputElement::value() const
{
    return textContent();
}

void HTMLOutputElement::setValue(const String& value)
{
    // The value mode flag set to "value" when the value attribute is set.
    m_isDefaultValueMode = false;
    if (value == this->value())
        return;
    setTextContentInternal(value);
}

String HTMLOutputElement::defaultValue() const
{
    return m_defaultValue;
}

void HTMLOutputElement::setDefaultValue(const String& value)
{
    if (m_defaultValue == value)
        return;
    m_defaultValue = value;
    // The spec requires the value attribute set to the default value
    // when the element's value mode flag to "default".
    if (m_isDefaultValueMode)
        setTextContentInternal(value);
}

void HTMLOutputElement::setTextContentInternal(const String& value)
{
    ASSERT(!m_isSetTextContentInProgress);
    m_isSetTextContentInProgress = true;
    setTextContent(value, IGNORE_EXCEPTION);
}

} // namespace


text:
/**
 * Module dependencies.
 */

var http = require('http'),
    utils = require('./utils'),
    mime = require('../connect/utils').mime;

/**
 * Return request header or optional default.
 *
 * Examples:
 *
 *     req.header('Content-Type');
 *     // => "text/plain"
 *
 *     req.header('content-type');
 *     // => "text/plain"
 *
 *     req.header('Accept');
 *     // => undefined
 *
 *     req.header('Accept', 'text/html');
 *     // => "text/html"
 *
 * @param {String} name
 * @param {String} defaultValue
 * @return {String}
 * @api public
 */

http.IncomingMessage.prototype.header = function(name, defaultValue){
    return this.headers[name.toLowerCase()] || defaultValue;
};

/**
 * Check if the _Accept_ header is present, and includes the given `type`.
 *
 * When the _Accept_ header is not present `true` is returned. Otherwise
 * the given `type` is matched by an exact match, and then subtypes. You
 * may pass the subtype such as "html" which is then converted internally
 * to "text/html" using the mime lookup table.
 *
 * Examples:
 *
 *     // Accept: text/html
 *     req.accepts('html');
 *     // => true
 *
 *     // Accept: text/*; application/json
 *     req.accepts('html');
 *     req.accepts('text/html');
 *     req.accepts('text/plain');
 *     req.accepts('application/json');
 *     // => true
 *
 *     req.accepts('image/png');
 *     req.accepts('png');
 *     // => false
 *
 * @param {String} type
 * @return {Boolean}
 * @api public
 */

http.IncomingMessage.prototype.accepts = function(type){
    var accept = this.header('Accept');
    if (!accept || accept === '*/*') {
        return true;
    } else if (type) {
        // Allow "html" vs "text/html" etc
        if (type.indexOf('/') < 0) {
            type = mime.types['.' + type];
        }
        // Check if we have a direct match
        if (accept.indexOf(type) >= 0) {
            return true;
        // Check if we have type/*
        } else {
            type = type.split('/')[0] + '/*';
            return accept.indexOf(type) >= 0;
        }
    } else {
        return false;
    }
};

/**
 * Return the value of param `name` when present.
 *
 *  - Checks route placeholders, ex: _/user/:id_
 *  - Checks query string params, ex: ?id=12
 *  - Checks urlencoded body params, ex: id=12
 *
 * To utilize urlencoded request bodies, `req.body`
 * should be an object. This can be done by using
 * the `connect.bodyDecoder` middleware.
 *
 * @param {String} name
 * @return {String}
 * @api public
 */

http.IncomingMessage.prototype.param = function(name){
    // Route params like /user/:id
    if (this.params[name] !== undefined) {
        return this.params[name];
    }
    // Query string params
    if (this.query[name] !== undefined) {
        return this.query[name];
    }
    // Request body params via connect.bodyDecoder
    if (this.body && this.body[name] !== undefined) {
        return this.body[name];
    }
};

/**
 * Queue flash `msg` of the given `type`.
 *
 * Examples:
 *
 *      req.flash('info', 'email sent');
 *      req.flash('error', 'email delivery failed');
 *      req.flash('info', 'email re-sent');
 *      // => 2
 *
 *      req.flash('info');
 *      // => ['email sent', 'email re-sent']
 *
 *      req.flash('info');
 *      // => []
 *
 *      req.flash();
 *      // => { error: ['email delivery failed'], info: [] }
 *
 * @param {String} type
 * @param {String} msg
 * @return {Array|Object|Number}
 * @api public
 */

http.IncomingMessage.prototype.flash = function(type, msg){
    var msgs = this.session.flash = this.session.flash || {};
    if (type && msg) {
        msg = utils.miniMarkdown(utils.htmlEscape(msg));
        return (msgs[type] = msgs[type] || []).push(msg);
    } else if (type) {
        var arr = msgs[type];
        delete msgs[type];
        return arr || [];
    } else {
        this.session.flash = {};
        return msgs;
    }
};

// Callback for isXMLHttpRequest / xhr

function isxhr() {
    return this.header('X-Requested-With', '').toLowerCase() === 'xmlhttprequest';
}

/**
 * Check if the request was an _XMLHttpRequest_.
 *
 * @return {Boolean}
 * @api public
 */

http.IncomingMessage.prototype.__defineGetter__('isXMLHttpRequest', isxhr);
http.IncomingMessage.prototype.__defineGetter__('xhr', isxhr);


text:
<?php
require_once ("person_controller.php");
class Customers extends Person_controller {
	function __construct() {
		parent::__construct('customers');
	}

	function index() {
		$config['base_url'] = site_url('/customers/index');
		$config['total_rows'] = $this->Customer->count_all();
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$this->pagination->initialize($config);

		$data['controller_name']=strtolower(get_class());
		$data['form_width']=$this->get_form_width();
		$data['manage_table']=get_people_manage_table( $this->Customer->get_all( $config['per_page'], $this->uri->segment( $config['uri_segment'] ) ), $this );
		//$this->load->view('people/manage',$data);
		$data['selected_module'] = 'customers';

		$this->smartyci->assign($data);
 		$this->smartyci->display( 'people/manage.php.tpl' );
	}

	function basic_info() {
 		$this->smartyci->display( 'people/form_basic_info.php.tpl' );
	}

	/*
	Returns customer table data rows. This will be called with AJAX.
	*/
	function search() {
		$search=$this->input->post('search');
		$data_rows=get_people_manage_table_data_rows($this->Customer->search($search),$this);
		echo $data_rows;
	}

	/*
	Gives search suggestions based on what is being searched for
	*/
	function suggest() {
		$suggestions = $this->Customer->get_search_suggestions($this->input->post('q'),$this->input->post('limit'));
		echo implode("\n",$suggestions);
	}

	/*
	Loads the customer edit form
	*/
	function view($customer_id=-1) {
		$data['person_info']=$this->Customer->get_info($customer_id);
		//$this->load->view("customers/form",$data);
		$data["modal_id"]='#'.$this->input->get('modal_id', true);
		$this->smartyci->assign($data);
 		$this->smartyci->display( 'customers/form.php.tpl' );
	}

	/*
	Inserts/updates a customer
	*/
	function save($customer_id=-1) {
		$person_data = array(
			'first_name'=>$this->input->post('first_name'),
			'last_name'=>$this->input->post('last_name'),
			'email'=>$this->input->post('email'),
			'phone_number'=>$this->input->post('phone_number'),
			'address_1'=>$this->input->post('address_1'),
			'address_2'=>$this->input->post('address_2'),
			'city'=>$this->input->post('city'),
			'state'=>$this->input->post('state'),
			'zip'=>$this->input->post('zip'),
			'country'=>$this->input->post('country'),
			'comments'=>$this->input->post('comments')
		);
		$customer_data= array(
			'account_number'=>$this->input->post('account_number')=='' ? null:$this->input->post('account_number'),
			'taxable'=>$this->input->post('taxable')=='' ? 0:1,
		);
		if($this->Customer->save($person_data,$customer_data,$customer_id)) {
			//New customer
			if($customer_id==-1) {
				echo json_encode(array('success'=>true,'message'=>$this->lang->line('customers_successful_adding').' '.
				$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>$customer_data['person_id']));
			} else { //previous customer
				echo json_encode(array('success'=>true,'message'=>$this->lang->line('customers_successful_updating').' '.
				$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>$customer_id));
			}
		} else { //failure
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('customers_error_adding_updating').' '.
			$person_data['first_name'].' '.$person_data['last_name'],'person_id'=>-1));
		}
	}

	/*
	This deletes customers from the customers table
	*/
	function delete()
	{
		$customers_to_delete=$this->input->post('ids');

		if($this->Customer->delete_list($customers_to_delete))
		{
			echo json_encode(array('success'=>true,'message'=>$this->lang->line('customers_successful_deleted').' '.
			count($customers_to_delete).' '.$this->lang->line('customers_one_or_multiple')));
		}
		else
		{
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('customers_cannot_be_deleted')));
		}
	}

	function excel() {
		$this->load->dbutil();

		$query = $this->Customer->get_all_export();

		$data = $this->dbutil->csv_from_result($query);

		//$data = file_get_contents("import_customers.csv");
		$name = 'import_customers.csv';
		force_download($name, $data);
	}

	function excel_import() {
		$data["modal_id"]='#'.$this->input->get('modal_id', true);
		$this->smartyci->assign($data);
 		$this->smartyci->display( 'customers/excel_import.php.tpl' );
	}

	function do_excel_import() {
		$msg = 'do_excel_import';
		$failCodes = array();
		header('Content-Type: application/json');
		if ($_FILES['file_path']['error']!=UPLOAD_ERR_OK)
		{
			$msg = $this->lang->line('items_excel_import_failed');
			echo json_encode( array('success'=>false,'message'=>$msg) );
			return;
		}
		else
		{
			if (($handle = fopen($_FILES['file_path']['tmp_name'], "r")) !== FALSE)
			{
				//Skip first row
				fgetcsv($handle);

				$i=1;
				while (($data = fgetcsv($handle)) !== FALSE)
				{
					$person_data = array(
						'first_name'=>$data[0],
						'last_name'=>$data[1],
						'email'=>$data[2],
						'phone_number'=>$data[3],
						'address_1'=>$data[4],
						'address_2'=>$data[5],
						'city'=>$data[6],
						'state'=>$data[7],
						'zip'=>$data[8],
						'country'=>$data[9],
						'comments'=>$data[10]
					);

					$customer_data=array(
						'account_number'=>$data[11]=='' ? null:$data[11],
						'taxable'=>$data[12]=='' ? 0:1,
					);

					if(!$this->Customer->save($person_data,$customer_data))
					{
						$failCodes[] = $i;
					}

					$i++;
				}
			}
			else
			{
				echo json_encode( array('success'=>false,'message'=>'Your upload file has no data or not in supported format.') );
				return;
			}
		}

		$success = true;
		if(count($failCodes) > 1)
		{
			$msg = "Most customers imported. But some were not, here is list of their CODE (" .count($failCodes) ."): ".implode(", ", $failCodes);
			$success = false;
		}
		else
		{
			$msg = "Import Customers successful";
		}

		echo json_encode( array('success'=>$success,'message'=>$msg) );
	}

	/*
	get the width for the add/edit form
	*/
	function get_form_width() {
		return 350;
	}

	function get_modal_id() {
		return "#myModal";
	}
}
?>


text:
/**
 * Handles loading of product tabs
 */
function ProductTabsManager(){
	var self = this;
	this.product_tabs = [];
	this.current_request;
	this.stack_error = [];
	this.page_reloading = false;

	this.setTabs = function(tabs){
		this.product_tabs = tabs;
	}

	/**
	 * Schedule execution of onReady() function for each tab and bind events
	 */
	this.init = function(){
		for (var tab_name in this.product_tabs)
		{
			if (this.product_tabs[tab_name].onReady !== undefined)
				this.onLoad(tab_name, this.product_tabs[tab_name].onReady);
		}

		// @see with tDidierjean
		//$(document).bind('change', function(){
		//	if (self.current_request)
		//	{
		//		self.current_request.abort();
		//	}
		//});

		$('.shopList.chzn-done').bind('change', function(){
			if (self.current_request)
			{
				self.page_reloading = true;
				self.current_request.abort();
			}
		});

		$(window).bind('beforeunload', function() {
			self.page_reloading = true;
		});
	}

	/**
	 * Execute a callback function when a specific tab has finished loading or right now if the tab has already loaded
	 *
	 * @param tab_name name of the tab that is checked for loading
	 * @param callback_function function to call
	 */
	this.onLoad = function (tab_name, callback)
	{
		var container = $('#product-tab-content-' + tab_name);
		// Some containers are not loaded depending on the shop configuration
		if (container.length === 0)
			return;

		// onReady() is always called after the dom has been created for the tab (similar to $(document).ready())
		if (container.hasClass('not-loaded'))
			container.bind('loaded', callback);
		else
			callback();
	}

	/**
	 * Get a single tab or recursively get tabs in stack then display them
	 *
	 * @param string tab_name name of the tab
	 * @param boolean selected is the tab selected
	 */
	this.display = function (tab_name, selected)
	{
		var tab_selector = $("#product-tab-content-"+tab_name);

		// Is the tab already being loaded?
		if (!tab_selector.hasClass('not-loaded') || tab_selector.hasClass('loading'))
			return;

		// Mark the tab as being currently loading
		tab_selector.addClass('loading');

		if (selected)
			$('#product-tab-content-wait').show();

		// send $_POST array with the request to be able to retrieve posted data if there was an error while saving product
		var data;
		if (save_error)
		{
			data = post_data;
			// set key_tab so that the ajax call returns the display for the current tab
			data.key_tab = tab_name;
		}

		return $.ajax({
			url : $('#link-'+tab_name).attr("href")+"&ajax=1" + '&rand=' + new Date().getTime(),
			async : true,
			cache: false, // cache needs to be set to false or IE will cache the page with outdated product values
			type: 'POST',
			headers: { "cache-control": "no-cache" },
			data: data,
			success : function(data)
			{
				tab_selector.html(data);
				tab_selector.removeClass('not-loaded');

				if (selected)
				{
					$("#link-"+tab_name).addClass('selected');
					tab_selector.show();
				}
				tab_selector.trigger('loaded');
			},
			complete : function(data)
			{
				tab_selector.removeClass('loading');
				if (selected)
				{
					$('#product-tab-content-wait').hide();
					tab_selector.trigger('displayed');
				}
			},
			beforeSend : function(data)
			{
				// don't display the loading notification bar
				if (typeof(ajax_running_timeout) !== 'undefined')
					clearTimeout(ajax_running_timeout);
			}
		});
	}

	/**
	 * Send an ajax call for each tab in the stack, binding each call to the "complete" event of the previous call
	 *
	 * @param array stack contains tab names as strings
	 */
	this.displayBulk = function(stack){
		this.current_request = this.display(stack[0], false);

		if (this.current_request !== undefined)
		{
			this.current_request.complete(function(request, status) {
				if (status === 'abort' || status === 'error')
					self.stack_error.push(stack.shift());
				else
					stack.shift()
				if (stack.length !== 0 && status !== 'abort')
				{
					self.displayBulk(stack);
				}
				else if (self.stack_error.length !== 0 && !self.page_reloading)
				{
					jConfirm(reload_tab_description, reload_tab_title, function(confirm) {
						if (confirm === true)
						{
							self.displayBulk(self.stack_error.slice(0));
							self.stack_error = [];
						}
						else
							return false;
					});
				}
			});
		}
	}
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DropDownButton.cs" company="Catel development team">
//   Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

#if NET

namespace Catel.Windows.Controls
{
    using System;
    using System.Windows;
    using System.Windows.Controls.Primitives;
    using System.Windows.Threading;

    /// <summary>
    /// DropDownButton, which is unfortunately missing in the controls library of WPF.
    /// </summary>
    /// <remarks>
    /// The code for this control is based on the code found at http://andyonwpf.blogspot.com/2006/10/dropdownbuttons-in-wpf.html.
    /// </remarks>
    [ObsoleteEx(ReplacementTypeOrMember = "Orc.Controls, see https://github.com/wildgums/orc.controls", TreatAsErrorFromVersion = "4.2", RemoveInVersion = "5.0")]
    public class DropDownButton : ToggleButton
    {
        #region Fields
        private Popup _popup;
        private DispatcherTimer _dispatcherTimer;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="DropDownButton"/> class.
        /// </summary>
        public DropDownButton()
        {
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets DropDownContent.
        /// </summary>
        /// <remarks>
        /// Wrapper for the DropDownContent dependency property.
        /// </remarks>
        public UIElement DropDownContent
        {
            get { return (UIElement)GetValue(DropDownContentProperty); }
            set { SetValue(DropDownContentProperty, value); }
        }

        /// <summary>
        /// DependencyProperty definition as the backing store for DropDownContent.
        /// </summary>
        public static readonly DependencyProperty DropDownContentProperty = DependencyProperty.Register("DropDownContent", typeof(UIElement),
            typeof(DropDownButton), new UIPropertyMetadata(null, (sender, e) => ((DropDownButton)sender).OnDropDownContentChanged(sender, e)));
        #endregion

        #region Methods
        /// <summary>
        /// Invoked when the DropDownContent dependency property has changed.
        /// </summary>
        /// <param name="sender">The object that contains the dependency property.</param>
        /// <param name="e">The event data.</param>
        private void OnDropDownContentChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (_popup != null)
            {
                _popup.LostFocus -= OnPopupLostFocus;
            }

            if ((e.NewValue == null) || !(e.NewValue is UIElement))
            {
                _popup = null;
                return;
            }

            _popup = new Popup();
            _popup.Child = (UIElement)e.NewValue;
            _popup.StaysOpen = false;
            _popup.PopupAnimation = PopupAnimation.Fade;
            _popup.LostFocus += OnPopupLostFocus;
        }

        /// <summary>
        /// Called when the popup has lost its focus.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnPopupLostFocus(object sender, RoutedEventArgs e)
        {
            if (_dispatcherTimer == null)
            {
                _dispatcherTimer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 40), DispatcherPriority.Normal, OnDispatcherTimerTick, Dispatcher);
            }

            _dispatcherTimer.Start();
        }

        /// <summary>
        /// Called when the dispatcher timer has invoked the tick event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void OnDispatcherTimerTick(object sender, EventArgs e)
        {
            ResetTimer();

            if (_popup != null)
            {
                _popup.IsOpen = false;
            }
        }

        /// <summary>
        /// Called when a control is clicked by the mouse or the keyboard.
        /// </summary>
        protected override void OnClick()
        {
            // If there is a drop-down assigned to this button, then position and display it
            if (_popup != null)
            {
                _popup.PlacementTarget = this;
                _popup.Placement = PlacementMode.Bottom;
                _popup.IsOpen = true;
                _popup.Child.Focus();
            }
        }

        /// <summary>
        /// Resets the timer.
        /// </summary>
        private void ResetTimer()
        {
            if (_dispatcherTimer != null)
            {
                _dispatcherTimer.Stop();
                _dispatcherTimer = null;
            }
        }
        #endregion
    }
}

#endif


text:
package ts.internal.client.protocol;

import java.util.List;

import com.google.gson.JsonObject;

import ts.client.CommandNames;
import ts.client.completions.CompletionEntryDetails;

/**
 * Completion entry details request; value of command field is
 * "completionEntryDetails". Given a file location (file, line, col) and an
 * array of completion entry names return more detailed information for each
 * completion entry.
 *
 * @see https://github.com/Microsoft/TypeScript/blob/master/src/server/protocol.ts
 *
 */
public class CompletionDetailsRequest extends FileLocationRequest<CompletionDetailsRequestArgs> {

	public CompletionDetailsRequest(String file, int line, int offset, String prefix, String[] entryNames) {
		super(CommandNames.CompletionEntryDetails.getName(),
				new CompletionDetailsRequestArgs(file, line, offset, prefix, entryNames));
	}

	@Override
	public Response<List<CompletionEntryDetails>> parseResponse(JsonObject json) {
		return GsonHelper.DEFAULT_GSON.fromJson(json, CompletionDetailsResponse.class);
	}

}


text:
import arrow
import re

from ..slack.resource import MsgResource

from ..utils.data_handler import DataHandler
from ..utils.member import Member

class BusinessCard(object):
    def __init__(self, slackbot=None):
        self.fname = "card.json"
        self.data_handler = DataHandler()

        if slackbot is None:
            self.slackbot = SlackerAdapter()
        else:
            self.slackbot = slackbot

    def read_holder(self):
        card_data = self.data_handler.read_file(self.fname)
        holder_names = ", ".join(card_data.get("holder", []))
        holder_names = re.sub("([A-Z])+", r"\1-", holder_names)
        self.slackbot.send_message(text=MsgResource.CARD_HOLDER(names=holder_names))

    def read_history(self):
        card_data = self.data_handler.read_file(self.fname)
        historys = "\n - ".join(card_data.get("history", [])[-5:])
        self.slackbot.send_message(text=MsgResource.CARD_HISTORY(historys=historys))

    def forward(self, member):
        if member is None:
            self.slackbot.send_message(text=MsgResource.CARD_FORWARD_NONE)
            return
        elif len(member) > 2:
            self.slackbot.send_message(text=MsgResource.CARD_FORWARD_NONE)
            return

        if len(member) == 2:
            from_name = member[0]
            to_name = member[1]
        else:  # len(member) == 1
            member_util = Member()
            from_name = member_util.get_name(self.slackbot.user)
            to_name = member[0]

        if from_name != to_name:
            card_data = self.data_handler.read_file(self.fname)

            holder_data = card_data.get("holder", [])

            if from_name not in holder_data:
                self.slackbot.send_message(
                    text=MsgResource.NOT_CARD_HOLDER(from_name=from_name)
                )
                return

            holder_data.remove(from_name)
            holder_data.append(to_name)

            history_data = card_data.get("history", [])
            history_data.append(
                arrow.now().format("YYYY-MM-DD HH:mm") + f": {from_name} -> {to_name}"
            )

            card_data["holder"] = holder_data
            card_data["history"] = history_data

            self.data_handler.write_file(self.fname, card_data)

        self.slackbot.send_message(
            text=MsgResource.CARD_FORWARD(from_name=from_name, to_name=to_name)
        )


text:
exports.componentDefinition = {
  name: 'withBoolResultTask',
  component: {
    result: null
  }
}