text:
/******+===================================================================\
+======|                         IRC Parlour Bot - Bargain Bin Class .CPP  |
[      \-------------------------------------------------------------------+
[  This code file provides classes used in the Parlour Framework game      ]
[  Bargain Bin.                                                            ]
[                                                                          ]
[  Bargain Bin was written as an API example for the IRC Parlour Bot.      ]
[  I encourage you to look through it and make your own games!             ]
[                                                                          ]
[  This software is under the MIT license, which allows free distribution  ]
[  and modification of the below code, such that it is not used            ]
[  maliciously and that the code is not credited to someone else. See      ]
[  LICENSE for more information.                                           ]
[                                                                   /======+
\**************************************************************************/

#include "main.h" /// Our class and enums are here.
#include <ostream> /// For ostringstream

/// Output a player's name through an output stream
/// sout - The output stream
/// player - The player class item (it is a friend)
/// Return - The output stream (sout)
std::ostream &operator << (std::ostream &sout, BBPlayerData &player)
{
    /// Simply output the player's name in IRC colour 8,1 to the string stream.
    /// Whenever you colour something, it is good to terminate the colour tag
    /// (char 3) if the string does not end there.
	sout << "\0038,1" << player.Name() << "\003";
	return sout;
}

/// Return the player's hand in a string
/// Return - The player's hand...in a string. :P
std::string BBPlayerData::HandString()
{
    std::ostringstream sout; /// Output streams are fun!

    /// Iterate through the hand...
    for (QVector<ParlourSupport::PFSCardData>::iterator cardIter = hand.begin();
         cardIter != hand.end();
         cardIter++)
    {
        /// ...putting each card in the string.
        sout << " " << (*cardIter);
    }

    /// sout.str() is a basic_string, so cast it to an std::string and return it.
    return (std::string)sout.str();
}

/// Attempt to retrieve a card from a player's hand.
/// cardIn - The card's label as stated by the player
/// cardOut - The resulting card data, if located
/// Return - Whether the card was located in the player's hand (T/F)
bool BBPlayerData::GetCard(const std::string &cardIn, ParlourSupport::PFSCardData &cardOut)
{
    /// We only want the first two characters of the input string
    std::string aliasIn = cardIn.substr(0, 2);

    /// Iterate through the hand...
    for (QVector<ParlourSupport::PFSCardData>::iterator cardIter = hand.begin();
         cardIter != hand.end();
         cardIter++)
    {
        /// ...and see if we can find the specified card.
        if (MATCH_I(cardIter->Alias(), aliasIn))
        {
            /// We found such a card, so output it, remove it from the hand, and
            /// let the game know we found the requested card.
            cardOut = (*cardIter);
            hand.erase(cardIter);
            return true;
        }
    }
    return false; /// Didn't find a card, let the game know
}

/// Change the player's nick.
/// nickData - The QueueData containing the NICK event
/// Return - Whether the nick changed (T/F)
bool BBPlayerData::NickChange(QueueData &nickData)
{
    if (nickData.getType() != MSG_NICK) return false; /// If it's not a nick event, do nothing
    if (!MATCH(name, nickData.getNick())) return false; /// If it's the wrong person, do nothing

    name = nickData.getPost(); /// Change the nick to the new nick
    return true; /// Success!
}

/// Constructor; define our commands and instantiate variables.
/// initData - The data used to instance the game
/// Does not return
ParlourBBGame::ParlourBBGame(QueueData &initData)
{
    /// We create our commands here. The first parameter is the text command, and the
    /// second is the game's interpretation. Feel free to have multiple text commands for
    /// the same game command. "commands" is a QVector provided by the Framework, and
    /// CommandRef is a simple command lookup class also provided by the Framework.
    commands.push_back(CommandRef("join", PFBB_CMD_JOIN));
    commands.push_back(CommandRef("start", PFBB_CMD_START));
    commands.push_back(CommandRef("play", PFBB_CMD_PLAY));
    commands.push_back(CommandRef("status", PFBB_CMD_STATUS));
    commands.push_back(CommandRef("hand", PFBB_CMD_HAND));
    commands.push_back(CommandRef("turn", PFBB_CMD_TURN));
    commands.push_back(CommandRef("help", PFBB_CMD_HELP));
    commands.push_back(CommandRef("pstop", PFBB_CMD_STOP));

    /// "owner" is not entirely necessary, but helps to find out who created the game,
    /// and allow them exclusive access to certain commands. Provided by the Framework.
    owner = initData.getNick();
    /// "channel" is required for AddToSendQueue to work. Provided by the Framework.
    channel = initData.getDest();

    /// Instantiate our variables.
	state = PFBB_STATE_INVITE;
	lastStart = 0;

    /// Randomize the seed.
	srand(time(NULL));

    /// Post a welcome message to the channel.
	AddToSendQueue("BARGAIN BIN game is starting! Type \"join\" to play.");
	AddToSendQueue("\0034WARNING:\003 Game is in \002beta testing phase\002. Strange things or crashes may occur.");
}

/// Destroy the game. Do whatever proper cleanup you need to.
/// Does not return
ParlourBBGame::~ParlourBBGame()
{
    /// There's really not much we did here that the game won't clean up on its own.
}

/// Process a command sent to us by the core program.
/// cmdData - The data sent by the core program.
/// Return - Whether the game did anything with it. (T/F)
bool ParlourBBGame::ProcessCommand(QueueData &cmdData)
{
    switch (cmdData.getType())
    {
        case MSG_PRIVMSG: /// Private message
            /// If the core accidentally sends us a message for another channel, return out.
            /// This should not happen.
            if (cmdData.getDest() != channel) return false;

            /// Iterate through our commands.
            for (QVector<CommandRef>::iterator cmditer = commands.begin();
                 cmditer != commands.end(); cmditer++)
            {
                /// If we find a match, process it through DoCommand.
                if (MATCH_I(cmdData.getPost(), cmditer->cmdLine))
                    return DoCommand(cmdData, cmditer->cmdLine.size(), cmditer->cmdID);
            }
            break;

        case MSG_NICK: /// Nick change
            /// Iterate through our players.
            for (QVector<BBPlayerData>::iterator playerIter = players.begin();
                 playerIter != players.end();
                 playerIter++)
            {
                /// If we find a player by that name...
                if (playerIter->Name() == cmdData.getNick())
                {
                    /// Change their name.
                    playerIter->NickChange(cmdData);
                    return true;
                }
            }
            break;
    }
    return false; /// Nothing done; return false
}

/// Process timed events.
/// crnTime - The current time in Unix seconds.
/// Return - Whether we did anything with it. (T/F)
bool ParlourBBGame::ProcessChrono(time_t crnTime)
{
    std::ostringstream sout; /// Yay for stream!
    bool retVal = false; /// Our return value (assume false)

    /// Iterate through our timed events.
    for (QVector<ChronoEvent>::iterator timeiter = chrono.begin(); timeiter != chrono.end();
         timeiter++)
    {
        /// If we found an event due to be fired...
        if (timeiter->crnEnd <= crnTime)
        {
            /// Create a fake PRIVMSG event we probably won't need, but which DoCommand
            /// expects to get.
            sout << owner << " PRIVMSG " << channel << " :CHRONOEVENT " << timeiter->crnEnd << " "
                 << timeiter->crnCmd << " " << timeiter->crnID;

            /// Create a QueueData based on that PRIVMSG.
            QueueData fakeData(sout.str().c_str());
            /// Perform the command. The second parameter is 11 as the command token is
            /// CHRONOEVENT, 11 letters long.
            DoCommand(fakeData, 11, timeiter->crnCmd, timeiter->crnID);
            /// Destroy the used event.
            timeiter = chrono.erase(timeiter);
            /// We'll be returning true.
            retVal = true;
            /// Since we're inside a for loop, let's make sure we don't overstep the iterator's
            /// boundaries; if we're at the end, break out now.
            if (timeiter == chrono.end()) break;
        }
    }

    return retVal; /// Return our return value.
}

/// Perform a numeric command.
/// cmdData - The command data we're processing.
/// cmdLength - The length of the command token, so we can drop it if we need to
/// cmdID - The command number we're handling
/// crnID - The ID number of the timed event, if there is one
/// Return - Whether we did anything with it (T/F)
bool ParlourBBGame::DoCommand(QueueData &cmdData, int cmdLength, int cmdID, int crnID)
{
    if (cmdID == PFBB_CMD_STOP) /// Received a stop command.
    {
        if (cmdData.getNick() != owner) return false; /// Only the game's owner can stop the game
        AddToSendQueue("Bargain Bin now stopping. Goodbye!"); /// Say goodbye
        stopping = true; /// Announce to the core program that we're ready to stop the game
        return true;
    }

    /// Request for help; get help!
    if (cmdID == PFBB_CMD_HELP) return CmdHelp(cmdData);

    /// The remaining commands can only happen during certain game states.
    switch (state)
    {
        case PFBB_STATE_INVITE: /// During the invite phase:
            switch (cmdID)
            {
                /// Request to join game
                case PFBB_CMD_JOIN: return CmdJoin(cmdData); break;
                /// Request to start game
                case PFBB_CMD_START: if (cmdData.getNick() != owner) return false; return CmdStart(cmdData); break;
                /// We don't accept any other commands here, so return false. This line is present
                /// in all of our sub-switches, for safety's sake.
                default: return false; break;
            }
            break;
        case PFBB_STATE_INTURN: /// During the turn phase:
            switch (cmdID)
            {
                /// Request to play a card
                case PFBB_CMD_PLAY: return CmdPlay(cmdData); break;
                /// Request for game status
                case PFBB_CMD_STATUS:
                    /// If there's no request for a specific player, get current player status
                    if (cmdData.getPost().find(" ") == std::string::npos) return CmdStatus();
                    /// Otherwise, send the full request to the function
                    else return CmdStatus(cmdData.getPost().substr(cmdData.getPost().find(" ") + 1));
                    break;

                /// Request for player's hand; always get the requester's hand
                case PFBB_CMD_HAND: return CmdHand(cmdData.getNick()); break;
                /// Request for current turn
                case PFBB_CMD_TURN: return CmdCurTurn(); break;
                default: return false; break; /// Catchall safety
            }
            break;

        case PFBB_STATE_ENDHAND: /// End of hand pause
            /// Timed event to end hand
            if (cmdID == PFBB_CMD_CHRONO_ENDHAND)
            {
                Tally(); /// Tally our scores
                return true;
            }
            else return false;
            break;

        case PFBB_STATE_TALLY: /// Tally phase
            /// Request to resume game
            if (cmdID == PFBB_CMD_START) return CmdStart(cmdData);
            else return false;
            break;

        default: return false; break; /// State catchall
    }

    return false; /// We did nothing; return false
}

