text:
	local p = premake
	local gmake2 = p.modules.gmake2

	gmake2.cpp       = {}
	local cpp        = gmake2.cpp

	local project    = p.project
	local config     = p.config
	local fileconfig = p.fileconfig

---
-- Add namespace for element definition lists for premake.callarray()
---

	cpp.elements = {}

--
-- Generate a GNU make C++ project makefile, with support for the new platforms API.
--

	cpp.elements.makefile = function(prj)
		return {
			gmake2.header,
			gmake2.phonyRules,
			gmake2.shellType,
			cpp.createRuleTable,
			cpp.outputConfigurationSection,
			cpp.outputPerFileConfigurationSection,
			cpp.createFileTable,
			cpp.outputFilesSection,
			cpp.outputRulesSection,
			cpp.outputFileRuleSection,
			cpp.dependencies,
		}
	end

	function cpp.generate(prj)
		p.eol("\n")
		p.callArray(cpp.elements.makefile, prj)

		-- allow the garbage collector to clean things up.
		for cfg in project.eachconfig(prj) do
			cfg._gmake = nil
		end
		prj._gmake = nil
	end

	function cpp.initialize()
		rule 'cpp'
			fileExtension { ".cc", ".cpp", ".cxx", ".mm" }
			buildoutputs  { "$(OBJDIR)/%{premake.modules.gmake2.cpp.makeUnique(cfg, file.objname)}.o" }
			buildmessage  '$(notdir $<)'
			buildcommands {'$(CXX) %{premake.modules.gmake2.cpp.fileFlags(cfg, file)} $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<"'}

		rule 'cc'
			fileExtension {".c", ".s", ".m"}
			buildoutputs  { "$(OBJDIR)/%{premake.modules.gmake2.cpp.makeUnique(cfg, file.objname)}.o" }
			buildmessage  '$(notdir $<)'
			buildcommands {'$(CC) %{premake.modules.gmake2.cpp.fileFlags(cfg, file)} $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<"'}

		rule 'resource'
			fileExtension ".rc"
			buildoutputs  { "$(OBJDIR)/%{premake.modules.gmake2.cpp.makeUnique(cfg, file.objname)}.res" }
			buildmessage  '$(notdir $<)'
			buildcommands {'$(RESCOMP) $< -O coff -o "$@" $(ALL_RESFLAGS)'}

		global(nil)
	end

	function cpp.createRuleTable(prj)
		local rules = {}

		local function addRule(extension, rule)
			if type(extension) == 'table' then
				for _, value in ipairs(extension) do
					addRule(value, rule)
				end
			else
				rules[extension] = rule
			end
		end

		-- add all rules.
		local usedRules = table.join({'cpp', 'cc', 'resource'}, prj.rules)
		for _, name in ipairs(usedRules) do
			local rule = p.global.getRule(name)
			addRule(rule.fileExtension, rule)
		end

		-- create fileset categories.
		local filesets = {
			['.o']   = 'OBJECTS',
			['.obj'] = 'OBJECTS',
			['.cc']  = 'SOURCES',
			['.cpp'] = 'SOURCES',
			['.cxx'] = 'SOURCES',
			['.mm']  = 'SOURCES',
			['.c']   = 'SOURCES',
			['.s']   = 'SOURCES',
			['.m']   = 'SOURCES',
			['.rc']  = 'RESOURCES',
		}

		-- cache the result.
		prj._gmake = prj._gmake or {}
		prj._gmake.rules = rules
		prj._gmake.filesets = filesets
	end

	function cpp.createFileTable(prj)
		for cfg in project.eachconfig(prj) do
			cfg._gmake = cfg._gmake or {}
			cfg._gmake.filesets = {}
			cfg._gmake.fileRules = {}
			cfg._gmake.bases = {}

			local files = table.shallowcopy(prj._.files)
			table.foreachi(files, function(node)
				cpp.addFile(cfg, node)
			end)

			for _, f in pairs(cfg._gmake.filesets) do
				table.sort(f)
			end

			cfg._gmake.kinds = table.keys(cfg._gmake.filesets)
			table.sort(cfg._gmake.kinds)

			prj._gmake.kinds = table.join(prj._gmake.kinds or {}, cfg._gmake.kinds)
		end

		-- we need to reassign object sequences if we generated any files.
		if prj.hasGeneratedFiles and p.project.iscpp(prj) then
			p.oven.assignObjectSequences(prj)
		end

		prj._gmake.kinds = table.unique(prj._gmake.kinds)
		table.sort(prj._gmake.kinds)
	end

	function cpp.addFile(cfg, node)
		local filecfg = fileconfig.getconfig(node, cfg)
		if not filecfg or filecfg.flags.ExcludeFromBuild then
			return
		end

		-- skip generated files, since we try to figure it out manually below.
		if node.generated then
			return
		end

		-- process custom build commands.
		if fileconfig.hasCustomBuildRule(filecfg) then
			local env = table.shallowcopy(filecfg.environ)
			env.PathVars = {
				["file.basename"]     = { absolute = false, token = node.basename },
				["file.abspath"]      = { absolute = true,  token = node.abspath },
				["file.relpath"]      = { absolute = false, token = node.relpath },
				["file.name"]         = { absolute = false, token = node.name },
				["file.objname"]      = { absolute = false, token = node.objname },
				["file.path"]         = { absolute = true,  token = node.path },
				["file.directory"]    = { absolute = true,  token = path.getdirectory(node.abspath) },
				["file.reldirectory"] = { absolute = false, token = path.getdirectory(node.relpath) },
			}

			local shadowContext = p.context.extent(filecfg, env)

			local buildoutputs = p.project.getrelative(cfg.project, shadowContext.buildoutputs)
			if buildoutputs and #buildoutputs > 0 then
				local file = {
					buildoutputs  = buildoutputs,
					source        = node.relpath,
					buildmessage  = shadowContext.buildmessage,
					buildcommands = shadowContext.buildcommands,
					buildinputs   = p.project.getrelative(cfg.project, shadowContext.buildinputs)
				}
				table.insert(cfg._gmake.fileRules, file)

				for _, output in ipairs(buildoutputs) do
					cpp.addGeneratedFile(cfg, node, output)
				end
			end
		else
			cpp.addRuleFile(cfg, node)
		end
	end

	function cpp.determineFiletype(cfg, node)
		-- determine which filetype to use
		local filecfg = fileconfig.getconfig(node, cfg)
		local fileext = path.getextension(node.abspath):lower()
		if filecfg and filecfg.compileas then
			if p.languages.isc(filecfg.compileas) then
				fileext = ".c"
			elseif p.languages.iscpp(filecfg.compileas) then
				fileext = ".cpp"
			end
		end

		return fileext;
	end

	function cpp.addGeneratedFile(cfg, source, filename)
		-- mark that we have generated files.
		cfg.project.hasGeneratedFiles = true

		-- add generated file to the project.
		local files = cfg.project._.files
		local node = files[filename]
		if not node then
			node = fileconfig.new(filename, cfg.project)
			files[filename] = node
			table.insert(files, node)
		end

		-- always overwrite the dependency information.
		node.dependsOn = source
		node.generated = true

		-- add to config if not already added.
		if not fileconfig.getconfig(node, cfg) then
			fileconfig.addconfig(node, cfg)
		end

		-- determine which filetype to use
		local fileext = cpp.determineFiletype(cfg, node)
		-- add file to the fileset.
		local filesets = cfg.project._gmake.filesets
		local kind     = filesets[fileext] or "CUSTOM"

		-- don't link generated object files automatically if it's explicitly
		-- disabled.
		if path.isobjectfile(filename) and source.linkbuildoutputs == false then
			kind = "CUSTOM"
		end

		local fileset = cfg._gmake.filesets[kind] or {}
		table.insert(fileset, filename)
		cfg._gmake.filesets[kind] = fileset

		-- recursively setup rules.
		cpp.addRuleFile(cfg, node)
	end

	function cpp.prepareEnvironment(rule, environ, cfg)
		for _, prop in ipairs(rule.propertydefinition) do
			local fld = p.rule.getPropertyField(rule, prop)
			local value = cfg[fld.name]
			if value ~= nil then

				if fld.kind == "path" then
					value = gmake2.path(cfg, value)
				elseif fld.kind == "list:path" then
					value = gmake2.path(cfg, value)
				end

				value = p.rule.expandString(rule, prop, value)
				if value ~= nil and #value > 0 then
					environ[prop.name] = p.esc(value)
				end
			end
		end
	end

	function cpp.addRuleFile(cfg, node)
		local rules = cfg.project._gmake.rules
		local fileext = cpp.determineFiletype(cfg, node)
		local rule = rules[fileext]
		if rule then

			local filecfg = fileconfig.getconfig(node, cfg)
			local environ = table.shallowcopy(filecfg.environ)

			if rule.propertydefinition then
				cpp.prepareEnvironment(rule, environ, cfg)
				cpp.prepareEnvironment(rule, environ, filecfg)
			end

			local shadowContext = p.context.extent(rule, environ)

			local buildoutputs  = shadowContext.buildoutputs
			local buildmessage  = shadowContext.buildmessage
			local buildcommands = shadowContext.buildcommands
			local buildinputs   = shadowContext.buildinputs

			buildoutputs = p.project.getrelative(cfg.project, buildoutputs)
			if buildoutputs and #buildoutputs > 0 then
				local file = {
					buildoutputs  = buildoutputs,
					source        = node.relpath,
					buildmessage  = buildmessage,
					buildcommands = buildcommands,
					buildinputs   = buildinputs
				}
				table.insert(cfg._gmake.fileRules, file)

				for _, output in ipairs(buildoutputs) do
					cpp.addGeneratedFile(cfg, node, output)
				end
			end
		end
	end

