text:
	#include <psapi.h>
#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
	#include <signal.h>
	#if defined(__linux__)
		#include <fstream>
	#elif defined(__APPLE__)
		#include <mach/mach.h>
	#endif
#endif

cRoot * cRoot::s_Root = nullptr;

cRoot::cRoot(void) :
	m_pDefaultWorld(nullptr),
	m_Server(nullptr),
	m_MonsterConfig(nullptr),
	m_CraftingRecipes(nullptr),
	m_FurnaceRecipe(nullptr),
	m_BrewingRecipes(nullptr),
	m_WebAdmin(nullptr),
	m_PluginManager(nullptr),
	m_MojangAPI(nullptr)
{
	s_Root = this;
	m_InputThreadRunFlag.clear();
}

cRoot::~cRoot()
{
	s_Root = 0;
}

void cRoot::InputThread(cRoot & a_Params)
{
	cLogCommandOutputCallback Output;

	while (a_Params.m_InputThreadRunFlag.test_and_set() && std::cin.good())
	{
		AString Command;
		std::getline(std::cin, Command);
		if (!Command.empty())
		{
			// Execute and clear command string when submitted
			a_Params.ExecuteConsoleCommand(TrimString(Command), Output);
		}
	}

	// We have come here because the std::cin has received an EOF / a terminate signal has been sent, and the server is still running
	if (!std::cin.good())
	{
		// Stop the server:
		a_Params.QueueExecuteConsoleCommand("stop");
	}
}

void cRoot::Start(std::unique_ptr<cSettingsRepositoryInterface> a_OverridesRepo)
{
	#ifdef _WIN32
		HMENU ConsoleMenu = GetSystemMenu(GetConsoleWindow(), FALSE);
		EnableMenuItem(ConsoleMenu, SC_CLOSE, MF_GRAYED);  // Disable close button when starting up; it causes problems with our CTRL-CLOSE handling
	#endif

	auto consoleLogListener = MakeConsoleListener(m_RunAsService);
	auto consoleAttachment = cLogger::GetInstance().AttachListener(std::move(consoleLogListener));
	auto fileLogListenerRet = MakeFileListener();
	if (!fileLogListenerRet.first)
	{
		LOGERROR("Failed to open log file, aborting");
		return;
	}
	auto fileAttachment = cLogger::GetInstance().AttachListener(std::move(fileLogListenerRet.second));

	LOG("--- Started Log ---");

	#ifdef BUILD_ID
		LOG("Cuberite " BUILD_SERIES_NAME " build id: " BUILD_ID);
		LOG("from commit id: " BUILD_COMMIT_ID " built at: " BUILD_DATETIME);
	#endif

	// Run the self-tests registered previously via cSelfTests::Register():
	#ifdef SELF_TEST
		cSelfTests::ExecuteAll();
	#endif

	cDeadlockDetect dd;
	auto BeginTime = std::chrono::steady_clock::now();

	LoadGlobalSettings();

	LOG("Creating new server instance...");
	m_Server = new cServer();

	LOG("Reading server config...");

	auto IniFile = cpp14::make_unique<cIniFile>();
	bool IsNewIniFile = !IniFile->ReadFile("settings.ini");

	if (IsNewIniFile)
	{
		LOGWARN("Regenerating settings.ini, all settings will be reset");
		IniFile->AddHeaderComment(" This is the main server configuration");
		IniFile->AddHeaderComment(" Most of the settings here can be configured using the webadmin interface, if enabled in webadmin.ini");
		IniFile->AddHeaderComment(" See: http://wiki.mc-server.org/doku.php?id=configure:settings.ini for further configuration help");
	}

	auto settingsRepo = cpp14::make_unique<cOverridesSettingsRepository>(std::move(IniFile), std::move(a_OverridesRepo));

	LOG("Starting server...");
	m_MojangAPI = new cMojangAPI;
	bool ShouldAuthenticate = settingsRepo->GetValueSetB("Authentication", "Authenticate", true);
	m_MojangAPI->Start(*settingsRepo, ShouldAuthenticate);  // Mojang API needs to be started before plugins, so that plugins may use it for DB upgrades on server init
	if (!m_Server->InitServer(*settingsRepo, ShouldAuthenticate))
	{
		settingsRepo->Flush();
		LOGERROR("Failure starting server, aborting...");
		return;
	}

	m_WebAdmin = new cWebAdmin();
	m_WebAdmin->Init();

	LOGD("Loading settings...");
	m_RankManager.reset(new cRankManager());
	m_RankManager->Initialize(*m_MojangAPI);
	m_CraftingRecipes = new cCraftingRecipes();
	m_FurnaceRecipe   = new cFurnaceRecipe();
	m_BrewingRecipes.reset(new cBrewingRecipes());

	LOGD("Loading worlds...");
	LoadWorlds(*settingsRepo, IsNewIniFile);

	LOGD("Loading plugin manager...");
	m_PluginManager = new cPluginManager();
	m_PluginManager->ReloadPluginsNow(*settingsRepo);

	LOGD("Loading MonsterConfig...");
	m_MonsterConfig = new cMonsterConfig;

	// This sets stuff in motion
	LOGD("Starting Authenticator...");
	m_Authenticator.Start(*settingsRepo);

	LOGD("Starting worlds...");
	StartWorlds();

	if (settingsRepo->GetValueSetB("DeadlockDetect", "Enabled", true))
	{
		LOGD("Starting deadlock detector...");
		dd.Start(settingsRepo->GetValueSetI("DeadlockDetect", "IntervalSec", 20));
	}

	settingsRepo->Flush();

	LOGD("Finalising startup...");
	if (m_Server->Start())
	{
		m_WebAdmin->Start();

		#if !defined(ANDROID_NDK)
			LOGD("Starting InputThread...");
			try
			{
				m_InputThreadRunFlag.test_and_set();
				m_InputThread = std::thread(InputThread, std::ref(*this));
			}
			catch (std::system_error & a_Exception)
			{
				LOGERROR("cRoot::Start (std::thread) error %i: could not construct input thread; %s", a_Exception.code().value(), a_Exception.what());
			}
		#endif

		LOG("Startup complete, took %ldms!", static_cast<long int>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - BeginTime).count()));

		// Save the current time
		m_StartTime = std::chrono::steady_clock::now();

		#ifdef _WIN32
			EnableMenuItem(ConsoleMenu, SC_CLOSE, MF_ENABLED);  // Re-enable close button
		#endif

		for (;;)
		{
			m_StopEvent.Wait();

			if (m_TerminateEventRaised && m_RunAsService)
			{
				// Dont kill if running as a service
				m_TerminateEventRaised = false;
			}
			else
			{
				break;
			}
		}

		// Stop the server:
		m_WebAdmin->Stop();

		LOG("Shutting down server...");
		m_Server->Shutdown();
	}  // if (m_Server->Start()

	delete m_MojangAPI; m_MojangAPI = nullptr;

	LOGD("Shutting down deadlock detector...");
	dd.Stop();

	LOGD("Stopping world threads...");
	StopWorlds();

	LOGD("Stopping authenticator...");
	m_Authenticator.Stop();

	LOGD("Freeing MonsterConfig...");
	delete m_MonsterConfig; m_MonsterConfig = nullptr;
	delete m_WebAdmin; m_WebAdmin = nullptr;

	LOGD("Unloading recipes...");
	delete m_FurnaceRecipe;   m_FurnaceRecipe = nullptr;
	delete m_CraftingRecipes; m_CraftingRecipes = nullptr;

	LOG("Unloading worlds...");
	UnloadWorlds();

	LOGD("Stopping plugin manager...");
	delete m_PluginManager; m_PluginManager = nullptr;

	cItemHandler::Deinit();

	LOG("Cleaning up...");
	delete m_Server; m_Server = nullptr;

	m_InputThreadRunFlag.clear();
	#ifdef _WIN32
		DWORD Length;
		INPUT_RECORD Record
		{
			KEY_EVENT,
			{
				{
					TRUE,
					1,
					VK_RETURN,
					static_cast<WORD>(MapVirtualKey(VK_RETURN, MAPVK_VK_TO_VSC)),
					{ { VK_RETURN } },
					0
				}
			}
		};

		// Can't kill the input thread since it breaks cin (getline doesn't block / receive input on restart)
		// Apparently no way to unblock getline
		// Only thing I can think of for now
		if (WriteConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &Record, 1, &Length) == 0)
		{
			LOGWARN("Couldn't notify the input thread; the server will hang before shutdown!");
			m_TerminateEventRaised = true;
			m_InputThread.detach();
		}
		else
		{
			m_InputThread.join();
		}
	#else
		if (pthread_kill(m_InputThread.native_handle(), SIGKILL) != 0)
		{
			LOGWARN("Couldn't notify the input thread; the server will hang before shutdown!");
			m_TerminateEventRaised = true;
			m_InputThread.detach();
		}
	#endif

	if (m_TerminateEventRaised)
	{
		LOG("Shutdown successful!");
	}
	else
	{
		LOG("Shutdown successful - restarting...");
	}
	LOG("--- Stopped Log ---");
}

void cRoot::LoadGlobalSettings()
{
	// Nothing needed yet
}

void cRoot::LoadWorlds(cSettingsRepositoryInterface & a_Settings, bool a_IsNewIniFile)
{
	// First get the default world
	if (a_IsNewIniFile)
	{
		a_Settings.AddValue("Worlds", "World", "world_nether");
		a_Settings.AddValue("Worlds", "World", "world_end");
		m_pDefaultWorld = new cWorld("world");
		m_WorldsByName["world"] = m_pDefaultWorld;
		m_WorldsByName["world_nether"] = new cWorld("world_nether", dimNether, "world");
		m_WorldsByName["world_end"] = new cWorld("world_end", dimEnd, "world");
		return;
	}

	AString DefaultWorldName = a_Settings.GetValueSet("Worlds", "DefaultWorld", "world");
	m_pDefaultWorld = new cWorld(DefaultWorldName.c_str());
	m_WorldsByName[ DefaultWorldName ] = m_pDefaultWorld;
	auto Worlds = a_Settings.GetValues("Worlds");

	// Fix servers that have default world configs created prior to #2815. See #2810.
	// This can probably be removed several years after 2016
	// We start by inspecting the world linkage and determining if it's the default one
	if (DefaultWorldName == "world")
	{
		auto DefaultWorldIniFile= cpp14::make_unique<cIniFile>();
		if (DefaultWorldIniFile->ReadFile("world/world.ini"))
		{
			AString NetherName = DefaultWorldIniFile->GetValue("LinkedWorlds", "NetherWorldName", "");
			AString EndName = DefaultWorldIniFile->GetValue("LinkedWorlds", "EndWorldName", "");
			if ((NetherName.compare("world_nether") == 0) && (EndName.compare("world_end") == 0))
			{
				// This is a default world linkage config, see if the nether and end are in settings.ini
				// If both of them are not in settings.ini, then this is a pre-#2815 default config
				// so we add them to settings.ini
				// Note that if only one of them is not in settings.ini, it's nondefault and we don't touch it

				bool NetherInSettings = false;
				bool EndInSettings = false;

				for (auto WorldNameValue : Worlds)
				{
					AString ValueName = WorldNameValue.first;
					if (ValueName.compare("World") != 0)
					{
						continue;
					}
					AString WorldName = WorldNameValue.second;
					if (WorldName.compare("world_nether") == 0)
					{
						NetherInSettings = true;
					}
					else if (WorldName.compare("world_end") == 0)
					{
						EndInSettings = true;
					}
				}

				if ((!NetherInSettings) && (!EndInSettings))
				{
					a_Settings.AddValue("Worlds", "World", "world_nether");
					a_Settings.AddValue("Worlds", "World", "world_end");
					Worlds = a_Settings.GetValues("Worlds");  // Refresh the Worlds list so that the rest of the function works as usual
				}
			}
		}
	}

	// Then load the other worlds
	if (Worlds.size() <= 0)
	{
		return;
	}

	bool FoundAdditionalWorlds = false;
	for (auto WorldNameValue : Worlds)
	{
		AString ValueName = WorldNameValue.first;
		if (ValueName.compare("World") != 0)
		{
			continue;
		}
		AString WorldName = WorldNameValue.second;
		if (WorldName.empty())
		{
			continue;
		}
		FoundAdditionalWorlds = true;
		cWorld * NewWorld = new cWorld(WorldName.c_str());
		m_WorldsByName[WorldName] = NewWorld;
	}  // for i - Worlds

	if (!FoundAdditionalWorlds)
	{
		if (a_Settings.GetKeyComment("Worlds", 0) != " World=secondworld")
		{
			a_Settings.DeleteKeyComment("Worlds", 0);
			a_Settings.AddKeyComment("Worlds", " World=secondworld");
		}
	}
}

