text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>V-Index</title>
<meta name="date" content="2014-04-28">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N O P Q R S T U V W X

V

VALUE_FIELD_NUMBER - Static variable in class protobuf.SimpleStringProtos.SimpleString

valueOf(String) - Static method in enum utils.RuntimeFields.modes

Returns the enum constant of this type with the specified name.

values() - Static method in enum utils.RuntimeFields.modes

Returns an array containing the constants of this enum type, in
the order they are declared.

venicehub - package venicehub

VeniceHub - Class in venicehub

Contains main.

VeniceHub(String[]) - Constructor for class venicehub.VeniceHub

Constructor of VeniceHub.

VeniceReader - Class in venicehub

Reads data from source.

VeniceReader() - Constructor for class venicehub.VeniceReader

Constructor.

VeniceWriter - Class in venicehub

Abstract class for writing data from TTEQueue to a target.

VeniceWriter() - Constructor for class venicehub.VeniceWriter

Constructor.

A B C D E F G H I L M N O P Q R S T U V W X

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
#if !defined(_COMMANDS)
#define _COMMANDS

#include "token.h"

extern token_t* command(token_t* args[], int numTokens);

#endif


text:
package com.github.jvanhie.discogsscrobbler;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.github.jvanhie.discogsscrobbler.util.Discogs;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class DiscogsLoginActivity extends ActionBarActivity {

    private Discogs mDiscogs;
    private WebView mWebView;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discogs_login);
        mWebView = (WebView) findViewById(R.id.webView);
        mDiscogs = Discogs.getInstance(this);
        //clear cookies, we don't want them -> security!
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        //set settings, js support and not storing form data for security
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSaveFormData(false);
        new DiscogsAuthTask().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.discogs_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Intent settingsIntent = new Intent(this, SettingsActivity.class);
            startActivity(settingsIntent);
        }
        return super.onOptionsItemSelected(item);
    }

    private class DiscogsAuthTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            return mDiscogs.getOAuthURL();
        }

        @Override
        protected void onPostExecute(String authURL) {
            if(authURL == null) {
                //the discogs oauth service was down, stop activity
                Toast.makeText(DiscogsLoginActivity.this, getString(R.string.oauth_error), Toast.LENGTH_SHORT).show();
                finish();
            }
            mWebView.setWebViewClient(new WebViewClient() {
                private ProgressBar progressBar = (ProgressBar)findViewById(R.id.webViewProgressBar);

                @Override
                public void onPageFinished(WebView view, String url)
                {
                    mWebView.loadUrl("javascript:(function() { " +
                            "document.getElementById('site_headers_super_wrap').style.display='none'; " +
                            "})()");
                    progressBar.setVisibility(View.INVISIBLE);
                    super.onPageFinished(view, url);

                }

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);

                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    super.shouldOverrideUrlLoading(view, url);

                    if (url.startsWith("oauth")) {
                        final String url1 = url;
                        Thread t1 = new Thread() {
                            public void run() {
                                //decode URL in case it contains + ? = htmlencoded
                                String decodedUrl = url1;
                                try {
                                    decodedUrl = URLDecoder.decode(decodedUrl, "UTF-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                Uri uri = Uri.parse(decodedUrl);
                                if(uri.getQueryParameter("denied") != null) {
                                    //user has cancelled the auth, finish activity
                                    finish();
                                }
                                String verifier = uri.getQueryParameter("oauth_verifier");
                                mDiscogs.setAccessToken(verifier);

                            }
                        };
                        t1.start();
                        return true;
                    }

                    return false;
                }
            });
            mWebView.loadUrl(authURL);
        }
    }
}


text:
		Resize

	<form id='adResized'>

		<input type="number" name='width' required/>Width (px):
		Height (px): <input name='height' type="number" required/>
		Close Position: <select name='customClosePosition'>
			<option>top-left</option>
			<option selected>top-right</option>
			<option>center</option>
			<option>bottom-left</option>
			<option>bottom-right</option>
			<option>top-center</option>
			<option>bottom-center</option>
		</select>
		Offset X (px): <input name='offsetX' type="number" required/>
		Offset Y (px): <input name='offsetY' type="number" required/>
		Allow Offscreen: <input name='allowOffscreen' type="checkbox" />

		Resize
		Close
	</form>


text: java -jar target/PriceBasket.jar $@


text:
<?php

namespace Brianwalden\SAS\Models;

class ProvinceAttr extends BaseAttr
{
    const BASE_TABLE = 'province';
}


text:
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#ifndef OPENTITAN_HW_IP_PRIM_DV_PRIM_RAM_SCR_CPP_SCRAMBLE_MODEL_H_
#define OPENTITAN_HW_IP_PRIM_DV_PRIM_RAM_SCR_CPP_SCRAMBLE_MODEL_H_

#include <stdint.h>
#include <vector>

const uint32_t kPrinceWidth = 64;
const uint32_t kPrinceWidthByte = kPrinceWidth / 8;

// C++ model of memory scrambling. All byte vectors are in little endian byte
// order (least significant byte at index 0).

/** Scramble an address to give the physical address used to access the
 * scrambled memory. Return vector of scrambled address bytes
 *
 * @param addr_in      Byte vector of address
 * @param addr_width   Width of the address in bits
 * @param nonce        Byte vector of scrambling nonce
 * @param nonce_width  Width of scramble nonce in bits
 * @return Byte vector with scrambled address
 */
std::vector<uint8_t> scramble_addr(const std::vector<uint8_t> &addr_in,
                                   uint32_t addr_width,
                                   const std::vector<uint8_t> &nonce,
                                   uint32_t nonce_width);

/** Decrypt scrambled data
 * @param data_in          Byte vector of data to decrypt
 * @param data_width       Width of data in bits
 * @param subst_perm_width Width over which the substitution/permutation network
 *                         is applied (DiffWidth parameter on prim_ram_1p_scr)
 * @param addr             Byte vector of data address
 * @param addr_width       Width of the address in bits
 * @param nonce            Byte vector of scrambling nonce
 * @param key              Byte vector of scrambling key
 * @param repeat_keystream Repeat the keystream of one single PRINCE instance if
 *                         set to true. Otherwise multiple PRINCE instances are
 *                         used.
 * @return Byte vector with decrypted data
 */
std::vector<uint8_t> scramble_decrypt_data(
    const std::vector<uint8_t> &data_in, uint32_t data_width,
    uint32_t subst_perm_width, const std::vector<uint8_t> &addr,
    uint32_t addr_width, const std::vector<uint8_t> &nonce,
    const std::vector<uint8_t> &key, bool repeat_keystream);

/** Encrypt scrambled data
 * @param data_in          Byte vector of data to encrypt
 * @param data_width       Width of data in bits
 * @param subst_perm_width Width over which the substitution/permutation network
 *                         is applied (DiffWidth parameter on prim_ram_1p_scr)
 * @param addr             Byte vector of data address
 * @param addr_width       Width of the address in bits
 * @param nonce            Byte vector of scrambling nonce
 * @param key              Byte vector of scrambling key
 * @param repeat_keystream Repeat the keystream of one single PRINCE instance if
 *                         set to true. Otherwise multiple PRINCE instances are
 *                         used.
 * @return Byte vector with encrypted data
 */
std::vector<uint8_t> scramble_encrypt_data(
    const std::vector<uint8_t> &data_in, uint32_t data_width,
    uint32_t subst_perm_width, const std::vector<uint8_t> &addr,
    uint32_t addr_width, const std::vector<uint8_t> &nonce,
    const std::vector<uint8_t> &key, bool repeat_keystream);

#endif  // OPENTITAN_HW_IP_PRIM_DV_PRIM_RAM_SCR_CPP_SCRAMBLE_MODEL_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!DOCTYPE resume PUBLIC "-//Sean Kelly//DTD Resume 1.5.1//EN"
  "http://xmlresume.sourceforge.net/dtd/resume.dtd">
<resume>
  <header>
    <name>
      <firstname>Jane</firstname>
      <surname>Blogs</surname>
    </name>
  </header>
  <skillarea>
    <title>Professional Skills</title>
    <skillset>
      <title>Technical Author</title>
      <skill level="Advanced">Developer Manuals</skill>
      <skill level="Advanced">User Manuals</skill>
    </skillset>
    <skillset>
      <title>Programming</title>
      <skill level="Advanced">Java</skill>
      <skill level="Advanced">XML and related standards</skill>
      <skill level="Advanced">Apache Forrest</skill>
      <skill level="Advanced">Apache Cocoon</skill>
    </skillset>
  </skillarea>
</resume>


text:
package it.cavallium.warppi.boot;

import java.util.Arrays;
import java.util.concurrent.Future;

import it.cavallium.warppi.WarpPI;
import it.cavallium.warppi.Platform;
import it.cavallium.warppi.gui.CalculatorHUD;
import it.cavallium.warppi.gui.screens.LoadingScreen;
import it.cavallium.warppi.math.rules.RulesManager;

public class Boot {

	public static void boot(final Platform platform, final String[] args) throws Exception {
		WarpPI.start(
				platform,
				new LoadingScreen(),
				new CalculatorHUD(),
				Boot.parseStartupArguments(args),
				Boot::loadCalculator);
	}

	private static void loadCalculator() throws Exception {
		WarpPI.INSTANCE.getHardwareDevice().getDisplayManager().setBrightness(0.2f);
		//TODO: plugins system: PluginsManager.initialize();
		RulesManager.initialize();
		RulesManager.warmUp();
	}

	public static StartupArguments parseStartupArguments(final String[] a) {
		final StartupArgumentsImpl args = new StartupArgumentsImpl();
		Arrays.asList(a).stream().parallel().filter((x) -> x != null).map(String::toLowerCase).forEach(arg -> Boot.parseArgument(args, arg));
		return args;
	}

	public static void parseArgument(final StartupArgumentsImpl args, final String arg) {
		switch (arg) {
			case "-zoomed":
				args.setZoomed(true);
				break;
			case "-verbose":
				args.setVerboseLoggingEnabled(true);
				break;
			case "-noraspi":
				args.setRaspberryModeAllowed(false);
				break;
			case "nogui":
				args.setNoGUIEngineForced(true);
				break;
			case "ms-dos":
				args.setMSDOSModeEnabled(true);
				break;
			case "html":
				args.setHTMLEngineForced(true);
				break;
			case "gpu":
				args.setGPUEngineForced(true);
				break;
			case "cpu":
				args.setCPUEngineForced(true);
				break;
			case "framebuffer":
				args.setFrameBufferEngineForced(true);
				break;
			case "-debug":
				args.setDebugEnabled(true);
				break;
			case "-uncached":
				args.setUncached(true);
				break;
			default:
				// Not using ConsoleUtils because it isn't initialized at this point.
				System.out.println("Unrecognized argument " + arg);
				break;
		}
	}
}