--
-- Write out the settings for a particular configuration.
--

	cpp.elements.configuration = function(cfg)
		return {
			cpp.tools,
			gmake2.target,
			gmake2.objdir,
			cpp.pch,
			cpp.defines,
			cpp.includes,
			cpp.forceInclude,
			cpp.cppFlags,
			cpp.cFlags,
			cpp.cxxFlags,
			cpp.resFlags,
			cpp.libs,
			cpp.ldDeps,
			cpp.ldFlags,
			cpp.linkCmd,
			cpp.bindirs,
			cpp.exepaths,
			gmake2.settings,
			gmake2.preBuildCmds,
			gmake2.preLinkCmds,
			gmake2.postBuildCmds,
		}
	end

	function cpp.outputConfigurationSection(prj)
		_p('# Configurations')
		_p('# #############################################')
		_p('')
		gmake2.outputSection(prj, cpp.elements.configuration)
	end

	function cpp.tools(cfg, toolset)
		local tool = toolset.gettoolname(cfg, "cc")
		if tool then
			_p('ifeq ($(origin CC), default)')
			_p('  CC = %s', tool)
			_p('endif' )
		end

		tool = toolset.gettoolname(cfg, "cxx")
		if tool then
			_p('ifeq ($(origin CXX), default)')
			_p('  CXX = %s', tool)
			_p('endif' )
		end

		tool = toolset.gettoolname(cfg, "ar")
		if tool then
			_p('ifeq ($(origin AR), default)')
			_p('  AR = %s', tool)
			_p('endif' )
		end

		tool = toolset.gettoolname(cfg, "rc")
		if tool then
			_p('RESCOMP = %s', tool)
		end
	end

	function cpp.pch(cfg, toolset)
		-- If there is no header, or if PCH has been disabled, I can early out
		if not cfg.pchheader or cfg.flags.NoPCH then
			return
		end

		-- Visual Studio requires the PCH header to be specified in the same way
		-- it appears in the #include statements used in the source code; the PCH
		-- source actual handles the compilation of the header. GCC compiles the
		-- header file directly, and needs the file's actual file system path in
		-- order to locate it.

		-- To maximize the compatibility between the two approaches, see if I can
		-- locate the specified PCH header on one of the include file search paths
		-- and, if so, adjust the path automatically so the user doesn't have
		-- add a conditional configuration to the project script.

		local pch = cfg.pchheader
		local found = false

		-- test locally in the project folder first (this is the most likely location)
		local testname = path.join(cfg.project.basedir, pch)
		if os.isfile(testname) then
			pch = project.getrelative(cfg.project, testname)
			found = true
		else
			-- else scan in all include dirs.
			for _, incdir in ipairs(cfg.includedirs) do
				testname = path.join(incdir, pch)
				if os.isfile(testname) then
					pch = project.getrelative(cfg.project, testname)
					found = true
					break
				end
			end
		end

		if not found then
			pch = project.getrelative(cfg.project, path.getabsolute(pch))
		end

		p.outln('PCH = ' .. pch)
		p.outln('PCH_PLACEHOLDER = $(OBJDIR)/$(notdir $(PCH))')
		p.outln('GCH = $(PCH_PLACEHOLDER).gch')
	end

	function cpp.defines(cfg, toolset)
		p.outln('DEFINES +=' .. gmake2.list(table.join(toolset.getdefines(cfg.defines, cfg), toolset.getundefines(cfg.undefines))))
	end

	function cpp.includes(cfg, toolset)
		local includes = toolset.getincludedirs(cfg, cfg.includedirs, cfg.sysincludedirs)
		p.outln('INCLUDES +=' .. gmake2.list(includes))
	end

	function cpp.forceInclude(cfg, toolset)
		local includes = toolset.getforceincludes(cfg)
		p.outln('FORCE_INCLUDE +=' .. gmake2.list(includes))
	end

	function cpp.cppFlags(cfg, toolset)
		local flags = gmake2.list(toolset.getcppflags(cfg))
		p.outln('ALL_CPPFLAGS += $(CPPFLAGS)' .. flags .. ' $(DEFINES) $(INCLUDES)')
	end

	function cpp.cFlags(cfg, toolset)
		local flags = gmake2.list(table.join(toolset.getcflags(cfg), cfg.buildoptions))
		p.outln('ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS)' .. flags)
	end

	function cpp.cxxFlags(cfg, toolset)
		local flags = gmake2.list(table.join(toolset.getcxxflags(cfg), cfg.buildoptions))
		p.outln('ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS)' .. flags)
	end

	function cpp.resFlags(cfg, toolset)
		local resflags = table.join(toolset.getdefines(cfg.resdefines), toolset.getincludedirs(cfg, cfg.resincludedirs), cfg.resoptions)
		p.outln('ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES)' .. gmake2.list(resflags))
	end

	function cpp.libs(cfg, toolset)
		local flags = toolset.getlinks(cfg)
		p.outln('LIBS +=' .. gmake2.list(flags, true))
	end

	function cpp.ldDeps(cfg, toolset)
		local deps = config.getlinks(cfg, "siblings", "fullpath")
		p.outln('LDDEPS +=' .. gmake2.list(p.esc(deps)))
	end

	function cpp.ldFlags(cfg, toolset)
		local flags = table.join(toolset.getLibraryDirectories(cfg), toolset.getrunpathdirs(cfg, cfg.runpathdirs), toolset.getldflags(cfg), cfg.linkoptions)
		p.outln('ALL_LDFLAGS += $(LDFLAGS)' .. gmake2.list(flags))
	end

	function cpp.linkCmd(cfg, toolset)
		if cfg.kind == p.STATICLIB then
			if cfg.architecture == p.UNIVERSAL then
				p.outln('LINKCMD = libtool -o "$@" $(OBJECTS)')
			else
				p.outln('LINKCMD = $(AR) -rcs "$@" $(OBJECTS)')
			end
		elseif cfg.kind == p.UTILITY then
			-- Empty LINKCMD for Utility (only custom build rules)
			p.outln('LINKCMD =')
		else
			-- this was $(TARGET) $(LDFLAGS) $(OBJECTS)
			--   but had trouble linking to certain static libs; $(OBJECTS) moved up
			-- $(LDFLAGS) moved to end (http://sourceforge.net/p/premake/patches/107/)
			-- $(LIBS) moved to end (http://sourceforge.net/p/premake/bugs/279/)

			local cc = iif(p.languages.isc(cfg.language), "CC", "CXX")
			p.outln('LINKCMD = $(' .. cc .. ') -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS)')
		end
	end

	function cpp.bindirs(cfg, toolset)
		local dirs = project.getrelative(cfg.project, cfg.bindirs)
		if #dirs > 0 then
			p.outln('EXECUTABLE_PATHS = "' .. table.concat(dirs, ":") .. '"')
		end
	end

	function cpp.exepaths(cfg, toolset)
		local dirs = project.getrelative(cfg.project, cfg.bindirs)
		if #dirs > 0 then
			p.outln('EXE_PATHS = export PATH=$(EXECUTABLE_PATHS):$$PATH;')
		end
	end

--
-- Write out the per file configurations.
--
	function cpp.outputPerFileConfigurationSection(prj)
		_p('# Per File Configurations')
		_p('# #############################################')
		_p('')
		for cfg in project.eachconfig(prj) do
			table.foreachi(prj._.files, function(node)
				local fcfg = fileconfig.getconfig(node, cfg)
				if fcfg then
					cpp.perFileFlags(cfg, fcfg)
				end
			end)
		end
		_p('')
	end

	function cpp.makeVarName(prj, value, saltValue)
		prj._gmake = prj._gmake or {}
		prj._gmake.varlist = prj._gmake.varlist or {}
		prj._gmake.varlistlength = prj._gmake.varlistlength or 0
		local cache = prj._gmake.varlist
		local length = prj._gmake.varlistlength

		local key = value .. saltValue

		if (cache[key] ~= nil) then
			return cache[key], false
		end

		local var = string.format("PERFILE_FLAGS_%d", length)
		cache[key] = var

		prj._gmake.varlistlength = length + 1

		return var, true
	end

	function cpp.perFileFlags(cfg, fcfg)
		local toolset = gmake2.getToolSet(cfg)

		local isCFile = path.iscfile(fcfg.name)

		local getflags = iif(isCFile, toolset.getcflags, toolset.getcxxflags)
		local value = gmake2.list(table.join(getflags(fcfg), fcfg.buildoptions))

		if fcfg.defines or fcfg.undefines then
			local defs = table.join(toolset.getdefines(fcfg.defines, cfg), toolset.getundefines(fcfg.undefines))
			if #defs > 0 then
				value = value .. gmake2.list(defs)
			end
		end

		if fcfg.includedirs or fcfg.sysincludedirs then
			local includes = toolset.getincludedirs(cfg, fcfg.includedirs, fcfg.sysincludedirs)
			if #includes > 0 then
				value = value ..  gmake2.list(includes)
			end
		end

		if #value > 0 then
			local newPerFileFlag = false
			fcfg.flagsVariable, newPerFileFlag = cpp.makeVarName(cfg.project, value, iif(isCFile, '_C', '_CPP'))
			if newPerFileFlag then
				if isCFile then
					_p('%s = $(ALL_CFLAGS)%s', fcfg.flagsVariable, value)
				else
					_p('%s = $(ALL_CXXFLAGS)%s', fcfg.flagsVariable, value)
				end
			end
		end
	end

	function cpp.fileFlags(cfg, file)
		local fcfg = fileconfig.getconfig(file, cfg)
		local flags = {}

		if cfg.pchheader and not cfg.flags.NoPCH and (not fcfg or not fcfg.flags.NoPCH) then
			table.insert(flags, "-include $(PCH_PLACEHOLDER)")
		end

		if fcfg and fcfg.flagsVariable then
			table.insert(flags, string.format("$(%s)", fcfg.flagsVariable))
		else
			local fileExt = cpp.determineFiletype(cfg, file)

			if path.iscfile(fileExt) then
				table.insert(flags, "$(ALL_CFLAGS)")
			elseif path.iscppfile(fileExt) then
				table.insert(flags, "$(ALL_CXXFLAGS)")
			end
		end

		return table.concat(flags, ' ')
	end

--
-- Write out the file sets.
--

	cpp.elements.filesets = function(cfg)
		local result = {}
		for _, kind in ipairs(cfg._gmake.kinds) do
			for _, f in ipairs(cfg._gmake.filesets[kind]) do
				table.insert(result, function(cfg, toolset)
					cpp.outputFileset(cfg, kind, f)
				end)
			end
		end
		return result
	end

	function cpp.outputFilesSection(prj)
		_p('# File sets')
		_p('# #############################################')
		_p('')

		for _, kind in ipairs(prj._gmake.kinds) do
			_x('%s :=', kind)
		end
		_x('')

		gmake2.outputSection(prj, cpp.elements.filesets)
	end

	function cpp.outputFileset(cfg, kind, file)
		_x('%s += %s', kind, file)
	end

--
-- Write out the targets.
--

	cpp.elements.rules = function(cfg)
		return {
			cpp.allRules,
			cpp.targetRules,
			gmake2.targetDirRules,
			gmake2.objDirRules,
			cpp.cleanRules,
			gmake2.preBuildRules,
			cpp.customDeps,
			cpp.pchRules,
		}
	end

	function cpp.outputRulesSection(prj)
		_p('# Rules')
		_p('# #############################################')
		_p('')
		gmake2.outputSection(prj, cpp.elements.rules)
	end

	function cpp.allRules(cfg, toolset)
		if cfg.system == p.MACOSX and cfg.kind == p.WINDOWEDAPP then
			_p('all: $(TARGET) $(dir $(TARGETDIR))PkgInfo $(dir $(TARGETDIR))Info.plist')
			_p('\t@:')
			_p('')
			_p('$(dir $(TARGETDIR))PkgInfo:')
			_p('$(dir $(TARGETDIR))Info.plist:')
		else
			_p('all: $(TARGET)')
			_p('\t@:')
		end
		_p('')
	end

	function cpp.targetRules(cfg, toolset)
		local targets = ''

		for _, kind in ipairs(cfg._gmake.kinds) do
			if kind ~= 'OBJECTS' and kind ~= 'RESOURCES' then
				targets = targets .. '$(' .. kind .. ') '
			end
		end

		targets = targets .. '$(OBJECTS) $(LDDEPS)'
		if cfg._gmake.filesets['RESOURCES'] then
			targets = targets .. ' $(RESOURCES)'
		end

		_p('$(TARGET): %s | $(TARGETDIR)', targets)
		_p('\t$(PRELINKCMDS)')
		_p('\t@echo Linking %s', cfg.project.name)
		_p('\t$(SILENT) $(LINKCMD)')
		_p('\t$(POSTBUILDCMDS)')
		_p('')
	end

	function cpp.customDeps(cfg, toolset)
		for _, kind in ipairs(cfg._gmake.kinds) do
			if kind == 'CUSTOM' or kind == 'SOURCES' then
				_p('$(%s): | prebuild', kind)
			end
		end
	end

	function cpp.cleanRules(cfg, toolset)
		_p('clean:')
		_p('\t@echo Cleaning %s', cfg.project.name)
		_p('ifeq (posix,$(SHELLTYPE))')
		_p('\t$(SILENT) rm -f  $(TARGET)')
		_p('\t$(SILENT) rm -rf $(OBJDIR)')
		_p('else')
		_p('\t$(SILENT) if exist $(subst /,\\\\,$(TARGET)) del $(subst /,\\\\,$(TARGET))')
		_p('\t$(SILENT) if exist $(subst /,\\\\,$(OBJDIR)) rmdir /s /q $(subst /,\\\\,$(OBJDIR))')
		_p('endif')
		_p('')
	end

	function cpp.pchRules(cfg, toolset)
		_p('ifneq (,$(PCH))')
		_p('$(OBJECTS): $(GCH) | $(PCH_PLACEHOLDER)')
		_p('$(GCH): $(PCH) | prebuild')
		_p('\t@echo $(notdir $<)')
		local cmd = iif(p.languages.isc(cfg.language), "$(CC) -x c-header $(ALL_CFLAGS)", "$(CXX) -x c++-header $(ALL_CXXFLAGS)")
		_p('\t$(SILENT) %s -o "$@" -MF "$(@:%%.gch=%%.d)" -c "$<"', cmd)
		_p('$(PCH_PLACEHOLDER): $(GCH) | $(OBJDIR)')
		_p('ifeq (posix,$(SHELLTYPE))')
		_p('\t$(SILENT) touch "$@"')
		_p('else')
		_p('\t$(SILENT) echo $null >> "$@"')
		_p('endif')
		_p('else')
		_p('$(OBJECTS): | prebuild')
		_p('endif')
		_p('')
	end

--
-- Output the file compile targets.
--

	function cpp.makeUnique(cfg, f)
		local cache = cfg._gmake.bases
		local seq = cache[f]
		if seq == nil then
			cache[f] = 1
			return f
		else
			cache[f] = seq + 1
			return f .. tostring(seq)
		end
	end

	cpp.elements.fileRules = function(cfg)
		local funcs = {}
		for _, fileRule in ipairs(cfg._gmake.fileRules) do
			table.insert(funcs, function(cfg, toolset)
				cpp.outputFileRules(cfg, fileRule)
			end)
		end
		return funcs
	end

	function cpp.outputFileRuleSection(prj)
		_p('# File Rules')
		_p('# #############################################')
		_p('')
		gmake2.outputSection(prj, cpp.elements.fileRules)
	end

	function cpp.outputFileRules(cfg, file)
		local outputs = table.concat(file.buildoutputs, ' ')

		local dependencies = p.esc(file.source)
		if file.buildinputs and #file.buildinputs > 0 then
			dependencies = dependencies .. " " .. table.concat(p.esc(file.buildinputs), " ")
		end

		_p('%s: %s', outputs, dependencies)

		if file.buildmessage then
			_p('\t@echo %s', file.buildmessage)
		end

		if file.buildcommands then
			local cmds = os.translateCommandsAndPaths(file.buildcommands, cfg.project.basedir, cfg.project.location)
			for _, cmd in ipairs(cmds) do
				if cfg.bindirs and #cfg.bindirs > 0 then
					_p('\t$(SILENT) $(EXE_PATHS) %s', cmd)
				else
					_p('\t$(SILENT) %s', cmd)
				end
			end
		end
	end

---------------------------------------------------------------------------
--
-- Handlers for individual makefile elements
--
---------------------------------------------------------------------------

	function cpp.dependencies(prj)
		-- include the dependencies, built by GCC (with the -MMD flag)
		_p('-include $(OBJECTS:%%.o=%%.d)')
		_p('ifneq (,$(PCH))')
			_p('  -include $(PCH_PLACEHOLDER).d')
		_p('endif')
	end


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IQueueNameConvention.cs" company="Epworth Consulting Ltd.">
//   © Epworth Consulting Ltd.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Atlas.ServiceBus.RabbitMQ
{
   using System;

   public interface IQueueNameConvention
   {
      string GetQueueName(Type messageType);

      Type GetMessageType(string queueName);
   }
}

redpajama_set_name: RedPajamaGithub


text:
package network;

import java.io.File;

import savefile.SaveUtils;
import world.ActorState;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;

import world.Activatable;
import world.Actor;
import world.Container;
import world.Entity;
import world.Player;
import world.World;
import world.effects.Effect;
import world.entity.item.Item;
import world.entity.item.RightClickable;
import world.entity.mob.Mob;

import com.jme3.math.Vector3f;
import com.jme3.network.ConnectionListener;
import com.jme3.network.Filters;
import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import com.jme3.network.Server;

import network.interfaces.PacketHandler;
import network.interfaces.WorldObserver;
import network.packets.*;

/**
 * The game server is responsible for handling packets on the server side.
 * Implements the visitor pattern to discern packets. Follows a general
 * publish/subscribe pattern for networking. Server information mostly overrides
 * client data and essentially all the damage and AI movements are handled on
 * the server.
 *
 * Server implements a world observer and notifies the clients of game updates.
 * In order to deal with multiple threads, an app queue is used.
 *
 * @author Garming Sam 300198721
 *
 */
public class GameServer extends WorldObserver implements MessageListener<HostedConnection>, ConnectionListener, PacketHandler{
	private World world;
	private Map<Integer, HostedConnection> connections = new ConcurrentHashMap<Integer, HostedConnection>();
	private Map<Integer, Integer> conIDToPlayerID = new ConcurrentHashMap<Integer, Integer>();
	private Map<Integer, Integer> playerIDtoConID = new ConcurrentHashMap<Integer, Integer>();
	private PlayerData playerData;
	private ServerMain app;
	private Server server;

	/**
	 * Create a game server.
	 *
	 * @param server
	 *            server
	 * @param w
	 *            world
	 * @param app
	 *            server main
	 * @param data
	 *            data storage for players
	 */
	public GameServer(Server server, World w, ServerMain app, PlayerData data){
		this.playerData = data;
		this.server = server;
		this.world = w;
		this.app = app;

		world.addObserver(this);
	}

	// JME message listener
	@Override
	public void messageReceived(HostedConnection conn, Message msg) {
		((GameUpdateMessage)msg).accept(this);
	}

	@Override
	public void connectionAdded(Server server, final HostedConnection conn) {
		System.out.println("New connection from " + conn.getAddress());
		app.enqueue(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				connections.put(conn.getId(), conn);
				conn.send(new PlayerSpeedMessage(world.getPlayerSpeed(), world.getSpawnPoint()));
				for(Entity o : world.getEntitiesOfClass(Entity.class))
					conn.send(new AddEntityMessage(o.getEntityID(), o, o.getLocation()));
				conn.send(new AddEntityFinishMessage());

				return null;
			}
		});
	}

	@Override
	public void onAddEntity(World w, Entity e) {
		// send both add entity and finish add entity messages to ensure order
		for(HostedConnection conn : connections.values()) {
			conn.send(new AddEntityMessage(e));
			conn.send(new AddEntityFinishMessage());
		}
	}

	@Override
	public void onRemoveEntity(World w, final Entity e) {
		app.enqueue(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				server.broadcast(new RemoveEntityMessage(e.getEntityID()));
				return null;
			}
		});
	}

	@Override
	public void connectionRemoved(Server arg0, HostedConnection arg1) {
		connections.remove(arg1.getId());
		Integer i = conIDToPlayerID.remove(arg1.getId());
		if(i != null) playerIDtoConID.remove(i);
	}

	/**
	 * Broadcast all the connected player positions.
	 */
	public void broadcastPlayerPosition() {
		for (int i : conIDToPlayerID.keySet()) {
			Actor p = (Actor)world.getEntityByID(conIDToPlayerID.get(i));
			if(p == null) continue; // player likely died
			Vector3f pos = p.getLocation();
			MoveMessage m = new MoveMessage(conIDToPlayerID.get(i),pos, p.getState().ordinal(), p.getDirection().negate());
			server.broadcast(m);
		}

	}

	/**
	 * Call a save on the world and save the player data at this current point
	 * in time as well.
	 */
	public void save() {
		app.enqueue(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				SaveUtils.save(world, new File("server.sav"));
				SaveUtils.save(playerData, new File("player-data.sav"));
				return null;
			}
		});
	}

	@Override
	public void handleMessage(final MoveMessage m) {
		app.enqueue(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				Entity p = world.getEntityByID(m.eid);
				if (p == null)
					return null;
				p.changeLocation(m.x - p.getLocation().x, m.y
						- p.getLocation().y, m.z - p.getLocation().z);
				((Actor) p).setState(ActorState.values()[m.state]);
				((Actor) p).setDirection(new Vector3f(m.dirA, m.dirB, m.dirC));
				return null;
			}
		});

	}

	@Override
	public void handleMessage(final AttackMessage m) {
		app.enqueue(new Callable<Void>(){
			@Override
			public Void call() throws Exception {
				Player p = (Player)world.getEntityByID(m.eid);
				if(p == null) return null;
				p.setLocation(m.x, m.y, m.z);
				p.setDirection(new Vector3f(m.dirX, m.dirY, m.dirZ)); // note: directions are inverted
				p.primaryAction();
				server.broadcast(Filters.notEqualTo(connections.get(playerIDtoConID.get(m.eid))), m);
				return null;
			}
		});

	}

	/**
	 * Chat system commands: /name - set name, /hit-count - counts hits, /mobs -
	 * disable mob AI, /msg [player] - private message note: only works with
	 * players who register their names
	 *
	 * Any other messages are public.
	 */
	@Override
	public void handleMessage(ChatMessage m) {
		if (m.text.startsWith("/name ")) {
			m.text = m.text.replace("/name ", "");
			if (!playerData.containsName(m.text)) {
				playerData.addData(m.text, m.id);
				//connections.get(playerIDtoConID.get(m.id)).send(
				//		new ChatMessage("Name", m.text, 0));
				connections.get(playerIDtoConID.get(m.id)).send(new PlayerSetupMessage(-1,m.text));
			}
			return;
		} else if(m.text.startsWith("/msg ")){
			Scanner s = new Scanner(m.text);
			s.next();
			if(!s.hasNext()) {
				s.close();
				return;
			}
			String target = s.next();
			if(playerData.containsName(target)){
				int id = playerData.getID(target);
				Integer con = playerIDtoConID.get(id);
				if(con != null && s.hasNext()) {
					s.useDelimiter("\\Z");
					String f = s.next().trim();
					ChatMessage c = new ChatMessage(m.source, f, -1);
					connections.get(con).send(c);
					connections.get(playerIDtoConID.get(m.id)).send(c);
				}
			}
			s.close();
		} else if(m.text.startsWith("/hit-count")){
			List<Player> players = new ArrayList<Player>(world.getPlayers());
			// sort the players in descending order
			Collections.sort(players, new Comparator<Player>(){
				@Override
				public int compare(Player p1, Player p2) {
					return p2.hitCount() - p1.hitCount();
				}
			});
			server.broadcast(new ChatMessage("", "HIT COUNT", -1));
			for(Player p : players){
				int id = p.getEntityID();
				String name = playerData.getName(id);
				server.broadcast(new ChatMessage("",p.hitCount() + " - " + ((name != null) ? name : ("Guest " + id)), -1));
			}
		} else if(m.text.startsWith("/mobs")){
			app.toggleSpawn();
		} else {
			server.broadcast(m);
		}
	}

	@Override
	public void handleMessage(final EffectMessage m) {
		// Not sure if this is ever called.
		app.enqueue(new Callable<Void>(){
			@Override
			public Void call() throws Exception {
				world.makeEffect(m.getEffect(world));
				server.broadcast(m);
				return null;
			}
		});
	}

	@Override
	public void handleMessage(PlayerJoinedMessage m) {
		// Player has their player set, send them some ping messages and
		// day/night. Store their connection.
		conIDToPlayerID.put(m.connection, m.eid);
		playerIDtoConID.put(m.eid, m.connection);
		HostedConnection c = connections.get(m.connection);

		c.send(new DayNightMessage(world.getTime()));
		c.send(new PingMessage(m.eid));
	}

	@Override
	public void handleMessage(PingMessage pingPacket) {
		// Calculate difference between server and client. Ideally this should
		// be stored somewhere to offset lag.
		long diff = System.currentTimeMillis() - pingPacket.timestamp;
		pingPacket.sentTime = diff;
		if (--pingPacket.count > 0) {
			pingPacket.timestamp = System.currentTimeMillis();
			server.broadcast(Filters.equalTo(connections.get(playerIDtoConID.get(pingPacket.id))), pingPacket);
		}
	}

	/**
	 * Broadcast all mob updates.
	 */
	public void updateMobs() {
		for(Mob m : world.getEntitiesOfClass(Mob.class))
			server.broadcast(new MoveMessage(m.getEntityID(), m.getLocation(), ((Actor)m).getState().ordinal(), m.getDirection()));
	}

	@Override
	public void handleMessage(final ItemTransferMessage itemTransfer) {
		app.enqueue(new Callable<Void>(){
			@Override
			public Void call() throws Exception {
				Player p = ((Player)world.getEntityByID(itemTransfer.eid));
				if(p == null) return null;
				Item i = (Item)world.getEntityByID(itemTransfer.itemID);
				if(!itemTransfer.drop){
					p.getContainerInventory().add(i);
					i.onPick(); // item was picked
				} else {
					p.getContainerInventory().dropItem(i);
				}
				server.broadcast(itemTransfer); // resend the message for the client
				return null;
			}
		});
	}

	@Override
	public void handleMessage(AddEntityMessage addEntityMessage) {
		// shouldn't do anything

	}

	@Override
	public void handleMessage(DayNightMessage dayNightMessage) {
		// shouldn't do anything

	}

	@Override
	public void handleMessage(RemoveEntityMessage removeEntityMessage) {
		// shouldn't do anything

	}

	public boolean hasConnectedPlayers(){
		return !conIDToPlayerID.isEmpty();
	}

	@Override
	public void handleMessage(final ChestAccessMessage m) {
		app.enqueue(new Callable<Void>(){
			@Override
			public Void call() throws Exception {
				Container c = (Container)world.getEntityByID(m.chestID);
				// if opening
				if(m.open){
					if(c.canAccess()){
						c.setCanAccess(false);
					} else {
						m.open = false;
					}
					//send the player the chest access message again
					connections.get(playerIDtoConID.get(m.eid)).send(m);
				} else {
					// if closing
					c.setCanAccess(true);
					//connections.get(playerIDtoConID.get(m.eid)).send(m);
				}
				return null;
			}
		});

	}

	@Override
	public void handleMessage(final InventoryTransferMessage m) {
		app.enqueue(new Callable<Void>(){
			@Override
			public Void call() throws Exception {
				Container c = (Container)world.getEntityByID(m.idTo);
				Item i = (Item)world.getEntityByID(m.itemID);
				Container c2 = (Container)world.getEntityByID(m.idFrom);
				c2.getContainerInventory().removeItem(i);
				c.getContainerInventory().add(i);
				server.broadcast(m); // ensure that the item transfer is told across the clients
				return null;
			}
		});
	}

	@Override
	public void handleMessage(final EquipItemMessage m) {
		app.enqueue(new Callable<Void>(){
			@Override
			public Void call() throws Exception {
				Entity e = world.getEntityByID(m.eid);
				Entity i = world.getEntityByID(m.itemID);
				if(!(e instanceof Player) || !(i instanceof Item)){
					throw new IllegalArgumentException("Non-players cannot equip and you can only equip items.");
				}

				Player p = (Player)e;

				if(m.equip){
					p.equip((Item)i);
				} else {
					p.unequip((Item)i);
				}

				server.broadcast(Filters.notEqualTo(connections
						.get(playerIDtoConID.get(m.eid))), m);

				return null;
			}

		});

	}

	@Override
	public void handleMessage(ServerSaveMessage m) {
		save();
		System.out.println("Server world saved.");

	}

	@Override
	public void handleMessage(AddEntityFinishMessage m) {
		// shouldn't happen on server
	}

	@Override
	public void handleMessage(final RightClickMessage m) {
		app.enqueue(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				RightClickable r = (RightClickable) world
						.getEntityByID(m.itemID);
				r.rightClick();
				server.broadcast(Filters.notEqualTo(connections
						.get(playerIDtoConID.get(m.player))), m);
				// broadcast the right click to everyone else
				return null;
			}
		});
	}

	@Override
	public void handleMessage(final OnActivateMessage m) {
		app.enqueue(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				Activatable a = (Activatable) world.getEntityByID(m.eid);
				a.activate((Player) world.getEntityByID(m.playerID));
				server.broadcast(Filters.notEqualTo(connections
						.get(playerIDtoConID.get(m.playerID))), m);
				// broadcast the activate
				return null;
			}
		});

	}

	@Override
	public void handleMessage(final PlayerSetupMessage m) {
		// if an improper name is given, just add them and not their name.
		app.enqueue(new Callable<Void>(){
			@Override
			public Void call() throws Exception {
				if(m.name == null || m.name.equals("")){
					Entity e = world.addOtherPlayer();
					e.changeLocation(new Vector3f(0, 200, 0));
					connections.get(m.conID).send(new PlayerJoinedMessage(e.getEntityID(), m.conID));
					connections.get(m.conID).send(new PlayerSetupMessage());
					return null;
				}
				if(playerData.containsName(m.name)){
					Entity e = world.getEntityByID(playerData.getID(m.name));
					if(e == null || playerIDtoConID.get(e.getEntityID()) != null){
						// if there is already a player connected using this name or the entity is missing
						// add the player but don't record a name
						e = world.addOtherPlayer();
						e.changeLocation(new Vector3f(0, 200, 0));
						connections.get(m.conID).send(new PlayerJoinedMessage(e.getEntityID(), m.conID));
						connections.get(m.conID).send(new PlayerSetupMessage());
					} else {
						// name is correct
						connections.get(m.conID).send(new PlayerJoinedMessage(e.getEntityID(), m.conID));
						connections.get(m.conID).send(m);
					}
				} else {
					Entity e = world.addOtherPlayer();
					e.changeLocation(new Vector3f(0, 200, 0));
					connections.get(m.conID).send(new AddEntityFinishMessage());
					connections.get(m.conID).send(new PlayerJoinedMessage(e.getEntityID(), m.conID));
					playerData.addData(m.name, e.getEntityID());
					//names.put(e.getEntityID(), m.name);
					//nameToID.put(m.name, e.getEntityID());
					// name is correct
					connections.get(m.conID).send(m);
				}
				return null;
			}
		});

	}

	@Override
	public void handleMessage(GameWonMessage m) {
		// doesn't do anything

	}

	/// observer methods

	@Override
	public void onPickItem(World w, Item i) {
		// picking happens on the clients
	}

	@Override
	public void addEffect(World w, Effect e) {
		server.broadcast(new EffectMessage(e));
	}

	@Override
	public void onDayNightChange(World w, float time) {
		server.broadcast(new DayNightMessage(time));
	}

	@Override
	public void onGameWon(World w) {
		server.broadcast(new GameWonMessage());
	}

	@Override
	public void handleMessage(PlayerSpeedMessage m) {
		// do nothing

	}

}