cWorld * cRoot::CreateAndInitializeWorld(const AString & a_WorldName, eDimension a_Dimension, const AString & a_OverworldName, bool a_InitSpawn)
{
	cWorld * World = m_WorldsByName[a_WorldName];
	if (World != nullptr)
	{
		return World;
	}

	cWorld * NewWorld = new cWorld(a_WorldName.c_str(), a_Dimension, a_OverworldName);
	m_WorldsByName[a_WorldName] = NewWorld;
	NewWorld->Start();
	if (a_InitSpawn)
	{
		NewWorld->InitializeSpawn();
	}
	m_PluginManager->CallHookWorldStarted(*NewWorld);
	return NewWorld;
}

void cRoot::StartWorlds(void)
{
	for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
	{
		itr->second->Start();
		itr->second->InitializeSpawn();
		m_PluginManager->CallHookWorldStarted(*itr->second);
	}
}

void cRoot::StopWorlds(void)
{
	for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
	{
		itr->second->Stop();
	}
}

void cRoot::UnloadWorlds(void)
{
	m_pDefaultWorld = nullptr;
	for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
	{
		delete itr->second;
	}
	m_WorldsByName.clear();
}

cWorld * cRoot::GetDefaultWorld()
{
	return m_pDefaultWorld;
}

cWorld * cRoot::GetWorld(const AString & a_WorldName, bool a_SearchForFolder)
{
	WorldMap::iterator itr = m_WorldsByName.find(a_WorldName);
	if (itr != m_WorldsByName.end())
	{
		return itr->second;
	}

	if (a_SearchForFolder && cFile::IsFolder(FILE_IO_PREFIX + a_WorldName))
	{
		return CreateAndInitializeWorld(a_WorldName);
	}
	return nullptr;
}

bool cRoot::ForEachWorld(cWorldListCallback & a_Callback)
{
	for (WorldMap::iterator itr = m_WorldsByName.begin(), itr2 = itr; itr != m_WorldsByName.end(); itr = itr2)
	{
		++itr2;
		if (itr->second != nullptr)
		{
			if (a_Callback.Item(itr->second))
			{
				return false;
			}
		}
	}
	return true;
}

void cRoot::TickCommands(void)
{
	// Execute any pending commands:
	cCommandQueue PendingCommands;
	{
		cCSLock Lock(m_CSPendingCommands);
		std::swap(PendingCommands, m_PendingCommands);
	}
	for (cCommandQueue::iterator itr = PendingCommands.begin(), end = PendingCommands.end(); itr != end; ++itr)
	{
		ExecuteConsoleCommand(itr->m_Command, *(itr->m_Output));
	}
}

void cRoot::QueueExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
	// Put the command into a queue (Alleviates FS #363):
	cCSLock Lock(m_CSPendingCommands);
	m_PendingCommands.emplace_back(a_Cmd, &a_Output);
}

void cRoot::QueueExecuteConsoleCommand(const AString & a_Cmd)
{
	// Put the command into a queue (Alleviates FS #363):
	cCSLock Lock(m_CSPendingCommands);
	m_PendingCommands.push_back(cCommand(a_Cmd, new cLogCommandDeleteSelfOutputCallback));
}

void cRoot::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
	// Some commands are built-in:
	if (a_Cmd == "stop")
	{
		m_TerminateEventRaised = true;
		m_StopEvent.Set();
		m_InputThreadRunFlag.clear();
		return;
	}
	else if (a_Cmd == "restart")
	{
		m_StopEvent.Set();
		m_InputThreadRunFlag.clear();
		return;
	}

	LOG("Executing console command: \"%s\"", a_Cmd.c_str());
	m_Server->ExecuteConsoleCommand(a_Cmd, a_Output);
}

void cRoot::KickUser(int a_ClientID, const AString & a_Reason)
{
	m_Server->KickUser(a_ClientID, a_Reason);
}

void cRoot::AuthenticateUser(int a_ClientID, const AString & a_Name, const AString & a_UUID, const Json::Value & a_Properties)
{
	m_Server->AuthenticateUser(a_ClientID, a_Name, a_UUID, a_Properties);
}

int cRoot::GetTotalChunkCount(void)
{
	int res = 0;
	for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
	{
		res += itr->second->GetNumChunks();
	}
	return res;
}

void cRoot::SaveAllChunks(void)
{
	for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr)
	{
		itr->second->QueueSaveAllChunks();
	}
}

void cRoot::SendPlayerLists(cPlayer * a_DestPlayer)
{
	for (const auto & itr : m_WorldsByName)
	{
		itr.second->SendPlayerList(a_DestPlayer);
	}  // for itr - m_WorldsByName[]
}

void cRoot::BroadcastPlayerListsAddPlayer(const cPlayer & a_Player, const cClientHandle * a_Exclude)
{
	for (const auto & itr : m_WorldsByName)
	{
		itr.second->BroadcastPlayerListAddPlayer(a_Player);
	}  // for itr - m_WorldsByName[]
}

void cRoot::BroadcastChat(const AString & a_Message, eMessageType a_ChatPrefix)
{
	for (WorldMap::iterator itr = m_WorldsByName.begin(), end = m_WorldsByName.end(); itr != end; ++itr)
	{
		itr->second->BroadcastChat(a_Message, nullptr, a_ChatPrefix);
	}  // for itr - m_WorldsByName[]
}

void cRoot::BroadcastChat(const cCompositeChat & a_Message)
{
	for (WorldMap::iterator itr = m_WorldsByName.begin(), end = m_WorldsByName.end(); itr != end; ++itr)
	{
		itr->second->BroadcastChat(a_Message);
	}  // for itr - m_WorldsByName[]
}

bool cRoot::ForEachPlayer(cPlayerListCallback & a_Callback)
{
	for (WorldMap::iterator itr = m_WorldsByName.begin(), itr2 = itr; itr != m_WorldsByName.end(); itr = itr2)
	{
		++itr2;
		if (!itr->second->ForEachPlayer(a_Callback))
		{
			return false;
		}
	}
	return true;
}

bool cRoot::FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallback & a_Callback)
{
	class cCallback : public cPlayerListCallback
	{
		size_t        m_BestRating;
		size_t        m_NameLength;
		const AString m_PlayerName;

		virtual bool Item (cPlayer * a_pPlayer)
		{
			size_t Rating = RateCompareString (m_PlayerName, a_pPlayer->GetName());
			if ((Rating > 0) && (Rating >= m_BestRating))
			{
				m_BestMatch = a_pPlayer->GetName();
				if (Rating > m_BestRating)
				{
					m_NumMatches = 0;
				}
				m_BestRating = Rating;
				++m_NumMatches;
			}
			if (Rating == m_NameLength)  // Perfect match
			{
				return true;
			}
			return false;
		}

	public:
		cCallback (const AString & a_CBPlayerName) :
			m_BestRating(0),
			m_NameLength(a_CBPlayerName.length()),
			m_PlayerName(a_CBPlayerName),
			m_BestMatch(),
			m_NumMatches(0)
		{}

		AString m_BestMatch;
		unsigned  m_NumMatches;
	} Callback (a_PlayerName);
	ForEachPlayer(Callback);

	if (Callback.m_NumMatches == 1)
	{
		return DoWithPlayer(Callback.m_BestMatch, a_Callback);
	}
	return false;
}

bool cRoot::DoWithPlayerByUUID(const AString & a_PlayerUUID, cPlayerListCallback & a_Callback)
{
	for (WorldMap::iterator itr = m_WorldsByName.begin(); itr !=  m_WorldsByName.end(); ++itr)
	{
		if (itr->second->DoWithPlayerByUUID(a_PlayerUUID, a_Callback))
		{
			return true;
		}
	}
	return false;
}

bool cRoot::DoWithPlayer(const AString & a_PlayerName, cPlayerListCallback & a_Callback)
{
	for (auto World : m_WorldsByName)
	{
		if (World.second->DoWithPlayer(a_PlayerName, a_Callback))
		{
			return true;
		}
	}
	return false;
}

AString cRoot::GetProtocolVersionTextFromInt(int a_ProtocolVersion)
{
	return cProtocolRecognizer::GetVersionTextFromInt(a_ProtocolVersion);
}

int cRoot::GetVirtualRAMUsage(void)
{
	#ifdef _WIN32
		PROCESS_MEMORY_COUNTERS_EX pmc;
		if (GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc)))
		{
			return (int)(pmc.PrivateUsage / 1024);
		}
		return -1;
	#elif defined(__linux__)
		// Code adapted from https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
		std::ifstream StatFile("/proc/self/status");
		if (!StatFile.good())
		{
			return -1;
		}
		while (StatFile.good())
		{
			AString Line;
			std::getline(StatFile, Line);
			if (strncmp(Line.c_str(), "VmSize:", 7) == 0)
			{
				int res = atoi(Line.c_str() + 8);
				return (res == 0) ? -1 : res;  // If parsing failed, return -1
			}
		}
		return -1;
	#elif defined (__APPLE__)
		// Code adapted from https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
		struct task_basic_info t_info;
		mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;

		if (KERN_SUCCESS == task_info(
			mach_task_self(),
			TASK_BASIC_INFO,
			reinterpret_cast<task_info_t>(&t_info),
			&t_info_count
		))
		{
			return static_cast<int>(t_info.virtual_size / 1024);
		}
		return -1;
	#else
		LOGINFO("%s: Unknown platform, cannot query memory usage", __FUNCTION__);
		return -1;
	#endif
}

int cRoot::GetPhysicalRAMUsage(void)
{
	#ifdef _WIN32
		PROCESS_MEMORY_COUNTERS pmc;
		if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
		{
			return (int)(pmc.WorkingSetSize / 1024);
		}
		return -1;
	#elif defined(__linux__)
		// Code adapted from https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
		std::ifstream StatFile("/proc/self/status");
		if (!StatFile.good())
		{
			return -1;
		}
		while (StatFile.good())
		{
			AString Line;
			std::getline(StatFile, Line);
			if (strncmp(Line.c_str(), "VmRSS:", 6) == 0)
			{
				int res = atoi(Line.c_str() + 7);
				return (res == 0) ? -1 : res;  // If parsing failed, return -1
			}
		}
		return -1;
	#elif defined (__APPLE__)
		// Code adapted from https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
		struct task_basic_info t_info;
		mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;

		if (KERN_SUCCESS == task_info(
			mach_task_self(),
			TASK_BASIC_INFO,
			reinterpret_cast<task_info_t>(&t_info),
			&t_info_count
		))
		{
			return static_cast<int>(t_info.resident_size / 1024);
		}
		return -1;
	#else
		LOGINFO("%s: Unknown platform, cannot query memory usage", __FUNCTION__);
		return -1;
	#endif
}

