text:
using namespace yojimbo;

namespace MAD
{
	DECLARE_LOG_CATEGORY(LogNetworkServer);

	UNetworkServer::UNetworkServer(UNetworkManager& inNetworkManager, eastl::unique_ptr<UNetworkTransport> inServerTransport, double inCurrentGameTime, const yojimbo::ClientServerConfig& inConfig)
		: Server(GetDefaultAllocator(), *inServerTransport, inConfig, inCurrentGameTime)
		, m_networkManager(inNetworkManager)
		, m_serverTransport(eastl::move(inServerTransport))
		, m_nextNetworkID(0) { }

	void UNetworkServer::PreTick(double inGameTime)
	{
		AdvanceTime(inGameTime);
		m_serverTransport->AdvanceTime(inGameTime);

		m_serverTransport->ReadPackets();
		ReceivePackets();

		ReceiveMessages();

		CheckForTimeOut();
	}

	void UNetworkServer::PostTick()
	{
		SendNetworkStateUpdates();
		FlushNetworkSpawns();

		SendPackets();
		m_serverTransport->WritePackets();
	}

	eastl::weak_ptr<ONetworkPlayer> UNetworkServer::GetPlayerByID(NetworkPlayerID_t inID) const
	{
		auto iter = m_players.find(inID);
		return (iter != m_players.end()) ? iter->second : nullptr;
	}

	eastl::shared_ptr<UObject> UNetworkServer::GetNetworkObject(SNetworkID inNetworkID) const
	{
		auto iter = m_netObjects.find(inNetworkID);
		if (iter == m_netObjects.end())
		{
			return nullptr;
		}

		return iter->second.Object;
	}

	void UNetworkServer::SendNetworkStateUpdates()
	{
		for (auto& netObject : m_netObjects)
		{
			auto  object = netObject.second.Object;
			auto  state  = netObject.second.State;
			auto& views  = netObject.second.NetworkViews;

			for (auto player : m_players)
			{
				auto playerID = player.first;

				// Don't bother sending state updates to local players (Listen servers)
				if (player.second->IsLocalPlayer()) continue;

				// TODO If object should be visible but does not have a network view, create one for this player and send Create message
				// TODO If object should not be visible and is currently visible, remove the network view for this player and send Destroy message

				// If object should be visible and should remain visible, serialize state for this player's network view into State message
				auto view = views.find(playerID);
				if (view != views.end())
				{
					auto msg = static_cast<MUpdateObject*>(CreateMsg(playerID, UPDATE_OBJECT));
					msg->m_objectNetID = object->GetNetID();
					state->SerializeState(msg->m_networkState, false);
					SendMsg(playerID, msg, MUpdateObject::MessageChannel);
				}
			}
		}
	}

	void UNetworkServer::ReceiveMessages()
	{
		for (const auto& player : m_players)
		{
			ReceiveMessagesForPlayer(*player.second);
		}
	}

	void UNetworkServer::ReceiveMessagesForPlayer(const ONetworkPlayer& inPlayer)
	{
		int numChannels = GetConnectionConfig().numChannels;

		for (int channelID = 0; channelID < numChannels; ++channelID)
		{
			ReceiveMessagesForPlayer(inPlayer, channelID);
		}
	}

	void UNetworkServer::ReceiveMessagesForPlayer(const ONetworkPlayer& inPlayer, int inChannelID)
	{
		auto playerID = inPlayer.GetPlayerID();

		while (auto msg = ReceiveMsg(playerID, inChannelID))
		{
			switch (msg->GetType())
			{
			case EVENT:
			{
				MEvent* message = static_cast<MEvent*>(msg);
				HandleEventMessage(*message, inPlayer);
				break;
			}

			default:
				LOG(LogNetworkServer, Warning, "[ReceiveMessagesForPlayer] Received unhandled or unknown message from player %d. Type: %i\n", playerID, msg->GetType());
				break;
			}

			ReleaseMsg(playerID, msg);
		}
	}

	void UNetworkServer::HandleEventMessage(MEvent& message, const ONetworkPlayer&)
	{
		// TODO: Probably want to verify that the player actually owns the target object

		auto targetObject = m_netObjects.find(message.m_targetObjectID);

		if (targetObject == m_netObjects.end())
		{
			LOG(LogNetworkServer, Warning, "Received event for invalid target network object!\n");
			return;
		}

		targetObject->second.Object->OnEvent(message.m_eventType, message.m_eventData.data());
	}

	eastl::shared_ptr<ONetworkPlayer> UNetworkServer::AddNewNetworkPlayer(NetworkPlayerID_t inNewPlayerID)
	{
		auto newPlayer = CreateDefaultObject<ONetworkPlayer>(nullptr);
		SetPlayerID(newPlayer, inNewPlayerID);
		return newPlayer;
	}

	void UNetworkServer::RemoveNetworkPlayer(NetworkPlayerID_t inPlayerID)
	{
		MAD_ASSERT_DESC(m_players.find(inPlayerID) != m_players.end(), "Cannot remove player ID that does not exist in m_players");

		// Clean up all their network views
		for (auto& netObject : m_netObjects)
		{
			netObject.second.NetworkViews.erase(inPlayerID);
		}

		m_players.erase(inPlayerID);
	}

	void UNetworkServer::SetPlayerID(eastl::shared_ptr<ONetworkPlayer> inPlayer, NetworkPlayerID_t inPlayerID)
	{
		MAD_ASSERT_DESC(m_players.find(inPlayerID) == m_players.end(), "Cannot assign a player to an already mapped playerID");

		auto iter = m_players.find(inPlayer->GetPlayerID());
		if (iter != m_players.end())
		{
			m_players.erase(iter);
		}

		inPlayer->SetPlayerID(inPlayerID);
		inPlayer->SetIsLocalPlayer(false);

		if (m_networkManager.GetNetMode() == ENetMode::ListenServer && inPlayerID == 0)
		{
			inPlayer->SetIsLocalPlayer(true);
		}

		m_players.insert({ inPlayerID, inPlayer });
	}

	eastl::shared_ptr<UObject> UNetworkServer::SpawnNetworkObject(const TTypeInfo& inTypeInfo, ONetworkPlayer& inNetOwner)
	{
		SNetworkID netID;
		netID.GetUnderlyingHandleRef() = m_nextNetworkID++;

		LOG(LogNetworkServer, Log, "Spawning a UObject<%s> on the server with ID %d\n", inTypeInfo.GetTypeName(), netID.GetUnderlyingHandleRef());

		eastl::shared_ptr<UObject> object = CreateDefaultObject<UObject>(inTypeInfo, nullptr);
		object->SetNetIdentity(netID, ENetRole::Authority, &inNetOwner);

		NetworkSpawn(object, inTypeInfo);

		return object;
	}

	eastl::shared_ptr<UObject> UNetworkServer::SpawnNetworkEntity(const TTypeInfo& inTypeInfo, ONetworkPlayer& inNetOwner, OGameWorld* inOwningGameWorld, const eastl::string& inWorldLayer)
	{
		MAD_ASSERT_DESC(!!inOwningGameWorld, "Spawning a networked Entity requires a target game world");
		if (!inOwningGameWorld) return nullptr;

		SNetworkID netID;
		netID.GetUnderlyingHandleRef() = m_nextNetworkID++;

		LOG(LogNetworkServer, Log, "Spawning a AEntity<%s> on the server with ID %d\n", inTypeInfo.GetTypeName(), netID.GetUnderlyingHandleRef());

		auto entity = inOwningGameWorld->SpawnEntityDeferred<AEntity>(inTypeInfo, inWorldLayer);
		entity->SetNetIdentity(netID, ENetRole::Authority, &inNetOwner);
		inOwningGameWorld->FinalizeSpawnEntity(entity);

		NetworkSpawn(entity, inTypeInfo);

		return entity;
	}

	void UNetworkServer::NetworkSpawn(eastl::shared_ptr<UObject> inObject, const TTypeInfo& inTypeInfo)
	{
		UNetObject netObject;
		netObject.Object = inObject;
		netObject.State = eastl::make_shared<UNetworkState>();
		netObject.State->TargetObject(inObject.get(), true);

		m_deferredSpawnMessages.push_back({ netObject, inTypeInfo.GetTypeID() });
	}

	void UNetworkServer::FlushNetworkSpawns()
	{
		for (auto& pair : m_deferredSpawnMessages)
		{
			auto& netObject = pair.first;
			const auto& object = netObject.Object;
			auto typeID = pair.second;

			for (const auto& player : m_players)
			{
				auto msg = static_cast<MCreateObject*>(CreateMsg(player.first, CREATE_OBJECT));
				msg->m_objectNetID = object->GetNetID();
				msg->m_netOwnerID = object->GetNetOwner()->GetPlayerID();
				msg->m_classTypeID = typeID;

				if (auto entity = Cast<AEntity>(object.get()))
				{
					msg->m_worldName = entity->GetOwningWorld()->GetWorldName();
					msg->m_layerName = entity->GetOwningWorldLayer().GetLayerName();
				}

				if (!player.second->IsLocalPlayer())
				{
					// Don't bother sending state data to a local player (for Listen servers)
					netObject.State->SerializeState(msg->m_networkState, false);
				}

				SendMsg(player.first, msg, MCreateObject::MessageChannel);

				netObject.NetworkViews.insert({ player.first, eastl::make_shared<UNetworkObjectView>(*netObject.State) });
			}

			m_netObjects.insert({ object->GetNetID(), netObject });
		}

		m_deferredSpawnMessages.clear();
	}

	void UNetworkServer::SendNetObjectsToNewPlayer(const ONetworkPlayer& inPlayer)
	{
		NetworkPlayerID_t playerID = inPlayer.GetPlayerID();

		for (auto& pair : m_netObjects)
		{
			SNetworkID netID = pair.first;
			UNetObject& netObject = pair.second;

			auto msg = static_cast<MCreateObject*>(CreateMsg(playerID, CREATE_OBJECT));
			msg->m_objectNetID = netID;
			msg->m_netOwnerID = netObject.Object->GetNetOwner()->GetPlayerID();
			msg->m_classTypeID = netObject.Object->GetTypeInfo()->GetTypeID();

			if (auto entity = Cast<AEntity>(netObject.Object.get()))
			{
				msg->m_worldName = entity->GetOwningWorld()->GetWorldName();
				msg->m_layerName = entity->GetOwningWorldLayer().GetLayerName();
			}

			if (!inPlayer.IsLocalPlayer())
			{
				// Don't bother sending state data to a local player (for Listen servers)
				netObject.State->SerializeState(msg->m_networkState, false, true);
			}

			SendMsg(playerID, msg, MCreateObject::MessageChannel);

			netObject.NetworkViews.insert({ playerID, eastl::make_shared<UNetworkObjectView>(*netObject.State) });
		}
	}

	void UNetworkServer::DestroyNetObjectsForPlayer(const ONetworkPlayer& inPlayer)
	{
		auto iter = m_netObjects.begin();
		while (iter != m_netObjects.end())
		{
			auto object = iter->second.Object;
			if (object->GetNetOwner()->GetPlayerID() == inPlayer.GetPlayerID())
			{
				object->Destroy();
				iter = m_netObjects.erase(iter);
			}
			else
			{
				++iter;
			}
		}
	}

