text:
#include "cppunit/cppunit_proxy.h"
#include "cppunit/test_beans.h"

namespace deque {
    namespace ci = cds::intrusive   ;
    namespace co = cds::opt         ;

    class IntrusiveDequeHeaderTest: public CppUnitMini::TestCase
    {
    public:
        template <typename NodeType>
        struct base_hook_item: public NodeType
        {
            int nVal    ;
            int nDisposeCount ;

            base_hook_item()
                : nDisposeCount(0)
            {}
        };

        template <typename NodeType>
        struct member_hook_item
        {
            int nVal    ;
            int nDisposeCount ;
            NodeType hMember ;

            member_hook_item()
                : nDisposeCount(0)
            {}
        };

        struct faked_disposer
        {
            template <typename T>
            void operator ()( T * p )
            {
                ++p->nDisposeCount  ;
            }
        };

        template <class Deque>
        void test()
        {
            test_beans::check_item_counter<typename Deque::item_counter> check_ic ;

            typedef typename Deque::value_type value_type    ;
            value_type v1, v2, v3   ;

            Deque q ;
            CPPUNIT_ASSERT( q.empty() )  ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;

            v1.nVal = 1 ;
            v2.nVal = 2 ;
            v3.nVal = 3 ;

            // push_left / pop_right
            CPPUNIT_ASSERT( q.push_front(v1))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 1 )) ;
            CPPUNIT_ASSERT( q.push_front(v2))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 2 )) ;
            CPPUNIT_ASSERT( q.push_front(v3))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 3 )) ;

            CPPUNIT_ASSERT( v1.nDisposeCount == 0 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 0 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 0 ) ;

            value_type * pv ;
            pv = q.pop_back()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 1 ) ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 2 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 0 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 0 ) ;

            pv = q.pop_back()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 2 ) ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 1 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 0 ) ;

            pv = q.pop_back()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 3 ) ;
            CPPUNIT_ASSERT( q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 1 ) ;

            pv = q.pop_back()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv == NULL )    ;
            CPPUNIT_ASSERT( q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 1 ) ;

            // push_right / pop_left
            CPPUNIT_ASSERT( q.push_back(v1))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 1 )) ;
            CPPUNIT_ASSERT( q.push_back(v2))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 2 )) ;
            CPPUNIT_ASSERT( q.push_back(v3))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 3 )) ;

            CPPUNIT_ASSERT( v1.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 1 ) ;

            pv = q.pop_front()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 1 ) ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 2 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 1 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 1 ) ;

            pv = q.pop_front()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 2 ) ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 1 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 1 ) ;

            pv = q.pop_front()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 3 ) ;
            CPPUNIT_ASSERT( q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 2 ) ;

            pv = q.pop_front()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv == NULL )    ;
            CPPUNIT_ASSERT( q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 2 ) ;

            // push_right / pop_right
            CPPUNIT_ASSERT( q.push_back(v1))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 1 )) ;
            CPPUNIT_ASSERT( q.push_back(v2))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 2 )) ;
            CPPUNIT_ASSERT( q.push_back(v3))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 3 )) ;

            CPPUNIT_ASSERT( v1.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 2 ) ;

            pv = q.pop_back()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 3 ) ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 2 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 3 ) ;

            pv = q.pop_back()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 2 ) ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 1 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 2 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 3 ) ;

            pv = q.pop_back()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 1 ) ;
            CPPUNIT_ASSERT( q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 3 ) ;

            pv = q.pop_back()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv == NULL )    ;
            CPPUNIT_ASSERT( q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 3 ) ;

            // push_left / pop_left
            CPPUNIT_ASSERT( q.push_front(v1))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 1 )) ;
            CPPUNIT_ASSERT( q.push_front(v2))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 2 )) ;
            CPPUNIT_ASSERT( q.push_front(v3))  ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 3 )) ;

            CPPUNIT_ASSERT( v1.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 3 ) ;

            pv = q.pop_front()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 3 ) ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 2 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 4 ) ;

            pv = q.pop_front()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 2 ) ;
            CPPUNIT_ASSERT( !q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 1 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 3 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 4 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 4 ) ;

            pv = q.pop_front()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv != NULL )    ;
            CPPUNIT_ASSERT( pv->nVal == 1 ) ;
            CPPUNIT_ASSERT( q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 4 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 4 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 4 ) ;

            pv = q.pop_front()  ;
            Deque::gc::scan() ;
            CPPUNIT_ASSERT( pv == NULL )    ;
            CPPUNIT_ASSERT( q.empty() ) ;
            CPPUNIT_ASSERT( check_ic( q.size(), 0 )) ;
            CPPUNIT_ASSERT( v1.nDisposeCount == 4 ) ;
            CPPUNIT_ASSERT( v2.nDisposeCount == 4 ) ;
            CPPUNIT_ASSERT( v3.nDisposeCount == 4 ) ;
        }

        void test_MichaelDeque_HP_default();
        void test_MichaelDeque_HP_default_ic();
        void test_MichaelDeque_HP_default_stat();
        void test_MichaelDeque_HP_base();
        void test_MichaelDeque_HP_member();
        void test_MichaelDeque_HP_base_ic();
        void test_MichaelDeque_HP_member_ic();
        void test_MichaelDeque_HP_base_stat();
        void test_MichaelDeque_HP_member_stat();
        void test_MichaelDeque_HP_base_align();
        void test_MichaelDeque_HP_member_align();
        void test_MichaelDeque_HP_base_noalign();
        void test_MichaelDeque_HP_member_noalign();
        void test_MichaelDeque_PTB_base();
        void test_MichaelDeque_PTB_member();
        void test_MichaelDeque_PTB_base_ic();
        void test_MichaelDeque_PTB_member_ic();
        void test_MichaelDeque_PTB_base_stat();
        void test_MichaelDeque_PTB_member_stat();
        void test_MichaelDeque_PTB_base_align();
        void test_MichaelDeque_PTB_member_align();
        void test_MichaelDeque_PTB_base_noalign();
        void test_MichaelDeque_PTB_member_noalign();

        CPPUNIT_TEST_SUITE(IntrusiveDequeHeaderTest)
            CPPUNIT_TEST( test_MichaelDeque_HP_default);
            CPPUNIT_TEST( test_MichaelDeque_HP_default_ic);
            CPPUNIT_TEST( test_MichaelDeque_HP_default_stat);
            CPPUNIT_TEST( test_MichaelDeque_HP_base);
            CPPUNIT_TEST( test_MichaelDeque_HP_member);
            CPPUNIT_TEST( test_MichaelDeque_HP_base_ic);
            CPPUNIT_TEST( test_MichaelDeque_HP_member_ic);
            CPPUNIT_TEST( test_MichaelDeque_HP_base_stat);
            CPPUNIT_TEST( test_MichaelDeque_HP_member_stat);
            CPPUNIT_TEST( test_MichaelDeque_HP_base_align);
            CPPUNIT_TEST( test_MichaelDeque_HP_member_align);
            CPPUNIT_TEST( test_MichaelDeque_HP_base_noalign);
            CPPUNIT_TEST( test_MichaelDeque_HP_member_noalign);
            CPPUNIT_TEST( test_MichaelDeque_PTB_base);
            CPPUNIT_TEST( test_MichaelDeque_PTB_member);
            CPPUNIT_TEST( test_MichaelDeque_PTB_base_ic);
            CPPUNIT_TEST( test_MichaelDeque_PTB_member_ic);
            CPPUNIT_TEST( test_MichaelDeque_PTB_base_stat);
            CPPUNIT_TEST( test_MichaelDeque_PTB_member_stat);
            CPPUNIT_TEST( test_MichaelDeque_PTB_base_align);
            CPPUNIT_TEST( test_MichaelDeque_PTB_member_align);
            CPPUNIT_TEST( test_MichaelDeque_PTB_base_noalign);
            CPPUNIT_TEST( test_MichaelDeque_PTB_member_noalign);

        CPPUNIT_TEST_SUITE_END()
    };

}   // namespace deque