void cRoot::LogChunkStats(cCommandOutputCallback & a_Output)
{
	int SumNumValid = 0;
	int SumNumDirty = 0;
	int SumNumInLighting = 0;
	int SumNumInGenerator = 0;
	int SumMem = 0;
	for (WorldMap::iterator itr = m_WorldsByName.begin(), end = m_WorldsByName.end(); itr != end; ++itr)
	{
		cWorld * World = itr->second;
		int NumInGenerator = World->GetGeneratorQueueLength();
		int NumInSaveQueue = static_cast<int>(World->GetStorageSaveQueueLength());
		int NumInLoadQueue = static_cast<int>(World->GetStorageLoadQueueLength());
		int NumValid = 0;
		int NumDirty = 0;
		int NumInLighting = 0;
		World->GetChunkStats(NumValid, NumDirty, NumInLighting);
		a_Output.Out("World %s:", World->GetName().c_str());
		a_Output.Out("  Num loaded chunks: %d", NumValid);
		a_Output.Out("  Num dirty chunks: %d", NumDirty);
		a_Output.Out("  Num chunks in lighting queue: %d", NumInLighting);
		a_Output.Out("  Num chunks in generator queue: %d", NumInGenerator);
		a_Output.Out("  Num chunks in storage load queue: %d", NumInLoadQueue);
		a_Output.Out("  Num chunks in storage save queue: %d", NumInSaveQueue);
		int Mem = NumValid * static_cast<int>(sizeof(cChunk));
		a_Output.Out("  Memory used by chunks: %d KiB (%d MiB)", (Mem + 1023) / 1024, (Mem + 1024 * 1024 - 1) / (1024 * 1024));
		a_Output.Out("  Per-chunk memory size breakdown:");
		a_Output.Out("    block types:    " SIZE_T_FMT_PRECISION(6)  " bytes (" SIZE_T_FMT_PRECISION(3)  " KiB)", sizeof(cChunkDef::BlockTypes), (sizeof(cChunkDef::BlockTypes) + 1023) / 1024);
		a_Output.Out("    block metadata: " SIZE_T_FMT_PRECISION(6)  " bytes (" SIZE_T_FMT_PRECISION(3)  " KiB)", sizeof(cChunkDef::BlockNibbles), (sizeof(cChunkDef::BlockNibbles) + 1023) / 1024);
		a_Output.Out("    block lighting: " SIZE_T_FMT_PRECISION(6)  " bytes (" SIZE_T_FMT_PRECISION(3)  " KiB)", 2 * sizeof(cChunkDef::BlockNibbles), (2 * sizeof(cChunkDef::BlockNibbles) + 1023) / 1024);
		a_Output.Out("    heightmap:      " SIZE_T_FMT_PRECISION(6)  " bytes (" SIZE_T_FMT_PRECISION(3)  " KiB)", sizeof(cChunkDef::HeightMap), (sizeof(cChunkDef::HeightMap) + 1023) / 1024);
		a_Output.Out("    biomemap:       " SIZE_T_FMT_PRECISION(6)  " bytes (" SIZE_T_FMT_PRECISION(3)  " KiB)", sizeof(cChunkDef::BiomeMap), (sizeof(cChunkDef::BiomeMap) + 1023) / 1024);
		SumNumValid += NumValid;
		SumNumDirty += NumDirty;
		SumNumInLighting += NumInLighting;
		SumNumInGenerator += NumInGenerator;
		SumMem += Mem;
	}
	a_Output.Out("Totals:");
	a_Output.Out("  Num loaded chunks: %d", SumNumValid);
	a_Output.Out("  Num dirty chunks: %d", SumNumDirty);
	a_Output.Out("  Num chunks in lighting queue: %d", SumNumInLighting);
	a_Output.Out("  Num chunks in generator queue: %d", SumNumInGenerator);
	a_Output.Out("  Memory used by chunks: %d KiB (%d MiB)", (SumMem + 1023) / 1024, (SumMem + 1024 * 1024 - 1) / (1024 * 1024));
}

int cRoot::GetFurnaceFuelBurnTime(const cItem & a_Fuel)
{
	cFurnaceRecipe * FR = Get()->GetFurnaceRecipe();
	return FR->GetBurnTime(a_Fuel);
}


text:
require 'rails_helper'

describe EnrollmentCvProxy do

  before(:all) do

    @xml_path = File.join(Rails.root, 'spec', 'data', 'lib', 'enrollment.xml')
    @xml = File.open(@xml_path)
    @enrollment_cv_proxy = EnrollmentCvProxy.new(@xml)
  end

  it 'extracts the enrollee elements' do
    @enrollment_cv_proxy.enrollees.each do |enrollee|
      expect(enrollee.class).to eq(Enrollee)
    end
  end

  it 'assigns members to enrollees' do
    @enrollment_cv_proxy.enrollees.each do |enrollee|
      #expect(enrollee.member.class).to eq(Person)
    end
  end

  it 'extracts the policy elements' do
    #expect(@enrollment_cv_proxy.policy.class).to eq(Policy)
  end

end

redpajama_set_name: RedPajamaGithub


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

public enum HostInternetScsiHbaChapAuthenticationType {
  chapProhibited ("chapProhibited"),
  chapDiscouraged ("chapDiscouraged"),
  chapPreferred ("chapPreferred"),
  chapRequired ("chapRequired");

  @SuppressWarnings("unused")
  private final String val;
  private HostInternetScsiHbaChapAuthenticationType(String val)
  {
    this.val = val;
  }
}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: java.io.Reader
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_IO_READER_HPP_DECL
#define J2CPP_JAVA_IO_READER_HPP_DECL

namespace j2cpp { namespace java { namespace nio { class CharBuffer; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class Readable; } } }
namespace j2cpp { namespace java { namespace io { class Closeable; } } }

#include <java/io/Closeable.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/Readable.hpp>
#include <java/nio/CharBuffer.hpp>

namespace j2cpp {

namespace java { namespace io {

	class Reader;
	class Reader
		: public object<Reader>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_METHOD(4)
		J2CPP_DECLARE_METHOD(5)
		J2CPP_DECLARE_METHOD(6)
		J2CPP_DECLARE_METHOD(7)
		J2CPP_DECLARE_METHOD(8)
		J2CPP_DECLARE_METHOD(9)
		J2CPP_DECLARE_METHOD(10)
		J2CPP_DECLARE_METHOD(11)
		J2CPP_DECLARE_FIELD(0)

		explicit Reader(jobject jobj)
		: object<Reader>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;
		operator local_ref<java::lang::Readable>() const;
		operator local_ref<java::io::Closeable>() const;

		void close();
		void mark(jint);
		jboolean markSupported();
		jint read();
		jint read(local_ref< array<jchar,1> >  const&);
		jint read(local_ref< array<jchar,1> >  const&, jint, jint);
		jboolean ready();
		void reset();
		jlong skip(jlong);
		jint read(local_ref< java::nio::CharBuffer >  const&);

	}; //class Reader

} //namespace io
} //namespace java

} //namespace j2cpp

#endif //J2CPP_JAVA_IO_READER_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_IO_READER_HPP_IMPL
#define J2CPP_JAVA_IO_READER_HPP_IMPL

namespace j2cpp {

java::io::Reader::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

java::io::Reader::operator local_ref<java::lang::Readable>() const
{
	return local_ref<java::lang::Readable>(get_jobject());
}

java::io::Reader::operator local_ref<java::io::Closeable>() const
{
	return local_ref<java::io::Closeable>(get_jobject());
}

void java::io::Reader::close()
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(2),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(2),
		void
	>(get_jobject());
}

void java::io::Reader::mark(jint a0)
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(3),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(3),
		void
	>(get_jobject(), a0);
}

jboolean java::io::Reader::markSupported()
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(4),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(4),
		jboolean
	>(get_jobject());
}

jint java::io::Reader::read()
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(5),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(5),
		jint
	>(get_jobject());
}

jint java::io::Reader::read(local_ref< array<jchar,1> > const &a0)
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(6),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(6),
		jint
	>(get_jobject(), a0);
}

jint java::io::Reader::read(local_ref< array<jchar,1> > const &a0, jint a1, jint a2)
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(7),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(7),
		jint
	>(get_jobject(), a0, a1, a2);
}

jboolean java::io::Reader::ready()
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(8),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(8),
		jboolean
	>(get_jobject());
}

void java::io::Reader::reset()
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(9),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(9),
		void
	>(get_jobject());
}

jlong java::io::Reader::skip(jlong a0)
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(10),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(10),
		jlong
	>(get_jobject(), a0);
}

jint java::io::Reader::read(local_ref< java::nio::CharBuffer > const &a0)
{
	return call_method<
		java::io::Reader::J2CPP_CLASS_NAME,
		java::io::Reader::J2CPP_METHOD_NAME(11),
		java::io::Reader::J2CPP_METHOD_SIGNATURE(11),
		jint
	>(get_jobject(), a0);
}

J2CPP_DEFINE_CLASS(java::io::Reader,"java/io/Reader")
J2CPP_DEFINE_METHOD(java::io::Reader,0,"<init>","()V")
J2CPP_DEFINE_METHOD(java::io::Reader,1,"<init>","(Ljava/lang/Object;)V")
J2CPP_DEFINE_METHOD(java::io::Reader,2,"close","()V")
J2CPP_DEFINE_METHOD(java::io::Reader,3,"mark","(I)V")
J2CPP_DEFINE_METHOD(java::io::Reader,4,"markSupported","()Z")
J2CPP_DEFINE_METHOD(java::io::Reader,5,"read","()I")
J2CPP_DEFINE_METHOD(java::io::Reader,6,"read","([C)I")
J2CPP_DEFINE_METHOD(java::io::Reader,7,"read","([CII)I")
J2CPP_DEFINE_METHOD(java::io::Reader,8,"ready","()Z")
J2CPP_DEFINE_METHOD(java::io::Reader,9,"reset","()V")
J2CPP_DEFINE_METHOD(java::io::Reader,10,"skip","(J)J")
J2CPP_DEFINE_METHOD(java::io::Reader,11,"read","(Ljava/nio/CharBuffer;)I")
J2CPP_DEFINE_FIELD(java::io::Reader,0,"lock","Ljava/lang/Object;")

} //namespace j2cpp

#endif //J2CPP_JAVA_IO_READER_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
namespace chromeos {

class DeviceOAuth2TokenService;

// Identity provider implementation backed by DeviceOAuth2TokenService.
class DeviceIdentityProvider : public IdentityProvider {
 public:
  explicit DeviceIdentityProvider(
      chromeos::DeviceOAuth2TokenService* token_service);
  ~DeviceIdentityProvider() override;

  // IdentityProvider:
  std::string GetActiveUsername() override;
  std::string GetActiveAccountId() override;
  OAuth2TokenService* GetTokenService() override;
  bool RequestLogin() override;

 private:
  chromeos::DeviceOAuth2TokenService* token_service_;

  DISALLOW_COPY_AND_ASSIGN(DeviceIdentityProvider);
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_IDENTITY_PROVIDER_H_


text:
package framework

import (
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/pkg/api/v1"
	"k8s.io/client-go/pkg/apis/extensions/v1beta1"
	"k8s.io/client-go/pkg/util/yaml"
)

func MakeDeployment(pathToYaml string) (*v1beta1.Deployment, error) {
	manifest, err := PathToOSFile(pathToYaml)
	if err != nil {
		return nil, err
	}
	tectonicPromOp := v1beta1.Deployment{}
	if err := yaml.NewYAMLOrJSONDecoder(manifest, 100).Decode(&tectonicPromOp); err != nil {
		return nil, err
	}

	return &tectonicPromOp, nil
}

func CreateDeployment(kubeClient kubernetes.Interface, namespace string, d *v1beta1.Deployment) error {
	_, err := kubeClient.Extensions().Deployments(namespace).Create(d)
	if err != nil {
		return err
	}
	return nil
}

func DeleteDeployment(kubeClient kubernetes.Interface, namespace, name string) error {
	d, err := kubeClient.Extensions().Deployments(namespace).Get(name)
	if err != nil {
		return err
	}

	zero := int32(0)
	d.Spec.Replicas = &zero

	d, err = kubeClient.Extensions().Deployments(namespace).Update(d)
	if err != nil {
		return err
	}
	return kubeClient.Extensions().Deployments(namespace).Delete(d.Name, &v1.DeleteOptions{})
}


text:
"""
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
  This file is part of the Smart Developer Hub Project:
    http://www.smartdeveloperhub.org

  Center for Open Middleware
        http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
  Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
"""

from agora.fountain.index import core
from agora.fountain.index import paths

__author__ = 'Fernando Serena'


text:
<?php

namespace Store\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class StoreAdminBundle extends Bundle
{
}


text:
var fs = require('fs');
var voicejs = require('../voice.js');

var client = new voicejs.Client({
	email: process.argv[2] || 'email@gmail.com',
	password: process.argv[3] || 'password',
	tokens: require('./tokens.json')
});

// Display all greetings
client.greetings('get', function(error, response, data){
    if(error){
        return console.log(error);
    }

    console.log('\Greetings:');
    data.settings.greetings.forEach(function(greeting){
        console.log(greeting.id + ': ' + greeting.name);
    });

	// Download the audio for the default system greeting
    client.greetings('getAudio', {id: 0}, function(error, response, data){
        if(error){
            return console.log('Error downloading audio: ', error);
        }

        fs.writeFileSync('defaultGreeting.mp3', data);
        console.log('defaultGreeting.mp3 downloaded');
	});

	// Create new greeting, call to record the greeting, cancel the call, and delete the greeting
	client.greetings('new',{name: 'voice.js greeting', default: false}, function(error, response, data){
		if(error){
			console.log('Error creating greeting:', error);
		}

		var greetingId = data.greeting.id;
		console.log('Created new greeting with id:', greetingId);

		// Record the greeting
		client.greetings('record',{
			id: greetingId,
			number: client.config.email // Call Google Talk to record the greeting. Note: This must be one of your forwarding phones.
		}, function(error, response, data){

			if(error){
				return console.log('Error initiating greeting record:', error);
			}

			console.log('Calling Google Talk forwarding phone', client.config.email, 'to record greeting');

			//cancel the call after 10 seconds and delete the greeting
			setTimeout(function(){

				console.log('Canceling the recording call...');
				client.greetings('cancelRecord', function(error, response, data){

					console.log(error ? error : 'Canceled recording');

					// Delete the greeting
					console.log('Deleting the greeting');
					client.greetings('delete', {id:greetingId}, function(error, response, data){
						console.log(error ? error : 'Deleted greeting with id', greetingId);
					});
				})
			}, 10000)
		});
	});
});


text:
require 'spec_helper'

describe Flatware::StepResult do
  context 'with an exception' do
    let(:status) { :failed }
    let(:exception) { Exception.new }
    subject { described_class.new(status, exception) }