	void UNetworkServer::DestroyNetworkObject(UObject& inObject)
	{
		SNetworkID netID = inObject.GetNetID();
		if (!netID.IsValid())
		{
			LOG(LogNetworkServer, Warning, "Cannot destroy a non-networked object\n");
			return;
		}

		auto netObject = m_netObjects.find(netID);
		MAD_ASSERT_DESC(netObject != m_netObjects.end(), "An object with valid network ID must exist in the server's map");

		LOG(LogNetworkServer, Log, "Destroying server object of type %s with ID %d...\n", inObject.GetTypeInfo()->GetTypeName(), netID.GetUnderlyingHandleRef());

		for (const auto& player : m_players)
		{
			auto msg = static_cast<MDestroyObject*>(CreateMsg(player.first, DESTROY_OBJECT));
			msg->m_objectNetID = netID;
			SendMsg(player.first, msg, MDestroyObject::MessageChannel);
		}

		inObject.Destroy();
		m_netObjects.erase(netObject);
	}

	void UNetworkServer::SendNetworkEvent(EEventTarget inEventTarget, EEventTypes inEventType, UObject& inTargetObject, void* inEventData, size_t inEventSize, NetworkPlayerID_t inTargetPlayer)
	{
		if (inEventTarget == EEventTarget::NetMulticast)
		{
			for (const auto& player : m_players)
			{
				// We don't want to resend this event to local player because server will execute anywhere
				if (player.second->IsLocalPlayer())
				{
					// TODO If NetMulticast on listen server, execute event locally
					continue;
				}

				auto msg = static_cast<MEvent*>(CreateMsg(player.first, EVENT));
				msg->m_eventType = inEventType;
				msg->m_targetObjectID = inTargetObject.GetNetID();
				msg->m_eventData.resize(inEventSize);
				memcpy(msg->m_eventData.data(), inEventData, inEventSize);

				SendMsg(player.first, msg, MEvent::MessageChannel);
			}
		}
		else if (inEventTarget == EEventTarget::Client)
		{
			auto msg = static_cast<MEvent*>(CreateMsg(inTargetPlayer, EVENT));
			msg->m_eventType = inEventType;
			msg->m_targetObjectID = inTargetObject.GetNetID();
			msg->m_eventData.resize(inEventSize);
			memcpy(msg->m_eventData.data(), inEventData, inEventSize);

			SendMsg(inTargetPlayer, msg, MEvent::MessageChannel);
		}
	}

	void UNetworkServer::OnStart(int maxClients)
	{
		(void)maxClients;
		LOG(LogNetworkServer, Log, "[OnStart] MaxClients=%i\n", maxClients);
	}

	void UNetworkServer::OnStop()
	{
		LOG(LogNetworkServer, Log, "[OnStop]\n");
	}

	void UNetworkServer::OnConnectionRequest(ServerConnectionRequestAction action, const ConnectionRequestPacket& packet, const Address& address, const ConnectToken& connectToken)
	{
		(void)packet;
		(void)connectToken;

		char addressString[MaxAddressLength];
		address.ToString(addressString, sizeof(addressString));

		switch (action)
		{
		case SERVER_CONNECTION_REQUEST_DENIED_SERVER_IS_FULL:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Denied connection request from %s. Server is full\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_BECAUSE_FLAG_IS_SET:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Flag is set to ignore connection requests\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_CONNECT_TOKEN_EXPIRED:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Connect token has expired (expire timestamp = %" PRIx64 ", current time = %" PRIx64 ")\n", addressString, packet.connectTokenExpireTimestamp, (uint64_t) ::time(NULL));
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_FAILED_TO_DECRYPT_CONNECT_TOKEN:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Failed to decrypt connect token\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_SERVER_ADDRESS_NOT_IN_WHITELIST:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Server address not in whitelist\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_CLIENT_ID_IS_ZERO:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Client ID is zero\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_ADDRESS_ALREADY_CONNECTED:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Address already connected\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_CLIENT_ID_ALREADY_CONNECTED:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Client id %" PRIx64 " already connected\n", addressString, connectToken.clientId);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_FAILED_TO_ADD_ENCRYPTION_MAPPING:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Failed to add encryption mapping\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_CONNECT_TOKEN_ALREADY_USED:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Connect token already used\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_FAILED_TO_GENERATE_CHALLENGE_TOKEN:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Failed to generate challenge token\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_FAILED_TO_ALLOCATE_CHALLENGE_PACKET:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Failed to allocate challenge packet\n", addressString);
			break;

		case SERVER_CONNECTION_REQUEST_IGNORED_FAILED_TO_ENCRYPT_CHALLENGE_TOKEN:
			LOG(LogNetworkServer, Warning, "[OnConnectionRequest] Ignored connection request from %s. Failed to encrypt challenge token\n", addressString);
			break;

		default:
			break;
		}
	}

	void UNetworkServer::OnChallengeResponse(ServerChallengeResponseAction action, const ChallengeResponsePacket& packet, const Address& address, const ChallengeToken& challengeToken)
	{
		(void)packet;
		(void)challengeToken;

		char addressString[MaxAddressLength];
		address.ToString(addressString, sizeof(addressString));

		switch (action)
		{
		case SERVER_CHALLENGE_RESPONSE_ACCEPTED:
			LOG(LogNetworkServer, Log, "[OnChallengeResponse] Accepted challenge response from %s\n", addressString);
			break;

		case SERVER_CHALLENGE_RESPONSE_DENIED_SERVER_IS_FULL:
			LOG(LogNetworkServer, Warning, "[OnChallengeResponse] Denied challenge response from %s. Server is full\n", addressString);
			break;

		case SERVER_CHALLENGE_RESPONSE_IGNORED_BECAUSE_FLAG_IS_SET:
			LOG(LogNetworkServer, Warning, "[OnChallengeResponse] Ignored challenge response from %s. Flag is set to ignore challenge responses\n", addressString);
			break;

		case SERVER_CHALLENGE_RESPONSE_IGNORED_FAILED_TO_DECRYPT_CHALLENGE_TOKEN:
			LOG(LogNetworkServer, Warning, "[OnChallengeResponse] Ignored challenge response from %s. Failed to decrypt challenge token\n", addressString);
			break;

		case SERVER_CHALLENGE_RESPONSE_IGNORED_ADDRESS_ALREADY_CONNECTED:
			LOG(LogNetworkServer, Warning, "[OnChallengeResponse] Ignored challenge response from %s. Address already connected\n", addressString, challengeToken.clientId);
			break;

		case SERVER_CHALLENGE_RESPONSE_IGNORED_CLIENT_ID_ALREADY_CONNECTED:
			LOG(LogNetworkServer, Warning, "[OnChallengeResponse] Ignored challenge response from %s. Client id %" PRIx64 " already connected\n", addressString, challengeToken.clientId);
			break;

		default:
			break;
		}
	}

	void UNetworkServer::OnClientConnect(int clientIndex)
	{
		char addressString[MaxAddressLength];
		GetClientAddress(clientIndex).ToString(addressString, sizeof(addressString));
		LOG(LogNetworkServer, Log, "[OnClientConnect] Client %d connected (client address = %s, client id = %.16" PRIx64 ")\n", clientIndex, addressString, GetClientId(clientIndex));

		auto newPlayer = AddNewNetworkPlayer(clientIndex);

		MInitializeNewPlayer* initMsg = static_cast<MInitializeNewPlayer*>(CreateMsg(clientIndex, INITIALIZE_NEW_PLAYER));

		// Notify other clients about this new client
		for (auto iter = m_players.cbegin(); iter != m_players.cend(); ++iter)
		{
			auto idx = iter->first;
			if (idx != clientIndex)
			{
				MOtherPlayerConnectionChanged* connectMsg = static_cast<MOtherPlayerConnectionChanged*>(CreateMsg(idx, OTHER_PLAYER_CONNECTION_CHANGED));
				connectMsg->m_connect = true;
				connectMsg->m_playerID = clientIndex;
				SendMsg(idx, connectMsg, MOtherPlayerConnectionChanged::MessageChannel);

				initMsg->m_otherPlayers.push_back(idx);
			}
		}

		// Tell this new client about other existing clients on the server
		SendMsg(clientIndex, initMsg, MInitializeNewPlayer::MessageChannel);

		// Tell this new client about existing network objects on the server
		SendNetObjectsToNewPlayer(*newPlayer);

		// Spawn the player's character
		auto world = gEngine->GetWorld(0);
		SpawnNetworkEntity(*Test::ADemoCharacter::StaticClass(), *newPlayer, world.get(), "default");
	}

	void UNetworkServer::OnClientDisconnect(int clientIndex)
	{
		char addressString[MaxAddressLength];
		GetClientAddress(clientIndex).ToString(addressString, sizeof(addressString));
		LOG(LogNetworkServer, Log, "[OnClientDisconnect] Client %d disconnected (client address = %s, client id = %.16" PRIx64 ")\n", clientIndex, addressString, GetClientId(clientIndex));

		DestroyNetObjectsForPlayer(*GetPlayerByID(clientIndex).lock());

		RemoveNetworkPlayer(clientIndex);
		MAD_ASSERT_DESC(m_players.find(clientIndex) == m_players.end(), "Disconnected client should no longer exist");

		for (auto iter = m_players.cbegin(); iter != m_players.cend(); ++iter)
		{
			int idx = iter->first;

			MOtherPlayerConnectionChanged* msg = static_cast<MOtherPlayerConnectionChanged*>(CreateMsg(idx, OTHER_PLAYER_CONNECTION_CHANGED));
			msg->m_connect = false;
			msg->m_playerID = clientIndex;
			SendMsg(idx, msg, MOtherPlayerConnectionChanged::MessageChannel);
		}
	}

	void UNetworkServer::OnClientError(int clientIndex, ServerClientError error)
	{
		(void)clientIndex;
		(void)error;

		switch (error)
		{
		case SERVER_CLIENT_ERROR_TIMEOUT:
			LOG(LogNetworkServer, Warning, "[OnClientError] Client %d timed out (client id = %.16" PRIx64 ")\n", clientIndex, GetClientId(clientIndex));
			break;

		case SERVER_CLIENT_ERROR_ALLOCATOR:
			LOG(LogNetworkServer, Warning, "[OnClientError] Client %d experienced an allocator error (client id = %.16" PRIx64 ")\n", clientIndex, GetClientId(clientIndex));
			break;

		case SERVER_CLIENT_ERROR_CONNECTION:
			LOG(LogNetworkServer, Warning, "[OnClientError] Client %d experienced a connection error (client id = %.16" PRIx64 ")\n", clientIndex, GetClientId(clientIndex));
			break;

		case SERVER_CLIENT_ERROR_MESSAGE_FACTORY:
			LOG(LogNetworkServer, Warning, "[OnClientError] Client %d experienced a message factory error (client id = %.16" PRIx64 ")\n", clientIndex, GetClientId(clientIndex));
			break;

		case SERVER_CLIENT_ERROR_PACKET_FACTORY:
			LOG(LogNetworkServer, Warning, "[OnClientError] Client %d experienced a packet factory error (client id = %.16" PRIx64 ")\n", clientIndex, GetClientId(clientIndex));
			break;

		default:
			break;
		}
	}

	void UNetworkServer::OnPacketSent(int packetType, const Address& to, bool immediate)
	{
		(void)immediate;

		const char* packetTypeString = nullptr;

		switch (packetType)
		{
		case CLIENT_SERVER_PACKET_CONNECTION_DENIED:          packetTypeString = "connection denied";     break;
		case CLIENT_SERVER_PACKET_CHALLENGE:                  packetTypeString = "challenge";             break;
		case CLIENT_SERVER_PACKET_KEEPALIVE:                  packetTypeString = "keep alive";            break;
		case CLIENT_SERVER_PACKET_DISCONNECT:                 packetTypeString = "disconnect";            break;

		default:
			return;
		}

#if NETWORK_VERBOSE_LOGGING
		char addressString[MaxAddressLength];
		to.ToString(addressString, sizeof(addressString));
		LOG(LogNetworkServer, Log, "[OnPacketSent] Server sent `%s` packet to %s%s\n", packetTypeString, addressString, immediate ? " (immediate)" : "");
#endif
	}

	void UNetworkServer::OnPacketReceived(int packetType, const Address& from)
	{
		const char* packetTypeString = nullptr;

		switch (packetType)
		{
		case CLIENT_SERVER_PACKET_CONNECTION_REQUEST:         packetTypeString = "connection request";        break;
		case CLIENT_SERVER_PACKET_CHALLENGE_RESPONSE:         packetTypeString = "challenge response";        break;
		case CLIENT_SERVER_PACKET_KEEPALIVE:                  packetTypeString = "keep alive";                break;
		case CLIENT_SERVER_PACKET_DISCONNECT:                 packetTypeString = "disconnect";                break;

		default:
			return;
		}

#if NETWORK_VERBOSE_LOGGING
		char addressString[MaxAddressLength];
		from.ToString(addressString, sizeof(addressString));
		LOG(LogNetworkServer, Log, "[OnPacketReceived] Server received `%s` packet from %s\n", packetTypeString, addressString);
#endif
	}
}