text:
import { IsEmail, IsString, Length } from 'class-validator';

export class CreateAuthorDto {
  @IsString() @Length(3, 64) readonly display_name: string;
  @IsEmail() readonly email: string;
}


text:
* [Current documentation](//aprilbrother.github.io/aprilbeacon-ios-sdk/Documents/index.html)
* [Community for AprilBeacon](http://bbs.aprbrother.com)

## How to install

### From CocoaPods

Add the following line to your Podfile:

	pod 'AprilSDK'

Then run the following command in the same directory as your Podfile:

	pod update

### Normal way

1. Copy the folder 'AprilSDK' to your project directory.
2. Add libAprilBeaconSDK.a to your Framework.
3. Add 'AprilSDK/Headers' (relative path to your project) to Header Search Paths in Build Settings of your target.

### iOS 8

If your app supports iOS 8, you should add NSLocationAlwaysUsageDescription key with message to be displayed in the prompt to Info.plist.

### Project Setting

Change the value of Build Active Architecture Only to "NO" of your project in Building Settings.

## Changelog

To see what has changed in recent versions of April SDK, see the [CHANGELOG](https://github.com/AprilBrother/AprilBeacon-iOS-SDK/blob/master/CHANGELOG.md).


text:
from __future__ import unicode_literals, division, absolute_import

from flexget import options
from flexget.event import event
from flexget.logger import console
from flexget.plugins.filter import seen
from flexget.utils.database import with_session
from flexget.utils.imdb import is_imdb_url, extract_id

def do_cli(manager, options):
    if options.seen_action == 'forget':
        seen_forget(manager, options)
    elif options.seen_action == 'add':
        seen_add(options)
    elif options.seen_action == 'search':
        seen_search(options)

def seen_forget(manager, options):
    forget_name = options.forget_value
    if is_imdb_url(forget_name):
        imdb_id = extract_id(forget_name)
        if imdb_id:
            forget_name = imdb_id

    count, fcount = seen.forget(forget_name)
    console('Removed %s titles (%s fields)' % (count, fcount))
    manager.config_changed()

def seen_add(options):
    seen_name = options.add_value
    if is_imdb_url(seen_name):
        imdb_id = extract_id(seen_name)
        if imdb_id:
            seen_name = imdb_id
    seen.add(seen_name, 'cli_add', {'cli_add': seen_name})
    console('Added %s as seen. This will affect all tasks.' % seen_name)

@with_session
def seen_search(options, session=None):
    search_term = '%' + options.search_term + '%'
    seen_entries = seen.search(value=search_term, status=None, session=session)
    for se in seen_entries.all():
        console('ID: %s Name: %s Task: %s Added: %s' % (se.id, se.title, se.task, se.added.strftime('%c')))
        for sf in se.fields:
            console(' %s: %s' % (sf.field, sf.value))
        console('')
    if not seen_entries:
        console('No results')

@event('options.register')
def register_parser_arguments():
    parser = options.register_command('seen', do_cli, help='view or forget entries remembered by the seen plugin')
    subparsers = parser.add_subparsers(dest='seen_action', metavar='<action>')
    forget_parser = subparsers.add_parser('forget', help='forget entry or entire task from seen plugin database')
    forget_parser.add_argument('forget_value', metavar='<value>',
                               help='title or url of entry to forget, or name of task to forget')
    add_parser = subparsers.add_parser('add', help='add a title or url to the seen database')
    add_parser.add_argument('add_value', metavar='<value>', help='the title or url to add')
    search_parser = subparsers.add_parser('search', help='search text from the seen database')
    search_parser.add_argument('search_term', metavar='<search term>')


text:
package io.quarkus;

/**
 * Exists only to suppress empty jar warning during build
 */
public class Dummy {
}


text:
<?php

echo $org_code;

error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
require('../configuration.php');

class CustomUploadHandler extends UploadHandler
{
protected function trim_file_name($name, $type) {
$name = parent::trim_file_name($name, $type);
// Your file name changes: $name = 'something';

$Ext = strrchr($name,".");

$Ext =strtolower($Ext);

$name = $_SESSION['username'];
$uploaded_by = $_SESSION['username'];
$upload_datetime=date('Y-m-d h:i:s');
$org_code = $_SESSION['org_code'];

$oldName=$name."$Ext";

$exists = file_exists($oldName);
if(!$exists) {
// do your processing
$name = $name."$Ext";
$sql="UPDATE organization
SET org_photo='$name',uploaded_by='$uploaded_by',upload_datetime='$upload_datetime'
where org_code='$org_code'";
$result = mysql_query($sql);
}
else
{
unlink("$oldName");
$name = $name."$Ext";
$sql="UPDATE organization
SET org_photo='$name',uploaded_by='$uploaded_by',upload_datetime='$upload_datetime'
where org_code='$org_code'";
$result = mysql_query($sql);
}

//$name = $name."$Ext";
return $name;
}
}

$upload_handler = new CustomUploadHandler();


text:
package org.bouncycastle.tsp.ers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.bouncycastle.operator.DigestCalculator;

/**
 * Representation of data groups with more than 1 members according to the description provided in RFC4998.
 * <p>
 * Such data groups represent a set of one or more data objects (e.g. electronic documents) for
 * which an Evidence Record should be generated. Data groups will be encapsulated in a single
 * PartialHashtree so that the presence of the group can be checked for, as well as the
 * individual items that make it up.
 */
public class ERSDataGroup
    extends ERSCachingData
{
    protected List<ERSData> dataObjects;

    /**
     * Base constructor for an "array" of data objects.
     *
     * @param dataObjects an array of data objects.
     */
    public ERSDataGroup(ERSData... dataObjects)
    {
        this.dataObjects = new ArrayList<ERSData>(dataObjects.length);
        this.dataObjects.addAll(Arrays.asList(dataObjects));
    }

    /**
     * Base constructor using a list of data objects.
     *
     * @param dataObjects a list of data objects.
     */
    public ERSDataGroup(List<ERSData> dataObjects)
    {
        this.dataObjects = new ArrayList<ERSData>(dataObjects.size());
        this.dataObjects.addAll(dataObjects);
    }

    /**
     * Constructor for a group with a single object.
     *
     * @param dataObject the data object to go in the group.
     */
    public ERSDataGroup(ERSData dataObject)
    {
        this.dataObjects = Collections.singletonList(dataObject);
    }

    /**
     * Generates hashes for all the data objects included in the data group with a previous chain hash.
     *
     * @param digestCalculator the {@link DigestCalculator} to use for computing the hashes
     * @return the set of hashes, in ascending order
     */
    public List<byte[]> getHashes(
        final DigestCalculator digestCalculator,
        final byte[] previousChainHash)
    {
        return ERSUtil.buildHashList(digestCalculator, dataObjects, previousChainHash);
    }

    /**
     * Return the calculated hash for the Data
     *
     * @param digestCalculator  digest calculator to use.
     * @param previousChainHash hash from an earlier chain if it needs to be included.
     * @return calculated hash.
     */
    public byte[] getHash(DigestCalculator digestCalculator, byte[] previousChainHash)
    {
        List<byte[]> hashes = getHashes(digestCalculator, previousChainHash);
        if (hashes.size() > 1)
        {
            return ERSUtil.calculateDigest(digestCalculator, hashes.iterator());
        }
        else
        {
            return (byte[])hashes.get(0);
        }
    }

    /**
     * Generates a hash for the whole DataGroup.
     *
     * @param digestCalculator the {@link DigestCalculator} to use for computing the hash
     * @return a hash that is representative of the whole DataGroup
     */
    protected byte[] calculateHash(DigestCalculator digestCalculator, byte[] previousChainHash)
    {
        List<byte[]> hashes = getHashes(digestCalculator, previousChainHash);

        if (hashes.size() > 1)
        {
            List<byte[]> dHashes = new ArrayList<byte[]>(hashes.size());
            for (int i = 0; i != dHashes.size(); i++)
            {
                dHashes.add(hashes.get(i));
            }
            return ERSUtil.calculateDigest(digestCalculator, dHashes.iterator());
        }
        else
        {
            return (byte[])hashes.get(0);
        }
    }

    /**
     * Return the number of data objects present in the group.
     *
     * @return membership count of the group.
     */
    public int size()
    {
        return dataObjects.size();
    }
}


text:
package io.argos.agent.sentinels

import akka.actor.ActorRef
import io.argos.agent.{Messages, SentinelConfiguration}
import io.argos.agent.bean.{MetricsRequest, MetricsResponse, _}
import io.argos.agent.util.HostnameProvider

class ConnectionTimeoutSentinel(val metricsProvider: ActorRef, val conf: SentinelConfiguration) extends Sentinel {

  private var previousValue = -1L

  override def processProtocolElement: Receive = {

    case CheckMetrics() => if (System.currentTimeMillis >= nextReact) metricsProvider ! MetricsRequest(ActorProtocol.ACTION_CHECK_CNX_TIMEOUT, Messages.CNX_TIMEOUT)

    case metrics: MetricsResponse[ConnectionTimeoutStats] if metrics.value.isDefined => {

      val timeoutMsg = metrics.value.get

      if (log.isDebugEnabled) {
        log.debug("ConnectionTimeoutSentinel : Timeout, onMinRate=<{}>, total=<{}>", timeoutMsg.oneMinRate.toString, timeoutMsg.count.toString)
      }

      if (timeoutMsg.oneMinRate > 0.0 && previousValue < timeoutMsg.count) {
        react(timeoutMsg)
        previousValue = timeoutMsg.count
      } else if (previousValue == -1) {
        previousValue = timeoutMsg.count
      }
    }
  }

  def react(info: ConnectionTimeoutStats): Unit = {

    val message =
      s"""Cassandra Node ${HostnameProvider.hostname} may be inconsistent.
        |
        |There are some connection timeouts.
        |
        |Last Minute rate : ${info.oneMinRate}
        |Last Five minutes rate : ${info.fiveMinRate}
        |Last Fifteen minutes rate : ${info.fifteenMinRate}
        |
        |Total since startup : ${info.count}
        |
        |According to the frequency of this notification, a repair may be useful...
      """.stripMargin

    context.system.eventStream.publish(buildNotification(conf.messageHeader.map(h => h + " \n\n--####--\n\n" + message).getOrElse(message)))

    updateNextReact()

    { }
  }
}


text:
/* You can add global styles to this file, and also import other style files */
.clickable {
  cursor: pointer;
}

body {
  color:#444444;
}


text:
/* global describe, it, expect, beforeEach, integration */
/* eslint camelcase: 0, no-invalid-this: 0 */

describe('The Annals of Castle Black', function() {
    integration(function() {
        beforeEach(function() {
            const deck = this.buildDeck('greyjoy', [
                'The Annals of Castle Black', 'A Noble Cause',
                'Wildling Horde', 'Lannisport Merchant', 'Hear Me Roar!'
            ]);

            this.player1.selectDeck(deck);
            this.player2.selectDeck(deck);
            this.startGame();
            this.keepStartingHands();

            this.player1.clickCard('Wildling Horde', 'hand');

            this.completeSetup();

            this.eventCard = this.player1.findCardByName('Hear Me Roar!', 'hand');
            this.character = this.player1.findCardByName('Lannisport Merchant', 'hand');
            this.opponentEventCard = this.player2.findCardByName('Hear Me Roar!', 'hand');
        });

        describe('when playing an event from hand', function() {
            beforeEach(function() {
                this.player1.selectPlot('The Annals of Castle Black');
                this.player2.selectPlot('A Noble Cause');
                this.selectFirstPlayer(this.player1);

                this.player1.clickCard(this.eventCard);
                this.player1.clickCard(this.character);
            });

            it('should allow the event to trigger', function() {
                expect(this.character.location).toBe('play area');
            });

            it('should remove the event from the game', function() {
                expect(this.eventCard.location).toBe('out of game');
            });
        });

        describe('when playing an event from discard pile', function() {
            beforeEach(function() {
                this.player1Object.moveCard(this.eventCard, 'discard pile');

                this.player1.selectPlot('The Annals of Castle Black');
                this.player2.selectPlot('A Noble Cause');
                this.selectFirstPlayer(this.player1);

                this.player1.clickCard(this.eventCard);
                expect(this.player1).toHavePrompt('Select character');
                this.player1.clickCard(this.character);
            });

            it('should allow the event to trigger', function() {
                expect(this.character.location).toBe('play area');
            });

            it('should remove the event from the game', function() {
                expect(this.eventCard.location).toBe('out of game');
            });
        });

        describe('when an event is discarded', function() {
            beforeEach(function() {
                this.player1.selectPlot('The Annals of Castle Black');
                this.player2.selectPlot('A Noble Cause');
                this.selectFirstPlayer(this.player1);

                this.player1.dragCard(this.eventCard, 'discard pile');
            });

            it('should remove the event from the game', function() {
                expect(this.eventCard.location).toBe('out of game');
            });
        });

        describe('when an event is discarded through pillage', function() {
            beforeEach(function() {
                this.player1.selectPlot('The Annals of Castle Black');
                this.player2.selectPlot('A Noble Cause');
                this.selectFirstPlayer(this.player1);

                this.player2Object.moveCard(this.opponentEventCard, 'draw deck');

                this.completeMarshalPhase();

                this.player1.clickPrompt('Power');
                this.player1.clickCard('Wildling Horde', 'play area');
                this.player1.clickPrompt('Done');

                this.skipActionWindow();

                this.player2.clickPrompt('Done');

                this.skipActionWindow();

                this.skipActionWindow();

                this.player1.clickPrompt('Apply Claim');
            });

            it('should remove the event from the game', function() {
                expect(this.opponentEventCard.location).toBe('out of game');
            });
        });
    });
});


text:
require 'test/unit'
require 'mutex_m'

class TestMutexM < Test::Unit::TestCase
  def test_cv_wait
    o = Object.new
    o.instance_variable_set(:@foo, nil)
    o.extend(Mutex_m)
    c = Thread::ConditionVariable.new
    t = Thread.start {
      o.synchronize do
        until foo = o.instance_variable_get(:@foo)
          c.wait(o)
        end
        foo
      end
    }
    sleep(0.0001)
    o.synchronize do
      o.instance_variable_set(:@foo, "abc")
    end
    c.signal
    assert_equal "abc", t.value
  end
end


text:
#include <vm/vm_as.h>
#include <vm/vm_seg.h>
#include <vm/vm_mem.h>
#include <vm/vm_errcode.h>
#include <sysarch/pages.h>
#include <xcpu/vm.h>

#ifdef SYSARCH_PAGESIZE_SHIFT
#define ROUND_DOWN(x) x &= ~((1<<SYSARCH_PAGESIZE_SHIFT)-1)
#else
#define ROUND_DOWN(x) x -= (x%SYSARCH_PAGESIZE)
#endif

#define NOT(x) (!(x))

#define GIVE_UP do{\
		kernlock_unlock(&(as->as_lock)); \
		return VM_FAILURE; \
	} while(0)

#define DO_SEGFAULT do{\
		kernlock_unlock(&(as->as_lock)); \
		return VM_SEGFAULT; \
	} while(0)

static int vm_seg_pagefault(vm_as_t as, vm_seg_t seg, vaddr_t va, vm_prot_t fault_type);

int vm_as_pagefault(vm_as_t as,vaddr_t va, vm_prot_t fault_type) {
	ROUND_DOWN(va);
	vm_bintree_t * __restrict__ bt;
	int ret;
	kernlock_lock(&(as->as_lock));

	kernlock_lock(&(as->as_lock_segs));
	bt = bt_floor(&(as->as_segs),va);
	kernlock_unlock(&(as->as_lock_segs));

	/*
	 * If no entry has been found, The pointer is not in an valid (mapped) address range.
	 */
	if(!bt) DO_SEGFAULT;
	if(!*bt) DO_SEGFAULT;

	ret = vm_seg_pagefault(as,((vm_seg_t)((*bt)->V)),va,fault_type);

	kernlock_unlock(&(as->as_lock));
	return ret;
}

#undef GIVE_UP
#undef DO_SEGFAULT

#define GIVE_UP do{\
		kernlock_unlock(&(seg->seg_lock)); \
		return VM_FAILURE; \
	} while(0)