    it 'can be serialized' do
      expect { Marshal.load(Marshal.dump(subject)) }.to_not raise_error
    end
  end
end


text:
package edu.cmu.minorthird.classify.ranking;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.swing.JComponent;

import edu.cmu.minorthird.classify.BinaryClassifier;
import edu.cmu.minorthird.classify.ClassLabel;
import edu.cmu.minorthird.classify.Example;
import edu.cmu.minorthird.classify.MutableInstance;
import edu.cmu.minorthird.util.BasicCommandLineProcessor;
import edu.cmu.minorthird.util.Saveable;
import edu.cmu.minorthird.util.StringUtil;
import edu.cmu.minorthird.util.gui.ComponentViewer;
import edu.cmu.minorthird.util.gui.LineCharter;
import edu.cmu.minorthird.util.gui.ParallelViewer;
import edu.cmu.minorthird.util.gui.VanillaViewer;
import edu.cmu.minorthird.util.gui.Viewer;
import edu.cmu.minorthird.util.gui.ViewerFrame;
import edu.cmu.minorthird.util.gui.Visible;

/** Evaluate a classifier as a ranker
 */

public class RankingEvaluation implements Visible, Saveable
{
	private final static int GRAPHS_PER_PAGE = 10;
	private final static int NUM_TOP_TO_SHOW = 50;
	private TreeMap<String,List<Example>> rankedListMap = new TreeMap<String,List<Example>>();
	private TreeMap<String,Set<String>> unrankedMap = new TreeMap<String,Set<String>>();
	private TreeMap<String,List<Double>> scoreMap = new TreeMap<String,List<Double>>();
	private TreeMap<String,Integer> numPosExamples = new TreeMap<String,Integer>();
	private boolean guiFlag = false;
	private String loadedFile = null;

	public void extend(String rankingId, List<Example> ranking, BinaryClassifier classifier)
	{
		extend(rankingId,ranking,classifier,Collections.EMPTY_SET);
	}

	public void extend(String rankingId, List<Example> ranking, BinaryClassifier classifier, Set<String> unrankedPos)
	{
		BatchRankingLearner.sortByScore( classifier, ranking );

		rankedListMap.put( rankingId, ranking );
		List<Double> scores = new ArrayList<Double>(ranking.size());
		int k=0;
		for (Iterator<Example> i=ranking.iterator(); i.hasNext(); ) {
			Example ex = i.next();
			if (ex.getLabel().isPositive()) increment(numPosExamples,rankingId,1);
			scores.set(k++,classifier.score(ex));
		}
		scoreMap.put(rankingId,scores);
		unrankedMap.put(rankingId,unrankedPos);
		increment(numPosExamples,rankingId,unrankedPos.size());
	}

	private void increment(TreeMap<String,Integer> map,String key,int delta)
	{
		Integer i = map.get(key);
		if (i==null) map.put(key,new Integer(delta));
		else map.put(key,new Integer(i.intValue()+delta));
	}

	//
	// accessors
	//

	private List<Example> getRanking(String rankingId) { return rankedListMap.get(rankingId); }
	private double getScore(String rankingId,int rank) { return scoreMap.get(rankingId).get(rank-1); }
	private Iterator<String> getRankingIterator() { return rankedListMap.keySet().iterator(); }
	private int numPosExamples(String rankingId) {return (numPosExamples.get(rankingId)).intValue();}
	private boolean isPositive(String rankingId,Example ex) { return ex.getLabel().isPositive(); }
	private int numRankings() { return rankedListMap.keySet().size(); }
	private Set<Example> getUnrankedPositives(String rankingId) { return Collections.EMPTY_SET; }

	//
	// split the examples into groups of K
	//
	private String[][] exampleGroups(int groupSize)
	{
		int remainder = numRankings() % groupSize;
		int numRemainderGroups = remainder>0 ? 1 : 0;
		String[][] group = new String[(numRankings()/groupSize) + numRemainderGroups][];
		for (int i=0; i<group.length-numRemainderGroups; i++) {
			group[i] = new String[groupSize];
		}
		if (numRemainderGroups>0) {
			group[group.length-1] = new String[ remainder ];
		}
		int j=0, k=0;
		for (Iterator<String> i=getRankingIterator(); i.hasNext(); ) {
			String name = i.next();
			group[j][k++] = name;
			if (k>=group[j].length) {
				j++;
				k=0;
			}
		}
		return group;
	}

	//
	// useful subroutine - returns an array a such that a[0] is recall
	// at each rank, and a[1] is precision at each rank.
	//
	private double[][] recallAndPrecisionForEachK(String rankingId)
	{
		List<Example> ranking = getRanking(rankingId);
		int totalPos = numPosExamples(rankingId);
		double[] recall = new double[ranking.size()+1];
		double[] precision = new double[ranking.size()+1];
		int rank=0;
		double numPosAboveRank=0;
		for (Iterator<Example> j=ranking.iterator(); j.hasNext(); ) {
			Example ex = j.next();
			rank++;
			if (isPositive(rankingId,ex))  numPosAboveRank++;
			if (totalPos>0) {
				recall[rank] = numPosAboveRank/totalPos;
				precision[rank] = numPosAboveRank/rank;
			} else {
				recall[rank] = precision[rank] = 1.0;
			}
		}
		double[][] result = new double[2][];
		result[0] = recall;
		result[1] = precision;
		return result;
	}

	//
	// public functions
	//

	/** Non-interpolated average precision.
	 */
	public double averagePrecision(String rankingId)
	{
		if (numPosExamples(rankingId)==0) return 1.0;
		double rank = 0, numPosAboveRank = 0, totPrec = 0;
		List<Example> ranking = getRanking(rankingId);
		for (Iterator<Example> i=ranking.iterator(); i.hasNext(); ) {
			Example ex = i.next();
			rank++;
			if (isPositive(rankingId,ex)) {
				numPosAboveRank++;
				totPrec += numPosAboveRank/rank;
			}
		}
		return totPrec/numPosExamples(rankingId);
	}

	/** Max value of F1 over all possible thresholds.
	 */
	public double maxF1(String rankingId)
	{
		if (numPosExamples(rankingId)==0) return 1.0;
		double rank=0, numPosAboveRank=0, maxF1=0;
		List<Example> ranking = getRanking(rankingId);
		for (Iterator<Example> i=ranking.iterator(); i.hasNext(); ) {
			Example id = i.next();
			rank++;
			if (isPositive(rankingId,id)) {
				numPosAboveRank++;
			}
			double precision = numPosAboveRank/rank;
			double recall = numPosAboveRank/numPosExamples(rankingId);
			if (precision+recall>0) {
				double f1 = 2*precision*recall/(precision+recall);
				maxF1 = Math.max( maxF1, f1 );
			}
		}
		return maxF1;
	}

	public double maxRecall(String rankingId)
	{
		if (numPosExamples(rankingId)==0) return 1.0;
		double numRanked = 0;
		List<Example> ranking = getRanking(rankingId);
		for (Iterator<Example> i=ranking.iterator(); i.hasNext(); ) {
			Example ex = i.next();
			if (ex.getLabel().isPositive()) numRanked++;
		}
		return numRanked/numPosExamples(rankingId);
	}

	/** Interpolated precision at eleven recall levels, averaged over all examples. */
	public double[] averageElevenPointPrecision()
	{
		double[] averagePrecision = new double[11];
		for (Iterator<String> i=getRankingIterator(); i.hasNext(); ) {
			String name = i.next();
			double[] precision = elevenPointPrecision(name);
			for (int j=0; j<=10; j++) {
				averagePrecision[j] += precision[j];
			}
		}
		for (int j=0; j<=10; j++) {
			averagePrecision[j] /= numRankings();
		}
		return averagePrecision;
	}

	/** Interpolated precision at eleven recall levels: 0.0, ... ,1.0 */
	public double[] elevenPointPrecision(String rankingId)
	{
		double[][] a = recallAndPrecisionForEachK(rankingId);
		double[] recall = a[0];
		double[] precision = a[1];
		double[] interpolatedPrecision = new double[11];
		for (int k=1; k<recall.length; k++) {
			double r = recall[k];
			double p = precision[k];
			for (int j=0; j<=10; j++) {
				if (r >= j/10.0) {
					interpolatedPrecision[j] = Math.max( interpolatedPrecision[j], p );
				}
			}
		}
		return interpolatedPrecision;
	}

	/** A summary table. Columns are: avgpr, the
	 * non-interpolated average precision of the ranking (the average
	 * of this is thus mean average precision); maxF1, the maximum F1
	 * value for the ranking; maxRec, the maximum recall achieved
	 * (i.e., the fraction of relevant nodes appearing in the
	 * ranking); and #pos, the number of positive/relevant nodes.
	 */
	public String toTable()
	{
		if (rankedListMap.keySet().size()==0) {
			return "no examples?\n";
		}
		StringBuffer buf = new StringBuffer();
		DecimalFormat fmt = new DecimalFormat("0.000");
		DecimalFormat fmt2 = new DecimalFormat("0.0");
		buf.append("avgPr\tmaxF1\tmaxRec\t#pos\n");
		double totMaxF1=0, totAvgPrec=0, totPos=0, totMaxRec=0;
		for (Iterator<String> i=getRankingIterator(); i.hasNext(); ) {
			String name = i.next();
			double ap = averagePrecision(name);
			double maxf = maxF1(name);
			double maxr = maxRecall(name);
			int np = numPosExamples(name);
			buf.append(fmt.format(ap) + "\t");
			buf.append(fmt.format(maxf) + "\t");
			buf.append(fmt.format(maxr) + "\t");
			buf.append(np + "\t");
			buf.append(name + "\n");
			totAvgPrec += ap;
			totMaxF1 += maxf;
			totMaxRec += maxr;
			totPos += np;
		}
		buf.append("\n");
		buf.append(fmt.format(totAvgPrec/numRankings())+"\t");
		buf.append(fmt.format(totMaxF1/numRankings())+"\t");
		buf.append(fmt.format(totMaxRec/numRankings())+"\t");
		buf.append(fmt2.format(totPos/numRankings())+"\t");
		buf.append("average" + "\n");
		return buf.toString();
	}

	private double[] averageRecallAtEachK()
	{
		int longestRankedList = 0;
		for (Iterator<String> i=getRankingIterator(); i.hasNext(); ) {
			String name = i.next();
			longestRankedList = Math.max( getRanking(name).size(), longestRankedList );
		}
		// first have recall[k] be total recall over all examples at rank k
		double[] recall = new double[longestRankedList+1];
		for (Iterator<String> i=getRankingIterator(); i.hasNext(); ) {
			String name = i.next();
			List<Example> ranking = getRanking(name);
			int rank=0;
			double numPosAboveRank=0;
			for (Iterator<Example> j=ranking.iterator(); j.hasNext(); ) {
				Example id = j.next();
				rank++;
				if (isPositive(name,id))  numPosAboveRank++;
				if (numPosExamples(name)>0) {
					recall[rank] += numPosAboveRank/numPosExamples(name);
				} else {
					recall[rank] = 1.0;
				}
			}
			// extend the last recorded recall level to the end of this list
			for (int k=rank+1; k<recall.length; k++) {
				recall[k] = recall[rank];
			}
		}
		// now scale recall to average recall at K
		for (int k=1; k<recall.length; k++) {
			recall[k] /= numRankings();
		}
		recall[0] = -1; // convenient
		return recall;
	}

	/** Recall as function of K, averaged over all examples. */
	public String averageRecallAsFunctionOfK()
	{
		DecimalFormat fmt = new DecimalFormat("0.000");
		StringBuffer buf = new StringBuffer("");
		buf.append("K\tAvgRecall\n");
		double[] recall = averageRecallAtEachK();
		for (int k=1; k<recall.length; k++) {
			if (recall[k]!=recall[k-1]) {
				buf.append(k+"\t"+fmt.format(recall[k])+"\n");
			}
		}
		return buf.toString();
	}

