text:
import {
  ADSENSE_MCRSPV_TAG,
  ADSENSE_RSPV_TAG,
  ADSENSE_RSPV_WHITELISTED_HEIGHT,
  getMatchedContentResponsiveHeightAndUpdatePubParams,
} from '../../../ads/google/utils';
import {Services} from '../../../src/services';
import {addExperimentIdToElement} from '../../../ads/google/a4a/traffic-experiments';
import {clamp} from '../../../src/utils/math';
import {computedStyle, setStyle} from '../../../src/style';
import {dev, devAssert, user} from '../../../src/log';
import {getData} from '../../../src/event-helper';
import {hasOwn} from '../../../src/utils/object';
import {randomlySelectUnsetExperiments} from '../../../src/experiments';
import {toWin} from '../../../src/types';

const TAG = 'amp-ad-network-adsense-impl';

/**
 * Value of &rafmt= URL parameter depending on data-auto-format.
 * @const {!Object<string, number>}
 */
const RAFMT_PARAMS = {
  [ADSENSE_RSPV_TAG]: 13,
  [ADSENSE_MCRSPV_TAG]: 15,
};

/** @const {!{branch: string, control: string, experiment: string}}
    @visibleForTesting
*/
export const AD_SIZE_OPTIMIZATION_EXP = {
  branch: 'adsense-ad-size-optimization',
  control: '368226510',
  experiment: '368226511',
};

/** @const {!{branch: string, control: string, experiment: string}}
    @visibleForTesting
*/
export const MAX_HEIGHT_EXP = {
  branch: 'fix-inconsistent-responsive-height-selection',
  control: '368226520',
  experiment: '368226521',
};

/** @final */
export class ResponsiveState {
  /**
   * @param {!Element} element
   */
  constructor(element) {
    /**  @private {!Element}*/
    this.element_ = element;

    /** @private {boolean} */
    this.isAlignedToViewport_ = false;

    /** @private {!Window} */
    this.win_ = toWin(element.ownerDocument.defaultView);
  }

  /**
   * @param {!Element} element to potentially create state for.
   * @return {?ResponsiveState} reponsive state for the element, if it
   *  corresponds to a responsive ad, otherwise null.
   */
  static createIfResponsive(element) {
    const autoFormat = element.getAttribute('data-auto-format');
    if (!hasOwn(RAFMT_PARAMS, autoFormat)) {
      return null;
    }
    return new ResponsiveState(element);
  }

  /**
   * Upgrades the ad unit to responsive if there is an opt-in setting in localstorage.
   * See https://github.com/ampproject/amphtml/issues/23568 for design.
   * @param {!Element} element
   * @param {string} adClientId
   * @return {!Promise<?ResponsiveState>} a promise that resolves when any upgrade is complete.
   */
  static maybeUpgradeToResponsive(element, adClientId) {
    if (!ResponsiveState.isInAdSizeOptimizationExperimentBranch_(element)) {
      return Promise.resolve(null);
    }
    // If the ad unit is already responsive we don't upgrade again.
    if (element.hasAttribute('data-auto-format')) {
      return Promise.resolve(null);
    }
    return (
      Services.storageForDoc(element)
        .then(storage =>
          storage.get(
            ResponsiveState.getAdSizeOptimizationStorageKey_(adClientId)
          )
        )
        .then(isAdSizeOptimizationEnabled => {
          if (isAdSizeOptimizationEnabled) {
            return ResponsiveState.upgradeToResponsive_(element);
          }
          return null;
        })
        // Do nothing if we fail to read localstorage.
        .catch(() => {
          dev().warn(TAG, 'Failed to look up publisher ad size settings.');
          return null;
        })
    );
  }

  /**
   * Upgrades the element to responsive.
   *
   * @param {!Element} element
   * @return {!ResponsiveState} responsive state
   * @private
   */
  static upgradeToResponsive_(element) {
    element.setAttribute('height', ADSENSE_RSPV_WHITELISTED_HEIGHT);
    element.setAttribute('width', '100vw');
    element.setAttribute('data-full-width', '');
    element.setAttribute('data-auto-format', 'rspv');

    const state = ResponsiveState.createIfResponsive(element);
    devAssert(state != null, 'Upgrade failed');
    return /** @type {!ResponsiveState} */ (state);
  }

  /**
   * Sets up a listener for a pingback of publisher settings in the ad response and
   * writing such settings to localstorage.
   *
   * Note that we can have multiple listeners on the same page, which is okay because
   * the settings for publishers should not change between different slots.
   *
   * Once the listener has received one valid setting update event, it will remove
   * itself.
   *
   * See https://github.com/ampproject/amphtml/issues/23568 for design.
   *
   * @param {!Element} element to use for fetching storage.
   * @param {!HTMLIFrameElement} iframe ad iframe.
   * @param {string} adClientId
   * @return {?Promise} a promise that resolves when ad size settings are updated, or null if no listener was attached.
   */
  static maybeAttachSettingsListener(element, iframe, adClientId) {
    if (!ResponsiveState.isInAdSizeOptimizationExperimentBranch_(element)) {
      return null;
    }
    let promiseResolver;
    const savePromise = new Promise(resolve => {
      promiseResolver = resolve;
    });
    const win = toWin(element.ownerDocument.defaultView);

    const listener = event => {
      if (event['source'] != iframe.contentWindow) {
        return;
      }
      const data = getData(event);
      // data will look like this:
      // {
      //   'googMsgType': 'adsense-settings',
      //   'adClient': 'ca-pub-123',
      //   'enableAutoAdSize': '1'
      // }
      if (!!data && data['googMsgType'] != 'adsense-settings') {
        return;
      }
      if (data['adClient'] != adClientId) {
        return;
      }

      const autoAdSizeStatus = data['enableAutoAdSize'] == '1';
      win.removeEventListener('message', listener);

      Services.storageForDoc(element)
        .then(storage =>
          storage
            .set(
              ResponsiveState.getAdSizeOptimizationStorageKey_(adClientId),
              autoAdSizeStatus
            )
            .then(() => {
              dev().info(
                TAG,
                `Saved publisher auto ad size setting: ${autoAdSizeStatus}`
              );
              promiseResolver();
            })
        )
        // Do nothing if we fail to write to localstorage.
        .catch(() => {
          dev().warn(TAG, 'Failed to persist publisher auto ad size setting.');
        });
    };
    win.addEventListener('message', listener);
    return savePromise;
  }

  /**
   * @param {string} adClientId
   * @return {string} ad size optimization storage key.
   * @private
   */
  static getAdSizeOptimizationStorageKey_(adClientId) {
    return `aas-${adClientId}`;
  }

  /** @return {boolean} */
  isValidElement() {
    if (!this.element_.hasAttribute('data-full-width')) {
      user().warn(
        TAG,
        'Responsive AdSense ad units require the attribute ' +
          'data-full-width.'
      );
      return false;
    }

    const height = this.element_.getAttribute('height');
    const width = this.element_.getAttribute('width');
    // height is set to 0 by amp-auto-ads to avoid reflow.
    if (height != 0 && height != ADSENSE_RSPV_WHITELISTED_HEIGHT) {
      user().warn(
        TAG,
        `Specified height ${height} in <amp-ad> tag is not equal to the ` +
          `required height of ${ADSENSE_RSPV_WHITELISTED_HEIGHT} for ` +
          'responsive AdSense ad units.'
      );
      return false;
    }
    if (width != '100vw') {
      user().warn(
        TAG,
        `Invalid width ${width} for full-width responsive <amp-ad> tag. ` +
          'Width must be 100vw.'
      );
      return false;
    }
    return true;
  }

  /** Aligns the responsive element with the viewport edges.*/
  alignToViewport() {
    if (this.isAlignedToViewport_) {
      return;
    }
    this.isAlignedToViewport_ = true;
    const vsync = Services.vsyncFor(this.win_);
    const layoutBox = this.element_.getLayoutBox();
    // Nudge into the correct horizontal position by changing side margin.
    vsync.run(
      {
        measure: state => {
          // Check the parent element because amp-ad is explicitly styled to
          // have direction: ltr.
          state.direction = computedStyle(
            this.win_,
            dev().assertElement(this.element_.parentElement)
          )['direction'];
        },
        mutate: state => {
          if (state.direction == 'rtl') {
            setStyle(this.element_, 'marginRight', layoutBox.left, 'px');
          } else {
            setStyle(this.element_, 'marginLeft', -layoutBox.left, 'px');
          }
        },
      },
      {direction: ''}
    );
  }

  /**
   * @return {string}
   * @private
   */
  getAutoFormat_() {
    return this.element_.getAttribute('data-auto-format');
  }

  /**
   * @return {number}
   */
  getRafmtParam() {
    return RAFMT_PARAMS[this.getAutoFormat_()];
  }

  /**
   * Selects into the ad size optimization experiment.
   * @param {!Element} element
   * @return {boolean}
   */
  static isInAdSizeOptimizationExperimentBranch_(element) {
    const experimentInfoMap = /** @type {!Object<string,
        !../../../src/experiments.ExperimentInfo>} */ ({
      [[AD_SIZE_OPTIMIZATION_EXP.branch]]: {
        isTrafficEligible: () => true,
        branches: [
          [AD_SIZE_OPTIMIZATION_EXP.control],
          [AD_SIZE_OPTIMIZATION_EXP.experiment],
        ],
      },
    });
    const win = toWin(element.ownerDocument.defaultView);
    const setExps = randomlySelectUnsetExperiments(win, experimentInfoMap);
    Object.keys(setExps).forEach(expName =>
      addExperimentIdToElement(setExps[expName], element)
    );
    return (
      setExps[AD_SIZE_OPTIMIZATION_EXP.branch] ==
      AD_SIZE_OPTIMIZATION_EXP.experiment
    );
  }

  /**
   * Selects into the inconsistent responsive height fix experiment.
   * @return {boolean}
   * @private
   */
  isInResponsiveHeightFixExperimentBranch_() {
    const experimentInfoMap = /** @type {!Object<string,
        !../../../src/experiments.ExperimentInfo>} */ ({
      [[MAX_HEIGHT_EXP.branch]]: {
        isTrafficEligible: () => true,
        branches: [[MAX_HEIGHT_EXP.control], [MAX_HEIGHT_EXP.experiment]],
      },
    });
    const setExps = randomlySelectUnsetExperiments(
      this.win_,
      experimentInfoMap
    );
    Object.keys(setExps).forEach(expName =>
      addExperimentIdToElement(setExps[expName], this.element_)
    );
    return setExps[MAX_HEIGHT_EXP.branch] == MAX_HEIGHT_EXP.experiment;
  }