#define DO_SEGFAULT do{\
		kernlock_unlock(&(seg->seg_lock)); \
		return VM_SEGFAULT; \
	} while(0)

static int vm_seg_pagefault(vm_as_t as,vm_seg_t seg, vaddr_t va, vm_prot_t fault_type) {
	paddr_t pa;
	vaddr_t rva;
	vm_prot_t iprod;
	struct vm_mem * mem;

	kernlock_lock(&(seg->seg_lock));

	/*
	 * If the address is outside the Segment, this is a segmentation fault.
	 */
	if(va > seg->seg_end) DO_SEGFAULT;

	rva = va - seg->seg_begin;

	/*
	 * Obtain the segment's memory protection.
	 */
	iprod = seg->seg_prot;

	/*
	 * Check, if the access type violates the protection.
	 */
	if(fault_type & ~(iprod)) DO_SEGFAULT;

	mem = seg->seg_mem;

	/* TODO: Pagein. */
	if(!mem) GIVE_UP;

	/*
	 * If Read-Only by Default is set on this segment, and no write access
	 * is being performed, then remove write from the privileges.
	 */
	if(mem->mem_default_ro && NOT(mem->mem_dirty   ) && NOT(fault_type & VM_PROT_WRITE  ))
		iprod &= ~VM_PROT_WRITE  ;

	/*
	 * If No-Execute by Default is set on this segment, and no execute access
	 * is being performed, then remove execute from the privileges.
	 */
	if(mem->mem_default_nx && NOT(mem->mem_executed) && NOT(fault_type & VM_PROT_EXECUTE))
		iprod &= ~VM_PROT_EXECUTE;

	/*
	 * If the lookup failes, give up. XXX: It shouldn't behave like this.
	 */
	if(!vm_mem_lookup(mem,rva, &pa, &iprod)) GIVE_UP;

	/*
	 * Check, if the access type violates those protection imposed by individual
	 * page-objects (if any).
	 */
	if(fault_type & ~(iprod)) DO_SEGFAULT;

	/*
	 * Based on the fault-type, some of the following bits will be set: the 'accessed-bit',
	 * the 'dirty-bit' and the 'executed-bit'.
	 */
	if(fault_type & VM_PROT_WRITE  ) mem->mem_dirty    = 1;
	if(fault_type & VM_PROT_EXECUTE) mem->mem_executed = 1;
	mem->mem_accessed = 1;

	/*
	 * Flush the cache on the given Page address only for the current pmap_t.
	 */
	xcpu_cache_flush_page(as->as_pmap,va);

	/*
	 * Map the memory. If it failes, give up.
	 */
	kernlock_lock(&(as->as_lock_pmap));

	if( pmap_enter(as->as_pmap,va,pa,iprod,0) ) {
		kernlock_unlock(&(as->as_lock_pmap));
		GIVE_UP;
	}

	kernlock_unlock(&(as->as_lock_pmap));

	/*
	 * Flush the faulted page on the given Page address only for the current pmap_t.
	 */
	xcpu_tlb_flush_page(as->as_pmap,va);

	kernlock_unlock(&(seg->seg_lock));
	return VM_OK;
}