	public String toTable(String name,int numToShowAllEntries)
	{
		List<Example> ranking = getRanking(name);
		StringBuffer buf = new StringBuffer();
		DecimalFormat fmt = new DecimalFormat("0.000");
		int rank = 0;
		for (Iterator<Example> i=ranking.iterator(); i.hasNext(); ) {
			Example id = i.next();
			++rank;
			double score = getScore(name,rank);
			String tag = isPositive(name,id) ? "+" : "-";
			// print the entry if it's positive, or if it's near the top
			if (rank<numToShowAllEntries || tag.startsWith("+")) {
				buf.append(rank+"\t"+fmt.format(score)+"\t"+tag+"\t"+id+"\n");
			}
		}
		// now print the false negatives - ie the unranked positives
		for (Iterator<Example> i=getUnrankedPositives(name).iterator(); i.hasNext(); ) {
			Example id = i.next();
			String tag = "+";
			buf.append(">"+rank+"\t0\t"+tag+"\t"+id+"\n");
		}
		return buf.toString();

	}

	@Override
	public Viewer toGUI()
	{
		ParallelViewer v = new ParallelViewer();
		v.addSubView( "Summary Table", new ComponentViewer() {
			static final long serialVersionUID=20080206L;
			@Override
			public JComponent componentFor(Object o) {
				RankingEvaluation gsEval = (RankingEvaluation)o;
				return new VanillaViewer( gsEval.toTable() );
			}
		});
		ParallelViewer v2 = new ParallelViewer();
		v.addSubView( "11-Pt Precision", v2 );
		v2.addSubView( "Averaged", new ComponentViewer() {
			static final long serialVersionUID=20080206L;
			@Override
			public JComponent componentFor(Object o) {
				RankingEvaluation gsEval = (RankingEvaluation)o;
				double[] avgPrec = gsEval.averageElevenPointPrecision();
				LineCharter lc = new LineCharter();
				lc.startCurve("11-Pt Avg Prec");
				for (int j=0; j<=10; j++) {
					lc.addPoint( j/10.0, avgPrec[j] );
				}
				return lc.getPanel("11-Pt Average Interpolated Precision", "Recall", "Precision");
			}
		});
		String[][] groups = exampleGroups(GRAPHS_PER_PAGE);
		for (int i=0; i<groups.length; i++) {
			final String tag = groups.length==1 ? "Details" : ("Details: Group "+(i+1));
			final String[] group = groups[i];
			v2.addSubView( tag, new ComponentViewer() {
				static final long serialVersionUID=20080206L;
				@Override
				public JComponent componentFor(Object o) {
					RankingEvaluation gsEval = (RankingEvaluation)o;
					LineCharter lc = new LineCharter();
					for (int i=0; i<group.length; i++) {
						String name = group[i];
						double[] avgPrec = gsEval.elevenPointPrecision(name);
						lc.startCurve(name);
						for (int j=0; j<=10; j++) {
							lc.addPoint( j/10.0, avgPrec[j] );
						}
					}
					return lc.getPanel("11-Pt Interpolated Precision", "Recall", "Precision");
				}
			});

		}
		v.addSubView( "AvgRecall vs Rank", new ComponentViewer() {
			static final long serialVersionUID=20080206L;
			@Override
			public JComponent componentFor(Object o) {
				//RankingEvaluation gsEval = (RankingEvaluation)o;
				double[] avgRec = averageRecallAtEachK();
				LineCharter lc = new LineCharter();
				lc.startCurve("Recall vs Rank");
				for (int i=1; i<avgRec.length; i++) {
					lc.addPoint( i, avgRec[i] );
				}
				return lc.getPanel("AvgRecall vs Rank", "Rank", "AvgRecall");
			}
		});
		ParallelViewer v3 = new ParallelViewer();
		v3.putTabsOnLeft();
		v.addSubView( "Details", v3 );
		for (Iterator<String> i=getRankingIterator(); i.hasNext(); ) {
			final String name = i.next();
			v3.addSubView( name, new ComponentViewer() {
				static final long serialVersionUID=20080206L;
				@Override
				public JComponent componentFor(Object o) {
					return new VanillaViewer( toTable(name,NUM_TOP_TO_SHOW) );
				}
			});
		}
		v.setContent(this);
		return v;
	}

	//
	// implement Saveable
	//
	final static private String EVAL_FORMAT_NAME = "Graph Searcher Evaluation";
	final static private String EVAL_EXT = ".gsev";
	@Override
	public String[] getFormatNames() { return new String[]{EVAL_FORMAT_NAME}; }
	@Override
	public String getExtensionFor(String format) { return EVAL_EXT; }
	@Override
	public void saveAs(File file,String formatName) throws IOException { save(file);	}
	@Override
	public Object restore(File file) throws IOException	{ return load(file); }

//	final static private StringEncoder encoder = new StringEncoder('%',"/\\:;$ \t\n");
//	final static private String evalExt = Evaluation.EVAL_EXT;

	private void save(File file) throws IOException
	{
		PrintStream out = new PrintStream(new FileOutputStream(file));
		for (Iterator<String> i=getRankingIterator(); i.hasNext(); ) {
			String name = i.next();
			List<Example> ranking = getRanking(name);
			int rank = 0;
			for (Iterator<Example> j=ranking.iterator(); j.hasNext(); ) {
				Example id = j.next();
				rank++;
				double weight = getScore(name,rank);
				out.println(name +"\t"+ id.getSource() +"\t"+ rank +"\t" + weight);
			}
			for (Iterator<Example> j=ranking.iterator(); j.hasNext(); ) {
				Example id = j.next();
				if (isPositive(name,id)) {
					out.println(name +"\t" + id.getSource());
				}
			}
			Set<Example> pos = getUnrankedPositives(name);
			for (Iterator<Example> j=pos.iterator(); j.hasNext(); ) {
				Example id = j.next();
				out.println(name +"\t" + id.getSource());
			}
		}
		out.close();
	}

	static public RankingEvaluation load(File file) throws IOException
	{
		RankingEvaluation eval = new RankingEvaluation();
		eval.loadFromFile(file);
		return eval;
	}

	private void loadFromFile(File file) throws IOException
	{
		TreeMap<String,List<String>> tempListMap=new TreeMap<String,List<String>>();
		LineNumberReader in = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
		String line = null;
		while ((line = in.readLine())!=null) {
			String[] parts = line.split("\t");
			if (parts.length==2) {
				// rankingId positiveExample
				Set<String> pos = unrankedMap.get(parts[0]);
				if (pos==null) unrankedMap.put(parts[0], (pos = new TreeSet<String>()));
				pos.add( parts[1] );
				increment(numPosExamples,parts[0],1);
			} else if (parts.length==4) {
				// rankingId graphId rank weight
				List<String> ranking = tempListMap.get(parts[0]);
				if (ranking==null) tempListMap.put(parts[0], (ranking = new ArrayList<String>()));
				List<Double> scores = scoreMap.get(parts[0]);
				if (scores==null) scoreMap.put( parts[0], (scores = new ArrayList<Double>()));
				scores.add( new Double(StringUtil.atof(parts[3])) );
				ranking.add( parts[1] );
			} else {
				throw new IllegalArgumentException(file+" line "+in.getLineNumber()+": illegal format");
			}
		}
		for (Iterator<String> i=getRankingIterator(); i.hasNext(); ) {
			String rankingId = i.next();
			//System.out.println("unbuffering: "+rankingId);
			Set<String> pos = unrankedMap.get( rankingId );
			if (pos==null) pos = Collections.EMPTY_SET;
			List<Double> scores = scoreMap.get( rankingId );
			List<String> tempRanking = tempListMap.get( rankingId );
			List<Example> ranking = new ArrayList<Example>(tempRanking.size());
			double[] newScores = new double[scores.size()];
			for (int j=0; j<tempRanking.size(); j++) {
				String exId = tempRanking.get(j);
				if (pos.contains(exId)) {
					ranking.set(j, new Example( new MutableInstance(exId), ClassLabel.binaryLabel(+1) ));
					pos.remove( exId );
				} else {
					ranking.set(j, new Example( new MutableInstance(exId), ClassLabel.binaryLabel(-1) ));
				}
				newScores[j] = (scores.get(j)).doubleValue();
			}

			List<Double> newScoresList = new ArrayList<Double>(scores.size());
			for(int j=0;j<newScores.length;j++){
				newScoresList.add(j,newScores[j]);
			}

			scoreMap.put( rankingId, newScoresList );
		}
	}

	//
	// test
	//

	public class MyCLP extends BasicCommandLineProcessor {
		//public void graph(String s) { graph=new TextGraph(s,'r'); }
		public void gui() { guiFlag = true; }
		public void loadFrom(String s) {
			loadedFile=s;
			try { loadFromFile(new File(s)); } catch (IOException ex) { ex.printStackTrace(); }
		}
	}
	public void processArguments(String[] args) { new MyCLP().processArguments(args); }

	static public void main(String[] args) throws IOException
	{
		RankingEvaluation eval = new RankingEvaluation();
		eval.processArguments(args);
		if (eval.guiFlag) new ViewerFrame(eval.loadedFile, eval.toGUI());
		else System.out.println(eval.toTable());
	}
}


text:
package com.unisinos.m2.mateusmanica.internacionalizacaodeapps;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
    protected Spinner mLangList;
    private static boolean is_translated;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
                this,
                R.layout.support_simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.langList));

        mLangList = (Spinner)findViewById(R.id.langSpin);
        mLangList.setAdapter(adapter);
        mLangList.setOnItemSelectedListener(this);

        String language = getCurrentLanguage();

        int langPosition = adapter.getPosition(language);
        mLangList.setSelection(langPosition);
        mLangList.setOnItemSelectedListener(this);

        if (is_translated == false) {
            translateApp(language);
            is_translated = true;
        }
    }

    @NonNull
    private String getCurrentLanguage() {
        SharedPreferences sharedPref = getPreferences(MODE_PRIVATE);
        String defaultLang = getResources().getString(R.string.DEFAULT_LANGUAGE);
        return sharedPref.getString(getString(R.string.SAVED_LANGUAGE), defaultLang);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String newLang = parent.getSelectedItem().toString();
        if (newLang.equals(getCurrentLanguage())){
            return;
        }
        setLanguage(newLang);
        translateApp(newLang);
    }

    private void translateApp(String newLang) {

        Locale locale        = null;
        String[] langList    = getResources().getStringArray(R.array.langList);
        Configuration config = getBaseContext().getResources().getConfiguration();

        if (newLang.equals(langList[1])){
            locale = new Locale("en");
        }else if(newLang.equals(langList[2])){
            locale = new Locale("es");
        }else{
            locale = new Locale("pt");
        }

        Locale.setDefault(locale);
        Configuration conf = new Configuration(config);
        conf.locale = locale;
        getBaseContext().getResources().updateConfiguration(
                conf,
                getBaseContext().getResources().getDisplayMetrics());

        Intent intent = getIntent();
        finish();
        startActivity(intent);

    }

    private void setLanguage(String newLang) {
        SharedPreferences.Editor spEditor = getPreferences(Context.MODE_PRIVATE).edit();
        spEditor.putString(getString(R.string.SAVED_LANGUAGE), newLang);
        spEditor.commit();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}


text:
module ActionController
  module Rescue
    def use_rails_error_handling!
      @use_rails_error_handling = true
    end

    def use_rails_error_handling?
      @use_rails_error_handling ||= false
    end

    protected
    def rescue_action_with_fast_errors(exception)
      if use_rails_error_handling?
        rescue_action_without_fast_errors exception
      else
        raise exception
      end
    end
    alias_method_chain :rescue_action, :fast_errors
  end
end