  /**
   * Attempts to change the size to match the desired responsive height.
   * @return {!Promise} a promise that resolves when we have attempted to change size
   * (whether successfully or not).
   */
  attemptToMatchResponsiveHeight() {
    const viewportSize = Services.viewportForDoc(
      this.element_.getAmpDoc()
    ).getSize();
    // Attempt to resize to the correct height. The width should already be
    // 100vw, but is fixed here so that future resizes of the viewport don't
    // affect it.
    return this.element_
      .getImpl(/* waitForBuild= */ false)
      .then(impl =>
        impl
          .attemptChangeSize(
            this.getResponsiveHeight_(viewportSize),
            viewportSize.width
          )
          .catch(() => {})
      );
  }

  /**
   * Calculates the appropriate height for a full-width responsive ad of the
   * given width.
   * @param {!{width: number, height: number}} viewportSize
   * @return {number}
   * @private
   */
  getResponsiveHeight_(viewportSize) {
    switch (this.getAutoFormat_()) {
      case ADSENSE_RSPV_TAG:
        const minHeight = 100;
        const maxHeight = Math.min(
          this.isInResponsiveHeightFixExperimentBranch_() ? 500 : 300,
          viewportSize.height
        );
        // We aim for a 6:5 aspect ratio.
        const idealHeight = Math.round(viewportSize.width / 1.2);
        return clamp(idealHeight, minHeight, maxHeight);
      case ADSENSE_MCRSPV_TAG:
        return getMatchedContentResponsiveHeightAndUpdatePubParams(
          viewportSize.width,
          this.element_
        );
      default:
        return 0;
    }
  }
}


text:
package net.jxta.exception;

/**
 * Thrown when JXTA cannot continue running.
 */

public class JxtaError extends Error {

    /**
     * Construct a new JxtaError with no detailed message.
     *
     */
    public JxtaError() {}

    public JxtaError(String msg) {
        super(msg);
    }

    public JxtaError(String msg, Throwable cause) {
        super(msg, cause);
    }