text:
package org.eclipse.php.internal.debug.core.xdebug.dbgp;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.php.internal.debug.core.PHPDebugCoreMessages;
import org.eclipse.php.internal.debug.core.xdebug.XDebugPreferenceMgr;
import org.eclipse.php.internal.debug.core.xdebug.XDebugPreferenceMgr.AcceptRemoteSession;
import org.eclipse.php.internal.debug.core.xdebug.dbgp.protocol.DBGpResponse;
import org.eclipse.php.internal.debug.core.xdebug.dbgp.session.DBGpSessionHandler;
import org.eclipse.swt.widgets.Display;

/**
 * This class handles the management of DBGp proxy interaction.
 */
public class DBGpProxyHandler {

	private boolean registered = false;
	private String currentIdeKey = null;
	private String proxyHost = ""; //$NON-NLS-1$
	private int proxyPort = DEFAULT_PROXY_PORT;
	private int idePort = -1;
	private int errorCode = 0;
	private String errorMsg = ""; //$NON-NLS-1$
	private boolean multisession = false;

	private static final int DEFAULT_PROXY_PORT = 9001;
	private static final int PROXY_CONNECT_TIMEOUT = 3000; // 3 seconds

	public static DBGpProxyHandler instance = new DBGpProxyHandler();

	private DBGpProxyHandler() {
	}

	/**
	 * Register with the proxy if we are not already registered.
	 *
	 * @return true if registration successful
	 */
	public boolean registerWithProxy() {

		// proxyinit -a ip:port -k ide_key -m [0|1]
		//
		// -p the port that the IDE listens for debugging on. The address is
		// retrieved from the connection information.
		// -k a IDE key, which the debugger engine will also use in it's
		// debugging init command. this allows the proxy to match request to
		// IDE. Typically the user will provide the session key as a
		// configuration item.
		// -m this tells the demon that the IDE supports (or doesn't) multiple
		// debugger sessions. if -m is missing, zero or no support is default.

		// response
		// <proxyinit success="[0|1]"
		// idekey="{ID}"
		// address="{IP_ADDRESS}"
		// port="{NUM}>
		// <error id="app_specific_error_code">
		// <message>UI Usable Message</message>
		// </error>
		// </proxyinit>
		if (!registered) {
			DBGpResponse resp = sendcmd("proxyinit -p " + idePort + " -k " + currentIdeKey + " -m " + (multisession ? "1" : "0")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
			if (resp != null) {
				if (resp.getType() == DBGpResponse.PROXY_INIT
						&& resp.getErrorCode() == DBGpResponse.ERROR_OK) {
					registered = true;
				} else {
					errorCode = resp.getErrorCode();
					errorMsg = resp.getErrorMessage();
				}
			}
		}
		return registered;
	}

	/**
	 * unregister from the proxy.
	 */
	public void unregister() {
		// IDE command
		//
		// proxystop -k ide_key
		if (registered) {
			DBGpResponse resp = sendcmd("proxystop" + " -k " + currentIdeKey); //$NON-NLS-1$ //$NON-NLS-2$
			registered = false;
			String isOk = DBGpResponse.getAttribute(resp.getParentNode(),
					"success"); //$NON-NLS-1$
			if (isOk == null || !isOk.equals("1")) { //$NON-NLS-1$
				DBGpLogger
						.logWarning(
								"Unexpected response from proxystop. ErrorCode=" + resp.getErrorCode() + ". msg=" + resp.getErrorMessage(), this, null); //$NON-NLS-1$ //$NON-NLS-2$
			}
		}
	}

	/**
	 * return true if registered with a proxy.
	 *
	 * @return
	 */
	public boolean isRegistered() {
		return registered;
	}

	/**
	 * get the last received error code.
	 *
	 * @return error code
	 */
	public int getErrorCode() {
		return errorCode;
	}

	/**
	 * get the last received error message.
	 *
	 * @return error message
	 */
	public String getErrorMsg() {
		return errorMsg;
	}

	/**
	 * configure the Proxy Handler from the preferences.
	 */
	public void configure() {
		// TODO: move to using preference manager completely.
		Preferences prefs = XDebugPreferenceMgr.getPreferences();

		if (useProxy() == false) {
			unregister();
		} else {
			int idePort = XDebugPreferenceMgr.getPort(prefs);
			String ideKey = prefs
					.getString(XDebugPreferenceMgr.XDEBUG_PREF_IDEKEY);
			boolean multisession = XDebugPreferenceMgr.useMultiSession();
			String proxy = prefs
					.getString(XDebugPreferenceMgr.XDEBUG_PREF_PROXY);
			String proxyHost = proxy;
			int proxyPort = DEFAULT_PROXY_PORT;
			int split = proxy.indexOf(':');
			if (split != -1) {
				proxyHost = proxy.substring(0, split);
				if (split + 1 < proxy.length()) {
					String portStr = proxy.substring(split + 1);
					try {
						proxyPort = Integer.parseInt(portStr);
					} catch (NumberFormatException e) {
					}
				}
			}

			if (proxyPort == XDebugPreferenceMgr.getPort()) {
				displayErrorMessage(PHPDebugCoreMessages.XDebug_DBGpProxyHandler_0);
				XDebugPreferenceMgr.setUseProxy(false);
			} else {
				setProxyInfo(proxyHost, proxyPort, ideKey, idePort,
						multisession);
				if (XDebugPreferenceMgr.getAcceptRemoteSession() != AcceptRemoteSession.off) {
					// if jit we must register with the proxy straight away
					// rather than wait
					// for the first launch

					Job job = new Job("register with proxy") { //$NON-NLS-1$

						@Override
						protected IStatus run(IProgressMonitor monitor) {
							if (registerWithProxy() == false) {
								displayErrorMessage(PHPDebugCoreMessages.XDebug_DBGpProxyHandler_1
										+ getErrorMsg());
								XDebugPreferenceMgr.setUseProxy(false);
							}
							return Status.OK_STATUS;
						}
					};
					job.schedule();
				}

			}
		}
	}

	/**
	 * store the proxy information.
	 *
	 * @param host
	 * @param port
	 * @param idekey
	 * @param listeningPort
	 * @param multisession
	 */
	private void setProxyInfo(String host, int port, String idekey,
			int listeningPort, boolean multisession) {
		if (!host.equalsIgnoreCase(proxyHost) || port != proxyPort
				|| !idekey.equals(currentIdeKey) || idePort != listeningPort
				|| this.multisession != multisession) {
			unregister(); // checks for connection
			proxyHost = host;
			proxyPort = port;
			idePort = listeningPort;
			currentIdeKey = idekey;
			this.multisession = multisession;
		}
	}

	/**
	 * returns true a proxy should be used.
	 *
	 * @return
	 */
	public boolean useProxy() {
		return XDebugPreferenceMgr.useProxy();
	}

	/**
	 * send a command to the proxy and get a response.
	 *
	 * @param cmd
	 *            the command to send
	 * @return the response.
	 */
	private DBGpResponse sendcmd(String cmd) {
		DBGpResponse dbgpResp = null;
		try {
			// TODO: look at reducing the timeout for connection failure.
			// Socket s = new Socket(proxyHost, proxyPort);
			Socket s = new Socket();
			InetSocketAddress server = new InetSocketAddress(proxyHost,
					proxyPort);
			InetSocketAddress local = new InetSocketAddress(0);
			s.bind(local);
			s.connect(server, PROXY_CONNECT_TIMEOUT);

			InputStream is = s.getInputStream();
			OutputStream os = s.getOutputStream();
			if (DBGpLogger.debugCmd()) {
				DBGpLogger.debug("cmd: " + cmd); //$NON-NLS-1$
			}
			os.write(cmd.getBytes("ASCII")); //command will always be ASCII //$NON-NLS-1$
			os.flush();
			byte[] resp = readResponse(is);
			dbgpResp = new DBGpResponse();
			dbgpResp.parseResponse(resp);
			s.shutdownInput();
			s.shutdownOutput();
			s.close();
			return dbgpResp;
		} catch (IOException ioe) {
			if (dbgpResp == null) {
				errorCode = 9999;
				if (ioe instanceof EOFException) {
					errorMsg = PHPDebugCoreMessages.XDebug_DBGpProxyHandler_2;
				} else {
					errorMsg = ioe.getMessage();
					if (errorMsg == null) {
						errorMsg = ioe.getClass().getName();
					}
				}
			}
		}
		return dbgpResp;

	}

	/**
	 * read from the socket input stream and create the response.
	 *
	 * @param is
	 *            socket input stream
	 * @return a response
	 * @throws IOException
	 */
	private byte[] readResponse(InputStream is) throws IOException {
		byte byteArray[];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int b;
		while ((b = is.read()) != -1) {
			baos.write(b);
		}
		byteArray = baos.toByteArray();
		if (DBGpLogger.debugResp()) {
			DBGpLogger.debug("Response: " + new String(byteArray, "ASCII")); //$NON-NLS-1$ //$NON-NLS-2$
		}
		return byteArray;
	}

	/**
	 * generate an IDE Key for this system.
	 *
	 * @return a generated ide key.
	 */
	public String generateIDEKey() {
		String toAppend = null;
		try {
			toAppend = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			toAppend = java.util.UUID.randomUUID().toString();

		}
		return DBGpSessionHandler.IDEKEY_PREFIX + "_" + toAppend; //$NON-NLS-1$
	}

	/**
	 * return the current ide key if we are configured to use the proxy. if
	 * useProxy is false, you should use the ide key here. It may or may not be
	 * null.
	 *
	 * @return
	 */
	public String getCurrentIdeKey() {
		return currentIdeKey;
	}

	private void displayErrorMessage(final String message) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				MessageDialog
						.openError(Display.getDefault().getActiveShell(),
								PHPDebugCoreMessages.XDebug_DBGpProxyHandler_3,
								message);
			}
		});
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.rules;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetPattern;
import com.facebook.buck.util.HumanReadableException;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;