text:
<template name="RescueCenter">

        {{#if Template.subscriptionsReady}}
            {{#each getAnimals}}
                {{> Animal}}
            {{/each}}
        {{else}}

Loading...

        {{/if}}

</template>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Kryptogamenflora Forsch. Bayer. Bot. Ges. Erforsch Leim. Flora 2: (1931)

#### Original name
Pleurodiscus gregarius Petr., 1931

### Remarks
null


text:
class X{
private:
    std::exception_ptr excptr_;
    boost::context::execution_context caller_;
    boost::context::execution_context callee_;

public:
    X():
        excptr_(),
        caller_(boost::context::execution_context::current()),
        callee_(
             [=]( void * vp){
                try {
                    int i = * static_cast< int * >( vp);
                    std::string str = boost::lexical_cast<std::string>(i);
                    caller_( & str);
                } catch (...) {
                    excptr_=std::current_exception();
                }
             })
    {}

    std::string operator()(int i){
        void * ret = callee_( & i);
        if(excptr_){
            std::rethrow_exception(excptr_);
        }
        return * static_cast< std::string * >( ret);
    }
};

int main() {
    X x;
    std::cout<<x(7)<<std::endl;
    std::cout << "done" << std::endl;
}


text:
#include "vice.h"

#include "datasette.h"
#include "plus4mem.h"

void datasette_trigger_flux_change(unsigned int on)
{
    mem_proc_port_trigger_flux_change(on);
}

void datasette_set_tape_sense(int sense)
{
    pio1_set_tape_sense(sense);
}


text:
require 'spec_helper'

describe Pixel do

  describe '.new(r, g, b)' do
    before(:all) do
      @red    = 100
      @green  = 200
      @blue   = 150

      @p = Pixel.new(@red, @green, @blue)

    end

    it 'instantiates' do
      expect(@p).to be_instance_of Pixel
    end

    it 'remembers its member variables' do
      expect(@p.red).to   eq @red
      expect(@p.green).to eq @green
      expect(@p.blue).to  eq @blue
    end
  end

  context 'pixel distance and addition' do

    before(:all) do
      @pixel_1 = Pixel.new(1, 2, 3)
      @pixel_2 = Pixel.new(-4, -8, -12)
    end

    describe '.distance_to(pixel)' do
      it 'can calculate distance from another pixel instance' do
        expect(@pixel_1.distance_to(@pixel_2)).to eql 18.708286933869708
        expect(@pixel_2.distance_to(@pixel_1)).to eql 18.708286933869708
      end
    end

    describe '.+(pixel)' do
      it 'implements the addition operator' do
        pixel_temp = @pixel_1 + @pixel_2

        expect(pixel_temp.red).to   eql -3
        expect(pixel_temp.green).to eql -6
        expect(pixel_temp.blue).to  eql -9
      end
    end

    describe './(n)' do
      it 'implements the division operator' do
        pixel_temp = @pixel_1 / 2

        expect(pixel_temp.red).to   eql 0
        expect(pixel_temp.green).to eql 1
        expect(pixel_temp.blue).to  eql 1

        pixel_temp = @pixel_2 / 3

        expect(pixel_temp.red).to   eql -2
        expect(pixel_temp.green).to eql -3
        expect(pixel_temp.blue).to  eql -4
      end
    end

  end

end


text:
namespace util {

extern const char kProgressBanner[];

class ErsatzProgress {
  public:
    // No output.
    ErsatzProgress();

    // Null means no output.  The null value is useful for passing along the ostream pointer from another caller.
    explicit ErsatzProgress(uint64_t complete, std::ostream *to = &std::cerr, const std::string &message = "");

    ~ErsatzProgress();

    ErsatzProgress &operator++() {
      if (++current_ >= next_) Milestone();
      return *this;
    }

    ErsatzProgress &operator+=(uint64_t amount) {
      if ((current_ += amount) >= next_) Milestone();
      return *this;
    }

    void Set(uint64_t to) {
      if ((current_ = to) >= next_) Milestone();
    }

    void Finished() {
      Set(complete_);
    }

  private:
    void Milestone();

    uint64_t current_, next_, complete_;
    unsigned char stones_written_;
    std::ostream *out_;

    // noncopyable
    ErsatzProgress(const ErsatzProgress &other);
    ErsatzProgress &operator=(const ErsatzProgress &other);
};

} // namespace util

#endif // UTIL_ERSATZ_PROGRESS__


text:
Results for App: {{bproxyService.bproxy.appName}}

<button class="btn btn-primary continueButton" (click)="getResults()">Refresh</button>

<button class="btn btn-warning startNewSessionButton" (click)="newSession()">Start new Session
Session: {{bproxyService.bproxy.session}} running.</button>

					{{reportRecord.value}}

					{{reportRecord.value}}

Requests

					Method

					Request

					Status

					{{requestResponse.httpMethod}}

					{{requestResponse.requestURL}}

					{{requestResponse.responseStatusCode}}

<template ngbModalContainer></template>


text:
require 'spec_helper'
require 'pdk/tests/unit'

describe PDK::Test::Unit do
  it 'has an invoke method' do
    expect(described_class.methods(false)).to include(:invoke)
  end

  describe '.rake_bin' do
    subject { described_class.rake_bin }

    before(:each) do
      allow(PDK::Util).to receive(:module_root).and_return('/path/to/module')
    end

    it { is_expected.to eq(File.join('/path/to/module', 'bin', 'rake')) }
  end

  describe '.parallel_with_no_tests?' do
    subject { described_class.parallel_with_no_tests?(ran_in_parallel, json_result, cmd_result) }

    let(:json_result) { [] }
    let(:cmd_result) { { stderr: '', stdout: '', exit_code: 1 } }

    context 'when not run in parallel' do
      let(:ran_in_parallel) { false }

      it { is_expected.to be_falsey }
    end

    context 'when run in parallel' do
      let(:ran_in_parallel) { true }

      context 'and no tests (puppetlabs_spec_helper <= 2.5.0)' do
        let(:cmd_result) do
          { stderr: 'Pass files or folders to run', stdout: '', exit_code: 1 }
        end

        it { is_expected.to be_truthy }
      end

      context 'and no tests (puppetlabs_spec_helper >= 2.5.1)' do
        let(:cmd_result) do
          { stderr: 'No files for parallel_spec to run against', stdout: '', exit_code: 0 }
        end

        it { is_expected.to be_truthy }
      end

      context 'and there are tests' do
        let(:json_result) { ['something'] }

        it { is_expected.to be_falsey }
      end
    end
  end

  describe '.setup' do
    before(:each) do
      mock_result = { stdout: 'some output', stderr: 'some error', exit_code: exit_code }
      allow(described_class).to receive(:rake).with('spec_prep', any_args).and_return(mock_result)
    end

    context 'when the rake task succeeds' do
      let(:exit_code) { 0 }

      it 'does not raise an error' do
        expect {
          described_class.setup
        }.not_to raise_error
      end
    end

    context 'when the rake task fails' do
      let(:exit_code) { 1 }

      it 'prints the output of the command to STDERR and raises a FatalError' do
        expect($stderr).to receive(:puts).with('').twice
        expect($stderr).to receive(:puts).with('some output')
        expect($stderr).to receive(:puts).with('some error')
        expect(logger).to receive(:error).with(a_string_matching(%r{spec_prep rake task failed}))
        expect(described_class).to receive(:tear_down)

        expect {
          described_class.setup
        }.to raise_error(PDK::CLI::FatalError, %r{failed to prepare to run the unit tests}i)
      end
    end
  end

  describe '.tear_down' do
    before(:each) do
      mock_result = { stdout: 'some output', stderr: 'some error', exit_code: exit_code }
      allow(described_class).to receive(:rake).with('spec_clean', any_args).and_return(mock_result)
    end

    context 'when the rake task succeeds' do
      let(:exit_code) { 0 }

      it 'does not raise an error' do
        expect {
          described_class.tear_down
        }.not_to raise_error
      end
    end

    context 'when the rake task fails' do
      let(:exit_code) { 1 }

      it 'prints the output of the command to STDERR and raises a FatalError' do
        expect($stderr).to receive(:puts).with('').twice
        expect($stderr).to receive(:puts).with('some output')
        expect($stderr).to receive(:puts).with('some error')
        expect(logger).to receive(:error).with(a_string_matching(%r{spec_clean rake task failed}))

        expect {
          described_class.tear_down
        }.to raise_error(PDK::CLI::FatalError, %r{failed to clean up after running unit tests}i)
      end
    end
  end

  describe '.merge_json_results' do
    let(:results) do
      [{ 'messages' => ['message 1', 'message 2'],
         'examples' => %w[example example example],
         'summary' => {
           'example_count' => 40,
           'failure_count' => 7,
           'pending_count' => 12,
           'duration' => 30,
         } },
       {
         'messages' => ['message 2', 'message 3'],
         'examples' => %w[example example example],
         'summary' => {
           'example_count' => 30,
           'failure_count' => 4,
           'pending_count' => 6,
           'duration' => 40,
         },
       }]
    end

    it 'successfully combines information' do
      json_result = described_class.merge_json_results(results)

      expect(json_result['messages'].count).to eq(3)
      expect(json_result['examples'].count).to eq(6)
      expect(json_result['summary']['example_count']).to eq(70)
      expect(json_result['summary']['failure_count']).to eq(11)
      expect(json_result['summary']['pending_count']).to eq(18)
    end
  end

  describe '.cmd' do
    before(:each) do
      allow(PDK::Util).to receive(:module_root).and_return('/path/to/module')
    end

    context 'when run with parallel option' do
      it 'uses the parallel_spec rake task' do
        cmd = described_class.cmd(nil, parallel: true)

        expect(cmd).to eq('parallel_spec_standalone')
      end
    end

    context 'when run without the parallel option' do
      it 'uses the spec rake task' do
        cmd = described_class.cmd(nil)

        expect(cmd).to eq('spec_standalone')
      end
    end

    context 'when run with tests option' do
      it 'passes file paths to rake' do
        cmd = described_class.cmd('/path/to/test1,/path/to/test2')

        expect(cmd).to eq('spec_standalone[/path/to/test1,/path/to/test2]')
      end
    end
  end

  describe '.parse_output' do
    let(:report) { PDK::Report.new }
    let(:duration) { 4.123 }

    before(:each) do
      allow(report).to receive(:add_event).with(%r{message \d})
    end

    context 'with messages' do
      let(:json) { { 'messages' => ['message 1', 'message 2'] } }

      it 'prints the messages to stderr' do
        expect($stderr).to receive(:puts).twice
        described_class.parse_output(report, json, duration)
      end
    end

    context 'with summary' do
      let(:json) do
        { 'summary' => {
          'example_count' => 30,
          'duration'      => 32,
          'failure_count' => 2,
          'pending_count' => 6,
        } }
      end

      after(:each) do
        described_class.parse_output(report, json, duration)
      end

      it 'prints the wall time of the rspec run instead of the rspec evaluation duration' do
        expect($stderr).to receive(:puts).once.with(%r{#{Regexp.escape(duration.to_s)} seconds})
        expect($stderr).not_to receive(:puts).with(%r{#{Regexp.escape(json['duration'].to_s)} seconds})
      end

      it 'prints the summary to stderr' do
        expect($stderr).to receive(:puts).once.with(%r{Evaluated 30 tests in 4\.123 seconds})
      end
    end
  end

  # Allow any_instance stubbing of Commands
  # rubocop:disable RSpec/AnyInstance
  describe '.list' do
    before(:each) do
      allow(PDK::Util::Bundler).to receive(:ensure_bundle!)
      allow(PDK::Util::Bundler).to receive(:ensure_binstubs!)
      allow(PDK::Util).to receive(:module_root).and_return('/path/to/module')
      allow_any_instance_of(PDK::CLI::Exec::Command).to receive(:execute!).and_return(stdout: rspec_json_output)
    end

    context 'with examples' do
      let(:rspec_json_output) do
        '{
          "examples": [
            { "file_path": "./path/to/test",
              "id": "./path/to/test[1:1:1]",
              "full_description": "a bunch of useful descriptive words",
              "description": "descriptive words" }
          ]
        }'
      end

      it 'returns the id and full_description from the rspec output' do
        expected_result = [
          {
            file_path: './path/to/test',
            id: './path/to/test[1:1:1]',
            full_description: 'a bunch of useful descriptive words',
          },
        ]

        expect(described_class.list).to eq(expected_result)
      end
    end

    context 'without examples' do
      let(:rspec_json_output) do
        '{
          "messages": [
            "No examples found."
          ],
          "examples": []
        }'
      end

      it 'returns an empty array' do
        expect(described_class.list).to eq([])
      end
    end
  end

  describe '.invoke' do
    let(:report) { PDK::Report.new }
    let(:rspec_json_output) { '{}' }

    before(:each) do
      allow(PDK::Util::Bundler).to receive(:ensure_bundle!)
      allow(PDK::Util::Bundler).to receive(:ensure_binstubs!)
      allow(PDK::Util).to receive(:module_root).and_return('/path/to/module')
      allow(described_class).to receive(:setup)
      allow(described_class).to receive(:tear_down)
      allow_any_instance_of(PDK::CLI::Exec::Command).to receive(:execute!).and_return(stdout: rspec_json_output, exit_code: -1)
      allow(described_class).to receive(:parse_output)
    end

    context 'when running interactively' do
      subject(:exit_code) do
        described_class.invoke(report, options)
      end

      before(:each) do
        allow(PDK::CLI::Exec::InteractiveCommand).to receive(:new)
          .and_return(command)
        allow(command).to receive(:execute!).and_return(exit_code: 0)
      end

      let(:options) { { interactive: true } }

      let(:command) do
        instance_double(
          PDK::CLI::Exec::InteractiveCommand,
          :context=     => true,
          :environment= => true,
        )
      end

      it 'runs the rake task interactively' do
        expect(exit_code).to eq(0)
      end

      context 'when --verbose is not passed' do
        it 'uses the progress formatter' do
          expect(command).to receive(:environment=).with(include('CI_SPEC_OPTIONS' => '--format progress'))

          exit_code
        end
      end

      context 'when --verbose is passed' do
        let(:options) { super().merge(verbose: true) }

        it 'uses the documentation formatter' do
          expect(command).to receive(:environment=).with(include('CI_SPEC_OPTIONS' => '--format documentation'))
          exit_code
        end
      end
    end

    context 'in parallel without examples' do
      let(:rspec_json_output) do
        'Pass files or folders to run'
      end

      it "returns 0 and doesn't error" do
        expect(described_class).to receive(:parallel_with_no_tests?).and_return(true)

        exit_code = -1
        expect { exit_code = described_class.invoke(report, tests: 'a_test_spec.rb') }.not_to raise_exception
        expect(exit_code).to eq(0)
      end
    end

    context 'configurable fixture cleaning' do
      after(:each) do
        described_class.invoke(report, options)
      end

      let(:rspec_json_output) do
        '{
          "examples":
          [
            {
              "id": "./spec/fixtures/modules/testmod/spec/classes/testmod_spec.rb[1:3:1]",
              "status": "passed",
              "pending_message": null
            }
          ],
          "summary": {
            "duration": 0.295112,
            "example_count": 1,
            "failure_count": 0,
            "pending_count": 0
          }
        }'
      end

      context 'when enabled' do
        let(:options) do
          {
            :'clean-fixtures' => true,
            :tests            => 'testmod_spec.rb',
          }
        end

        it 'calls tear_down' do
          expect(described_class).to receive(:tear_down)
        end
      end

      context 'when disabled' do
        let(:options) do
          {
            tests: 'testmod_spec.rb',
          }
        end

        it 'does not call tear_down' do
          expect(described_class).not_to receive(:tear_down)
        end
      end
    end

    context 'in parallel without examples' do
      let(:rspec_json_output) do
        '{
          "examples":
          [
            {
              "id": "./spec/fixtures/modules/testmod/spec/classes/testmod_spec.rb[1:3:1]",
              "status": "passed",
              "pending_message": null
            }
          ],
          "summary": {
            "duration": 0.295112,
            "example_count": 1,
            "failure_count": 0,
            "pending_count": 0
          }
        }
        {
          "examples":
          [
            {
              "id": "./spec/fixtures/modules/testmod/spec/classes/testmod_spec.rb[1:3:1]",
              "status": "passed",
              "pending_message": null
            }
          ],
          "summary": {
            "duration": 0.295112,
            "example_count": 1,
            "failure_count": 0,
            "pending_count": 0
          }
        }'
      end

      it 'returns 0' do
        expect(PDK::Util).not_to receive(:find_first_json_in)

        expect(described_class.invoke(report, parallel: true, tests: 'a_test_spec.rb')).to eq(-1)
      end
    end

    context 'with examples' do
      let(:rspec_json_output) do
        '{
          "examples":
          [
            {
              "id": "./spec/fixtures/modules/testmod/spec/classes/testmod_spec.rb[1:3:1]",
              "status": "passed",
              "pending_message": null
            }
          ],
          "summary": {
            "duration": 0.295112,
            "example_count": 1,
            "failure_count": 0,
            "pending_count": 0
          }
        }'
      end

      it 'executes and parses output' do
        expect(described_class).to receive(:parse_output).once
        exit_code = described_class.invoke(report, tests: 'a_test_spec.rb')
        expect(exit_code).to eq(-1)
      end

      context 'with Windows paths' do
        it 'uses forward slashes to invoke rake' do
          expect(described_class).to receive(:parse_output).once
          expect(described_class).to receive(:rake).with(%r{path/a_test_spec.rb}, anything, anything).and_call_original
          exit_code = described_class.invoke(report, tests: 'path\\a_test_spec.rb')
          expect(exit_code).to eq(-1)
        end
      end
    end
  end
  # rubocop:enable RSpec/AnyInstance
end


text:
// Abstract base class for Connection classes
Ext.sql.Connection = function(config){
	Ext.apply(this, config);
	Ext.sql.Connection.superclass.constructor.call(this);

	this.addEvents({
		open : true,
		close: true
	});
};

Ext.extend(Ext.sql.Connection, Ext.util.Observable, {
	maxResults: 10000,
	openState : false,

    // abstract methods
    open : function(file){
	},

	close : function(){
	},

    exec : function(sql){
	},

	execBy : function(sql, args){
	},

	query : function(sql){
	},

	queryBy : function(sql, args){
	},

    // protected/inherited method
    isOpen : function(){
		return this.openState;
	},

	getTable : function(name, keyName){
		return new Ext.sql.Table(this, name, keyName);
	},

	createTable : function(o){
		var tableName = o.name;
		var keyName = o.key;
		var fs = o.fields;
		if(!Ext.isArray(fs)){ // Ext fields collection
			fs = fs.items;
		}
		var buf = [];
		for(var i = 0, len = fs.length; i < len; i++){
			var f = fs[i], s = f.name;
			switch(f.type){
	            case "int":
	            case "bool":
	            case "boolean":
	                s += ' INTEGER';
	                break;
	            case "float":
	                s += ' REAL';
	                break;
	            default:
	            	s += ' TEXT';
	        }
	        if(f.allowNull === false || f.name == keyName){
	        	s += ' NOT NULL';
	        }
	        if(f.name == keyName){
	        	s += ' PRIMARY KEY';
	        }
	        if(f.unique === true){
	        	s += ' UNIQUE';
	        }

	        buf[buf.length] = s;
	    }
	    var sql = ['CREATE TABLE IF NOT EXISTS ', tableName, ' (', buf.join(','), ')'].join('');
        this.exec(sql);
	}
});

Ext.sql.Connection.getInstance = function(db, config){
    if(Ext.isAir){ // air
        return new Ext.sql.AirConnection(config);
    } else { // gears
        return new Ext.sql.GearsConnection(config);
    }
};


text: This collection regroups a bunch of useful plugins for Tulip coded in Python


text:
{% import 'macros/page_macros.html' as page %}
{% extends 'layouts/base.html' %}

{% block content %}

        	Know Your Rights
        	{% if current_user.is_admin() %}

This is what the user will see on the Know Your Rights page

        	{% endif %}

        {{ page.render_inline_editor(editable_html_obj, current_user) }}

{% endblock %}


text:
@implementation DHCCounter

+(void)bumpCountForEventName:(NSString *)eventName{
    [self increaseCountForEventName:eventName byInteger:1];
}
+(void)increaseCountForEventName:(NSString *)eventName byInteger:(NSInteger)integer{
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    NSString *eventKey=[NSString stringWithFormat:@"DHCEvents-%@",eventName];
    NSInteger prevCount=[defaults integerForKey:eventKey];
    [defaults setInteger:prevCount+integer forKey:eventKey];
    [defaults synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:[NSString stringWithFormat:@"DHCEventCountChangeForEventName%@",eventName] object:self userInfo:@{@"count": [NSNumber numberWithInt:prevCount+integer]}];

}

+(NSInteger)countForEventName:(NSString *)eventName{
    NSString *eventKey=[NSString stringWithFormat:@"DHCEvents-%@",eventName];
    NSInteger count=[[NSUserDefaults standardUserDefaults] integerForKey:eventKey];
    return count;
}

+(void)setCount:(NSInteger)count ForEventName:(NSString *)eventName{
    NSString *eventKey=[NSString stringWithFormat:@"DHCEvents-%@",eventName];
    [[NSUserDefaults standardUserDefaults] setInteger:count forKey:eventKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end


text:
name: cljs.reader/read-past
see also:
---

## Summary

## Details

## Examples


text:
using System;
using System.Collections;
using System.Collections.Generic;
using JSIL.Meta;
using JSIL.Proxy;

namespace JSIL.Proxies {
    [JSProxy(
        new[] {
            "System.Collections.ArrayList",
            "System.Collections.Hashtable",
            "System.Collections.Generic.List`1",
            "System.Collections.Generic.Dictionary`2",
            "System.Collections.Generic.Stack`1",
            "System.Collections.Generic.Queue`1",
            "System.Collections.Generic.HashSet`1",
            "System.Collections.Hashtable/KeyCollection",
            "System.Collections.Hashtable/ValueCollection",
            "System.Collections.Generic.Dictionary`2/KeyCollection",
            "System.Collections.Generic.Dictionary`2/ValueCollection"
        },
        memberPolicy: JSProxyMemberPolicy.ReplaceNone,
        inheritable: false
    )]
    public abstract class CollectionProxy<T> : IEnumerable {
        [JSIsPure]
        [JSResultIsNew]
        System.Collections.IEnumerator IEnumerable.GetEnumerator () {
            throw new InvalidOperationException();
        }

        [JSIsPure]
        [JSResultIsNew]
        public AnyType GetEnumerator () {
            throw new InvalidOperationException();
        }

        [JSMutatedArguments()]
        public AnyType this[AnyType index] {
            [JSEscapingArguments()]
            get {
                throw new InvalidOperationException();
            }
            [JSEscapingArguments("value")]
            set {
                throw new InvalidOperationException();
            }
        }
    }

    [JSProxy(
        new[] {
            "System.Collections.ArrayList",
            "System.Collections.Generic.List`1",
            "System.Collections.Generic.Stack`1",
            "System.Collections.Generic.Queue`1"
        },
        memberPolicy: JSProxyMemberPolicy.ReplaceNone,
        inheritable: true
    )]
    public abstract class CollectionProxy2<T> : IEnumerable {
        [JSUnderlyingArray("_items", "_size")]
        System.Collections.IEnumerator IEnumerable.GetEnumerator () {
            throw new InvalidOperationException();
        }

        [JSUnderlyingArray("_items", "_size")]
        public AnyType GetEnumerator () {
            throw new InvalidOperationException();
        }

        [JSMutatedArguments()]
        public AnyType this[AnyType index] {
            [JSEscapingArguments()]
            get {
                throw new InvalidOperationException();
            }
            [JSEscapingArguments("value")]
            set {
                throw new InvalidOperationException();
            }
        }
    }

    [JSProxy(
        new[] {
            "System.Collections.ArrayList/ArrayListEnumerator",
            "System.Collections.Hashtable/HashtableEnumerator",
            "System.Collections.Generic.List`1/Enumerator",
            "System.Collections.Generic.Stack`1/Enumerator",
            "System.Collections.Generic.Queue`1/Enumerator",
            "System.Collections.Generic.HashSet`1/Enumerator",
            "System.Collections.Generic.Dictionary`2/Enumerator",
            "System.Collections.Generic.Dictionary`2/KeyCollection/Enumerator",
            "System.Collections.Generic.Dictionary`2/ValueCollection/Enumerator"
        },
        memberPolicy: JSProxyMemberPolicy.ReplaceNone,
        inheritable: false
    )]
    [JSPureDispose]
    public abstract class CollectionEnumeratorProxy {
    }

    [JSProxy(
        new[] {
            "System.Collections.ArrayList/ArrayListEnumerator",
            "System.Collections.Generic.List`1/Enumerator",
            "System.Collections.Generic.Stack`1/Enumerator",
            "System.Collections.Generic.Queue`1/Enumerator",
        },
        memberPolicy: JSProxyMemberPolicy.ReplaceNone,
        inheritable: false
    )]
    [JSIsArrayEnumerator("_array", "_index", "_length")]
    public abstract class ArrayEnumeratorProxy {
    }
}


text:
module Models

  class Sold

    attr_reader :value

    def initialize(value)
      @value = value
    end

    def to_s
      "Sold #{value}"
    end

    def ==(another_sold)
      self.value == another_sold.value
    end

  end

end


text:
``IncrementalPCA``
============================================================================

.. autoclass:: ibex.sklearn.decomposition.IncrementalPCA
    :members:
    :special-members:
    :show-inheritance:


text:
package semtex.archery;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import semtex.archery.data.DatabaseHelper;
import semtex.archery.data.ReportGenerator;
import semtex.archery.data.entities.UserVisit;
import semtex.archery.data.entities.Visit;
import semtex.archery.data.reports.ParcourReportData;
import semtex.archery.util.ArcheryBackupManager;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.*;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;

public class Scoreboard extends OrmLiteBaseActivity<DatabaseHelper> {

  public static final int COLOR_1 = 0xFF696969;

  public static final int COLOR_2 = 0xFF808080;

  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scoreboard);
    final Intent intent = getIntent();
    if (intent == null) {
      return;
    } // if

    final ParcelUuid visitUuid = intent.getParcelableExtra("visit_id");

    if (visitUuid == null) {
      return;
    } // if

    final Visit v = getHelper().getVisitDao().queryForId(visitUuid.getUuid());

    final ReportGenerator generator = new ReportGenerator(getHelper());
    final ParcourReportData reportData = generator.generateReportForVisit(v);

    final TextView name = (TextView)findViewById(R.id.lblParcourName);
    final TextView date = (TextView)findViewById(R.id.lblParcourRevisionDate);

    name.setText(reportData.getParcourName());
    date.setText(reportData.getParcourRevisionDate().toLocaleString());

    final TableLayout tl = (TableLayout)findViewById(R.id.tblScoring);

    final TableRow tr = new TableRow(this);

    TextView tv = new TextView(this);
    tv.setText("");
    tv.setTypeface(null, Typeface.BOLD);
    tv.setBackgroundColor(COLOR_1);

    tr.addView(tv, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.2f));

    for (final UserVisit uv : v.getUserVisit()) {
      tv = new TextView(this);
      tv.setText(uv.getUser().getUserName());
      tv.setTypeface(null, Typeface.BOLD);
      tv.setBackgroundColor(COLOR_1);
      tr.addView(tv, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.2f));
    }

    tl.addView(tr);
    final Map<Integer, Map<String, Integer>> scoringData = reportData.getScoringData();

    ArrayList<Double> values = new ArrayList<Double>();
    for (final UserVisit uv : v.getUserVisit()) {
      values.add(reportData.getAvgPoints().get(uv.getUser().getUserName()));
    }
    addLineToTable(tl, "average", values, true);

    values = new ArrayList<Double>();
    for (final UserVisit uv : v.getUserVisit()) {
      values.add(reportData.getTotalPoints().get(uv.getUser().getUserName()) * 1.0);
    }
    addLineToTable(tl, "total", values, true);

    for (final Map.Entry<Integer, Map<String, Integer>> entry : scoringData.entrySet()) {
      values = new ArrayList<Double>();
      for (final UserVisit uv : v.getUserVisit()) {
        // Sanitation checking - has the user really scores or might we run into a nullpointer along the way?
        if (entry.getValue() != null) {
          final Integer score = entry.getValue().get(uv.getUser().getUserName());
          if (score != null) {
            values.add(entry.getValue().get(uv.getUser().getUserName()) * 1.0);
          } else {
            values.add(null);// if
          } // if - score not null
        } // if
      } // for - each userVisit
      addLineToTable(tl, entry.getKey().toString(), values, entry.getKey() % 2 == 0);
    } // for - all entries

    final Button btnVisitClose = (Button)findViewById(R.id.btnVisitClose);

    // don't show button if visit is closed
    if (v.getEndTime() != null) {
      btnVisitClose.setVisibility(View.GONE);
    }

    btnVisitClose.setOnClickListener(new View.OnClickListener() {

      public void onClick(final View view) {
        v.setEndTime(new Date());
        getHelper().getVisitDao().update(v);

        Toast.makeText(view.getContext(), "Visit successfully ended!", Toast.LENGTH_SHORT).show();

        // triggering new backup on google services
        final ArcheryBackupManager bm = new ArcheryBackupManager(Scoreboard.this);
        bm.dataChanged();

        final Intent intent = new Intent(getApplicationContext(), Sharing.class);
        intent.putExtra("visit_id", new ParcelUuid(v.getId()));
        startActivity(intent);

        setResult(RESULT_OK);
        finish();
      } // onClick
    });
  } // onCreate

  private void addLineToTable(final TableLayout tl, final String key, final ArrayList<Double> values,
      final boolean isOdd) {
    final TableRow tr = new TableRow(this);
    final int col = isOdd ? COLOR_2 : COLOR_1;
    TextView tv = new TextView(this);
    tv.setText(key);
    tv.setTypeface(null, Typeface.BOLD);
    tv.setBackgroundColor(col);
    tr.addView(tv, new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.2f));

    for (final Double value : values) {
      tv = new TextView(this);
      tv.setText(value != null ? MessageFormat.format("{0,number,#.##}", value) : "-");
      tv.setBackgroundColor(col);
      tr.addView(tv, new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0.2f));
    }
    tl.addView(tr);
  }
}