/// Requests to join the game are handled here.
/// inputData - Command data
/// Return - Whether we did anything here (T/F)
bool ParlourBBGame::CmdJoin(QueueData &inputData)
{
	std::ostringstream sout; /// Streeeeeeam~

    /// Iterate through our playes, and see if they haven't already joined.
	for (QVector<BBPlayerData>::iterator readList = players.begin();
         readList != players.end();
		 readList++)
	{
		if (readList->Name() == inputData.getNick())
		{
		    /// We found that this player already joined; don't let them join again.
			sout << (*readList) << "\0034, you've already joined!";
			AddToSendQueue(sout);
			return false;
		}
	}

    /// This game takes a maximum of ten players. Don't allow any more than that.
    if (players.size() == 10)
    {
        sout << "\00308,01" << inputData.getNick() << "\0034, the game is full!";
        AddToSendQueue(sout);
        return false;
    }

    /// Let's create a player and pop them onto the player vector.
    {
        BBPlayerData newPlayer(inputData.getNick());
        players.push_back(newPlayer);
        sout << players.back() << " has joined the game!";
        AddToSendQueue(sout);
    }

    /// If we have four players, let the owner know privately that the game can start.
	if (players.size() == 4)
	{
	    AddToSendQueue("Game is ready. You may now \002start\002 the game, or wait for more players (max 10).",
                        MSG_NOTICE, owner);
	}

    /// If we have ten players, let the channel know the game is full.
    if (players.size() == 10)
    {
        sout << "\0034The game is now full. \0038,1" << owner
             << "\003, \002start\002 the game!";
        AddToSendQueue(sout);
    }

	return true;
}

/// Requests to start the game are handled here.
/// inputData - Command data
/// Return - Whether we did anything here (T/F)
bool ParlourBBGame::CmdStart(QueueData &inputData)
{
	std::ostringstream sout; /// I would like to announce a stream.

    /// If we're in the invite phase...
	if (state == PFBB_STATE_INVITE)
	{
	    /// Make sure that the owner is calling "start".
	    if (inputData.getNick() != owner) return false;

        /// Make sure we have enough players.
		if (players.size() < 4)
		{
		    AddToSendQueue("\0034Not enough players!\003 Need at least four.");
		    return false;
		}
	}
	/// Otherwise, if it's not the Tally phase, return out. This should not happen.
    else if (state != PFBB_STATE_TALLY) return false;

    /// If this is the invite phase, we're starting the game.
    if (state == PFBB_STATE_INVITE) AddToSendQueue("Let's begin!");
    /// If this is the tally phase, let the next player start this hand.
    else
    {
        AddToSendQueue("Let's continue!");
        if (++lastStart == players.size()) lastStart = 0;
        players = lastStart;
    }

    deck.clear(); /// Empty the deck...
    ParlourSupport::GenStdDeck(deck); /// ...and get a new one

    /// Deal five cards to each player, starting "to the left" of the dealer.
    for (int X = 0; X < 5; X++)
    {
        for (size_t Y = 0; Y < players.size(); Y++)
        {
            players++;
            if (X == 0) (*players).ResetHand();
            PushCard();
        }
    }

    /// Set the state to the in-turn state, allowing players to play.
    state = PFBB_STATE_INTURN;

    /// Display turn information.
    CmdCurTurn();
    CmdStatus();
    CmdHand();

    return true;
}

/// Requests to play a card are handled here.
/// inputData - Command data
/// Return - Whether we did anything here (T/F)
bool ParlourBBGame::CmdPlay(QueueData &inputData)
{
    ParlourSupport::PFSCardData cardPick;   /// The card we're getting from the player's hand
	std::string::size_type matchPoint;      /// Used to determine player target
	std::string cardToken;                  /// The card to be played
	std::string targetToken;                /// The player receiving the card
	size_t playerTarget = -1;               /// The numeric ID of the above player

    /// If the current player did not issue the command, return out.
	if ((*players).Name() != inputData.getNick()) return false;

    /// Try to figure out what card is being played.
	matchPoint = inputData.getPost().find(" ");
	/// No card was found in the string. Return.
	if (matchPoint == std::string::npos)
    {
        AddToSendQueue("\0034You have not specified a card.\003 Please select a card to play.");
        return false;
    }

    /// Get the card token, and find the next space.
    cardToken = inputData.getPost().substr(matchPoint + 1);
    matchPoint = cardToken.find(" ");

    /// If there was no player specified, target self.
    /// The second clause supposes that someone typed "play [card] ", with a trailing space, which
    /// would result in a player name of a blank string.
    if (matchPoint == std::string::npos || cardToken.substr(matchPoint + 1) == "")
        playerTarget = (size_t)players;
    else
    {
        /// Get the player's name.
        targetToken = cardToken.substr(matchPoint + 1);
        /// Truncate the card token to the first space.
        cardToken = cardToken.substr(0, matchPoint);

        /// Iterate through the players.
        for (size_t X = 0; X < players.size(); X++)
        {
            /// If we find a player...
            if (MATCH_I(targetToken, players[X].Name()))
            {
                /// Target them!
                playerTarget = X;
                break;
            }
        }

        /// Didn't find a player; either choose someone playing or nobody
        if ((int)playerTarget == -1)
        {
            AddToSendQueue("\0034The target specified is not a player.\003 Please select a player on whom to play a card.");
            return false;
        }
    }

    /// Try to get the card from the player's hand
    if ((*players).GetCard(cardToken, cardPick))
    {
        std::ostringstream sout; /// OMGSTREAM

        /// If it's a red card, subtract points from the target's hand score
        if (cardPick.Suit() == ParlourSupport::PFS_SUIT_HEARTS ||
            cardPick.Suit() == ParlourSupport::PFS_SUIT_DIAMONDS)
            players[playerTarget] -= ((int)cardPick.Rank() + 1);
        /// If it's a black card, add points to the target's hand score
        else players[playerTarget] += ((int)cardPick.Rank() + 1);

        /// "[Player] plays [card] on"...
        sout << (*players) << " plays " << cardPick << " on ";
        /// If target is current player, "their self"...
        if (playerTarget == (size_t)players) sout << "their self";
        /// Otherwise, "[target]"...
        else sout << players[playerTarget];
        /// ", bringing their total to [hand score]."
        sout << ", bringing their total to " << players[playerTarget].HandScore() << ".";
        AddToSendQueue(sout);

        /// Next player.
        players++;
        /// If the player has no cards...
        if ((*players).CardsLeft() == 0)
        {
            /// Then nobody should have any cards left. End the hand.
            AddToSendQueue("\0037The hand is over.\003 Everyone has played their cards.");
            /// Create a timed event to tally scores in five seconds.
            chrono.push_back(ChronoEvent(time(NULL), 5, PFBB_CMD_CHRONO_ENDHAND));
            /// Change the state so nobody can issue any commands.
            state = PFBB_STATE_ENDHAND;
        }
        else
        {
            /// Display turn info.
            CmdCurTurn();
            CmdStatus();
            CmdHand();
        }
    }
    else
    {
        /// Couldn't find the card. Pick a valid card.
        AddToSendQueue("\0034Invalid card selection.\003 Please select a card in your hand to play.");
        return false;
    }
    return true;
}

/// Requests for game status are handled here.
/// nick - For whom we're getting their status (default to current player)
/// Return - Whether we did anything here (T/F)
bool ParlourBBGame::CmdStatus(std::string nick)
{
	std::ostringstream sout; /// I'm a little ostream, short and sout...
	size_t searchList = 0; /// Our search point in the player list

    /// If no player specified, assume the current player
    if (nick.empty()) searchList = (size_t)players;
    else
	{
	    /// Search the player list for the specified name.
	    for (searchList = 0; searchList < players.size(); searchList++)
	    {
	        /// If we find it, cut out of the loop.
            if (MATCH_I(nick, players[searchList].Name())) break;
	    }
	    /// Can't find the player.
        if (searchList == players.size()) return false;
	}

    /// "[Player] ([hand score]/[game score]) - [X] card(s) left."
    sout << players[searchList] << " (\00307" << players[searchList].HandScore() << "\003/\00309"
         << players[searchList].GameScore() << "\003) - " << players[searchList].CardsLeft()
         << " card" << (players[searchList].CardsLeft() != 1 ? "s" : "") << " left.";
    AddToSendQueue(sout);

    return true;
}

/// Requests for player's hand are handled here.
/// nick - For whom we're getting their hand (default to current player)
/// Return - Whether we did anything here (T/F)
bool ParlourBBGame::CmdHand(std::string nick)
{
	std::ostringstream sout; /// This is my input, this is my out.
	size_t searchList = 0; /// Search position

    /// If no nick specified, assume current player.
    if (nick.empty()) searchList = (size_t)players;
    else
	{
	    /// Search the player list for the specified name.
	    for (searchList = 0; searchList < players.size(); searchList++)
	    {
	        /// If we find it, cut out of the loop.
            if (MATCH_I(nick, players[searchList].Name())) break;
	    }
	    /// Can't find the player.
        if (searchList == players.size()) return false;
	}

    /// If the hand is empty, report it as such.
    if (players[searchList].CardsLeft() == 0) sout << "Your hand is empty.";
    /// Otherwise, get the hand from the player class.
    else sout << "Your hand:" << players[searchList].HandString();
    /// Send privately to player.
    AddToSendQueue(sout, MSG_NOTICE, players[searchList].Name());
    return true;
}

/// Requests for current turn are handled here.
/// Return - Whether we did anything here (pretty much invariably true)
bool ParlourBBGame::CmdCurTurn()
{
    /// Pretty self-explanatory here.
	std::ostringstream sout;
	sout << (*players) << " is up.";
	AddToSendQueue(sout);
	return true;
}