    public JxtaError(Throwable cause) {
        super(cause);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package br.com.arbo.steamside.steam.client.rungame;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.Validate;

import br.com.arbo.opersys.processes.seek.Criteria;
import br.com.arbo.opersys.processes.seek.ProcessSeeker;
import br.com.arbo.opersys.processes.seek.ProcessSeekerFactory;

class WaitForExecutable {

	WaitForExecutable(final String exe,
			ScheduledExecutorServiceFactory executorFactory)
	{
		Validate.notNull(exe);
		criteria = new Criteria();
		criteria.executable = exe;
		executor = executorFactory
				.newScheduledExecutorService(
				"Seek executable: " + exe);
	}

	void waitFor() throws Timeout
	{
		goSeekInAnotherThread();
		try
		{
			waitUntilItsUp();
		}
		finally
		{
			stopSeeking();
		}
	}

	private void goSeekInAnotherThread()
	{
		this.future = executor.scheduleWithFixedDelay(
				this::seek, 0, 1, TimeUnit.SECONDS);
	}

	private void seek()
	{
		if (!seeker.seek(criteria)) return;
		seeking.release();
		future.cancel(false);
	}

	private void stopSeeking()
	{
		executor.shutdown();
	}

	private void waitUntilItsUp() throws Timeout
	{
		try
		{
			if (!seeking.tryAcquire(1, TimeUnit.MINUTES))
			{
				throw new Timeout();
			}
		}
		catch (final InterruptedException e)
		{
			throw new RuntimeException(e);
		}
	}

	private final ProcessSeeker seeker = ProcessSeekerFactory.build();
	private final Criteria criteria;
	private final Semaphore seeking = new Semaphore(0);
	private final ScheduledExecutorService executor;
	private ScheduledFuture< ? > future;

}


text:
<?php

if ($recaptcha = \RemoteSystems\ReCaptcha::getInstance()) {
    ContactRequestHandler::$validators[] = [
        'id' => 'ReCaptcha',
        'field' => 'g-recaptcha-response',
        'required' => true,
        'errorMessage' => 'Please prove that you aren\'t a spam robot by completing the reCAPTCHA',
        'validator' => function ($response) use ($recaptcha) {
            $recaptchaResponse = $recaptcha->verify($response, $_SERVER['REMOTE_ADDR']);

            return $recaptchaResponse->isSuccess();
        },
    ];

    ContactRequestHandler::$excludeFields[] = 'g-recaptcha-response';
}


text:
[![Build status](https://travis-ci.org/epickrram/rustogram.svg?branch=master)](https://travis-ci.org/epickrram/rustogram)

A Rust port of [HdrHistogram](https://github.com/HdrHistogram/HdrHistogram).

# features

* Implements the signed 64-bit histogram implementation
* Binary compatible storage/retrieval of histogram values
* Serialisation compatible (v2 only, scaling not supported)

# usage

	extern crate rustogram;
	#[test]
	fn it_works() {
    	let mut h = rustogram::histogram::new_histogram(10000, 3);
    	h.record_value(42);
    	println!("Total recorded samples: {}", h.get_total_count());
	}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Nymphicus.ExternalLibraries.Notifications.Snarl
{
    public class SnarlInterface
    {
        /// <summary>
        /// Snarl C# interface implementation
        /// API version 42
        ///
        /// http://sourceforge.net/apps/mediawiki/snarlwin/index.php?title=Windows_API
        /// https://sourceforge.net/apps/mediawiki/snarlwin/index.php?title=Generic_API
        ///
        /// Written and maintained by Toke Noer N�ttrup (toke@noer.it)
        ///
        /// Please note the following changes compared to the general (official API) dokumentation:
        ///  - Naming of constants and variables are generally changed to follow Microsoft C# standard.
        ///    - Grouped variables like SNARL_LAUNCHED, SNARL_QUIT is in enum GlobalEvent.
        ///
        ///  - Some functions in the general API takes an appToken as first parameter. This token
        ///    is a member variable in C# version, so it is omitted from the functions.
        ///    (Always call RegisterApp as first function!)
        ///
        ///  - Functions manipulating messages (Update, Hide etc.) still takes a message token as
        ///    parameter, but you can get the last message token calling GetLastMsgToken();
        ///    Example: snarl.Hide(snarl.GetLastMsgToken());
        ///
        ///  - Implements RegisterWithEvents() and event handlers. See SnarlInterfaceExample1 project.
        ///
        /// Note on optional parameters:
        ///   Since C# 3.0 and prior doesn't have optional parameters, the C# SnarlInterface does not
        ///   use this feature! Some functions have overloaded versions though. If no suitable
        ///   overload exists, pass null for optional parameters.
        ///
        /// </summary>
        ///
        /// <VersionHistory>
        /// 2011-03-13 : Implemented Update()
        ///            : Initial event implementation. Needs cleanup.
        /// 2011-02-05 : Removed MessageEvent enum. Only SnarlStatus enum now (same as in VB code)
        /// 2011-02-04 : Updated per rev. 3 of General API documentation.
        ///            : Implemented Escape function. Updated some documentation and fixes.
        ///            : Should be usable by now!
        /// 2011-02-03 : Initial release of V42 API
        /// </VersionHistory>
        ///
        /// <Todo>
        ///  - Update documentation all around
        /// </Todo>
        ///

        #region Public constants and enums

        /// <summary>
        /// Global event identifiers.
        /// Identifiers marked with a '*' are sent by Snarl in two ways:
        ///   1. As a broadcast message (uMsg = 'SNARL_GLOBAL_MSG')
        ///   2. To the window registered in snRegisterConfig() or snRegisterConfig2()
        ///      (uMsg = reply message specified at the time of registering)
        /// In both cases these values appear in wParam.
        ///
        /// Identifiers not marked are not broadcast; they are simply sent to the application's registered window.
        /// </summary>
        public enum GlobalEvent
        {
            SnarlLaunched = 1,      // Snarl has just started running*
            SnarlQuit = 2,          // Snarl is about to stop running*
            SnarlAskAppletVer = 3,  // (R1.5) Reserved for future use
            SnarlShowAppUi = 4,     // (R1.6) Application should show its UI

            // R2.4 Beta3
            SnarlUserAway,          // away mode was enabled
            SnarlUserBack,          // away mode was disabled
        }

        /// <summary>
        /// Snarl status codes.
        /// Containes error codes for function calls, as well as callback values sent by Snarl
        /// to the window specified in Register() when the Snarl Notification raised times out
        /// or the user clicks on it.
        /// </summary>
        public enum SnarlStatus : short
        {
            Success = 0,

            // Win32 callbacks (renamed under V42)
            CallbackRightClick = 32,       // Deprecated as of V42, ex. SNARL_NOTIFICATION_CLICKED/SNARL_NOTIFICATION_CANCELLED
            CallbackTimedOut,
            CallbackInvoked,               // left clicked and no default callback assigned
            CallbackMenuSelected,          // HIWORD(wParam) contains 1-based menu item index
            CallbackMiddleClick,           // Deprecated as of V42
            CallbackClosed,

            // critical errors
            ErrorFailed = 101,             // miscellaneous failure
            ErrorUnknownCommand,           // specified command not recognised
            ErrorTimedOut,                 // Snarl took too long to respond
            //104 gen critical #4
            //105 gen critical #5
            ErrorBadSocket = 106,          // invalid socket (or some other socket-related error)
            ErrorBadPacket = 107,          // badly formed request
            //108 net critical #3
            ErrorArgMissing = 109,         // required argument missing
            ErrorSystem,                   // internal system error
            //120 libsnarl critical block
            ErrorAccessDenied = 121,       // libsnarl only

            // warnings
            ErrorNotRunning = 201,         // Snarl handling window not found
            ErrorNotRegistered,
            ErrorAlreadyRegistered,        // not used yet; sn41RegisterApp() returns existing token
            ErrorClassAlreadyExists,       // not used yet
            ErrorClassBlocked,
            ErrorClassNotFound,
            ErrorNotificationNotFound,
            ErrorFlooding,                 // notification generated by same class within quantum
            ErrorDoNotDisturb,             // DnD mode is in effect was not logged as missed
            ErrorCouldNotDisplay,          // not enough space on-screen to display notification
            ErrorAuthFailure,              // password mismatch

            // informational
            WasMerged = 251,               // notification was merged, returned token is the one we merged with

            // callbacks
            NotifyGone = 301,              // reserved for future use

            // The following are currently specific to SNP 2.0 and are effectively the
            // Win32 SNARL_CALLBACK_nnn constants with 270 added to them

            // SNARL_NOTIFY_CLICK = 302    // indicates notification was right-clicked (deprecated as of V42)
            NotifyExpired = 303,
            NotifyInvoked = 304,           // note this was "ACK" in a previous life
            NotifyMenu,                    // indicates an item was selected from user-defined menu (deprecated as of V42)
            // SNARL_NOTIFY_EX_CLICK       // user clicked the middle mouse button (deprecated as of V42)
            // SNARL_NOTIFY_CLOSED         // user clicked the notification's close gadget

            // the following is generic to SNP and the Win32 API
            NotifyAction = 308             // user picked an action from the list, the data value will indicate which one
        }

        /// <summary>
        /// The priority of messages.
        /// See <cref>http://sourceforge.net/apps/mediawiki/snarlwin/index.php?title=Generic_API#notify</cref>
        /// </summary>
        public enum MessagePriority
        {
            Low = -1,
            Normal = 0,
            High = 1
        }

        public const uint WM_SNARLTEST = (uint)WindowsMessage.WM_USER + 237;

        #endregion

        #region Internal constants and enums

        protected const string SnarlWindowClass = "w>Snarl";
        protected const string SnarlWindowTitle = "Snarl";

        protected const string SnarlGlobalMsg = "SnarlGlobalEvent";
        protected const string SnarlAppMsg = "SnarlAppMessage";

        // protected const Int32 WM_DEFAULT_APPMSG = (Int32)WindowsMessage.WM_APP + 0x2fff; // AFFF
        protected const Int32 WM_DEFAULT_APPMSG = (Int32)WindowsMessage.WM_USER + 0x1fff;  // 23FF

        #endregion

        #region Member variables

        private Int32 appToken = 0;
        private Int32 lastMsgToken = 0;
        private String appSignature = "";
        private String password = null;
        private Object instanceLock = new Object();

        #endregion

        #region Static Snarl functions

        public struct Requests
        {
            public static String AddAction { get { return "addaction"; } }
            public static String AddClass { get { return "addclass"; } }
            public static String ClearActions { get { return "clearactions"; } }
            public static String ClearClasses { get { return "clearclasses"; } }
            public static String Hello { get { return "hello"; } }
            public static String Hide { get { return "hide"; } }
            public static String IsVisible { get { return "isvisible"; } }
            public static String Notify { get { return "notify"; } }
            public static String Register { get { return "register"; } }
            public static String RemoveClass { get { return "remclass"; } }
            public static String Unregister { get { return "unregister"; } }
            public static String UpdateApp { get { return "updateapp"; } }
            public static String Update { get { return "update"; } }
            public static String Version { get { return "version"; } }
        }

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

        /// <summary>
        /// Send message to Snarl.
        /// Will UTF8 encode the message before sending.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="replyTimeout">(Optional - default = 1000)</param>
        /// <returns>Return zero or positive on succes. Negative on error.</returns>
        static public Int32 DoRequest(String request, UInt32 replyTimeout)
        {
            Int32 nReturn = -1;
            IntPtr nSendMessageResult = IntPtr.Zero;
            IntPtr ptrToUtf8Request = IntPtr.Zero;
            IntPtr ptrToCds = IntPtr.Zero;
            byte[] utf8Request = null;

            // Test if Snarl is running
            IntPtr hWnd = GetSnarlWindow();
            if (!IsWindow(hWnd))
                return -(Int32)SnarlStatus.ErrorNotRunning;

            try
            {
                // Convert to UTF8
                // utf8Request = StringToUtf8(request);
                UTF8Encoding utf8 = new UTF8Encoding();
                utf8Request = new byte[utf8.GetMaxByteCount(request.Length)];
                int convertCount = utf8.GetBytes(request, 0, request.Length, utf8Request, 0);

                // Create interop struct
                COPYDATASTRUCT cds = new COPYDATASTRUCT();
                cds.dwData = (IntPtr)0x534E4C03; // "SNL",3
                cds.cbData = convertCount;

                // Create unmanaged byte[] and copy utf8Request into it
                ptrToUtf8Request = Marshal.AllocHGlobal(convertCount);
                Marshal.Copy(utf8Request, 0, ptrToUtf8Request, convertCount);
                cds.lpData = ptrToUtf8Request;

                // Create unmanaged pointer to COPYDATASTRUCT
                ptrToCds = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(COPYDATASTRUCT)));
                Marshal.StructureToPtr(cds, ptrToCds, false);

                if (SendMessageTimeout(hWnd,
                          (uint)WindowsMessage.WM_COPYDATA,
                          (IntPtr)GetCurrentProcessId(),
                          ptrToCds,
                          SendMessageTimeoutFlags.SMTO_ABORTIFHUNG | SendMessageTimeoutFlags.SMTO_NOTIMEOUTIFNOTHUNG,
                          replyTimeout,
                          out nSendMessageResult) == IntPtr.Zero)
                {
                    // Error
                    int nError = Marshal.GetLastWin32Error();
                    if (nError == ERROR_TIMEOUT)
                        nReturn = -(Int32)SnarlStatus.ErrorTimedOut;
                    else
                        nReturn = -(Int32)SnarlStatus.ErrorFailed;
                }
                else
                    nReturn = unchecked((Int32)nSendMessageResult.ToInt64()); // Avoid aritmetic overflow error
            }
            finally
            {
                utf8Request = null;
                Marshal.FreeHGlobal(ptrToCds);
                Marshal.FreeHGlobal(ptrToUtf8Request);
            }

            return nReturn;
        }

        static public Int32 DoRequest(String request)
        {
            return DoRequest(request, 1000);
        }

        static public String Escape(String str)
        {
            // Optimize for nothing to escape (all parameters are run through this function!)
            int pos = str.IndexOfAny(new char[] { '=', '&' });

            if (pos != -1)
            {
                // Escape the string
                int len = str.Length;
                char[] charArray = str.ToCharArray();
                StringBuilder sb = new StringBuilder(str.Length + 10); // A random guess at max number of escaped chars

                for (int i = 0; i < str.Length; ++i)
                {
                    if (charArray[i] == '=')
                        sb.Append("=");
                    else if (charArray[i] == '&')
                        sb.Append("&");
                    sb.Append(charArray[i]);
                }
                return sb.ToString();
            }
            else
                return str;
        }

        /// <summary>
        /// Returns true if Snarl system was found running.
        /// </summary>
        /// <returns></returns>
        static public bool IsSnarlRunning()
        {
            return IsWindow(GetSnarlWindow());
        }

        /// <summary>
        /// Returns the version of Snarl running.
        /// </summary>
        /// <returns></returns>
        static public Int32 GetVersion()
        {
            return DoRequest(Requests.Version);
        }

        /// <summary>
        /// Returns the value of Snarl's global registered message.
        /// Notes:
        ///   Snarl registers SNARL_GLOBAL_MSG during startup which it then uses to communicate
        ///   with all running applications through a Windows broadcast message. This function can
        ///   only fail if for some reason the Windows RegisterWindowMessage() function fails
        ///   - given this, this function *cannnot* be used to test for the presence of Snarl.
        /// </summary>
        /// <returns>A 16-bit value (translated to 32-bit) which is the registered Windows message for Snarl.</returns>
        static public uint Broadcast()
        {
            return RegisterWindowMessage(SnarlGlobalMsg);
        }

        /// <summary>
        /// Returns the global Snarl Application message  (V39)
        /// </summary>
        /// <returns>Snarl Application registered message.</returns>
        static public uint AppMsg()
        {
            return RegisterWindowMessage(SnarlAppMsg);
        }

        /// <summary>
        /// Returns a handle to the Snarl Dispatcher window  (V37)
        /// Notes:
        ///   This is now the preferred way to test if Snarl is actually running.
        /// </summary>
        /// <returns>Returns handle to Snarl Dispatcher window, or zero if it's not found</returns>
        static public IntPtr GetSnarlWindow()
        {
            return FindWindow(SnarlWindowClass, SnarlWindowTitle);
        }

        /// <summary>
        /// Returns a fully qualified path to Snarl's installation folder.
        /// This is a V39 API method.
        /// </summary>
        /// <returns>Path to Snarl's installation folder. Empty string on failure.</returns>
        static public string GetAppPath()
        {
            StringBuilder sb = new StringBuilder(512);

            IntPtr hwnd = GetSnarlWindow();
            if (hwnd != IntPtr.Zero)
            {
                IntPtr hWndPath = FindWindowEx(hwnd, IntPtr.Zero, "static", null);
                if (hWndPath != IntPtr.Zero)
                {
                    GetWindowText(hWndPath, sb, 512);
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// Returns a fully qualified path to Snarl's default icon location.
        /// This is a V39 API method.
        /// </summary>
        /// <returns>Path to Snarl's default icon location. Empty string on failure.</returns>
        static public string GetIconsPath()
        {
            return Path.Combine(GetAppPath(), "etc\\icons\\");
        }

        #endregion

        #region SnarlInterface member functions

        /// <summary>
        /// AddAction
        /// </summary>
        /// <param name="notificationToken"></param>
        /// <param name="label"></param>
        /// <param name="command">If using dynamic callback command (@data), use numbers in the range [0, 32767]</param>
        /// <returns></returns>
        public Int32 AddAction(Int32 msgToken, String label, String command)
        {
            // addaction?[token=<notification token>|app-sig=<signature>&uid=<uid>][&password=<password>]&label=<label>&cmd=<command>

            SnarlParameterList spl = new SnarlParameterList(4);
            spl.Add("token", msgToken);
            spl.Add("label", label);
            spl.Add("cmd", command);
            spl.Add("password", password);

            return DoRequest(Requests.AddAction, spl);
        }

        /// <summary>
        /// AddClass
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="name"></param>
        /// <param name="title"></param>
        /// <param name="text"></param>
        /// <param name="icon"></param>
        /// <param name="sound"></param>
        /// <param name="duration"></param>
        /// <param name="callback"></param>
        /// <param name="enabled"></param>
        /// <returns></returns>
        public Int32 AddClass(String classId, String name, String title, String text, String icon, String sound, Int32? duration, String callback, bool enabled)
        {
            // addclass?[token=<token>|app-sig=<signature>][&password=<password>]&id=<class identifier>&name=<class name>[&enabled=<0|1>][&callback=<callback>]
            //          [&title=<title>][&text=<text>][&icon=<icon>][&sound=<sound>][&duration=<duration>]

            SnarlParameterList spl = new SnarlParameterList(9);
            spl.Add("token", appToken);
            spl.Add("id", classId);
            spl.Add("name", name);
            spl.Add("enabled", enabled);
            spl.Add("callback", callback);
            spl.Add("title", title);
            spl.Add("text", text);
            spl.Add("icon", icon);
            spl.Add("sound", sound);
            spl.Add("duration", duration);
            spl.Add("password", password);

            return DoRequest(Requests.AddClass, spl);
        }

        public Int32 AddClass(String classId, String name)
        {
            return AddClass(classId, name, null, null, null, null, null, null, true);
        }

        /// <summary>
        /// ClearActions
        /// </summary>
        /// <param name="notificationToken"></param>
        /// <returns></returns>
        public Int32 ClearActions(Int32 msgToken)
        {
            // clearactions?[token=<notification token>|app-sig=<app-sig>&uid=<uid>][&password=<password>]

            SnarlParameterList spl = new SnarlParameterList(2);
            spl.Add("token", msgToken);
            spl.Add("password", password);

            return DoRequest(Requests.ClearActions, spl);
        }

        /// <summary>
        /// ClearClasses
        /// </summary>
        /// <returns></returns>
        public Int32 ClearClasses()
        {
            // clearclasses?token=<app token>[&password=<password>]

            SnarlParameterList spl = new SnarlParameterList(2);
            spl.Add("token", appToken);
            spl.Add("password", password);

            return DoRequest(Requests.ClearClasses, spl);
        }

        /// <summary>
        /// Hide
        /// </summary>
        /// <param name="msgToken"></param>
        /// <returns></returns>
        public Int32 Hide(Int32 msgToken)
        {
            // hide?[token=<notification token>|app-sig=<app-sig>&uid=<uid>][&password=<password>]

            SnarlParameterList spl = new SnarlParameterList(2);
            spl.Add("token", msgToken);
            spl.Add("password", password);

            return DoRequest(Requests.Hide, spl);
        }

        /// <summary>
        /// IsVisible
        /// </summary>
        /// <param name="msgToken"></param>
        /// <returns></returns>
        public Int32 IsVisible(Int32 msgToken)
        {
            // isvisible?[token=<notification token>|app-sig=<app-sig>&uid=<uid>][&password=<password>]

            SnarlParameterList spl = new SnarlParameterList(2);
            spl.Add("token", msgToken);
            spl.Add("password", password);

            return DoRequest(Requests.IsVisible, spl);
        }

        /// <summary>
        /// Notify
        /// </summary>
        /// <param name="classId">Optional</param>
        /// <param name="title">Optional</param>
        /// <param name="text">Optional</param>
        /// <param name="timeout">Optional</param>
        /// <param name="iconPath">Optional</param>
        /// <param name="iconBase64">Optional</param>
        /// <param name="callback">Optional</param>
        /// <param name="priority">Optional</param>
        /// <param name="uid">Optional</param>
        /// <param name="value">Optional</param>
        /// <returns></returns>
        /// <remarks>All parameters are optional. Pass null to use class default values.</remarks>
        public Int32 Notify(String classId, String title, String text, Int32? timeout, String iconPath, String iconBase64, MessagePriority? priority, String uid, String callback, String value)
        {
            // notify?[app-sig=<signature>|token=<application token>][&password=<password>][&id=<class identifier>]
            //        [&title=<title>][&text=<text>][&timeout=<timeout>][&icon=<icon path>][&icon-base64=<MIME data>][&callback=<default callback>]
            //        [&priority=<priority>][&uid=<notification uid>][&value=<value>]

            SnarlParameterList spl = new SnarlParameterList(8);
            spl.Add("token", appToken);
            spl.Add("password", password);

            spl.Add("id", classId);
            spl.Add("title", title);
            spl.Add("text", text);
            spl.Add("timeout", timeout);
            spl.Add("icon", iconPath);
            spl.Add("icon-base64", iconBase64);
            spl.Add("callback", callback);
            spl.Add("priority", (Int32?)priority);
            spl.Add("uid", uid);
            spl.Add("value", value);

            lastMsgToken = DoRequest(Requests.Notify, spl);

            return lastMsgToken;
        }

        public Int32 Notify(String classId, String title, String text, Int32? timeout, String iconPath, String iconBase64, MessagePriority? priority)
        {
            return Notify(classId, title, text, timeout, iconPath, iconBase64, priority, null, null, null);
        }

        public Int32 Notify(String classId, String title, String text, Int32? timeout, String iconPath, String iconBase64)
        {
            return Notify(classId, title, text, timeout, iconPath, iconBase64, null, null, null, null);
        }

        public Int32 Notify(String classId, String title, String text, Int32? timeout)
        {
            return Notify(classId, title, text, timeout, null, null, null, null, null, null);
        }

        public Int32 Notify(String classId, String title, String text)
        {
            return Notify(classId, title, text, null, null, null, null, null, null, null);
        }

        /// <summary>
        /// RemoveClass
        /// </summary>
        /// <param name="classID"></param>
        /// <returns></returns>
        /// <seealso cref="ClearClasses"/>
        public Int32 RemoveClass(String classID)
        {
            // remclass?[app-sig=<signature>|token=<application token>][&password=<password>][&id=<class identifier>|&all=<0|1>]

            SnarlParameterList spl = new SnarlParameterList(3);
            spl.Add("token", appToken);
            spl.Add("id", classID);
            spl.Add("password", password);
            // spl.Add("all", password); // Use ClearClasses

            return DoRequest(Requests.RemoveClass, spl);
        }

        /// <summary>
        /// Register application with Snarl.
        /// </summary>
        /// <param name="signatur"></param>
        /// <param name="title"></param>
        /// <param name="icon"></param>
        /// <param name="password">Optional (null)</param>
        /// <param name="hWndReply">Optional (IntPtr.Zero)</param>
        /// <param name="msgReply">Optional (0)</param>
        /// <returns></returns>
        public Int32 Register(String signature, String title, String icon, String password, IntPtr hWndReplyTo, Int32 msgReply)
        {
            // register?app-sig=<signature>&title=<title>[&icon=<icon>][&password=<password>][&reply-to=<reply window>][&reply=<reply message>]

            SnarlParameterList spl = new SnarlParameterList(6);
            spl.Add("app-sig", signature);
            spl.Add("title", title);
            spl.Add("icon", icon);
            spl.Add("password", password);
            spl.Add("reply-to", hWndReplyTo);
            spl.Add("reply", msgReply);

            // If password was given, save and use in all other functions requiring password
            if (!String.IsNullOrEmpty(password))
                this.password = password;

            Int32 request = DoRequest(Requests.Register, spl);
            if (request > 0)
            {
                this.appToken = request;
                this.msgReply = msgReply;
                this.appSignature = signature;
            }

            return request;
        }

        public Int32 Register(String signature, String title, String icon, String password)
        {
            return Register(signature, title, icon, password, IntPtr.Zero, 0);
        }

        public Int32 Register(String signature, String title, String icon)
        {
            return Register(signature, title, icon, null, IntPtr.Zero, 0);
        }

        /// <summary>
        /// Unregister application.
        /// </summary>
        /// <returns></returns>
        public Int32 Unregister()
        {
            // unregister?[app-sig=<signature>|token=<application token>][&password=<password>]

            SnarlParameterList spl = new SnarlParameterList(6);
            spl.Add("app-sig", appSignature);
            spl.Add("password", password);

            appToken = 0;
            lastMsgToken = 0;
            appSignature = "";
            password = null;
            msgReply = 0;

            return DoRequest(Requests.Unregister, spl);
        }

        public Int32 Update(Int32 msgToken, String classId, String title, String text, Int32? timeout, String iconPath, String iconBase64, MessagePriority? priority, String ack, String callback, String value)
        {
            // Made from best guess - no documentation available yet
            SnarlParameterList spl = new SnarlParameterList(12);
            spl.Add("token", msgToken);
            spl.Add("password", password);

            spl.Add("id", classId);
            spl.Add("title", title);
            spl.Add("text", text);
            spl.Add("icon", iconPath);
            spl.Add("icon-base64", iconBase64);
            spl.Add("ack", ack);
            spl.Add("callback", callback);
            spl.Add("value", value);
            spl.Add("timeout", timeout);
            spl.Add("priority", (Int32?)priority);

            return DoRequest(Requests.Update, spl);
        }

        public Int32 Update(Int32 msgToken, String classId, String title, String text, Int32? timeout, String iconPath, String iconBase64, MessagePriority? priority)
        {
            return Update(msgToken, classId, title, text, timeout, iconPath, iconBase64, priority, null, null, null);
        }

        public Int32 Update(Int32 msgToken, String classId, String title, String text, Int32? timeout)
        {
            return Update(msgToken, classId, title, text, timeout, null, null, null, null, null, null);
        }

        public Int32 Update(Int32 msgToken, String classId, String title, String text)
        {
            return Update(msgToken, classId, title, text, null, null, null, null, null, null, null);
        }

        /// <summary>
        /// GetLastMsgToken() returns token of the last message sent to Snarl.
        /// </summary>
        /// <returns></returns>
        public Int32 GetLastMsgToken()
        {
            return lastMsgToken;
        }

        #endregion

        #region Private functions

        /// <summary>
        /// Use this function to convert a string into an UTF8 encoded byte[]
        /// </summary>
        /// <param name="strToConvert">The managed string object to convert.</param>
        /// <returns><c>byte[]</c> with the converted string.</returns>
        /*private static byte[] StringToUtf8(string str)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            byte[] returnString = new byte[utf8.GetMaxByteCount(str.Length)];

            int convertCount = utf8.GetBytes(str, 0, str.Length, returnString, 0);

            Array.Resize<byte>(ref returnString, convertCount);

            return returnString;
        }*/

        /// <summary>
        /// Internal helper function for constructing the Snarl messages
        /// </summary>
        /// <param name="request"></param>
        /// <param name="spl"></param>
        /// <param name="replyTimeout"></param>
        /// <returns></returns>
        static private Int32 DoRequest(String request, SnarlParameterList spl, UInt32 replyTimeout)
        {
            // <action>[?<data>=<value>[&<data>=<value>]]

            if (spl.ParamList.Count > 0)
            {
                StringBuilder sb = new StringBuilder(request);
                sb.Append("?");

                foreach (KeyValuePair<String, String> kvp in spl.ParamList)
                {
                    if (kvp.Value != null && kvp.Value.Length > 0)
                    {
                        sb.AppendFormat("{0}={1}&", kvp.Key, Escape(kvp.Value));
                    }
                }

                // Delete last &
                sb.Remove(sb.Length - 1, 1);

                return DoRequest(sb.ToString(), replyTimeout);
            }
            else
                return DoRequest(request, replyTimeout);
        }

        static private Int32 DoRequest(String request, SnarlParameterList spl)
        {
            return DoRequest(request, spl, 1000);
        }

        /// <summary>
        /// Helper class used with internal DoRequest()
        /// </summary>
        private class SnarlParameterList
        {
            private List<KeyValuePair<String, String>> list = new List<KeyValuePair<String, String>>();
            public IList<KeyValuePair<String, String>> ParamList
            {
                get { return list; }
            }

            public SnarlParameterList()
            {
            }

            public SnarlParameterList(int initialCapacity)
            {
                list.Capacity = initialCapacity;
            }

            public void Add(String key, String value)
            {
                if (value != null)
                    list.Add(new KeyValuePair<String, String>(key, value));
            }

            public void Add(String key, bool value)
            {
                list.Add(new KeyValuePair<String, String>(key, value ? "1" : "0"));
            }

            public void Add(String key, Int32? value)
            {
                if (value != null && value.HasValue)
                    list.Add(new KeyValuePair<String, String>(key, value.Value.ToString()));
            }

            public void Add(String key, IntPtr value)
            {
                if (value != null)
                    list.Add(new KeyValuePair<String, String>(key, value.ToString()));
            }
        }

        #endregion

        #region Interop imports and structures

        [DllImport("user32.dll", SetLastError = false)]
        internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = false)]
        internal static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, Int32 nMaxCount);

        [DllImport("user32.dll", SetLastError = false, CharSet = CharSet.Auto)]
        internal static extern uint RegisterWindowMessage(string lpString);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        internal static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out IntPtr lpdwResult);

        [DllImport("user32.dll")]
        internal static extern bool IsWindow(IntPtr hWnd);

        // [DllImport("user32.dll", SetLastError = false, CharSet = CharSet.Auto)]
        // internal static extern IntPtr GetProp(IntPtr hWnd, string lpString);

        [DllImport("kernel32.dll")]
        internal static extern uint GetCurrentProcessId();

        [Flags]
        internal enum SendMessageTimeoutFlags : uint
        {
            SMTO_NORMAL = 0x0000,
            SMTO_BLOCK = 0x0001,
            SMTO_ABORTIFHUNG = 0x0002,
            SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct COPYDATASTRUCT
        {
            public IntPtr dwData;   // DWORD
            public Int32 cbData;   // DWORD
            public IntPtr lpData;   // PVOID
        }

        private const int ERROR_TIMEOUT = 1460;

        #endregion

        #region WindowsMessage enum

        public enum WindowsMessage : uint
        {
            WM_ACTIVATE = 0x6,
            WM_ACTIVATEAPP = 0x1C,
            WM_AFXFIRST = 0x360,
            WM_AFXLAST = 0x37F,
            WM_APP = 0x8000,
            WM_ASKCBFORMATNAME = 0x30C,
            WM_CANCELJOURNAL = 0x4B,
            WM_CANCELMODE = 0x1F,
            WM_CAPTURECHANGED = 0x215,
            WM_CHANGECBCHAIN = 0x30D,
            WM_CHAR = 0x102,
            WM_CHARTOITEM = 0x2F,
            WM_CHILDACTIVATE = 0x22,
            WM_CLEAR = 0x303,
            WM_CLOSE = 0x10,
            WM_COMMAND = 0x111,
            WM_COMPACTING = 0x41,
            WM_COMPAREITEM = 0x39,
            WM_CONTEXTMENU = 0x7B,
            WM_COPY = 0x301,
            WM_COPYDATA = 0x4A,
            WM_CREATE = 0x1,
            WM_CTLCOLORBTN = 0x135,
            WM_CTLCOLORDLG = 0x136,
            WM_CTLCOLOREDIT = 0x133,
            WM_CTLCOLORLISTBOX = 0x134,
            WM_CTLCOLORMSGBOX = 0x132,
            WM_CTLCOLORSCROLLBAR = 0x137,
            WM_CTLCOLORSTATIC = 0x138,
            WM_CUT = 0x300,
            WM_DEADCHAR = 0x103,
            WM_DELETEITEM = 0x2D,
            WM_DESTROY = 0x2,
            WM_DESTROYCLIPBOARD = 0x307,
            WM_DEVICECHANGE = 0x219,
            WM_DEVMODECHANGE = 0x1B,
            WM_DISPLAYCHANGE = 0x7E,
            WM_DRAWCLIPBOARD = 0x308,
            WM_DRAWITEM = 0x2B,
            WM_DROPFILES = 0x233,
            WM_ENABLE = 0xA,
            WM_ENDSESSION = 0x16,
            WM_ENTERIDLE = 0x121,
            WM_ENTERMENULOOP = 0x211,
            WM_ENTERSIZEMOVE = 0x231,
            WM_ERASEBKGND = 0x14,
            WM_EXITMENULOOP = 0x212,
            WM_EXITSIZEMOVE = 0x232,
            WM_FONTCHANGE = 0x1D,
            WM_GETDLGCODE = 0x87,
            WM_GETFONT = 0x31,
            WM_GETHOTKEY = 0x33,
            WM_GETICON = 0x7F,
            WM_GETMINMAXINFO = 0x24,
            WM_GETOBJECT = 0x3D,
            WM_GETSYSMENU = 0x313,
            WM_GETTEXT = 0xD,
            WM_GETTEXTLENGTH = 0xE,
            WM_HANDHELDFIRST = 0x358,
            WM_HANDHELDLAST = 0x35F,
            WM_HELP = 0x53,
            WM_HOTKEY = 0x312,
            WM_HSCROLL = 0x114,
            WM_HSCROLLCLIPBOARD = 0x30E,
            WM_ICONERASEBKGND = 0x27,
            WM_IME_CHAR = 0x286,
            WM_IME_COMPOSITION = 0x10F,
            WM_IME_COMPOSITIONFULL = 0x284,
            WM_IME_CONTROL = 0x283,
            WM_IME_ENDCOMPOSITION = 0x10E,
            WM_IME_KEYDOWN = 0x290,
            WM_IME_KEYLAST = 0x10F,
            WM_IME_KEYUP = 0x291,
            WM_IME_NOTIFY = 0x282,
            WM_IME_REQUEST = 0x288,
            WM_IME_SELECT = 0x285,
            WM_IME_SETCONTEXT = 0x281,
            WM_IME_STARTCOMPOSITION = 0x10D,
            WM_INITDIALOG = 0x110,
            WM_INITMENU = 0x116,
            WM_INITMENUPOPUP = 0x117,
            WM_INPUTLANGCHANGE = 0x51,
            WM_INPUTLANGCHANGEREQUEST = 0x50,
            WM_KEYDOWN = 0x100,
            WM_KEYFIRST = 0x100,
            WM_KEYLAST = 0x108,
            WM_KEYUP = 0x101,
            WM_KILLFOCUS = 0x8,
            WM_LBUTTONDBLCLK = 0x203,
            WM_LBUTTONDOWN = 0x201,
            WM_LBUTTONUP = 0x202,
            WM_MBUTTONDBLCLK = 0x209,
            WM_MBUTTONDOWN = 0x207,
            WM_MBUTTONUP = 0x208,
            WM_MDIACTIVATE = 0x222,
            WM_MDICASCADE = 0x227,
            WM_MDICREATE = 0x220,
            WM_MDIDESTROY = 0x221,
            WM_MDIGETACTIVE = 0x229,
            WM_MDIICONARRANGE = 0x228,
            WM_MDIMAXIMIZE = 0x225,
            WM_MDINEXT = 0x224,
            WM_MDIREFRESHMENU = 0x234,
            WM_MDIRESTORE = 0x223,
            WM_MDISETMENU = 0x230,
            WM_MDITILE = 0x226,
            WM_MEASUREITEM = 0x2C,
            WM_MENUCHAR = 0x120,
            WM_MENUCOMMAND = 0x126,
            WM_MENUDRAG = 0x123,
            WM_MENUGETOBJECT = 0x124,
            WM_MENURBUTTONUP = 0x122,
            WM_MENUSELECT = 0x11F,
            WM_MOUSEACTIVATE = 0x21,
            WM_MOUSEFIRST = 0x200,
            WM_MOUSEHOVER = 0x2A1,
            WM_MOUSELAST = 0x20A,
            WM_MOUSELEAVE = 0x2A3,
            WM_MOUSEMOVE = 0x200,
            WM_MOUSEWHEEL = 0x20A,
            WM_MOVE = 0x3,
            WM_MOVING = 0x216,
            WM_NCACTIVATE = 0x86,
            WM_NCCALCSIZE = 0x83,
            WM_NCCREATE = 0x81,
            WM_NCDESTROY = 0x82,
            WM_NCHITTEST = 0x84,
            WM_NCLBUTTONDBLCLK = 0xA3,
            WM_NCLBUTTONDOWN = 0xA1,
            WM_NCLBUTTONUP = 0xA2,
            WM_NCMBUTTONDBLCLK = 0xA9,
            WM_NCMBUTTONDOWN = 0xA7,
            WM_NCMBUTTONUP = 0xA8,
            WM_NCMOUSEHOVER = 0x2A0,
            WM_NCMOUSELEAVE = 0x2A2,
            WM_NCMOUSEMOVE = 0xA0,
            WM_NCPAINT = 0x85,
            WM_NCRBUTTONDBLCLK = 0xA6,
            WM_NCRBUTTONDOWN = 0xA4,
            WM_NCRBUTTONUP = 0xA5,
            WM_NEXTDLGCTL = 0x28,
            WM_NEXTMENU = 0x213,
            WM_NOTIFY = 0x4E,
            WM_NOTIFYFORMAT = 0x55,
            WM_NULL = 0x0,
            WM_PAINT = 0xF,
            WM_PAINTCLIPBOARD = 0x309,
            WM_PAINTICON = 0x26,
            WM_PALETTECHANGED = 0x311,
            WM_PALETTEISCHANGING = 0x310,
            WM_PARENTNOTIFY = 0x210,
            WM_PASTE = 0x302,
            WM_PENWINFIRST = 0x380,
            WM_PENWINLAST = 0x38F,
            WM_POWER = 0x48,
            WM_PRINT = 0x317,
            WM_PRINTCLIENT = 0x318,
            WM_QUERYDRAGICON = 0x37,
            WM_QUERYENDSESSION = 0x11,
            WM_QUERYNEWPALETTE = 0x30F,
            WM_QUERYOPEN = 0x13,
            WM_QUERYUISTATE = 0x129,
            WM_QUEUESYNC = 0x23,
            WM_QUIT = 0x12,
            WM_RBUTTONDBLCLK = 0x206,
            WM_RBUTTONDOWN = 0x204,
            WM_RBUTTONUP = 0x205,
            WM_RENDERALLFORMATS = 0x306,
            WM_RENDERFORMAT = 0x305,
            WM_SETCURSOR = 0x20,
            WM_SETFOCUS = 0x7,
            WM_SETFONT = 0x30,
            WM_SETHOTKEY = 0x32,
            WM_SETICON = 0x80,
            WM_SETREDRAW = 0xB,
            WM_SETTEXT = 0xC,
            WM_SETTINGCHANGE = 0x1A,
            WM_SHOWWINDOW = 0x18,
            WM_SIZE = 0x5,
            WM_SIZECLIPBOARD = 0x30B,
            WM_SIZING = 0x214,
            WM_SPOOLERSTATUS = 0x2A,
            WM_STYLECHANGED = 0x7D,
            WM_STYLECHANGING = 0x7C,
            WM_SYNCPAINT = 0x88,
            WM_SYSCHAR = 0x106,
            WM_SYSCOLORCHANGE = 0x15,
            WM_SYSCOMMAND = 0x112,
            WM_SYSDEADCHAR = 0x107,
            WM_SYSKEYDOWN = 0x104,
            WM_SYSKEYUP = 0x105,
            WM_SYSTIMER = 0x118,  // undocumented, see http://support.microsoft.com/?id=108938
            WM_TCARD = 0x52,
            WM_TIMECHANGE = 0x1E,
            WM_TIMER = 0x113,
            WM_UNDO = 0x304,
            WM_UNINITMENUPOPUP = 0x125,
            WM_USER = 0x400,
            WM_USERCHANGED = 0x54,
            WM_VKEYTOITEM = 0x2E,
            WM_VSCROLL = 0x115,
            WM_VSCROLLCLIPBOARD = 0x30A,
            WM_WINDOWPOSCHANGED = 0x47,
            WM_WINDOWPOSCHANGING = 0x46,
            WM_WININICHANGE = 0x1A,
            WM_XBUTTONDBLCLK = 0x20D,
            WM_XBUTTONDOWN = 0x20B,
            WM_XBUTTONUP = 0x20C
        }

        #endregion

        public class GlobalEventArgs : EventArgs
        {
            public GlobalEvent GlobalEvent { get; set; }

            public GlobalEventArgs(GlobalEvent globalEvent)
            {
                GlobalEvent = globalEvent;
            }
        }

        public class CallbackEventArgs : EventArgs
        {
            public Int32 MessageToken { get; set; }
            public SnarlStatus SnarlEvent { get; set; }

            /// <summary>
            /// The @data member if an action callback. Menu index if popup menu.
            /// </summary>
            public UInt16 Parameter { get; set; }

            public CallbackEventArgs(SnarlStatus snarlEvent, UInt16 parameter, int msgToken)
            {
                SnarlEvent = snarlEvent;
                MessageToken = msgToken;
                Parameter = parameter;
            }
        }

        public delegate void CallbackEventHandler(SnarlInterface sender, CallbackEventArgs args);
        public event CallbackEventHandler CallbackEvent;
        public delegate void GlobalEventHandler(SnarlInterface sender, GlobalEventArgs args);
        public event GlobalEventHandler GlobalSnarlEvent;

        private SnarlCallbackNativeWindow callbackWindow = null;
        private Int32 msgReply = 0;

        public Int32 RegisterWithEvents(String signature, String title, String icon, String password, IntPtr hWndReplyTo, Int32? msgReply)
        {
            lock (instanceLock)
            {
                if (msgReply == null || msgReply.Value == 0)
                    msgReply = WM_DEFAULT_APPMSG;

                // Reuse callbackwindo as is, if DetachCallbackWindow() hasn't been called manually
                if (callbackWindow == null)
                    callbackWindow = new SnarlCallbackNativeWindow(this, hWndReplyTo);

                return Register(signature, title, icon, password, callbackWindow.Handle, msgReply.Value);
            }
        }

        public void UnregisterCallbackWindow()
        {
            lock (instanceLock)
            {
                // Release handle
                if (callbackWindow != null)
                {
                    callbackWindow.Detach();
                    callbackWindow = null;
                }
            }
        }

        // protected
        class SnarlCallbackNativeWindow : System.Windows.Forms.NativeWindow
        {
            private bool hasCreatedCallbackWindow = false;
            private UInt32 snarlGlobalMessage = 0;
            private SnarlInterface parent = null;

            internal SnarlCallbackNativeWindow(SnarlInterface parent, IntPtr windowHandle)
            {
                this.parent = parent;
                snarlGlobalMessage = SnarlInterface.Broadcast();

                if (windowHandle == IntPtr.Zero)
                {
                    hasCreatedCallbackWindow = true;

                    CreateParams cp = new CreateParams();
                    cp.Caption = GetType().FullName;
                    CreateHandle(cp);
                }
                else
                {
                    hasCreatedCallbackWindow = false;
                    AssignHandle(windowHandle);
                }
            }

            internal void Detach()
            {
                if (hasCreatedCallbackWindow)
                    DestroyHandle();
                else
                    ReleaseHandle();
            }

            protected override void WndProc(ref System.Windows.Forms.Message m)
            {
                if (m.Msg == snarlGlobalMessage)
                {
                    if (parent.GlobalSnarlEvent == null)
                        return;

                    GlobalEventArgs eventArgs = new GlobalEventArgs((SnarlInterface.GlobalEvent)(m.WParam.ToInt64() & 0xffffffff));
                    parent.GlobalSnarlEvent(parent, eventArgs);
                }
                else if (m.Msg == parent.msgReply)
                {
                    if (parent.CallbackEvent == null)
                        return;

                    UInt16 loword, hiword;
                    ConvertToUInt16(m.WParam, out loword, out hiword);
                    Int32 msgToken = m.LParam.ToInt32();

                    CallbackEventArgs eventArgs = new CallbackEventArgs((SnarlStatus)loword, hiword, msgToken);

                    parent.CallbackEvent(parent, eventArgs);
                }

                base.WndProc(ref m);
            }

            private void ConvertToUInt16(IntPtr input, out UInt16 outLow, out UInt16 outHigh)
            {
                // Assumes only 32 bit
                UInt32 tmp = (UInt32)input.ToInt64();

                outLow = (UInt16)(tmp & 0x0000ffff);
                outHigh = (UInt16)(tmp >> 16);
            }
        }
    }
}


text:
package ru.job4j.servlets;

import ru.job4j.UserStore;
import ru.job4j.models.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * The class SearchUser.
 *
 * @author Alexander Mezgin
 * @version 1.0
 * @since 24.12.2017
 */
public class SearchUser extends HttpServlet {

    /**
     * The field of type UserStore.
     */
    private final UserStore users = UserStore.getInstance();

    /**
     * Overrides method doPost.
     *
     * @param req  request.
     * @param resp response.
     * @throws ServletException ServletException.
     * @throws IOException      IOException.
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        User user = users.getUser(req.getParameter("login"));
        req.setAttribute("user", user);
        req.getServletContext().getRequestDispatcher(String.format("%s/search.jsp", req.getContextPath())).forward(req, resp);
    }
}


text:
copyright:
  years: 2015, 2017
lastupdated: "2017-01-09"

---

<!-- Attribute definitions -->
{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:codeblock: .codeblock}
{:screen: .screen}
{:pre: .pre}

#Requisitos del servicio
{: #requirements}

##Requisitos de mensajes de dispositivo MQTT

* El intermediario de mensajes MQTT debe proporcionar los mensajes de dispositivo en formato JSON en uno o varios temas MQTT.
* Los mensajes de dispositivo pueden contener cualquier serie de atributos, pero los tres atributos siguientes son siempre obligatorios:
	* Un atributo que identifica de forma exclusiva el dispositivo.
	* Un atributo que especifica la latitud de la ubicación actual del dispositivo.
	* Un atributo que especifica la longitud de la ubicación actual del dispositivo.
* Se da soporte a dos modalidades de mensajes:
	* Un mensaje MQTT puede contener un objeto JSON con información sobre un único dispositivo.
	* Un mensaje MQTT puede obtener una matriz de objetos JSON con información sobre un conjunto de dispositivos.

##Sucesos MQTT y configuración del servicio

La aplicación se suscribe a los mensajes MQTT y controla {{site.data.keyword.geospatialshort_Geospatial}} a través de su [API REST](https://console.ng.bluemix.net/apidocs/246). Las siguientes opciones están disponibles mediante las llamadas de API REST:

* Configurar e iniciar el servicio.
* Añadir y eliminar regiones geográficas que desea supervisar.
* Recuperar información sobre el estado del servicio y sobre el conjunto de regiones definidas actualmente.
* Detener el servicio.
* Reiniciar un servicio ya configurado.


text:
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]

Check if a character is alphabetical.

## Install

[npm][]:

```sh
npm install is-alphabetical
```

## Use

```js
var alphabetical = require('is-alphabetical')

alphabetical('a') // => true
alphabetical('B') // => true
alphabetical('0') // => false
alphabetical('💩') // => false
```

## API

### `alphabetical(character|code)`

Check whether the given character code (`number`), or the character code at the
first position (`string`), is alphabetical.

## Related

*   [`is-decimal`](https://github.com/wooorm/is-decimal)
*   [`is-hexadecimal`](https://github.com/wooorm/is-hexadecimal)
*   [`is-alphanumerical`](https://github.com/wooorm/is-alphanumerical)
*   [`is-whitespace-character`](https://github.com/wooorm/is-whitespace-character)
*   [`is-word-character`](https://github.com/wooorm/is-word-character)

## License

[MIT][license] © [Titus Wormer][author]

<!-- Definitions -->

[build-badge]: https://img.shields.io/travis/wooorm/is-alphabetical.svg

[build]: https://travis-ci.org/wooorm/is-alphabetical

[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/is-alphabetical.svg

[coverage]: https://codecov.io/github/wooorm/is-alphabetical

[downloads-badge]: https://img.shields.io/npm/dm/is-alphabetical.svg

[downloads]: https://www.npmjs.com/package/is-alphabetical

[size-badge]: https://img.shields.io/bundlephobia/minzip/is-alphabetical.svg

[size]: https://bundlephobia.com/result?p=is-alphabetical

[npm]: https://docs.npmjs.com/cli/install

[license]: license

[author]: https://wooorm.com


text:
"""
Creates the ReprObjType object, which enables any python object to be stored
as a string in a database.

In order for Trump to support it, reprobj.py needs to be able to run
an exec command, of the object's repr, successfully.  So, extra
import statements may be needed and added in such a way that the import
statement matches the object's repr.
"""

from sqlalchemy.types import TypeDecorator, String

# Wrap any needed third-party libraries or modules, in a try-pass statetment.
# to ensure any other users, stay sane.  Example was done with the
# datetime, which obviously all users have.

try: import datetime
except: pass

class ReprObjType(TypeDecorator):

    """
    SQLAlchemy type definition for the ReprObj implementation.
    A ReprObj is a python object that enables lazily storing
    flags into a single integer value for quick database access and use."""

    impl = String

    def __init__(self, *args, **kwargs):
        super(ReprObjType, self).__init__(*args, **kwargs)

    def process_bind_param(self, value, dialect):
        """
        When SQLAlchemy binds a ReprObjType, it converts it
        to a string for storage in the database, via the python
        repr string equivalent.
        """
        if value is not None:
            value = repr(value)
        return value

    def process_result_value(self, value, dialect):
        """
        When SQLAlchemy gets the string representation from a ReprObjType
        column, it converts it to the python equivalent via exec.
        """
        if value is not None:
            cmd = "value = {}".format(value)
            exec(cmd)
        return value

    def copy(self):
        return ReprObjType()


text:
"""
bluedaisy.bluedaisyd
~~~~~~~~~~~~~~~~~~~~

This module is responsible for daemonizing the application.

Attributes:
    PID_FILE (str): A path to the ``~/.bluedaisy/bluedaisy.pid`` file.
"""

import os

from daemonize import Daemonize

from config import Config
from server import BluetoothServer

PID_FILE = os.path.expanduser('~/.bluedaisy/bluedaisy.pid')

def run():
    """Function to be run when daemon starts."""
    while True:
        config = Config()
        server = BluetoothServer(config)
        server.receive_data()

if __name__ == '__main__':
    # create .bluedaisy directory if it does not exist
    os.makedirs(os.path.expanduser('~/.bluedaisy'), exist_ok=True)

    # create daemon
    daemon = Daemonize(app='BlueDaisy', pid=PID_FILE, action=run)
    daemon.start()


text:
set -e

echo "Starting etcd service ..."

sudo systemctl daemon-reload
sudo systemctl enable etcd.service
sudo systemctl restart etcd.service


text:
=======================================================
 django-achievements - Django App for user achievements
=======================================================

:Version: 0.0.9
:Source: http://github.com/ssaboum/django-achievements/

django-achievements is an application allowing you to handle
Achievements and link them to users.
Apart from defining these two objects the projet aims to provide
a framework allowing you to define Achievement classes and callbacks
that will be called by an Engine responsible for checking if a specific
achievement has been unlocked by a user.
You can access this engine from any part of your application and ask
it to verify if a precise achievement has been unlocked given a context.

Warning, Warning
================

This is a very young project, yet i'm using it in production,
therefore you can rely on it for being fully operational.

Using django-achievements
=========================

To enable ``django-achievements`` for your project you need to add ``achievements`` to
``INSTALLED_APPS``::

    INSTALLED_APPS += ("achievements", )

and execute the database sync command : ::

    ./manage.py syncdb

    #or if you're using south :
    ./manage.py syncdb --migrate

That's all.
If you want you can also customize the application settings these variables in your  ``settings.py``::

    ACHIEVEMENT_USE_CELERY = True

Documentation
=============

The documentation is generated using Sphinx and available on :

    http://readthedocs.org/docs/django-achievements/en/latest/

Installation
=============

This package is now uploaded on PyPi so all you need to do is to install it using :

    pip install django-achievements

License
=======

This software is licensed under the ``New BSD License``. See the ``LICENSE``
file in the top distribution directory for the full license text.

.. # vim: syntax=rst expandtab tabstop=4 shiftwidth=4 shiftround


text:
package p2;

public class Statics {
    public static final int PUB_CONST = 0;
}


text:
<?php

namespace IntegrationApi\DvlaVehicle\Controller;

use DvsaCommonApi\Controller\AbstractDvsaRestfulController;
use DvsaCommonApi\Model\ApiResponse;
use DvsaCommonApi\Service\Exception\NotFoundException;
use IntegrationApi\DvlaVehicle\Service\DvlaVehicleUpdatedService;
use Zend\View\Model\JsonModel;

/**
 * Class DvlaVehicleUpdatedController.
 */
class DvlaVehicleUpdatedController extends AbstractDvsaRestfulController
{
    private $dvlaVehicleUpdatedService;

    public function __construct(DvlaVehicleUpdatedService $dvlaVehicleUpdatedService)
    {
        $this->dvlaVehicleUpdatedService = $dvlaVehicleUpdatedService;
    }

    /**
     * @param array $data
     *
     * @return JsonModel
     *
     * @throws NotFoundException
     */
    public function create($data)
    {
        if (empty($data['vehicleId'])) {
            throw new NotFoundException('vehicleId');
        }

        $isDvlaImport = true;

        $this->dvlaVehicleUpdatedService->createReplacementCertificate($data['vehicleId'], $this->getUserId(), $isDvlaImport);

        return ApiResponse::jsonOk();
    }
}


text:
<?php
namespace Kumatch\KeyStore\S3;

use Aws\Common\Enum\Region;

class AwsRegion extends Region
{
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<base href="file:/C:/Users/PatrickF/eclipse workspaces/swt workspace/HTMLParser/.clover/report/"/>
    <link rel="stylesheet" type="text/css" href="style.css" title="Style"/>
    <link rel="stylesheet" type="text/css" href="roundedcorners.css" title="Style"/>

	       AppletTag

	       BaseHrefTag

	       CompositeTag

	       DoctypeTag

	       FormTag

	       FrameSetTag

	       FrameTag

	       HeadTag

	       ImageTag

	       JspTag

	       LabelTag

	       LinkTag

	       MetaTag

	       ObjectTag

	       OptionTag

	       ProcessingInstructionTag

	       ScriptTag

	       SelectTag

	       StyleTag

	       TableHeader

	       TableRow

	       TableTag

	       TextareaTag

	       TitleTag


text:
for i in {1..158}; do
	php runFixSemanticDomainKey.php
done


text:
"""Abstract class for unary dynamic categorical QSRs

:Author: Yiannis Gatsoulis <y.gatsoulis@leeds.ac.uk>
:Organization: University of Leeds
"""

from __future__ import print_function, division
import numpy as np
from qsr_arg_relations_abstractclass import QSR_Arg_Relations_Abstractclass
from qsrlib_io.world_qsr_trace import *

class QSR_Arg_Relations_Distance(QSR_Arg_Relations_Abstractclass):
    def __init__(self, config=None):
        super(QSR_Arg_Relations_Distance, self).__init__()
        self.qsr_type = "arg_relations_distance"
        self.qsr_keys = "argd"
        if config:
            self.set_from_config_file(config)

    def custom_set_from_config_file(self, document):
        try:
            relations_and_values = document["arg_relations_distance"]["relations_and_values"]
        except:
            print("ERROR (qsr_arg_relations_distance.py/custom_set_from_config_file):"
                  "'arg_relations_distance' or 'relations_and_values' not found in config file")
            self.qsr_relations_and_values = None
            self.all_possible_relations = None
            self.all_possible_values = None
            raise LookupError
        self.set_qsr_relations_and_values(qsr_relations_and_values=relations_and_values)

    def custom_help(self):
        """Write your own help message function"""
        print("")

    def custom_checks(self, input_data):
        """Write your own custom checks on top of the default ones

        :return: error code, error message (integer, string), use 10 and above for error code as 1-9 are reserved by system
        """
        return 0, ""

    def custom_checks_for_qsrs_for(self, qsrs_for, error_found):
        """qsrs_for must be tuples of two objects.

        :param qsrs_for: list of strings and/or tuples for which QSRs will be computed
        :param error_found: if an error was found in the qsrs_for that violates the QSR rules
        :return: qsrs_for, error_found
        """
        for p in list(qsrs_for):
            if (type(p) is not tuple) and (type(p) is not list) and (len(p) != 2):
                qsrs_for.remove(p)
                error_found = True
        return qsrs_for, error_found

    def make(self, *args, **kwargs):
        """Make the QSRs

        :param args: not used at the moment
        :param kwargs:
                        - input_data: World_Trace
        :return: World_QSR_Trace
        """
        # optional set from ini
        try:
            if kwargs["config"]:
                self.set_from_config_file(kwargs["config"])
        except:
            pass
        # optional direct set, deprecated way
        try:
            if kwargs["qsr_relations_and_values"]:
                print("Warning: This feature is deprecated, use dynamic_args on your request message instead")
                self.set_qsr_relations_and_values(qsr_relations_and_values=kwargs["qsr_relations_and_values"])
        except:
            pass
        # optional direct set
        try:
            if kwargs["dynamic_args"]["qsr_relations_and_values"]:
                self.set_qsr_relations_and_values(qsr_relations_and_values=kwargs["dynamic_args"]["qsr_relations_and_values"])
        except:
            pass
        # print(self.qsr_relations_and_values)  # dbg
        if not self.qsr_relations_and_values:
            raise ValueError("qsr_relations_and_values is uninitialized,\n"
                             "use dynamic_args={'qsr_relations_and_values': <your dictionary of relations and values>"
                             "in the QSRlib_Request_Message")
        input_data = kwargs["input_data"]
        include_missing_data = kwargs["include_missing_data"]
        ret = World_QSR_Trace(qsr_type=self.qsr_type)
        for t in input_data.get_sorted_timestamps():
            world_state = input_data.trace[t]
            timestamp = world_state.timestamp
            if kwargs["qsrs_for"]:
                # print(kwargs["qsrs_for"])
                qsrs_for, error_found = self.check_qsrs_for_data_exist(world_state.objects.keys(), kwargs["qsrs_for"])
            else:
                qsrs_for = self.qsrs_for_default(world_state.objects.keys())
            if qsrs_for:
                for p in qsrs_for:
                    between = str(p[0]) + "," + str(p[1])
                    objs = (world_state.objects[p[0]], world_state.objects[p[1]])
                    qsr = QSR(timestamp=timestamp, between=between,
                              qsr=self.handle_future(kwargs["future"], self.__compute_qsr(objs), self.qsr_keys))
                    ret.add_qsr(qsr, timestamp)
            else:
                if include_missing_data:
                    ret.add_empty_world_qsr_state(timestamp)
        return ret

    def __compute_qsr(self, objs):
        if np.isnan(objs[0].z) or np.isnan(objs[1].z):
            d = np.sqrt(np.square(objs[0].x - objs[1].x) + np.square(objs[0].y - objs[1].y))
        else:
            d = np.sqrt(np.square(objs[0].x - objs[1].x) + np.square(objs[0].y - objs[1].y) + np.square(objs[0].z - objs[1].z))
        for thres, relation in zip(self.all_possible_values, self.all_possible_relations):
            if d <= thres:
                return relation
        return self.all_possible_relations[-1]

    def qsrs_for_default(self, objects_names):
        if len(objects_names) < 2:
            return []
        ret = []
        for i in sorted(objects_names):
            for j in objects_names:
                if i != j and (j, i) not in ret:
                    ret.append((i, j))
        return ret


text:
/*
 * This file is part of WebLookAndFeel library.
 *
 * WebLookAndFeel library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * WebLookAndFeel library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with WebLookAndFeel library.  If not, see <http://www.gnu.org/licenses/>.
 */

package web.laf.lite.layout;

import javax.swing.plaf.TextUI;
import javax.swing.text.JTextComponent;

import web.laf.lite.ui.TextFieldUI;

import java.awt.*;

/**
 * User: mgarin Date: 14.12.12 Time: 16:56
 */

public class TextComponentLayout extends AbstractLayoutManager
{
    // Positions component at the leading side of the field
    public static final String LEADING = "LEADING";
    // Positions component at the trailing side of the field
    public static final String TRAILING = "TRAILING";

    // Empty insets
    private static final Insets emptyInsets = new Insets ( 0, 0, 0, 0 );

    // todo Make weak references
    // Saved layout constraints
    private ValuesTable<Component, String> constraints = new ValuesTable<Component, String> ();

    // Text component
    private JTextComponent textComponent;

    public TextComponentLayout ( JTextComponent textComponent )
    {
        super ();
        this.textComponent = textComponent;
    }

    /**
     * Standard LayoutManager methods
     */

    /**
     * {@inheritDoc}
     */
    @Override
    public void addComponent ( Component component, Object constraints )
    {
        String value = ( String ) constraints;
        if ( value == null || !value.equals ( LEADING ) && !value.equals ( TRAILING ) )
        {
            throw new IllegalArgumentException ( "Cannot add to layout: constraint must be 'LEADING' or 'TRAILING' string" );
        }
        this.constraints.put ( component, value );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void removeComponent ( Component component )
    {
        this.constraints.remove ( component );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Dimension preferredLayoutSize ( Container parent )
    {
        Insets b = getInsets ( parent );
        Dimension l = constraints.containsValue ( LEADING ) ? constraints.getKey ( LEADING ).getPreferredSize () : new Dimension ();
        Dimension t = constraints.containsValue ( TRAILING ) ? constraints.getKey ( TRAILING ).getPreferredSize () : new Dimension ();
        return new Dimension ( b.left + l.width + t.width + b.right, b.top + Math.max ( l.height, t.height ) + b.bottom );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void layoutContainer ( Container parent )
    {
        boolean ltr = parent.getComponentOrientation ().isLeftToRight ();
        Insets b = getInsets ( parent );
        if ( constraints.containsValue ( LEADING ) )
        {
            Component leading = constraints.getKey ( LEADING );
            int w = leading.getPreferredSize ().width;
            if ( ltr )
            {
                leading.setBounds ( b.left - w, b.top, w, parent.getHeight () - b.top - b.bottom );
            }
            else
            {
                leading.setBounds ( parent.getWidth () - b.right, b.top, w, parent.getHeight () - b.top - b.bottom );
            }
        }
        if ( constraints.containsValue ( TRAILING ) )
        {
            Component trailing = constraints.getKey ( TRAILING );
            int w = trailing.getPreferredSize ().width;
            if ( ltr )
            {
                trailing.setBounds ( parent.getWidth () - b.right, b.top, w, parent.getHeight () - b.top - b.bottom );
            }
            else
            {
                trailing.setBounds ( b.left - w, b.top, w, parent.getHeight () - b.top - b.bottom );
            }
        }
    }

    /**
     * Actual border
     */

    private Insets getInsets ( Container parent )
    {
        Insets b = parent.getInsets ();
        Insets fm = getFieldMargin ();
        boolean ltr = parent.getComponentOrientation ().isLeftToRight ();
        return new Insets ( b.top - fm.top, b.left - ( ltr ? fm.left : fm.right ), b.bottom - fm.bottom,
                b.right - ( ltr ? fm.right : fm.left ) );
    }

    private Insets getFieldMargin ()
    {
        TextUI ui = textComponent.getUI ();
        if ( ui instanceof TextFieldUI )
        {
            return ( ( TextFieldUI ) ui ).getFieldMargin ();
        }
        else
        {
            return emptyInsets;
        }
    }
}


text:
package com.javapapers.java.gcm;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/GCMNotification")
public class GCMNotification extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// Put your Google API Server Key here
	private static final String GOOGLE_SERVER_KEY = "AIzaSyC3hK5uFiFIaz7VQ8e4RC_a59y32_SGUwc";
	static final String REGISTER_NAME = "name";
	static final String MESSAGE_ACTIVITY = "activity";
        static final String MESSAGE_PLACE = "place";
        static final String DATE = "date";
        static final String TIME = "time";
	static final String TO_NAME = "toName";
	static final String REG_ID_STORE = "GCMRegId.txt";

	public GCMNotification() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String action = request.getParameter("action");

		if ("shareRegId".equalsIgnoreCase(action)) {

			writeToFile(request.getParameter("name"),
					request.getParameter("regId"));
			request.setAttribute("pushStatus",
					"GCM Name and corresponding RegId Received.");
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);

		} else if ("sendMessage".equalsIgnoreCase(action)) {

			try {
				String fromName = request.getParameter(REGISTER_NAME);
				String toName = request.getParameter(TO_NAME);
				String userActivity = request.getParameter(MESSAGE_ACTIVITY);
                                String userPlace = request.getParameter(MESSAGE_PLACE);
                                String userDate = request.getParameter(DATE);
                                String userTime = request.getParameter(TIME);
				Sender sender = new Sender(GOOGLE_SERVER_KEY);
				Message message = new Message.Builder().timeToLive(30)
						.delayWhileIdle(true).addData(MESSAGE_ACTIVITY, userActivity)
                                                .addData(MESSAGE_PLACE, userPlace)
						.addData(REGISTER_NAME, fromName)
                                                .addData(DATE, userDate)
                                                .addData(TIME, userTime).build();
				Map<String, String> regIdMap = readFromFile();
				String regId = regIdMap.get(toName);
				Result result = sender.send(message, regId, 1);
				request.setAttribute("pushStatus", result.toString());
			} catch (IOException ioe) {
				ioe.printStackTrace();
				request.setAttribute("pushStatus",
						"RegId required: " + ioe.toString());
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("pushStatus", e.toString());
			}
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);
		} else if ("multicast".equalsIgnoreCase(action)) {

			try {
				String fromName = request.getParameter(REGISTER_NAME);
				String userMessage = request.getParameter(MESSAGE_ACTIVITY);
				Sender sender = new Sender(GOOGLE_SERVER_KEY);
				Message message = new Message.Builder().timeToLive(30)
						.delayWhileIdle(true).addData(MESSAGE_ACTIVITY, userMessage)
						.addData(REGISTER_NAME, fromName).build();
				Map<String, String> regIdMap = readFromFile();

				List<String> regIdList = new ArrayList<String>();

				for (Entry<String, String> entry : regIdMap.entrySet()) {
					regIdList.add(entry.getValue());
				}

				MulticastResult multiResult = sender.send(message, regIdList, 1);
				request.setAttribute("pushStatus", multiResult.toString());
			} catch (IOException ioe) {
				ioe.printStackTrace();
				request.setAttribute("pushStatus",
						"RegId required: " + ioe.toString());
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("pushStatus", e.toString());
			}
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);
		}
	}

	private void writeToFile(String name, String regId) throws IOException {
		Map<String, String> regIdMap = readFromFile();
		regIdMap.put(name, regId);
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
				REG_ID_STORE, false)));
		for (Map.Entry<String, String> entry : regIdMap.entrySet()) {
			out.println(entry.getKey() + "," + entry.getValue());
		}
		out.println(name + "," + regId);
		out.close();

	}