text:
require 'minitest/spec'
require_relative 'spec_helper'

class InstallVstoSpec < MiniTest::Chef::Spec

  describe_recipe 'visualstudio::install_vsto' do
    describe 'packages' do

      it 'installs VSTO' do
        node['visualstudio']['vsto']['package_name'].must_be_installed
      end

    end
  end

end


text:
package io.opentelemetry.exporter.otlp.http.metrics;

import static io.opentelemetry.api.internal.Utils.checkArgument;
import static java.util.Objects.requireNonNull;

import io.opentelemetry.exporter.internal.okhttp.OkHttpExporterBuilder;
import io.opentelemetry.exporter.internal.otlp.OtlpUserAgent;
import io.opentelemetry.exporter.internal.otlp.metrics.MetricsRequestMarshaler;
import io.opentelemetry.sdk.metrics.InstrumentType;
import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector;
import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector;
import io.opentelemetry.sdk.metrics.export.MetricExporter;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * Builder utility for {@link OtlpHttpMetricExporter}.
 *
 * @since 1.14.0
 */
public final class OtlpHttpMetricExporterBuilder {

  private static final String DEFAULT_ENDPOINT = "http://localhost:4318/v1/metrics";

  private static final AggregationTemporalitySelector DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR =
      AggregationTemporalitySelector.alwaysCumulative();