text:
package org.usc.demo.lock;

import com.sun.management.GcInfo;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SystemInfo {

    private static String serverStartupTime;// 服务器启动时间
    /**
     * 服务器的启动类
     */

    private static String formatMemoryUsage(MemoryUsage mem) {
        String fmt = "初始化:%-10s 已使用:%-10s 最大:%-10s";
        return String.format(fmt, HumanReadableUtil.byteSize(mem.getInit()), HumanReadableUtil.byteSize(mem.getUsed()), HumanReadableUtil.byteSize(mem.getMax()));
    }

    private static String getContrastString(long before, long after) {
        long sub = after - before;
        if (sub > 0) {
            return "↑" + HumanReadableUtil.byteSize(after);
        } else if (sub < 0) {
            return "↓" + HumanReadableUtil.byteSize(after);
        }
        return "";
    }

    public static StringBuilder getGarbageCollectorInfo(StringBuilder tmp) {
        List<GarbageCollectorMXBean> gcs = ManagementFactory.getGarbageCollectorMXBeans();
        tmp.append("GarbageCollectorMXBeans\n");
        String gcFmt = "%-23s %-8s %-20s %s\n";
        tmp.append(String.format(gcFmt, "GCName", "Count", "Time", "MemoryPoolNames"));
        Set<String> poolNames = new LinkedHashSet<String>();
        for (GarbageCollectorMXBean gc : gcs) {
            tmp.append(String.format(gcFmt, gc.getName(), gc.getCollectionCount(), HumanReadableUtil.timeSpan(gc.getCollectionTime()), Arrays.toString(gc.getMemoryPoolNames())));
            for (String n : gc.getMemoryPoolNames()) {
                poolNames.add(n);
            }
        }
        for (GarbageCollectorMXBean gc : gcs) {
            if(gc instanceof com.sun.management.GarbageCollectorMXBean) {
                com.sun.management.GarbageCollectorMXBean g = (com.sun.management.GarbageCollectorMXBean) gc;
                GcInfo gi = g.getLastGcInfo();
                if(gi == null || gi.getStartTime() == 0) {
                    continue;
                }

                Map<String, MemoryUsage> before = gi.getMemoryUsageBeforeGc();
                Map<String, MemoryUsage> after = gi.getMemoryUsageAfterGc();
                String muFmt = "%-23s %-30s %-14s %-14s %-14s %-14s\n";
                tmp.append(String.format(muFmt, "", "poolName", "init", "used", "committed", "max"));
                for (String name : poolNames) {
                    // for (java.util.Map.Entry<String, MemoryUsage> e : before.entrySet()) {
                    // String name = e.getKey();
                    // MemoryUsage mu = e.getValue();
                    MemoryUsage mu = before.get(name);
                    MemoryUsage mu1 = after.get(name);
                    if(mu == null) {
                        continue;
                    }
                    tmp.append(String.format(muFmt, "", name, HumanReadableUtil.byteSize(mu.getInit()), HumanReadableUtil.byteSize(mu.getUsed()), HumanReadableUtil.byteSize(mu.getCommitted()),
                            HumanReadableUtil.byteSize(mu.getMax())));
                    String init = getContrastString(mu.getInit(), mu1.getInit());
                    String used = getContrastString(mu.getUsed(), mu1.getUsed());
                    String committted = getContrastString(mu.getCommitted(), mu1.getCommitted());
                    String max = getContrastString(mu.getMax(), mu1.getMax());
                    tmp.append(String.format(muFmt, "", "", init, used, committted, max));
                }
            }
        }
        return tmp;
    }

    public static StringBuilder getMemoryInfo(StringBuilder tmp) {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        tmp.append("\nmemoryMXBean\n");
        tmp.append("已使用内存:\t\t").append(HumanReadableUtil.byteSize(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())).append("\n");
        tmp.append("已分配内存:\t\t").append(HumanReadableUtil.byteSize(Runtime.getRuntime().totalMemory())).append("\n");
        tmp.append("最大内存:\t\t").append(HumanReadableUtil.byteSize(Runtime.getRuntime().maxMemory())).append("\n");
        tmp.append("堆内存:\t\t\t").append(formatMemoryUsage(memoryMXBean.getHeapMemoryUsage())).append("\n");
        tmp.append("非堆内存:\t\t").append(formatMemoryUsage(memoryMXBean.getNonHeapMemoryUsage())).append("\n");
        tmp.append("待回收对象数:\t\t").append(memoryMXBean.getObjectPendingFinalizationCount()).append("\n");
        tmp.append("\n");
        return tmp;
    }

}

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Windows;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog
{
    internal class PullMemberUpSymbolViewModel : SymbolViewModel<ISymbol>
    {
        private bool _isCheckable;
        private bool _makeAbstract;
        private bool _isMakeAbstractCheckable;
        private string _tooltipText;
        public string MakeAbstractCheckBoxAutomationText => string.Format(ServicesVSResources.Make_0_abstract, Symbol.Name);
        public string RowSelectionAutomationText => ServicesVSResources.Select_member;

        /// <summary>
        /// Property controls the 'Make abstract' check box's Visibility.
        /// The check box is hidden for members impossbile to be made to abstract.
        /// </summary>
        public Visibility MakeAbstractVisibility => Symbol.Kind == SymbolKind.Field || Symbol.IsAbstract ? Visibility.Hidden : Visibility.Visible;

        /// <summary>
        /// Indicates whether 'Make abstract' check box is checked.
        /// </summary>
        public bool MakeAbstract { get => _makeAbstract; set => SetProperty(ref _makeAbstract, value, nameof(MakeAbstract)); }

        /// <summary>
        /// Indicates whether make abstract check box is enabled or not. (e.g. When user selects on interface destination, it will be disabled)
        /// </summary>
        public bool IsMakeAbstractCheckable { get => _isMakeAbstractCheckable; set => SetProperty(ref _isMakeAbstractCheckable, value, nameof(IsMakeAbstractCheckable)); }

        /// <summary>
        /// Indicates whether this member checkable.
        /// </summary>
        public bool IsCheckable { get => _isCheckable; set => SetProperty(ref _isCheckable, value, nameof(IsCheckable)); }

        /// <summary>
        /// Tooltip text, also used as HelpText for screen readers. Should be empty
        /// when no tool tip should be shown
        /// </summary>
        public string TooltipText { get => _tooltipText; set => SetProperty(ref _tooltipText, value, nameof(TooltipText)); }

        /// <summary>
        /// The content of tooltip.
        /// </summary>
        public string Accessibility => Symbol.DeclaredAccessibility.ToString();

        public PullMemberUpSymbolViewModel(ISymbol symbol, IGlyphService glyphService) : base(symbol, glyphService)
        {
        }
    }
}


text:
import android.app.*;
import android.content.Context;
import android.os.Environment;
import android.widget.Button;
import com.special.AndroidSmartUpdates.Constant;
import com.special.AndroidSmartUpdates.R;
import com.special.AndroidSmartUpdates.SmartUpdates;
import com.special.AndroidSmartUpdates.helper.ApiHelper;
import com.special.AndroidSmartUpdates.helper.PatchHelper;
import com.special.AndroidSmartUpdates.impl.UpdateListener;
import com.special.AndroidSmartUpdates.model.PatchInformation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.*;
import java.io.File;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

/**
 * User: special
 * Date: 13-9-16
 * Time: 上午10:14
 * Mail: specialcyci@gmail.com
 */
@RunWith(RobolectricTestRunner.class)
public class TestSmartUpdates{

    private static final String UPDATE_SERVER_ADDRESS = "http://192.168.1.171:8080/smartupdates/";
    private ShadowActivity activity;
    private Application application;
    private AlertDialog alertDialog;
    private SmartUpdates smartUpdates;

    public void startCheckUpdate() throws Exception {
        setUpActivity();
        setUpApplication();
        checkForUpdate();
        setUpDialog();
        ShadowEnvironment.setExternalStorageState(Environment.MEDIA_MOUNTED);
    }

    private void setUpActivity(){
        activity = new ShadowActivity();
        activity.onCreate(null);
    }

    private void setUpApplication(){
        application = activity.getApplication();
    }

    private void setUpDialog(){
        alertDialog = ShadowAlertDialog.getLatestAlertDialog();
    }

    private void checkForUpdate(){
        smartUpdates = new SmartUpdates(activity.getApplicationContext());
        smartUpdates.setServerAddress(UPDATE_SERVER_ADDRESS);
        smartUpdates.checkForUpdate();
    }

    @Test
    public void testRequsetFailed() throws Exception{
        Robolectric.setDefaultHttpResponse(500, "");
        startCheckUpdate();
        assertNull(alertDialog);
        assertFalse(activity.isFinishing());
    }

    @Test
    public void testHasUpdate() throws Exception{
        startHasUpdateSituation();
        shouldHasUpdateDialog();
    }

    @Test
    public void testUpdateListenerWhenHasUpdate() throws Exception{
        pauseBackgroundWork();
        startHasUpdateSituation();
        UpdateListener listener = mockUpdateListener();
        contiuneBackgroundWork();
        verify(listener, times(1)).hasUpdate(any(PatchInformation.class));
        verify(listener, never()).hasNoUpdate();
    }

    @Test
    public void testUpdateListenerWhenNoUpdate() throws Exception{
        pauseBackgroundWork();
        startNoUpdateSituation();
        UpdateListener listener = mockUpdateListener();
        contiuneBackgroundWork();
        verify(listener, never()).hasUpdate(any(PatchInformation.class));
        verify(listener, times(1)).hasNoUpdate();
    }