text:
All calculators must implement `Support\CalculatorInterface`.

Aim for 100% line coverage in tests. If you can't reach a line in a test, why
have the line at all?

## Testing

We use composer to set up phpunit and autoloading.

```
composer install
```

The test script is also defined in composer.

```
composer test
```

The test script includes code coverage report which relies on xdebug. If you
don't have xdebug, you can run the tests directly.

```
vendor/bin/phpunit
```

## TODO

Any improvements will be seriously considered for merging into the package.

Well thought out improvements to documentation would be greatly appreciated.

Additional editions for any of the calculators will be accepted as long as
those are actual scoring systems used somewhere.

Regarding inclusion of additional calculators — we will have to weight
relevance against the burden of maintenance.


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#define EIGEN_NO_STATIC_ASSERT

#include "main.h"

template<typename MatrixType> void adjoint(const MatrixType& m)
{
  /* this test covers the following files:
     Transpose.h Conjugate.h Dot.h
  */
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;
  typedef typename NumTraits<Scalar>::Real RealScalar;
  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;

  Index rows = m.rows();
  Index cols = m.cols();

  MatrixType m1 = MatrixType::Random(rows, cols),
             m2 = MatrixType::Random(rows, cols),
             m3(rows, cols),
             mzero = MatrixType::Zero(rows, cols),
             identity = SquareMatrixType::Identity(rows, rows),
             square = SquareMatrixType::Random(rows, rows);
  VectorType v1 = VectorType::Random(rows),
             v2 = VectorType::Random(rows),
             v3 = VectorType::Random(rows),
             vzero = VectorType::Zero(rows);

  Scalar s1 = internal::random<Scalar>(),
         s2 = internal::random<Scalar>();

  // check basic compatibility of adjoint, transpose, conjugate
  VERIFY_IS_APPROX(m1.transpose().conjugate().adjoint(),    m1);
  VERIFY_IS_APPROX(m1.adjoint().conjugate().transpose(),    m1);

  // check multiplicative behavior
  VERIFY_IS_APPROX((m1.adjoint() * m2).adjoint(),           m2.adjoint() * m1);
  VERIFY_IS_APPROX((s1 * m1).adjoint(),                     internal::conj(s1) * m1.adjoint());

  // check basic properties of dot, norm, norm2
  typedef typename NumTraits<Scalar>::Real RealScalar;

  RealScalar ref = NumTraits<Scalar>::IsInteger ? 0 : std::max((s1 * v1 + s2 * v2).norm(),v3.norm());
  VERIFY(test_isApproxWithRef((s1 * v1 + s2 * v2).dot(v3),     internal::conj(s1) * v1.dot(v3) + internal::conj(s2) * v2.dot(v3), ref));
  VERIFY(test_isApproxWithRef(v3.dot(s1 * v1 + s2 * v2),       s1*v3.dot(v1)+s2*v3.dot(v2), ref));
  VERIFY_IS_APPROX(internal::conj(v1.dot(v2)),               v2.dot(v1));
  VERIFY_IS_APPROX(internal::real(v1.dot(v1)),                v1.squaredNorm());
  if(!NumTraits<Scalar>::IsInteger)
    VERIFY_IS_APPROX(v1.squaredNorm(),                v1.norm() * v1.norm());
  VERIFY_IS_MUCH_SMALLER_THAN(internal::abs(vzero.dot(v1)),  static_cast<RealScalar>(1));

  // check compatibility of dot and adjoint

  ref = NumTraits<Scalar>::IsInteger ? 0 : std::max(std::max(v1.norm(),v2.norm()),std::max((square * v2).norm(),(square.adjoint() * v1).norm()));
  VERIFY(test_isApproxWithRef(v1.dot(square * v2), (square.adjoint() * v1).dot(v2), ref));

  // like in testBasicStuff, test operator() to check const-qualification
  Index r = internal::random<Index>(0, rows-1),
      c = internal::random<Index>(0, cols-1);
  VERIFY_IS_APPROX(m1.conjugate()(r,c), internal::conj(m1(r,c)));
  VERIFY_IS_APPROX(m1.adjoint()(c,r), internal::conj(m1(r,c)));

  if(!NumTraits<Scalar>::IsInteger)
  {
    // check that Random().normalized() works: tricky as the random xpr must be evaluated by
    // normalized() in order to produce a consistent result.
    VERIFY_IS_APPROX(VectorType::Random(rows).normalized().norm(), RealScalar(1));
  }

  // check inplace transpose
  m3 = m1;
  m3.transposeInPlace();
  VERIFY_IS_APPROX(m3,m1.transpose());
  m3.transposeInPlace();
  VERIFY_IS_APPROX(m3,m1);

  // check inplace adjoint
  m3 = m1;
  m3.adjointInPlace();
  VERIFY_IS_APPROX(m3,m1.adjoint());
  m3.transposeInPlace();
  VERIFY_IS_APPROX(m3,m1.conjugate());

  // check mixed dot product
  typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, 1> RealVectorType;
  RealVectorType rv1 = RealVectorType::Random(rows);
  VERIFY_IS_APPROX(v1.dot(rv1.template cast<Scalar>()), v1.dot(rv1));
  VERIFY_IS_APPROX(rv1.template cast<Scalar>().dot(v1), rv1.dot(v1));
}

void test_adjoint()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( adjoint(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( adjoint(Matrix3d()) );
    CALL_SUBTEST_3( adjoint(Matrix4f()) );
    CALL_SUBTEST_4( adjoint(MatrixXcf(internal::random<int>(1,50), internal::random<int>(1,50))) );
    CALL_SUBTEST_5( adjoint(MatrixXi(internal::random<int>(1,50), internal::random<int>(1,50))) );
    CALL_SUBTEST_6( adjoint(MatrixXf(internal::random<int>(1,50), internal::random<int>(1,50))) );
  }
  // test a large matrix only once
  CALL_SUBTEST_7( adjoint(Matrix<float, 100, 100>()) );

#ifdef EIGEN_TEST_PART_4
  {
    MatrixXcf a(10,10), b(10,10);
    VERIFY_RAISES_ASSERT(a = a.transpose());
    VERIFY_RAISES_ASSERT(a = a.transpose() + b);
    VERIFY_RAISES_ASSERT(a = b + a.transpose());
    VERIFY_RAISES_ASSERT(a = a.conjugate().transpose());
    VERIFY_RAISES_ASSERT(a = a.adjoint());
    VERIFY_RAISES_ASSERT(a = a.adjoint() + b);
    VERIFY_RAISES_ASSERT(a = b + a.adjoint());

    // no assertion should be triggered for these cases:
    a.transpose() = a.transpose();
    a.transpose() += a.transpose();
    a.transpose() += a.transpose() + b;
    a.transpose() = a.adjoint();
    a.transpose() += a.adjoint();
    a.transpose() += a.adjoint() + b;
  }
#endif
}


text:
/*
 * Wacom-related stuff for the USB-side interface
 *
 */
#include "featureinclusion.h"

#include "usb_util.h"
#include "extdata.h"
#include "console.h"
#include "wacom_usb.h"
#include "pen_event.h"
#include "pen_data_transform.h"
#include "strings.h"
#include "debugproc.h"
#include "led.h"

#define WACOM_PEN_ENDPOINT	1
#define WACOM_INTUOS5_PEN_ENDPOINT 3

namespace WacomUsb
{
	static uint8_t	usbProtocol;

	void init()
	{
		usbProtocol = extdata_getValue8(EXTDATA_USB_PROTOCOL);
	}

#ifdef USB_PROTOCOL_IV_SUPPORT
	//-----------------------------------------------------------------
	// USB Protocol IV (4)
	//-----------------------------------------------------------------

	struct protocol4_struct
	{
		union
		{
			uint8_t buffer[8];
			struct
			{
				uint8_t hid_identifier; // 0x02
				struct
				{
					unsigned touch:1;   // bit 0 - pen touches the tablet
					unsigned button0:1; // bit 1 - first button on the pen
					unsigned button1:1; // bit 2 - second button on the pen
					unsigned reserved:1;// bit 3 - appears to be always 0
					unsigned inrange:1; // bit 4 - like 'proximity' but for a greater distance.
							    // 		mouse is not moving in Windows when in that range
							    // 		but x/y coordinates are being sent.
					unsigned eraser:1;  // bit 5 - eraser tool
					unsigned is_mouse:1;// bit 6 - 0=pen, 1=mouse

					unsigned proximity:1;//bit 7 - pen in close proximity, moves the mouse
				};
				uint16_t x;
				uint16_t y;
				unsigned pressure:9;
				unsigned zero:7;	// 0
			};
		};
	} protocol4_packet;

	void send_protocol4_packet(Pen::PenEvent& penEvent)
	{
		bool shouldfill = false;
		// copy event for direct access (TODO: does that make a difference?)

		protocol4_packet.hid_identifier = 0x02;

		protocol4_packet.reserved = 0;
		protocol4_packet.is_mouse = penEvent.is_mouse;
		protocol4_packet.proximity = penEvent.proximity;
		protocol4_packet.inrange = penEvent.proximity;

		if(protocol4_packet.inrange)
		{
			PenDataTransform::XformedData xformed;

			PenDataTransform::transform_pen_data(penEvent, xformed,
								false); // no tilt

			protocol4_packet.x = xformed.x;
			protocol4_packet.y = xformed.y;
			protocol4_packet.pressure = xformed.pressure;
			protocol4_packet.touch = penEvent.touch;
			protocol4_packet.eraser = penEvent.eraser;
			protocol4_packet.button0 = penEvent.button0;
			protocol4_packet.button1 = penEvent.button1;

			shouldfill = true;
		}
		else
		{
			protocol4_packet.x = 0;
			protocol4_packet.y = 0;
			protocol4_packet.pressure = 0;
			protocol4_packet.touch = 0;
			protocol4_packet.eraser = 0;
			protocol4_packet.button0 = 0;
			protocol4_packet.button1 = 0;
#ifdef DEBUG_SUPPORT
			DebugProc::proxOutTrigger();
#endif
		}

/*		if(console::console_enabled)
		{
			console::print("[USB Packet - prox:");
			console::printbit(protocol4_packet.proximity);
			console::print(" mou:");
			console::printbit(protocol4_packet.is_mouse);
			console::print(" range:");
			console::printbit(protocol4_packet.inrange);
			console::print(" touc:");
			console::printbit(protocol4_packet.touch);
			console::print(" era:");
			console::printbit(protocol4_packet.eraser);
			console::print(" b0:");
			console::printbit(protocol4_packet.button0);
			console::print(" b1:");
			console::printbit(protocol4_packet.button1);
			console::print(" res:");
			console::printbit(protocol4_packet.reserved);
			console::print(" x=");
			console::printNumber(protocol4_packet.x);
			console::print(", y=");
			console::printNumber(protocol4_packet.y);
			console::print(", pressure=");
			console::printNumber(protocol4_packet.pressure);
			console::println("]");
		}
*/
		if(extdata_getValue8(EXTDATA_USB_PORT) == EXTDATA_USB_PORT_DIGITIZER)
			UsbUtil::send_packet_fill_idle_time(protocol4_packet.buffer, 8, WACOM_PEN_ENDPOINT, 50);
	}
#endif