  private final OkHttpExporterBuilder<MetricsRequestMarshaler> delegate;
  private AggregationTemporalitySelector aggregationTemporalitySelector =
      DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;

  private DefaultAggregationSelector defaultAggregationSelector =
      DefaultAggregationSelector.getDefault();

  OtlpHttpMetricExporterBuilder() {
    delegate = new OkHttpExporterBuilder<>("otlp", "metric", DEFAULT_ENDPOINT);
    OtlpUserAgent.addUserAgentHeader(delegate::addHeader);
  }

  /**
   * Sets the maximum time to wait for the collector to process an exported batch of metrics. If
   * unset, defaults to {@value OkHttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s.
   */
  public OtlpHttpMetricExporterBuilder setTimeout(long timeout, TimeUnit unit) {
    requireNonNull(unit, "unit");
    checkArgument(timeout >= 0, "timeout must be non-negative");
    delegate.setTimeout(timeout, unit);
    return this;
  }

  /**
   * Sets the maximum time to wait for the collector to process an exported batch of metrics. If
   * unset, defaults to {@value OkHttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s.
   */
  public OtlpHttpMetricExporterBuilder setTimeout(Duration timeout) {
    requireNonNull(timeout, "timeout");
    return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS);
  }

  /**
   * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT}. The
   * endpoint must start with either http:// or https://, and include the full HTTP path.
   */
  public OtlpHttpMetricExporterBuilder setEndpoint(String endpoint) {
    requireNonNull(endpoint, "endpoint");
    delegate.setEndpoint(endpoint);
    return this;
  }

  /**
   * Sets the method used to compress payloads. If unset, compression is disabled. Currently
   * supported compression methods include "gzip" and "none".
   */
  public OtlpHttpMetricExporterBuilder setCompression(String compressionMethod) {
    requireNonNull(compressionMethod, "compressionMethod");
    checkArgument(
        compressionMethod.equals("gzip") || compressionMethod.equals("none"),
        "Unsupported compression method. Supported compression methods include: gzip, none.");
    delegate.setCompression(compressionMethod);
    return this;
  }

  /** Add header to requests. */
  public OtlpHttpMetricExporterBuilder addHeader(String key, String value) {
    delegate.addHeader(key, value);
    return this;
  }

  /**
   * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]}
   * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will
   * use the system default trusted certificates.
   */
  public OtlpHttpMetricExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) {
    delegate.setTrustedCertificates(trustedCertificatesPem);
    return this;
  }

  /**
   * Sets ths client key and the certificate chain to use for verifying client when TLS is enabled.
   * The key must be PKCS8, and both must be in PEM format.
   */
  public OtlpHttpMetricExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) {
    delegate.setClientTls(privateKeyPem, certificatePem);
    return this;
  }

  /**
   * Set the {@link AggregationTemporalitySelector} used for {@link
   * MetricExporter#getAggregationTemporality(InstrumentType)}.
   *
   *
If unset, defaults to {@link AggregationTemporalitySelector#alwaysCumulative()}.
   *
   *
{@link AggregationTemporalitySelector#deltaPreferred()} is a common configuration for delta
   * backends.
   */
  public OtlpHttpMetricExporterBuilder setAggregationTemporalitySelector(
      AggregationTemporalitySelector aggregationTemporalitySelector) {
    requireNonNull(aggregationTemporalitySelector, "aggregationTemporalitySelector");
    this.aggregationTemporalitySelector = aggregationTemporalitySelector;
    return this;
  }

  /**
   * Set the {@link DefaultAggregationSelector} used for {@link
   * MetricExporter#getDefaultAggregation(InstrumentType)}.
   *
   *
If unset, defaults to {@link DefaultAggregationSelector#getDefault()}.
   *
   * @since 1.16.0
   */
  public OtlpHttpMetricExporterBuilder setDefaultAggregationSelector(
      DefaultAggregationSelector defaultAggregationSelector) {
    requireNonNull(defaultAggregationSelector, "defaultAggregationSelector");
    this.defaultAggregationSelector = defaultAggregationSelector;
    return this;
  }

  OtlpHttpMetricExporterBuilder exportAsJson() {
    delegate.exportAsJson();
    return this;
  }

  /**
   * Constructs a new instance of the exporter based on the builder's values.
   *
   * @return a new exporter's instance
   */
  public OtlpHttpMetricExporter build() {
    return new OtlpHttpMetricExporter(
        delegate.build(), aggregationTemporalitySelector, defaultAggregationSelector);
  }
}


text:
<?php

namespace BB\GalleryBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * BbOrderDetail
 *
 * @ORM\Table(name="bb_order_detail", indexes={@ORM\Index(name="FK_detail_order_idx", columns={"order_id"}), @ORM\Index(name="FK_detail_beer_idx", columns={"beer_id"})})
 * @ORM\Entity
 */
class BbOrderDetail
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="amount", type="integer", nullable=true)
     */
    private $amount;

    /**
     * @var \BB\GalleryBundle\Entity\BbBeer
     *
     * @ORM\ManyToOne(targetEntity="BB\GalleryBundle\Entity\BbBeer")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="beer_id", referencedColumnName="id")
     * })
     */
    private $beer;

    /**
     * @var \BB\GalleryBundle\Entity\BbOrder
     *
     * @ORM\ManyToOne(targetEntity="BB\GalleryBundle\Entity\BbOrder")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="order_id", referencedColumnName="id")
     * })
     */
    private $order;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set amount
     *
     * @param integer $amount
     * @return BbOrderDetail
     */
    public function setAmount($amount)
    {
        $this->amount = $amount;

        return $this;
    }

    /**
     * Get amount
     *
     * @return integer
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * Set beer
     *
     * @param \BB\GalleryBundle\Entity\BbBeer $beer
     * @return BbOrderDetail
     */
    public function setBeer(\BB\GalleryBundle\Entity\BbBeer $beer = null)
    {
        $this->beer = $beer;

        return $this;
    }

    /**
     * Get beer
     *
     * @return \BB\GalleryBundle\Entity\BbBeer
     */
    public function getBeer()
    {
        return $this->beer;
    }

    /**
     * Set order
     *
     * @param \BB\GalleryBundle\Entity\BbOrder $order
     * @return BbOrderDetail
     */
    public function setOrder(\BB\GalleryBundle\Entity\BbOrder $order = null)
    {
        $this->order = $order;

        return $this;
    }

    /**
     * Get order
     *
     * @return \BB\GalleryBundle\Entity\BbOrder
     */
    public function getOrder()
    {
        return $this->order;
    }
}