text:
#include "RoomsBrowserGFx3_RakNet.h"
#include "Lobby2Client.h"
#include "XMLParser.h"
#include "MessageIdentifiers.h"
#include "RoomTypes.h"
#include "GetTime.h"

using namespace RakNet;

// ---------------------------------------------------------------------------------------

void ServerAndRoomBrowserData::Serialize(RakNet::BitStream *bitStream, bool writeToBitstream)
{
	bitStream->Serialize(writeToBitstream, numPlayers);
	bitStream->Serialize(writeToBitstream, maxPlayers);
	bitStream->Serialize(writeToBitstream, mapName);
	bitStream->Serialize(writeToBitstream, roomName);
	bitStream->Serialize(writeToBitstream, roomId);

}
void ServerAndRoomBrowserData::WriteToTable(DataStructures::Table *table)
{
	table->Clear();
	DataStructures::Table::Cell cells[4];
	table->AddColumn("numPlayers", DataStructures::Table::NUMERIC);
	cells[0].Set((unsigned int) numPlayers);
	table->AddColumn("maxPlayers", DataStructures::Table::NUMERIC);
	cells[1].Set((unsigned int) maxPlayers);
	table->AddColumn("mapName", DataStructures::Table::STRING);
	cells[2].Set(mapName.C_String());
	table->AddColumn("roomName", DataStructures::Table::STRING); // "Room name" from RoomTypes.cpp, write this here?
	cells[3].Set(roomName.C_String());
	// The rooms plugin uses this table, and the rooms plugin automatically assigns a room id
//	table->AddColumn(DefaultRoomColumns::GetColumnName(DefaultRoomColumns::TC_ROOM_ID), DataStructures::Table::NUMERIC);
//	cells[4].Set((double) roomId.g);
	RakAssert(table->GetColumnCount()==4);
	DataStructures::List<DataStructures::Table::Cell*> initialCellValues;
	for (int i=0; i < 4; i++)
		initialCellValues.Push(&cells[i],_FILE_AND_LINE_);
	table->AddRow(table->GetRowCount(), initialCellValues, true);
}
void ServerAndRoomBrowserData::SetAsOfflinePingResponse(RakNet::RakPeerInterface *rakPeer)
{
	RakNet::BitStream bs;
	Serialize(&bs,true);
	rakPeer->SetOfflinePingResponse((const char*) bs.GetData(),bs.GetNumberOfBytesUsed());
}

// ---------------------------------------------------------------------------------------