	//-----------------------------------------------------------------
	// USB Bamboo Pen Packet
	//-----------------------------------------------------------------

	struct bamboo_pen_struct
	{
		union
		{
			uint8_t buffer[9];
			struct
			{
				uint8_t hid_identifier; // 0x02
				struct
				{
					unsigned touch:1;   // bit 0 - pen touches the tablet
					unsigned button0:1; // bit 1 - first button on the pen
					unsigned button1:1; // bit 2 - second button on the pen
					unsigned eraser:1;  // bit 3 - eraser tool
					unsigned inrange:1; // bit 4 - (?)like 'proximity' but for a greater distance.
							    // 		mouse is not moving in Windows when in that range
							    // 		but x/y coordinates are being sent.
					unsigned proximity:1;// bit 5 - proximity(?) pen in close proximity, moves the mouse
					unsigned notsure:1; // bit 6 - ??
					unsigned outofprox:1;// bit 7 - appears to be the only thing set with everything else is zero?
				};
				uint16_t x;
				uint16_t y;
				uint16_t pressure;
				uint8_t distance;
			};
		};
	} bamboo_pen_packet;

	void send_bamboo_pen_packet(Pen::PenEvent& penEvent)
	{
		bool shouldfill = false;
		bamboo_pen_packet.hid_identifier = 0x02;

		bamboo_pen_packet.notsure = 0;

//		bamboo_pen_packet.is_mouse = penEvent.is_mouse; // no mouse with bamboo(?)
		bamboo_pen_packet.inrange = penEvent.proximity;

		if(bamboo_pen_packet.inrange)
		{
			PenDataTransform::XformedData xformed;

			PenDataTransform::transform_pen_data(penEvent, xformed,
								false); // no tilt

			bamboo_pen_packet.x = xformed.x;
			bamboo_pen_packet.y = xformed.y;
			bamboo_pen_packet.pressure = xformed.pressure;
			bamboo_pen_packet.proximity = penEvent.proximity;
			bamboo_pen_packet.touch = penEvent.touch;
			bamboo_pen_packet.eraser = penEvent.eraser;
			bamboo_pen_packet.button0 = penEvent.button0;
			bamboo_pen_packet.button1 = penEvent.button1;
			bamboo_pen_packet.distance = 0x1A; // not sure if that value is used(?)
			bamboo_pen_packet.outofprox = 0;

			shouldfill = true;
		}
		else
		{
			bamboo_pen_packet.x = 0;
			bamboo_pen_packet.y = 0;
			bamboo_pen_packet.proximity = 0;
			bamboo_pen_packet.pressure = 0;
			bamboo_pen_packet.distance = 0;
			bamboo_pen_packet.touch = 0;
			bamboo_pen_packet.eraser = 0;
			bamboo_pen_packet.button0 = 0;
			bamboo_pen_packet.button1 = 0;
			bamboo_pen_packet.outofprox = 1;

#ifdef DEBUG_SUPPORT
			DebugProc::proxOutTrigger();
#endif
		}

		if(console::console_enabled)
		{
			console::print("[USB Packet - prox:");
			console::printbit(bamboo_pen_packet.proximity);
			console::print(" outofprox:");
			console::printbit(bamboo_pen_packet.outofprox);
			console::print(" range:");
			console::printbit(bamboo_pen_packet.inrange);
			console::print(" touc:");
			console::printbit(bamboo_pen_packet.touch);
			console::print(" era:");
			console::printbit(bamboo_pen_packet.eraser);
			console::print(" b0:");
			console::printbit(bamboo_pen_packet.button0);
			console::print(" b1:");
			console::printbit(bamboo_pen_packet.button1);
			console::print(" x=");
			console::printNumber(bamboo_pen_packet.x);
			console::print(", y=");
			console::printNumber(bamboo_pen_packet.y);
			console::print(", pressure=");
			console::printNumber(bamboo_pen_packet.pressure);
			console::print(", distance=");
			console::printNumber(bamboo_pen_packet.distance);
			console::println("]");
		}

		if(extdata_getValue8(EXTDATA_USB_PORT) == EXTDATA_USB_PORT_DIGITIZER)
			UsbUtil::send_packet_fill_idle_time(bamboo_pen_packet.buffer, 9, WACOM_PEN_ENDPOINT, 50);
	}

	struct bamboo_touch_struct
	{
		union
		{
			uint8_t buffer[20];
			struct
			{
				uint8_t hid_identifier; // 0x2
			};
		};
	} bamboo_touch_packet;

	void send_bamboo_touch_packet(Touch::TouchEvent& touchEvent)
	{
		if(!touchEvent.touch)
		{
			for(int i=0;i<20;i++)
				bamboo_touch_packet.buffer[i] = 0;
			bamboo_touch_packet.hid_identifier = 0x2;
		}
		else
		{
			return;
		}

		if(extdata_getValue8(EXTDATA_USB_PORT) == EXTDATA_USB_PORT_DIGITIZER)
			UsbUtil::send_packet(bamboo_touch_packet.buffer, 20, WACOM_PEN_ENDPOINT, 50);
	}

	//-----------------------------------------------------------------
	// USB Protocol V (5)
	//
	// Data gleaned for the Intuos2
	// Button 0 = side switch near the tip (not working with eraser)
	// Button 1 = side switch away from the tip (not working with eraser)
	//
	//	02 C2 85 20 16 00 2C D0 00 00   In Range: NORMAL PEN
	//	02 C2 85 A0 16 00 2C D0 00 00   In Range: ERASER (PEN)
	//
	//	02 A0 91 06 66 9F 00 20 40 B8   Pen Data (see below)
	//	...
	//	...
	//
	//	02 80 00 00 00 00 00 00 00 00   Out of range
	//
	//
	// Pen Data:	02 A0 91 06 66 9F 00 20 40 B8
	//
	// [0]	02  HID report identifier (02)
	// [1]	A0  1 1 p 0  0 b c i   p = prox, b = button1, c = button0, i = tool index
	// [2]	91  x x x x  x x x x   x pos
	// [3]	06  x x x x  x x x x
	// [4]	66  y y y y  y y y y   y pos
	// [5]	9F  y y y y  y y y y
	// [6]	00  p p p p  p p p p   pressure (1024)
	// [7]	20  p p t t  t t t t   t = tiltx - 0 = -60 degrees, 40 = 0, 7F = +60 degrees
	// [8]	40  t u u u  u u u u   u = tilty - 0 = -60 degrees, 40 = 0, 7F = +60 degrees
	// [9]	B8  d d d d  d 0 0 0   d = sensor z distance 0x26..0x0D
	//
	// touch = pressure > 10
	//
	//-----------------------------------------------------------------

	struct protocol5_struct
	{
		union
		{
			uint8_t buffer[10];
			struct
			{
				uint8_t hid_identifier; // 0x02
				struct
				{
					unsigned toolindex:1;// bit 0 - tool index -- set to 0 -- Intuos4/5: pressure low data extra bit
					unsigned button0:1; // bit 1 - first button on the pen
					unsigned button1:1; // bit 2 - second button on the pen
					unsigned bit3:1;    // bit 3 - set to 0 (for pen)
					unsigned bit4:1;    // bit 4 - set to 0 (for pen)
					unsigned proximity:1;//bit 5 - when 0, pen is far from the surface but
							    // mouse is moving in Windows.
					unsigned bit6:1;    // bit 6 - set to 1 (for pen)
					unsigned bit7:1;    // bit 7 - set to 1 (for pen)
				};
				uint8_t x_high;
				uint8_t x_low;
				uint8_t y_high;
				uint8_t y_low;
				uint8_t byte6;			// pressure high
				uint8_t byte7;			// pressure + tiltx
				uint8_t byte8;			// tiltx + tilty
				unsigned y_lowest:1;		// for Intuos3/4/5. (Intuos2 = 0)
				unsigned x_lowest:1;		// for Intuos3/4/5. (Intuos2 = 0)
				unsigned distance_lowest:1;	// for Intuos3/4/5. (Intuos2 = 0)
				unsigned distance:5;		// distance from the sensor -
								// Intuos2: seen numbers from 0x26 (far) to 0x0D (close) (bits 3..7)
			};
		};
	} protocol5_packet;

	static bool currentlyInRange = false;