    private UpdateListener mockUpdateListener(){
        UpdateListener listener = mock(UpdateListener.class);
        smartUpdates.setUpdateListener(listener);
        return listener;
    }

    @Test
    public void testSetShowUpdateDialog() throws Exception{
        pauseBackgroundWork();
        startHasUpdateSituation();
        smartUpdates.setShowUpdateDialog(false);
        contiuneBackgroundWork();
        assertFalse(isDialogShowing());
    }

    @Test
    public void testParseErrorSituaction() throws Exception{
        startParseSituation();
        assertTrue(isToastTextEqualTo(R.string.toast_parse_error));
        assertFalse(isDialogShowing());
    }

    @Test
    public void testApplicationNotExistedSituaction() throws Exception{
        startApplicationNotExistedSituation();
        assertTrue(isToastTextEqualTo(R.string.toast_application_not_existed));
        assertFalse(isDialogShowing());
    }

    @Test
    public void testCurrentVersionNotExistedSituation() throws Exception{
        startCurrentVersionNotExistedSituation();
        assertTrue(isToastTextEqualTo(R.string.toast_current_version_not_existed));
        assertFalse(isDialogShowing());
    }

    @Test
    public void testPackageNameNotMatchSituation() throws Exception{
        startPackageNameNotMatchSituation();
        assertTrue(isToastTextEqualTo(R.string.toast_package_name_not_match));
        assertFalse(isDialogShowing());
    }

    @Test
    public void testHasUpdateAndPressOkButton() throws Exception {
        startHasUpdateSituation();
        stubDownLoadUrl("http://www.baidu.com/");
        stubPathFileUrl(getNewApkPath());
        pauseBackgroundWork();
        pressingOnDialogUpdateButton();
        assertTrue(isNotificationShowing());
        contiuneBackgroundWork();
        checkPatchFileIsDelete();
    }

    private void checkPatchFileIsDelete(){
        File patchFile = new File(ShadowEnvironment.getExternalStorageDirectory() +
             File.separator + Constant.SAVE_FOLDER + File.separator
                + Constant.SAVE_FILENAME);
        assertFalse(patchFile.exists());
    }

    @Test
    public void testHasUpdateAndPressCancelButton() throws Exception {
        startHasUpdateSituation();
        pressingDialogCancelButton();
        assertFalse(isNotificationShowing());
    }

    @Test
    public void testHasUpdateAndPressUpdateButtonButSDCardNotExisted() throws Exception{
        startHasUpdateSituation();
        ShadowEnvironment.setExternalStorageState(Environment.MEDIA_UNMOUNTED);
        pressingOnDialogUpdateButton();
        assertTrue(isToastTextEqualTo(R.string.toast_sdcard_not_existed));
        assertFalse(isNotificationShowing());
    }

    @Test
    public void testHasUpdateAndPressUpdateButtonButDownloadUrlNotExisted() throws Exception{
        startHasUpdateSituation();
        stubDownLoadUrl("http://255.255.255.255/");
        pressingOnDialogUpdateButton();
        assertTrue(isToastTextEqualTo(R.string.toast_download_error));
        assertFalse(isNotificationShowing());
    }

    @Test
    public void testNoUpdate() throws Exception{
        startNoUpdateSituation();
        assertFalse(isDialogShowing());
    }

    private void shouldHasUpdateDialog() throws Exception{
        ShadowAlertDialog shadowAlertDialog = Robolectric.shadowOf(alertDialog);
        String dialog_title = application.getString(R.string.dialog_title);
        assertEquals(shadowAlertDialog.getTitle(), dialog_title);
        System.out.println(shadowAlertDialog.getMessage());
        checkHasStringInDialog(shadowAlertDialog, "1.1");
        checkHasStringInDialog(shadowAlertDialog,"version 2");
        checkHasStringInDialog(shadowAlertDialog,"2.15K");
        checkHasStringInDialog(shadowAlertDialog, "2013-10-04");
    }

    private void checkHasStringInDialog(ShadowAlertDialog dialog,String wantString){
        assertNotSame(dialog.getMessage().toString().indexOf(wantString), -1);
    }

    private void stubPathFileUrl(String fileUrl){
        PatchHelper patchHelper = mock(PatchHelper.class);
        stub(patchHelper.patch(getPatchFilePath())).toReturn(fileUrl);
        smartUpdates.setMockPatchHelper(patchHelper);
    }

    private String getPatchFilePath(){
        return getStorePath() + Constant.SAVE_FILENAME;
    }

    private String getNewApkPath(){
        return getStorePath() + Constant.NEWAPK_FILENAME;
    }

    private String getStorePath(){
        return ShadowEnvironment.getExternalStorageDirectory()
                + File.separator + Constant.SAVE_FOLDER + File.separator;
    }

    private void stubDownLoadUrl(String downloadUrl) throws Exception {
        ApiHelper api = mock(ApiHelper.class);
        stub(api.getDownloadUrl()).toReturn(downloadUrl);
        smartUpdates.setMockApiHelper(api);
    }

    private void startHasUpdateSituation() throws Exception {
        String response = "{\"message\":\"has_update\",\"information\":{\"application_id\":1,\"version_code\":2,\"version_name\":\"1.1\",\"description\":\"version 2\",\"apk_updated_at\":1380823151,\"apk_patch_size\":2206}}";
        Robolectric.setDefaultHttpResponse(200,response);
        startCheckUpdate();
    }

    private void startNoUpdateSituation() throws Exception{
        String response =  "{\"message\":\"no_update\",\"information\":null}";
        setResponseAndStartCheckUpdate(response);
    }

    private void startParseSituation() throws Exception{
        String response =  "{";
        setResponseAndStartCheckUpdate(response);
    }

    private void startApplicationNotExistedSituation() throws Exception{
        String response =  "{\"message\":\"application_not_existed\",\"information\":null}";
        setResponseAndStartCheckUpdate(response);
    }

    private void startCurrentVersionNotExistedSituation() throws Exception{
        String response =  "{\"message\":\"current_version_not_existed\",\"information\":null}";
        setResponseAndStartCheckUpdate(response);
    }

    private void startPackageNameNotMatchSituation() throws Exception{
        String response =  "{\"message\":\"package_name_not_match\",\"information\":null}";
        setResponseAndStartCheckUpdate(response);
    }

    private void setResponseAndStartCheckUpdate(String response) throws Exception {
        Robolectric.setDefaultHttpResponse(200,response);
        startCheckUpdate();
    }

    private void pressingOnDialogUpdateButton() throws Exception{
        Button updateButton = alertDialog.getButton(Dialog.BUTTON_POSITIVE);
        Robolectric.clickOn(updateButton);
        assertTrue(!alertDialog.isShowing());
    }

    private void pressingDialogCancelButton() throws Exception{
        Button cancelButton = alertDialog.getButton(Dialog.BUTTON_NEGATIVE);
        Robolectric.clickOn(cancelButton);
        assertTrue(!alertDialog.isShowing());
    }

    private boolean isDialogShowing(){
        return ShadowAlertDialog.getLatestAlertDialog() != null;
    }

    private boolean isNotificationShowing(){
        Notification shadow = getNotification();
        return shadow != null;
    }

    private boolean isToastTextEqualTo(int stringResourceId){
        String title = ShadowToast.getTextOfLatestToast();
        String toastTitle = application.getString(stringResourceId);
        return title.equals(toastTitle);
    }

    private Notification getNotification(){
        NotificationManager notificationManager = (NotificationManager)
                Robolectric.application.getSystemService(Context.NOTIFICATION_SERVICE);
        ShadowNotificationManager shadow = Robolectric.shadowOf(notificationManager);
        return shadow.getNotification(null, Constant.NOTIFICATION_ID);
    }

    private void pauseBackgroundWork(){
        Robolectric.getBackgroundScheduler().pause();
    }

    private void contiuneBackgroundWork(){
        Robolectric.runBackgroundTasks();
    }

}