/// Requests for help are handled here.
/// inputData - Command data
/// Return - Whether we did anything here (T/F)
bool ParlourBBGame::CmdHelp(QueueData &inputData)
{
    std::ostringstream sout; /// Stream Party Tonite!
    std::string secondToken; /// Whatever the player might be requesting help for

    /// If the player is requesting help on a command, get the token from the post string
    if (inputData.getPost().find(" ") != std::string::npos)
        secondToken = inputData.getPost().substr(inputData.getPost().find(" ") + 1);

    /// Help tag
    sout << "[HELP] ";

    /// If there is a second token...
    if (!secondToken.empty())
    {
        /// Since we can't have switch cases for things that aren't numeric, here's a
        /// somewhat messy if statement!

        /// Pretty self-explanatory. For each command, return help and syntax for it.
        if (MATCH_IC(secondToken.c_str(), "join"))
        {
            sout << "\002JOIN\002: During the invitation phase, allows you to join the game. "
                 << "Presently can only be used before the game has started. Syntax: join";
        }
        else if (MATCH_IC(secondToken.c_str(), "start"))
        {
            sout << "\002START\002: Starts the game, or resumes it after a completed hand. ";
            if (inputData.getSender() != owner) sout << "Only the person who initiated the game "
                 << "may start it, but anyone may resume it. ";
            sout << "Syntax: start";
        }
        else if (MATCH_IC(secondToken.c_str(), "play"))
        {
            sout << "\002PLAY\002: Play a card from your hand. Black cards will increase the "
                 << "target player's score, and red cards will decrease it. If no target is "
                 << "specified, the card will be played on yourself. Syntax: play <card> [target]";
        }
        else if (MATCH_IC(secondToken.c_str(), "hand"))
        {
            sout << "\002HAND\002: Whether or not it is your turn, displays your hand to you "
                 << "in a private message. Syntax: hand";
        }
        else if (MATCH_IC(secondToken.c_str(), "status"))
        {
            sout << "\002STATUS\002: Whether or not it is your turn, displays general information "
                 << "about the current hand and about either the current or any other given player "
                 << "to the channel. Syntax: status [player]";
        }
        else if (MATCH_IC(secondToken.c_str(), "turn"))
        {
            sout << "\002TURN\002: Whether or not it is your turn, displays whose turn it is "
                 << "to the channel. Syntax: turn";
        }
        else if (MATCH_IC(secondToken.c_str(), "order"))
        {
            sout << "\002TURN\002: Whether or not it is your turn, displays the current player "
                 << "and next three players, as well as whether order is reversed, to the "
                 << "channel. Syntax: order";
        }
        /// Nothing wrong with a little Easter egg here and there.
        else if (MATCH_IC(secondToken.c_str(), "help help"))
        {
            sout << "\002HELP! HELP! HELP!\002: \"The most terrifying words in the English language "
                 << "are: I'm from the government and I'm here to help.\" -- Ronald Reagan";
        }
        else if (MATCH_IC(secondToken.c_str(), "help"))
        {
            sout << "\002HELP\002: Without a parameter, displays list of commands available to "
                 << "you at the current time. With a parameter, displays help about a given "
                 << "command. Syntax: help [command]";
        }
        else if (MATCH_IC(secondToken.c_str(), "pstop"))
        {
            if (inputData.getNick() == owner)
                sout << "\002PSTOP\002: Deinitializes and exits the game. This is required if a "
                     << "new game is to be started. The game exits automatically upon completion, "
                     << "or if the bot parts or is kicked from the channel, or quits IRC. "
                     << "Syntax: pstop";
            else sout << "\002PSTOP\002: This command stops the game, but only the person who "
                      << "initiated the game may do so.";
        }
        /// If there's a website where rules can be found, it's a good idea to let the player know
        /// where they can consult it.
        else if (MATCH_IC(secondToken.c_str(), "rules"))
        {
            sout << "\002RULES\002: For a full description of official rules, please visit "
                 << "http://kewliomzx.simguy.net/dropftp/BargainBin.txt .";
        }
        /// Finally, a catchall so that we can let the player know there's no such command.
        else
        {
            sout << "Command not recognized. Type \"help\" without parameters to view a list "
                 << "of commands available to you.";
        }
    }

    /// If there's no command stated, let the player know what they can do right now.
    else switch (state)
    {
        case PFBB_STATE_INVITE:
            sout << "The game is currently accepting players. Type \"join\" if you wish to "
                 << "play.";
            /// Remember that some commands may only be available to the person who instantiated.
            /// the game, or at certain times.
            if (inputData.getNick() == owner && players.size() >= 2)
                sout << " Type \"start\" at any time to begin the game.";
            break;

        case PFBB_STATE_INTURN:
            sout << "Available commands: ";
            /// Other commands may only be available to the current player.
            if ((*players).Name() == inputData.getNick()) sout << "play ";
            sout << "status hand turn (type \"help <command>\" to learn more)";
            break;

        case PFBB_STATE_ENDHAND:
            sout << "The game will resume in a few seconds. If it does not, a timed event "
                 << "may have failed to execute.";
            if (inputData.getSender() == owner)
                sout << " If still frozen after a minute, type \"pstop\" to exit the game.";
            break;

        case PFBB_STATE_TALLY:
            sout << "Type \"start\" to begin the next hand.";
            break;
    }

    /// Finally, send the help message privately to the player.
    AddToSendQueue(sout, MSG_NOTICE, inputData.getNick());
    return true;
}

/// Deal a card to the current player.
/// Return - void
void ParlourBBGame::PushCard()
{
    /// If the deck is empty, return out. This should never happen.
    if (deck.size() == 0) return;

    /// Pick a random card.
	int rCard = rand() % (int)deck.size();
	/// Create an iterator.
	QVector<ParlourSupport::PFSCardData>::iterator deckIter = deck.begin();
	/// Iterate to the random card.
	for (int X = 0; X < rCard; X++) deckIter++;

    /// Deal the card to the player.
	(*players) += (*deckIter);
	/// Remove the card from the deck.
	deck.erase(deckIter);
}

/// Score tally at the end of the hand. Determines if there is a winner.
/// Return - void
void ParlourBBGame::Tally()
{
    std::ostringstream sout;    /// Not one!
    std::ostringstream sout2;   /// Not two!
    std::ostringstream sout3;   /// But THREE streams! (Wouldn't need them all if you could clear them...)
    size_t topScore = -1;       /// Who the top scorer is
    size_t secondScore = -1;    /// Who the second top scorer is
    bool tie = false;           /// Whether there is a tie

    /// For now, assume the two first players in the list are the top scorers
    if (players[0].HandScore() > players[1].HandScore())
    {
        /// If player[0] has a better score, then player[1] is second
        topScore = 0;
        secondScore = 1;
    }
    else
    {
        /// If player[1] has a better score or if it's a tie, then make player[1] the top scorer
        topScore = 1;
        secondScore = 0;
    }

    /// Now, starting at player[2], compare these scores
    for (size_t X = 2; X < players.size(); X++)
    {
        /// If player[X] has a better hand score than the top scorer...
        if (players[X].HandScore() > players[topScore].HandScore())
        {
            /// If the old top scorer and second scorer are not tied, then there is no tie
            if (players[topScore].HandScore() != players[secondScore].HandScore()) tie = false;
            /// The old top scorer is now the second scorer
            secondScore = topScore;
            /// Player[X] is the top scorer
            topScore = X;
        }
        /// If player[X] has a better hand score than the second scorer...
        else if (players[X].HandScore() > players[secondScore].HandScore())
        {
            /// Player[X] is the second scorer
            secondScore = X;
            /// Logically, there cannot be a tie if this condition is met
            /// (player[X]'s score cannot be equal to anyone else's who has been evaluated)
            tie = false;
        }
        /// If player[X]'s score is equal to the second scorer, then there is a potential tie
        else if (players[X].HandScore() == players[secondScore].HandScore()) tie = true;
    }

    if (tie) /// If there's a tie...
    {
        /// If the two top scores are tied, then "tie" means a third player is tied.
        /// Per the rules, nobody gets a game point.
        if (players[topScore].HandScore() == players[secondScore].HandScore())
        {
            sout << "Three or more players are tied for first...\0034no points for anyone!\003";
        }
        /// If not, then it's a tie for second; therefore, only the top scorer get s game point
        else
        {
            players[topScore]++;
            /// "The top scorer was [player] ([hand score]). However, with two or more people
            ///  tied for second, only [player] gets a point!"
            sout << "The top scorer was "
                 << players[topScore] << " (\00307" << players[topScore].HandScore() << "\003). "
                 << "However, with two or more people tied for second, only "
                 << players[topScore] << " gets a point!";
        }
    }
    /// If there's no tie, the two top scorers get a game point.
    else
    {
        players[topScore]++;
        players[secondScore]++;
        /// "The top two scorers were [player] ([hand score]) and [player] ([hand score]).
        ///  Each gain a point."
        sout << "The top two scorers were "
             << players[topScore] << " (\00307" << players[topScore].HandScore() << "\003) and "
             << players[secondScore] << " (\00307" << players[secondScore].HandScore() << "\003). "
             << "Each gain a point.";
    }

    /// Whatever just happened above, send it to the channel.
    AddToSendQueue(sout);

    /// Reset these variables, as we'll be needing them again to determine a winner.
    topScore = -1;
    secondScore = -1;
    tie = false;

    /// Print out each player's game score standing.
    AddToSendQueue("The standings so far:");
    for (size_t X = 0; X < players.size(); X++)
    {
        if (X != 0) sout2 << " - ";
        sout2 << players[X] << " (\00303" << players[X].GameScore() << "\003)";

        /// While we're doing this, see if someone's reached 10 game points, the goal of the game.
        if (players[X].GameScore() == 10)
        {
            if ((int)topScore == -1) topScore = X;
            /// If a second player has 10 points, save us the trouble looking for the second
            /// winner afterward. There will never be three people at 10 game points.
            else secondScore = X;
        }
    }
    AddToSendQueue(sout2);

    /// If we found a winner...
    if ((int)topScore != -1)
    {
        /// If we didn't find a second winner already, look for it.
        if ((int)secondScore == -1)
        {
            /// Assume the second highest score is player[0], unless player[0] is the top scorer.
            /// Otherwise, assume it's player[1].
            secondScore = (topScore == 0 ? 1 : 0);

            /// Iterate through our player list.
            for (size_t X = 0; X < players.size(); X++)
            {
                /// Skip the top scorer. We already know they won.
                if (X == topScore) continue;

                /// If player[X]'s game score is higher than the second scorer...
                if (players[X].GameScore() > players[secondScore].GameScore())
                {
                    /// They become the second scorer.
                    secondScore = X;
                    /// Negate any previously existing tie.
                    tie = false;
                }
                /// If they're equal, then there's a tie for second.
                else if (players[X].GameScore() == players[secondScore].GameScore()) tie = true;
            }
        }

        /// If there's a tie for second, declare a sole winner.
        if (tie)
        {
            /// "With a game point tie for second, [player] is the SOLE WINNER for this game!
            ///  Congratulations!"
            sout3 << "With a game point tie for second, " << players[topScore] << " is the "
                  << "\00311,2SOLE WINNER\003 for this game! Congratulations!";
        }
        /// If there's no tie, then there are two winners.
        else
        {
            /// "[player] gets a SHARED VICTORY with [player]! Congratulations to both!"
            sout3 << players[topScore] << " gets a \00311,2SHARED VICTORY\003 with "
                  << players[secondScore] << "! Congratulations to both!";
        }
        /// Send this final message, and announce that the game is stopping.
        sout3 << " The game is now ending. To start again, type \"pstart bb\".";
        AddToSendQueue(sout3);
        stopping = true;
    }
    /// There is no winner, so we're ready to start the next hand.
    else
    {
        AddToSendQueue("Ready for the next hand? Type \002start\002 to continue!");
        state = PFBB_STATE_TALLY;
    }
}