	private Map<String, String> readFromFile() throws IOException {
                File f = new File("GCMRegId.txt");
                if(!f.exists()){
                PrintWriter writer = new PrintWriter("GCMRegId.txt", "UTF-8");
                }
		BufferedReader br = new BufferedReader(new FileReader(REG_ID_STORE));
		String regIdLine = "";
		Map<String, String> regIdMap = new HashMap<String, String>();
		while ((regIdLine = br.readLine()) != null ) {
			String[] regArr = regIdLine.split(",");
                        if(!regArr[0].equalsIgnoreCase("null")){
			regIdMap.put(regArr[0], regArr[1]);
                        }
		}
		br.close();
		return regIdMap;
	}
}


text:
package org.tigris.subversion.svnclientadapter.basictests;

import junit.framework.TestSuite;

public class SVNCmdLineTests extends SVNBasicTestsSuite {

    public SVNCmdLineTests(String name) {
        super(name);
    }

    public static TestSuite suite() {
        System.setProperty("test.clientType","commandline");

        TestSuite testSuite = new SVNCmdLineTests("Test group");
        addTestsToSuite(testSuite);
        return testSuite;
    }

}


text:
package OptimizationTests.ShortLeafMethodsInlining.InvokeStatic_const_4_002;
class Main {
    final static int iterations = 10;