text:
@(orders: Seq[(paermar.model.Domain.OrdersModule.Order, paermar.model.Domain.CustomersModule.Customer)])
@main {

Current orders

Lorem ipsum.

                        Status
                        Customer
                        Comment

                @for((order, customer) <- orders) {

                        @order.status
                        @customer.name
                        @order.comment

                }

}


text:
layout: organization
category: local

title: Brooklyn Autism Center
impact_area: Health
keywords:
location_services:
location_offices:
website: brooklynautismcenter.org

description:
mission: |
  The BAC is a not-for-profit 501(c)(3) school serving children with special needs. We are located in the historic Brooklyn Heights neighborhood, one subway stop from Manhattan, and steps from the Brooklyn Bridge.

  Our program is founded by parents, educators and community activists who are determined to provide high quality, effective educational services for children that need 1:1 support. Our philosophy is grounded in data-based scientific research, Applied Behavior Analysis (ABA), which is the educational standard and best practice for children on the Autism Spectrum.

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: Brooklyn
state: NY
address: |
  111 Remsen Street
  Brooklyn NY 11201
lat: 40.693979
lng: -73.994107
phone: 718-554-1027
ext:
fax: 718-360-9595
email:
preferred_contact:
contact_person_intro:
---


text:
import React from 'react';
import store from './store.js';