text:
<template name="postEdit">
  {{#with post}}
    <form class="main">

        URL

          <input name="url" type="text" value="{{url}}" placeholder="Your URL"/>

        Title

          <input name="title" type="text" value="{{title}}" placeHolder="Name your post"/>

          <input type="submit" value="submit" class="btn btn-primary"/>

          Delete post

    </form>
  {{/with}}
</template>


text:
namespace crcutil {

#pragma pack(push, 16)

// CrcImplementation should provide:
// - typename Crc
// - typename TableEntry
// - typename Word
// - Crc CrcDefault(const void *data, size_t bytes, const Crc &start)
// - const GfUtil<Crc> &Base() const
template<typename CrcImplementation> class RollingCrc {
 public:
  typedef typename CrcImplementation::Crc Crc;
  typedef typename CrcImplementation::TableEntry TableEntry;
  typedef typename CrcImplementation::Word Word;

  RollingCrc() {}

  // Initializes internal data structures.
  // Retains reference to "crc" instance -- it is used by Start().
  RollingCrc(const CrcImplementation &crc,
             size_t roll_window_bytes,
             const Crc &start_value) {
    Init(crc, roll_window_bytes, start_value);
  }

  // Computes crc of "roll_window_bytes" using
  // "start_value" of "crc" (see Init()).
  Crc Start(const void *data) const {
    return crc_->CrcDefault(data, roll_window_bytes_, start_value_);
  }

  // Computes CRC of "roll_window_bytes" starting in next position.
  Crc Roll(const Crc &old_crc, size_t byte_out, size_t byte_in) const {
    return (old_crc >> 8) ^ in_[TO_BYTE(old_crc) ^ byte_in] ^ out_[byte_out];
  }

  // Initializes internal data structures.
  // Retains reference to "crc" instance -- it is used by Start().
  void Init(const CrcImplementation &crc,
            size_t roll_window_bytes,
            const Crc &start_value) {
    crc_ = &crc;
    roll_window_bytes_ = roll_window_bytes;
    start_value_ = start_value;

    Crc add = crc.Base().Canonize() ^ start_value;
    add = crc.Base().Multiply(add, crc.Base().Xpow8N(roll_window_bytes));
    add ^= crc.Base().Canonize();
    Crc mul = crc.Base().One() ^ crc.Base().Xpow8N(1);
    add = crc.Base().Multiply(add, mul);

    mul = crc.Base().XpowN(8 * roll_window_bytes + crc.Base().Degree());
    for (size_t i = 0; i < 256; ++i) {
      out_[i] = static_cast<TableEntry>(
                    crc.Base().MultiplyUnnormalized(
                        static_cast<Crc>(i), 8, mul) ^ add);
    }
    for (size_t i = 0; i < 256; ++i) {
      in_[i] = crc.crc_word_[sizeof(Word) - 1][i];
    }
  }

  // Returns start value.
  Crc StartValue() const { return start_value_; }

  // Returns length of roll window.
  size_t WindowBytes() const { return roll_window_bytes_; }

 protected:
  TableEntry in_[256];
  TableEntry out_[256];

  // Used only by Start().
  Crc start_value_;
  const CrcImplementation *crc_;
  size_t roll_window_bytes_;
} GCC_ALIGN_ATTRIBUTE(16);

#pragma pack(pop)

}  // namespace crcutil

#endif  // CRCUTIL_ROLLING_CRC_H_


text:
import { val, type } from "kamboja"

export class CustomerModel {
    @val.required()
    @val.email()
    @type("string")
    email: string

    @val.required()
    @type("string")
    name: string

    @type("date")
    createdAt: Date

    @type("date")
    updatedAt: Date
}


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class AutoWeather extends StdCommand
{
	public AutoWeather(){}

	private final String[] access=_i(new String[]{"AUTOWEATHER"});
	@Override public String[] getAccessWords(){return access;}

	@Override
	public boolean execute(MOB mob, Vector commands, int metaFlags)
		throws java.io.IOException

	{
		if(CMath.bset(mob.getBitmap(),MOB.ATT_AUTOWEATHER))
		{
			mob.setBitmap(CMath.unsetb(mob.getBitmap(),MOB.ATT_AUTOWEATHER));
			mob.tell(_("Weather descriptions are now off."));
		}
		else
		{
			mob.setBitmap(CMath.setb(mob.getBitmap(),MOB.ATT_AUTOWEATHER));
			mob.tell(_("Weather descriptions are now on."));
		}
		return false;
	}

	@Override public boolean canBeOrdered(){return true;}
}


text:
layout: page
subheadline: "Tech"
title: "Webcampak : les photos archivées"
date: 2010-10-05 05:54:14+00:00
teaser: "Petit retour en arrière, souvenez-vous : l'utilisation de Webcampak avec une caméra USB HD de marque Hercules, et son intégration pour la rendre étanche."
header:
    image_fullwidth: "header_typewriter.jpg"
    caption: Image by Florian Klauer
    caption_url: "http://florianklauer.de/"
image:
    thumb:  typewriter_thumb.jpg
    homepage: homepage_typewriter.jpg
categories:
    - tech
comments: false
show_meta: true
---
Webcampak, serveur d'images par excellence, permet de visualiser facilement les photos enregistrées automatiquement.

Voyons, par exemple, ce qu'il s'est passé hier dans l'Alberta, au Canada :

[![](http://infracom-france.com/blog2/wp-content/uploads/2010/10/webcampak5-1024x463.png)](http://infracom-france.com/blog2/wp-content/uploads/2010/10/webcampak5.png)

Dans l'interface de visualisation, nous retrouvons :

  * un calendrier sur la partie gauche
  * les heures des clichés à droite
  * l'image affichée au centre

Dans notre exemple, nous avons demandé l'ajout du logo Webcampak en haut à gauche, affiché avec 30% de transparence, et le titre "Alberta / Canada" suivi de la date et de l'heure en bas à gauche. Bien entendu, ces images peuvent être sans aucun insert, tout se fait dans la configuration de la source d'images.

Plus proche de nous, que s'est-il donc passé à Paris entre 1h00 et 1h05 ce matin ? Devinez :

[![](http://infracom-france.com/blog2/wp-content/uploads/2010/10/webcampakeiffel-1024x465.png)](http://infracom-france.com/blog2/wp-content/uploads/2010/10/webcampakeiffel.png)

[![](http://infracom-france.com/blog2/wp-content/uploads/2010/10/webcampakeiffel1-1024x462.png)](http://infracom-france.com/blog2/wp-content/uploads/2010/10/webcampakeiffel1.png)

Oui, effectivement, un technicien s'est pris les pieds dans la rallonge électrique alimentant le haut de la célèbre tour , à moins qu'il ne s'agisse d'une manoeuvre anti-terroriste pour empêcher à un avion de venir tester la solidité des étages supérieurs ;-)

Plus sérieusement, vous l'aurez compris, Webcampak permettant de gérer plusieurs sources d'images, vous aurez toute latitude d'ajouter les flux qui vous intéressent et d'observer à tête reposée le défilement de la vie capturé par la caméra distante.

_This article has been automatically imported from our old blog, there might be formatting or layout issues._


text:
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class AAL_Hook_Plugins extends AAL_Hook_Base {

	protected function _add_log_plugin( $action, $plugin_name ) {
		// Get plugin name if is a path
		if ( false !== strpos( $plugin_name, '/' ) ) {
			$plugin_dir  = explode( '/', $plugin_name );
			$plugin_data = array_values( get_plugins( '/' . $plugin_dir[0] ) );
			$plugin_data = array_shift( $plugin_data );
			$plugin_name = $plugin_data['Name'];
		}

		aal_insert_log(
			array(
				'action'      => $action,
				'object_type' => 'Plugin',
				'object_id'   => 0,
				'object_name' => $plugin_name,
			)
		);
	}

	public function hooks_deactivated_plugin( $plugin_name ) {
		$this->_add_log_plugin( 'deactivated', $plugin_name );
	}

	public function hooks_activated_plugin( $plugin_name ) {
		$this->_add_log_plugin( 'activated', $plugin_name );
	}

	public function hooks_plugin_modify( $location, $status ) {
		if ( false !== strpos( $location, 'plugin-editor.php' ) ) {
			if ( ( ! empty( $_POST ) && 'update' === $_REQUEST['action'] ) ) {
				$aal_args = array(
					'action'         => 'file_updated',
					'object_type'    => 'Plugin',
					'object_subtype' => 'plugin_unknown',
					'object_id'      => 0,
					'object_name'    => 'file_unknown',
				);

				if ( ! empty( $_REQUEST['file'] ) ) {
					$aal_args['object_name'] = $_REQUEST['file'];
					// Get plugin name
					$plugin_dir  = explode( '/', $_REQUEST['file'] );
					$plugin_data = array_values( get_plugins( '/' . $plugin_dir[0] ) );
					$plugin_data = array_shift( $plugin_data );

					$aal_args['object_subtype'] = $plugin_data['Name'];
				}
				aal_insert_log( $aal_args );
			}
		}

		// We are need return the instance, for complete the filter.
		return $location;
	}

	/**
	 * @param Plugin_Upgrader $upgrader
	 * @param array $extra
	 */
	public function hooks_plugin_install_or_update( $upgrader, $extra ) {
		if ( ! isset( $extra['type'] ) || 'plugin' !== $extra['type'] )
			return;

		if ( 'install' === $extra['action'] ) {
			$path = $upgrader->plugin_info();
			if ( ! $path )
				return;

			$data = get_plugin_data( $upgrader->skin->result['local_destination'] . '/' . $path, true, false );

			aal_insert_log(
				array(
					'action' => 'installed',
					'object_type' => 'Plugin',
					'object_name' => $data['Name'],
					'object_subtype' => $data['Version'],
				)
			);
		}

		if ( 'update' === $extra['action'] ) {
			if ( isset( $extra['bulk'] ) && true == $extra['bulk'] ) {
				$slugs = $extra['plugins'];
			} else {
				if ( ! isset( $upgrader->skin->plugin ) )
					return;

				$slugs = array( $upgrader->skin->plugin );
			}

			foreach ( $slugs as $slug ) {
				$data = get_plugin_data( WP_PLUGIN_DIR . '/' . $slug, true, false );

				aal_insert_log(
					array(
						'action' => 'updated',
						'object_type' => 'Plugin',
						'object_name' => $data['Name'],
						'object_subtype' => $data['Version'],
					)
				);
			}
		}
	}

	public function __construct() {
		add_action( 'activated_plugin', array( &$this, 'hooks_activated_plugin' ) );
		add_action( 'deactivated_plugin', array( &$this, 'hooks_deactivated_plugin' ) );
		add_filter( 'wp_redirect', array( &$this, 'hooks_plugin_modify' ), 10, 2 );

		add_action( 'upgrader_process_complete', array( &$this, 'hooks_plugin_install_or_update' ), 10, 2 );

		parent::__construct();
	}

}


text:
import grpc

import vswapi_pb2 as vswapi__pb2

class VswApiStub(object):
  # missing associated documentation comment in .proto file
  pass

  def __init__(self, channel):
    """Constructor.

    Args:
      channel: A grpc.Channel.
    """
    self.ModIfname = channel.unary_unary(
        '/vswapi.VswApi/ModIfname',
        request_serializer=vswapi__pb2.ModIfnameRequest.SerializeToString,
        response_deserializer=vswapi__pb2.ModIfnameReply.FromString,
        )
    self.GetIfnames = channel.unary_stream(
        '/vswapi.VswApi/GetIfnames',
        request_serializer=vswapi__pb2.GetIfnamesRequest.SerializeToString,
        response_deserializer=vswapi__pb2.GetIfnamesReply.FromString,
        )
    self.ModLink = channel.unary_unary(
        '/vswapi.VswApi/ModLink',
        request_serializer=vswapi__pb2.ModLinkRequest.SerializeToString,
        response_deserializer=vswapi__pb2.ModLinkReply.FromString,
        )
    self.GetLinks = channel.unary_stream(
        '/vswapi.VswApi/GetLinks',
        request_serializer=vswapi__pb2.GetLinksRequest.SerializeToString,
        response_deserializer=vswapi__pb2.GetLinksReply.FromString,
        )
    self.GetStats = channel.unary_stream(
        '/vswapi.VswApi/GetStats',
        request_serializer=vswapi__pb2.GetStatsRequest.SerializeToString,
        response_deserializer=vswapi__pb2.GetStatsReply.FromString,
        )
    self.SaveConfig = channel.unary_unary(
        '/vswapi.VswApi/SaveConfig',
        request_serializer=vswapi__pb2.SaveConfigRequest.SerializeToString,
        response_deserializer=vswapi__pb2.SaveConfigReply.FromString,
        )

class VswApiServicer(object):
  # missing associated documentation comment in .proto file
  pass

  def ModIfname(self, request, context):
    # missing associated documentation comment in .proto file
    pass
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

  def GetIfnames(self, request, context):
    # missing associated documentation comment in .proto file
    pass
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

  def ModLink(self, request, context):
    # missing associated documentation comment in .proto file
    pass
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

  def GetLinks(self, request, context):
    # missing associated documentation comment in .proto file
    pass
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

  def GetStats(self, request, context):
    # missing associated documentation comment in .proto file
    pass
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

  def SaveConfig(self, request, context):
    # missing associated documentation comment in .proto file
    pass
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

def add_VswApiServicer_to_server(servicer, server):
  rpc_method_handlers = {
      'ModIfname': grpc.unary_unary_rpc_method_handler(
          servicer.ModIfname,
          request_deserializer=vswapi__pb2.ModIfnameRequest.FromString,
          response_serializer=vswapi__pb2.ModIfnameReply.SerializeToString,
      ),
      'GetIfnames': grpc.unary_stream_rpc_method_handler(
          servicer.GetIfnames,
          request_deserializer=vswapi__pb2.GetIfnamesRequest.FromString,
          response_serializer=vswapi__pb2.GetIfnamesReply.SerializeToString,
      ),
      'ModLink': grpc.unary_unary_rpc_method_handler(
          servicer.ModLink,
          request_deserializer=vswapi__pb2.ModLinkRequest.FromString,
          response_serializer=vswapi__pb2.ModLinkReply.SerializeToString,
      ),
      'GetLinks': grpc.unary_stream_rpc_method_handler(
          servicer.GetLinks,
          request_deserializer=vswapi__pb2.GetLinksRequest.FromString,
          response_serializer=vswapi__pb2.GetLinksReply.SerializeToString,
      ),
      'GetStats': grpc.unary_stream_rpc_method_handler(
          servicer.GetStats,
          request_deserializer=vswapi__pb2.GetStatsRequest.FromString,
          response_serializer=vswapi__pb2.GetStatsReply.SerializeToString,
      ),
      'SaveConfig': grpc.unary_unary_rpc_method_handler(
          servicer.SaveConfig,
          request_deserializer=vswapi__pb2.SaveConfigRequest.FromString,
          response_serializer=vswapi__pb2.SaveConfigReply.SerializeToString,
      ),
  }
  generic_handler = grpc.method_handlers_generic_handler(
      'vswapi.VswApi', rpc_method_handlers)
  server.add_generic_rpc_handlers((generic_handler,))


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import uuid

class Migration(migrations.Migration):

    dependencies = [
        ('socialnet', '0016_author_host'),
    ]

    operations = [
        migrations.CreateModel(
            name='FriendRequest',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ],
        ),
        migrations.CreateModel(
            name='Node',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('node_url', models.URLField()),
                ('access_to_posts', models.BooleanField()),
                ('access_to_images', models.BooleanField()),
            ],
        ),
        migrations.CreateModel(
            name='PostVisibility',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('visible', models.BooleanField(default=True)),
            ],
        ),
        migrations.RenameField(
            model_name='post',
            old_name='published_date',
            new_name='published_time',
        ),
        migrations.RemoveField(
            model_name='author',
            name='followers',
        ),
        migrations.RemoveField(
            model_name='author',
            name='following',
        ),
        migrations.RemoveField(
            model_name='comment',
            name='published_date',
        ),
        migrations.RemoveField(
            model_name='post',
            name='image',
        ),
        migrations.AddField(
            model_name='author',
            name='friends',
            field=models.ManyToManyField(blank=True, related_name='_author_friends_+', to='socialnet.Author'),
        ),
        migrations.AddField(
            model_name='post',
            name='content_type',
            field=models.CharField(choices=[('text/plain', 'text/plain'), ('text/markdown', 'text/markdown')], default='text/markdown', max_length=15),
        ),
        migrations.AlterField(
            model_name='author',
            name='host',
            field=models.URLField(default='http://127.0.0.1:8000/'),
        ),
        migrations.AlterField(
            model_name='author',
            name='id',
            field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
        ),
        migrations.AlterField(
            model_name='comment',
            name='id',
            field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
        ),
        migrations.AlterField(
            model_name='post',
            name='id',
            field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
        ),
        migrations.AddField(
            model_name='postvisibility',
            name='author',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='socialnet.Author'),
        ),
        migrations.AddField(
            model_name='postvisibility',
            name='post',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='socialnet.Post'),
        ),
        migrations.AddField(
            model_name='friendrequest',
            name='receiver',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='receiver', to='socialnet.Author'),
        ),
        migrations.AddField(
            model_name='friendrequest',
            name='sender',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sender', to='socialnet.Author'),
        ),
    ]


text:
<?php
/**
 * Upgrade API: Language_Pack_Upgrader class
 *
 * @package WordPress
 * @subpackage Upgrader
 * @since 4.6.0
 */

/**
 * Core class used for updating/installing language packs (translations)
 * for plugins, themes, and core.
 *
 * @since 3.7.0
 * @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
 *
 * @see WP_Upgrader
 */
class Language_Pack_Upgrader extends WP_Upgrader {

	/**
	 * Result of the language pack upgrade.
	 *
	 * @since 3.7.0
	 * @var array|WP_Error $result
	 * @see WP_Upgrader::$result
	 */
	public $result;

	/**
	 * Whether a bulk upgrade/installation is being performed.
	 *
	 * @since 3.7.0
	 * @var bool $bulk
	 */
	public $bulk = true;

	/**
	 * Asynchronously upgrades language packs after other upgrades have been made.
	 *
	 * Hooked to the {@see 'upgrader_process_complete'} action by default.
	 *
	 * @since 3.7.0
	 *
	 * @param false|WP_Upgrader $upgrader Optional. WP_Upgrader instance or false. If `$upgrader` is
	 *                                    a Language_Pack_Upgrader instance, the method will bail to
	 *                                    avoid recursion. Otherwise unused. Default false.
	 */
	public static function async_upgrade( $upgrader = false ) {
		// Avoid recursion.
		if ( $upgrader && $upgrader instanceof Language_Pack_Upgrader ) {
			return;
		}

		// Nothing to do?
		$language_updates = wp_get_translation_updates();
		if ( ! $language_updates ) {
			return;
		}

		/*
		 * Avoid messing with VCS installations, at least for now.
		 * Noted: this is not the ideal way to accomplish this.
		 */
		$check_vcs = new WP_Automatic_Updater;
		if ( $check_vcs->is_vcs_checkout( WP_CONTENT_DIR ) ) {
			return;
		}

		foreach ( $language_updates as $key => $language_update ) {
			$update = ! empty( $language_update->autoupdate );

			/**
			 * Filters whether to asynchronously update translation for core, a plugin, or a theme.
			 *
			 * @since 4.0.0
			 *
			 * @param bool   $update          Whether to update.
			 * @param object $language_update The update offer.
			 */
			$update = apply_filters( 'async_update_translation', $update, $language_update );

			if ( ! $update ) {
				unset( $language_updates[ $key ] );
			}
		}

		if ( empty( $language_updates ) ) {
			return;
		}

		// Re-use the automatic upgrader skin if the parent upgrader is using it.
		if ( $upgrader && $upgrader->skin instanceof Automatic_Upgrader_Skin ) {
			$skin = $upgrader->skin;
		} else {
			$skin = new Language_Pack_Upgrader_Skin(
				array(
					'skip_header_footer' => true,
				)
			);
		}

		$lp_upgrader = new Language_Pack_Upgrader( $skin );
		$lp_upgrader->bulk_upgrade( $language_updates );
	}

	/**
	 * Initialize the upgrade strings.
	 *
	 * @since 3.7.0
	 */
	public function upgrade_strings() {
		$this->strings['starting_upgrade'] = __( 'Some of your translations need updating. Sit tight for a few more seconds while we update them as well.' );
		$this->strings['up_to_date']       = __( 'The translations are up to date.' );
		$this->strings['no_package']       = __( 'Update package not available.' );
		/* translators: %s: package URL */
		$this->strings['downloading_package'] = sprintf( __( 'Downloading translation from %s…' ), '%s' );
		$this->strings['unpack_package']      = __( 'Unpacking the update…' );
		$this->strings['process_failed']      = __( 'Translation update failed.' );
		$this->strings['process_success']     = __( 'Translation updated successfully.' );
		$this->strings['remove_old']          = __( 'Removing the old version of the translation…' );
		$this->strings['remove_old_failed']   = __( 'Could not remove the old translation.' );
	}

	/**
	 * Upgrade a language pack.
	 *
	 * @since 3.7.0
	 *
	 * @param string|false $update Optional. Whether an update offer is available. Default false.
	 * @param array        $args   Optional. Other optional arguments, see
	 *                             Language_Pack_Upgrader::bulk_upgrade(). Default empty array.
	 * @return array|bool|WP_Error The result of the upgrade, or a WP_Error object instead.
	 */
	public function upgrade( $update = false, $args = array() ) {
		if ( $update ) {
			$update = array( $update );
		}

		$results = $this->bulk_upgrade( $update, $args );

		if ( ! is_array( $results ) ) {
			return $results;
		}

		return $results[0];
	}

	/**
	 * Bulk upgrade language packs.
	 *
	 * @since 3.7.0
	 *
	 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
	 *
	 * @param object[] $language_updates Optional. Array of language packs to update. @see wp_get_translation_updates().
	 *                                   Default empty array.
	 * @param array    $args {
	 *     Other arguments for upgrading multiple language packs. Default empty array.
	 *
	 *     @type bool $clear_update_cache Whether to clear the update cache when done.
	 *                                    Default true.
	 * }
	 * @return array|bool|WP_Error Will return an array of results, or true if there are no updates,
	 *                             false or WP_Error for initial errors.
	 */
	public function bulk_upgrade( $language_updates = array(), $args = array() ) {
		global $wp_filesystem;

		$defaults    = array(
			'clear_update_cache' => true,
		);
		$parsed_args = wp_parse_args( $args, $defaults );

		$this->init();
		$this->upgrade_strings();

		if ( ! $language_updates ) {
			$language_updates = wp_get_translation_updates();
		}

		if ( empty( $language_updates ) ) {
			$this->skin->header();
			$this->skin->set_result( true );
			$this->skin->feedback( 'up_to_date' );
			$this->skin->bulk_footer();
			$this->skin->footer();
			return true;
		}

		if ( 'upgrader_process_complete' == current_filter() ) {
			$this->skin->feedback( 'starting_upgrade' );
		}

		// Remove any existing upgrade filters from the plugin/theme upgraders #WP29425 & #WP29230
		remove_all_filters( 'upgrader_pre_install' );
		remove_all_filters( 'upgrader_clear_destination' );
		remove_all_filters( 'upgrader_post_install' );
		remove_all_filters( 'upgrader_source_selection' );

		add_filter( 'upgrader_source_selection', array( $this, 'check_package' ), 10, 2 );

		$this->skin->header();

		// Connect to the Filesystem first.
		$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) );
		if ( ! $res ) {
			$this->skin->footer();
			return false;
		}

		$results = array();

		$this->update_count   = count( $language_updates );
		$this->update_current = 0;

		/*
		 * The filesystem's mkdir() is not recursive. Make sure WP_LANG_DIR exists,
		 * as we then may need to create a /plugins or /themes directory inside of it.
		 */
		$remote_destination = $wp_filesystem->find_folder( WP_LANG_DIR );
		if ( ! $wp_filesystem->exists( $remote_destination ) ) {
			if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) {
				return new WP_Error( 'mkdir_failed_lang_dir', $this->strings['mkdir_failed'], $remote_destination );
			}
		}

		$language_updates_results = array();

		foreach ( $language_updates as $language_update ) {

			$this->skin->language_update = $language_update;

			$destination = WP_LANG_DIR;
			if ( 'plugin' == $language_update->type ) {
				$destination .= '/plugins';
			} elseif ( 'theme' == $language_update->type ) {
				$destination .= '/themes';
			}

			$this->update_current++;

			$options = array(
				'package'                     => $language_update->package,
				'destination'                 => $destination,
				'clear_destination'           => true,
				'abort_if_destination_exists' => false, // We expect the destination to exist.
				'clear_working'               => true,
				'is_multi'                    => true,
				'hook_extra'                  => array(
					'language_update_type' => $language_update->type,
					'language_update'      => $language_update,
				),
			);

			$result = $this->run( $options );

			$results[] = $this->result;

			// Prevent credentials auth screen from displaying multiple times.
			if ( false === $result ) {
				break;
			}

			$language_updates_results[] = array(
				'language' => $language_update->language,
				'type'     => $language_update->type,
				'slug'     => isset( $language_update->slug ) ? $language_update->slug : 'default',
				'version'  => $language_update->version,
			);
		}

		// Remove upgrade hooks which are not required for translation updates.
		remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
		remove_action( 'upgrader_process_complete', 'wp_version_check' );
		remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
		remove_action( 'upgrader_process_complete', 'wp_update_themes' );

		/** This action is documented in wp-admin/includes/class-wp-upgrader.php */
		do_action(
			'upgrader_process_complete',
			$this,
			array(
				'action'       => 'update',
				'type'         => 'translation',
				'bulk'         => true,
				'translations' => $language_updates_results,
			)
		);

		// Re-add upgrade hooks.
		add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
		add_action( 'upgrader_process_complete', 'wp_version_check', 10, 0 );
		add_action( 'upgrader_process_complete', 'wp_update_plugins', 10, 0 );
		add_action( 'upgrader_process_complete', 'wp_update_themes', 10, 0 );

		$this->skin->bulk_footer();

		$this->skin->footer();

		// Clean up our hooks, in case something else does an upgrade on this connection.
		remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );

		if ( $parsed_args['clear_update_cache'] ) {
			wp_clean_update_cache();
		}

		return $results;
	}

	/**
	 * Check the package source to make sure there are .mo and .po files.
	 *
	 * Hooked to the {@see 'upgrader_source_selection'} filter by
	 * Language_Pack_Upgrader::bulk_upgrade().
	 *
	 * @since 3.7.0
	 *
	 * @global WP_Filesystem_Base $wp_filesystem Subclass
	 *
	 * @param string|WP_Error $source
	 * @param string          $remote_source
	 */
	public function check_package( $source, $remote_source ) {
		global $wp_filesystem;

		if ( is_wp_error( $source ) ) {
			return $source;
		}

		// Check that the folder contains a valid language.
		$files = $wp_filesystem->dirlist( $remote_source );

		// Check to see if a .po and .mo exist in the folder.
		$po = $mo = false;
		foreach ( (array) $files as $file => $filedata ) {
			if ( '.po' == substr( $file, -3 ) ) {
				$po = true;
			} elseif ( '.mo' == substr( $file, -3 ) ) {
				$mo = true;
			}
		}

		if ( ! $mo || ! $po ) {
			return new WP_Error(
				'incompatible_archive_pomo',
				$this->strings['incompatible_archive'],
				sprintf(
					/* translators: 1: .po, 2: .mo */
					__( 'The language pack is missing either the %1$s or %2$s files.' ),
					'.po',
					'.mo'
				)
			);
		}

		return $source;
	}

	/**
	 * Get the name of an item being updated.
	 *
	 * @since 3.7.0
	 *
	 * @param object $update The data for an update.
	 * @return string The name of the item being updated.
	 */
	public function get_name_for_update( $update ) {
		switch ( $update->type ) {
			case 'core':
				return 'WordPress'; // Not translated

			case 'theme':
				$theme = wp_get_theme( $update->slug );
				if ( $theme->exists() ) {
					return $theme->Get( 'Name' );
				}
				break;
			case 'plugin':
				$plugin_data = get_plugins( '/' . $update->slug );
				$plugin_data = reset( $plugin_data );
				if ( $plugin_data ) {
					return $plugin_data['Name'];
				}
				break;
		}
		return '';
	}

	/**
	 * Clears existing translations where this item is going to be installed into.
	 *
	 * @since 5.1.0
	 *
	 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
	 *
	 * @param string $remote_destination The location on the remote filesystem to be cleared.
	 * @return bool|WP_Error True upon success, WP_Error on failure.
	 */
	public function clear_destination( $remote_destination ) {
		global $wp_filesystem;

		$language_update    = $this->skin->language_update;
		$language_directory = WP_LANG_DIR . '/'; // Local path for use with glob().

		if ( 'core' === $language_update->type ) {
			$files = array(
				$remote_destination . $language_update->language . '.po',
				$remote_destination . $language_update->language . '.mo',
				$remote_destination . 'admin-' . $language_update->language . '.po',
				$remote_destination . 'admin-' . $language_update->language . '.mo',
				$remote_destination . 'admin-network-' . $language_update->language . '.po',
				$remote_destination . 'admin-network-' . $language_update->language . '.mo',
				$remote_destination . 'continents-cities-' . $language_update->language . '.po',
				$remote_destination . 'continents-cities-' . $language_update->language . '.mo',
			);

			$json_translation_files = glob( $language_directory . $language_update->language . '-*.json' );
			if ( $json_translation_files ) {
				foreach ( $json_translation_files as $json_translation_file ) {
					$files[] = str_replace( $language_directory, $remote_destination, $json_translation_file );
				}
			}
		} else {
			$files = array(
				$remote_destination . $language_update->slug . '-' . $language_update->language . '.po',
				$remote_destination . $language_update->slug . '-' . $language_update->language . '.mo',
			);

			$language_directory     = $language_directory . $language_update->type . 's/';
			$json_translation_files = glob( $language_directory . $language_update->slug . '-' . $language_update->language . '-*.json' );
			if ( $json_translation_files ) {
				foreach ( $json_translation_files as $json_translation_file ) {
					$files[] = str_replace( $language_directory, $remote_destination, $json_translation_file );
				}
			}
		}

		$files = array_filter( $files, array( $wp_filesystem, 'exists' ) );

		// No files to delete.
		if ( ! $files ) {
			return true;
		}

		// Check all files are writable before attempting to clear the destination.
		$unwritable_files = array();

		// Check writability.
		foreach ( $files as $file ) {
			if ( ! $wp_filesystem->is_writable( $file ) ) {
				// Attempt to alter permissions to allow writes and try again.
				$wp_filesystem->chmod( $file, FS_CHMOD_FILE );
				if ( ! $wp_filesystem->is_writable( $file ) ) {
					$unwritable_files[] = $file;
				}
			}
		}

		if ( ! empty( $unwritable_files ) ) {
			return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) );
		}

		foreach ( $files as $file ) {
			if ( ! $wp_filesystem->delete( $file ) ) {
				return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] );
			}
		}

		return true;
	}
}