    public static float simple_method() {
        float   l7;
        l7 = 0.0f;
        return l7;
    }

    public static void main(String[] args) {
        float workJ = Float.MIN_VALUE;

        System.out.println("Initial workJ value is " + workJ);

        for(int i = 0; i < iterations; i++) {
            workJ = simple_method() + workJ;
        }

        System.out.println("Final workJ value is " + workJ);
    }
}


text: cd /var/lib/app && forever start -c "npm start" . 2> error-start.txt


text:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <gradient
        android:angle="135"
        android:centerColor="#4fbbc9"
        android:endColor="#4792ab"
        android:startColor="#33acb9"
        android:type="linear"/>
</shape>


text:
import Network
import System.Environment
import System.IO
import System.Directory
import Control.Concurrent
import Data.List
import qualified Data.ByteString.Lazy as BL

main :: IO ()
main = withSocketsDo $ do
  args <- getArgs
  let port = fromIntegral (read $ head args :: Int)
  sock <- listenOn $ PortNumber port
  putStrLn $ "Listening on " ++ (head args)
  sockHandler sock

sockHandler :: Socket -> IO ()
sockHandler sock = do
  (handle, _, _) <- accept sock
  hSetBuffering handle NoBuffering
  forkIO $ httpHandler handle
  sockHandler sock