	static void do_send_protocol5_packet(Pen::PenEvent& penEvent)
	{
		bool shouldfill = false;

		uint8_t* pbuf = protocol5_packet.buffer;

		*pbuf++ = 0x02; // [0] - HID report identifier

		if(penEvent.proximity)
		{
			if(currentlyInRange)
			{
				if(penEvent.is_mouse == false)
				{
					// normal pen packet
					protocol5_packet.toolindex = 0;
					protocol5_packet.button0 = penEvent.button0;
					protocol5_packet.button1 = penEvent.button1;
					protocol5_packet.bit3 = 0;
					protocol5_packet.bit4 = 0;
					protocol5_packet.proximity = penEvent.proximity; // TODO: Does this work correctly?
					protocol5_packet.bit6 = 1;
					protocol5_packet.bit7 = 1;

					// Bizarre discovery: Wondering if bit 6 was actually proximity, I set proximity to 0
					// and set bit6 = penEvent.proximity and when I put an Intuos1 pen on the tablet it
					// started cycling through a bunch of weird tools, many of which I don't think actually
					// exist such as "10 button stylus" and "Wood pen".

					PenDataTransform::XformedData xformed;

					PenDataTransform::transform_pen_data(penEvent, xformed,
										true); // with tilt

					protocol5_packet.x_high = ((xformed.x >> 8) & 0xff);
					protocol5_packet.x_low = (xformed.x & 0xff);

					protocol5_packet.y_high = ((xformed.y >> 8) & 0xff);
					protocol5_packet.y_low = (xformed.y & 0xff);

					uint8_t tiltx = xformed.tilt_x + 0x40;
					uint8_t tilty = xformed.tilt_y + 0x40;

					if((penEvent.serial_packet_first_byte & 0xB8) != 0xA0)
					{
						// TODO: Test this code with an actual airbrush.
						// This is an airbrush "second packet".  The only difference between the first and second
						// packets is that the absolute wheel position replaces the bits that contain the pressure
						// value in the first packet and all buttons are ignored.
						xformed.pressure = penEvent.abswheel;

						// Also, to identify that this is an airbrush second packet using the USB protocol,
						// (data[1] & 0xbc) == 0xb4 must be true.
						// 0xbc: 1011 1100
						// 0xb4: 1011 0100
						// So basically we need to send a value like this (where * bits can have changing values):
						//       1*11 01**
						//
						// The three unknown * bits are like a 3 bit number with 8 possible values.  I tried
						// sending each of these values using debug packet playback and found the following:
						// B4 and F4 seem to give correct results.
						// B6 and F6 change the wheel value to negative in the "Diagnose" panel of the Wacom
						// control panel.  Since this bit isn't interpreted by the linux driver, I assume this
						// is a bug or the start of a feature not implemented.
						// F5, B5, B7, and F7 all have bit 0 set which is supposed to be the tool index bit.
						// When any of these values are passed, no wheel position is detected by the Diagnose
						// panel and even the pen position packets are mostly ignored.
						// So B4 and F4 are the only working values.  I'm choosing B4 since Linux is actually
						// checking for a B4 value.
						// 0xb4 = 1011 0100
						// The standard data[1] we send with a normal pen packet is (B are buttons, P is proximity):
						//        11P0 0BB0
						// So we need to set button1 and bit4 to 1 and button0 and bit6 to 0.  Other bits are already
						// set correctly.
						protocol5_packet.button0 = 0;
						protocol5_packet.button1 = 1;
						protocol5_packet.bit4 = 1;
						protocol5_packet.bit6 = 0;

						// According to the linux driver, pressure, tilt, and the side button state are ignored
						// unless (data[1] & 0xb8) == 0xa0:
						// 0xb8: 1011 1000
						// 0xa0: 1010 0000
						// So we'd need to send 1*10 0*** but that isn't compatible with sending 1*11 01**
						// so pressure, tilt, and the side button state in the second packet would be ignored
						// except that the linux driver interprets just the tilt values when (data[1] & 0xbc) == 0xb4.
						// So we can expect tilt to change based on the second packet, but not pressure (which
						// is replaced by the wheel value) or button state.
					}

					uint16_t pressure = xformed.pressure;

					if(usbProtocol == EXTDATA_USB_PROTOCOL_WACOM_INTUOS5)
					{
						// extra pressure range for INTUOS4/5
						protocol5_packet.toolindex = pressure & 1;
						pressure = pressure >> 1;
					}

					protocol5_packet.byte6 = (pressure >> 2) & 0xFF;
					protocol5_packet.byte7 = ((pressure & 0x3) << 6) | ((tiltx >> 1) & 0x3F);
					protocol5_packet.byte8 = ((tiltx << 7) & 0x80) | ( tilty & 0x7F);

					protocol5_packet.distance = 0x0D; // The serial protocol doesn't include a distance value, but it does include the PROXIMITY_BIT

/*					if(console::console_enabled)
					{
						console::print("[USB Packet - prox:");
						console::printbit(protocol5_packet.proximity);
						console::print(" b0:");
						console::printbit(protocol5_packet.button0);
						console::print(" b1:");
						console::printbit(protocol5_packet.button1);
						console::print(" x:");
						console::printNumber((((uint16_t)protocol5_packet.x_high) << 8) | protocol5_packet.x_low);
						console::print(" y:");
						console::printNumber((((uint16_t)protocol5_packet.y_high) << 8) | protocol5_packet.y_low);
						console::print(" pressure:");
						console::printNumber((((uint16_t)protocol5_packet.byte6) << 2) |
								(((uint16_t)protocol5_packet.byte7) >> 6));
						console::print(" byte6,7,8:");
						console::printHex(protocol5_packet.byte6,2);
						console::printHex(protocol5_packet.byte7,2);
						console::printHex(protocol5_packet.byte8,2);
						console::println("]");
					}
*/				}
				else
				{
					// data[1] must be set so the following if statement is true (from the Linux driver):
					// if ((data[1] & 0xbc) == 0xa8 || (data[1] & 0xbe) == 0xb0 || (data[1] & 0xbc) == 0xac) {
					// 0xbc: 1011 1100
					// 0xbe: 1011 1110
					// 0xa8: 1010 1000
					// 0xb0: 1011 0000
					// 0xac: 1010 1100
					// So the if statement is saying:
					// If bit 7=1, 5=1, 4=0, 3=1, 2=0       // Theory: 4D mouse
					//    ||  7=1, 5=1, 4=1, 3=0, 2=0, 1=0  // Theory: Lens cursor packet
					//    ||  7=1, 5=1, 4=0, 3=1, 2=1       // Theory: 2D mouse and/or maybe marker pen
					// We later see that bit 1 is set only for a rotation packet.
					// bit 4 is cleared only for 4D mouse packets.
					// bit 3 is never referenced, but it's set to 0 only when bit 4 is set, so I'll assume it varies with bit 4.
					// bit 2 is never referenced but when it's set, the mouse's rotation and throttle wheel stop working so I would guess this bit means 2D mouse.
					// bit 5 is the "proximity" bit (set later), according to protocol5_struct, so if that bit isn't set, the linux
					// driver will only pay attention to the position of the mouse and not its buttons, rotation, etc.
					// Through experimentation I found that bit 6 must be set to 1 or the Wacom driver will not detect any button presses from the mouse.  It does still detect mouse position, rotation, and throttle position.
					*pbuf++ = 0xe0; // data[1] with bit 7, 6, and 5 set.

					// These bytes will later be filled with x/y position.
					*pbuf++ = 0; // data[2]
					*pbuf++ = 0; // data[3]
					*pbuf++ = 0; // data[4]
					*pbuf++ = 0; // data[5]

					int throttle = 0;
					int rotation = 0;

					if(LENS_CURSOR(penEvent)) {
						// Construct lens cursor packet (tested using a 4D mouse to spoof a lens cursor tool id)
						protocol5_packet.bit4 = 1;

						*pbuf++ = 0; // data[6]
						*pbuf++ = 0; // data[7]
						*pbuf++ = penEvent.buttons & 0x1f; // data[8] bits: 0:left btn, 1:mid btn, 2:right btn, 3:lower right button, 4:lower left button
					}
					else if (MOUSE_2D(penEvent))
					{
						// Construct 2D mouse packet
						// TODO: Test this code with a 2D mouse
						protocol5_packet.bit3 = 1;
						protocol5_packet.button1 = 1;

						*pbuf++ = 0; // data[6]
						*pbuf++ = 0; // data[7]

						// A 2d mouse has only left and right buttons plus a scroll wheel that can be clicked
						// to send a middle button.  The scroll wheel apparently works by sending an "up" or
						// "down" bit rather than sending an absolute value or a "throttle" value like the 4D mouse.
						// penEvent.relwheel will be 0 if no scroll wheel movement was received, or -1 or 1 if an
						// up or down wheel turn was received.
						// It looks like the serial protocol interprets bit 0 as -1 and bit 1 as +1, but I think
						// the USB protocol does the opposite.
						// USB is expecting these bits to be set in data[8] (R=right btn, M=middle btn, L=left btn,
						// D=down scroll wheel, U=up scroll wheel, *=doesn't matter, although two of these bits
						// are used by the Intuos3 mouse to represent two side buttons):
						//   ***RMLDU
						*pbuf++ = ((penEvent.buttons & 0x07) << 2)
							      | (penEvent.relwheel > 0 ? 0x01 : 0x00)
								  | (penEvent.relwheel < 0 ? 0x02 : 0x00);
					}
					else
					{
						// Construct 4D mouse packet
						protocol5_packet.bit3 = 1;

						if((penEvent.serial_packet_first_byte & 0xbe) == 0xaa)
						{
							// This is a 4D mouse "second packet" containing rotational information.
							protocol5_packet.button0 = 1; // Set bit 1 to indicate this is the "second packet".

							// In the serial protocol, rotation is measured by an 11 bit number (11 bits stores 0-2047).
							// By looking at the linux driver and by rotating the mouse, I found that with the mouse held
							// straight up, rotation_z jumps between 0 and 1799.  Rotating clockwise it decreases below 1799,
							// 1350 at 90 degrees, 900 at 180, 450 at 270.
							// In USB, rotation gets 10 bits plus a single +/- bit, so we can represent -1023 to 1023.
							// By rotating the mouse in About > Diagnose I found that a value of -1 represents 359.9 degrees,
							// -3 is around 358, etc.  A value of 125 is about 25 deg, while 1 is about 0 deg.  So they're
							// essentially representing 0 (straight up) to 180 degrees with 0 to 900 rotating clockwise,
							// then it jumps to around -900 and returns to 0 as you continue to rotate clockwise.
							rotation = penEvent.rotation_z;
							if(rotation < 900)
							{
								// Rotation must be shifted left by 1 bit to make room to use bit 0 to represent
								// positive or negative.  Why the heck they made the formatting so confusing is beyond me.
								rotation = (rotation << 1) | 0x1; // Bit 0 is set when rotation is negative.
							}
							else
							{
								rotation = 1799 - rotation;
								rotation = rotation << 1;
							}
							*pbuf++ = (rotation & 0x7f8) >> 3; // data[6] holds the first 8 bits
							*pbuf++ = (rotation & 0x07) << 5; // data[7]: bits 7-5 contain bits 2-0 of rotation_z, bit 5 also indicates whether the rotation is negative or not.
							*pbuf++ = 0; // data[8]
							//*pbuf++ = (penEvent.buttons & 0x07) | ((penEvent.buttons & 0x18) << 1); // data[8] bits: 0:left btn, 1:mid btn, 2:right btn, 3:throttle wheel has negative value when set, 4:lower right button, 5:lower left button
						}
						else
						{
							// The serial data contains throttle values ranging from -1023 to 1023 using 10 bits for the value plus
							// 1 bit for the +/-.  The USB data only supports an 8-bit value plus 1 bit for +/-, so we must scale
							// throttle to range from -255 to +255 using 8 bits for the number and 1 bit for the +/-
							throttle = penEvent.throttle;
							if(throttle < 0) {
								throttle = -throttle;
							}
							throttle >>= 2;

							*pbuf++ = (throttle & 0xfc) >> 2; // data[6] stores bits 7-2 of throttle
							*pbuf++ = (throttle & 0x03) << 6; // data[7] stores bits 1-0 of throttle
							*pbuf++ = (penEvent.buttons & 0x07) | ((penEvent.buttons & 0x18) << 1) | (penEvent.throttle < 0 ? 0x08 : 0); // data[8] bits: 0:left btn, 1:mid btn, 2:right btn, 3:throttle wheel has negative value when set, 4:lower right button, 5:lower left button
						}
					}

					// TODO: If setting X/Y here works, set it in one shared place for pen and mouse events.
					protocol5_packet.proximity = penEvent.proximity;
					//protocol5_packet.bit6 = penEvent.proximity;

					PenDataTransform::XformedData xformed;

					PenDataTransform::transform_pen_data(penEvent, xformed,
										false); // without tilt

					// This will overwrite data[2] - [5] and the last 5 bits of [9]:
					protocol5_packet.x_high = ((xformed.x >> 8) & 0xff);
					protocol5_packet.x_low = (xformed.x & 0xff);

					protocol5_packet.y_high = ((xformed.y >> 8) & 0xff);
					protocol5_packet.y_low = (xformed.y & 0xff);

					protocol5_packet.distance = 0x0D;

					/*
					if(protocol5_packet.button0 == 0) {
						console::print("SB: ");
						console::printNumber(penEvent.throttle);
						console::print(" ");
						console::printNumber(throttle);
						console::print(" ");
						console::printHex(protocol5_packet.byte8, 2);
						console::println();
					}
					if(protocol5_packet.button0 == 1) {
						console::print("SB: ");
						console::printNumber(penEvent.rotation_z);
						console::print(" ");
						console::printNumber(rotation);
						console::print(" ");
						console::printHex(protocol5_packet.byte8, 2);
						console::println();
					}*/
					/*
					if(protocol5_packet.button0 == 0) {
						console::print("SB: ");
						console::printHex(protocol5_packet.byte8, 2);
						console::println();
					}*/
				}
			}
			else
			{
				currentlyInRange = true;

				// Tell the Wacom driver a tool has come into proximity.
				//
				// Example Intuos2 pen and eraser proximity packets:
				//   02 C2 85 20 16 00 2C D0 00 00   In Range: NORMAL PEN
				//   02 C2 85 A0 16 00 2C D0 00 00   In Range: ERASER (PEN)
				// Tool id is 85<<4 | 20>>4 | D0&0f<<20 | 00&f0<<12 = 850 | 2 | 0 | 0 = 0x000852
				// Serial number is 20&0f<<28 + 16<<20 + 00<<12 + 2c<<4 + d0>>4 = 0+1600000+0+2c0+d = 0x016002CD
				//
				//   02 C2 85 A0 16 00 2C D0 00 00   In Range: ERASER (PEN)
				// Tool id is 85<<4 | 20>>4 | D0&0f<<20 | 00&f0<<12 = 850 | 2 | 0 | 0 = 0x00085A
				// Serial number (is the same) = 0x016002CD
				//
				// Intuos5 touch S pen proximity packet:
				//   02 C2 80 22 28 08 26 91 00 00   In Range: Intuos5(?) Pen
				//   02 C2 80 A2 28 08 26 91 00 00  eraser
				// Tool id is 80<<4 | 22>>4 | 91&0f<<20 | 00&f0<<12 = 800 | 2 | 100000 | 0 = 0x100802 pen
				// Tool id is 80<<4 | A2>>4 | 91&0f<<20 | 00&f0<<12 = 800 | A | 100000 | 0 = 0x10080A eraser
				// Serial number is = 0x22808269
				//

				//
				/*
				*pbuf++ = 0xC2; // [1]
				*pbuf++ = 0x85; // [2]

				if(penEvent.eraser)
					*pbuf++ = 0xA0; // [3]
				else
					*pbuf++ = 0x20; // [3]

				*pbuf++ = 0x16; // [4]
				*pbuf++ = 0x00; // [5]
				*pbuf++ = 0x2C; // [6]
				*pbuf++ = 0xD0; // [7]
				*pbuf++ = 0x00; // [8]
				*pbuf   = 0x00; // [9]*/

				// From http://git.yoctoproject.org/cgit/cgit.cgi/linux-yocto-2.6.37/plain/drivers/input/tablet/wacom_wac.c
				// data[1] & 0x01 contains the "tool number".  Since this is a single bit, I'm guessing it's used to
				// track up to two tools being used at the same time?  We'll just set it to 0.
				// (data[1] & 0xfc) == 0xc0 must be true to be considered a "tool in proximity" packet.
				// In the captured packets from an Intuos2 pen, this byte contained 0xc2, but the source code above
				// doesn't use the "2" bit for anything.  Still, we may as well replicate the captured data.
				*pbuf++ = 0xC2; // data[1]

				// This is how the tool type is decoded by the USB linux driver:
				//   (data[2] << 4) | (data[3] >> 4) | ((data[7] & 0x0f) << 20) | ((data[8] & 0xf0) << 12);
				// And this is how the serial is decoded:
				//   ((data[3] & 0x0f) << 28) + (data[4] << 20) + (data[5] << 12) + (data[6] << 4) + (data[7] >> 4);
				// We need to reverse these equations to encode the tool id and serial.  If you look at the equations,
				// Tool id (T) is encoded using 20 bits and serial (S) is encoded using 32 bits.  However, notice that
				// tool id decodes to a 24 bit number where only bits 23-16, 11-0 are assigned values stored in the
				// encoded data.  It would be logical to place bits 15-12 as the last 4 bits of data[8] but the
				// decoding equation ignores those bits using & 0xf0.  That could be a bug in the decoding equation.
				// Either way, these bits are all 0 in the data we plan to send so it doesn't matter for our purposes.
				// The tool id bits are spread out in a strange pattern, presumably because tool type started out as 12 bits
				// and was later padded to 24 by placing additional bits in the last half of data[7] and the first
				// half of data[8].
				// data[2]  [3]      [4]      [5]      [6]      [7]      [8]
				// TTTTTTTT TTTTSSSS SSSSSSSS SSSSSSSS SSSSSSSS SSSSTTTT TTTT????
				// Bit numbers (a 3 above a 1 means bit 31):
				// 11987654 32103322 22222222 11111111 11987654 32102222 1111
				// 10           1098 76543210 98765432 10           3210 9876

				// Some places that call do_send_protocol5_packet don't set the toolid or serial, so in
				// that case, assign generic values.
				uint32_t tool_id;

				if(penEvent.tool_id == 0)
				{
					if(usbProtocol == EXTDATA_USB_PROTOCOL_WACOM_INTUOS5)
					{
						if(penEvent.eraser)
						{
							tool_id = 0x10080A; // Eraser tool id (intuos 5)
						}
						else
							tool_id = 0x100802; // Pen tool id  (intuos 5)
					}
					else
					{
						if(penEvent.eraser)
							tool_id = 0x85A; // Eraser tool id  (intuos 2)
						else
							tool_id = 0x852; // Pen tool id  (intuos 2)
					}
				}
				else
				{
					tool_id = penEvent.tool_id;
				}

				uint32_t tool_serial_num;

				if(penEvent.tool_serial_num == 0)
				{
					if(usbProtocol == EXTDATA_USB_PROTOCOL_WACOM_INTUOS5)
						tool_serial_num = 0x22808269U; // Intuos 5 pen serial number (same for both the pen and eraser side)
					else
						tool_serial_num = 0x016002CDU; // Intuos 2 pen serial number (same for both the pen and eraser side)
				}
				else
					tool_serial_num = penEvent.tool_serial_num;

				*pbuf++ = tool_id >> 4; // data[2]
				*pbuf++ = ((tool_id & 0x0f) << 4) | ((tool_serial_num & 0xf0000000) >> 28); // data[3]
				*pbuf++ = (tool_serial_num & 0xff00000) >> 20; // data[4]
				*pbuf++ = (tool_serial_num & 0xff000) >> 12; // data[5]
				*pbuf++ = (tool_serial_num & 0xff0) >> 4; // data[6]
				*pbuf++ = ((tool_serial_num & 0xf) << 4) | ((tool_id & 0xf00000) >> 20); // data[7]
				*pbuf++ = (tool_id & 0xf0000) >> 12; // data[8]

				// I don't think data[9] means anything, but the captured data contained 0, so set to 0.
				*pbuf = 0; // data[9]

/*				if(console::console_enabled)
				{
					CONSOLE_PRINTP(STR_USB_PACKET_IN_RANGE_PACKET_ERASER);
					console::printbit(penEvent.eraser);
					console::println("]");
				}
*/			}

			shouldfill = true;
		}
		else if(currentlyInRange)
		{
			currentlyInRange = false;

			// out of range  -- 02 80 00 00 00 00 00 00 00 00

			*pbuf++ = 0x80; // [1]
			*pbuf++ = 0x00; // [2]
			*pbuf++ = 0x00; // [3]
			*pbuf++ = 0x00; // [4]
			*pbuf++ = 0x00; // [5]
			*pbuf++ = 0x00; // [6]
			*pbuf++ = 0x00; // [7]
			*pbuf++ = 0x00; // [8]
			*pbuf   = 0x00; // [9]

/*			if(console::console_enabled)
			{
				CONSOLE_PRINTLNP(STR_USB_PACKET_OUT_OF_RANGE_PACKET_ALL_ZEROS);
			}
*/
#ifdef DEBUG_SUPPORT
			DebugProc::proxOutTrigger();
#endif
		}
		else
		{
			// invalid state -- do not send anything
			return;
		}

		#ifdef DEBUG_USB_DATA
/*			console::print("SU: "); // Sending USB data.  Keep these debug statements short or it seems to overflow the USB buffer
			for(int i = 0; i < 10; i++) {
				console::printHex(protocol5_packet.buffer[i], 2);
				console::print(" ");
			}
			console::println();
*/		#endif
		if(extdata_getValue8(EXTDATA_USB_PORT) == EXTDATA_USB_PORT_DIGITIZER)
		{
			uint8_t endPoint;

			if(usbProtocol == EXTDATA_USB_PROTOCOL_WACOM_INTUOS5)
				endPoint = WACOM_INTUOS5_PEN_ENDPOINT;  // Pen data on Endpoint 3 (0x83) with Intuos5
			else
				endPoint = WACOM_PEN_ENDPOINT; // Pen data on Endpoint 1 (0x81) with Intuos2

			UsbUtil::send_packet_fill_idle_time(protocol5_packet.buffer, 10, endPoint, 50);
		}
	}