text:
namespace CPlusPlus {

class CPLUSPLUS_EXPORT NameVisitor
{
    NameVisitor(const NameVisitor &other);
    void operator =(const NameVisitor &other);

public:
    NameVisitor();
    virtual ~NameVisitor();

    void accept(const Name *name);

    virtual bool preVisit(const Name *) { return true; }
    virtual void postVisit(const Name *) {}

    virtual void visit(const AnonymousNameId *) {}
    virtual void visit(const Identifier *) {}
    virtual void visit(const TemplateNameId *) {}
    virtual void visit(const DestructorNameId *) {}
    virtual void visit(const OperatorNameId *) {}
    virtual void visit(const ConversionNameId *) {}
    virtual void visit(const QualifiedNameId *) {}
    virtual void visit(const SelectorNameId *) {}
};

} // namespace CPlusPlus

#endif // CPLUSPLUS_NAMEVISITOR_H


text:
package com.danielkueffer.filehosting.auth;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

import com.danielkueffer.filehosting.persistence.model.User;
import com.danielkueffer.filehosting.rest.auth.RestLoggedIn;

/**
 * The AuthManager
 *
 * @author dkueffer
 *
 */
@Named
@SessionScoped
public class AuthManager implements Serializable {

	private static final long serialVersionUID = -1997507066926190203L;