export default class Component extends React.Component {
  constructor() {
    super();
  }

  componentDidMount() {
    this.listenerId = store.addListener(this._handleChange.bind(this));
  }

  componentWillUnmount() {
    store.removeListener(this.listenerId);
  }

  registerFor(items) {
    this.registeredDefaults = items;
    this.state = this._getStateFromStore();
  }

  _getStateFromStore() {
    const state = {};
    Object.keys(this.registeredDefaults).forEach(namespace => {
      state[namespace] = {};
      Object.keys(this.registeredDefaults[namespace]).forEach(key => {
        state[namespace][key] = store.get(namespace, key, this.registeredDefaults[namespace][key]);
      });
    });
    return state;
  }

  _getKeys() {
    const ret = {};
    if(this.registeredDefaults) {
      Object.keys(this.registeredDefaults).forEach(namespace => {
        ret[namespace] = Object.keys(this.registeredDefaults[namespace]);
      })
    }
    return ret;
  }

  _handleChange(state, keys) {
    if (this._hasChange(keys, this._getKeys())) {
      this.setState(this._getStateFromStore());
    }
  }

  _hasChange(keys1, keys2) {
    return Object.keys(keys1).filter(namespace => {
      if (!keys2[namespace]) {
        return false;
      } else {
        return Object.keys(keys1[namespace]).filter(key => keys2[namespace][key] !== undefined).length > 0;
      }
    }).length > 0;
  }
}


text:
package cgen_test

import (
	"bytes"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
	"testing"

	"github.com/rthornton128/minc/cgen"
	"github.com/rthornton128/minc/parse"
)

func TestGenerateSanity(t *testing.T) {
	src := strings.NewReader("func main() {}")

	var p parse.Parser
	p.Init("cgen.mc", src)

	// compile program
	prog := p.Parse()
	buf1 := new(bytes.Buffer)
	gen := cgen.CGen{buf1}
	gen.Generate(prog)

	// compile program again
	buf2 := new(bytes.Buffer)
	gen = cgen.CGen{buf2}
	gen.Generate(prog)

	// confirm results are the same
	if bytes.Compare(buf1.Bytes(), buf2.Bytes()) != 0 {
		t.Fatal("output from buf1 differs from buf2")
	}
}

func TestGenerateAssemble(t *testing.T) {
	src := strings.NewReader("func main() {}")

	var p parse.Parser
	p.Init("cgen.mc", src)

	// compile program
	prog := p.Parse()
	buf := new(bytes.Buffer)
	gen := cgen.CGen{buf}
	gen.Generate(prog)

	if msg, err := execAssembler(buf); err != nil {
		if msg != nil {
			t.Log(string(msg))
		}
		t.Fatal(err)
	}
}

func execAssembler(buf *bytes.Buffer) ([]byte, error) {
	f, err := ioutil.TempFile("", "cgentest")
	if err != nil {
		return nil, err
	}
	defer os.Remove(f.Name())
	defer f.Close()

	cmd := exec.Command("as", "-o", f.Name())
	cmd.Stdin = buf
	return cmd.CombinedOutput()
}