	bool in_special_operation = false;
	bool special_op_inrange_state = false;

	void send_protocol5_packet(Pen::PenEvent& penEvent)
	{
		if(in_special_operation)
			return; // already in a special operation!

		do_send_protocol5_packet(penEvent);
	}

	/**
	 * get the device out of proximity momentarily
	 */
	void begin_special_operation_protocol5()
	{
		if(in_special_operation)
			return;	// already in a special operation!

		in_special_operation = true;
		special_op_inrange_state = currentlyInRange;

		if(currentlyInRange)
		{
			Pen::PenEvent penEvent;

			penEvent.proximity = false;

			do_send_protocol5_packet(penEvent);
		}
	}

	/**
	 * return to the state before the device was out of prox momentarily
	 */
	void end_special_operation_protocol5()
	{
		if(!in_special_operation)
			return;	// was not in a special operation

		in_special_operation = false;

		if(special_op_inrange_state)
		{
			// do nothing. Let the next pen movement re-initialize the status
		}

		special_op_inrange_state = false;
	}
}


text:
package com.intellij.psi.formatter;

import com.intellij.lang.ASTFactory;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.CharTable;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class FormatterUtil {
  private static final List<FormatterUtilHelper> ourHelpers = ContainerUtil.createEmptyCOWList();

  private FormatterUtil() {
  }

  public static void addHelper(FormatterUtilHelper helper) {
    ourHelpers.add(helper);
  }

  private static ASTNode getWsCandidate(ASTNode element) {
    if (element == null) return null;
    ASTNode treePrev = element.getTreePrev();
    if (treePrev != null) {
      if (isSpaceTextElement(treePrev)) {
        return treePrev;
      }
      else if (treePrev.getTextLength() == 0) {
        return getWsCandidate(treePrev);
      }
      else {
        return element;
      }
    }
    final ASTNode treeParent = element.getTreeParent();

    if (treeParent == null || treeParent.getTreeParent() == null) {
      return element;
    }
    else {
      return getWsCandidate(treeParent);
    }
  }

  @Nullable
  private static ASTNode getLastChildOf(ASTNode element) {
    return TreeUtil.getLastChild(element);
  }

  private static boolean isWhiteSpaceElement(ASTNode treePrev) {
    return treePrev.getElementType() == TokenType.WHITE_SPACE;
  }

  private static boolean isSpaceTextElement(ASTNode treePrev) {
    return isWhiteSpaceElement(treePrev);
  }

  public static void replaceWhiteSpace(final String whiteSpace,
                                         final ASTNode leafElement,
                                         final IElementType whiteSpaceToken,
                                         final @Nullable TextRange textRange) {
    final CharTable charTable = SharedImplUtil.findCharTableByTree(leafElement);

    if (textRange != null && textRange.getStartOffset() > leafElement.getTextRange().getStartOffset() &&
        textRange.getEndOffset() < leafElement.getTextRange().getEndOffset()) {
      StringBuilder newText = createNewLeafChars(leafElement, textRange, whiteSpace);
      LeafElement newElement = Factory.createSingleLeafElement(leafElement.getElementType(), newText, charTable, leafElement.getPsi().getManager());

      leafElement.getTreeParent().replaceChild(leafElement, newElement);
      return;
    }

    ASTNode treePrev = findPreviousWhiteSpace(leafElement);
    if (treePrev == null) {
      treePrev = getWsCandidate(leafElement);
    }

    if (treePrev != null &&
        treePrev.getText().trim().length() == 0 &&
        treePrev.getElementType() != whiteSpaceToken &&
        treePrev.getTextLength() > 0 &&
        whiteSpace.length() >
        0) {
      LeafElement whiteSpaceElement = Factory.createSingleLeafElement(treePrev.getElementType(), whiteSpace, charTable, SharedImplUtil.getManagerByTree(leafElement));

      ASTNode treeParent = treePrev.getTreeParent();
      treeParent.replaceChild(treePrev, whiteSpaceElement);
    }
    else {
      LeafElement whiteSpaceElement = Factory.createSingleLeafElement(whiteSpaceToken, whiteSpace, charTable, SharedImplUtil.getManagerByTree(leafElement));

      if (treePrev == null) {
        if (whiteSpace.length() > 0) {
          addWhiteSpace(leafElement, whiteSpaceElement);
        }
      }
      else if (!isSpaceTextElement(treePrev)) {
        if (whiteSpace.length() > 0) {
          addWhiteSpace(treePrev, whiteSpaceElement);
        }
      }
      else if (isWhiteSpaceElement(treePrev)) {
        final CompositeElement treeParent = (CompositeElement)treePrev.getTreeParent();
        if (whiteSpace.length() > 0) {
//          LOG.assertTrue(textRange == null || treeParent.getTextRange().equals(textRange));
          treeParent.replaceChild(treePrev, whiteSpaceElement);
        }
        else {
          treeParent.removeChild(treePrev);
        }
        //treeParent.subtreeChanged();
      }
    }
  }

  private static StringBuilder createNewLeafChars(final ASTNode leafElement, final TextRange textRange, final String whiteSpace) {
    final TextRange elementRange = leafElement.getTextRange();
    final String elementText = leafElement.getText();

    final StringBuilder result = new StringBuilder();

    if (elementRange.getStartOffset() < textRange.getStartOffset()) {
      result.append(elementText.substring(0, textRange.getStartOffset() - elementRange.getStartOffset()));
    }

    result.append(whiteSpace);

    if (elementRange.getEndOffset() > textRange.getEndOffset()) {
      result.append(elementText.substring(textRange.getEndOffset() - elementRange.getStartOffset()));
    }

    return result;
  }

  private static void addWhiteSpace(final ASTNode treePrev, final LeafElement whiteSpaceElement) {
    for (FormatterUtilHelper helper : ourHelpers) {
      if (helper.addWhitespace(treePrev, whiteSpaceElement)) return;
    }

    final ASTNode treeParent = treePrev.getTreeParent();
    treeParent.addChild(whiteSpaceElement, treePrev);
  }

  @Nullable
  private static ASTNode findPreviousWhiteSpace(final ASTNode leafElement) {
    final int offset = leafElement.getTextRange().getStartOffset() - 1;
    if (offset < 0) return null;
    final PsiElement found = SourceTreeToPsiMap.treeElementToPsi(leafElement).getContainingFile().findElementAt(offset);
    if (found == null) return null;
    final ASTNode treeElement = found.getNode();
    if (treeElement.getElementType() == TokenType.WHITE_SPACE) return treeElement;
    return null;
  }

  @Nullable
  public static ASTNode getLeafNonSpaceBefore(final ASTNode element) {
    if (element == null) return null;
    ASTNode treePrev = element.getTreePrev();
    if (treePrev != null) {
      ASTNode candidate = getLastChildOf(treePrev);
      if (candidate != null && !isSpaceTextElement(candidate) && candidate.getTextLength() > 0) {
        return candidate;
      }
      else {
        return getLeafNonSpaceBefore(candidate);
      }
    }
    final ASTNode treeParent = element.getTreeParent();

    if (treeParent == null || treeParent.getTreeParent() == null) {
      return null;
    }
    else {
      return getLeafNonSpaceBefore(treeParent);
    }

  }

  public static boolean isIncompleted(final ASTNode treeNode) {
    ASTNode lastChild = treeNode.getLastChildNode();
    while (lastChild != null && lastChild.getElementType() == TokenType.WHITE_SPACE) {
      lastChild = lastChild.getTreePrev();
    }
    if (lastChild == null) return false;
    if (lastChild.getElementType() == TokenType.ERROR_ELEMENT) return true;
    return isIncompleted(lastChild);
  }

  public static void replaceLastWhiteSpace(final ASTNode astNode, final String whiteSpace, final TextRange textRange) {
    LeafElement lastWS = TreeUtil.findLastLeaf(astNode);
    if (lastWS.getElementType() != TokenType.WHITE_SPACE) {
      lastWS = null;
    }
    if (lastWS != null && !lastWS.getTextRange().equals(textRange)) {
      return;
    }
    if (whiteSpace.length() == 0 && lastWS == null) {
      return;
    }
    if (lastWS != null && whiteSpace.length() == 0) {
      lastWS.getTreeParent().removeRange(lastWS, null);
      return;
    }

    LeafElement whiteSpaceElement = ASTFactory.whitespace(whiteSpace);

    if (lastWS == null) {
      astNode.addChild(whiteSpaceElement, null);
    } else {
      ASTNode treeParent = lastWS.getTreeParent();
      treeParent.replaceChild(lastWS, whiteSpaceElement);
    }
  }

  public static boolean containsWhiteSpacesOnly(final ASTNode node) {
    if (node.getElementType() == TokenType.WHITE_SPACE || node.getTextLength() == 0) return true;
    for (FormatterUtilHelper helper : ourHelpers) {
      if (helper.containsWhitespacesOnly(node)) return true;
    }

    if (node instanceof LeafElement) return false;
    ASTNode child = node.getFirstChildNode();
    while (child != null) {
      if (!containsWhiteSpacesOnly(child)) return false;
      child = child.getTreeNext();
    }
    return true;
  }

}