import java.util.Collections;
import java.util.Set;

@Beta
public abstract class AbstractBuildRuleBuilder<T extends BuildRule> implements BuildRuleBuilder<T> {

  protected BuildTarget buildTarget;
  protected Set<BuildTarget> deps = Sets.newHashSet();
  protected Set<BuildTargetPattern> visibilityPatterns = Sets.newHashSet();

  private final Function<String, String> pathRelativizer;
  private final RuleKeyBuilderFactory ruleKeyBuilderFactory;

  protected AbstractBuildRuleBuilder(AbstractBuildRuleBuilderParams params) {
    this.pathRelativizer = params.getPathRelativizer();
    this.ruleKeyBuilderFactory = params.getRuleKeyBuilderFactory();
  }

  @Override
  public abstract T build(BuildRuleResolver ruleResolver);

  public AbstractBuildRuleBuilder<T> setBuildTarget(BuildTarget buildTarget) {
    this.buildTarget = buildTarget;
    return this;
  }

  @Override
  public BuildTarget getBuildTarget() {
    return buildTarget;
  }

  public AbstractBuildRuleBuilder<T> addDep(BuildTarget dep) {
    deps.add(dep);
    return this;
  }

  /** @return a view of the deps of this rule */
  @Override
  public Set<BuildTarget> getDeps() {
    return Collections.unmodifiableSet(deps);
  }

  protected ImmutableSortedSet<BuildRule> getDepsAsBuildRules(
      final BuildRuleResolver ruleResolver) {
    return getBuildTargetsAsBuildRules(ruleResolver, getDeps(), false /* allowNonExistentRule */);
  }

  protected ImmutableSortedSet<BuildRule> getBuildTargetsAsBuildRules(
      BuildRuleResolver ruleResolver, Iterable<BuildTarget> buildTargets) {
    return getBuildTargetsAsBuildRules(ruleResolver, buildTargets, /* allowNonExistentRule */ false);
  }

  @VisibleForTesting
  protected ImmutableSortedSet<BuildRule> getBuildTargetsAsBuildRules(
      BuildRuleResolver ruleResolver,
      Iterable<BuildTarget> buildTargets,
      boolean allowNonExistentRule) {
    BuildTarget invokingBuildTarget = Preconditions.checkNotNull(getBuildTarget());

    ImmutableSortedSet.Builder<BuildRule> buildRules = ImmutableSortedSet.naturalOrder();

    for (BuildTarget target : buildTargets) {
      BuildRule buildRule = ruleResolver.get(target);
      if (buildRule != null) {
        buildRules.add(buildRule);
      } else if (!allowNonExistentRule) {
        throw new HumanReadableException("No rule for %s found when processing %s",
            target, invokingBuildTarget.getFullyQualifiedName());
      }
    }

    return buildRules.build();
  }

  public AbstractBuildRuleBuilder<T> addVisibilityPattern(BuildTargetPattern visibilityPattern) {
    visibilityPatterns.add(visibilityPattern);
    return this;
  }

  @Override
  public ImmutableSet<BuildTargetPattern> getVisibilityPatterns() {
    return ImmutableSet.copyOf(visibilityPatterns);
  }

  protected BuildRuleParams createBuildRuleParams(BuildRuleResolver ruleResolver) {
    return new BuildRuleParams(getBuildTarget(),
        getDepsAsBuildRules(ruleResolver),
        getVisibilityPatterns(),
        pathRelativizer,
        ruleKeyBuilderFactory);
  }
}


text:
using System;
using System.Collections;
using System.Linq;

namespace Nucleo.DataMapper.Incrementing
{
	public class StringTemplateMappingGenerator : IMappingGenerator
	{
		private string _template = null;

		#region " Constructors "

		public StringTemplateMappingGenerator(string template)
		{
			_template = template;
		}

		#endregion

		#region " Methods "

		public object Generate(IncrementMappings map)
		{
			IncrementMappingCollection mappings = map.GetMappings();
			ArrayList values = new ArrayList();

			foreach (IncrementMapping mapping in mappings)
				values.Add(mapping.GetValue());

			return String.Format(_template, values.ToArray());
		}

		#endregion
	}
}


text:
        Cookies

Scientilla uses cookies in order to personalize your site experience.
By using Scientilla you consent cookies. Read here our cookies policy.

        <button
            ng-click="vm.accept()"
            class="btn btn-default"
        >Ok, I consent.</button>


text:
package com.oozinoz.carousel;

import java.util.Observable;

/**
 * This class provides an initial model of a carousel door
 * that manages its state without moving state-specific
 * logic out to state classes.
 */
public class Door extends Observable {
    public final int CLOSED = -1;
    public final int OPENING = -2;
    public final int OPEN = -3;
    public final int CLOSING = -4;
    public final int STAYOPEN = -5;

    private int state = CLOSED;

    /**
     * The carousel user has touched the carousel button. This "one touch"
     * button elicits different behaviors, depending on the state of the door.
     */
    public void touch() {
        switch (state)
        {
            case OPENING:
            case STAYOPEN:
                setState(CLOSING);
                break;
            case CLOSING:
            case CLOSED:
                setState(OPENING);
                break;
            case OPEN:
                setState(STAYOPEN);
                break;
            default:
                throw new Error("can't happen");
        }
    }

    /**
     * This is a notification from the mechanical carousel that
     * the door finished opening or shutting.
     */
    public void complete() {
        if (state == OPENING)
            setState(OPEN);
        else if (state == CLOSING)
            setState(CLOSED);
    }

    /**
     * This is a notification from the mechanical carousel that the
     * door got tired of being open.
     */
        public void timeout() {
            setState(CLOSING);
        }

    /**
     * @return a textual description of the door's state
     */
    public String status()
    {
        switch (state)
        {
            case OPENING:
                return "Opening";
            case OPEN:
                return "Open";
            case CLOSING:
                return "Closing";
            case STAYOPEN:
                return "StayOpen";
            default:
                return "Closed";
        }
    }

    private void setState(int state)
    {
        this.state = state;
        setChanged();
        notifyObservers();
    }
}


text:
package com.github.gserv.serv.wx.support.api.authentication;

import com.github.gserv.serv.wx.service.manager.WxService;
import com.github.gserv.serv.wx.support.WxApiInvorkException;

/**
 * 认证状态接口
 *
 * @author shiying
 *
 */
public interface WxApiAuthenticationStateService extends WxService {

	/**
	 * 公众帐号是否认证
	 * @return
	 * @throws WxApiInvorkException
	 */
	public Boolean isAuthentication() throws WxApiInvorkException;

}