text:
<resources>

    <declare-styleable name="GMThree">
        <attr name="topViewId" format="reference"></attr>
        <attr name="middleViewId" format="reference"></attr>
        <attr name="bottomViewId" format="reference"></attr>
    </declare-styleable>

</resources>

redpajama_set_name: RedPajamaGithub


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28639_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">SAMPLE PROGRAM:

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">LOGGING PROGRAM:
WELL STATUS:

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">COMPANY ENGINEER:

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">WELLSITE SUPERVISOR:
COMPANY GEOLOGIST:
WELLSITE GEOLOGIST:

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Wayne Miller, John Mullican, Wyatt Bodray, Adrian Mantei Tony Rios
Mitch Olson

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Caught: Examined: Saved: Quality:
No logs run
Awaiting completion
Jim Binegar

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">All
All Good to excellent

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">30' Vertical/Curve, 100' Horizontal
All


text:
import Ember from 'ember';

export default Ember.Component.extend({
    value: null,
    name: null,
    attributeBindings: ['value', 'style'],
    tagName: 'select',
    classNames: ['selectbox'],

    options: [],
    style: function() {
        var width = this.get('width');
        if (width) {
            return 'width:' + width + ';';
        }
        return '';
    }.property('width'),

    keyUp: function(e) {
        if (e.which === 13) {
            this.sendAction('submit', this.get('value'), this.get('name'));
        }
    },

    buildOptions: function() {
        var selectedValue = this.get('value'),
            labelProperty = this.getWithDefault('labelProperty', 'name'),
            valueProperty = this.getWithDefault('valueProperty', 'name'),
            defaultValue = [];
        if (!selectedValue) {
            defaultValue = [{value:'', label: '', selected: true}];
        } else {
            this.sendAction('changed', selectedValue, this.get('name'));
        }
        var seenSelected = false,
            arr = defaultValue.concat(this.get('options').map(function(opt) {
                if (typeof(opt) === 'string') {
                    opt = { value: opt };
                } else if (opt instanceof Ember.Object) {
                    opt = {
                        value: opt.get(valueProperty),
                        label: opt.get(labelProperty),
                    };
                } else {
                    opt = {
                        value: opt[valueProperty] || opt.value,
                        label: opt[labelProperty] || opt.label,
                    };
                }
                if (opt.value === selectedValue) {
                    seenSelected = true;
                }
                opt.label = opt.label || opt.value;
                opt.selected = opt.value === selectedValue;
                return opt;
            }));
        if (!seenSelected && selectedValue && this.get('addSelected')) {
            arr.push({
                value: selectedValue,
                label: selectedValue,
                selected: true
            });
        }
        return arr;
    },

    optionsList: function() {
        return this.buildOptions();
    }.property('value', 'options'),

    change: function(e) {
        if (e.type !== 'change') {
            return;
        }
        var originalEvent = e.originalEvent,
            target = originalEvent.explicitOriginalTarget || originalEvent.target,
            changedTo = target.value;
        this.set('value', changedTo);
        this.sendAction('changed', changedTo, this.get('name'));
    },
});


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Configuration;
using Epi.Web.Enter.Common.Constants;
using Epi.Cloud.PublishMetaData;
namespace PublishAndRepublishTest
{
    [TestClass]
    public class PublishRePublishTest
    {
        [TestMethod]
        public void PublishAndRepublishTest()
        {

        }

        [TestMethod]
        public void PublishRepublishTest()
        {

            MetaDataToCloud _publishMetaDataToCloud = new MetaDataToCloud();
            //Stop WebJob
            if (WebJobProcess(Constant.WebJob.Stop))
            {
                //Update the blob
                //Clear the Cache
                if (_publishMetaDataToCloud.ClearCache())
                {
                    //Start Web Job
                    var webJobResponse = _publishMetaDataToCloud.StartAndStopWebJob(Constant.WebJob.Start);
                    Assert.IsTrue(webJobResponse);
                }
            }

        }

        public bool WebJobProcess(string webJobStatus)
        {
            MetaDataToCloud _publishMetaDataToCloud = new MetaDataToCloud();
            if (_publishMetaDataToCloud.StartAndStopWebJob(webJobStatus))
            {
                return true;
            }
            return false;
        }
    }
}


text:
<?php

namespace PhpAb\Event;

use Zend\EventManager\EventManager;

/**
 * A dispatcher that uses the Zend Framework Event manager to dispatch events.
 *
 * @package PhpAb
 */
class ZendFrameworkDispatcher implements DispatcherInterface
{
    /**
     * The event manager used to dispatch events.
     *
     * @var EventManager
     */
    private $eventManager;

    /**
     * Initializes a new instance of this class.
     *
     * @param EventManager $eventManager
     */
    public function __construct(EventManager $eventManager)
    {
        $this->eventManager = $eventManager;
    }

    /**
     * Gets the event manager.
     *
     * @return EventManager
     */
    public function getEventManager()
    {
        return $this->eventManager;
    }