text:
package com.aventstack.extentreports.model;

import java.io.Serializable;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public abstract class NameValuePair extends NamedAttribute implements Serializable, BaseEntity {
    private static final long serialVersionUID = 6613712676810614719L;
    private String value;

    public NameValuePair(String name, String value) {
        super(name);
        this.value = value;
    }
}


text:
package org.dcm4che.net;

import java.io.*;
import java.util.*;

import junit.framework.*;

/**
 *
 * @author  gunter.zeilinger@tiani.com
 * @version 1.0.0
 */
public class AAbortTest extends ExtTestCase {

    public AAbortTest(java.lang.String testName) {
        super(testName);
    }

    public static void main(java.lang.String[] args) {
        junit.textui.TestRunner.run(suite());
    }

    public static Test suite() {
        TestSuite suite = new TestSuite(AAbortTest.class);
        return suite;
    }

    private static final String A_ABORT = "data/AAbort.pdu";
    private final int SOURCE = AAbort.SERVICE_PROVIDER;
    private final int REASON = AAbort.INVALID_PDU_PARAMETER_VALUE;

    private AssociationFactory fact;

    protected void setUp() throws Exception {
        fact = AssociationFactory.getInstance();
    }

    public void testWrite() throws Exception {
        AAbort pdu = fact.newAAbort(SOURCE, REASON);
        ByteArrayOutputStream out = new ByteArrayOutputStream(10);
//        OutputStream out = new FileOutputStream(A_ABORT);
        pdu.writeTo(out);
        out.close();
        assertEquals(load(A_ABORT), out.toByteArray());
    }