RoomsBrowserGFx3_RakNet::RoomsBrowserGFx3_RakNet()
{
}
RoomsBrowserGFx3_RakNet::~RoomsBrowserGFx3_RakNet()
{
	Shutdown();
}
void RoomsBrowserGFx3_RakNet::Init(RakNet::Lobby2Client *_lobby2Client,
								   RakNet::Lobby2MessageFactory *_messageFactory,
								   RakPeerInterface *_rakPeer,
								   RakNet::RoomsPlugin *_roomsPlugin,
								   RakNet::RakString _titleName,
								   RakNet::RakString _titleSecretKey,
								   RakNet::RakString _pathToXMLPropertyFile,
								   unsigned short _lanServerPort,
								   GPtr<FxDelegate> pDelegate,
								   GPtr<GFxMovieView> pMovie)
{
	RoomsBrowserGFx3::Init(pDelegate, pMovie);

	lobby2Client=_lobby2Client;
	msgFactory=_messageFactory;
	rakPeer=_rakPeer;
	roomsPlugin=_roomsPlugin;
	titleName=_titleName;
	titleSecretKey=_titleSecretKey;
	pathToXMLPropertyFile=_pathToXMLPropertyFile;
	lanServerPort=_lanServerPort;

	RoomsErrorCodeDescription::Validate();

	roomsPlugin->SetRoomsCallback(this);
}
void RoomsBrowserGFx3_RakNet::Update(void)
{

}
void RoomsBrowserGFx3_RakNet::Shutdown(void)
{
	RoomsBrowserGFx3::Shutdown();
}
void RoomsBrowserGFx3_RakNet::SaveProperty(const char *propertyId, const char *propertyValue)
{
	// this open and parse the XML file:
	XMLNode xMainNode=XMLNode::openFileHelper(pathToXMLPropertyFile.C_String(),"");
	if (xMainNode.isEmpty())
	{
		xMainNode=XMLNode::createXMLTopNode("");
	}
	XMLNode xNode=xMainNode.getChildNode(propertyId);
	if (xNode.isEmpty()==false)
	{
		xNode.deleteAttribute(0);
		xNode.addAttribute("value", propertyValue);
	}
	else
	{
		xNode = xMainNode.addChild(propertyId);
		xNode.addAttribute("value", propertyValue);
	}
	xMainNode.writeToFile(pathToXMLPropertyFile.C_String());
}
void RoomsBrowserGFx3_RakNet::LoadProperty(const char *propertyId, RakNet::RakString &propertyOut)
{
	XMLNode xMainNode=XMLNode::openFileHelper(pathToXMLPropertyFile.C_String(),"");
	if (xMainNode.isEmpty())
		return;
	XMLNode xNode=xMainNode.getChildNode(propertyId);
	LPCTSTR attr = xNode.getAttribute("value", 0);
	if (attr)
		propertyOut = attr;
	else
		propertyOut.Clear();
}
void RoomsBrowserGFx3_RakNet::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason )
{
	if (systemAddress==lobby2Client->GetServerAddress())
	{
		// lost connection
		FxResponseArgs<1> rargs;
		switch (lostConnectionReason)
		{
		case LCR_CLOSED_BY_USER:
			rargs.Add("LCR_CLOSED_BY_USER");
			break;
		case LCR_DISCONNECTION_NOTIFICATION:
			rargs.Add("LCR_DISCONNECTION_NOTIFICATION");
			break;
		case LCR_CONNECTION_LOST:
			rargs.Add("LCR_CONNECTION_LOST");
			break;
		}
		FxDelegate::Invoke2(movie, "c2f_NotifyServerConnectionLost", rargs);
	}
}
void RoomsBrowserGFx3_RakNet::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)
{
	if (systemAddress==lobby2Client->GetServerAddress())
	{
		// is connected
		FxResponseArgs<0> rargs;
		FxDelegate::Invoke2(movie, "c2f_NotifyConnectionAttemptToServerSuccess", rargs);
	}
	else
	{
		FxResponseArgs<3> rargs;
		char saString[64];
		systemAddress.ToString(true,saString);
		char guidString[64];
		rakNetGUID.ToString(guidString);
		rargs.Add(saString);
		rargs.Add(guidString);
		rargs.Add(isIncoming);
		FxDelegate::Invoke2(movie, "c2f_NotifyNewConnection", rargs);
	}
}
void RoomsBrowserGFx3_RakNet::OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason)
{
	// isn't connected
	FxResponseArgs<2> rargs;
	switch(failedConnectionAttemptReason)
	{
	case FCAR_CONNECTION_ATTEMPT_FAILED:
		rargs.Add("FCAR_CONNECTION_ATTEMPT_FAILED");
		break;
	case FCAR_ALREADY_CONNECTED:
		rargs.Add("FCAR_ALREADY_CONNECTED");
		break;
	case FCAR_NO_FREE_INCOMING_CONNECTIONS:
		rargs.Add("FCAR_NO_FREE_INCOMING_CONNECTIONS");
		break;
	case FCAR_SECURITY_PUBLIC_KEY_MISMATCH:
		rargs.Add("FCAR_SECURITY_PUBLIC_KEY_MISMATCH");
		break;
	case FCAR_CONNECTION_BANNED:
		rargs.Add("FCAR_CONNECTION_BANNED");
		break;
	case FCAR_INVALID_PASSWORD:
		rargs.Add("FCAR_INVALID_PASSWORD");
		break;
	case FCAR_INCOMPATIBLE_PROTOCOL:
		rargs.Add("FCAR_INCOMPATIBLE_PROTOCOL");
		break;
	case FCAR_IP_RECENTLY_CONNECTED:
		rargs.Add("FCAR_IP_RECENTLY_CONNECTED");
		break;
	case FCAR_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY:
		rargs.Add("FCAR_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY");
		break;
	case FCAR_OUR_SYSTEM_REQUIRES_SECURITY:
		rargs.Add("FCAR_OUR_SYSTEM_REQUIRES_SECURITY");
		break;
	case FCAR_PUBLIC_KEY_MISMATCH:
		rargs.Add("FCAR_PUBLIC_KEY_MISMATCH");
		break;
	}

	char saString[64];
	packet->systemAddress.ToString(true,saString);
	rargs.Add(saString);

	if (packet->systemAddress==lobby2Client->GetServerAddress())
		FxDelegate::Invoke2(movie, "c2f_NotifyConnectionAttemptToServerFailure", rargs);
	else
		FxDelegate::Invoke2(movie, "c2f_NotifyFailedConnectionAttempt", rargs);
}
PluginReceiveResult RoomsBrowserGFx3_RakNet::OnReceive(Packet *packet)
{
	switch (packet->data[0])
	{
	case ID_UNCONNECTED_PONG:
		if (packet->systemAddress.GetPort()>=lanServerPort && packet->systemAddress.GetPort()<lanServerPort+8 && packet->length>sizeof(RakNet::TimeMS)+sizeof(MessageID)
			// && packet->guid!=rakPeer->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS)
			)
		{
			RakNet::BitStream bsIn(packet->data+1,packet->length-1,false);
			RakNet::TimeMS pingResponse;
			bsIn.Read(pingResponse);
			RakNet::TimeMS elapsedPing=RakNet::GetTimeMS()-pingResponse;
			RakNet::TimeMS elapsedPingMs;
#if __GET_TIME_64BIT==1
			elapsedPingMs=elapsedPing/1000;
#else
			elapsedPingMs=elapsedPing;
#endif

			// This was set in RakPeerInterface::SetOfflinePingResponse, by using ServerWANUpdate::SetAsOfflinePingResponse()
			ServerAndRoomBrowserData browserData;
			browserData.Serialize(&bsIn,false);

			FxResponseArgsList rargs;
			rargs.Add(false);
			rargs.Add((Double)browserData.roomId.g);
			char ipAddr[64];
			packet->systemAddress.ToString(true,ipAddr);
			rargs.Add(ipAddr);
			rargs.Add(browserData.roomName.C_String());
			rargs.Add((Double)browserData.numPlayers);
			rargs.Add((Double)browserData.maxPlayers);
			rargs.Add(browserData.mapName.C_String());

			FxDelegate::Invoke2(movie, "c2f_AddSingleRoom", rargs);
		}
		break;
	}

	return RR_CONTINUE_PROCESSING;
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_ConnectToServer)
{
	bool callSucceeded = rakPeer->Connect(pparams[0].GetString(), atoi(pparams[1].GetString()), 0, 0)==RakNet::CONNECTION_ATTEMPT_STARTED;
	FxResponseArgs<1> rargs;
	rargs.Add(callSucceeded);
	lobby2Client->SetServerAddress(SystemAddress(pparams[0].GetString(), atoi(pparams[1].GetString())));
	roomsPlugin->SetServerAddress(lobby2Client->GetServerAddress());
	// pparams.Respond(rargs);

	FxDelegate::Invoke2(movie, pparams[2].GetString(), rargs);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_Login)
{
	Client_Login *arg = (Client_Login *) msgFactory->Alloc(L2MID_Client_Login);
	arg->titleName=titleName;
	arg->titleSecretKey=titleSecretKey;
	arg->userName=pparams[0].GetString();
	arg->userPassword=pparams[1].GetString();
	loginUsername=arg->userName;

	lobby2Client->SendMsgAndDealloc(arg);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_RegisterAccount)
{
	RakNet::Client_RegisterAccount *arg = (RakNet::Client_RegisterAccount *) msgFactory->Alloc(L2MID_Client_RegisterAccount);
	arg->userName=pparams[0].GetString();
	loginUsername=arg->userName;
	arg->createAccountParameters.password=pparams[1].GetString();
	arg->titleName=titleName;
	lobby2Client->SendMsgAndDealloc(arg);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_UpdateRoomsList)
{
	bool isNetUpdate = pparams[0].GetBool();
	if (isNetUpdate)
	{
		SearchByFilter_Func func;
		func.roomQuery.queries=0;
		func.roomQuery.numQueries=0;
		func.onlyJoinable=false;
		func.gameIdentifier=titleName;
		func.userName=loginUsername;
		roomsPlugin->ExecuteFunc(&func);
	}
	else
	{
		// Ping out looking for game servers. We can't find servers unless they all use the same port
		// Up to 8 instances on the same machine is reasonable
		for (int i=0; i < 8; i++)
		{
			rakPeer->Ping("255.255.255.255", lanServerPort+i, false);
		}
	}
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_UpdateFriendsList)
{
	RakNet::Friends_GetFriends *arg = (RakNet::Friends_GetFriends *) msgFactory->Alloc(L2MID_Friends_GetFriends);
	lobby2Client->SendMsgAndDealloc(arg);
	RakNet::Friends_GetInvites *arg2 = (RakNet::Friends_GetInvites *) msgFactory->Alloc(L2MID_Friends_GetInvites);
	lobby2Client->SendMsgAndDealloc(arg2);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_JoinByFilter)
{
	if (pparams.GetArgCount()<1)
		return;

	RakNet::JoinByFilter_Func func;
	func.userName=loginUsername;
	func.gameIdentifier=titleName;
	func.roomMemberMode=RMM_ANY_PLAYABLE;

	bool roomIsFromServer=pparams[0].GetBool();
	double roomGuid=pparams[1].GetNumber();

	if (roomIsFromServer)
	{
		// See RoomTypes.h for other default columns
		func.query.AddQuery_NUMERIC( DefaultRoomColumns::GetColumnName(DefaultRoomColumns::TC_ROOM_ID), roomGuid);
		roomsPlugin->ExecuteFunc(&func);
	}
	else
	{
		SystemAddress sa;
		sa.FromString(pparams[2].GetString());
		char ipPart[32];
		sa.ToString(false,ipPart);
		rakPeer->Connect(ipPart,sa.GetPort(),0,0);
	}

}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_CreateRoom)
{
	/// Create a room for the WAN browser
	RakNet::CreateRoom_Func func;
	func.networkedRoomCreationParameters.slots.publicSlots=(unsigned int) pparams[2].GetNumber();
	func.networkedRoomCreationParameters.slots.reservedSlots=(unsigned int) pparams[3].GetNumber();
	func.networkedRoomCreationParameters.slots.spectatorSlots=0;
	func.networkedRoomCreationParameters.hiddenFromSearches=pparams[4].GetBool();
	func.networkedRoomCreationParameters.destroyOnModeratorLeave=false;
	func.networkedRoomCreationParameters.autoLockReadyStatus=true;
	if (pparams[4].GetBool()==true) // Room members can invite
		func.networkedRoomCreationParameters.inviteToRoomPermission=NetworkedRoomCreationParameters::INVITE_MODE_ANYONE_CAN_INVITE;
	else
		func.networkedRoomCreationParameters.inviteToRoomPermission=NetworkedRoomCreationParameters::INVITE_MODE_MODERATOR_CAN_INVITE;
	func.networkedRoomCreationParameters.inviteToSpectatorSlotPermission=NetworkedRoomCreationParameters::INVITE_MODE_ANYONE_CAN_INVITE;
	func.networkedRoomCreationParameters.clearInvitesOnNewModerator=true;
	func.networkedRoomCreationParameters.roomName=pparams[0].GetString();
	if (func.networkedRoomCreationParameters.roomName.IsEmpty())
		func.networkedRoomCreationParameters.roomName=loginUsername + "'s room";
	func.gameIdentifier=titleName;

	ServerAndRoomBrowserData browserData;
	browserData.roomId=rakPeer->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS);
	browserData.numPlayers=0;
	browserData.maxPlayers=func.networkedRoomCreationParameters.slots.publicSlots+func.networkedRoomCreationParameters.slots.reservedSlots;
	browserData.mapName=pparams[1].GetString();
	browserData.roomName=func.networkedRoomCreationParameters.roomName;
	browserData.SetAsOfflinePingResponse(rakPeer);

	browserData.WriteToTable(&func.initialRoomProperties);

	bool isLanGame = pparams[6].GetBool();
	if (isLanGame)
	{
		FxResponseArgsList rargs;
		rargs.Add(RoomsErrorCodeDescription::ToEnum(REC_SUCCESS));
		rargs.Add(true);
		FxDelegate::Invoke2(movie, "c2f_CreateRoom", rargs);
		return;
	}

	func.userName=loginUsername;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_Friends_SendInvite)
{
	RakNet::Friends_SendInvite *arg = (RakNet::Friends_SendInvite *) msgFactory->Alloc(L2MID_Friends_SendInvite);
	arg->targetHandle=pparams[0].GetString();
	lobby2Client->SendMsgAndDealloc(arg);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_Friends_Remove)
{
	RakNet::Friends_Remove *arg = (RakNet::Friends_Remove *) msgFactory->Alloc(L2MID_Friends_Remove);
	arg->targetHandle=pparams[0].GetString();
	lobby2Client->SendMsgAndDealloc(arg);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_Friends_AcceptInvite)
{
	RakNet::Friends_AcceptInvite *arg = (RakNet::Friends_AcceptInvite *) msgFactory->Alloc(L2MID_Friends_AcceptInvite);
	arg->targetHandle=pparams[0].GetString();
	lobby2Client->SendMsgAndDealloc(arg);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_Friends_RejectInvite)
{
	RakNet::Friends_RejectInvite *arg = (RakNet::Friends_RejectInvite *) msgFactory->Alloc(L2MID_Friends_RejectInvite);
	arg->targetHandle=pparams[0].GetString();
	lobby2Client->SendMsgAndDealloc(arg);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_Directed_Chat_Func)
{
	Chat_Func func;
	func.userName=loginUsername;
	func.chatMessage=pparams[1].GetString();
	func.privateMessageRecipient=pparams[0].GetString();
	func.chatDirectedToRoom=false;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_Room_Chat_Func)
{
	Chat_Func func;
	func.userName=loginUsername;
	func.chatMessage=pparams[0].GetString();
	func.chatDirectedToRoom=true;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_Logoff)
{
	RakNet::Client_Logoff *arg = (RakNet::Client_Logoff *) msgFactory->Alloc(L2MID_Client_Logoff);
	lobby2Client->SendMsgAndDealloc(arg);
}
//////////////////////////////////////////////////////////////////................................................
//////////////////////////////////////////////////////////////////................................................
//////////////////////////////////////////////////////////////////................................................
//////////////////////////////////////////////////////////////////................................................
//////////////////////////////////////////////////////////////////................................................
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_LeaveRoom)
{
	LeaveRoom_Func func;
	func.userName=loginUsername;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_SendInvite)
{
	SendInvite_Func func;
	func.userName=loginUsername;
	func.inviteeName=pparams[0].GetString();
	func.inviteToSpectatorSlot=pparams[1].GetBool();
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_StartSpectating)
{
	StartSpectating_Func func;
	func.userName=loginUsername;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_StopSpectating)
{
	StopSpectating_Func func;
	func.userName=loginUsername;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_GrantModerator)
{
	GrantModerator_Func func;
	func.userName=loginUsername;
	func.newModerator=pparams[0].GetString();
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_SetReadyStatus)
{
	SetReadyStatus_Func func;
	func.userName=loginUsername;
	func.isReady=pparams[0].GetBool();
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_GetReadyStatus)
{
	GetReadyStatus_Func func;
	func.userName=loginUsername;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_SetRoomLockState)
{
	SetRoomLockState_Func func;
	func.userName=loginUsername;
	RakNet::RakString lockState=pparams[0].GetString();
	if (lockState=="NOT_LOCKED")
		func.roomLockState=RLS_NOT_LOCKED;
	else if (lockState=="PLAYERS_LOCKED")
		func.roomLockState=RLS_PLAYERS_LOCKED;
	else if (lockState=="ALL_LOCKED")
		func.roomLockState=RLS_ALL_LOCKED;
	else
	{
		RakAssert("Unknown lock state in RoomsBrowserGFx3_RakNet" && 0);
	}
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_GetRoomLockState)
{
	GetRoomLockState_Func func;
	func.userName=loginUsername;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_AreAllMembersReady)
{
	AreAllMembersReady_Func func;
	func.userName=loginUsername;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_KickMember)
{
	KickMember_Func func;
	func.userName=loginUsername;
	func.kickedMember=pparams[0].GetString();
	func.reason=pparams[1].GetString();
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_GetRoomProperties)
{
	GetRoomProperties_Func func;
	func.userName=loginUsername;
	roomsPlugin->ExecuteFunc(&func);
}
ACTIONSCRIPT_CALLABLE_FUNCTION(RoomsBrowserGFx3_RakNet, f2c_StartGame)
{
	// User should override this to do start game functionality, if desired

	FxResponseArgs<1> rargs;
	rargs.Add("User must override RoomsBrowserGFx3_RakNet");
	FxDelegate::Invoke2(movie, "c2f_StartGame", rargs);

}
void RoomsBrowserGFx3_RakNet::Accept(CallbackProcessor* cbreg)
{
	RoomsBrowserGFx3::Accept(cbreg);

	cbreg->Process( "f2c_ConnectToServer", &::f2c_ConnectToServer );
	cbreg->Process( "f2c_Login", &::f2c_Login );
	cbreg->Process( "f2c_RegisterAccount", &::f2c_RegisterAccount );

	cbreg->Process( "f2c_UpdateRoomsList", &::f2c_UpdateRoomsList );
	cbreg->Process( "f2c_UpdateFriendsList", &::f2c_UpdateFriendsList );
	cbreg->Process( "f2c_JoinByFilter", &::f2c_JoinByFilter );
	cbreg->Process( "f2c_CreateRoom", &::f2c_CreateRoom );
	cbreg->Process( "f2c_Friends_SendInvite", &::f2c_Friends_SendInvite );
	cbreg->Process( "f2c_Friends_Remove", &::f2c_Friends_Remove );
	cbreg->Process( "f2c_Friends_AcceptInvite", &::f2c_Friends_AcceptInvite );
	cbreg->Process( "f2c_Friends_RejectInvite", &::f2c_Friends_RejectInvite );
	cbreg->Process( "f2c_Directed_Chat_Func", &::f2c_Directed_Chat_Func );
	cbreg->Process( "f2c_Room_Chat_Func", &::f2c_Room_Chat_Func );
	cbreg->Process( "f2c_Logoff", &::f2c_Logoff );

	cbreg->Process( "f2c_LeaveRoom", &::f2c_LeaveRoom );
	cbreg->Process( "f2c_SendInvite", &::f2c_SendInvite );
	cbreg->Process( "f2c_StartSpectating", &::f2c_StartSpectating );
	cbreg->Process( "f2c_StopSpectating", &::f2c_StopSpectating );
	cbreg->Process( "f2c_GrantModerator", &::f2c_GrantModerator );
	cbreg->Process( "f2c_SetReadyStatus", &::f2c_SetReadyStatus );
	cbreg->Process( "f2c_GetReadyStatus", &::f2c_GetReadyStatus );
	cbreg->Process( "f2c_SetRoomLockState", &::f2c_SetRoomLockState );
	cbreg->Process( "f2c_GetRoomLockState", &::f2c_GetRoomLockState );
	cbreg->Process( "f2c_AreAllMembersReady", &::f2c_AreAllMembersReady );
	cbreg->Process( "f2c_KickMember", &::f2c_KickMember );
	cbreg->Process( "f2c_GetRoomProperties", &::f2c_GetRoomProperties );
	cbreg->Process( "f2c_StartGame", &::f2c_StartGame );

}
void RoomsBrowserGFx3_RakNet::MessageResult(Client_Login *message)
{
	FxResponseArgs<1> rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));
	FxDelegate::Invoke2(movie, "c2f_Client_Login", rargs);
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Client_Logoff *message)
{
	FxResponseArgs<1> rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));
	FxDelegate::Invoke2(movie, "c2f_Client_Logoff", rargs);

	rakPeer->CloseConnection(lobby2Client->GetServerAddress(), true);
}
void RoomsBrowserGFx3_RakNet::MessageResult(Client_RegisterAccount *message)
{
	FxResponseArgs<1> rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));
	FxDelegate::Invoke2(movie, "c2f_Client_RegisterAccount", rargs);
}
void RoomsBrowserGFx3_RakNet::CreateRoom_Callback( const SystemAddress &senderAddress, RakNet::CreateRoom_Func *callResult)
{
	if (senderAddress!=lobby2Client->GetServerAddress())
		return;

	FxResponseArgsList rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	rargs.Add(false);
	FxDelegate::Invoke2(movie, "c2f_CreateRoom", rargs);
}
void RoomsBrowserGFx3_RakNet::SearchByFilter_Callback( const SystemAddress &senderAddress, RakNet::SearchByFilter_Func *callResult)
{
	if (senderAddress!=lobby2Client->GetServerAddress())
		return;

	FxResponseArgsList rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));

	if (callResult->resultCode==REC_SUCCESS)
	{
		rargs.Add((Double)callResult->roomsOutput.Size());

		unsigned int i;
		for (i=0; i < callResult->roomsOutput.Size(); i++)
		{
			rargs.Add(true);
			rargs.Add((Double)callResult->roomsOutput[i]->GetProperty(DefaultRoomColumns::GetColumnName(DefaultRoomColumns::TC_ROOM_ID))->i);
			char ipAddr[64];
			callResult->roomsOutput[i]->roomMemberList[0].systemAddress.ToString(true,ipAddr);
			rargs.Add(ipAddr);
			rargs.Add(callResult->roomsOutput[i]->roomMemberList[0].name.C_String());
			rargs.Add((Double)callResult->roomsOutput[i]->roomMemberList.Size());
			rargs.Add((Double)callResult->roomsOutput[i]->GetProperty(DefaultRoomColumns::TC_TOTAL_SLOTS)->i);
			rargs.Add(callResult->roomsOutput[i]->GetProperty("mapName")->c);
		}
	}

	FxDelegate::Invoke2(movie, "c2f_SearchByFilter_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::JoinByFilter_Callback( const SystemAddress &senderAddress, RakNet::JoinByFilter_Func *callResult)
{
	if (senderAddress!=lobby2Client->GetServerAddress())
		return;

	FxResponseArgsList rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));

	FxDelegate::Invoke2(movie, "c2f_JoinByFilter", rargs);
}
void RoomsBrowserGFx3_RakNet::Chat_Callback( const SystemAddress &senderAddress, Chat_Func *callResult)
{
	if (senderAddress!=lobby2Client->GetServerAddress())
		return;

	FxResponseArgs<3> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	rargs.Add(callResult->privateMessageRecipient.C_String());
	rargs.Add(callResult->chatMessage.C_String());

	FxDelegate::Invoke2(movie, "c2f_Chat_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::Chat_Callback( const SystemAddress &senderAddress, Chat_Notification *notification)
{
	if (senderAddress!=lobby2Client->GetServerAddress())
		return;

	FxResponseArgs<4> rargs;

	rargs.Add(notification->sender.C_String());
	rargs.Add(notification->privateMessageRecipient.C_String());
	rargs.Add(notification->chatMessage.C_String());
	rargs.Add(notification->filteredChatMessage.C_String());

	FxDelegate::Invoke2(movie, "c2f_Chat_Notification", rargs);
}
void WriteUsernameAndStatus(UsernameAndOnlineStatus &uaos, FxResponseArgsList &rargs)
{
	rargs.Add(uaos.handle.C_String());
	rargs.Add(uaos.isOnline);
	rargs.Add(uaos.presence.isVisible);
	rargs.Add(uaos.presence.titleNameOrID.C_String());
	rargs.Add(uaos.presence.statusString.C_String());
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Friends_GetFriends *message)
{
	FxResponseArgsList rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));

	unsigned int i;
	rargs.Add((Double) message->myFriends.Size());
	for (i=0; i < message->myFriends.Size(); i++)
	{
		WriteUsernameAndStatus(message->myFriends[i].usernameAndStatus, rargs);
	}

	FxDelegate::Invoke2(movie, "c2f_Friends_GetFriends", rargs);
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Friends_GetInvites *message)
{
	FxResponseArgsList rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));

	unsigned int i;
	rargs.Add((Double) message->invitesReceived.Size());
	for (i=0; i < message->invitesReceived.Size(); i++)
	{
		WriteUsernameAndStatus(message->invitesReceived[i].usernameAndStatus, rargs);
	}

	rargs.Add((Double) message->invitesSent.Size());
	for (i=0; i < message->invitesSent.Size(); i++)
	{
		WriteUsernameAndStatus(message->invitesSent[i].usernameAndStatus, rargs);
	}

	FxDelegate::Invoke2(movie, "c2f_Friends_GetInvites", rargs);
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Friends_SendInvite *message)
{
	FxResponseArgs<2> rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));
	rargs.Add(message->targetHandle.C_String());

	FxDelegate::Invoke2(movie, "c2f_Friends_SendInvite", rargs);
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Friends_AcceptInvite *message)
{
	FxResponseArgs<5> rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));
	rargs.Add(message->targetHandle.C_String());
	rargs.Add(message->presence.isVisible);
	rargs.Add(message->presence.titleNameOrID.C_String());
	rargs.Add(message->presence.statusString.C_String());

	FxDelegate::Invoke2(movie, "c2f_Friends_AcceptInvite", rargs);
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Friends_RejectInvite *message)
{
	FxResponseArgs<2> rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));
	rargs.Add(message->targetHandle.C_String());

	FxDelegate::Invoke2(movie, "c2f_Friends_RejectInvite", rargs);
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Friends_Remove *message)
{
	FxResponseArgs<2> rargs;
	rargs.Add(Lobby2ResultCodeDescription::ToEnum(message->resultCode));
	rargs.Add(message->targetHandle.C_String());

	FxDelegate::Invoke2(movie, "c2f_Friends_Remove", rargs);
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Notification_Friends_PresenceUpdate *message)
{
	FxResponseArgs<4> rargs;
	rargs.Add(message->otherHandle.C_String());
	rargs.Add(message->newPresence.isVisible);
	rargs.Add(message->newPresence.titleNameOrID.C_String());
	rargs.Add(message->newPresence.statusString.C_String());

	FxDelegate::Invoke2(movie, "c2f_Notification_Friends_PresenceUpdate", rargs);
}
void RoomsBrowserGFx3_RakNet::MessageResult(RakNet::Notification_Friends_StatusChange *message)
{
	FxResponseArgs<5> rargs;
	rargs.Add(message->OpToString());
	rargs.Add(message->otherHandle.C_String());
	rargs.Add(message->presence.isVisible);
	rargs.Add(message->presence.titleNameOrID.C_String());
	rargs.Add(message->presence.statusString.C_String());

	FxDelegate::Invoke2(movie, "c2f_Notification_Friends_StatusChange", rargs);
}
//////////////////////////////////////////////////////////////////................................................
//////////////////////////////////////////////////////////////////................................................
//////////////////////////////////////////////////////////////////................................................
//////////////////////////////////////////////////////////////////................................................
//////////////////////////////////////////////////////////////////................................................
void RoomsBrowserGFx3_RakNet::LeaveRoom_Callback( const SystemAddress &senderAddress, RakNet::LeaveRoom_Func *callResult)
{
	FxResponseArgs<1> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	FxDelegate::Invoke2(movie, "c2f_LeaveRoom", rargs);
}
void RoomsBrowserGFx3_RakNet::SendInvite_Callback( const SystemAddress &senderAddress, RakNet::SendInvite_Func *callResult)
{
	FxResponseArgs<2> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	rargs.Add(callResult->inviteeName.C_String());
	rargs.Add(callResult->inviteToSpectatorSlot);
	FxDelegate::Invoke2(movie, "c2f_SendInvite", rargs);
}
void RoomsBrowserGFx3_RakNet::StartSpectating_Callback( const SystemAddress &senderAddress, RakNet::StartSpectating_Func *callResult)
{
	FxResponseArgs<1> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	FxDelegate::Invoke2(movie, "c2f_StartSpectating", rargs);
}
void RoomsBrowserGFx3_RakNet::StopSpectating_Callback( const SystemAddress &senderAddress, RakNet::StopSpectating_Func *callResult)
{
	FxResponseArgs<1> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	FxDelegate::Invoke2(movie, "c2f_StopSpectating", rargs);
}
void RoomsBrowserGFx3_RakNet::GrantModerator_Callback( const SystemAddress &senderAddress, RakNet::GrantModerator_Func *callResult)
{
	FxResponseArgs<2> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	rargs.Add(callResult->newModerator.C_String());
	FxDelegate::Invoke2(movie, "c2f_AreAllMembersReady", rargs);
}
void RoomsBrowserGFx3_RakNet::SetReadyStatus_Callback( const SystemAddress &senderAddress, RakNet::SetReadyStatus_Func *callResult)
{
	FxResponseArgsList rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	rargs.Add(callResult->isReady);
	rargs.Add((Double) callResult->readyUsers.Size());
	for (unsigned int i=0; i < callResult->readyUsers.Size(); i++)
		rargs.Add(callResult->readyUsers[i].C_String());
	rargs.Add((Double) callResult->unreadyUsers.Size());
	for (unsigned int i=0; i < callResult->unreadyUsers.Size(); i++)
		rargs.Add(callResult->unreadyUsers[i].C_String());
	FxDelegate::Invoke2(movie, "c2f_SetReadyStatus", rargs);
}
void RoomsBrowserGFx3_RakNet::GetReadyStatus_Callback( const SystemAddress &senderAddress, RakNet::GetReadyStatus_Func *callResult)
{
	FxResponseArgsList rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	for (unsigned int i=0; i < callResult->readyUsers.Size(); i++)
		rargs.Add(callResult->readyUsers[i].C_String());
	rargs.Add((Double) callResult->unreadyUsers.Size());
	for (unsigned int i=0; i < callResult->unreadyUsers.Size(); i++)
		rargs.Add(callResult->unreadyUsers[i].C_String());
	FxDelegate::Invoke2(movie, "c2f_GetReadyStatus", rargs);
}
void RoomsBrowserGFx3_RakNet::SetRoomLockState_Callback( const SystemAddress &senderAddress, RakNet::SetRoomLockState_Func *callResult)
{
	FxResponseArgs<2> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	if (callResult->roomLockState==RLS_NOT_LOCKED)
		rargs.Add("NOT_LOCKED"); // Anyone can join or leave
	else if (callResult->roomLockState==RLS_PLAYERS_LOCKED)
		rargs.Add("PLAYERS_LOCKED"); // Anyone can join as spectator or become spectator. New players are not allowed. You cannot leave spectator.
	else
		rargs.Add("ALL_LOCKED"); // No new players are allowed, and you cannot toggle spectator
	FxDelegate::Invoke2(movie, "c2f_SetRoomLockState", rargs);
}
void RoomsBrowserGFx3_RakNet::GetRoomLockState_Callback( const SystemAddress &senderAddress, RakNet::GetRoomLockState_Func *callResult)
{
	FxResponseArgs<2> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	if (callResult->roomLockState==RLS_NOT_LOCKED)
		rargs.Add("NOT_LOCKED"); // Anyone can join or leave
	else if (callResult->roomLockState==RLS_PLAYERS_LOCKED)
		rargs.Add("PLAYERS_LOCKED"); // Anyone can join as spectator or become spectator. New players are not allowed. You cannot leave spectator.
	else
		rargs.Add("ALL_LOCKED"); // No new players are allowed, and you cannot toggle spectator
	FxDelegate::Invoke2(movie, "c2f_GetRoomLockState", rargs);
}
void RoomsBrowserGFx3_RakNet::AreAllMembersReady_Callback( const SystemAddress &senderAddress, RakNet::AreAllMembersReady_Func *callResult)
{
	FxResponseArgs<2> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	rargs.Add(callResult->allReady);
	FxDelegate::Invoke2(movie, "c2f_AreAllMembersReady", rargs);
}
void RoomsBrowserGFx3_RakNet::KickMember_Callback( const SystemAddress &senderAddress, RakNet::KickMember_Func *callResult)
{
	FxResponseArgs<3> rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	rargs.Add(callResult->kickedMember.C_String());
	rargs.Add(callResult->reason.C_String());
	FxDelegate::Invoke2(movie, "c2f_KickMember", rargs);
}
void RoomsBrowserGFx3_RakNet::GetRoomProperties_Callback( const SystemAddress &senderAddress, RakNet::GetRoomProperties_Func *callResult)
{
	char saString[32];
	char guidString[64];
	FxResponseArgsList rargs;
	rargs.Add(RoomsErrorCodeDescription::ToEnum(callResult->resultCode));
	rargs.Add(callResult->roomName.C_String());
	rargs.Add((Double)callResult->roomDescriptor.roomMemberList.Size());
	for (unsigned int i=0; i < callResult->roomDescriptor.roomMemberList.Size(); i++)
	{
		rargs.Add(callResult->roomDescriptor.roomMemberList[i].name.C_String());
		const char *c = RoomMemberModeToEnum(callResult->roomDescriptor.roomMemberList[i].roomMemberMode);
		rargs.Add(c);
		rargs.Add(callResult->roomDescriptor.roomMemberList[i].isReady);
		callResult->roomDescriptor.roomMemberList[i].systemAddress.ToString(true,saString);
		rargs.Add(saString);
		callResult->roomDescriptor.roomMemberList[i].guid.ToString(guidString);
		rargs.Add(guidString);
	}

	rargs.Add((Double)callResult->roomDescriptor.banList.Size());
	for (unsigned int i=0; i < callResult->roomDescriptor.banList.Size(); i++)
	{
		rargs.Add(callResult->roomDescriptor.banList[i].target.C_String());
		rargs.Add(callResult->roomDescriptor.banList[i].reason.C_String());
	}

	if (callResult->roomDescriptor.roomLockState==RLS_NOT_LOCKED)
		rargs.Add("NOT_LOCKED"); // Anyone can join or leave
	else if (callResult->roomDescriptor.roomLockState==RLS_PLAYERS_LOCKED)
		rargs.Add("PLAYERS_LOCKED"); // Anyone can join as spectator or become spectator. New players are not allowed. You cannot leave spectator.
	else
		rargs.Add("ALL_LOCKED"); // No new players are allowed, and you cannot toggle spectator

	rargs.Add((Double) callResult->roomDescriptor.lobbyRoomId);
	rargs.Add((Double) callResult->roomDescriptor.autoLockReadyStatus);
	rargs.Add((Double) callResult->roomDescriptor.hiddenFromSearches);

	rargs.Add(NetworkedRoomCreationParameters::SendInvitePermissionToEnum(callResult->roomDescriptor.inviteToRoomPermission));
	rargs.Add(NetworkedRoomCreationParameters::SendInvitePermissionToEnum(callResult->roomDescriptor.inviteToSpectatorSlotPermission));

	rargs.Add(callResult->roomDescriptor.GetProperty("mapName")->c);

	FxDelegate::Invoke2(movie, "c2f_GetRoomProperties", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomMemberStartedSpectating_Callback( const SystemAddress &senderAddress, RakNet::RoomMemberStartedSpectating_Notification *notification)
{
	FxResponseArgs<1> rargs;
	rargs.Add(notification->userName.C_String());
	FxDelegate::Invoke2(movie, "c2f_RoomMemberStartedSpectating_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomMemberStoppedSpectating_Callback( const SystemAddress &senderAddress, RakNet::RoomMemberStoppedSpectating_Notification *notification)
{
	FxResponseArgs<1> rargs;
	rargs.Add(notification->userName.C_String());
	FxDelegate::Invoke2(movie, "c2f_RoomMemberStoppedSpectating_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::ModeratorChanged_Callback( const SystemAddress &senderAddress, RakNet::ModeratorChanged_Notification *notification)
{
	FxResponseArgs<2> rargs;
	rargs.Add(notification->newModerator.C_String());
	rargs.Add(notification->oldModerator.C_String());
	FxDelegate::Invoke2(movie, "c2f_ModeratorChanged_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomMemberReadyStatusSet_Callback( const SystemAddress &senderAddress, RakNet::RoomMemberReadyStatusSet_Notification *notification)
{
	FxResponseArgsList rargs;
	rargs.Add(notification->isReady);
	rargs.Add(notification->roomMember.C_String());
	rargs.Add((Double) notification->readyUsers.Size());
	for (unsigned int i=0; i < notification->readyUsers.Size(); i++)
		rargs.Add(notification->readyUsers[i].C_String());
	rargs.Add((Double) notification->unreadyUsers.Size());
	for (unsigned int i=0; i < notification->unreadyUsers.Size(); i++)
		rargs.Add(notification->unreadyUsers[i].C_String());
	FxDelegate::Invoke2(movie, "c2f_RoomMemberReadyStatusSet_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomLockStateSet_Callback( const SystemAddress &senderAddress, RakNet::RoomLockStateSet_Notification *notification)
{
	FxResponseArgs<1> rargs;
	if (notification->roomLockState==RLS_NOT_LOCKED)
		rargs.Add("NOT_LOCKED"); // Anyone can join or leave
	else if (notification->roomLockState==RLS_PLAYERS_LOCKED)
		rargs.Add("PLAYERS_LOCKED"); // Anyone can join as spectator or become spectator. New players are not allowed. You cannot leave spectator.
	else
		rargs.Add("ALL_LOCKED"); // No new players are allowed, and you cannot toggle spectator
	FxDelegate::Invoke2(movie, "c2f_RoomLockStateSet_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomMemberKicked_Callback( const SystemAddress &senderAddress, RakNet::RoomMemberKicked_Notification *notification)
{
	FxResponseArgs<3> rargs;
	rargs.Add(notification->kickedMember.C_String());
	rargs.Add(notification->moderator.C_String());
	rargs.Add(notification->reason.C_String());
	FxDelegate::Invoke2(movie, "c2f_RoomMemberKicked_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomMemberLeftRoom_Callback( const SystemAddress &senderAddress, RakNet::RoomMemberLeftRoom_Notification *notification)
{
	FxResponseArgs<1> rargs;
	rargs.Add(notification->roomMember.C_String());
	FxDelegate::Invoke2(movie, "c2f_RoomMemberLeftRoom_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomMemberJoinedRoom_Callback( const SystemAddress &senderAddress, RakNet::RoomMemberJoinedRoom_Notification *notification)
{
	char saString[32];
	FxResponseArgs<4> rargs;
	rargs.Add(notification->joinedRoomResult->acceptedInvitorName.C_String());
	notification->joinedRoomResult->acceptedInvitorAddress.ToString(true,saString);
	rargs.Add(saString);
	rargs.Add(notification->joinedRoomResult->joiningMemberName.C_String());
	notification->joinedRoomResult->joiningMemberAddress.ToString(true,saString);
	rargs.Add(saString);
	FxDelegate::Invoke2(movie, "c2f_RoomMemberJoinedRoom_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomInvitationSent_Callback( const SystemAddress &senderAddress, RakNet::RoomInvitationSent_Notification *notification)
{
	FxResponseArgs<2> rargs;
	rargs.Add(notification->invitorName.C_String());
	rargs.Add(notification->inviteToSpectatorSlot);
	FxDelegate::Invoke2(movie, "c2f_RoomInvitationSent_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomInvitationWithdrawn_Callback( const SystemAddress &senderAddress, RakNet::RoomInvitationWithdrawn_Notification *notification)
{
	FxResponseArgs<2> rargs;
	rargs.Add(notification->invitedUser.invitorName.C_String());
	char saString[32];
	notification->invitedUser.invitorSystemAddress.ToString(true,saString);
	rargs.Add(saString);
	FxDelegate::Invoke2(movie, "c2f_RoomInvitationWithdrawn_Callback", rargs);
}
void RoomsBrowserGFx3_RakNet::RoomDestroyedOnModeratorLeft_Callback( const SystemAddress &senderAddress, RakNet::RoomDestroyedOnModeratorLeft_Notification *notification)
{
	FxResponseArgs<1> rargs;
	rargs.Add(notification->oldModerator.C_String());
	FxDelegate::Invoke2(movie, "c2f_RoomDestroyedOnModeratorLeft_Callback", rargs);
}


text:
package org.ak80.standin.verification.exception;

/**
 * Verification exception when a message has not been received often enough
 */
public class NotEnoughMessagesError extends VerificationError {

    public NotEnoughMessagesError(String errorMessage) {
        super(errorMessage);
    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const senecaFactory = require('seneca');
const addResources = require('./resources');
const listenAMQPTransport = require('./amqp').listenAMQPTransport;

function Service() {
}

module.exports = Service;

const proto = Service.prototype;

proto.start = function startService(callback) {
    this.db = require('./db');
    this.models = require('./models')(this.db);

    if (!isProduction()) loadConfigurationFromDotEnv();

    let senecaOptions = {};
    senecaOptions = {
        log: {
            level: 'error'
        }
    };

    this.seneca = senecaFactory(senecaOptions);
    addResources(this.seneca, { models: this.models });

    const pin = [{ role: 'users' }];

    listenAMQPTransport(this.seneca, pin, callback);
};

function isProduction() {
    return process.env.NODE_ENV === 'production';
}

function loadConfigurationFromDotEnv() {
    require('dotenv').config({ path: '../../.env', silent: true });
}

proto.stop = function stopService(callback) {
    this.seneca.close(callback);
};


text:
package ucar.nc2.ui.grib;

import ucar.nc2.grib.GribResourceReader;
import ucar.nc2.grib.grib1.tables.Grib1Customizer;
import ucar.nc2.grib.grib1.Grib1Parameter;
import ucar.nc2.grib.grib1.tables.Grib1ParamTableReader;
import ucar.nc2.grib.grib1.tables.Grib1ParamTables;
import ucar.nc2.ui.dialog.Grib1TableCompareDialog;
import ucar.ui.widget.*;
import ucar.nc2.ui.dialog.Grib1TableDialog;
import ucar.ui.widget.PopupMenu;
import ucar.nc2.units.SimpleUnit;
import ucar.nc2.util.IO;
import ucar.nc2.wmo.CommonCodeTable;
import ucar.nc2.wmo.Util;
import ucar.util.prefs.PreferencesExt;
import ucar.ui.prefs.BeanTable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.List;

/**
 * Show Grib1 Tables
 *
 * @author caron
 * @since Sep 26, 2010
 */
public class Grib1TablesViewer extends JPanel {

  private PreferencesExt prefs;

  private BeanTable codeTable, entryTable;
  private JSplitPane split;

  private TextHistoryPane infoTA;
  private IndependentWindow infoWindow;

  private Grib1TableDialog showTableDialog;
  private Grib1TableCompareDialog compareTableDialog;

  public Grib1TablesViewer(PreferencesExt prefs, JPanel buttPanel) {
    this.prefs = prefs;

    codeTable = new BeanTable(TableBean.class, (PreferencesExt) prefs.node("CodeTableBean"), false);
    codeTable.addListSelectionListener(e -> {
      TableBean csb = (TableBean) codeTable.getSelectedBean();
      setEntries(csb.table);
    });

    ucar.ui.widget.PopupMenu varPopup = new PopupMenu(codeTable.getJTable(), "Options");
    varPopup.addAction("Show File contents", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        TableBean bean = (TableBean) codeTable.getSelectedBean();
        if (bean == null)
          return;
        showFile(bean);
      }
    });

    varPopup.addAction("Compare to default WMO table", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        TableBean bean = (TableBean) codeTable.getSelectedBean();
        if (bean == null)
          return;
        initTableDialog();

        Grib1ParamTableReader wmo = new Grib1ParamTables().getParameterTable(0, 0, bean.getVersion());
        if (wmo == null) {
          infoTA.setText("Cant find WMO version " + bean.getVersion());
          infoWindow.show();
          return;
        }

        compareTableDialog.setTable1(new TableBean(wmo));
        compareTableDialog.setTable2(bean);
        compareTableDialog.setVisible(true);
      }
    });

    varPopup.addAction("Compare two tables", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        TableBean bean = (TableBean) codeTable.getSelectedBean();
        if (bean == null)
          return;
        initTableDialog();

        List list = codeTable.getSelectedBeans();
        if (list.size() == 2) {
          TableBean bean1 = (TableBean) list.get(0);
          TableBean bean2 = (TableBean) list.get(1);
          compareTableDialog.setTable1(bean1);
          compareTableDialog.setTable2(bean2);
          compareTableDialog.setVisible(true);
        }
      }
    });

    varPopup.addAction("Compare to all non-local tables", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        TableBean bean = (TableBean) codeTable.getSelectedBean();
        if (bean == null)
          return;
        initTableDialog();

        compareTableDialog.setTable1(bean);
        compareTableDialog.setTable2(null);
        compareTableDialog.setVisible(true);
      }
    });

    entryTable = new BeanTable(EntryBean.class, (PreferencesExt) prefs.node("EntryBean"), false);
    /*
     * entryTable.addListSelectionListener(new ListSelectionListener() {
     * public void valueChanged(ListSelectionEvent e) {
     * entryTable.getSelectedBean();
     * }
     * });
     */

    varPopup = new PopupMenu(entryTable.getJTable(), "Options");
    varPopup.addAction("Show in all tables", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        EntryBean bean = (EntryBean) entryTable.getSelectedBean();
        if (bean == null)
          return;
        showAll(bean);
      }
    });

    // the info window
    infoTA = new TextHistoryPane();
    infoWindow = new IndependentWindow("Extra Information", BAMutil.getImage("nj22/NetcdfUI"), infoTA);
    infoWindow.setBounds((Rectangle) prefs.getBean("InfoWindowBounds", new Rectangle(300, 300, 800, 600)));

    split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, codeTable, entryTable);
    split.setDividerLocation(prefs.getInt("splitPos", 500));

    setLayout(new BorderLayout());
    add(split, BorderLayout.CENTER);

    AbstractButton infoButton = BAMutil.makeButtcon("Information", "Show Table Used", false);
    infoButton.addActionListener(e -> {
      if (showTableDialog == null) {
        showTableDialog = new Grib1TableDialog((Frame) null);
        showTableDialog.pack();
      }
      showTableDialog.setVisible(true);
    });
    buttPanel.add(infoButton);

    try {
      List<Grib1ParamTableReader> tables = Grib1ParamTables.getStandardParameterTables();
      java.util.List<TableBean> beans = new ArrayList<>(tables.size());
      for (Grib1ParamTableReader t : tables) {
        beans.add(new TableBean(t));
      }
      // Collections.sort(beans);
      codeTable.setBeans(beans);

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  private void initTableDialog() {
    if (compareTableDialog == null) {
      compareTableDialog = new Grib1TableCompareDialog((Frame) null);
      compareTableDialog.pack();
      compareTableDialog.addPropertyChangeListener("OK",
          evt -> compareTables((Grib1TableCompareDialog.Data) evt.getNewValue()));
    }
  }

  public void save() {
    codeTable.saveState(false);
    entryTable.saveState(false);
    prefs.putBeanObject("InfoWindowBounds", infoWindow.getBounds());
    // prefs.putBeanObject("InfoWindowBounds2", infoWindow2.getBounds());
    prefs.putInt("splitPos", split.getDividerLocation());
    // prefs.putInt("splitPos2", split2.getDividerLocation());
    // if (fileChooser != null) fileChooser.save();
  }

  public void setTable(String filename) throws IOException {
    Grib1ParamTableReader table = new Grib1ParamTableReader(filename);
    TableBean bean = new TableBean(table);
    codeTable.addBean(bean);
    codeTable.setSelectedBean(bean);
  }

  private void setEntries(Grib1ParamTableReader table) {
    Map<Integer, Grib1Parameter> map = table.getParameters();
    if (map == null) {
      map = table.getParameters();
    }

    ArrayList<Integer> params = new ArrayList<>(map.keySet());
    Collections.sort(params);
    java.util.List<EntryBean> beans = new ArrayList<>(params.size());
    for (Integer key : params) {
      beans.add(new EntryBean(map.get(key)));
    }
    entryTable.setBeans(beans);
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////

  private void showFile(TableBean bean) {
    infoTA.setText("Table:" + bean.getPath() + "\n");
    try (InputStream is = GribResourceReader.getInputStream(bean.getPath())) {
      infoTA.appendLine(IO.readContents(is));
      infoWindow.setVisible(true);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private void showAll(EntryBean ebean) {
    Formatter f = new Formatter();
    infoTA.setText("Entry:" + ebean.getNumber() + "\n");
    for (Object bean : codeTable.getBeans()) {
      TableBean tbean = (TableBean) bean;
      Grib1Parameter p = tbean.table.getLocalParameter(ebean.getNumber());
      if (p != null)
        f.format(" %s from %s (%d)%n", p, tbean.table.getName(), tbean.table.getParameters().hashCode());
    }

    infoTA.appendLine(f.toString());
    infoWindow.setVisible(true);
  }

  private void compareTables(Grib1TableCompareDialog.Data data) {
    Formatter f = new Formatter();
    if (data.table2bean == null)
      compareAll(data.table1bean.table, data, f);
    else
      compare(data.table1bean.table, data.table2bean.table, data, f);

    infoTA.setText(f.toString());
    infoTA.gotoTop();
    infoWindow.show();
  }

  private void compare(Grib1ParamTableReader t1, Grib1ParamTableReader t2, Grib1TableCompareDialog.Data data,
      Formatter out) {
    out.format("Compare%n %s%n %s%n", t1.toString(), t2.toString());
    Map<Integer, Grib1Parameter> h1 = t1.getParameters();
    Map<Integer, Grib1Parameter> h2 = t2.getParameters();
    List<Integer> keys = new ArrayList<>(h1.keySet());
    Collections.sort(keys);

    for (Integer key : keys) {
      Grib1Parameter d1 = h1.get(key);
      Grib1Parameter d2 = h2.get(key);
      if (d2 == null) {
        if (data.showMissing)
          out.format("**No key %s (%s) in second table%n", key, d1);
      } else {
        if (data.compareDesc) {
          if (!equiv(d1.getDescription(), d2.getDescription()))
            out.format(" %s desc%n   %s%n   %s%n", d1.getNumber(), d1.getDescription(), d2.getDescription());
        }
        if (data.compareNames) {
          if (!equiv(d1.getName(), d2.getName()))
            out.format(" %d name%n   %s%n   %s%n", d1.getNumber(), d1.getName(), d2.getName());
        }
        if (data.compareUnits) {
          if (!equiv(d1.getUnit(), d2.getUnit()))
            out.format(" %s units%n   %s%n   %s%n", d1.getNumber(), d1.getUnit(), d2.getUnit());
        }
        if (data.cleanUnits) {
          String cu1 = Util.cleanUnit(d1.getUnit());
          String cu2 = Util.cleanUnit(d2.getUnit());
          if (!equiv(cu1, cu2))
            out.format(" %s cleanUnits%n   %s%n   %s%n", d1.getNumber(), cu1, cu2);
        }
        if (data.udunits) {
          String cu1 = Util.cleanUnit(d1.getUnit());
          String cu2 = Util.cleanUnit(d2.getUnit());
          try {
            SimpleUnit su1 = SimpleUnit.factoryWithExceptions(cu1);
            if (!su1.isCompatible(cu2))
              out.format(" %s udunits%n   %s%n   %s%n", d1.getNumber(), cu1, cu2);
          } catch (Exception e) {
            out.format(" %s udunits%n   cant parse = %s%n   %s%n", d1.getNumber(), cu1, cu2);
          }
        }
      }
    }

    if (data.showMissing) {
      out.format("%n***Check if entries are missing in first table%n");
      keys = new ArrayList<>(h2.keySet());
      Collections.sort(keys);
      for (Integer key : keys) {
        Grib1Parameter d1 = h1.get(key);
        Grib1Parameter d2 = h2.get(key);
        if (d1 == null)
          out.format("**No key %s (%s) in first table%n", key, d2);
      }
    }

  }

  private boolean equiv(String org1, String org2) {
    if (org1 == org2)
      return true;
    if (org1 == null)
      return false;
    if (org2 == null)
      return false;
    return org1.equalsIgnoreCase(org2);
  }

  private void compareAll(Grib1ParamTableReader t1, Grib1TableCompareDialog.Data data, Formatter out) {
    out.format("Compare All non-local Tables%s%n", t1.toString());
    Map<Integer, Grib1Parameter> h1 = t1.getParameters();
    List<Integer> keys = new ArrayList<>(h1.keySet());
    Collections.sort(keys);

    for (Integer key : keys) {
      Grib1Parameter d1 = h1.get(key);
      out.format("%n--- %s%n", d1);

      for (Object bean : codeTable.getBeans()) {
        TableBean tbean = (TableBean) bean;
        if (tbean.getVersion() > 127)
          continue;

        Grib1Parameter d2 = tbean.table.getLocalParameter(d1.getNumber());
        if (d2 != null) {
          boolean descDiff = data.compareDesc && !equiv(d1.getDescription(), d2.getDescription());
          boolean namesDiff = data.compareNames && !equiv(d1.getName(), d2.getName());
          boolean unitsDiff = data.compareUnits && !equiv(d1.getUnit(), d2.getUnit());
          boolean cunitsDiff = data.cleanUnits && !equiv(Util.cleanUnit(d1.getUnit()), Util.cleanUnit(d2.getUnit()));
          boolean udunitsDiff = false;
          if (data.udunits) {
            String cu1 = Util.cleanUnit(d1.getUnit());
            String cu2 = Util.cleanUnit(d2.getUnit());
            try {
              SimpleUnit su1 = SimpleUnit.factoryWithExceptions(cu1);
              udunitsDiff = !su1.isCompatible(cu2);
            } catch (Exception e) {
              udunitsDiff = false;
            }
          }

          if (descDiff)
            out.format("    desc=%s from %s%n", d2.getDescription(), tbean.table.getPath());
          if (namesDiff)
            out.format("    name=%s from %s%n", d2.getName(), tbean.table.getPath());
          if (unitsDiff || cunitsDiff || udunitsDiff)
            out.format("    units=%s from %s%n", d2.getUnit(), tbean.table.getPath());
        }
      }
    }

  }

  public static class TableBean implements Comparable<TableBean> {
    Grib1ParamTableReader table;

    // no-arg constructor

    public TableBean() {}

    // create from a dataset

    public TableBean(Grib1ParamTableReader table) {
      this.table = table;
    }

    public int getCenter_id() {
      return table.getCenter_id();
    }

    public String getCenter() {
      return CommonCodeTable.getCenterName(table.getCenter_id(), 1);
    }

    public String getSubCenter() {
      return Grib1Customizer.getSubCenterNameStatic(table.getCenter_id(), table.getSubcenter_id());
    }

    public int getSubcenter_id() {
      return table.getSubcenter_id();
    }

    public int getVersion() {
      return table.getVersion();
    }

    public String getPath() {
      return table.getPath();
    }

    public String getName() {
      return table.getName();
    }

    public int getKey() {
      return table.getKey();
    }

    @Override
    public int compareTo(TableBean o) {
      int ret = getCenter_id() - o.getCenter_id();
      if (ret == 0)
        ret = getSubcenter_id() - o.getSubcenter_id();
      if (ret == 0)
        ret = getVersion() - o.getVersion();
      return ret;
    }
  }

  public static class EntryBean {
    Grib1Parameter param;

    // no-arg constructor
    public EntryBean() {}

    public EntryBean(Grib1Parameter param) {
      this.param = param;
    }

    public String getName() {
      return param.getName();
    }

    public String getCFname() {
      return param.getCFname();
    }

    public String getWMOdesc() {
      Grib1ParamTableReader wmo = Grib1ParamTables.getDefaultWmoTable();
      Grib1Parameter p = wmo.getParameter(param.getNumber());
      return p == null ? "" : p.getDescription();
    }

    public String getDescription() {
      return param.getDescription();
    }

    public String getUnit() {
      return param.getUnit();
    }

    public String getCleanUnit() {
      return Util.cleanUnit(param.getUnit());
    }

    public String getUdunit() {
      String cu = Util.cleanUnit(param.getUnit());
      try {
        SimpleUnit su1 = SimpleUnit.factoryWithExceptions(cu);
        return (su1.isUnknownUnit()) ? "UNKNOWN" : su1.toString();
      } catch (Exception e) {
        return "FAIL " + e.getMessage();
      }
    }

    public int getNumber() {
      return param.getNumber();
    }

  }
}


text:
using namespace clang;
using ::testing::ElementsAre;

namespace {
class ProcessASTAction : public clang::ASTFrontendAction {
public:
  ProcessASTAction(llvm::unique_function<void(clang::ASTContext &)> Process)
      : Process(std::move(Process)) {
    assert(this->Process);
  }

  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
                                                 StringRef InFile) {
    class Consumer : public ASTConsumer {
    public:
      Consumer(llvm::function_ref<void(ASTContext &CTx)> Process)
          : Process(Process) {}

      void HandleTranslationUnit(ASTContext &Ctx) override { Process(Ctx); }

    private:
      llvm::function_ref<void(ASTContext &CTx)> Process;
    };

    return std::make_unique<Consumer>(Process);
  }

private:
  llvm::unique_function<void(clang::ASTContext &)> Process;
};

enum class VisitEvent {
  StartTraverseFunction,
  EndTraverseFunction,
  StartTraverseAttr,
  EndTraverseAttr
};

class CollectInterestingEvents
    : public RecursiveASTVisitor<CollectInterestingEvents> {
public:
  bool TraverseFunctionDecl(FunctionDecl *D) {
    Events.push_back(VisitEvent::StartTraverseFunction);
    bool Ret = RecursiveASTVisitor::TraverseFunctionDecl(D);
    Events.push_back(VisitEvent::EndTraverseFunction);

    return Ret;
  }

  bool TraverseAttr(Attr *A) {
    Events.push_back(VisitEvent::StartTraverseAttr);
    bool Ret = RecursiveASTVisitor::TraverseAttr(A);
    Events.push_back(VisitEvent::EndTraverseAttr);

    return Ret;
  }

  std::vector<VisitEvent> takeEvents() && { return std::move(Events); }

private:
  std::vector<VisitEvent> Events;
};

std::vector<VisitEvent> collectEvents(llvm::StringRef Code) {
  CollectInterestingEvents Visitor;
  clang::tooling::runToolOnCode(
      std::make_unique<ProcessASTAction>(
          [&](clang::ASTContext &Ctx) { Visitor.TraverseAST(Ctx); }),
      Code);
  return std::move(Visitor).takeEvents();
}
} // namespace

TEST(RecursiveASTVisitorTest, AttributesInsideDecls) {
  /// Check attributes are traversed inside TraverseFunctionDecl.
  llvm::StringRef Code = R"cpp(
__attribute__((annotate("something"))) int foo() { return 10; }
  )cpp";

  EXPECT_THAT(collectEvents(Code),
              ElementsAre(VisitEvent::StartTraverseFunction,
                          VisitEvent::StartTraverseAttr,
                          VisitEvent::EndTraverseAttr,
                          VisitEvent::EndTraverseFunction));
}


text:
void setUp(void) {
    property_types_init();
}

void tearDown(void) {
    property_types_deinit();
}

static http_request_t _test_request;

void test_http_request_init(void) {
    http_request_init(&_test_request, GET, "http://api.arrowconnect.io:80/api/v1/kronos/gateways");
    TEST_ASSERT(_test_request._response_payload_meth._p_add_handler);
    TEST_ASSERT(_test_request._response_payload_meth._p_set_handler);
    TEST_ASSERT_EQUAL_INT(0, _test_request.is_corrupt);
    TEST_ASSERT_EQUAL_STRING("api.arrowconnect.io", P_VALUE(_test_request.host));
    TEST_ASSERT_EQUAL_INT(80, _test_request.port);
    TEST_ASSERT_EQUAL_STRING("GET", P_VALUE(_test_request.meth));
    TEST_ASSERT_EQUAL_STRING("http", P_VALUE(_test_request.scheme));
    TEST_ASSERT( IS_EMPTY(_test_request.payload) );
    TEST_ASSERT( ! _test_request.header );
    TEST_ASSERT( IS_EMPTY(_test_request.content_type.value) );
    TEST_ASSERT( IS_EMPTY(_test_request.content_type.key) );
    TEST_ASSERT( ! _test_request.content_type.node.next );
}

void test_http_request_add_header(void) {
    http_request_add_header(&_test_request, p_heap("hello"), p_heap("kokoko"));
    TEST_ASSERT( _test_request.header );
    property_map_t *tmp = NULL;
    arrow_linked_list_for_each(tmp, _test_request.header, property_map_t) {
        TEST_ASSERT_EQUAL_STRING("hello", P_VALUE(tmp->key));
        TEST_ASSERT_EQUAL_STRING("kokoko", P_VALUE(tmp->value));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2019 Google LLC
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     https://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<layout>

    <data>
        <variable
            name="fileEntity"
            type="com.android.example.filelocker.FileEntity" />
        <variable
            name="handler"
            type="com.android.example.filelocker.FileAdapter.FileAdapterListener" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:minHeight="?listPreferredItemHeightSmall"
        android:paddingHorizontal="16dp"
        android:paddingVertical="16dp"
        android:foreground="?attr/selectableItemBackground"
        android:onClick="@{(view) -> handler.onFileClicked(fileEntity)}">

        <TextView
            android:id="@+id/title_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:textAppearance="?attr/textAppearanceHeadline6"
            android:text="@{fileEntity.title}"
            tools:text="rocket_design.txt"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:textAppearance="?attr/textAppearanceBody2"
            android:text="Just now"/>

    </LinearLayout>

</layout>


text:
package org.cafebabepy.runtime.module._ast;

import org.cafebabepy.runtime.Python;
import org.cafebabepy.runtime.module.DefinePyType;

/**
 * Created by yotchang4s on 2017/05/29.
 */
@DefinePyType(name = "_ast.USub", parent = {"_ast.unaryop"})
public class PyUSubType extends AbstractAST {

    public PyUSubType(Python runtime) {
        super(runtime);
    }
}


text:
var util = require('util');

setTimeout(function () {
  util.puts('Throwing error now.');
  throw new Error('User generated fault.');
}, 200);


text:
Public Class lblEngangs

    End Sub
End Class


text:
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">

          <form action="starttrack" method="POST">
            {% csrf_token %}
            <input name="chat_id" id="chat_id" value='{{chat_id}}' type="hidden"/>
            <input name="userId" id="userId" value='{{userId}}' type="hidden"/>
            <input name="chat_name" id="chat_name" value='{{chat_name}}' type="hidden"/>
            <input name="username" id="username" value='{{username}}' type="hidden"/>
          </form>

{{track.name}}

            Purpose&nbsp:&nbsp{{track.purpose}}

            {% if budget %}
              Budget&nbsp:&nbsp{{track.budget_currency.abbr}}&nbsp{{track.budget}}

              Percent spent&nbsp:&nbsp{{perc_spent}}%

            {% endif %}
            {% if converted_total %}
              Total&nbsp:&nbsp{{track.budget_currency.abbr}}&nbsp{{converted_total}}

            {% endif %}
            {% if total_expense%}
              Total expense breakdown

              {% for key, values in total_expense.items %}

{{key}}&nbsp{{values}}

              {% endfor %}
            {% endif %}

          {% if expense_list %}

Expenses

            {% for expense in expense_list %}

{{expense.currency.abbr}}&nbsp{{expense.amount}}&nbspfor&nbsp{{expense.purpose}}

                  Paid by&nbsp:&nbsp{{expense.paidby}}

                  Time &nbsp:&nbsp{{expense.timestamp}}

                  <button onclick="myFunction({{expense.id}})">Delete</button>

            {% endfor %}

          {% endif %}


text:
using Fclp;
using PKISharp.WACS.Configuration;

namespace PKISharp.WACS.Plugins.StorePlugins
{
    class PemFilesArgumentsProvider : BaseArgumentsProvider<PemFilesArguments>
    {
        public override string Name => "PEM files plugin";
        public override string Group => "Store";
        public override string Condition => "--store pemfiles";

        public override void Configure(FluentCommandLineParser<PemFilesArguments> parser)
        {
            parser.Setup(o => o.PemFilesPath)
                 .As("pemfilespath")
                 .WithDescription(".pem files are exported to this folder");
        }

        public override bool Active(PemFilesArguments current)
        {
            return !string.IsNullOrEmpty(current.PemFilesPath);
        }
    }
}


text:
package by.istin.android.xcore.test.bo;

import java.io.Serializable;

import android.content.ContentValues;

import by.istin.android.xcore.annotations.dbEntity;
import by.istin.android.xcore.test.vk.Dialog;
import by.istin.android.xcore.test.vk.User;

public class DialogsResponse implements Serializable {

	private static final long serialVersionUID = 577009158147303735L;

    @dbEntity(clazz = Dialog.class)
	private ContentValues[] dialogs;

    @dbEntity(clazz = User.class)
	private ContentValues[] users;

	public ContentValues[] getDialogs() {
		return dialogs;
	}

	public ContentValues[] getUsers() {
		return users;
	}

	public void setDialogs(ContentValues[] dialogs) {
		this.dialogs = dialogs;
	}

	public void setUsers(ContentValues[] users) {
		this.users = users;
	}

}


text:
// Copyright (c) 2015 Geeth Tharanga
// Under the MIT licence - See licence.txt

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TicTacToe.Properties;

namespace TicTacToe.Util
{
    public static class Config
    {
        public static int AIThinkDuration
        {
            get
            {
                return Settings.Default.AIThinkDuration ;
            }
        }

        public static int GameStartDelay
        {
            get
            {
                return Settings.Default.GameStartDelay;
            }
        }
    }
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../../../shared/continuation/call', __FILE__)

with_feature :continuation do
  describe "Continuation#call" do
    it_behaves_like :continuation_call, :call
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
using Microsoft.Azure.Cosmos.Table.Queryable;

namespace AzureStorageExtensions
{
    public class CloudTable<T> where T : class, ITableEntity, new()
    {
        public CloudTable(CloudTable cloudTable)
        {
            CloudTableContext = cloudTable;
        }

        public CloudTable CloudTableContext { get; }

        public void Insert(T entity)
        {
            var op = TableOperation.Insert(entity);
            CloudTableContext.Execute(op);
        }

        public Task InsertAsync(T entity)
        {
            var op = TableOperation.Insert(entity);
            return CloudTableContext.ExecuteAsync(op);
        }

        public void InsertOrReplace(T entity)
        {
            var op = TableOperation.InsertOrReplace(entity);
            CloudTableContext.Execute(op);
        }

        public Task InsertOrReplaceAsync(T entity)
        {
            var op = TableOperation.InsertOrReplace(entity);
            return CloudTableContext.ExecuteAsync(op);
        }

        public void ExecuteBatch(TableBatchOperation op)
        {
            if (op.Count == 0)
                return;
            if (op.Count <= 100)
            {
                CloudTableContext.ExecuteBatch(op);
                return;
            }
            foreach (var chunk in op.Chunk(100))
            {
                var chunkOp = new TableBatchOperation();
                foreach (var item in chunk)
                {
                    chunkOp.Add(item);
                }

                CloudTableContext.ExecuteBatch(chunkOp);
            }
        }
        public async Task ExecuteBatchAsync(TableBatchOperation op)
        {
            if (op.Count == 0)
                return;
            if (op.Count <= 100)
            {
                await CloudTableContext.ExecuteBatchAsync(op);
                return;
            }
            foreach (var chunk in op.Chunk(100))
            {
                var chunkOp = new TableBatchOperation();
                foreach (var item in chunk)
                {
                    chunkOp.Add(item);
                }

                await CloudTableContext.ExecuteBatchAsync(chunkOp);
            }
        }

        internal void Bulk(Func<TableBatchOperation, Action<ITableEntity>> func, IEnumerable<ITableEntity> entities, bool checkConcurrency)
        {
            var op = new TableBatchOperation();
            var action = func(op);
            foreach (var item in entities)
            {
                if (!checkConcurrency)
                    item.ETag = "*";
                action(item);
            }
            this.ExecuteBatch(op);
        }

        internal Task BulkAsync(Func<TableBatchOperation, Action<ITableEntity>> func, IEnumerable<ITableEntity> entities, bool checkConcurrency)
        {
            var op = new TableBatchOperation();
            var action = func(op);
            foreach (var item in entities)
            {
                if (!checkConcurrency)
                    item.ETag = "*";
                action(item);
            }
            return this.ExecuteBatchAsync(op);
        }

        public void BulkInsert(IEnumerable<T> entities)
        {
            Bulk(op => op.Insert, entities, true);
        }

        public Task BulkInsertAsync(IEnumerable<T> entities)
        {
            return BulkAsync(op => op.Insert, entities, true);
        }

        public void BulkInsertOrReplace(IEnumerable<T> entities)
        {
            Bulk(op => op.InsertOrReplace, entities, true);
        }

        public Task BulkInsertOrReplaceAsync(IEnumerable<T> entities)
        {
            return BulkAsync(op => op.InsertOrReplace, entities, true);
        }

        public TableQuery<T> Query()
        {
            return CloudTableContext.CreateQuery<T>();
        }

        public TableQuery<T> Query(string partitionKey, IEnumerable<string> rowKeys)
        {
            var p = Expression.Parameter(typeof(T), "p");
            var predicate = rowKeys.Select(
                    item => Expression.Equal(Expression.Property(p, "RowKey"), Expression.Constant(item)))
                .AggregateBalance(Expression.OrElse);

            var linq = (from item in Query()
                where item.PartitionKey == partitionKey
                select item);
            var lambda = Expression.Lambda<Func<T, bool>>(predicate, p);
            return linq.Where(lambda).AsTableQuery();
        }

        public T Retrieve(string partitionKey, string rowKey)
        {
            var op = TableOperation.Retrieve<T>(partitionKey, rowKey);
            var result = CloudTableContext.Execute(op);
            return (T) result.Result;
        }

        public async Task<T> RetrieveAsync(string partitionKey, string rowKey)
        {
            var op = TableOperation.Retrieve<T>(partitionKey, rowKey);
            var result = await CloudTableContext.ExecuteAsync(op);
            return (T) result.Result;
        }

        public async Task<U> RetryAsync<U>(Func<CloudTable<T>, Task<U>> func, IRetryPolicy policy = null)
        {
            policy ??= CloudTableContext.ServiceClient.DefaultRequestOptions.RetryPolicy;
            var retry = 0;
            while (true)
            {
                try
                {
                    return await func(this);
                }
                catch (StorageException e)
                {
                    if (e.RequestInformation.HttpStatusCode != (int) HttpStatusCode.PreconditionFailed &&
                        e.RequestInformation.HttpStatusCode != (int) HttpStatusCode.Conflict)
                        throw;
                    if (!policy.ShouldRetry(retry++, 0, e, out TimeSpan delay, null))
                        throw;
                    await Task.Delay(delay);
                }
            }
        }

        public void Delete(T entity, bool checkConcurrency = false)
        {
            if (!checkConcurrency)
                entity.ETag = "*";
            var op = TableOperation.Delete(entity);
            CloudTableContext.Execute(op);
        }

        public Task DeleteAsync(T entity, bool checkConcurrency = false)
        {
            if (!checkConcurrency)
                entity.ETag = "*";
            var op = TableOperation.Delete(entity);
            return CloudTableContext.ExecuteAsync(op);
        }

        public void Delete(string partitionKey, string rowKey)
        {
            var entity = new T
            {
                PartitionKey = partitionKey,
                RowKey = rowKey,
                ETag = "*",
            };
            var op = TableOperation.Delete(entity);
            CloudTableContext.Execute(op);
        }

        public Task DeleteAsync(string partitionKey, string rowKey)
        {
            var entity = new T
            {
                PartitionKey = partitionKey,
                RowKey = rowKey,
                ETag = "*",
            };
            var op = TableOperation.Delete(entity);
            return CloudTableContext.ExecuteAsync(op);
        }

        public void BulkDelete(IEnumerable<T> entities, bool checkConcurrency = false)
        {
            Bulk(op => op.Delete, entities, checkConcurrency);
        }

        public Task BulkDeleteAsync(IEnumerable<T> entities, bool checkConcurrency = false)
        {
            return BulkAsync(op => op.Delete, entities, checkConcurrency);
        }

        public void DeleteIfExists(string partitionKey, string rowKey)
        {
            try
            {
                this.Delete(partitionKey, rowKey);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode != 404)
                    throw;
            }
        }

        public async Task DeleteIfExistsAsync(string partitionKey, string rowKey)
        {
            try
            {
                await this.DeleteAsync(partitionKey, rowKey);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode != 404)
                    throw;
            }
        }

        public void DeleteIfExists(T entity, bool checkConcurrency = false)
        {
            try
            {
                this.Delete(entity, checkConcurrency);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode != 404)
                    throw;
            }
        }

        public async Task DeleteIfExistsAsync(T entity, bool checkConcurrency = false)
        {
            try
            {
                await this.DeleteAsync(entity, checkConcurrency);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode != 404)
                    throw;
            }
        }

        public void BulkDeleteIfExists(IEnumerable<T> entities, bool checkConcurrency = false)
        {
            foreach (var chunk in entities.Chunk(100))
            {
                this.bulkDeleteIfExists(chunk, checkConcurrency);
            }
        }

        public async Task BulkDeleteIfExistsAsync(IEnumerable<T> entities, bool checkConcurrency = false)
        {
            foreach (var chunk in entities.Chunk(100))
            {
                await this.bulkDeleteIfExistsAsync(chunk, checkConcurrency);
            }
        }

        void bulkDeleteIfExists(IEnumerable<T> entities, bool checkConcurrency = false)
        {
            try
            {
                this.BulkDelete(entities, checkConcurrency);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode != 404)
                    throw;
                var list = entities as IList<T> ?? entities.ToList();
                var rowKeys = list.Select(it => it.RowKey);
                var available = this.Query(list[0].PartitionKey, rowKeys).Select(it => it.RowKey).ToHashSet();
                if (available.Count >= list.Count)
                    throw;
                var newList = list.Where(it => available.Contains(it.RowKey));
                bulkDeleteIfExists(newList, checkConcurrency);
            }
        }

        async Task bulkDeleteIfExistsAsync(IEnumerable<T> entities, bool checkConcurrency = false)
        {
            try
            {
                await this.BulkDeleteAsync(entities, checkConcurrency);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation.HttpStatusCode != 404)
                    throw;
                var list = entities as IList<T> ?? entities.ToList();
                var rowKeys = list.Select(it => it.RowKey);
                var tmp = this.Query(list[0].PartitionKey, rowKeys).Select(it => it.RowKey).AsTableQuery().AsAsyncTableQuery();
                var available = new HashSet<string>();
                await foreach (var item in tmp)
                {
                    available.Add(item);
                }
                if (available.Count >= list.Count)
                    throw;
                var newList = list.Where(it => available.Contains(it.RowKey));
                await bulkDeleteIfExistsAsync(newList, checkConcurrency);
            }
        }

        public void Replace(T entity)
        {
            entity.ETag = "*";
            var op = TableOperation.Replace(entity);
            CloudTableContext.Execute(op);
        }

        public Task ReplaceAsync(T entity)
        {
            entity.ETag = "*";
            var op = TableOperation.Replace(entity);
            return CloudTableContext.ExecuteAsync(op);
        }

        public void BulkReplace(IEnumerable<T> entities)
        {
            Bulk(op => op.Replace, entities, false);
        }

        public Task BulkReplaceAsync(IEnumerable<T> entities)
        {
            return BulkAsync(op => op.Replace, entities, false);
        }

        public void Update(T entity)
        {
            var op = TableOperation.Replace(entity);
            CloudTableContext.Execute(op);
        }

        public Task UpdateAsync(T entity)
        {
            var op = TableOperation.Replace(entity);
            return CloudTableContext.ExecuteAsync(op);
        }

        public void BulkUpdate(IEnumerable<T> entities)
        {
            Bulk(op => op.Replace, entities, true);
        }

        public Task BulkUpdateAsync(IEnumerable<T> entities)
        {
            return BulkAsync(op => op.Replace, entities, true);
        }

        private static ITableEntity Expand(ITableEntity entity)
        {
            switch (entity)
            {
                case ExpandableTableEntity expandable:
                {
                    var properties = expandable.WriteEntity(null, true);
                    return new DynamicTableEntity(entity.PartitionKey, entity.RowKey, entity.ETag, properties);
                }
                default:
                    return entity;
            }
        }

        public void Merge(ITableEntity entity, bool checkConcurrency = false)
        {
            if (!checkConcurrency)
                entity.ETag = "*";
            var op = TableOperation.Merge(Expand(entity));
            CloudTableContext.Execute(op);
        }

        public Task MergeAsync(ITableEntity entity, bool checkConcurrency = false)
        {
            if (!checkConcurrency)
                entity.ETag = "*";
            var op = TableOperation.Merge(Expand(entity));
            return CloudTableContext.ExecuteAsync(op);
        }

        public void BulkMerge(IEnumerable<ITableEntity> entities, bool checkConcurrency = false)
        {
            Bulk(op => op.Merge, entities.Select(Expand), checkConcurrency);
        }

        public Task BulkMergeAsync(IEnumerable<ITableEntity> entities, bool checkConcurrency = false)
        {
            return BulkAsync(op => op.Merge, entities.Select(Expand), checkConcurrency);
        }

        public void InsertOrMerge(ITableEntity entity)
        {
            var op = TableOperation.InsertOrMerge(Expand(entity));
            CloudTableContext.Execute(op);
        }

        public Task InsertOrMergeAsync(ITableEntity entity)
        {
            var op = TableOperation.InsertOrMerge(Expand(entity));
            return CloudTableContext.ExecuteAsync(op);
        }

        public void BulkInsertOrMerge(IEnumerable<ITableEntity> entities)
        {
            Bulk(op => op.InsertOrMerge, entities.Select(Expand), true);
        }

        public Task BulkInsertOrMergeAsync(IEnumerable<ITableEntity> entities)
        {
            return BulkAsync(op => op.InsertOrMerge, entities.Select(Expand), true);
        }

    }
}


text:
package org.revenj.database.postgres.jinq.jpqlquery;

public class ConstantExpression extends Expression {
	final String text;

	public ConstantExpression(String text) {
		this.text = text;
	}

	@Override
	public void generateQuery(QueryGenerationState queryState, OperatorPrecedenceLevel operatorPrecedenceScope) {
		queryState.appendQuery(text);
	}

	@Override
	public void prepareQueryGeneration(
			QueryGenerationPreparationPhase preparePhase,
			QueryGenerationState queryState) {
		// Nothing to do.
	}

	@Override
	public boolean equals(Object obj) {
		if (!getClass().equals(obj.getClass())) return false;
		ConstantExpression o = (ConstantExpression) obj;
		return text.equals(o.text);
	}

	@Override
	public void visit(ExpressionVisitor visitor) {
		visitor.visitConstant(this);
	}
}


text:
/**
 * @(#) BS_Wander.java
 */

import java.util.*;

/*
    Bot Wander state

    Technique:
        1. Bot moves freely & randomly, gathers any pickups it sees.
        2. If attacked - goes to Defend state.
        3. If has enough ammo and health & sees enemy - goes to attack state.
 */
public class BS_Wander extends BotState
{
    enum BotAction{
        NONE,
        WALK,
        GET_ITEM
    };

    static int          NORMAL_HEALTH = BS_Defend.NORMAL_HEALTH;

    private Random      m_random = new Random();
    private BotAction   m_action = BotAction.NONE;
    private PickUp      m_desiredItem = null;

    // invoked when this state is created
    public void onEnter( World world, Bot bot)
    {
        System.out.println("Bot "+bot.getName()+" entered Wander state");
    }

    // invoked when updating Bot
    public void onExecute( World world, Bot bot )
    {
        Graph g = world.getGraph();
        if(g == null) return;

        //----------------------------------------------------
        // 2 option: someone is attacking - deal with it
        //----------------------------------------------------
        if(bot.wasShot()){

            // find the shooter
            Player attacker = bot.getLastAttacker();
            if(attacker != null){
                ArrayList<Player> mem = new ArrayList<Player>();
                mem.add(attacker);
                bot.updateMemory(mem);
            }

            bot.changeState(new BS_Defend());
            return;
        }

        // move path finished?
        boolean walkIsDone = bot.hasPath() == false || bot.isPathDone();

        //----------------------------------------------------
        // 1 option: check if pickups are visible then go and fetch closest
        //----------------------------------------------------
        PickUp getItem = null;

        // bot is already seeking for an item
        if(m_desiredItem != null && m_desiredItem.isPicked())
        {
            // someone got there first and stole our item or we picked it
            walkIsDone = true;
            m_desiredItem = null;
            m_action = BotAction.NONE;
        }

        // choose next item only if we're not seeking for one
        if(m_action != BotAction.GET_ITEM)
        {
            getItem = world.getClosestVisiblePickup(bot);
            if(getItem != null) walkIsDone = true;
        }

        //----------------------------------------------------
        // 3 option: attack visible enemy!
        //----------------------------------------------------
        ArrayList<Player> enemies = world.getEnemiesVisible(bot);
        boolean canAttack = bot.getHealth() >= NORMAL_HEALTH && bot.getWeapon().getAmmo() > 0;

        if(enemies != null && enemies.size() > 0 && canAttack)
        {
            // update memory of the targets
            bot.updateMemory(enemies);

            // get aggressive
            bot.changeState(new BS_Attack());
            return;
        }

        //----------------------------------------------------
        // movement
        //----------------------------------------------------
        if(walkIsDone){

            vector2f gotoPos = null;

            if(getItem != null){ // go for an item that is nearby
                gotoPos = getItem.getPos().copy();
            }else{
                // choose new path by choosing random graph nodes
                int gotoId = m_random.nextInt(g.getNumNodes());
                gotoPos = g.getNode(gotoId).getPos().copy();
            }

            Path path = g.findPath(bot.getPos(), gotoPos);
            if(path != null) {
                //path.smooth(this);

                if(getItem != null){ // fetch item?
                    m_action = BotAction.GET_ITEM;
                    m_desiredItem = getItem;
                }else{
                    m_action = BotAction.WALK;
                }

                bot.setPath(path);
            }
        }else{
            // DO NOTHING

            // look where you move
            bot.targetView(bot.getPos().add(bot.getVelocity()), 0.5f);
        }

    }

    // invoked when this state is about to be destroyed
    public void onExit( World world, Bot bot)
    {

    }

    String getType(){
        return "w";
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations

def forwards_func(apps, schema_editor):
    State = apps.get_model("ivrs", "State")
    User = apps.get_model("users", "User")

    states = State.objects.all()
    for state in states:
        # Trimming the starting 0. Have checked to make sure
        # all telephones on the State table have 11 digits
        # including the 0 at the beginning.
        telephone = state.telephone[1:]
        try:
            user = User.objects.get(mobile_no=telephone)
            state.user = user
        except:
            pass
        state.telephone = telephone
        state.save()

def reverse_func(apps, schema_editor):
    State = apps.get_model("ivrs", "State")

    states = State.objects.all()
    for state in states:
        telephone = "0" + state.telephone
        state.telephone = telephone
        state.user = None
        state.save()

class Migration(migrations.Migration):

    dependencies = [
        ('ivrs', '0025_state_user'),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]


text:
<?php  ?>
<?php

class Moogento_NoMoreSpam_Model_NoMoreSpam extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('nomorespam/nomorespam');
    }
	public function getReviewsToday(){
		$today = date("Y-m-d");
		$review_collection     = Mage::getModel('review/review')->getCollection();
		$review_collection = $review_collection->addFieldToFilter('created_at',
		array(
		   'from' => $today,
		));
		return $review_collection;
	}

	public function checkCronTime()
    {
    	$mage_time = Mage::getModel('core/date')->timestamp(time());

		$current_time =  date('H:i:s', $mage_time);
    	$cron_config_time = Mage::getStoreConfig('no_more_spam/no_spam/specific_time');
    	$cron_period = 5;
    	if(is_numeric($cron_period))
    		$cron_period = 60*$cron_period;
    	else
    		$cron_period = 300;
    	$cron_config_time = str_replace(',',':',$cron_config_time);
    	$time_cron =  strtotime($current_time);
		$time_config = strtotime($cron_config_time);
		if((($time_cron -30) <= $time_config) && ($time_config <= ($time_cron + $cron_period -30)))
    	{
			return true;
    	}
    	return false;
    }

	public function sendEmailReview(){
		$new_no_spam_review_yn = mage::getStoreConfig("no_more_spam/no_spam/new_no_spam_review");
		$enabled_review_yn = mage::getStoreConfig("no_more_spam/no_spam/enabled_review");
		if($enabled_review_yn == 0)
		return;

		if($new_no_spam_review_yn==0)
		return;

		if($this->checkCronTime() == false)
			return;
		$review_collection = $this->getReviewsToday();
		$ids = array();
		$reviews_collection = array();
		foreach($review_collection as $review){

			$review_id = $review->getData('review_id');
			$ids[] =$review_id;
			$reviews_collection[] = $review;
		}
		Mage::helper("nomorespam")->sendEmailNotify($ids,$reviews_collection);
	}
}


text:
<title>war_dls :: Functions (Hytool Toolbox)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="hytool.css">

HYTOOL Function Reference

war_dls

 Dimensionless drawdown of Warren and Root (1963) solution

Syntax

war_dls(x,t)
    x(1) = sigma
    x(2) = lamda
    t = time

Description

    Calculates the dimensionless drawdown

  References:
    Warren, J. E., and P. J. Root (1963), The behaviour of naturally
    fractured reservoirs, Society of Petroleum Engineers Journal, 3,
    245-255.

See Also

war_lap
    Published output in the Help browser
       showdemo war_dls

Hytool

© 1998-2017 Philppe Renard and Co.
<tt class="minicdot">•</tt> Terms of Use
<tt class="minicdot">•</tt> Acknowledgments


text: Improve the names of parameters to some `MapFuncs`


text:
from setuptools import setup, find_packages
from codecs import open
from os import path

__author__ = 'Giulio Rossetti'
__license__ = "BSD-2-Clause"
__email__ = "giulio.rossetti@gmail.com"

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(name='ndlib',
      version='5.1.1',
      license='BSD-Clause-2',
      description='Network Diffusion Library',
      url='https://github.com/GiulioRossetti/ndlib',
      author='Giulio Rossetti',
      author_email='giulio.rossetti@gmail.com',
      use_2to3=True,
      entry_points={
          'console_scripts': [
              'NDQL_translate = scripts.NDQL_translate:translate',
              'NDQL_execute = scripts.NDQL_execute:execute'
          ],
      },
      classifiers=[
          # How mature is this project? Common values are
          #   3 - Alpha
          #   4 - Beta
          #   5 - Production/Stable
          'Development Status :: 5 - Production/Stable',

          # Indicate who your project is intended for
          'Intended Audience :: Developers',
          'Topic :: Software Development :: Build Tools',

          # Pick your license as you wish (should match "license" above)
          'License :: OSI Approved :: BSD License',

          "Operating System :: OS Independent",

          # Specify the Python versions you support here. In particular, ensure
          # that you indicate whether you support Python 2, Python 3 or both.
          'Programming Language :: Python',
          'Programming Language :: Python :: 3'
      ],
      keywords='epidemics opinion-dynamics simulator complex-networks',
      long_description=long_description,
      long_description_content_type='text/markdown',
      install_requires=['netdispatch', 'python-igraph', 'numpy', 'networkx', 'dynetx', 'scipy', 'bokeh', 'future', ''],
      packages=find_packages(exclude=["*.test", "*.test.*", "test.*", "test", "ndlib.test", "ndlib.test.*"]),
      )


text:
<?php
function __ant_build_commons_profile($startTime)
{
    ob_end_clean();
    echo "Execution time (s),Memory usage (Mb)", PHP_EOL;
    printf(
        "%d,%.2f",
        (time() - $startTime),
        (memory_get_peak_usage() / 1024 / 1024),
        PHP_EOL
    );
}

register_shutdown_function('__ant_build_commons_profile', time());

ob_start();


text:
/** @module reiter/unzip */

import iter from "./iter.js";
import next from "./next.js";

/**
 * Returns `iterables` to its pre-zip configuration. Essentially `zip` taking
 * an arbitrary number of iterables. Ceases yielding after the first iterable
 * in `iterables` is exhausted.
 *
 * @since 0.0.1
 * @generator
 * @function unzip
 * @param {ForOfIterable<ForOfIterable>} iterables The iterables.
 * @yields {Iterator} The next set of regrouped elements.
 * @see [zip]{@link module:reiter/zip}
 * @example
 *
 * reiter.unzip([["a", 1], ["b", 2], ["c", 3]])
 * // => ["a", "b", "c"], [1, 2, 3]
 *
 * reiter.unzip([["a", 1], ["b", 2], ["c", 3, null]])
 * // => ["a", "b", "c"], [1, 2, 3]
 */
export default function*(iterables) {
  const iterators = [...iterables].map(iter);
  if (iterators.length > 0) {
    for (;;) {
      const values = [];
      for (const iterator of iterators) {
        const { done, value } = next(iterator);
        if (done) return;
        values.push(value);
      }
      yield values;
    }
  }
}


text:
import os
import sys
import scilifelab.utils.fastq_utils as fastq_utils
import argparse

def main():

    parser = argparse.ArgumentParser(description="Filter reads from a pair of FastQ files based on the average quality."\
                                     "If the average quality of one of the reads in the pair is below the given threshold, "\
                                     "the pair is discarded. Output is a file named as INPUT.Q[T].[EXT], where T is the threshold "\
                                     "and EXT is the file extension. Accepts uncompressed or gzip-compressed input files")

    parser.add_argument('-T','--threshold', action='store', default=20,
                        help="if any read in the pair has an average quality below this threshold, the pair is discarded. Default is 20.")
    parser.add_argument('-p','--phred', action='store', default=33,
                        help="the Phred quality score offset. Default is 33 (Sanger)")
    parser.add_argument('--1.7', dest='casava17', action='store_true', default=False,
                        help="the fastq files were generated by a Casava version < 1.8")
    parser.add_argument('fastq1', action='store', default=None,
                        help="the first sequence file of the pair")
    parser.add_argument('fastq2', action='store', default=None,
                        help="the second sequence file of the pair")

    args = parser.parse_args()
    process_fastq(args.fastq1, args.fastq2, [int(args.threshold)], int(args.phred), args.casava17)

def print_average_quals(qualities):

    first = True
    for bin, avg_quality in sorted(qualities.items()):
        if first:
            print ",".join([str(i) for i in range(len(avg_quality)+1)])
            first = False
        avg_quality.insert(0,bin)
        print ",".join([str(i) for i in avg_quality])

def process_fastq(fastq_r1, fastq_r2, bins, phred_offset, casava17):

    fh_r1 = fastq_utils.FastQParser(fastq_r1)
    fh_r2 = fastq_utils.FastQParser(fastq_r2)
    oh1 = {}
    oh2 = {}
    root1, ext1 = os.path.splitext(fastq_r1)
    root2, ext2 = os.path.splitext(fastq_r2)
    for b in bins:
        oh1[b] = fastq_utils.FastQWriter("%s.Q%d%s" % (root1,b,ext1))
        oh2[b] = fastq_utils.FastQWriter("%s.Q%d%s" % (root2,b,ext2))

    for r1 in fh_r1:
        r2 = fh_r2.next()
        assert fastq_utils.is_read_pair(r1,r2,not casava17), "FATAL: Read identifiers differ for paired reads ({:s} and {:s})".format(r1[0],r2[0])

        bin = min(int(round(fastq_utils.avgQ(r1,phred_offset))),int(round(fastq_utils.avgQ(r2,phred_offset))))

        for b in bins:
            if bin >= b:
                oh1[b].write(r1)
                oh2[b].write(r2)

    for oh in oh1.values() + oh2.values():
        oh.close()

def quality_average(quality_str, phred_offset):
    sum = 0.
    for qual in quality_str:
        sum += ord(qual)
    sum -= len(quality_str)*phred_offset
    return sum/len(quality_str)

if __name__ == "__main__":
    sys.exit(main())


text:
// JS Hint directives and strict mode
/* globals exports,__filename */
'use strict';

//////////////////////////////////////////////////////////////////////////
// Requires and initialization
//////////////////////////////////////////////////////////////////////////

var _ = require('underscore');

//////////////////////////////////////////////////////////////////////////
// Configuration object
//////////////////////////////////////////////////////////////////////////

var configuration = {

  // secret key for sessions
  secret: "supersecretnotsosecrettestingkey",

  // authentication information
  auth: {

    // Google OAuth
    googleAuth: {
      clientID     : "testclientid",
      clientSecret : "testclientsecret",
      callbackURL  : "/auth/test/callback"
    }

  }

};

//////////////////////////////////////////////////////////////////////////
// Exports
//////////////////////////////////////////////////////////////////////////

module.exports = configuration;


text:
class Hear < Cask
  version '1.1.6'
  sha256 'e7b5e5782020be407f456e59167770b07afc97afb0f1f7e9d226c00c524b106b'

  url "https://s3.amazonaws.com/prosoft-engineering/hear/Hear_#{version}.dmg"
  appcast 'http://www.prosofteng.com/resources/sparkle/sparkle.php?psProduct=Hear',
          :sha256 => '48edc9b03ce5d9709b27fb5099dc3cce25cc8920656b9cdb9a066ae7999c8d9d'
  homepage 'http://www.prosofteng.com/products/hear.php'
  license :unknown

  app 'Hear.app'

  # todo: an uninstall stanza should be provided, and this message removed
  caveats <<-EOS.undent
    To uninstall, open Hear.app and choose the menu item "Hear > Uninstall"
  EOS
end


text:
FROM $USER/openmpi
NAME openmpi-client

# Add the control script to the image.
ADD ./helloworld.cpp /service/examples/
ADD ./test01.sh /service/runscripts/test/
RUN chmod a+x /service/runscripts/test/*

# Clear the apt cache.
RUN rm -rf /var/cache/apt/archives/*
RUN rm -rf /var/lib/apt/lists/*