	public AuthManager() {
	}

	@Inject
	@LoggedIn
	User currentUser;

	@Inject
	@RestLoggedIn
	User restUser;

	/**
	 * Get the current user
	 *
	 * @return
	 */
	public User getCurrentUser() {
		if (currentUser != null) {
			return currentUser;
		} else {
			return restUser;
		}
	}
}


text:
  <title>Links test</title>

Navigate
JavaScript


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, SoundRecordAndAnalysisActivity!</string>
    <string name="app_name">SoundRecordAndAnalysis</string>
    <color name="background">#FFFFFF</color>

</resources>


text:
package org.optaplanner.core.impl.heuristic.selector.common.iterator;

import java.util.Iterator;

import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.heuristic.selector.entity.EntitySelector;
import org.optaplanner.core.impl.heuristic.selector.value.ValueSelector;

public abstract class AbstractRandomChangeIterator<S extends Move> extends UpcomingSelectionIterator<S> {

    private final EntitySelector entitySelector;
    private final ValueSelector valueSelector;

    private Iterator<Object> entityIterator;

    public AbstractRandomChangeIterator(EntitySelector entitySelector, ValueSelector valueSelector) {
        this.entitySelector = entitySelector;
        this.valueSelector = valueSelector;
        entityIterator = entitySelector.iterator();
        // Don't do hasNext() in constructor (to avoid upcoming selections breaking mimic recording)
    }

    @Override
    protected S createUpcomingSelection() {
        // Ideally, this code should have read:
        //     Object entity = entityIterator.next();
        //     Iterator<Object> valueIterator = valueSelector.iterator(entity);
        //     Object toValue = valueIterator.next();
        // But empty selectors and ending selectors (such as non-random or shuffled) make it more complex
        if (!entityIterator.hasNext()) {
            entityIterator = entitySelector.iterator();
            if (!entityIterator.hasNext()) {
                return noUpcomingSelection();
            }
        }
        Object entity = entityIterator.next();

        Iterator<Object> valueIterator = valueSelector.iterator(entity);
        int entityIteratorCreationCount = 0;
        // This loop is mostly only relevant when the entityIterator or valueIterator is non-random or shuffled
        while (!valueIterator.hasNext()) {
            // Try the next entity
            if (!entityIterator.hasNext()) {
                entityIterator = entitySelector.iterator();
                entityIteratorCreationCount++;
                if (entityIteratorCreationCount >= 2) {
                    // All entity-value combinations have been tried (some even more than once)
                    return noUpcomingSelection();
                }
            }
            entity = entityIterator.next();
            valueIterator = valueSelector.iterator(entity);
        }
        Object toValue = valueIterator.next();
        return newChangeSelection(entity, toValue);
    }

    protected abstract S newChangeSelection(Object entity, Object toValue);

}


text: int copy_file(char *src, char *dst);


text:
import module from '../../tests/helpers/module-for-acceptance';
import { test } from '../helpers/qunit';
import { visit, currentURL } from 'ember-native-dom-helpers';

module('Acceptance | index');

test('visiting /', async function(assert) {
  await visit('/');
  assert.equal(currentURL(), '/');
});


text:
var xmpp = require('node-xmpp-client');
var ltx = require('node-xmpp-core').ltx;

var HangManClient = function (settings, auth)
{
    this.connection = new xmpp.Client({
        port: settings.googleTalk.port,
        host: settings.googleTalk.host,
        jid: auth.jid,
        password: auth.password
    });

    this.send = function (recipient, msg)
    {
        var stanza = new ltx.Element(
            'message', {
                to: recipient,
                type: 'chat'
            })
            .c('body').t(msg);

        console.log(stanza);

        this.connection.send(stanza);
    };

    this.connection.on('stanza', function (stanza)
    {
        console.log(JSON.stringify(stanza));
    });

    this.connection.addListener('online', function (data)
    {
        console.log(data);
    });

    this.connection.addListener('error', function (e)
    {
        console.error(e);
        process.exit(1);
    });
};

module.exports = {
    HangManClient: HangManClient
}


text:
#include "mirtk/GaussianBlurring.h"

#include "mirtk/Math.h"
#include "mirtk/ScalarFunctionToImage.h"
#include "mirtk/ScalarGaussian.h"