    public void testRead() throws Exception {
        InputStream in = new FileInputStream(A_ABORT);
        AAbort pdu = null;
        try {
            pdu = (AAbort)fact.readFrom(in, null);
        } finally {
            try { in.close(); } catch (IOException ignore) {}
        }
        assertEquals(SOURCE, pdu.source());
        assertEquals(REASON, pdu.reason());
    }
}


text:
package main

import (
	"fmt"
	"time"
)

func UpdateApiCounters() {
	key := fmt.Sprintf("%d%d%d", time.Now().Month(), time.Now().Day(), time.Now().Year())
	stat := ApiStat{}
	DB.FirstOrCreate(&stat, ApiStat{DateKey: key})
	DB.Exec("UPDATE api_stats SET counter = counter + 1 WHERE date_key = ?", key)
}


text:
package com.github.pockethub.core.user;

import android.accounts.Account;
import android.content.Context;
import android.util.Log;

import com.alorma.github.sdk.services.user.follow.CheckFollowingUser;
import com.github.pockethub.accounts.AuthenticatedUserTask;

/**
 * Task to check user following status
 */
public class FollowingUserTask extends AuthenticatedUserTask<Boolean> {

    private static final String TAG = "FollowingUserTask";

    private final String login;

    /**
     * Create task for context and login
     *
     * @param context
     * @param login
     */
    public FollowingUserTask(final Context context, final String login) {
        super(context);

        this.login = login;
    }

    @Override
    protected Boolean run(final Account account) throws Exception {
        return new CheckFollowingUser(login).observable().toBlocking().first();
    }

    @Override
    protected void onException(final Exception e) throws RuntimeException {
        super.onException(e);

        Log.d(TAG, "Exception checking if following user", e);
    }
}


text:
require 'csv'

module AnIndex
  # used to export the results
  class CsvStreamer

    def initialize(search_class, params)
      @search_class  = search_class
      @params        = params
      @export_fields = Settings.export_fields
    end

    def each
      yield @export_fields.to_csv
      # the :size is multiplied by the number of shards (which are 5) so the actual batch is 20 text documents
      # keeping it low avoids memory problems, in exchange to a bit less of speed
      @search_class.search_in_batches(@params, :params=>{:size=>4}) do |result|
        result.collection.each do |doc|
          source = doc.source
          yield build_csv(source)
        end
      end
    end

  private

    def build_csv(source)
      @export_fields.map do |k|
        source[k]
      end.to_csv
    end

  end
end


text:
4