text:
Various programming experiments written in x86_64 assembly language using flat assembler (http://flatassembler.net/index.php).
CPU with AVX2 support is required.

amnestia - 3D rotating triangle coded in pure ASM using DX12 for educational purposes.

buddhabrot - Mandelbrot fractal variation.

cpuraymarching - Real-time ray marching of simple distance field on the CPU with soft shadows. Very fast, vectorized and multithreaded ASM code.


text:
class Post < ActiveRecord::Base
	validates :filmid, presence: true,
                    length: { minimum: 5 }
end


text:
package epublibre.eplerratas.controlador;

import epublibre.eplerratas.modelo.Modelo;
import epublibre.eplerratas.modelo.informe.Informe;
import epublibre.eplerratas.modelo.plantilla.Expresion;
import epublibre.eplerratas.modelo.plantilla.Plantilla;
import epublibre.eplerratas.modelo.preferencias.Preferencias;
import epublibre.eplerratas.vista.Vista;
import epublibre.eplerratas.vista.panelconfiguracion.PanelConfiguracion;
import epublibre.eplerratas.vista.panelconfiguracion.SubpanelExportar;
import epublibre.eplerratas.vista.panelconfiguracion.SubpanelExpresiones;
import epublibre.eplerratas.vista.panelconfiguracion.SubpanelGeneral;
import epublibre.eplerratas.vista.panelconfiguracion.SubpanelImportar;
import epublibre.eplerratas.vista.panelconfiguracion.SubpanelPlantillas;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author ePubLibre
 */
public final class ControlConfiguracion {

    private static final String MENSAJE_NOMBRE_PLANTILLA = "Los nombres de plantillas/expresiones regulares deben:\n\n"
            + "—Comenzar con una letra; al menos debe contener un carácter.\n"
            + "—Contener caracteres imprimibles; no se permiten espacios en blanco.\n"
            + "—Ser únicos; no se permiten nombres repetidos.\n\n";

    private ControlConfiguracion() {
    }

    /**
     *
     * @param modelo
     * @param vista
     */
    public static void configurarEventos(Modelo modelo, Vista vista) {
        SubpanelGeneral subpanel_gen = vista.getConfiguracion().getGeneral();
        subpanel_gen.addEscuchaBotonOrden(cambioBotonOrden(modelo, vista));
        subpanel_gen.addEscuchaBotonSalida(accionBotonSalida(modelo, vista));
        subpanel_gen.addEscuchaTextoSeparador(focoTextoSeparador(modelo, vista));

        SubpanelImportar subpanel_imp = vista.getConfiguracion().getImportar();
        subpanel_imp.addEscuchaAreaTexto(cambioDocumentoInforme(modelo, vista));
        subpanel_imp.addEscuchaBotonBorrar(accionBotonBorrarPlantillaRegex(modelo, vista));
        subpanel_imp.addEscuchaBotonCrear(accionBotonCrearPlantillaRegex(modelo, vista));
        subpanel_imp.addEscuchaBotonGuardar(accionBotonGuardarPlantillaRegex(modelo, vista));
        subpanel_imp.addEscuchaBotonRenombrar(accionBotonRenombrarPlantillaRegex(modelo, vista));
        subpanel_imp.addEscuchaBotonSeleccionar(accionBotonSeleccionarPlantillaRegex(modelo, vista));
        subpanel_imp.addEscuchaBotonPlantilla(accionBotonPlantillaRegex(modelo, vista, true));
        subpanel_imp.addEscuchaBotonRegex(accionBotonPlantillaRegex(modelo, vista, false));

        SubpanelPlantillas subpanel_imp_pla = subpanel_imp.getPanelPlantillas();
        subpanel_imp_pla.addEscuchaAreaTexto(cambioDocumentoPlantillaRegex(modelo, vista));
        subpanel_imp_pla.addEscuchaBotonFecha(accionBotonTokenPlantilla(subpanel_imp_pla, modelo.getTokenFecha()));
        subpanel_imp_pla.addEscuchaBotonLinea(accionBotonTokenPlantilla(subpanel_imp_pla, modelo.getTokenLinea()));
        subpanel_imp_pla.addEscuchaBotonNota(accionBotonTokenPlantilla(subpanel_imp_pla, modelo.getTokenNota()));
        subpanel_imp_pla.addEscuchaBotonPagina(accionBotonTokenPlantilla(subpanel_imp_pla, modelo.getTokenPagina()));
        subpanel_imp_pla.addEscuchaBotonPorcentaje(accionBotonTokenPlantilla(subpanel_imp_pla, modelo.getTokenPorcentaje()));
        subpanel_imp_pla.addEscuchaBotonResalte(accionBotonTokenPlantilla(subpanel_imp_pla, modelo.getTokenResalte()));
        subpanel_imp_pla.addEscuchaBotonSeccion(accionBotonTokenPlantilla(subpanel_imp_pla, modelo.getTokenSeccion()));
        subpanel_imp_pla.addEscuchaRatonPlantilla(ratonListaPlantilla(modelo, vista, subpanel_imp_pla, true));
        subpanel_imp_pla.addEscuchaSeleccionPlantilla(seleccionListaPlantillaImportar(vista.getConfiguracion().getImportar()));
        subpanel_imp_pla.addEscuchaTecladoPlantilla(tecladoListaPlantilla(modelo, vista, subpanel_imp_pla, true));

        SubpanelExpresiones subpanel_imp_exp = subpanel_imp.getPanelExpresiones();
        subpanel_imp_exp.addEscuchaAreaTexto(cambioDocumentoRegex(modelo, vista));
        subpanel_imp_exp.addEscuchaRatonExpresion(ratonListaExpresion(modelo, vista, subpanel_imp_exp));
        subpanel_imp_exp.addEscuchaSeleccionExpresion(seleccionListaExpresion(vista.getConfiguracion().getImportar()));
        subpanel_imp_exp.addEscuchaTecladoExpresion(tecladoListaExpresion(modelo, vista, subpanel_imp_exp));

        SubpanelExportar subpanel_exp = vista.getConfiguracion().getExportar();
        subpanel_exp.addEscuchaBotonBorrar(accionBotonBorrarPlantilla(modelo, vista));
        subpanel_exp.addEscuchaBotonCrear(accionBotonCrearPlantilla(modelo, vista));
        subpanel_exp.addEscuchaBotonGuardar(accionBotonGuardarPlantilla(modelo, vista));
        subpanel_exp.addEscuchaBotonRenombrar(accionBotonRenombrarPlantilla(modelo, vista));
        subpanel_exp.addEscuchaBotonSeleccionar(accionBotonSeleccionarPlantilla(modelo, vista));

        SubpanelPlantillas subpanel_exp_pla = subpanel_exp.getPanelPlantillas();
        subpanel_exp_pla.addEscuchaAreaTexto(cambioDocumentoPlantilla(modelo, vista));
        subpanel_exp_pla.addEscuchaBotonFecha(accionBotonTokenPlantilla(subpanel_exp_pla, modelo.getTokenFecha()));
        subpanel_exp_pla.addEscuchaBotonLinea(accionBotonTokenPlantilla(subpanel_exp_pla, modelo.getTokenLinea()));
        subpanel_exp_pla.addEscuchaBotonNota(accionBotonTokenPlantilla(subpanel_exp_pla, modelo.getTokenNota()));
        subpanel_exp_pla.addEscuchaBotonPagina(accionBotonTokenPlantilla(subpanel_exp_pla, modelo.getTokenPagina()));
        subpanel_exp_pla.addEscuchaBotonPorcentaje(accionBotonTokenPlantilla(subpanel_exp_pla, modelo.getTokenPorcentaje()));
        subpanel_exp_pla.addEscuchaBotonResalte(accionBotonTokenPlantilla(subpanel_exp_pla, modelo.getTokenResalte()));
        subpanel_exp_pla.addEscuchaBotonSeccion(accionBotonTokenPlantilla(subpanel_exp_pla, modelo.getTokenSeccion()));
        subpanel_exp_pla.addEscuchaRatonPlantilla(ratonListaPlantilla(modelo, vista, subpanel_exp_pla, false));
        subpanel_exp_pla.addEscuchaSeleccionPlantilla(seleccionListaPlantillaExportar(modelo, vista, vista.getConfiguracion().getExportar()));
        subpanel_exp_pla.addEscuchaTecladoPlantilla(tecladoListaPlantilla(modelo, vista, subpanel_exp_pla, false));
    }

    /**
     *
     * @param modelo
     * @param vista
     */
    public static void iniciarComponentes(Modelo modelo, Vista vista) {
        PanelConfiguracion panel = vista.getConfiguracion();

        SubpanelGeneral subpanel_gen = panel.getGeneral();

        Preferencias preferencias = modelo.getPreferencias();
        subpanel_gen.setOrden(preferencias.getOrdenMarcas());
        subpanel_gen.setTextoSalida(preferencias.getCarpetaSalida());
        subpanel_gen.setTextoSeparador(preferencias.getSeparadorMarcasBq());

        SubpanelExportar subpanel_exp = panel.getExportar();

        subpanel_exp.getPanelPlantillas().setPlantillas(modelo.getPlantillas(false));

        SubpanelImportar subpanel_imp = panel.getImportar();

        subpanel_imp.getPanelPlantillas().setPlantillas(modelo.getPlantillas(true));
        subpanel_imp.getPanelExpresiones().setExpresiones(modelo.getExpresiones());
    }

    private static ActionListener accionBotonBorrarPlantilla(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            SubpanelPlantillas subpanel = vista.getConfiguracion().getExportar().getPanelPlantillas();
            if (!subpanel.isSeleccionVacia()) {
                borrarPlantilla(modelo, subpanel, false);
            }
        };
    }

    private static ActionListener accionBotonBorrarPlantillaRegex(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            if (vista.getConfiguracion().getImportar().isRegEx()) {
                SubpanelExpresiones subpanel = vista.getConfiguracion().getImportar().getPanelExpresiones();
                if (!subpanel.isSeleccionVacia()) {
                    borrarExpresion(modelo, subpanel);
                }
            } else {
                SubpanelPlantillas subpanel = vista.getConfiguracion().getImportar().getPanelPlantillas();
                if (!subpanel.isSeleccionVacia()) {
                    borrarPlantilla(modelo, subpanel, true);
                }
            }
        };
    }

    private static ActionListener accionBotonCrearPlantilla(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            SubpanelPlantillas subpanel = vista.getConfiguracion().getExportar().getPanelPlantillas();
            crearPlantilla(modelo, subpanel, false);
        };
    }

    private static ActionListener accionBotonCrearPlantillaRegex(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            if (vista.getConfiguracion().getImportar().isRegEx()) {
                SubpanelExpresiones subpanel = vista.getConfiguracion().getImportar().getPanelExpresiones();
                crearExpresion(modelo, subpanel);
            } else {
                SubpanelPlantillas subpanel = vista.getConfiguracion().getImportar().getPanelPlantillas();
                crearPlantilla(modelo, subpanel, true);
            }
        };
    }

    private static ActionListener accionBotonGuardarPlantilla(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            SubpanelPlantillas subpanel = vista.getConfiguracion().getExportar().getPanelPlantillas();
            if (!subpanel.isSeleccionVacia()) {
                guardarPlantilla(modelo, subpanel);
            }
        };
    }

    private static ActionListener accionBotonGuardarPlantillaRegex(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            if (vista.getConfiguracion().getImportar().isRegEx()) {
                SubpanelExpresiones subpanel = vista.getConfiguracion().getImportar().getPanelExpresiones();
                if (!subpanel.isSeleccionVacia()) {
                    guardarExpresion(modelo, subpanel);
                }
            } else {
                SubpanelPlantillas subpanel = vista.getConfiguracion().getImportar().getPanelPlantillas();
                if (!subpanel.isSeleccionVacia()) {
                    guardarPlantilla(modelo, subpanel);
                }
            }
        };
    }

    private static ActionListener accionBotonPlantillaRegex(Modelo modelo, Vista vista, boolean esPlantilla) {
        return (ActionEvent e) -> {
            if (((JToggleButton) e.getSource()).isSelected()) {
                SubpanelImportar subpanel = vista.getConfiguracion().getImportar();
                subpanel.setVisibleSubpanelPlantillas(esPlantilla);
                if (esPlantilla) {
                    subpanel.getPanelExpresiones().borrarSeleccion();
                    subpanel.getPanelExpresiones().setCampoTexto("");
                    subpanel.getPanelExpresiones().habilitarExpresion(false);
                } else {
                    subpanel.getPanelPlantillas().borrarSeleccion();
                    subpanel.getPanelPlantillas().setAreaTexto("");
                    subpanel.getPanelPlantillas().habilitarPlantilla(false);
                }
                subpanel.habilitarBorrar(false);
                subpanel.habilitarGuardar(false);
                subpanel.habilitarRenombrar(false);
                subpanel.habilitarSeleccionar(false);
                actualizarVistaPreviaImportar(modelo, vista);
            }
        };
    }

    private static ActionListener accionBotonRenombrarPlantilla(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            SubpanelPlantillas subpanel = vista.getConfiguracion().getExportar().getPanelPlantillas();
            if (!subpanel.isSeleccionVacia()) {
                renombrarPlantilla(modelo, subpanel, false);
            }
        };
    }

    private static ActionListener accionBotonRenombrarPlantillaRegex(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            if (vista.getConfiguracion().getImportar().isRegEx()) {
                SubpanelExpresiones subpanel = vista.getConfiguracion().getImportar().getPanelExpresiones();
                if (!subpanel.isSeleccionVacia()) {
                    renombrarExpresion(modelo, subpanel);
                }
            } else {
                SubpanelPlantillas subpanel = vista.getConfiguracion().getImportar().getPanelPlantillas();
                if (!subpanel.isSeleccionVacia()) {
                    renombrarPlantilla(modelo, subpanel, true);
                }
            }
        };
    }

    private static ActionListener accionBotonSalida(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            File carpeta = vista.getConfiguracion().getGeneral().getCarpetaSalida();
            if (carpeta != null) {
                String ruta = carpeta.getAbsolutePath();
                vista.getConfiguracion().getGeneral().setTextoSalida(ruta);
                vista.getPrincipal().setEtiquetaCarpeta(ruta);
                Preferencias preferencias = modelo.getPreferencias();
                preferencias.setCarpetaSalida(ruta);
                modelo.setPreferencias(preferencias);
            }
        };
    }

    private static ActionListener accionBotonSeleccionarPlantilla(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            SubpanelPlantillas subpanel = vista.getConfiguracion().getExportar().getPanelPlantillas();
            if (!subpanel.isSeleccionVacia()) {
                seleccionarPlantilla(modelo, vista, subpanel, false);
            }
        };
    }

    private static ActionListener accionBotonSeleccionarPlantillaRegex(Modelo modelo, Vista vista) {
        return (ActionEvent e) -> {
            if (vista.getConfiguracion().getImportar().isRegEx()) {
                SubpanelExpresiones subpanel = vista.getConfiguracion().getImportar().getPanelExpresiones();
                if (!subpanel.isSeleccionVacia()) {
                    seleccionarExpresion(modelo, vista, subpanel);
                }
            } else {
                SubpanelPlantillas subpanel = vista.getConfiguracion().getImportar().getPanelPlantillas();
                if (!subpanel.isSeleccionVacia()) {
                    seleccionarPlantilla(modelo, vista, subpanel, true);
                }
            }
        };
    }

    private static ActionListener accionBotonTokenPlantilla(SubpanelPlantillas subpanel, String token) {
        return (ActionEvent e) -> {
            subpanel.addAreaTexto(token);
        };
    }

    private static void actualizarVistaPreviaExportar(Modelo modelo, Vista vista) {
        int[] indices = vista.getPrincipal().getIndicesSeleccion();
        Informe informe = null;
        if (indices.length > 0) {
            informe = modelo.getInforme(vista.getPrincipal().getInforme(indices[0]).getId());
        }
        Plantilla plantilla = new Plantilla();
        plantilla.setTexto(vista.getConfiguracion().getExportar().getPanelPlantillas().getAreaTexto());
        String texto = modelo.getPreviaExportar(informe, plantilla);
        vista.getConfiguracion().getExportar().setVistaPrevia(texto);
    }

    private static void actualizarVistaPreviaImportar(Modelo modelo, Vista vista) {
        String texto_informe = vista.getConfiguracion().getImportar().getAreaTextoInforme();
        String texto_previa;
        if (vista.getConfiguracion().getImportar().isRegEx()) {
            SubpanelExpresiones subpanel = vista.getConfiguracion().getImportar().getPanelExpresiones();
            Expresion expresion = new Expresion();
            expresion.setTexto(subpanel.getCampoTexto());
            expresion.setIndiceFecha(subpanel.getGrupoFecha());
            expresion.setIndiceNota(subpanel.getGrupoNota());
            expresion.setIndicePagina(subpanel.getGrupoPagina());
            expresion.setIndicePorcentaje(subpanel.getGrupoPorcentaje());
            expresion.setIndiceResalte(subpanel.getGrupoResalte());
            expresion.setIndiceSeccion(subpanel.getGrupoSeccion());
            texto_previa = modelo.getPreviaImportar(texto_informe, expresion);
        } else {
            Plantilla plantilla = new Plantilla();
            plantilla.setTexto(vista.getConfiguracion().getImportar().getPanelPlantillas().getAreaTexto());
            texto_previa = modelo.getPreviaImportar(texto_informe, plantilla);
        }
        vista.getConfiguracion().getImportar().setVistaPrevia(texto_previa);
    }

    private static void borrarExpresion(Modelo modelo, SubpanelExpresiones subpanel) {
        long id = subpanel.getSeleccionada().getId();
        modelo.borrarExpresion(id);
        subpanel.setExpresiones(modelo.getExpresiones());
    }

    private static void borrarPlantilla(Modelo modelo, SubpanelPlantillas subpanel, boolean esEntrada) {
        long id = subpanel.getPlantillaSeleccionada().getId();
        modelo.borrarPlantilla(id);
        subpanel.setPlantillas(modelo.getPlantillas(esEntrada));
    }

    private static ChangeListener cambioBotonOrden(Modelo modelo, Vista vista) {
        return (ChangeEvent e) -> {
            int orden_marcas = vista.getConfiguracion().getGeneral().getOrden();
            Preferencias preferencias = modelo.getPreferencias();
            preferencias.setOrdenMarcas(orden_marcas);
            modelo.setPreferencias(preferencias);
            vista.getPrincipal().borrarSeleccion();
            vista.getEdicion().borrarSeleccionLista();
        };
    }

    private static DocumentListener cambioDocumentoInforme(Modelo modelo, Vista vista) {
        return (new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                actualizarVistaPreviaImportar(modelo, vista);
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                actualizarVistaPreviaImportar(modelo, vista);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                actualizarVistaPreviaImportar(modelo, vista);
            }
        });
    }

    private static DocumentListener cambioDocumentoPlantilla(Modelo modelo, Vista vista) {
        return new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                actualizarVistaPreviaExportar(modelo, vista);
                pintarFondoAreaTexto(modelo, vista);
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                actualizarVistaPreviaExportar(modelo, vista);
                pintarFondoAreaTexto(modelo, vista);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                actualizarVistaPreviaExportar(modelo, vista);
                pintarFondoAreaTexto(modelo, vista);
            }
        };
    }

    private static DocumentListener cambioDocumentoPlantillaRegex(Modelo modelo, Vista vista) {
        return (new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                actualizarVistaPreviaImportar(modelo, vista);
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                actualizarVistaPreviaImportar(modelo, vista);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                actualizarVistaPreviaImportar(modelo, vista);
            }
        });
    }

    private static DocumentListener cambioDocumentoRegex(Modelo modelo, Vista vista) {
        return (new DocumentListener() {
            @Override
            public void changedUpdate(DocumentEvent e) {
                accionCambioRegex();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                accionCambioRegex();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                accionCambioRegex();
            }

            private void accionCambioRegex() {
                String texto_regex = vista.getConfiguracion().getImportar().getPanelExpresiones().getCampoTexto();
                int num_grupos = modelo.numGruposExpresion(texto_regex);
                vista.getConfiguracion().getImportar().getPanelExpresiones().setMaximoGrupo(num_grupos);
                actualizarVistaPreviaImportar(modelo, vista);
            }
        });
    }

    private static void crearExpresion(Modelo modelo, SubpanelExpresiones subpanel) {
        String nombre_regex = Vista.mostrarPregunta("Crear expresión regular", MENSAJE_NOMBRE_PLANTILLA);
        if (nombre_regex != null) {
            if (!modelo.esNombreValidoPlantillaRegEx(nombre_regex)) {
                Vista.mostrarAviso("El nombre no es válido.");
            } else if (modelo.existeNombrePlantillaRegEx(nombre_regex)) {
                Vista.mostrarAviso("El nombre ya está en uso.");
            } else {
                modelo.addExpresion(nombre_regex);
                subpanel.setExpresiones(modelo.getExpresiones());
            }
        }
    }

    private static void crearPlantilla(Modelo modelo, SubpanelPlantillas subpanel, boolean esEntrada) {
        String nombre_plantilla = Vista.mostrarPregunta("Crear plantilla", MENSAJE_NOMBRE_PLANTILLA);
        if (nombre_plantilla != null) {
            if (!modelo.esNombreValidoPlantillaRegEx(nombre_plantilla)) {
                Vista.mostrarAviso("El nombre no es válido.");
            } else if (modelo.existeNombrePlantillaRegEx(nombre_plantilla)) {
                Vista.mostrarAviso("El nombre ya está en uso.");
            } else {
                modelo.addPlantilla(nombre_plantilla, esEntrada);
                subpanel.setPlantillas(modelo.getPlantillas(esEntrada));
            }
        }
    }

    private static FocusListener focoTextoSeparador(Modelo modelo, Vista vista) {
        return new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
            }

            @Override
            public void focusLost(FocusEvent e) {
                String texto_separador = vista.getConfiguracion().getGeneral().getTextoSeparador();
                if (!texto_separador.trim().isEmpty()) {
                    Preferencias preferencias = modelo.getPreferencias();
                    preferencias.setSeparadorMarcasBq(texto_separador);
                    modelo.setPreferencias(preferencias);
                    vista.getConfiguracion().getGeneral().setTextoSeparador(texto_separador);
                }
            }
        };
    }

    private static void guardarExpresion(Modelo modelo, SubpanelExpresiones subpanel) {
        Expresion expresion = subpanel.getSeleccionada();
        expresion.setTexto(subpanel.getCampoTexto());
        expresion.setIndiceFecha(subpanel.getGrupoFecha());
        expresion.setIndiceNota(subpanel.getGrupoNota());
        expresion.setIndicePagina(subpanel.getGrupoPagina());
        expresion.setIndicePorcentaje(subpanel.getGrupoPorcentaje());
        expresion.setIndiceResalte(subpanel.getGrupoResalte());
        expresion.setIndiceSeccion(subpanel.getGrupoSeccion());
        modelo.setExpresion(expresion);
    }

    private static void guardarPlantilla(Modelo modelo, SubpanelPlantillas subpanel) {
        Plantilla plantilla = subpanel.getPlantillaSeleccionada();
        plantilla.setTexto(subpanel.getAreaTexto());
        modelo.setPlantilla(plantilla);
    }

    private static void pintarFondoAreaTexto(Modelo modelo, Vista vista) {
        SubpanelPlantillas subpanel = vista.getConfiguracion().getExportar().getPanelPlantillas();
        String texto_plantilla = subpanel.getAreaTexto();
        if (texto_plantilla.isEmpty()) {
            subpanel.setColorAreaTexto(Color.getHSBColor(0.66f, 0.15f, 1));
        } else if (modelo.esPlantillaValida(texto_plantilla)) {
            subpanel.setColorAreaTexto(Color.white);
        } else if (modelo.esPlantillaCorrecta(texto_plantilla)) {
            subpanel.setColorAreaTexto(Color.getHSBColor(0.25f, 0.25f, 1));
        } else {
            subpanel.setColorAreaTexto(Color.getHSBColor(0, 0.2f, 1));
        }
    }

    private static MouseListener ratonListaExpresion(Modelo modelo, Vista vista, SubpanelExpresiones subpanel) {
        return new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() >= 2 && !subpanel.isSeleccionVacia()) {
                    seleccionarExpresion(modelo, vista, subpanel);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }
        };
    }

    private static MouseListener ratonListaPlantilla(Modelo modelo, Vista vista, SubpanelPlantillas subpanel, boolean esEntrada) {
        return new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() >= 2 && !subpanel.isSeleccionVacia()) {
                    seleccionarPlantilla(modelo, vista, subpanel, esEntrada);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }
        };
    }

    private static void renombrarExpresion(Modelo modelo, SubpanelExpresiones subpanel) {
        String nombre_expreseion = Vista.mostrarPregunta("Renombrar expresión regular", MENSAJE_NOMBRE_PLANTILLA);
        if (nombre_expreseion != null) {
            if (!modelo.esNombreValidoPlantillaRegEx(nombre_expreseion)) {
                Vista.mostrarAviso("El nombre no es válido.");
            } else if (modelo.existeNombrePlantillaRegEx(nombre_expreseion)) {
                Vista.mostrarAviso("El nombre ya está en uso.");
            } else {
                Expresion expresion = subpanel.getSeleccionada();
                expresion.setNombre(nombre_expreseion);
                modelo.setExpresion(expresion);
                subpanel.setExpresiones(modelo.getExpresiones());
            }
        }
    }

    private static void renombrarPlantilla(Modelo modelo, SubpanelPlantillas subpanel, boolean esEntrada) {
        String nombre_plantilla = Vista.mostrarPregunta("Renombrar plantilla", MENSAJE_NOMBRE_PLANTILLA);
        if (nombre_plantilla != null) {
            if (!modelo.esNombreValidoPlantillaRegEx(nombre_plantilla)) {
                Vista.mostrarAviso("El nombre no es válido.");
            } else if (modelo.existeNombrePlantillaRegEx(nombre_plantilla)) {
                Vista.mostrarAviso("El nombre ya está en uso.");
            } else {
                Plantilla plantilla = subpanel.getPlantillaSeleccionada();
                plantilla.setNombre(nombre_plantilla);
                modelo.setPlantilla(plantilla);
                subpanel.setPlantillas(modelo.getPlantillas(esEntrada));
            }
        }
    }

    private static ListSelectionListener seleccionListaExpresion(SubpanelImportar subpanel) {
        return (ListSelectionEvent e) -> {
            if (!e.getValueIsAdjusting()) {
                if (subpanel.isRegEx()) {
                    if (subpanel.getPanelExpresiones().isSeleccionVacia()) {
                        subpanel.getPanelExpresiones().setCampoGrupoFecha(0);
                        subpanel.getPanelExpresiones().setCampoGrupoNota(0);
                        subpanel.getPanelExpresiones().setCampoGrupoPagina(0);
                        subpanel.getPanelExpresiones().setCampoGrupoPorcentaje(0);
                        subpanel.getPanelExpresiones().setCampoGrupoResalte(0);
                        subpanel.getPanelExpresiones().setCampoGrupoSeccion(0);
                        subpanel.getPanelExpresiones().habilitarExpresion(false);
                        subpanel.habilitarBorrar(false);
                        subpanel.habilitarGuardar(false);
                        subpanel.habilitarRenombrar(false);
                        subpanel.habilitarSeleccionar(false);
                        subpanel.getPanelExpresiones().setCampoTexto("");
                    } else {
                        Expresion expresion = subpanel.getPanelExpresiones().getSeleccionada();
                        subpanel.getPanelExpresiones().setCampoGrupoFecha(expresion.getIndiceFecha());
                        subpanel.getPanelExpresiones().setCampoGrupoNota(expresion.getIndiceNota());
                        subpanel.getPanelExpresiones().setCampoGrupoPagina(expresion.getIndicePagina());
                        subpanel.getPanelExpresiones().setCampoGrupoPorcentaje(expresion.getIndicePorcentaje());
                        subpanel.getPanelExpresiones().setCampoGrupoResalte(expresion.getIndiceResalte());
                        subpanel.getPanelExpresiones().setCampoGrupoSeccion(expresion.getIndiceSeccion());
                        subpanel.getPanelExpresiones().habilitarExpresion(!expresion.isPredeterminada());
                        subpanel.habilitarBorrar(!expresion.isPredeterminada());
                        subpanel.habilitarGuardar(!expresion.isPredeterminada());
                        subpanel.habilitarRenombrar(!expresion.isPredeterminada());
                        subpanel.habilitarSeleccionar(!expresion.isSeleccionada());
                        subpanel.getPanelExpresiones().setCampoTexto(expresion.getTexto());
                    }
                }
            }
        };
    }

    private static ListSelectionListener seleccionListaPlantillaExportar(Modelo modelo, Vista vista, SubpanelExportar subpanel) {
        return (ListSelectionEvent e) -> {
            if (!e.getValueIsAdjusting()) {
                if (subpanel.getPanelPlantillas().isSeleccionVacia()) {
                    subpanel.getPanelPlantillas().setAreaTexto("");
                    subpanel.getPanelPlantillas().habilitarPlantilla(false);
                    subpanel.habilitarBorrar(false);
                    subpanel.habilitarGuardar(false);
                    subpanel.habilitarRenombrar(false);
                    subpanel.habilitarSeleccionar(false);
                    subpanel.getPanelPlantillas().setColorAreaTexto(Color.gray);
                } else {
                    Plantilla plantilla = subpanel.getPanelPlantillas().getPlantillaSeleccionada();
                    subpanel.getPanelPlantillas().setAreaTexto(plantilla.getTexto());
                    subpanel.getPanelPlantillas().habilitarPlantilla(!plantilla.isPredeterminada());
                    subpanel.habilitarBorrar(!plantilla.isPredeterminada());
                    subpanel.habilitarGuardar(!plantilla.isPredeterminada());
                    subpanel.habilitarRenombrar(!plantilla.isPredeterminada());
                    subpanel.habilitarSeleccionar(!plantilla.isSeleccionada());
                    pintarFondoAreaTexto(modelo, vista);
                }
            }
        };
    }

    private static ListSelectionListener seleccionListaPlantillaImportar(SubpanelImportar subpanel) {
        return (ListSelectionEvent e) -> {
            if (!e.getValueIsAdjusting()) {
                if (!subpanel.isRegEx()) {
                    if (subpanel.getPanelPlantillas().isSeleccionVacia()) {
                        subpanel.getPanelPlantillas().setAreaTexto("");
                        subpanel.getPanelPlantillas().habilitarPlantilla(false);
                        subpanel.habilitarBorrar(false);
                        subpanel.habilitarGuardar(false);
                        subpanel.habilitarRenombrar(false);
                        subpanel.habilitarSeleccionar(false);
                    } else {
                        Plantilla plantilla = subpanel.getPanelPlantillas().getPlantillaSeleccionada();
                        subpanel.getPanelPlantillas().setAreaTexto(plantilla.getTexto());
                        subpanel.getPanelPlantillas().habilitarPlantilla(!plantilla.isPredeterminada());
                        subpanel.habilitarBorrar(!plantilla.isPredeterminada());
                        subpanel.habilitarGuardar(!plantilla.isPredeterminada());
                        subpanel.habilitarRenombrar(!plantilla.isPredeterminada());
                        subpanel.habilitarSeleccionar(!plantilla.isSeleccionada());
                    }
                }
            }
        };
    }

    private static void seleccionarExpresion(Modelo modelo, Vista vista, SubpanelExpresiones subpanel) {
        Expresion expresion = subpanel.getSeleccionada();
        if (!expresion.isSeleccionada()) {
            modelo.setExpresionSeleccionada(expresion);
            subpanel.setExpresiones(modelo.getExpresiones());
            vista.getConfiguracion().getImportar().getPanelPlantillas().setPlantillas(modelo.getPlantillas(true));
            vista.getPrincipal().setEtiquetaEntrada(modelo.getExpresionSeleccionada().getNombre(), false);
        }
    }

    private static void seleccionarPlantilla(Modelo modelo, Vista vista, SubpanelPlantillas subpanel, boolean esEntrada) {
        Plantilla plantilla = subpanel.getPlantillaSeleccionada();
        if (!plantilla.isSeleccionada()) {
            modelo.setPlantillaSeleccionada(plantilla);
            subpanel.setPlantillas(modelo.getPlantillas(esEntrada));
            if (esEntrada) {
                vista.getConfiguracion().getImportar().getPanelExpresiones().setExpresiones(modelo.getExpresiones());
                vista.getPrincipal().setEtiquetaEntrada(modelo.getPlantillaSeleccionada(esEntrada).getNombre(), esEntrada);
            } else {
                vista.getPrincipal().setEtiquetaSalida(modelo.getPlantillaSeleccionada(esEntrada).getNombre());
                if (vista.getPrincipal().getNumeroSeleccion() == 1) {
                    long informe_id = vista.getPrincipal().getInforme().getId();
                    vista.getPrincipal().setVistaPrevia(modelo.getPreviaExportar(informe_id));
                }
            }
        }
    }

    private static KeyListener tecladoListaExpresion(Modelo modelo, Vista vista, SubpanelExpresiones subpanel) {
        return new KeyListener() {
            @Override
            public void keyPressed(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 127 && !subpanel.isSeleccionVacia()) {
                    borrarExpresion(modelo, subpanel);
                } else if (e.getKeyCode() == 10 && !subpanel.isSeleccionVacia()) {
                    seleccionarExpresion(modelo, vista, subpanel);
                }
            }

            @Override
            public void keyTyped(KeyEvent e) {
            }
        };
    }

    private static KeyListener tecladoListaPlantilla(Modelo modelo, Vista vista, SubpanelPlantillas subpanel, boolean esEntrada) {
        return new KeyListener() {
            @Override
            public void keyPressed(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 127 && !subpanel.isSeleccionVacia()) {
                    borrarPlantilla(modelo, subpanel, esEntrada);
                } else if (e.getKeyCode() == 10 && !subpanel.isSeleccionVacia()) {
                    seleccionarPlantilla(modelo, vista, subpanel, esEntrada);
                }
            }

            @Override
            public void keyTyped(KeyEvent e) {
            }
        };
    }

}