    /**
     * {@inheritDoc}
     *
     * @param string $event The name of the Event which should be dispatched
     * @param array $options The options that should get passed to the callback
     */
    public function dispatch($event, $options)
    {
        return $this->eventManager->trigger($event, $this, $options);
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../libc/struct.sockaddr_in.html">

Redirecting to ../../../libc/struct.sockaddr_in.html...


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
			  android:orientation="vertical"
			  android:background="@color/white"
			  android:layout_width="match_parent"
			  android:layout_height="match_parent">

	<include layout="@layout/application_header"/>

	<android.support.v4.view.ViewPager
			xmlns:android="http://schemas.android.com/apk/res/android"
			android:id="@+id/_activity_speaker_pager"
			android:layout_width="match_parent"
			android:layout_height="0dp"
			android:layout_weight="1"/>

</LinearLayout>


text:
package org.optaplanner.persistence.jaxb.api.score.buildin.hardmediumsoftbigdecimal;

import org.optaplanner.core.api.score.buildin.hardmediumsoftbigdecimal.HardMediumSoftBigDecimalScore;
import org.optaplanner.persistence.jaxb.api.score.AbstractScoreJaxbXmlAdapter;

/**
 * {@inheritDoc}
 */
public class HardMediumSoftBigDecimalScoreJaxbXmlAdapter extends AbstractScoreJaxbXmlAdapter<HardMediumSoftBigDecimalScore> {

    @Override
    public HardMediumSoftBigDecimalScore unmarshal(String scoreString) {
        return HardMediumSoftBigDecimalScore.parseScore(scoreString);
    }

}


text:
using System.Collections.Generic;

namespace NeuralNetworks.Training
{
    public interface ITrainer
    {
        void Train(List<TrainingElement> trainingData);
    }
}


text:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { createPost } from '../actions';

class PostsNew extends Component {
    renderField(field) {
        const { meta: { touched, error} } = field;
        const className = `form-group ${touched && error ? 'has-danger' : ''}`;

        return (

                {field.label}
                <input
                    className="form-control"
                    type="text"
                    {...field.input}
                />

                    {touched ? error : ''}

        );
    }

    onSubmit(values) {
        // go to root route
        this.props.createPost(values, () => {
            this.props.history.push('/');
        });
    }

    render() {
        const { handleSubmit } = this.props;

        return (
            <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
                <Field
                    label="Title for Post"
                    name="title"
                    component={this.renderField}
                />
                <Field
                    label="Categories"
                    name="categories"
                    component={this.renderField}
                />
                <Field
                    label="Post Content"
                    name="content"
                    component={this.renderField}
                />
                <button type="submit" className="btn btn-primary">Submit</button>
                <Link to="/" className="btn btn-danger">Cancel</Link>
            </form>
        );
    }
}

function validate(values) {
    const errors = {};

    // validate the inputs from 'values'
    if (!values.title) {
        errors.title = "Enter a title!";
    }
    if (!values.categories) {
        errors.categories = "Enter some categories";
    }
    if (!values.content) {
        errors.content = "Enter some content please";
    }
    // If error is empty, the form is fine to submit
    // If error has any properties, redux form assumes form is invalid
    return errors;
}

export default reduxForm({
    validate,
    form: 'PostsNewForm'
})(
    connect(null, { createPost })(PostsNew)
);


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;

namespace live.asp.net.Models
{
    public class LiveShowDetails
    {
        public string LiveShowEmbedUrl { get; set; }

        public string LiveShowHtml { get; set; }

        public DateTime? NextShowDateUtc { get; set; }

        public string AdminMessage { get; set; }
    }
}


text:
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharedLibrary.MongoDB
{
    public class MongoDbContext
    {
        #region ** Attributes **

        static string m_baseConnectionString = String.Empty;
        static string m_login = null;
        static string m_password = null;
        static MongoServer m_server = null;

        #endregion

        #region ** Core MongoDB Methods **

        /// <summary>
        /// Configures the specified login.
        /// </summary>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        /// <param name="addresses">List of addresses. Format: host1[:port1][,host2[:port2],...[,hostN[:portN]]]</param>
        /// <param name="safeMode">The safe mode. True to receive write confirmation from mongo.</param>
        /// <param name="readOnSecondary">The read on secondary. True to direct read operations to cluster secondary nodes (secondaryPreferred), else try to read from primary (primaryPreferred).</param>
        /// <param name="connectionTimeoutMilliseconds">The time to attempt a connection before timing out.</param>
        /// <param name="socketTimeoutMilliseconds">The time to attempt a send or receive on a socket before the attempt times out.</param>
        /// <param name="isReplicaSet">The is replica set hint.</param>
        /// <param name="readPreferenceTags">The read preference tags. List of a comma-separated list of colon-separated key-value pairs. Ex.: { {dc:ny,rack:1}, { dc:ny } } </param>
        public static void Configure (string login, string password, string authSrc, string addresses, bool safeMode = true, bool readOnSecondary = false, int connectionTimeoutMilliseconds = 60000, int socketTimeoutMilliseconds = 60000, IEnumerable<string> readPreferenceTags = null)
        {
            m_login = login;
            m_password = password;
            // prepares the connection string
            string connectionString = BuildConnectionString (login, password, authSrc, safeMode, readOnSecondary, addresses, connectionTimeoutMilliseconds, socketTimeoutMilliseconds, /*isReplicaSet, */ readPreferenceTags);
            // if there is any change, reconnect
            if (m_baseConnectionString != connectionString)
            {
                m_baseConnectionString = connectionString;
                Dispose ();
            }
        }

        /// <summary>
        /// Releases MongoDb resources.<para/>
        /// Obs.: the last Connection String is kept, so if any request is made, the resources will be recreated and the connection opened.
        /// </summary>
        public static void Dispose ()
        {
            m_server = null;
            m_docStore = new Lazy<MongoClient> (OpenConnection);
        }

        /// <summary>
        /// Forcefully closes all connections from the connection pool.<para/>
        /// Not recommended, since can cause some connection instability issues.
        /// </summary>
        public static void ForceDisconnect ()
        {
            if (m_server != null)
            {
                m_server.Disconnect ();
            }
        }

        /// <summary>
        /// Builds the connection string.
        /// </summary>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        /// <param name="safeMode">The safe mode. True to receive write confirmation from mongo.</param>
        /// <param name="readOnSecondary">The read on secondary. True to direct read operations to cluster secondary nodes (secondaryPreferred), else try to read from primary (primaryPreferred).</param>
        /// <param name="addresses">List of addresses. Format: host1[:port1][,host2[:port2],...[,hostN[:portN]]]</param>
        /// <param name="connectionTimeoutMilliseconds">The time to attempt a connection before timing out.</param>
        /// <param name="socketTimeoutMilliseconds">The time to attempt a send or receive on a socket before the attempt times out.</param>
        /// <param name="isReplicaSet">The is replica set hint.</param>
        /// <param name="readPreferenceTags">The read preference tags. List of a comma-separated list of colon-separated key-value pairs. Ex.: { {dc:ny,rack:1}, { dc:ny } } </param>
        public static string BuildConnectionString (string login, string password, string authSrc, bool safeMode, bool readOnSecondary, string addresses, int connectionTimeoutMilliseconds, int socketTimeoutMilliseconds,  IEnumerable<string> readPreferenceTags = null)
        {
            StringBuilder sb = new StringBuilder ("mongodb://", 230);
            // check credentials
            if (!String.IsNullOrWhiteSpace (login) && !String.IsNullOrWhiteSpace (password))
            {
                //Optional para when do not need the login and password
                //sb.Append (login).Append (':').Append (password).Append ('@');
            }

            // address
            sb.Append (addresses).Append ("/?");

            if (!String.IsNullOrEmpty(authSrc))
            {
                sb.Append("authSource=").Append (authSrc).Append("&");
            }

            // options
            //if (isReplicaSet)
            //    sb.Append ("connect=replicaset&");
            if (safeMode)
                sb.Append ("w=1&");
            else
                sb.Append ("w=0&");
            if (readOnSecondary)
            {
                sb.Append ("readPreference=secondaryPreferred&");
            }
            else
            {
                sb.Append ("readPreference=primaryPreferred&");
            }
            if (readPreferenceTags != null)
            {
                foreach (var tag in readPreferenceTags)
                {
                    if (String.IsNullOrWhiteSpace (tag))
                        continue;
                    sb.Append ("readPreferenceTags=").Append (tag.Trim ().Replace (' ', '_')).Append ('&');
                }
            }

            sb.Append ("connectTimeoutMS=").Append (connectionTimeoutMilliseconds).Append ("&socketTimeoutMS=").Append (socketTimeoutMilliseconds);

            // generate final connection string
            return sb.ToString ();
        }

        private static Lazy<MongoClient> m_docStore = new Lazy<MongoClient> (OpenConnection);

        static DateTimeSerializer _dateTimeSerializer = null;

        private static MongoClient OpenConnection ()
        {
            // create mongo client
            MongoClient client = new MongoClient (m_baseConnectionString);
            return client;
        }

        public static MongoClient Client
        {
            get { return m_docStore.Value; }
        }

        public static MongoServer Server
        {
            get
            {
                if (m_server == null)
                    m_server = Client.GetServer ();
                return m_server;
            }
        }

        public static MongoDatabase GetDatabase (string dbName)
        {
            return Server.GetDatabase (dbName);
        }

        #endregion
    }

	/// <summary>
    /// Some MongoDb helpers methods
    /// </summary>
    public static class MongoExtensions
    {
        /// <summary>
        /// Insert an item, retrying in case of connection errors..
        /// </summary>
        /// <typeparam name="T">The type of the item.</typeparam>
        /// <param name="col">The collection.</param>
        /// <param name="item">The item.</param>
        /// <param name="retryCount">The retry count in case of connection errors.</param>
        /// <param name="throwOnError">Throws an exception on error.</param>
        /// <returns></returns>
        public static bool SafeInsert<T> (this MongoCollection col, T item, int retryCount = 2, bool throwOnError = false)
        {
            int done = 0;
            // try to update/insert and
            // retry n times in case of connection errors
            do
            {
                try
                {
                    if (col.Insert (item).Ok)
                        return true;
                }
                catch (System.IO.IOException ex)
                {
                    // retry limit
                    if (throwOnError && done > (retryCount - 1))
                        throw;
                }
                catch (WriteConcernException wcEx)
                {
                    // duplicate id exception (no use to retry)
                    if (wcEx.CommandResult != null && (wcEx.CommandResult.Code ?? 0) == 11000)
                    {
                        if (throwOnError)
                            throw;
                        else
                            return false;
                    }
                    // retry limit
                    if (throwOnError && done > (retryCount - 1))
                        throw;
                }
            }
            while (++done < retryCount);
            // if we got here, the operation have failled
            return false;
        }

        /// <summary>
        /// Update or insert an item, retrying in case of connection errors.
        /// </summary>
        /// <typeparam name="T">The type of the item.</typeparam>
        /// <param name="col">The collection.</param>
        /// <param name="item">The item.</param>
        /// <param name="retryCount">The retry count in case of connection errors.</param>
        /// <param name="throwOnError">Throws an exception on error.</param>
        /// <returns></returns>
        public static bool SafeSave<T> (this MongoCollection col, T item, int retryCount = 2, bool throwOnError = false)
        {
            int done = 0;
            // try to update/insert and
            // retry n times in case of connection errors
            do
            {
                try
                {
                    if (col.Save (item).Ok)
                        return true;
                }
                catch (System.IO.IOException ex)
                {
                    // retry limit
                    if (throwOnError && done > (retryCount - 1))
                        throw;
                }
                catch (WriteConcernException wcEx)
                {
                    // retry limit
                    if (throwOnError && done > (retryCount - 1))
                        throw;
                }
            }
            while (++done < retryCount);
            // if we got here, the operation have failled
            return false;
        }

        /// <summary>
        /// Execute insert batch, retrying in case of connection errors.
        /// </summary>
        /// <typeparam name="T">The type of the item.</typeparam>
        /// <param name="col">The collection</param>
        /// <param name="items">list of items.</param>
        /// <param name="retryCount">The retry count in case of connection errors.</param>
        /// <param name="throwOnError">Throws an exception on error.</param>
        /// <returns></returns>
        public static bool SafeInsertBatch<T> (this MongoCollection col, IList<T> items, int retryCount = 2, bool throwOnError = false)
        {
            // try to insertbatch
            try
            {
                col.InsertBatch (items);
            }
            catch (Exception ex)
            {
                // in case of a insertbatch faillure,
                // update or insert each item individually
                for (int i = 0; i < items.Count; i++)
                {
                    if (!col.SafeSave (items[i], retryCount, throwOnError))
                    {
                        // in case of another faillure, give up saving items
                        return false;
                    }
                }
            }
            return true;
        }
    }
}


text:
<title>Customising XSite</title>

XSite under the hood

XSite can be customised using the following main components:

SitemapLoader: defaults to XStream-based loader

PageExtractor: defaults to SiteMesh-based page extractor

Skin: defaults to Freemarker-based skin

LinkValidators: a list of link validators

FileSystem: defaults to Commons-IO filesystem

All default components can be overridden via the conf/xsite.xml composition resource found in the binary distribution, and specifiable via
the '-f' (if a file resource) or '-R' (if a classpath resource) options.

SiteMesh components

The context extraction is by default done by SiteMesh. SiteMesh does not only extract the content, but is also
able to modify it on the fly based on tag rules and text filters. Some of it are being used by XSite already
internally, but others are available (from SiteMesh directly or from XSite). Implementations of both types can be
registered in the composition resource.

Text Filter

Text filter are applied to the extracted text value. Following TextFilter implementations are available:

RegexReplacementTextFilter

Text replacement with regular expressions

MailToLinkTextFilter

Syntax to inject a mailto: link with parameters into the text of a page.

Tag Rules

A TagRule processes HTML tags. Note, that it is not possible to process the same tag twice with different rules.
Following TagRule implementations are available and useful in the context of XSite:

FramesetRule

The rule will simply add the property "frameset" with value "true" to the properties of the current Page model.

HtmlAttributesRule

The rule will add all attributes of the HTML tag as property to the current Page model.

MetaTagRule

The rule will add all attributes of the meta tags in the HTML header as property to the current Page model.

ParameterExtractingRule

The rule will remove any tag named "parameter" and add its value as property with the name of the tag's attribute "name" to the current Page model.

TagReplaceRule

Replace the current tag with a different one.

AddClassAttributeToFirstHeaderRule

Add a class attribute to the first header tag.

H1ToTitleRule

Extract the content of the first H1 tag and provide it in as title in the page model.

ImgAttributesRule

Extracts attributes for an image from the src attribute.

DropDivOfClassSectionRule

Special rule for Doxia/Maven generated HTML pages that nest any header tag (H1-6) into div elements with
	class "section". The rule will remove these div tags and therefore unnest the inner elements again.

TopLevelBlockExtractingRule

Special rule for the body of the HTML page, that extracts all HTML top level block elements as individual
	paragraphs. The rule will add the number of paragraphs as property "paragraphs" and all the
	individual paragraphs as property "paragraph.<i>" with i starting with 0. The
	Page model provides the paragraphs directly as list for your convenience.


text:
bool g_myResourceReleaseMethodCalled = false;

extern "C" DLL_EXPORT void __stdcall MyResourceReleaseMethod(HANDLE hnd)
{
    g_myResourceReleaseMethodCalled = true;

    //call CloseHandle to actually release the handle corresponding to the SafeFileHandle
    CloseHandle(hnd);
}

extern "C" DLL_EXPORT bool GetMyResourceReleaseMethodCalled()
{
    return g_myResourceReleaseMethodCalled;
}

extern "C" DLL_EXPORT void ResetMyResourceReleaseMethodCalled()
{
    g_myResourceReleaseMethodCalled = false;
}

extern "C" DLL_EXPORT void __stdcall SHReleasing_OutParams(IUnknown* ppIUnknFOO, HANDLE* phnd, IUnknown** ppIUnknBAR, int* pInt)
{
    //initialize the hnd out param
    *phnd = (HANDLE)123;

    //initialize the IUnknBAR out param
    *ppIUnknBAR = ppIUnknFOO;
    ppIUnknFOO->AddRef(); //addref Foo

    //initialize the int out param
    *pInt = 123;
}


text:
$(document).ready( function() {
    ngm_editor = {
        init: function (config) {
            ngm_editor.dataSourceUri = config.dataSourceUri;
            ngm_editor.layers = config.layers;
            var controls = $('#ngm-editor');
            var objectTypes = ngm_editor.loadObjectTypes();
            for (var i=0; i<ngm_editor.layers.length; i++) {
                controls.append();
                var html = '<fieldset class="'+ngm_editor.layers[i].class+'"><legend>'+ngm_editor.layers[i].name+'</legend>';
                var objects = objectTypes.filter(function(el){return (el.layer == i);});
                for (var j=0; j<objects.length; j++) {
                    //console.log(objects[j]['attribs']['image']);
                    html = html + '

';
                }
                html = html + '</fieldset>';
                controls.append(html);
            }

            $("#ngm-editor .object").on('click', function (e) {
                e.preventDefault();
                $("#ngm-editor .object").removeClass('selected');
                $(this).addClass('selected');
            });

            $(".grid-svg").on('click', function(e) {
                coords = ngm.toggleSelect(e);
                console.log(coords);
                var selectedType = $("#ngm-editor .object.selected");
                console.log(selectedType);
                var layerClass = selectedType.parent().attr('class');
                console.log(layerClass);
                var tmp = $(".grid-svg ."+layerClass);
                console.log(tmp);
            });
        },
        loadObjectTypes: function() {
            // currently use of dummy data
            return (function () {
                var json = null;
                $.ajax({
                    jsonp: 'jsonp_callback',
                    'async': false,
                    'global': false,
                    'url': ngm_editor.dataSourceUri,
                    'dataType': "json",
                    'success': function (data) {
                        json = data;
                    }
                });
                return json;
            })();
        },
        exportMap: function() {
            var objects_data = [];
            $('.ngm svg g').children().each(function(i, item){
                var layer_class = $(this).parent().attr('class');
                if (this.tagName == 'rect' || this.tagName == 'circle') {
                    objects_data.push({
                        'attr': {
                            'class' : $(this).attr('class'),
                            'title' : $(this).attr('title')
                        },
                        'x' : $(this).data('x'),
                        'y' : $(this).data('y')
                    });
                }
            });
            return objects_data;
        }
    };
});


text:
import React from 'react';
import {
    Link
} from 'react-router';

import ArticleListStore from '../stores/ArticleListStore';
import ArticleListActions from '../actions/ArticleListActions';
import LogActions from '../actions/LogActions';
import Pages from './Pages';
import SideColumn from './SideColumn';
import Weixin from './Weixin';

class ArticleList extends React.Component {
    constructor(props) {
        super(props);
        this.state = ArticleListStore.getState();
        this.onChange = this.onChange.bind(this);
        this.limit = 10;
        this.stop = true;
        this.page = props.params && props.params.page ? parseInt(props.params.page) : 1;
        this.maxShowLength = 150;
        this.url = location.href.split('#')[0];
        this.autoLoadCount = 6;
    }

    componentDidMount() {
        Weixin.updateUrlCode();
        console.log("ArticleList", "componentDidMount");
        $(".active").removeClass("active");
        $("#quickRead").addClass("active");
        ArticleListStore.listen(this.onChange);
        const page = this.props.params && this.props.params.page ? this.props.params.page : 1;
        ArticleListActions.getArticles(page, this.limit);
        var that =this;
        $(window).scroll(function() {
            //当内容滚动到底部时加载新的内容 100当距离最底部100个像素时开始加载.
            if ($(this).scrollTop() + $(window).height() + 50 >= $(document).height() && $(this).scrollTop() > 100) {
                if(that.stop==true){
                    that.stop=false;
                    //加载提示信息
                    $(".pc-center-box").append("

");
                    ArticleListActions.getMoreArticles(++that.page, that.limit).then(
                            data => that.addNewArticle(data.data)
                    );
                }
            }
        });
        this.bindGetMoreDetailEvent();
    }

    componentWillUnmount() {
        ArticleListStore.unlisten(this.onChange);
        $(window).unbind('scroll');
    }
    componentDidUpdate(prevProps) {
        const lastPage = prevProps.params && prevProps.params.page ? prevProps.params.page : 1;
        const page = this.props.params && this.props.params.page ? this.props.params.page : 1;
        if (lastPage != page) {
            ArticleListActions.getArticles(this.props.params.page, this.limit);
        } else {
            //scroll(0, 0);
        }

    }
    addNewArticle(news){
        $(".spinner").remove();
        this.setState({
            data:{
                data:this.state.data.data.concat(news)
            }});
        if(this.autoLoadCount>0){
            this.autoLoadCount--;
        }else{
            $(window).unbind('scroll');
            $(".pc-center-box").append("

点击加载更多

");
        }
        this.stop=true;
    }
    bindGetMoreDetailEvent(){
        var that = this;
        $("#pc-body-box").on('click','.pc-click-get-more',function(){
            if(that.stop==true){
                that.stop=false;
                $(".pc-click-get-more").remove();
                //加载提示信息
                $(".pc-center-box").append("

");
                ArticleListActions.getMoreArticles(++that.page, that.limit).then(
                        data => that.addNewArticle(data.data)
                );
            }
        });
        $("#pc-body-box").on('click','.open-close-icon-act',function(){
            var pNode = $(this).parent().parent().find(".pc-card-info p");
            var currentHtml = pNode.html();
            var attrHtml = pNode.attr("data-p-text");
            if(!!attrHtml){
                pNode.html(attrHtml);
                pNode.attr("data-p-text",currentHtml);
                if($(this).parent().find(".glyphicon-chevron-down").length>0){
                    $(this).parent().find(".glyphicon-chevron-down").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
                }else if($(this).parent().find(".glyphicon-chevron-up").length>0){
                    $(this).parent().find(".glyphicon-chevron-up").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
                }
            }
        });
        $(".pc-center-box").on('click','.pc-card-info-act',function(){
            var pNode = $(this).parent().find(".pc-card-info p");
            var currentHtml = pNode.html();
            var attrHtml = pNode.attr("data-p-text");
            if(!!attrHtml){
                pNode.html(attrHtml);
                pNode.attr("data-p-text",currentHtml);
                if($(this).parent().find(".glyphicon-chevron-down").length>0){
                    var artid = pNode.attr("data-p-artid");
                    var artTitle = pNode.attr("data-p-title");
                    LogActions.quickReadLog(artid, artTitle);
                    $(this).parent().find(".glyphicon-chevron-down").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
                }else if($(this).parent().find(".glyphicon-chevron-up").length>0){
                    $(this).parent().find(".glyphicon-chevron-up").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
                }
            }
        });
    }
    onChange(state) {
        this.setState(state);

    }
    getPage() {
        return this.props.params && this.props.params.page ? this.props.params.page : 1;
    }

    getThumbnail(article) {
        var thumbnail = article.thumbnail;
        if (thumbnail != "") {
            return (

                <Link to={'/article/' + article.id}></Link>

)
        }
        return "";
    }
    render() {
        var that = this;
        function subContent(str) {
            if(str.length>that.maxShowLength){
                return str.substr(0, that.maxShowLength)+'...';
            }
            return str;
        }
        function readTime(time){

            //let data = new Date(time);
            let diff = (new Date().getTime() - parseInt(time))/1000;
            let aDate = 86400;
            let aHour = 3600;
            if(diff < aHour){
                let minute = Math.ceil(diff/36);
                return minute + "分钟前"
            }
            if(diff < aDate){
                let hour = parseInt(diff/aHour);
                return hour + "小时前"
            }
            if(diff < 2*aDate){
                return "1天前"
            }
            if(diff < 3*aDate){
                return "2天前"
            }
            if(diff < 4*aDate){
                return "3天前"
            }
            if(diff < 5*aDate){
                return "4天前"
            }
            if(diff < 6*aDate){
                return "5天前"
            }
            if(diff < 7*aDate){
                return "6天前"
            }
            if(diff < 8*aDate){
                return "7天前"
            }
            if(diff < aDate*30){
                return "7天以前"
            }
            if(diff < aDate*60){
                return "一个月前"
            }
            return "a天前";
        }
        function markTag(tags){
            var i = 0;
            return tags.map((tag) => (
                {tag}
            ))
        }
        let cookie;
        if(document.cookie.split("articles=")[1] && document.cookie.split("articles=")[1] != ""){
            cookie = JSON.parse(unescape(document.cookie.split("articles=")[1].split(";")[0]))
        }else{
            cookie = []
        }
        let cookie_art = new Set(cookie);
        let articles = this.state.data.data;
        let artclelist = articles.map(function(article) {
            let title_class = "title_link";
            var hasread = false;
            if(cookie_art.has(article.id)){
                title_class = "title_link read";
                hasread = true;
            }
            if(!!!article.tags) article.tags=[];
            if(!!!article.smartSummary) article.smartSummary='';
            var tagsLen = article.tags.length;
            var tagsPClassName = "glyphicon glyphicon-tags cd-tag-icon";
            var currentTags = [];
            var iconClass= "glyphicon glyphicon-chevron-down open-close-icon open-close-icon-act";
            var textClass= "col-xs-12 pc-card-info pc-card-info-act";
            if(article.smartSummary.length<=that.maxShowLength){
                iconClass= "glyphicon glyphicon-chevron-down open-close-icon hide";
                textClass= "col-xs-12 pc-card-info";
            }
            if(hasread){
                textClass += " read";
            }
            if(tagsLen>0){
                if(tagsLen>4){
                    for(var i=0;i<4;i++){
                        currentTags.push(article.tags[i]);
                    }
                }else{
                    currentTags = article.tags;
                }
            }else{
                tagsPClassName = "glyphicon glyphicon-tags cd-tag-icon hide";
            }
            /*

             {that.getThumbnail(article)}

            */
            return (

{article.title}

                                            {readTime(article.createDate)}

                                            {markTag(currentTags)}

                                            {subContent(article.smartSummary)}

            );
        });

        return (

                                {artclelist}

                    <SideColumn />

        );
    }
}

export default ArticleList;


text:
package ac.simons.biking2.support;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;

/**
 * @author Michael J. Simons, 2017-04-19
 */
public class RegexMatcher extends BaseMatcher<String> {

    private final String regex;

    public RegexMatcher(String regex) {
        this.regex = regex;
    }

    @Override
    public boolean matches(Object o) {
        return ((String) o).matches(regex);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("matches regex=" + this.regex);
    }

    public static RegexMatcher matches(String regex) {
        return new RegexMatcher(regex);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.btc_e_assist">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:name="com.btc_e_assist.App"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher_icon"
        android:label="@string/app_name"
        android:theme="@style/BaseCustomTheme" >
        <activity
            android:name="com.btc_e_assist.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.btc_e_assist.TickerActivity"
            android:label="@string/title_activity_ticker"
            android:parentActivityName="com.btc_e_assist.MainActivity" >

            <!-- Parent activity meta-data to support API level 7+ -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name="com.btc_e_assist.TradeActivity"
            android:parentActivityName="com.btc_e_assist.TickerActivity"
            android:windowSoftInputMode="stateHidden|adjustPan" >

            <!-- Parent activity meta-data to support API level 7+ -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".TickerActivity" />
        </activity>
        <activity
            android:name="com.btc_e_assist.ProfileActivity"
            android:label="@string/title_activity_addprofile"
            android:parentActivityName="com.btc_e_assist.MainActivity"
            android:windowSoftInputMode="stateHidden|adjustPan" >

            <!-- Parent activity meta-data to support API level 7+ -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name="com.btc_e_assist.NewsContentActivity"
            android:parentActivityName="com.btc_e_assist.ChatActivity" >

            <!-- Parent activity meta-data to support API level 7+ -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".ChatActivity" />
        </activity>
        <activity
            android:name="com.btc_e_assist.FinancesActivity"
            android:label="@string/title_activity_finances"
            android:parentActivityName="com.btc_e_assist.MainActivity" >

            <!-- Parent activity meta-data to support API level 7+ -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name="com.btc_e_assist.AssistActivity"
            android:label="@string/title_activity_assist"
            android:parentActivityName="com.btc_e_assist.MainActivity"
            android:windowSoftInputMode="stateHidden|adjustPan" >

            <!-- Parent activity meta-data to support API level 7+ -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name="com.btc_e_assist.ChatActivity"
            android:label="@string/title_activity_finances"
            android:parentActivityName="com.btc_e_assist.MainActivity" >

            <!-- Parent activity meta-data to support API level 7+ -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity
            android:name="com.btc_e_assist.AboutActivity"
            android:label="@string/about_title"
            android:parentActivityName="com.btc_e_assist.MainActivity" >

            <!-- Parent activity meta-data to support API level 7+ -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity android:name="com.btc_e_assist.SettingsActivity" >
        </activity>
        <!-- Declaring broadcast receiver for BOOT_COMPLETED event -->
        <receiver
            android:name="com.btc_e_assist.AutostartReceiver"
            android:enabled="true"
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.btc_e_assist.ServiceAssist"
            android:exported="false" />

        <receiver
            android:name="com.btc_e_assist.Widget"
            android:label="BTC-e 4x1" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_meta" >
            </meta-data>
        </receiver>
        <receiver
            android:name="com.btc_e_assist.WidgetHalf"
            android:label="BTC-e 2x1" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_half_meta" >
            </meta-data>
        </receiver>

        <activity
            android:name="com.btc_e_assist.WidgetConfigActivity"
            android:label="@string/title_widget_config" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.btc_e_assist.WidgetHalfConfigActivity"
            android:label="@string/title_widget_config" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package gov.nih.nci.cagrid.syncgts.tools;

import gov.nih.nci.cagrid.syncgts.bean.SyncDescription;
import gov.nih.nci.cagrid.syncgts.core.SyncGTS;
import gov.nih.nci.cagrid.syncgts.core.SyncGTSDefault;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

public class SyncGTSCommand {

	public static final String DESCRIPTION_OPT = "d";
	public static final String DESCRIPTION_OPT_FULL = "description";
	public static final String ONCE_OPT = "o";
	public static final String ONCE_OPT_FULL = "once";
	public static final String HELP_OPT = "h";
	public static final String HELP_OPT_FULL = "help";

	public static void main(String[] args) {
		Options options = new Options();
		Option help = new Option(HELP_OPT, HELP_OPT_FULL, false, "Prints this message.");
		Option desc = new Option(DESCRIPTION_OPT, DESCRIPTION_OPT_FULL, true,
			"The path to the synchronization description file.");
		desc.setRequired(false);
		Option once = new Option(ONCE_OPT, ONCE_OPT_FULL, false,
			"Specifiy this option if you wish to sync with the GTS only once.");
		once.setRequired(false);

		options.addOption(help);
		options.addOption(desc);
		options.addOption(once);

		try {
			CommandLineParser parser = new PosixParser();
			CommandLine line = parser.parse(options, args);

			if (line.hasOption(HELP_OPT)) {
				HelpFormatter formatter = new HelpFormatter();
				formatter.printHelp(SyncGTSCommand.class.getName(), options);
				System.exit(0);
			} else {
				if (line.hasOption(DESCRIPTION_OPT)) {
					SyncGTSDefault.setServiceSyncDescriptionLocation(line.getOptionValue(DESCRIPTION_OPT));
				}
				SyncDescription description = SyncGTSDefault.getSyncDescription();
				if (line.hasOption(ONCE_OPT)) {
					try {
						SyncGTS sync = SyncGTS.getInstance();
						sync.syncOnce(description);
						System.exit(0);
					} catch (Exception e) {
						e.printStackTrace();
						System.exit(1);
					}

				} else {
					try {
						SyncGTS sync = SyncGTS.getInstance();
						sync.syncAndResync(description, false);
					} catch (Exception e) {
						e.printStackTrace();
						System.exit(1);
					}
				}
			}

		} catch (ParseException exp) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp(SyncGTSCommand.class.getName(), options, false);
			System.exit(1);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}

	}

}


text:
import axios, { AxiosResponse } from 'axios';
import { useMutation, useQueryClient } from 'react-query';

import { getMetaValue } from 'src/utils';
import type { API } from 'src/types';
import useErrorToast from 'src/utils/useErrorToast';

import { emptyGridData } from './useGridData';
import type { GridData } from './useGridData';

const setDagRunNoteURI = getMetaValue('set_dag_run_note');

interface Props {
  dagId: string;
  runId: string;
}

export default function useSetDagRunNote({
  dagId, runId,
}: Props) {
  const queryClient = useQueryClient();
  const errorToast = useErrorToast();
  const setDagRunNote = setDagRunNoteURI.replace('_DAG_RUN_ID_', runId);

  return useMutation(
    ['setDagRunNote', dagId, runId],
    (note: string | null) => axios.patch<AxiosResponse, API.DAGRun>(setDagRunNote, { note }),
    {
      onSuccess: async (data) => {
        const note = data.note ?? null;

        const updateGridData = (oldGridData: GridData | undefined) => (
          !oldGridData
            ? emptyGridData
            : {
              ...oldGridData,
              dagRuns: oldGridData.dagRuns.map((dr) => (
                dr.runId === runId ? { ...dr, note } : dr)),
            }
        );

        await queryClient.cancelQueries('gridData');
        queryClient.setQueriesData('gridData', updateGridData);
      },
      onError: (error: Error) => errorToast({ error }),
    },
  );
}


text:
var util = require("util");
var BaseTrigger = require("./baseTrigger.js").BaseTrigger;
var createHandler = require('github-webhook-handler');
var _ = require('underscore');

/*
Tells you in chat when something happens to your repo. You need to set up a webhook as well.
room = string - where do you want events announced? REQUIRED.
path = string - where should github attach? (you might be running multiple bots on the same host. I am)
		Defaults to whatever you *name* the trigger. Path will be doubled because of the way this function works.
secret = string - use the same secret as you put in the webhook. You can consider it an API key for github to use when it connects to the bot.
showDetails = string - Show details of actions. IE the actual comment text added if true, otherwise just the username/place of the comment.
disabled, disabled = array - if you don't want *all* events enabled, then you should set a whitelist or blacklist with an array of items you want enabled/disabled.
			The individual values must be the event names from https://developer.github.com/v3/activity/events/types
			For subtypes like pullrequest actions, add the type, then / then the subtype. EG 'pull_request/synchronize'. * as a subtype means all subtypes.
			If you're using a blacklist *and* a whitelist, you need to explicitly add all subtypes to the blacklist/whitelist.
*/

var GithubTrigger = function() {
	GithubTrigger.super_.apply(this, arguments);
};

util.inherits(GithubTrigger, BaseTrigger);

var type = "GithubTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
	var trigger = new GithubTrigger(type, name, chatBot, options);
	trigger.options.path = options.path || name;
	trigger.options.showDetails = options.showDetails === false ? false : true;
	trigger.options.disabled = options.disabled || false;
	trigger.options.enabled = options.enabled || false;
	trigger.db = (function(){try{return JSON.parse(fs.readFileSync(trigger.options.dbFile));}catch(err){return {}}})();
	return trigger;
};

GithubTrigger.prototype._onLoad = function() {
	var that = this;
	try {
		if(!(that.options.rooms instanceof Array && that.options.rooms.length>0)) {
			that.winston.error(that.chatBot.name+" "+that.name+": options.rooms needs to be a single-length array");
			return false;
		}
		if(!that.options.secret) {
			that.winston.error(that.chatBot.name+" "+that.name+": options.secret is required");
			return false;
		}
		that.handler = createHandler({path: that.options.path,secret:that.options.secret});
	} catch(err) {
		that.winston.error(that.chatBot.name+"/"+that.name);
		that.winston.error(err.stack);
		return false;
	}
	var sm = function(text){
		_.each(that.options.rooms, function(room) {
			try {
				that._sendMessageAfterDelay(room,text);
			} catch(err) {
				that.winston.error(err.stack);
			}
		});
	}
	var sd = this.options.showDetails; //I should really start using NPP or something else that has autocompletion.
	this.addRouter(this.options.path).use(function(req, res) {
		that.winston.silly(this.chatBot.name+"/"+this.name+": Request inbound");
		that.handler(req, res, function(err) {
			that.winston.error(err);
			that.winston.silly(this.chatBot.name+"/"+this.name+": 404");
			res.statusCode = 404;
			res.end('no such location')
		});
	});
	this._callIfEnabled('*', function(event) {
		that.winston.silly(event);
	});
	this.handler.on('error', function(err) {
		that.winston.error(that.name+": Error: ");
		that.winston.error(err);
	});
	this._callIfEnabled('commit_comment', function (event) {
		var c = event.payload.comment;
		var message = "GitHub: "+c.user.login+" has commented on "+c['commit_id'].substr(0,8);
		message += c.html_url.split(c.commit_id).join(c.commit_id.substr(0,10)); //cut the hash, it's too %*(&@# long.
		message += that.options.showDetails ? "\n"+c.body : "";
		sm(message);
	});
	this._callIfEnabled('create', function (event) {
		var p = event.payload;
		sm("GitHub: "+p.sender.login+" has created a new "+p['ref_type']+", "+p.ref+", in "+(sd?"https://github.com/":"")+p.repository['full_name']);
	});
	this._callIfEnabled('delete', function (event) {
		var p = event.payload;
		sm("GitHub: "+p.sender.login+" has deleted "+p['ref_type']+", "+p.ref+", from "+(sd?"https://github.com/":"")+p.repository['full_name']);
	});
//	this._callIfEnabled('deployment', function (event) {       });  //wtf is this?
//	this._callIfEnabled('deployment_status', function (event) {	}); //ditto
	this._callIfEnabled('fork', function (event) {
		var p = event.payload;
		sm("GitHub: "+p.repository['full_name']+" has been forked to "+(sd?p.html_url:p.forkee['full_name']));
	});
	this._callIfEnabled('gollum', function (event) {
		var p = event.payload;
		sm("GitHub: "+p.pages[0].page_name+" wiki page has been "+p.pages[0].action+(sd?"\n"+p.pages[0].html_url:""));
	});
	this._callIfEnabled('issue_comment', function (event) {
		var p = event.payload;
		var msg = "GitHub: "+p.issue.user.login+" has "+p.action+" a comment on "+p.issue.number
		if(sd) msg+=" ("+p.issue.title+")\n"+p.comment.body+"\n"+p.issue.html_url;
		else msg+= " at "+p.repository.full_name;
		sm(msg);
	});
	this._callIfEnabled('issues', function (event) {
		var p = event.payload;

		if(!this._checkIfEnabled('issues/'+p.action) && !this._checkIfEnabled('issues/'+'*')) {
			return; //check for subtypes
		}

		var msg = "GitHub: "+p.sender.login+" has "+p.action+" issue "+p.issue.number+(sd?"":" at "+p.repository.full_name);
		msg += sd||p.action==="opened" ? " ("+p.issue.title+") " : "";
		if(p.action==="assigned") {
			msg+=" to "+p.issue.assignee.login;
		} else if(p.action==="unassigned") {
			msg += " from "+p.issue.assignee.login;
		} else if(p.action==="labeled") {
			msg += " as "+"<unknown, check debug log>";
		} else if(p.action==="unlabeled") {
			msg += " as "+"<unknown, check debug log>";
		} else if(p.action==="opened" && sd) {
			msg += "\n"+p.issue.body;;
		}
		if(sd) {
			msg += "\n"+p.issue.html_url;
		}
		sm(msg);
	});
	this._callIfEnabled('member', function (event) {
		var p = event.payload;
		sm("GitHub: "+p.sender.login+" has "+p.action+" "+p.member.login+" as a collaborator at "+(sd?p.repository.html_url:p.repository.full_name));
	});
//	this._callIfEnabled('membership', function (event) {	}); //MEH
//	this._callIfEnabled('page_build', function (event) {	}); //nobody cares
	this._callIfEnabled('public', function (event) { //nobody cares about this either, but whatever
		var p = event.payload;
		sm("GitHub: "+p.sender.login+" has made "+(sd?p.repository.html_url:p.repository.full_name)+(p.repository.private?" private":" public"));
	});
	this._callIfEnabled('pull_request_review_comment', function (event) {
		var p = event.payload;
		var pr = p.pull_request;
		var c = p.comment;
		var message = "GitHub: "+c.user.login+" has commented on pull request "+pr.number + (sd?" ("+pr.title+")":"");
		message += " at "+c.html_url+(that.options.showDetails ? "\n"+c.body : "");
		sm(message);
	});
	this._callIfEnabled('pull_request', function (event) {
		var p = event.payload;

		if(!this._checkIfEnabled('pull_request/'+p.action) && !this._checkIfEnabled('pull_request/'+'*')) {
			return; //check for subtypes
		}

		var pr = p.pull_request;
		var b = pr.base;
		var h = pr.head;

		var msg = "GitHub: "+p.sender.login+" has "+p.action+" pull request "+pr.number;
		msg += sd||p.action==="opened" ? " ("+pr.title+") " : "";
		msg+= " into "+b.repo.full_name+(b.ref?"#"+b.ref:"")+" from "+h.repo.full_name+(h.ref?"#"+h.ref:"");

		if(p.action==="assigned") {
			msg+=" to "+pr.assignee;
		} else if(p.action==="unassigned") {
			msg += " from "+pr.assignee;
		} else if(p.action==="labeled") {
			msg += " as "+"<unknown, check debug log>";
		} else if(p.action==="unlabeled") {
			msg += " as "+"<unknown, check debug log>";
		} else if(p.action==="opened" && sd) {
			msg += "\nFrom: ";
			msg += "\n"+pr.body;
		} else if(p.action==="closed" && sd) {
			if(pr.merged) msg+="\nThis pull was previously merged by "+pr.merged_by;
		}
		if(sd) {
			msg += "\n"+pr.html_url;
		}
		sm(msg);
	});
	this._callIfEnabled('push', function (event) {
		console.log(event);
		var p = event.payload;
		var h = p.head_commit;
		if(!h) return;
		var msg = "GitHub: "+p.sender.login+" has pushed "+(p.commits.length>1?"commits":"a commit");
		msg += sd ? "\n" +h.message+"\n"+h.url.split(h.id).join(h.id.substr(0,10)) : " to "+p.repository.full_name;
		sm(msg);
	});
//	this._callIfEnabled('repository', function (event) {	}); //MEH
	this._callIfEnabled('release', function (event) {
		console.log(event);
	}); //not implemented, not enough details yet.

	this._callIfEnabled('status', function (event) {
		console.log(event);
	}); //I don't even remember what this one does
//	this._callIfEnabled('team_add', function (event) {	}); //go away, team
//	this._callIfEnabled('watch', function (event) {	}); //if you want to see when someone stars you, implement it yourself and submit a pull request
	return true;
}

GithubTrigger.prototype._stripCommand = function(message, command){
	if (message.toLowerCase().indexOf(command.toLowerCase()) === 0) {
		return message.substring(command.length+1);
	}
	return false;
}

GithubTrigger.prototype._callIfEnabled = function(hook,callback) {
	var that = this;
	if(!this._checkIfEnabled('hook')) {
		return false;
	}
	this.handler.on(hook, function(event) {
		try{
			callback(event);
		} catch(err) {
			that.winston.error(err.stack);
		}
	});
}

GithubTrigger.prototype._checkIfEnabled = function(hook) {
	if((this.options.disabled && this.options.disabled.indexOf(hook) === -1) || (this.options.enabled && this.options.enabled.indexOf(hook) > -1)) {
		return true;
	}
	return false;
}


text:
<!DOCTYPE html>
<html ng-app="myApp">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Expander Simple</title>
		<meta name="author" content="sanshishen">
		<!-- 2015-09-01 10:21:48 -->
		<link rel="stylesheet" type="text/css" href="./css/expanderSimple.css">
	</head>
	<body>
	    <div ng-controller="ExpanderCtrl">
	    	<expander class="expander" expander-title="title">
	    		{{text}}
	    	</expander>
	    </div>
	    <script type="text/javascript" src="../bower_components/angular/angular.js"></script>
	    <script type="text/javascript" src="./js/expanderSimple.js"></script>
	</body>
</html>


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpdox xmlns="http://phpdox.de/config">
	<project name="sdp-store" source="module" workdir="build/phpdox">
		<collector publiconly="false">
			<include mask="*.php" />
			<exclude mask="*Autoload.php" />
		</collector>

		<generator output="build">
			<build engine="html" enabled="true" output="api"/>
		</generator>
	</project>
</phpdox>