![thumb](http://placehold.it/348x196)

![splash](http://placehold.it/770x433)

## Short

WGBH Archives official website<br/>
Interviews and in depth program content

## Medium

TODO: Medium-length blurb for banner goes here.

## Long

### INTERVIEWS, ground-breaking WGBH television series

**Open Vault** is the official website of the WGBH Media Library and Archives.
Here you will find annotated **INTERVIEWS** from seminal WGBH miniseries from the
1980's and 1990's:
**Vietnam: A Television History** (1983),
**War and Peace in the Nuclear Age** (1989) and
**Rock and Roll** (1995).
In addition, you will find content from older WGBH series including the innovative series,
**New Television Workshop** (1974-1993),
**Say Brother**, one of the first African American public affairs series (1968-1982),
**The Advocates** (1969-1984),
the **WGBH Ten O'Clock News** (1976-1991),
**Press and the People** (1958-59),
and complete audio coverage from the 1963 March on Washington
and other highlights from WGBH's history.

You can also search the entire catalog of WGBH programs by clicking on
the "Browse: Series" button on the Open Vault site.

## Links

## Grid

- [TODO Title | optional subtitle](/TODO) ![](http://placehold.it/348x196)
- [TODO Title](/TODO) ![](http://placehold.it/348x196)
- [TODO Title](/TODO) ![](http://placehold.it/348x196)


text:
package com.intellij.openapi.vcs.changes;

import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class SimpleContentRevision implements ContentRevision {
  private final String myContent;
  private final FilePath myNewFilePath;
  @NotNull private final String myRevision;

  public SimpleContentRevision(final String content, final FilePath newFilePath, @NotNull final String revision) {
    myContent = content;
    myNewFilePath = newFilePath;
    myRevision = revision;
  }

  @Override
  @Nullable
  public String getContent() {
    return myContent;
  }

  @Override
  @NotNull
  public FilePath getFile() {
    return myNewFilePath;
  }

  @Override
  @NotNull
  public VcsRevisionNumber getRevisionNumber() {
    return new VcsRevisionNumber() {
      @NotNull
      @Override
      public String asString() {
        return myRevision;
      }

      @Override
      public int compareTo(final VcsRevisionNumber o) {
        return 0;
      }
    };
  }
}


text:
export declare class DateFormatter {
    format(date: Date, format: string, locale: string): string;
}


text:
'''Simple example of using the SWIG generated TWS wrapper to place an order
with interactive brokers.

'''

import sys
from threading import Event

from swigibpy import (EWrapper, EPosixClientSocket, Contract, Order, TagValue,
                      TagValueList)

WAIT_TIME = 10.0

try:
    # Python 2 compatibility
    input = raw_input
    from Queue import Queue
except:
    from queue import Queue

###

class PlaceOrderExample(EWrapper):
    '''Callback object passed to TWS, these functions will be called directly
    by TWS.

    '''

    def __init__(self):
        super(PlaceOrderExample, self).__init__()
        self.order_filled = Event()
        self.order_ids = Queue()

    def openOrderEnd(self):
        '''Not relevant for our example'''
        pass

    def execDetails(self, id, contract, execution):
        '''Not relevant for our example'''
        pass

    def managedAccounts(self, openOrderEnd):
        '''Not relevant for our example'''
        pass

    ###############

    def nextValidId(self, validOrderId):
        '''Capture the next order id'''
        self.order_ids.put(validOrderId)

    def orderStatus(self, id, status, filled, remaining, avgFillPrice, permId,
                    parentId, lastFilledPrice, clientId, whyHeld):

        print(("Order #%s - %s (filled %d, remaining %d, avgFillPrice %f,"
               "last fill price %f)") %
              (id, status, filled, remaining, avgFillPrice, lastFilledPrice))
        if remaining <= 0:
            self.order_filled.set()

    def openOrder(self, orderID, contract, order, orderState):

        print("Order opened for %s" % contract.symbol)

    def commissionReport(self, commissionReport):
        print 'Commission %s %s P&L: %s' % (commissionReport.currency,
                                            commissionReport.commission,
                                            commissionReport.realizedPNL)

prompt = input("WARNING: This example will place an order on your IB "
               "account, are you sure? (Type yes to continue): ")
if prompt.lower() != 'yes':
    sys.exit()

# Instantiate our callback object
callback = PlaceOrderExample()

# Instantiate a socket object, allowing us to call TWS directly. Pass our
# callback object so TWS can respond.
tws = EPosixClientSocket(callback)

# Connect to tws running on localhost
if not tws.eConnect("", 7496, 42):
    raise RuntimeError('Failed to connect to TWS')

# Simple contract for GOOG
contract = Contract()
contract.symbol = "IBM"
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"

print('Waiting for valid order id')
order_id = callback.order_ids.get(timeout=WAIT_TIME)
if not order_id:
    raise RuntimeError('Failed to receive order id after %ds' % WAIT_TIME)

# Order details
algoParams = TagValueList()
algoParams.append(TagValue("componentSize", "3"))
algoParams.append(TagValue("timeBetweenOrders", "60"))
algoParams.append(TagValue("randomizeTime20", "1"))
algoParams.append(TagValue("randomizeSize55", "1"))
algoParams.append(TagValue("giveUp", "1"))
algoParams.append(TagValue("catchUp", "1"))
algoParams.append(TagValue("waitForFill", "1"))
algoParams.append(TagValue("startTime", "20110302-14:30:00 GMT"))
algoParams.append(TagValue("endTime", "20110302-21:00:00 GMT"))

order = Order()
order.action = 'BUY'
order.lmtPrice = 140
order.orderType = 'LMT'
order.totalQuantity = 10
order.algoStrategy = "AD"
order.tif = 'DAT'
order.algoParams = algoParams
#order.transmit = False

print("Placing order for %d %s's (id: %d)" % (order.totalQuantity,
                                              contract.symbol, order_id))

# Place the order
tws.placeOrder(
    order_id,                                   # orderId,
    contract,                                   # contract,
    order                                       # order
)

print("\n====================================================================")
print(" Order placed, waiting %ds for TWS responses" % WAIT_TIME)
print("====================================================================\n")

print("Waiting for order to be filled..")

try:
    callback.order_filled.wait(WAIT_TIME)
except KeyboardInterrupt:
    pass
finally:
    if not callback.order_filled.is_set():
        print('Failed to fill order')

    print("\nDisconnecting...")
    tws.eDisconnect()


text:
function wrapperVersion(e) {
	const spawn = require('child_process').spawn;
	const proc = spawn('./gradlew', ['-v']);

	proc.stdout.on('data', (data) => {
		console.log(`${data}`);

		/*data += "";
		data = data.replace(/\r\n/g, "
");
		data = data.replace(/\n/g, "
");

		var paragraph = document.createElement("p");
		paragraph.innerHTML = data;

		var element = document.getElementById("console");
		element.appendChild(paragraph);*/
	});
}

function wrapperListTasks(e) {
	const spawn = require('child_process').spawn;
	const proc = spawn('./gradlew', ['tasks']);

	proc.stdout.on('data', (data) => {
		console.log(`${data}`);

		/*data += "";
		data = data.replace(/\r\n/g, "
");
		data = data.replace(/\n/g, "
");

		var paragraph = document.createElement("p");
		paragraph.innerHTML = data;

		var element = document.getElementById("console");
		element.appendChild(paragraph);*/
	});
}

function wrapperExecuteBuild(e) {
	const spawn = require('child_process').spawn;
	const proc = spawn('./gradlew', ['hello']);

	proc.stdout.on('data', (data) => {
		console.log(`${data}`);

		/*data += "";
		data = data.replace(/\r\n/g, "
");
		data = data.replace(/\n/g, "
");

		var paragraph = document.createElement("p");
		paragraph.innerHTML = data;

		var element = document.getElementById("console");
		element.appendChild(paragraph);*/
	});
}

function javaPluginListTasks(e) {
	var java = require('java');

	var filesystem = require("fs");

    filesystem.readdirSync('lib').forEach(function(file) {
        file = 'lib/'+file;
        java.classpath.push(file);
    });

	var system = java.import('java.lang.System');
	java.import('org.gradle.tooling.GradleConnector');
	java.import('org.gradle.tooling.ProjectConnection');
	java.import('org.gradle.tooling.model.GradleProject');
	java.import('org.gradle.tooling.model.GradleTask');
	java.import('org.gradle.tooling.model.Task');

	var filePath = java.newInstanceSync("java.io.File", ".");

	var connector = java.callStaticMethodSync("org.gradle.tooling.GradleConnector", "newConnector");
	java.callMethodSync(connector, "forProjectDirectory", filePath);
	var connection = java.callMethodSync(connector, "connect");

	var buildLauncher = java.callMethodSync(connection, "newBuild");
	java.callMethodSync(buildLauncher, "forTasks", "tasks");
	java.callMethodSync(buildLauncher, "setStandardOutput", java.getStaticFieldValue("java.lang.System", "out"));
	java.callMethodSync(buildLauncher, "run");

	java.callMethodSync(connection, "close");
}


text:
pub mod detector;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PurposeForFindingRensa {
    ForFire,
    ForKey,
}


text:
/* ====================================
 * Amp framework v1.0.0
 * Quipu GmbH (http://www.quipugmbh.com)
 *
 * Amp Input.
 * ==================================== */
;(function($, Amp) {

  function Input(element, options){
    element.attr('autocomplete', 'off');
    return Amp.createObject(Input.proto, Amp.controls.control(element, options));
  }

  Input.proto = Amp.createObject(Amp.controls.control.proto, {
    __reformat: function(val){
      val === undefined && (val = this.element.val());
      this.element.val(val);
      this.element.data('valBeforeType', val);
      return this;
    },

    toString: function(){
      var val = this.__get();
      return val === null ? "" : val;
    }
  });

  function TextInput(element, options){
    var format, value, input, options = options || {};

    value  = options.value  || null
    format = options.format || null;

    delete options.value;
    delete options.format;

    input = Amp.createObject(TextInput.proto, Input(element, options));
    input.element.addClass('amp-text');
    input.__set(value, true);
    input.setFormat(format);

    return input;
  }

  TextInput.proto = Amp.createObject(Input.proto, {
    __get: function() {
      return this.element.val();
    },

    __set: function(value, silent, oldval){
      oldval === undefined && (oldval = this.__get());
      value = value === null ? "" : "" + value;

      if(value && this.options.format && !this.options.format.test(value)){
        this.element.val(oldval === null ? "" : oldval);
        return this;
      }

      if(oldval !== value) {
        if(this.trigger('beforechange', oldval, value) !== false) {
          this.element.val(value);
          silent || this.trigger('change');
        }
        else {
          this.element.val(oldval);
        }
      }

      this.element.data('valBeforeEdit', this.__get());
      this.element.data('valBeforeType', this.element.val());
      return this;
    },

    // Prevents changing the value of an input if it doesn't check out
    // with the regular expression passed as format
    setFormat: function(format){
      if("" + this.options.format === "" + format) {
        return this;
      }

      if(!format) {
        this.options.format = null;
      }
      else if(format instanceof RegExp) {
        this.options.format = format;
      }
      else {
        try {
          this.options.format = new RegExp(format);
        } catch (e) {
          throw "Invalid formatting for input '" + this.element.attr('id') + "': " + format;
        }
      }
      return this;
    }
  });

  function NumberInput(element, options){
    var min, max, format, value, input, options = options || {};

    value  = options.value;
    format = options.format;
    min    = options.min;
    max    = options.max;

    delete options.min;
    delete options.max;
    delete options.format;
    delete options.value;

    input = Amp.createObject(NumberInput.proto, Input(element, options));
    input.element.addClass('amp-number');
    input.setFormat(format);

    input.__set(value, true);
    input.clamp(min, max);

    return input;
  }

  NumberInput.proto = Amp.createObject(Input.proto, {
    __get: function() {
      var val = parseFloat(this.element.val().replace(/,/g, ''), 10);
      return isNaN(val) ? null : val;
    },

    __set: function(value, silent, oldval) {
      oldval === undefined && (oldval = this.__get());
      value = parseFloat(('' + value).replace(/,/g, ''), 10);

      isNaN(value) && (value = null);

      if( value !== null ) {
        var min = this.options.min;
        var max = this.options.max;

        if((min !== undefined && min !== null && value < min) || (max !== undefined && max !== null && value > max)){
          this.element.val(oldval === null ? "" : oldval.format(this.options.format));
          return this;
        }
      }

      if(oldval !== value) {
        this.element.val(value === null ? "" : value.format(this.options.format));
        silent || this.trigger('change');
      }

      this.element.data('valBeforeEdit', this.__get());
      this.element.data('valBeforeType', this.element.val());
      return this;
    },

    toString: function() {
      var val = this.__get();
      return val === null ? "" : "" + val;
    },

    setFormat: function(format){
      var precision = format = isNaN(format) ? 0 : parseInt(format, 10);

      if(this.options.format === format) {
        return this;
      }
      this.options.format = format;

      var options           = this.options;
      var maxlength         = options.maxlength || null;
      var dot               = precision > 0 ? '.' : '';
      var allowedKeys       = [37, 38, 39, 40, 27, 8, 46, 9];
      var regexLeadingZeros = /^0[^.]/;
      var regexValidChar    = new RegExp('[0-9' + dot + ']');

      // Unbind the previously bound formatting handler (if any)
      this.__formatter && this.element.off('keydown', this.__formatter);

      // Performs as-you-type formatting of numerical inputs by inserting commas
      // after every third digit and disallowing input of leading zeros and non-digit
      // characters except for dots in decimal fields.
      this.element.on('keydown', this.__formatter = function(e){
        // This beforechange event was not invoked by typing
        if(!e || typeof e !== 'object' || !e.which) {
          return;
        }
        // This will allow arrow keys, cut, copy, paste actions.
        // It will also allow any input for browsers < IE8 that don't support the selection api.
        if(_.include(allowedKeys, e.which) || !('selectionStart' in this && 'selectionEnd' in this) || e.metaKey) {
          return;
        }
        // 96-105 are numpad numbers
        if(e.which >= 96 && e.which <= 105) {
          e.which -= 48;
        }
        // 110 is the numpad decimal point
        if(e.which === Amp.keys.NUMPAD_DECIMAL) {
          e.which = Amp.keys.PERIOD
        }

        var ch = e.which === Amp.keys.PERIOD ? '.' : String.fromCharCode(e.which);
        if(regexValidChar.test(ch)){
          var i, tmpStart, parts, whole, decimal, highOrder,
              newValue    = "",
              caretOffset = 1,
              start       = this.selectionStart,
              newStart    = this.selectionStart,
              end         = this.selectionEnd,
              value       = this.value,
              value       = value.substr( 0, start ) + value.substr( end );

          // Disallow more than one dot
          if(ch === dot && value.indexOf(ch) !== -1){
            e.preventDefault()
            return false;
          }

          // Auto-prepend zeros when the user hits '.' on an empty field
          if(ch === dot && value.length === 0){
            ch = '0.';
            caretOffset += 1;
          }

          // Compensate caret position for removed commas
          tmpStart = start;
          for(i=0; i < start; i++){
            if( value[i] == "," ){
              tmpStart -= 1;
            }
            start = tmpStart;
          }

          // Disallow leading zeros for the whole number part.
          if( ch === '0' ){
            var testval = value.replace(/,/g, '');
            testval = testval.substr( 0, start ) + ch + testval.substr( start );
            if( regexLeadingZeros.test( testval ) ){
              e.preventDefault()
              return false;
            }
          }

          // Change the value of the field (add commas)
          value     = value.replace(/,/g, '');
          value     = value.substr(0, start) + ch + value.substr(start);
          parts     = value.split(".");
          whole     = parts[0];
          if(precision > 0 && parts[1] && parts[1].length > precision){
            e.preventDefault();
            return;
          }
          decimal   = parts[1] === undefined ? "" : "." + parts[1];
          highOrder = whole.length % 3;
          for(i=0; i<whole.length; ++i){
            if( i && ((i - highOrder) % 3 == 0) ){
              newValue += ",";
              if( i < start + 1 )
                caretOffset += 1;
            }
            newValue += whole[i];
          }

          newValue += decimal;
          newNumVal = parseFloat(newValue.replace(/,/g, ''), 10);

          // We need to programatically limit the length since the input is value changes programatically
          if( (maxlength && newValue.length > maxlength) ) {
            return false;
          }

          this.value = newValue;
          this.selectionStart = this.selectionEnd = start + caretOffset;
        }

        e && e.preventDefault && e.preventDefault();
        return false;
      });

      return this;
    },

    clamp: function(min, max){
      this.options.min = isNaN('' + min) ? null : min;
      this.options.max = isNaN('' + max) ? null: max;
      return this;
    }
  });

  $(function() {
    $(document.body)
    .delegate('input.amp:not([disabled])', {
      keyup: function (e) {
        var self = $(this), value = self.val();
        if(self.data('valBeforeType') + "" !== value + "") {
          self.amp().trigger('type', value, e);
        }
        $(this).data('valBeforeType', this.value);
      },

      focus: function (e) {
        $(this).data('valBeforeEdit', $(this).amp().val());
        $(this).data('valBeforeType', $(this).val());
      }
    })

    .delegate('input.amp:not(.amp-date):not([disabled]):not(.amp-combo)', 'blur', function (e) {
      var self = $(this), amp = self.amp();
      amp.__set(amp.val(), false, self.data('valBeforeEdit'));
    });
  });

  Amp.controls.input  = Input;
  Amp.controls.text   = TextInput;
  Amp.controls.number = NumberInput;
  Amp.registerMethods(['__reformat', 'setFormat', 'clamp']);
})(window.jQuery, window.Amp);