namespace mirtk {

// -----------------------------------------------------------------------------
template <class VoxelType>
GaussianBlurring<VoxelType>::GaussianBlurring(double sigma)
:
  GaussianBlurring<VoxelType>::GaussianBlurring(sigma, sigma, sigma, 0.)
{
}

// -----------------------------------------------------------------------------
template <class VoxelType>
GaussianBlurring<VoxelType>::GaussianBlurring(double xsigma, double ysigma, double zsigma, double tsigma)
:
  _SigmaX(xsigma),
  _SigmaY(ysigma),
  _SigmaZ(zsigma),
  _SigmaT(tsigma)
{
}

// -----------------------------------------------------------------------------
template <class VoxelType>
GaussianBlurring<VoxelType>::~GaussianBlurring()
{
}

// -----------------------------------------------------------------------------
template <class VoxelType>
void GaussianBlurring<VoxelType>::SetSigma(double sigma)
{
  _SigmaX = _SigmaY = _SigmaZ = sigma;
  _SigmaT = 0.;
}

// -----------------------------------------------------------------------------
template <class VoxelType>
void GaussianBlurring<VoxelType>::SetSigma(double xsigma, double ysigma, double zsigma, double tsigma)
{
  _SigmaX = xsigma;
  _SigmaY = ysigma;
  _SigmaZ = zsigma;
  _SigmaT = tsigma;
}

// -----------------------------------------------------------------------------
template <class VoxelType>
int GaussianBlurring<VoxelType>::KernelSize(double sigma)
{
  return 2 * ifloor(3.0 * sigma) + 1;
}

// -----------------------------------------------------------------------------
template <class VoxelType>
UniquePtr<typename GaussianBlurring<VoxelType>::KernelType>
GaussianBlurring<VoxelType>::InitializeKernel(double sigma)
{
  // Create filter kernel for 1D Gaussian function
  UniquePtr<KernelType> kernel(new KernelType(KernelSize(sigma), 1, 1));

  // Create scalar function which corresponds to a 1D Gaussian function
  ScalarGaussian gaussian(sigma,           0., 0.,  // stddev in x, y, z
                          kernel->X() / 2, 0., 0.); // center in x, y, z

  // Convert from scalar function to filter kernel
  for (int i = 0; i < kernel->X(); ++i) {
    kernel->PutAsDouble(i, gaussian.Evaluate(i));
  }

  return kernel;
}

// -----------------------------------------------------------------------------
template <class VoxelType>
void GaussianBlurring<VoxelType>::Initialize()
{
  // Initialize base class
  SeparableConvolution<VoxelType>::Initialize();

  // Instantiate convolution kernels
  const ImageType *input  = this->Input();
  if (!AreEqual(_SigmaX, 0.) && input->X() > 1) {
    _GaussianKernel[0] = this->InitializeKernel(_SigmaX / input->XSize());
  } else {
    _GaussianKernel[0].reset();
  }
  if (!AreEqual(_SigmaY, 0.) && input->Y() > 1) {
    _GaussianKernel[1] = this->InitializeKernel(_SigmaY / input->YSize());
  } else {
    _GaussianKernel[1].reset();
  }
  if (!AreEqual(_SigmaZ, 0.) && input->Z() > 1 && !AreEqual(input->ZSize(), 0.)) {
    _GaussianKernel[2] = this->InitializeKernel(_SigmaZ / input->ZSize());
  } else {
    _GaussianKernel[2].reset();
  }
  if (!AreEqual(_SigmaT, 0.) && input->T() > 1 && !AreEqual(input->TSize(), 0.)) {
    _GaussianKernel[3] = this->InitializeKernel(_SigmaT / input->TSize());
  } else {
    _GaussianKernel[3].reset();
  }

  // Set kernels
  this->_KernelX = _GaussianKernel[0].get();
  this->_KernelY = _GaussianKernel[1].get();
  this->_KernelZ = _GaussianKernel[2].get();
  this->_KernelT = _GaussianKernel[3].get();
}

// =============================================================================
// Explicit template instantiations
// =============================================================================

template class GaussianBlurring<unsigned char>;
template class GaussianBlurring<short>;
template class GaussianBlurring<unsigned short>;
template class GaussianBlurring<float>;
template class GaussianBlurring<double>;

} // namespace mirtk


text:
using System;
/*Problem 3. Divide by 7 and 5

Write a Boolean expression that checks for given integer if it can be divided (without remainder) by 7 and 5 at the same time.*/

namespace DivideBy7And5
{
    class DivideBy7And5
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please write integer number:");
            int number = int.Parse(Console.ReadLine());
            bool result = (number % 5 == 0) && (number % 7 == 0);
            Console.WriteLine(result ? "Divided by 7 and 5 at the same time" : "Not divided by 7 and 5 at the same time");
        }
    }
}


text:
{% extends "base.html" %}

{% block title %}Bookmark an image{% endblock %}

{% block content %}

Bookmark an image

         <form action="." method="POST" enctype="multipart/form-data">
             {% csrf_token %}
             {{ form.as_p }}
           <input type="submit" value="Bookmark it!" class="btn" />
         </form>

{% endblock %}


text:
<?php

declare(strict_types=1);

namespace Tests\View\Console;

use Leevel\Di\IContainer;
use Leevel\Filesystem\Helper;
use Leevel\Kernel\App as Apps;
use Leevel\Kernel\IApp;
use Leevel\Option\Option;
use Leevel\View\Console\Cache;
use Leevel\View\Manager;
use Tests\Console\BaseCommand;
use Tests\TestCase;

class CacheTest extends TestCase
{
    use BaseCommand;

    protected function tearDown(): void
    {
        if (is_dir($cacheDirPath = __DIR__.'/cache_app')) {
            Helper::deleteDirectory($cacheDirPath);
        }
    }

    public function testBaseUse(): void
    {
        $result = '';
        $this->obGetContents(function () use (&$result) {
            $result = $this->runCommand(
                new Cache(),
                [
                    'command' => 'view:cache',
                ],
                function ($container) {
                    $this->initContainerService($container);
                }
            );
        });

        $result = $this->normalizeContent($result);
        $this->assertStringContainsString(
            $this->normalizeContent('Start to cache view.'),
            $result,
        );
        $this->assertStringContainsString(
            $this->normalizeContent(sprintf('Start to compiles path `%s`', __DIR__.'/assert')),
            $result,
        );
        $this->assertStringContainsString(
            $this->normalizeContent('View files cache successed.'),
            $result,
        );

        $this->assertDirectoryExists(__DIR__.'/cache_app/themes');
    }

    protected function initContainerService(IContainer $container): void
    {
        $app = new AppForCache($container, '');
        $this->assertInstanceof(IApp::class, $app);
        $container->singleton('app', $app);
        $container->alias('app', IApp::class);
        $this->makeViewViews($container);
    }

    protected function makeViewViews(IContainer $container): void
    {
        $option = new Option([
            'view' => [
                'default'               => 'html',
                'action_fail'           => 'public/fail',
                'action_success'        => 'public/success',
                'connect'               => [
                    'html' => [
                        'driver'         => 'html',
                        'suffix'         => '.html',
                    ],
                    'phpui' => [
                        'driver' => 'phpui',
                        'suffix' => '.php',
                    ],
                ],
            ],
        ]);
        $container->singleton('option', $option);

        $container
            ->singleton(
                'views',
                fn (IContainer $container): Manager => new Manager($container),
            );
    }
}

class AppForCache extends Apps
{
    public function themesPath(string $path = ''): string
    {
        return __DIR__.'/assert';
    }

    public function storagePath(string $path = ''): string
    {
        return __DIR__.'/cache_'.$path;
    }

    protected function registerBaseProvider(): void
    {
    }
}


text:
package com.thinkbiganalytics.nifi.provenance.model.stats;

import com.thinkbiganalytics.nifi.provenance.model.ProvenanceEventRecordDTO;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Group Stats by Feed and Processor
 */
public class AggregatedFeedProcessorStatistics implements Serializable {

    String feedName;
    String processGroup;
    Map<String, AggregatedProcessorStatistics> processorStats = new ConcurrentHashMap<>();
    private String collectionId;
    private Long totalEvents = 0L;
    private Long minEventId = 0L;
    private Long maxEventId = 0L;

    public AggregatedFeedProcessorStatistics() {
    }

    public AggregatedFeedProcessorStatistics(String feedName, String collectionId) {
        this.feedName = feedName;
        this.collectionId = collectionId;
    }

    /**
     * Add the event to compute statistics
     */
    public void addEventStats(ProvenanceEventRecordDTO event) {
        processorStats.computeIfAbsent(event.getComponentId(), processorId -> new AggregatedProcessorStatistics(processorId, event.getComponentName(), collectionId)).add(event);
        totalEvents++;
        if (event.getEventId() < minEventId) {
            minEventId = event.getEventId();
        }
        if (event.getEventId() > maxEventId) {
            maxEventId = event.getEventId();
        }
        if (StringUtils.isBlank(processGroup) && StringUtils.isNotBlank(event.getFeedProcessGroupId())) {
            processGroup = event.getFeedProcessGroupId();
        }
    }

    public String getFeedName() {
        return feedName;
    }

    public void setFeedName(String feedName) {
        this.feedName = feedName;
    }

    public String getProcessGroup() {
        return processGroup;
    }

    public Long getMaxEventId() {
        return maxEventId;
    }

    public Map<String, AggregatedProcessorStatistics> getProcessorStats() {
        return processorStats;
    }

    public void clear(String newCollectionId) {
        this.collectionId = newCollectionId;
        processorStats.entrySet().forEach(e -> e.getValue().clear());
    }
}


text:
require 'capistrano/all'
require 'capistrano/setup'
require 'capistrano/deploy'

require 'rvm1/capistrano3'
load File.expand_path('../tasks/vmf.cap', __FILE__)
load File.expand_path('../tasks/redis.cap', __FILE__)
load File.expand_path('../tasks/files.cap', __FILE__)


text:
package com.tazzie02.tazbot.helpers.structures;

import java.util.Calendar;
import java.util.TimeZone;

public class Counter implements Comparable<Counter> {
	private String key;
	private int value;
	private long time;

	public Counter(String key, int value) {
		this.key = key;
		this.value = value;
		this.time = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis();
	}

	public String getKey() {
		return this.key;
	}

	public int getValue() {
		return this.value;
	}

	public long getTime() {
		return this.time;
	}

	public void incrementValue() {
		this.value++;
		this.time = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis();
	}

	public void setValue(int value) {
		this.value = value;
		this.time = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis();
	}

	@Override
	public int compareTo(Counter o) {
		return o.getValue() - getValue();
	}
}


text:
package org.hojeehdiaderua.utils;

import org.hojeehdiaderua.beans.Resultado;
import org.hojeehdiaderua.beans.Status;

public class ResultadoUtil<T> {

    public Resultado<T> comSucesso(T resultado) {
        Resultado<T> resultadoFinal = novo(Status.SUCCESS);
        resultadoFinal.setMensagem("Processamento concluído com sucesso");
        resultadoFinal.setResultado(resultado);

        return resultadoFinal;
    }

    public Resultado<T> comFalha(T resultado) {
        Resultado<T> resultadoFinal = novo(Status.ERROR);
        resultadoFinal.setMensagem("Houve uma falha no processamento da requisição");
        resultadoFinal.setResultado(resultado);

        return resultadoFinal;
    }

    private Resultado<T> novo(Status status) {
        Resultado<T> resultadoFinal = new Resultado<>();

        resultadoFinal.setStatus(status);

        return resultadoFinal;
    }

}