httpHandler handle = do
  line <- hGetLine handle
  let httpMethod = head $ words line
  let resource = head $ tail $ words line
  case httpMethod of
    "GET" -> serveFile resource handle
    _     -> serve405 handle

serve405 handle = do
  hPutStrLn handle "HTTP/1.1 405 Method Not Allowed"
  hPutStrLn handle "Date: Thu, 1 Jan 1970 00:00:01 GMT"
  hPutStrLn handle "Content-Type: text/plain"
  hPutStrLn handle ""
  hPutStrLn handle "This server supports only GET requests"
  hClose handle

serveFile relativePath handle =
  getFilePath relativePath >>= \filePath -> serveBinaryFile filePath handle

serveBinaryFile filePath handle =
  BL.readFile filePath >>=
    \resourceContent -> serve200 (resolveContentType filePath) resourceContent handle

serve200 contentType resourceContent handle = do
  hPutStrLn handle "HTTP/1.1 200 OK"
  hPutStrLn handle "Date: Thu, 1 Jan 1970 00:00:01 GMT"
  hPutStrLn handle ("Content-Type: " ++ contentType)
  hPutStrLn handle ""
  BL.hPut handle resourceContent
  hClose handle

getFilePath relativePath = do
  absolutePath <- fmap (++ relativePath) getCurrentDirectory
  return $ absolutePath ++ indexHtmlIfNeeded
  where
    endsWithSlash = last relativePath == '/'
    indexHtmlIfNeeded = if endsWithSlash then "index.html" else ""

resolveContentType filePath =
  case suffix of
    "html" -> "text/html"
    "png"  -> "image/png"
    "jpg"  -> "image/jpg"
    "jpeg" -> "image/jpeg"
    "gif"  -> "image/gif"
    "css"  -> "text/css"
    _      -> "text/plain"
    where
      suffix = reverse $ takeUntilDot $ reverse filePath
      takeUntilDot str = takeWhile isDot str
      isDot c = c /= '.'


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Example Page</title>
  <link rel="stylesheet" href="./CSS/style.css" />

  <script src="./JS/ServiceAPI/moduleHelper.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <script src="./JS/ServiceAPI/b64.js"></script>
  <script src="./JS/ServiceAPI/serviceAPI.js"></script>

  <script src="./JS/example.js"></script>
</head>
<body>
  <div id="main">

  </div>
</body>
</html>