text:
<?php
/**
 *
 */

namespace Commercetools\Core\Request\OrderEdits\StagedOrder\Command;

use Commercetools\Core\Request\Orders\Command\OrderChangeShipmentStateAction;

/**
 * @package Commercetools\Core\Request\OrderEdits\StagedOrder\Command
 *
 * @method string getAction()
 * @method StagedOrderChangeShipmentStateAction setAction(string $action = null)
 * @method string getShipmentState()
 * @method StagedOrderChangeShipmentStateAction setShipmentState(string $shipmentState = null)
 */
class StagedOrderChangeShipmentStateAction extends OrderChangeShipmentStateAction implements StagedOrderUpdateAction
{
}


text:
TypedAdapter
============

Object Oriented android list view adapter(s) using generics to display given Pojos.

This technique is an alternative to the view holder design pattern. It has the following advantages :
* is strongly typed ;
* allows to avoid the `setTag` ugly hack of the view holders ;
* gives the opportunity to create full android custom views, elegant and complete, that can even be reused as XML layout elements.

[![Build Status on Travis:](https://travis-ci.org/stephanenicolas/TypedAdapter.svg?branch=master)](https://travis-ci.org/stephanenicolas/TypedAdapter)

Usage
-----
Let's say you got a POJO class :

```java
public class Pojo {
   public String name;
}
```
To display a list of Pojo into a `ListView` using Typed Adapter, follow the 2 following steps.

Define your adapter using both the POJO type and your custom view type :

```java
public class PojoAdapter extends TypedArrayAdapter<Pojo, PojoView> {

    public PojoAdapter(Context context, List<Pojo> pojos) {
        super(context, pojos);
    }

    @Override
    public PojoView createView() {
        return new PojoView(getContext());
    }
}

````

Define your custom view type and implement `TypedCellView<Pojo>`

```java
public class PojoView extends RelativeLayout implements TypedCellView<Pojo> {

    private TextView textViewName;

    public PojoView(Context context) {
        super(context);
        LayoutInflater.from(context).inflate(<view layout>, this);
        textViewName = (TextView) findViewById(R.id.textView_name);

        //good practice
        onFinishInflate();
    }

    @Override
    public void update(Pojo pojo) {
        textViewName.setText(pojo.name);
    }
}
```

You need a single constructor using a `Context` as parameter when creating a view programmatically (here, the adapter does). Add the other `View` constructors if you want to make your custom view a full android component that can be inflated via XML.


text:
#include "Backtrace.hpp"
#include "../filesystem/path.hpp"
#include "../collections/Array.hpp"
#include <execinfo.h>

#include <unistd.h>

#include <cxxabi.h>

#include <bfd.h>
#include <link.h>
#include <algorithm>

namespace BacktraceStatic
{
	bool initialized_ = false;

	struct Symbol
	{
		bfd_vma pc;
		char const* filename;
		char const* functionName;
		bfd_vma offset;
		unsigned int line;
	};

	static bool findSymbol_( bfd* bfdPtr, asymbol** syms, Symbol& symbol )
	{
		for(asection* section = bfdPtr->sections; section != nullptr; section = section->next)
		{
			auto& flags = bfd_get_section_flags(bfdPtr, section);

			if( ( flags & SEC_ALLOC ) == 0 )
				continue;

			bfd_vma vma = bfd_get_section_vma( bfdPtr, section );
			if(symbol.pc < vma)
				continue;

			bfd_size_type size = bfd_get_section_size(section);
			if(symbol.pc >= vma + size)
				continue;

			bfd_vma offset = symbol.pc - vma;
			if(bfd_find_nearest_line( bfdPtr, section, syms, offset, &symbol.filename, &symbol.functionName, &symbol.line ))
			{
				symbol.offset = offset;
				return true;
			}
		}
		return false;
	}

	struct Module
	{
		uintptr_t baseAddress;
		char const* path;
		char const* baseFilename;
		bfd* bfdPtr;
		asymbol** symbols;

		Module()
			: baseAddress(0)
			, path(nullptr)
			, baseFilename(nullptr)
			, bfdPtr(nullptr)
			, symbols(nullptr)
		{

		}

		Module(Module&& other)
			: baseAddress(other.baseAddress)
			, path(other.path)
			, baseFilename(other.baseFilename)
			, bfdPtr(other.bfdPtr)
			, symbols(other.symbols)
		{
			other.baseAddress = 0;
			other.path = nullptr;
			other.baseFilename = nullptr;
			other.bfdPtr = nullptr;
			other.symbols = nullptr;
		}

		Module& operator=(Module&& other)
		{
			baseAddress = other.baseAddress;
			path = other.path;
			baseFilename = other.baseFilename;
			bfdPtr = other.bfdPtr;
			symbols = other.symbols;

			other.baseAddress = 0;
			other.path = nullptr;
			other.baseFilename = nullptr;
			other.bfdPtr = nullptr;
			other.symbols = nullptr;
			return *this;
		}

		Module(char const* path_, uintptr_t addr)
			: baseAddress(addr)
			, path(path_)
			, baseFilename(path_)
			, bfdPtr(nullptr)
			, symbols(nullptr)
		{
			bfdPtr = bfd_openr(path_, nullptr);

			if(!bfdPtr)
				return;

			if (bfd_check_format(bfdPtr, bfd_archive))
			{
				bfd_close(bfdPtr);
				bfdPtr = nullptr;
				return;
			}

			char** matching = NULL;
			if (!bfd_check_format_matches(bfdPtr, bfd_object, &matching))
			{
				bfd_close(bfdPtr);
				bfdPtr = nullptr;
				return;
			}

			if ((bfd_get_file_flags(bfdPtr) & HAS_SYMS) == 0)
			{
				bfd_close(bfdPtr);
				bfdPtr = nullptr;
				return;
			}

			unsigned int size;
			long symcount = bfd_read_minisymbols( bfdPtr, FALSE, (void**)&symbols, &size );

			if(symcount == 0)
			{
				symcount = bfd_read_minisymbols( bfdPtr, TRUE, (void**)&symbols, &size );
			}

			if(symcount < 0)
			{
				bfd_close(bfdPtr);
				bfdPtr = nullptr;
				symbols = nullptr;
			}

			char const* ptr = path;
			char const sep = sprawl::path::Separator();
			char const altSep = sprawl::path::AltSeparator();
			while(*ptr != '\0')
			{
				if(*ptr == sep || *ptr == altSep)
				{
					baseFilename = ptr + 1;
				}
				++ptr;
			}
		}

		~Module()
		{
			if(symbols)
			{
				free(symbols);
			}
			if(bfdPtr)
			{
				bfd_close(bfdPtr);
			}
		}

		bool Good()
		{
			return bfdPtr != nullptr && symbols != nullptr;
		}
	};

	char moduleBuffer_[256 * sizeof(Module)];
	Module* modules_ = reinterpret_cast<Module*>(moduleBuffer_);

	static size_t nModules_ = 0;

	int dlCallback_(struct dl_phdr_info* info, size_t /*size*/, void* /*data*/)
	{
		size_t idx = nModules_;
		Module& module = modules_[idx];

		new(&module) Module(info->dlpi_name, info->dlpi_addr);

		if(module.Good())
		{
			++nModules_;
		}
		else
		{
			module.~Module();
		}

		return 0;
	}

	static Module* findModule_(uintptr_t address, int start = 0, int end = nModules_- 1)
	{
		if(end < start)
		{
			return nullptr;
		}

		size_t mid = (start + end) / 2;

		Module& module = modules_[mid];
		if( module.baseAddress < address )
		{
			if(mid < nModules_ - 1 && reinterpret_cast<Module&>(modules_[mid+1]).baseAddress > address)
				return &module;

			return findModule_(address, mid+1, end);
		}
		return findModule_(address, start, mid-1);
	}

	static bool demangle_(char const* input, char* outputBuffer, size_t outputLength)
	{
		///@TODO: Implement this directly so we can avoid heap allocations.
		int status;
		size_t length = outputLength;
		char* buffer = abi::__cxa_demangle(input, nullptr, &length, &status);
		if(buffer == nullptr)
		{
			return false;
		}
		strncpy(outputBuffer, buffer, outputLength);
		free(buffer);
		return true;
	}
}

void sprawl::logging::Backtrace::Init()
{
	if(BacktraceStatic::initialized_)
		return;

	BacktraceStatic::initialized_ = true;

	bfd_init();

	static char path[1024];
	readlink("/proc/self/exe", path, 1024);

	size_t idx = BacktraceStatic::nModules_;
	BacktraceStatic::Module& module = BacktraceStatic::modules_[idx];

	new(&module) BacktraceStatic::Module(path, 0);

	if(module.Good())
	{
		++BacktraceStatic::nModules_;
	}
	else
	{
		module.~Module();
	}

	dl_iterate_phdr(&BacktraceStatic::dlCallback_, nullptr);

	std::sort(BacktraceStatic::modules_, BacktraceStatic::modules_ + BacktraceStatic::nModules_, [](BacktraceStatic::Module const& module, BacktraceStatic::Module const& other)
	{
		return module.baseAddress < other.baseAddress;
	});
}

void sprawl::logging::Backtrace::ShutDown()
{
	for(size_t i = 0; i < BacktraceStatic::nModules_; ++i)
	{
		BacktraceStatic::modules_[i].~Module();
	}

	BacktraceStatic::nModules_ = 0;

	BacktraceStatic::initialized_ = false;
}

sprawl::logging::Backtrace sprawl::logging::Backtrace::Get(int skipFrames)
{
	// We could use libUnwind here instead of backtrace(), and in fact, we originally did.
	// libUnwind is very very very very very slightly faster than backtrace (to the tune of 1 us per call on average)
	// But since we don't use libUnwind for symbolification and libUnwind's primary performance gain is when compared to
	// backtrace_symbols, the 1us performance improvement does not seem worth the dependency.
	Backtrace stack;
	void* bt[SPRAWL_BACKTRACE_MAX_STACK];
	stack.m_size = backtrace(bt, SPRAWL_BACKTRACE_MAX_STACK) - skipFrames;
	memcpy(stack.m_stack, bt + skipFrames, SPRAWL_BACKTRACE_MAX_STACK - skipFrames);

	return stack;
}

sprawl::logging::Backtrace::Frame sprawl::logging::Backtrace::GetFrame(size_t index) const
{
	Frame frame;

	uintptr_t addr = m_stack[index];
	frame.address = addr;

	BacktraceStatic::Module* module = BacktraceStatic::findModule_(addr);

	if(module != nullptr)
	{
		strncpy(frame.module, module->baseFilename, SPRAWL_BACKTRACE_STRING_MAX);

		BacktraceStatic::Symbol sym;
		sym.pc = addr - module->baseAddress;
		if(BacktraceStatic::findSymbol_(module->bfdPtr, module->symbols, sym))
		{
			frame.offset = sym.offset;

			if(!BacktraceStatic::demangle_( sym.functionName, frame.func, SPRAWL_BACKTRACE_STRING_MAX ))
			{
				strncpy(frame.func, sym.functionName, SPRAWL_BACKTRACE_STRING_MAX);
			}

			if(sym.filename != nullptr)
			{
				strncpy(frame.file, sym.filename, SPRAWL_BACKTRACE_STRING_MAX);

				char const* ptr = frame.file;
				char sep = sprawl::path::Separator();
				char altSep = sprawl::path::AltSeparator();
				while(*ptr != '\0')
				{
					if(*ptr == sep || *ptr == altSep)
					{
						frame.baseFile = ptr + 1;
					}
					++ptr;
				}

				frame.line = sym.line;
			}
			else
			{
				strncpy(frame.file, "Unknown", SPRAWL_BACKTRACE_STRING_MAX);
				frame.baseFile = frame.file;

				frame.line = -1;
			}
		}
	}

	return frame;
}


text:
'use strict';

export default
class AppConfig {
	constructor(appConstant, appAnotherConstant) {
		appConstant.value = appAnotherConstant;
	}
}


text:
import * as React from "react";
import { Fragment } from "react";
import { Actions } from "../model/Actions";
import { TabNode } from "../model/TabNode";
import { TabSetNode } from "../model/TabSetNode";
import { CLASSES } from "../Types";
import { ILayoutCallbacks } from "./Layout";
import { ErrorBoundary } from "./ErrorBoundary";
import { I18nLabel } from "../I18nLabel";
import { BorderNode } from "../model/BorderNode";
import { hideElement } from "./Utils";

/** @internal */
export interface ITabProps {
    layout: ILayoutCallbacks;
    selected: boolean;
    node: TabNode;
    factory: (node: TabNode) => React.ReactNode;
    path: string;
}

/** @internal */
export const Tab = (props: ITabProps) => {
    const { layout, selected, node, factory, path } = props;
    const [renderComponent, setRenderComponent] = React.useState<boolean>(!props.node.isEnableRenderOnDemand() || props.selected);

    React.useLayoutEffect(() => {
        if (!renderComponent && selected) {
            // load on demand
            // console.log("load on demand: " + node.getName());
            setRenderComponent(true);
        }
    });

    const onMouseDown = () => {
        const parent = node.getParent() as TabSetNode;
        if (parent.getType() === TabSetNode.TYPE) {
            if (!parent.isActive()) {
                layout.doAction(Actions.setActiveTabset(parent.getId()));
            }
        }
    };

    const cm = layout.getClassName;
    const useVisibility = node.getModel().isUseVisibility();

    const parentNode = node.getParent() as TabSetNode | BorderNode;
    const style: Record<string, any> = node._styleWithPosition();
    if (!selected) {
        hideElement(style, useVisibility);
    }

    if (parentNode instanceof TabSetNode) {
        if (node.getModel().getMaximizedTabset() !== undefined && !parentNode.isMaximized()) {
            hideElement(style, useVisibility);
        }
    }

    let child;
    if (renderComponent) {
        child = factory(node);
    }

    let className = cm(CLASSES.FLEXLAYOUT__TAB);
    if (parentNode instanceof BorderNode) {
        className += " " + cm(CLASSES.FLEXLAYOUT__TAB_BORDER);
        className += " " + cm(CLASSES.FLEXLAYOUT__TAB_BORDER_ + parentNode.getLocation().getName());
    }

    return (
        <div
            className={className}
            data-layout-path={path}
            onMouseDown={onMouseDown}
            onTouchStart={onMouseDown}
            style={style}>
            <ErrorBoundary message={props.layout.i18nName(I18nLabel.Error_rendering_component)}>
                <Fragment>{child}</Fragment>
            </ErrorBoundary>
        </div>
    );
};


text:
[![Version npm](https://img.shields.io/npm/v/hubot-ansible.svg?style=flat-square)](https://www.npmjs.com/package/hubot-ansible) [![npm Downloads](https://img.shields.io/npm/dm/hubot-ansible.svg?style=flat-square)](https://www.npmjs.com/package/hubot-ansible) [![Dependencies](https://img.shields.io/david/vspiewak/hubot-ansible.svg?style=flat-square)](https://david-dm.org/vspiewak/hubot-ansible)

## Description

A hubot script for launching ansible commands

See [`src/scripts/ansible.coffee`](src/scripts/ansible.coffee) for full documentation.

## Installation

In hubot project repo, run:

`npm install hubot-ansible --save`

Then add **hubot-ansible** to your `external-scripts.json`:

```json
[
  "hubot-ansible"
]
```

## Configuration

hubot-ansible can use [`hubot-auth`](https://github.com/hubot-scripts/hubot-auth) for restrict usage to certains roles.

hobot-ansible use slack-attachment for nice integration with Slack.

## Sample Interaction

```
vspiewak> Hubot ansible webserver date
Hubot> admin@webserver: date
173.194.45.83 | success | rc=0 >>
Sun Nov  8 11:27:55 CET 2015

vspiewak> Hubot ansible-sudo webserver /etc/init.d/ntp restart
Hubot> admin@webserver: sudo /etc/init.d/ntp restart
173.194.45.83 | success | rc=0 >>
Restarting ntp (via systemctl): ntp.service.

vspiewak> Hubot ansible-as go gocd ps
Hubot> admin@gocd: sudo -iu go ps
173.194.45.83 | success | rc=0 >>
 PID TTY          TIME CMD
30912 pts/0    00:00:00 sh
30913 pts/0    00:00:00 python
30914 pts/0    00:00:00 sh
30915 pts/0    00:00:00 ps
```

## EC2 dynamic inventory configuration

* Install hubot in /opt/hubot (or somewhere else...)
* Upload inventory/ec2.{py,ini} in /opt/hubot folder
* Upload a PEM (or ssh key) in /opt/hubot folder
* Set at least the following ENV VARS to hubot:
  - export ANSIBLE_HOST_KEY_CHECKING=False
  - export EC2_REGION=us-east-1
  - export AWS_ACCESS_KEY=`<your_aws_key>`
  - export AWS_SECRET_KEY=`<your_aws_secret>`
  - export AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY
  - export AWS_SECRET_ACCESS_KEY=$AWS_SECRET_KEY
  - export HUBOT_ANSIBLE_INVENTORY_FILE=/opt/hubot/inventory/ec2.py
  - export HUBOT_ANSIBLE_PRIVATE_KEY=/opt/hubot/`<your_pem_file>`.pem
  - export HUBOT_ANSIBLE_REMOTE_USER="admin"
* chmod 400 /opt/hubot/the_pem_file.pem
* Dont forget to install ansible on hubot host !

You can *debug* launching this command as the "hubot user":

    ansible -i $HUBOT_ANSIBLE_INVENTORY_FILE --private-key=$HUBOT_ANSIBLE_PRIVATE_KEY all -u $HUBOT_ANSIBLE_REMOTE_USER -m shell -a "date"

## Contribute

Just send pull request or file an issue !

## Copyright

Copyright © Vincent Spiewak. See [`LICENSE`](LICENSE) for details.


text:
package org.apache.struts2.dojo.views.jsp.ui;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

import junit.framework.AssertionFailedError;

import com.mockobjects.servlet.MockHttpServletRequest;

/**
 * StrutsMockHttpServletRequest
 *
 */
public class StrutsMockHttpServletRequest extends MockHttpServletRequest {

    Locale locale = Locale.US;
    private Map attributes = new HashMap();
    private Map parameterMap = new HashMap();
    private String context = "";
    private String pathInfo = "";
    private String queryString;
    private String requestURI;
    private String scheme;
    private String serverName;
    private int serverPort;
    private String encoding;
    private String requestDispatherString;

    public void setAttribute(String s, Object o) {
        attributes.put(s, o);
    }

    public Object getAttribute(String s) {
        return attributes.get(s);
    }

    public Enumeration getAttributeNames() {
        Vector v = new Vector();
        v.addAll(attributes.keySet());

        return v.elements();
    }

    public String getContextPath() {
        return this.context;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    public Locale getLocale() {
        return locale;
    }

    public void setCharacterEncoding(String s) {
        this.encoding = s;
    }

    public String getCharacterEncoding() {
        return encoding;
    }

    public void setParameterMap(Map parameterMap) {
        this.parameterMap = parameterMap;
    }

    public Map getParameterMap() {
        return parameterMap;
    }

    public String getParameter(String string) {
        return (String) parameterMap.get(string);
    }

    public Enumeration getParameterNames() {
        return Collections.enumeration(parameterMap.keySet());
    }

    public String[] getParameterValues(String string) {
        return (String[]) parameterMap.get(string);
    }

    public String getPathInfo() {
        return pathInfo;
    }

    public void setQueryString(String queryString) {
        this.queryString = queryString;
    }

    public String getQueryString() {
        return queryString;
    }

    public RequestDispatcher getRequestDispatcher(String string) {
        this.requestDispatherString = string;
        return super.getRequestDispatcher(string);
    }

    /**
     * Get's the source string that was used in the last getRequestDispatcher method call.
     */
    public String getRequestDispatherString() {
        return requestDispatherString;
    }

    public void setRequestURI(String requestURI) {
        this.requestURI = requestURI;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public void setScheme(String scheme) {
        this.scheme = scheme;
    }

    public String getScheme() {
        return scheme;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public String getServerName() {
        return serverName;
    }

    public void setServerPort(int serverPort) {
        this.serverPort = serverPort;
    }

    public int getServerPort() {
        return serverPort;
    }

    public HttpSession getSession() {
        HttpSession session = null;

        try {
            session = super.getSession();
        } catch (AssertionFailedError e) {
            //ignore
        }

        if (session == null) {
            session = new StrutsMockHttpSession();
            setSession(session);
        }

        return session;
    }

    public void setupGetContext(String context) {
        this.context = context;
    }

    public void setupGetPathInfo(String pathInfo) {
        this.pathInfo = pathInfo;
    }

    public int getRemotePort() {
        return 0;
    }

    public String getLocalName() {
        return null;
    }

    public String getLocalAddr() {
        return null;
    }

    public int getLocalPort() {
        return 0;
    }
}


text:
from typing import TYPE_CHECKING
import warnings

from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling

from .. import models as _models

if TYPE_CHECKING:
    # pylint: disable=unused-import,ungrouped-imports
    from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union

    T = TypeVar('T')
    ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

class AccountsOperations(object):
    """AccountsOperations operations.

    You should not instantiate this class directly. Instead, you should create a Client instance that
    instantiates it for you and attaches it as an attribute.

    :ivar models: Alias to model classes used in this operation group.
    :type models: ~azure.mgmt.datalake.store.models
    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    """

    models = _models

    def __init__(self, client, config, serializer, deserializer):
        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self._config = config

    def list(
        self,
        filter=None,  # type: Optional[str]
        top=None,  # type: Optional[int]
        skip=None,  # type: Optional[int]
        select=None,  # type: Optional[str]
        orderby=None,  # type: Optional[str]
        count=None,  # type: Optional[bool]
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["_models.DataLakeStoreAccountListResult"]
        """Lists the Data Lake Store accounts within the subscription. The response includes a link to the
        next page of results, if any.

        :param filter: OData filter. Optional.
        :type filter: str
        :param top: The number of items to return. Optional.
        :type top: int
        :param skip: The number of items to skip over before returning elements. Optional.
        :type skip: int
        :param select: OData Select statement. Limits the properties on each entry to just those
         requested, e.g. Categories?$select=CategoryName,Description. Optional.
        :type select: str
        :param orderby: OrderBy clause. One or more comma-separated expressions with an optional "asc"
         (the default) or "desc" depending on the order you'd like the values sorted, e.g.
         Categories?$orderby=CategoryName desc. Optional.
        :type orderby: str
        :param count: The Boolean value of true or false to request a count of the matching resources
         included with the resources in the response, e.g. Categories?$count=true. Optional.
        :type count: bool
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either DataLakeStoreAccountListResult or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.datalake.store.models.DataLakeStoreAccountListResult]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.DataLakeStoreAccountListResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-11-01"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list.metadata['url']  # type: ignore
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                if filter is not None:
                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int', minimum=1)
                if skip is not None:
                    query_parameters['$skip'] = self._serialize.query("skip", skip, 'int', minimum=1)
                if select is not None:
                    query_parameters['$select'] = self._serialize.query("select", select, 'str')
                if orderby is not None:
                    query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str')
                if count is not None:
                    query_parameters['$count'] = self._serialize.query("count", count, 'bool')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('DataLakeStoreAccountListResult', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DataLakeStore/accounts'}  # type: ignore

    def list_by_resource_group(
        self,
        resource_group_name,  # type: str
        filter=None,  # type: Optional[str]
        top=None,  # type: Optional[int]
        skip=None,  # type: Optional[int]
        select=None,  # type: Optional[str]
        orderby=None,  # type: Optional[str]
        count=None,  # type: Optional[bool]
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["_models.DataLakeStoreAccountListResult"]
        """Lists the Data Lake Store accounts within a specific resource group. The response includes a
        link to the next page of results, if any.

        :param resource_group_name: The name of the Azure resource group.
        :type resource_group_name: str
        :param filter: OData filter. Optional.
        :type filter: str
        :param top: The number of items to return. Optional.
        :type top: int
        :param skip: The number of items to skip over before returning elements. Optional.
        :type skip: int
        :param select: OData Select statement. Limits the properties on each entry to just those
         requested, e.g. Categories?$select=CategoryName,Description. Optional.
        :type select: str
        :param orderby: OrderBy clause. One or more comma-separated expressions with an optional "asc"
         (the default) or "desc" depending on the order you'd like the values sorted, e.g.
         Categories?$orderby=CategoryName desc. Optional.
        :type orderby: str
        :param count: A Boolean value of true or false to request a count of the matching resources
         included with the resources in the response, e.g. Categories?$count=true. Optional.
        :type count: bool
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either DataLakeStoreAccountListResult or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.datalake.store.models.DataLakeStoreAccountListResult]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.DataLakeStoreAccountListResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-11-01"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list_by_resource_group.metadata['url']  # type: ignore
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                if filter is not None:
                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int', minimum=1)
                if skip is not None:
                    query_parameters['$skip'] = self._serialize.query("skip", skip, 'int', minimum=1)
                if select is not None:
                    query_parameters['$select'] = self._serialize.query("select", select, 'str')
                if orderby is not None:
                    query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str')
                if count is not None:
                    query_parameters['$count'] = self._serialize.query("count", count, 'bool')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('DataLakeStoreAccountListResult', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts'}  # type: ignore

    def _create_initial(
        self,
        resource_group_name,  # type: str
        account_name,  # type: str
        parameters,  # type: "_models.CreateDataLakeStoreAccountParameters"
        **kwargs  # type: Any
    ):
        # type: (...) -> "_models.DataLakeStoreAccount"
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.DataLakeStoreAccount"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-11-01"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self._create_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(parameters, 'CreateDataLakeStoreAccountParameters')
        body_content_kwargs['content'] = body_content
        request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        if response.status_code == 200:
            deserialized = self._deserialize('DataLakeStoreAccount', pipeline_response)

        if response.status_code == 201:
            deserialized = self._deserialize('DataLakeStoreAccount', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    _create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}'}  # type: ignore

    def begin_create(
        self,
        resource_group_name,  # type: str
        account_name,  # type: str
        parameters,  # type: "_models.CreateDataLakeStoreAccountParameters"
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.DataLakeStoreAccount"]
        """Creates the specified Data Lake Store account.

        :param resource_group_name: The name of the Azure resource group.
        :type resource_group_name: str
        :param account_name: The name of the Data Lake Store account.
        :type account_name: str
        :param parameters: Parameters supplied to create the Data Lake Store account.
        :type parameters: ~azure.mgmt.datalake.store.models.CreateDataLakeStoreAccountParameters
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either DataLakeStoreAccount or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.datalake.store.models.DataLakeStoreAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.DataLakeStoreAccount"]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._create_initial(
                resource_group_name=resource_group_name,
                account_name=account_name,
                parameters=parameters,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

        def get_long_running_output(pipeline_response):
            deserialized = self._deserialize('DataLakeStoreAccount', pipeline_response)

            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized

        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
        }

        if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}'}  # type: ignore

    def get(
        self,
        resource_group_name,  # type: str
        account_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "_models.DataLakeStoreAccount"
        """Gets the specified Data Lake Store account.

        :param resource_group_name: The name of the Azure resource group.
        :type resource_group_name: str
        :param account_name: The name of the Data Lake Store account.
        :type account_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DataLakeStoreAccount, or the result of cls(response)
        :rtype: ~azure.mgmt.datalake.store.models.DataLakeStoreAccount
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.DataLakeStoreAccount"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-11-01"
        accept = "application/json"

        # Construct URL
        url = self.get.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        deserialized = self._deserialize('DataLakeStoreAccount', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}'}  # type: ignore

    def _update_initial(
        self,
        resource_group_name,  # type: str
        account_name,  # type: str
        parameters,  # type: "_models.UpdateDataLakeStoreAccountParameters"
        **kwargs  # type: Any
    ):
        # type: (...) -> "_models.DataLakeStoreAccount"
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.DataLakeStoreAccount"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-11-01"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self._update_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(parameters, 'UpdateDataLakeStoreAccountParameters')
        body_content_kwargs['content'] = body_content
        request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 201, 202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        if response.status_code == 200:
            deserialized = self._deserialize('DataLakeStoreAccount', pipeline_response)

        if response.status_code == 201:
            deserialized = self._deserialize('DataLakeStoreAccount', pipeline_response)

        if response.status_code == 202:
            deserialized = self._deserialize('DataLakeStoreAccount', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}'}  # type: ignore

    def begin_update(
        self,
        resource_group_name,  # type: str
        account_name,  # type: str
        parameters,  # type: "_models.UpdateDataLakeStoreAccountParameters"
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.DataLakeStoreAccount"]
        """Updates the specified Data Lake Store account information.

        :param resource_group_name: The name of the Azure resource group.
        :type resource_group_name: str
        :param account_name: The name of the Data Lake Store account.
        :type account_name: str
        :param parameters: Parameters supplied to update the Data Lake Store account.
        :type parameters: ~azure.mgmt.datalake.store.models.UpdateDataLakeStoreAccountParameters
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either DataLakeStoreAccount or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.datalake.store.models.DataLakeStoreAccount]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.DataLakeStoreAccount"]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._update_initial(
                resource_group_name=resource_group_name,
                account_name=account_name,
                parameters=parameters,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

        def get_long_running_output(pipeline_response):
            deserialized = self._deserialize('DataLakeStoreAccount', pipeline_response)

            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized

        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
        }

        if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}'}  # type: ignore

    def _delete_initial(
        self,
        resource_group_name,  # type: str
        account_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-11-01"

        # Construct URL
        url = self._delete_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]

        request = self._client.delete(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 202, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})

    _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}'}  # type: ignore

    def begin_delete(
        self,
        resource_group_name,  # type: str
        account_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller[None]
        """Deletes the specified Data Lake Store account.

        :param resource_group_name: The name of the Azure resource group.
        :type resource_group_name: str
        :param account_name: The name of the Data Lake Store account.
        :type account_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._delete_initial(
                resource_group_name=resource_group_name,
                account_name=account_name,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

        def get_long_running_output(pipeline_response):
            if cls:
                return cls(pipeline_response, None, {})

        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
        }

        if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}'}  # type: ignore

    def enable_key_vault(
        self,
        resource_group_name,  # type: str
        account_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Attempts to enable a user managed Key Vault for encryption of the specified Data Lake Store
        account.

        :param resource_group_name: The name of the Azure resource group.
        :type resource_group_name: str
        :param account_name: The name of the Data Lake Store account.
        :type account_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-11-01"

        # Construct URL
        url = self.enable_key_vault.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'accountName': self._serialize.url("account_name", account_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]

        request = self._client.post(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})

    enable_key_vault.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/enableKeyVault'}  # type: ignore

    def check_name_availability(
        self,
        location,  # type: str
        parameters,  # type: "_models.CheckNameAvailabilityParameters"
        **kwargs  # type: Any
    ):
        # type: (...) -> "_models.NameAvailabilityInformation"
        """Checks whether the specified account name is available or taken.

        :param location: The resource location without whitespace.
        :type location: str
        :param parameters: Parameters supplied to check the Data Lake Store account name availability.
        :type parameters: ~azure.mgmt.datalake.store.models.CheckNameAvailabilityParameters
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: NameAvailabilityInformation, or the result of cls(response)
        :rtype: ~azure.mgmt.datalake.store.models.NameAvailabilityInformation
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.NameAvailabilityInformation"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-11-01"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self.check_name_availability.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'location': self._serialize.url("location", location, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(parameters, 'CheckNameAvailabilityParameters')
        body_content_kwargs['content'] = body_content
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        deserialized = self._deserialize('NameAvailabilityInformation', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    check_name_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DataLakeStore/locations/{location}/checkNameAvailability'}  # type: ignore


text:
HelloNodeJS
===========

Repository to test NodeJS

============

Run in Development Mode
$ NODE_ENV=development DEBUG=HelloNodeJS npm start

Run in Production Mode
$ NODE_ENV=production DEBUG=HelloNodeJS npm start

Run in Staging Mode
$ NODE_ENV=staging DEBUG=HelloNodeJS npm start


text:
using std::string;

class CopyFileTest : public TemporaryDirectoryTest {};

TEST_F(CopyFileTest, CopyWithAbsolutePath) {
  const string fileContents = "Some file content";

  const string sourceFile = path::join(sandbox.get(), "source-file");
  EXPECT_SOME(os::write(sourceFile, fileContents));

  const string destination = path::join(sandbox.get(), "dest-file");
  EXPECT_FALSE(os::exists(destination));

  EXPECT_SOME(os::copyfile(sourceFile, destination));
  EXPECT_TRUE(os::exists(destination));

  // Check contents of files for the correct data.
  EXPECT_SOME_EQ(fileContents, os::read(sourceFile));
  EXPECT_SOME_EQ(fileContents, os::read(destination));
}

TEST_F(CopyFileTest, CopyToDirectoryDestinationFails) {
  const string sourceFile = path::join(sandbox.get(), "source-file");
  EXPECT_SOME(os::write(sourceFile, "Some file content"));

  const string destination = path::join(sandbox.get(), "dest-dir");
  EXPECT_FALSE(os::exists(destination));
  EXPECT_SOME(os::mkdir(destination));

  // Copying to a directory should fail.
  EXPECT_ERROR(os::copyfile(sourceFile, destination));
}

TEST_F(CopyFileTest, DestinationEndsInSlashFails) {
  const string sourceFile = path::join(sandbox.get(), "source-file");
  EXPECT_SOME(os::write(sourceFile, "Some file content"));

  const string destination = path::join(sandbox.get(), "dest-dir/");
  EXPECT_FALSE(os::exists(destination));

  // Copying to a destination that looks like a directory should fail.
  EXPECT_ERROR(os::copyfile(sourceFile, destination));
}

TEST_F(CopyFileTest, CopyToRelativeFilenameFails) {
  const string sourceFile = path::join(sandbox.get(), "source-file");
  EXPECT_SOME(os::write(sourceFile, "Some file content"));

  const string destination = path::join(sandbox.get(), "dest-file");

  // Relative file locations will be rejected.
  EXPECT_ERROR(os::copyfile(sourceFile, "dest-file"));
  EXPECT_ERROR(os::copyfile("source-file", destination));
  EXPECT_ERROR(os::copyfile("source-file", "dest-file"));
}


text:
module Win32
  module Screenshot
    # @private
    # This is an internal class for taking the actual screenshots and not part of a public API.
    class BitmapMaker
      class << self
        extend FFI::Library

        ffi_lib 'user32', 'gdi32'
        ffi_convention :stdcall

        # user32.dll
        attach_function :window_dc, :GetWindowDC,
                        [:long], :long
        attach_function :window_rect, :GetWindowRect,
                        [:long, :pointer], :bool
        attach_function :foreground_window, :GetForegroundWindow,
                        [], :long
        attach_function :desktop_window, :GetDesktopWindow,
                        [], :long
        attach_function :print_window, :PrintWindow,
                        [:long, :long, :int], :bool
        attach_function :get_system_metrics, :GetSystemMetrics,
                        [:int], :int

        # gdi32.dll
        attach_function :create_compatible_dc, :CreateCompatibleDC,
                        [:long], :long
        attach_function :create_compatible_bitmap, :CreateCompatibleBitmap,
                        [:long, :int, :int], :long
        attach_function :select_object, :SelectObject,
                        [:long, :long], :long
        attach_function :di_bits, :GetDIBits,
                        [:long, :long, :int, :int, :pointer, :pointer, :int], :int
        attach_function :delete_object, :DeleteObject,
                        [:long], :bool
        attach_function :delete_dc, :DeleteDC,
                        [:long], :bool
        attach_function :release_dc, :ReleaseDC,
                        [:long, :long], :int
        attach_function :bit_blt, :BitBlt,
                        [:long, :int, :int, :int, :int, :long, :int, :int, :long], :bool

        DIB_RGB_COLORS = 0
        PW_RENDERFULLCONTENT = 0x00000002
        SRCCOPY = 0x00CC0020

        SM_XVIRTUALSCREEN = 76
        SM_YVIRTUALSCREEN = 77
        SM_CXVIRTUALSCREEN = 78
        SM_CYVIRTUALSCREEN = 79

        def capture_window(hwnd)
          width, height = dimensions_for(hwnd)

          hScreenDC, hmemDC, hmemBM = prepare_object(hwnd, width, height)
          print_window(hwnd, hmemDC, PW_RENDERFULLCONTENT)
          create_bitmap(hScreenDC, hmemDC, hmemBM, width, height)
        end

        def capture_screen(hwnd)
          left, top, width, height = desktop.dimensions

          hScreenDC, hmemDC, hmemBM = prepare_object(hwnd, width, height)
          bit_blt(hmemDC, 0, 0, width, height, hScreenDC, left, top, SRCCOPY)
          create_bitmap(hScreenDC, hmemDC, hmemBM, width, height)
        end

        def prepare_object(hwnd, width, height)
          hScreenDC = window_dc(hwnd)
          hmemDC = create_compatible_dc(hScreenDC)
          hmemBM = create_compatible_bitmap(hScreenDC, width, height)
          select_object(hmemDC, hmemBM)
          [hScreenDC, hmemDC, hmemBM]
        end

        def create_bitmap(hScreenDC, hmemDC, hmemBM, width, height)
          bitmap_size = width * height * 3 + width % 4 * height
          lpvpxldata = FFI::MemoryPointer.new(bitmap_size)

          # Bitmap header
          # http://www.fortunecity.com/skyscraper/windows/364/bmpffrmt.html
          bmInfo = [40, width, height, 1, 24, 0, 0, 0, 0, 0, 0, 0].pack('L3S2L6')
          di_bits(hmemDC, hmemBM, 0, height, lpvpxldata, bmInfo, DIB_RGB_COLORS)

          bmFileHeader = [
                  19778,
                  bitmap_size + 40 + 14,
                  0,
                  0,
                  54
          ].pack('SLSSL')

          Image.new(bmFileHeader + bmInfo + lpvpxldata.read_string(bitmap_size), width, height)
        ensure
          lpvpxldata.free
          delete_object(hmemBM)
          delete_dc(hmemDC)
          release_dc(0, hScreenDC)
        end

        def desktop
          Win32::Screenshot::Desktop.new(
               get_system_metrics(SM_XVIRTUALSCREEN),
               get_system_metrics(SM_YVIRTUALSCREEN),
               get_system_metrics(SM_CXVIRTUALSCREEN),
               get_system_metrics(SM_CYVIRTUALSCREEN)
          )
        end

        def dimensions_for(hwnd)
          rect = [0, 0, 0, 0].pack('l4')
          window_rect(hwnd.to_i, rect)
          left, top, width, height = rect.unpack('l4')

          [width - left, height - top]
        end
      end
    end
  end
end


text:
<?php
namespace frontend\models;

use yii\base\Model;
use common\models\User;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $username;
    public $email;
    public $password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }

        $user = new User();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        $saved = $user->save() ? $user : null;
        if ($saved) {
            // assign role of regular user
            $auth = \Yii::$app->authManager;
            $userRole = $auth->getRole('user');
            $auth->assign($userRole, $user->getId());
        }
        return $saved;
    }
}


text:
using DragonSpark.Model.Commands;
using DragonSpark.Model.Selection;
using Microsoft.Extensions.DependencyInjection;

namespace DragonSpark.Composition.Compose.Deferred;

sealed class ApplyDeferredRegistrations : ICommand<IServiceCollection>
{
	public static ApplyDeferredRegistrations Default { get; } = new();

	ApplyDeferredRegistrations() : this(GetDeferredRegistrations.Default) { }

	readonly ISelect<IServiceCollection, DeferredRegistrations> _accessor;

	public ApplyDeferredRegistrations(ISelect<IServiceCollection, DeferredRegistrations> accessor)
		=> _accessor = accessor;

	public void Execute(IServiceCollection parameter)
	{
		foreach (var registration in _accessor.Get(parameter))
		{
			registration.Execute(parameter);
		}
	}
}