text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "modules/bluetooth/BluetoothRemoteGATTServer.h"

#include "bindings/core/v8/CallbackPromiseAdapter.h"
#include "bindings/core/v8/ScriptPromise.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "core/dom/DOMException.h"
#include "core/dom/ExceptionCode.h"
#include "core/events/Event.h"
#include "modules/bluetooth/BluetoothError.h"
#include "modules/bluetooth/BluetoothRemoteGATTService.h"
#include "modules/bluetooth/BluetoothSupplement.h"
#include "modules/bluetooth/BluetoothUUID.h"
#include "public/platform/modules/bluetooth/WebBluetooth.h"

namespace blink {

namespace {

const char kGATTServerDisconnected[] = "GATT Server disconnected while retrieving services.";
const char kGATTServerNotConnected[] = "GATT Server is disconnected. Cannot retrieve services.";

}

BluetoothRemoteGATTServer::BluetoothRemoteGATTServer(BluetoothDevice* device)
    : m_device(device)
    , m_connected(false)
{
}

BluetoothRemoteGATTServer* BluetoothRemoteGATTServer::create(BluetoothDevice* device)
{
    return new BluetoothRemoteGATTServer(device);
}

void BluetoothRemoteGATTServer::AddToActiveAlgorithms(ScriptPromiseResolver* resolver)
{
    auto result = m_activeAlgorithms.add(resolver);
    CHECK(result.isNewEntry);
}

bool BluetoothRemoteGATTServer::RemoveFromActiveAlgorithms(ScriptPromiseResolver* resolver)
{
    if (!m_activeAlgorithms.contains(resolver)) {
        return false;
    }
    m_activeAlgorithms.remove(resolver);
    return true;
}

DEFINE_TRACE(BluetoothRemoteGATTServer)
{
    visitor->trace(m_activeAlgorithms);
    visitor->trace(m_device);
}

class ConnectCallback : public WebBluetoothRemoteGATTServerConnectCallbacks {
public:
    ConnectCallback(BluetoothDevice* device, ScriptPromiseResolver* resolver)
        : m_device(device)
        , m_resolver(resolver) {}

    void onSuccess() override
    {
        if (!m_resolver->getExecutionContext() || m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
            return;
        m_device->gatt()->setConnected(true);
        m_resolver->resolve(m_device->gatt());
    }

    void onError(int32_t error /* Corresponds to WebBluetoothError in web_bluetooth.mojom */) override
    {
        if (!m_resolver->getExecutionContext() || m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
            return;
        m_resolver->reject(BluetoothError::take(m_resolver, error));
    }
private:
    Persistent<BluetoothDevice> m_device;
    Persistent<ScriptPromiseResolver> m_resolver;
};

ScriptPromise BluetoothRemoteGATTServer::connect(ScriptState* scriptState)
{
    WebBluetooth* webbluetooth = BluetoothSupplement::fromScriptState(scriptState);
    if (!webbluetooth)
        return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError));

    ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
    ScriptPromise promise = resolver->promise();
    webbluetooth->connect(device()->id(), device(), new ConnectCallback(device(), resolver));
    return promise;
}

void BluetoothRemoteGATTServer::disconnect(ScriptState* scriptState)
{
    if (!m_connected)
        return;
    m_connected = false;
    ClearActiveAlgorithms();
    WebBluetooth* webbluetooth = BluetoothSupplement::fromScriptState(scriptState);
    webbluetooth->disconnect(device()->id());
    device()->dispatchEvent(Event::createBubble(EventTypeNames::gattserverdisconnected));
}

// Class that allows us to resolve the promise with a single service or
// with a vector owning the services.
class GetPrimaryServicesCallback : public WebBluetoothGetPrimaryServicesCallbacks {
public:
    GetPrimaryServicesCallback(BluetoothDevice* device, mojom::blink::WebBluetoothGATTQueryQuantity quantity, ScriptPromiseResolver* resolver)
        : m_device(device)
        , m_quantity(quantity)
        , m_resolver(resolver)
    {
        // We always check that the device is connected before constructing this
        // object.
        CHECK(m_device->gatt()->connected());
        m_device->gatt()->AddToActiveAlgorithms(m_resolver.get());
    }

    void onSuccess(const WebVector<WebBluetoothRemoteGATTService*>& webServices) override
    {
        if (!m_resolver->getExecutionContext() || m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
            return;

        // If the resolver is not in the set of ActiveAlgorithms then the frame
        // disconnected so we reject.
        if (!m_device->gatt()->RemoveFromActiveAlgorithms(m_resolver.get())) {
            m_resolver->reject(DOMException::create(NetworkError, kGATTServerDisconnected));
            return;
        }

        if (m_quantity == mojom::blink::WebBluetoothGATTQueryQuantity::SINGLE) {
            DCHECK_EQ(1u, webServices.size());
            m_resolver->resolve(BluetoothRemoteGATTService::take(m_resolver, wrapUnique(webServices[0]), m_device));
            return;
        }

        HeapVector<Member<BluetoothRemoteGATTService>> services;
        services.reserveInitialCapacity(webServices.size());
        for (WebBluetoothRemoteGATTService* webService : webServices) {
            services.append(BluetoothRemoteGATTService::take(m_resolver, wrapUnique(webService), m_device));
        }
        m_resolver->resolve(services);
    }

    void onError(int32_t error /* Corresponds to WebBluetoothError in web_bluetooth.mojom */) override
    {
        if (!m_resolver->getExecutionContext() || m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
            return;

        m_device->gatt()->RemoveFromActiveAlgorithms(m_resolver.get());
        m_resolver->reject(BluetoothError::take(m_resolver, error));
    }
private:
    Persistent<BluetoothDevice> m_device;
    mojom::blink::WebBluetoothGATTQueryQuantity m_quantity;
    Persistent<ScriptPromiseResolver> m_resolver;
};

ScriptPromise BluetoothRemoteGATTServer::getPrimaryService(ScriptState* scriptState, const StringOrUnsignedLong& service, ExceptionState& exceptionState)
{
    String serviceUUID = BluetoothUUID::getService(service, exceptionState);
    if (exceptionState.hadException())
        return exceptionState.reject(scriptState);

    return getPrimaryServicesImpl(scriptState, mojom::blink::WebBluetoothGATTQueryQuantity::SINGLE, serviceUUID);
}

ScriptPromise BluetoothRemoteGATTServer::getPrimaryServices(ScriptState* scriptState, const StringOrUnsignedLong& service, ExceptionState& exceptionState)
{
    String serviceUUID = BluetoothUUID::getService(service, exceptionState);
    if (exceptionState.hadException())
        return exceptionState.reject(scriptState);

    return getPrimaryServicesImpl(scriptState, mojom::blink::WebBluetoothGATTQueryQuantity::MULTIPLE, serviceUUID);
}

ScriptPromise BluetoothRemoteGATTServer::getPrimaryServices(ScriptState* scriptState, ExceptionState&)
{
    return getPrimaryServicesImpl(scriptState, mojom::blink::WebBluetoothGATTQueryQuantity::MULTIPLE);
}

ScriptPromise BluetoothRemoteGATTServer::getPrimaryServicesImpl(ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, String servicesUUID)
{
    if (!connected()) {
        return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NetworkError, kGATTServerNotConnected));
    }

    ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
    ScriptPromise promise = resolver->promise();

    WebBluetooth* webbluetooth = BluetoothSupplement::fromScriptState(scriptState);
    webbluetooth->getPrimaryServices(device()->id(), static_cast<int32_t>(quantity), servicesUUID, new GetPrimaryServicesCallback(device(), quantity, resolver));

    return promise;
}

} // namespace blink


text:
--TEST--
Mosquitto\Client::connect()
--SKIPIF--
if (!extension_loaded('mosquitto')) die('skip - Mosquitto extension not available');
--FILE--
<?php
include(dirname(__DIR__) . '/setup.php');

/* No parameters */
try {
    $client = new Mosquitto\Client();
    $client->connect();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Invalid hostname */
try {
    $client = new Mosquitto\Client();
    $client->connect(false);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Invalid hostname */
try {
    $client = new Mosquitto\Client();
    $client->connect(":^(%^*:");
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Invalid port */
try {
    $client = new Mosquitto\Client();
    $client->connect(TEST_MQTT_HOST, 0);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Invalid port */
try {
    $client = new Mosquitto\Client();
    $client->connect(TEST_MQTT_HOST, new stdClass);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Invalid keepalive */
try {
    $client = new Mosquitto\Client();
    $client->connect(TEST_MQTT_HOST, TEST_MQTT_PORT, new stdClass);
    var_dump($client);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Invalid bind address */
try {
    $client = new Mosquitto\Client();
    $client->connect(TEST_MQTT_HOST, TEST_MQTT_PORT, 0, '^(%%^&*');
    var_dump($client);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Zero keepalive (OK) */
try {
    $client = new Mosquitto\Client();
    $client->connect(TEST_MQTT_HOST, TEST_MQTT_PORT, 0);
    var_dump($client);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* 10-second keepalive */
try {
    $client = new Mosquitto\Client();
    $client->connect(TEST_MQTT_HOST, TEST_MQTT_PORT, 10);
    var_dump($client);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Bind to 127.0.0.1 - should work if connecting to localhost */
try {
    $client = new Mosquitto\Client();
    $client->connect(TEST_MQTT_HOST, TEST_MQTT_PORT, 0, '127.0.0.1');
    var_dump($client);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

/* Specify just the host */
try {
    $client = new Mosquitto\Client();
    $client->connect(TEST_MQTT_HOST);
    var_dump($client);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}

?>
--EXPECTF--
Mosquitto\Client::connect() expects at least 1 parameter, 0 given
%s error.
%s error.
Invalid function arguments provided.
Mosquitto\Client::connect() expects parameter 2 to be %s, object given
Mosquitto\Client::connect() expects parameter 3 to be %s, object given
%s error.
object(Mosquitto\Client)#%d (%d) {
}
object(Mosquitto\Client)#%d (%d) {
}
object(Mosquitto\Client)#%d (%d) {
}
object(Mosquitto\Client)#%d (%d) {
}

redpajama_set_name: RedPajamaGithub


text:
from telemetry.internal.actions import page_action
from telemetry.internal.actions import utils
from telemetry.util import js_template

class PinchAction(page_action.PageAction):

  def __init__(self,
               selector=None,
               text=None,
               element_function=None,
               left_anchor_ratio=0.5,
               top_anchor_ratio=0.5,
               scale_factor=None,
               speed_in_pixels_per_second=800,
               synthetic_gesture_source=page_action.GESTURE_SOURCE_DEFAULT):
    super(PinchAction, self).__init__()
    self._selector = selector
    self._text = text
    self._element_function = element_function
    self._left_anchor_ratio = left_anchor_ratio
    self._top_anchor_ratio = top_anchor_ratio
    self._scale_factor = scale_factor
    self._speed = speed_in_pixels_per_second
    self._synthetic_gesture_source = (
        'chrome.gpuBenchmarking.%s_INPUT' % synthetic_gesture_source)

    if (self._selector is None and self._text is None and
        self._element_function is None):
      self._element_function = 'document.body'

  def WillRunAction(self, tab):
    utils.InjectJavaScript(tab, 'gesture_common.js')
    utils.InjectJavaScript(tab, 'pinch.js')

    # Fail if browser doesn't support synthetic pinch gestures.
    if not tab.EvaluateJavaScript('window.__PinchAction_SupportedByBrowser()'):
      raise page_action.PageActionNotSupported(
          'Synthetic pinch not supported for this browser')

    tab.ExecuteJavaScript("""
        window.__pinchActionDone = false;
        window.__pinchAction = new __PinchAction(function() {
          window.__pinchActionDone = true;
        });""")

  @staticmethod
  def _GetDefaultScaleFactorForPage(tab):
    current_scale_factor = tab.EvaluateJavaScript(
        'window.outerWidth / window.innerWidth')
    return 3.0 / current_scale_factor

  def RunAction(self, tab):
    scale_factor = (self._scale_factor if self._scale_factor else
                    PinchAction._GetDefaultScaleFactorForPage(tab))
    code = js_template.Render(
        """
        function(element, info) {
          if (!element) {
            throw Error('Cannot find element: ' + info);
          }
          window.__pinchAction.start({
            element: element,
            left_anchor_ratio: {{ left_anchor_ratio }},
            top_anchor_ratio: {{ top_anchor_ratio }},
            scale_factor: {{ scale_factor }},
            speed: {{ speed }}
          });
        }""",
        left_anchor_ratio=self._left_anchor_ratio,
        top_anchor_ratio=self._top_anchor_ratio,
        scale_factor=scale_factor,
        speed=self._speed)
    page_action.EvaluateCallbackWithElement(
        tab,
        code,
        selector=self._selector,
        text=self._text,
        element_function=self._element_function)
    tab.WaitForJavaScriptCondition('window.__pinchActionDone', timeout=60)


text:
{% extends 'layout.html' %}

{% block header %}

Perfil

Ajustes

Salir

			Logo

Galeriacollections

Subir Archivosfile_upload

{{user.userName}}arrow_drop_down

{% endblock %}

{% block title %}

Edición de Imagenes

{% endblock %}

{% block form %}
<input type="hidden" value="{{imgSrc}}" id="myImageSrc">
<input type="hidden" value="{{imgName}}" id="myImageName">

		<canvas id="myCanvas" width="750" height="400">
			Tu navegador no soporta canvas.
		</canvas>

				edit

insert_chart

autorenew

file_download

color_lens

Seleccione el color del lapiz

{% endblock %}

{% block scripts %}

{% endblock %}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Stigmina phragmidioides Speg.

### Remarks
null


text:
<?php

namespace Tsugi\Util;

use \Tsugi\OAuth\TrivialOAuthDataStore;
use \Tsugi\OAuth\OAuthServer;
use \Tsugi\OAuth\OAuthSignatureMethod_HMAC_SHA1;
use \Tsugi\OAuth\OAuthSignatureMethod_HMAC_SHA256;
use \Tsugi\OAuth\OAuthRequest;
use \Tsugi\OAuth\OAuthConsumer;
use \Tsugi\OAuth\OAuthUtil;

use \Tsugi\Util\Net;

/**
 * This is a general purpose LTI class with no Tsugi-specific dependencies.
 *
 * This class handles the protocol and OAuth validation and does not
 * deal with how to use LTI data during the runtime of the tool.
 *
 */
class LTI {

    // Returns true if this is a Basic LTI message
    // with minimum values to meet the protocol
    public static function isRequest() {
        if ( !isset($_REQUEST["lti_message_type"]) ) return false;
        if ( !isset($_REQUEST["lti_version"]) ) return false;
        $good_message_type = $_REQUEST["lti_message_type"] == "basic-lti-launch-request" ||
            $_REQUEST["lti_message_type"] == "ToolProxyReregistrationRequest";
        $good_lti_version = $_REQUEST["lti_version"] == "LTI-1p0" || $_REQUEST["lti_version"] == "LTI-2p0";
        if ($good_message_type and $good_lti_version ) return(true);
        return false;
    }

    /**
     * Verify the message signature for this request
     *
     * @return mixed This returns true if the request verified.  If the request did not verify,
     * this returns an array with the first element as an error string, and the second element
     * as the base string of the request.
     */
    public static function verifyKeyAndSecret($key, $secret) {
        global $LastOAuthBodyBaseString;
        if ( ! ($key && $secret) ) return array("Missing key or secret", "");
        $store = new TrivialOAuthDataStore();
        $store->add_consumer($key, $secret);

        $server = new OAuthServer($store);

        $method = new OAuthSignatureMethod_HMAC_SHA1();
        $server->add_signature_method($method);
        $method = new OAuthSignatureMethod_HMAC_SHA256();
        $server->add_signature_method($method);
        $request = OAuthRequest::from_request();

        $LastOAuthBodyBaseString = $request->get_signature_base_string();

        try {
            $server->verify_request($request);
            return true;
        } catch (\Exception $e) {
            return array($e->getMessage(), $LastOAuthBodyBaseString);
        }
    }
    public static function signParameters($oldparms, $endpoint, $method, $oauth_consumer_key, $oauth_consumer_secret,
        $submit_text = false, $org_id = false, $org_desc = false)
    {
        global $LastOAuthBodyBaseString;
        $parms = $oldparms;
        if ( ! isset($parms["lti_version"]) ) $parms["lti_version"] = "LTI-1p0";
        if ( ! isset($parms["lti_message_type"]) ) $parms["lti_message_type"] = "basic-lti-launch-request";
        if ( ! isset($parms["oauth_callback"]) ) $parms["oauth_callback"] = "about:blank";
        if ( $org_id ) $parms["tool_consumer_instance_guid"] = $org_id;
        if ( $org_desc ) $parms["tool_consumer_instance_description"] = $org_desc;
        if ( $submit_text ) $parms["ext_submit"] = $submit_text;

        $test_token = '';

        $oauth_signature_method = isset($parms['oauth_signature_method']) ? $parms['oauth_signature_method'] : false;

        $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
        if ( $oauth_signature_method == "HMAC-SHA256" ) {
            $hmac_method = new OAuthSignatureMethod_HMAC_SHA256();
        }
        $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);

        $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
        $acc_req->sign_request($hmac_method, $test_consumer, $test_token);

        // Pass this back up "out of band" for debugging
        $LastOAuthBodyBaseString = $acc_req->get_signature_base_string();

        $newparms = $acc_req->get_parameters();

      // Don't want to pull GET parameters into POST data so
        // manually pull back the oauth_ parameters
      foreach($newparms as $k => $v ) {
            if ( strpos($k, "oauth_") === 0 ) {
                $parms[$k] = $v;
            }
        }

        return $parms;
    }

    public static function postLaunchHTML($newparms, $endpoint, $debug=false, $iframeattr=false) {
        global $LastOAuthBodyBaseString;
        $r = "
\n";
        if ( $iframeattr =="_blank" ) {
            $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" target=\"_blank\" encType=\"application/x-www-form-urlencoded\">\n" ;
        } else if ( $iframeattr ) {
            $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" target=\"basicltiLaunchFrame\" encType=\"application/x-www-form-urlencoded\">\n" ;
        } else {
            $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n" ;
        }
        $submit_text = $newparms['ext_submit'];
        foreach($newparms as $key => $value ) {
            $key = htmlspec_utf8($key);
            $value = htmlspec_utf8($value);
            if ( $key == "ext_submit" ) {
                $r .= "<input type=\"submit\" name=\"";
            } else {
                $r .= "<input type=\"hidden\" name=\"";
            }
            $r .= $key;
            $r .= "\" value=\"";
            $r .= $value;
            $r .= "\"/>\n";
        }
        if ( $debug ) {
            $r .= "\n";
            $r .= "";
            $r .= self::get_string("toggle_debug_data","basiclti")."\n";
            $r .= "
\n";
            $r .=  "".self::get_string("basiclti_endpoint","basiclti")."
\n";
            $r .= $endpoint . "
\n
\n";
            $r .=  "".self::get_string("basiclti_parameters","basiclti")."
\n";
            foreach($newparms as $key => $value ) {
                $key = htmlspec_utf8($key);
                $value = htmlspec_utf8($value);
                $r .= "$key = $value
\n";
            }
            $r .= "
\n";
            $r .= "
".self::get_string("basiclti_base_string","basiclti")."
\n".$LastOAuthBodyBaseString."
\n";
            $r .= "
\n";
        }
        $r .= "</form>\n";
        if ( $iframeattr && $iframeattr != '_blank' ) {
            $r .= "\n
".self::get_string("frames_required","basiclti")."
\n\n";
        }
        if ( ! $debug ) {
            $ext_submit = "ext_submit";
            $ext_submit_text = $submit_text;
            $r .= "  \n";
        }
        $r .= "
\n";
        return $r;
    }

    /* This is a bit of homage to Moodle's pattern of internationalisation */
    public static function get_string($key,$bundle) {
        return $key;
    }

    public static function bodyRequest($url, $method, $data, $optional_headers = null)
    {
      if ($optional_headers !== null) {
         $header = $optional_headers . "\r\n";
      }
      $header = $header . "Content-Type: application/x-www-form-urlencoded\r\n";

      return Net::doBody($url,$method,$data,$header);
    }

    public static function addCustom(&$parms, $custom) {
        foreach ( $custom as $key => $val) {
          $key = strtolower($key);
          $nk = "";
          for($i=0; $i < strlen($key); $i++) {
            $ch = substr($key,$i,1);
            if ( $ch >= "a" && $ch <= "z" ) $nk .= $ch;
            else if ( $ch >= "0" && $ch <= "9" ) $nk .= $ch;
            else $nk .= "_";
          }
          $parms["custom_".$nk] = $val;
        }
    }

    public static function getLastOAuthBodyBaseString() {
        global $LastOAuthBodyBaseString;
        return $LastOAuthBodyBaseString;
    }

    public static function getLastOAuthBodyHashInfo() {
        global $LastOAuthBodyHashInfo;
        return $LastOAuthBodyHashInfo;
    }

    public static function getOAuthKeyFromHeaders()
    {
        $request_headers = OAuthUtil::get_headers();
        // print_r($request_headers);

        if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
            $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);

            // echo("HEADER PARMS=\n");
            // print_r($header_parameters);
            return $header_parameters['oauth_consumer_key'];
        }
        return false;
    }

    public static function handleOAuthBodyPOST($oauth_consumer_key, $oauth_consumer_secret)
    {
        $request_headers = OAuthUtil::get_headers();
        // print_r($request_headers);

        // Must reject application/x-www-form-urlencoded
        if ($request_headers['Content-Type'] == 'application/x-www-form-urlencoded' ) {
            throw new \Exception("OAuth request body signing must not use application/x-www-form-urlencoded");
        }

        if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
            $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);

            // echo("HEADER PARMS=\n");
            // print_r($header_parameters);
            $oauth_body_hash = $header_parameters['oauth_body_hash'];
            // echo("OBH=".$oauth_body_hash."\n");
        }

        if ( ! isset($oauth_body_hash)  ) {
            throw new \Exception("OAuth request body signing requires oauth_body_hash body");
        }

        // Check the key and secret.
        $retval = self::verifyKeyAndSecret($oauth_consumer_key, $oauth_consumer_secret);
        if ( $retval !== true ) {
            throw new \Exception("OAuth signature failed: " . $retval[0]);
        }

        $postdata = file_get_contents('php://input');
        // echo($postdata);

        $hash = base64_encode(sha1($postdata, TRUE));

        global $LastOAuthBodyHashInfo;
        $LastOAuthBodyHashInfo = "hdr_hash=$oauth_body_hash body_len=".strlen($postdata)." body_hash=$hash";

        if ( $hash != $oauth_body_hash ) {
            throw new \Exception("OAuth oauth_body_hash mismatch");
        }

        return $postdata;
    }

    public static function sendOAuthGET($endpoint, $oauth_consumer_key, $oauth_consumer_secret, $accept_type, $signature=false)
    {
        $test_token = '';
        $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
        if ( $signature == "HMAC-SHA256" ) {
            $hmac_method = new OAuthSignatureMethod_HMAC_SHA256();
        }
        $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
        $parms = array();

        $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, "GET", $endpoint, $parms);
        $acc_req->sign_request($hmac_method, $test_consumer, $test_token);

        // Pass this back up "out of band" for debugging
        global $LastOAuthBodyBaseString;
        $LastOAuthBodyBaseString = $acc_req->get_signature_base_string();

        $header = $acc_req->to_header();
        $header = $header . "\r\nAccept: " . $accept_type . "\r\n";

        global $LastGETHeader;
        $LastGETHeader = $header;

        return Net::doGet($endpoint,$header);
    }

    public static function sendOAuthBody($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret,
	$content_type, $body, $more_headers=false, $signature=false)
    {
        $hash = base64_encode(sha1($body, TRUE));

        $parms = array('oauth_body_hash' => $hash);

        $test_token = '';

        $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
        if ( $signature == "HMAC-SHA256" ) {
            $hmac_method = new OAuthSignatureMethod_HMAC_SHA256();
        }

        $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);

        $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
        $acc_req->sign_request($hmac_method, $test_consumer, $test_token);

        // Pass this back up "out of band" for debugging
        global $LastOAuthBodyBaseString;
        $LastOAuthBodyBaseString = $acc_req->get_signature_base_string();

        $header = $acc_req->to_header();
        $header = $header . "\r\nContent-Type: " . $content_type . "\r\n";
        if ( $more_headers === false ) $more_headers = array();
        foreach ($more_headers as $more ) {
            $header = $header . $more . "\r\n";
        }

        return Net::doBody($endpoint, $method, $body,$header);
    }

    /**
     * Retrieve a grade using the LTI 1.1 protocol (POX)
     *
     * This retrieves a grade using the Plain-Old-XML protocol from
     * IMS LTI 1.1
     *
     * @param debug_log This can either be false or an empty array.  If
     * this is an array, it is filled with data as the steps progress.
     * Each step is an array with a string message as the first element
     * and optional debug detail (i.e. like a post body) as the second
     * element.
     *
     * @return mixed If things go well this returns a float of the existing grade.
     * If this goes badly, this returns a string with an error message.
     */
    public static function getPOXGrade($sourcedid, $service, $key_key, $secret, &$debug_log=false) {
        global $LastPOXGradeResponse;
        global $LastPOXGradeParse;
        global $LastPOXGradeError;
        $LastPOXGradeResponse = false;
        $LastPOXGradeParse = false;
        $LastPOXGradeError = false;

        $content_type = "application/xml";
        $sourcedid = htmlspecialchars($sourcedid);

        $operation = 'readResultRequest';
        $postBody = str_replace(
            array('SOURCEDID', 'OPERATION','MESSAGE'),
            array($sourcedid, $operation, uniqid()),
            self::getPOXRequest());

        if ( is_array($debug_log) ) $debug_log[] = array('Loading grade from '.$service.' sourcedid='.$sourcedid);
        if ( is_array($debug_log) )  $debug_log[] = array('Grade API Request',$postBody);

        $response = self::sendOAuthBody("POST", $service, $key_key, $secret,
            $content_type, $postBody);
        $LastPOXGradeResponse = $response;
        if ( is_array($debug_log) )  $debug_log[] = array("Grade API Response",$response);

        $status = "Failure to retrieve grade";
        if ( strpos($response, '<?xml') !== 0 ) {
            error_log("Fatal XML Grade Read: ".session_id()." sourcedid=".$sourcedid);
            error_log("Detail: service=".$service." key_key=".$key_key);
            error_log("Response: ".$response);
            return "Unable to read XML from web service.";
        }

        $grade = false;
        try {
            $retval = self::parseResponse($response);
            $LastPOXGradeParse = $retval;
            if ( is_array($retval) ) {
                if ( isset($retval['imsx_codeMajor']) && $retval['imsx_codeMajor'] == 'success') {
                    if ( isset($retval['textString'])) $grade = $retval['textString']+0.0;
                } else if ( isset($retval['imsx_description']) ) {
                    $LastPOXGradeError = $retval['imsx_description'];
                    error_log("Grade read failure: "+$LastPOXGradeError);
                    if ( is_array($debug_log) )  $debug_log[] = array("Grade read failure: "+$LastPOXGradeError);
                    return $LastPOXGradeError;
                }
            }
        } catch(Exception $e) {
            $LastPOXGradeError = $e->getMessage();
            error_log("Grade read failure: "+$LastPOXGradeError);
            if ( is_array($debug_log) )  $debug_log[] = array("Exception: ".$status);
            return $LastPOXGradeError;
        }
        return $grade;
    }

    /**
     * Send a grade using the LTI 1.1 protocol (POX)
     *
     * This sends a grade using the Plain-Old-XML protocol from
     * IMS LTI 1.1
     *
     * @param debug_log This can either be false or an empty array.  If
     * this is an array, it is filled with data as the steps progress.
     * Each step is an array with a string message as the first element
     * and optional debug detail (i.e. like a post body) as the second
     * element.
     *
     * @return mixed If things go well this returns true.
     * If this goes badly, this returns a string with an error message.
     */
    public static function sendPOXGrade($grade, $sourcedid, $service, $key_key, $secret, &$debug_log=false) {
        global $LastPOXGradeResponse;
        $LastPOXGradeResponse = false;

        $content_type = "application/xml";
        $sourcedid = htmlspecialchars($sourcedid);

        $operation = 'replaceResultRequest';
        $postBody = str_replace(
            array('SOURCEDID', 'GRADE', 'OPERATION','MESSAGE'),
            array($sourcedid, $grade.'', 'replaceResultRequest', uniqid()),
            self::getPOXGradeRequest());

        if ( is_array($debug_log) ) $debug_log[] = array('Sending '.$grade.' to '.$service.' sourcedid='.$sourcedid);

        if ( is_array($debug_log) )  $debug_log[] = array('Grade API Request',$postBody);

        $response = self::sendOAuthBody("POST", $service, $key_key, $secret,
            $content_type, $postBody);
        global $LastOAuthBodyBaseString;
        $lbs = $LastOAuthBodyBaseString;
        if ( is_array($debug_log) )  $debug_log[] = array("Grade API Response",$response);
        $LastPOXGradeResponse = $response;
        $status = "Failure to store grade";
        if ( strpos($response, '<?xml') !== 0 ) {
            error_log("Fatal XML Grade Update: ".session_id()." sourcedid=".$sourcedid);
            error_log("Detail: service=".$service." key_key=".$key_key);
            error_log("Response: ".$response);
            return $status;
        }
        try {
            $retval = self::parseResponse($response);
            if ( isset($retval['imsx_codeMajor']) && $retval['imsx_codeMajor'] == 'success') {
                $status = true;
            } else if ( isset($retval['imsx_description']) ) {
                $status = $retval['imsx_description'];
            }
        } catch(Exception $e) {
            $status = $e->getMessage();
            if ( is_array($debug_log) )  $debug_log[] = array("Exception: ".$status);
        }
        return $status;
    }

    public static function getPOXGradeRequest() {
        return '<?xml version = "1.0" encoding = "UTF-8"?>
    <imsx_POXEnvelopeRequest xmlns = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
      <imsx_POXHeader>
        <imsx_POXRequestHeaderInfo>
          <imsx_version>V1.0</imsx_version>
          <imsx_messageIdentifier>MESSAGE</imsx_messageIdentifier>
        </imsx_POXRequestHeaderInfo>
      </imsx_POXHeader>
      <imsx_POXBody>
        <OPERATION>
          <resultRecord>
            <sourcedGUID>
              <sourcedId>SOURCEDID</sourcedId>
            </sourcedGUID>
            <result>
              <resultScore>
                <language>en-us</language>
                <textString>GRADE</textString>
              </resultScore>
            </result>
          </resultRecord>
        </OPERATION>
      </imsx_POXBody>
    </imsx_POXEnvelopeRequest>';
    }

    /*  $postBody = str_replace(
          array('SOURCEDID', 'OPERATION','MESSAGE'),
          array($sourcedid, $operation, uniqid()),
          self::getPOXRequest());
    */
    public static function getPOXRequest() {
        return '<?xml version = "1.0" encoding = "UTF-8"?>
    <imsx_POXEnvelopeRequest xmlns = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
      <imsx_POXHeader>
        <imsx_POXRequestHeaderInfo>
          <imsx_version>V1.0</imsx_version>
          <imsx_messageIdentifier>MESSAGE</imsx_messageIdentifier>
        </imsx_POXRequestHeaderInfo>
      </imsx_POXHeader>
      <imsx_POXBody>
        <OPERATION>
          <resultRecord>
            <sourcedGUID>
              <sourcedId>SOURCEDID</sourcedId>
            </sourcedGUID>
          </resultRecord>
        </OPERATION>
      </imsx_POXBody>
    </imsx_POXEnvelopeRequest>';
    }

    /*     sprintf(getPOXResponse(),uniqid(),'success', "Score read successfully",$message_ref,$body);
    */

    public static function getPOXResponse() {
        return '<?xml version="1.0" encoding="UTF-8"?>
    <imsx_POXEnvelopeResponse xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
        <imsx_POXHeader>
            <imsx_POXResponseHeaderInfo>
                <imsx_version>V1.0</imsx_version>
                <imsx_messageIdentifier>%s</imsx_messageIdentifier>
                <imsx_statusInfo>
                    <imsx_codeMajor>%s</imsx_codeMajor>
                    <imsx_severity>status</imsx_severity>
                    <imsx_description>%s</imsx_description>
                    <imsx_messageRefIdentifier>%s</imsx_messageRefIdentifier>
                    <imsx_operationRefIdentifier>%s</imsx_operationRefIdentifier>
                </imsx_statusInfo>
            </imsx_POXResponseHeaderInfo>
        </imsx_POXHeader>
        <imsx_POXBody>%s
        </imsx_POXBody>
    </imsx_POXEnvelopeResponse>';
    }

    public static function replaceResultRequest($grade, $sourcedid, $endpoint, $oauth_consumer_key, $oauth_consumer_secret) {
        $method="POST";
        $content_type = "application/xml";
        $operation = 'replaceResultRequest';
        $postBody = str_replace(
            array('SOURCEDID', 'GRADE', 'OPERATION','MESSAGE'),
            array($sourcedid, $grade, $operation, uniqid()),
            self::getPOXGradeRequest());

        $response = sendOAuthBody("POST", $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $postBody);
        return parseResponse($response);
    }

    public static function parseResponse($response) {
        $retval = Array();
        try {
            $xml = new \SimpleXMLElement($response);
            $imsx_header = $xml->imsx_POXHeader->children();
            $parms = $imsx_header->children();
            $status_info = $parms->imsx_statusInfo;
            $retval['imsx_codeMajor'] = (string) $status_info->imsx_codeMajor;
            $retval['imsx_severity'] = (string) $status_info->imsx_severity;
            $retval['imsx_description'] = (string) $status_info->imsx_description;
            $retval['imsx_messageIdentifier'] = (string) $parms->imsx_messageIdentifier;
            $imsx_body = $xml->imsx_POXBody->children();
            $operation = $imsx_body->getName();
            $retval['response'] = $operation;
            $parms = $imsx_body->children();
        } catch (Exception $e) {
            throw new \Exception('Error: Unable to parse XML response' . $e->getMessage());
        }

        if ( $operation == 'readResultResponse' ) {
           try {
               $retval['language'] =(string) $parms->result->resultScore->language;
               $retval['textString'] = (string) $parms->result->resultScore->textString;
           } catch (Exception $e) {
                throw new \Exception("Error: Body parse error: ".$e->getMessage());
           }
        }
        return $retval;
    }

    /**
     * Send a grade using the JSON protocol from IMS LTI 2.x
     *
     * @param debug_log This can either be false or an empty array.  If
     * this is an array, it is filled with data as the steps progress.
     * Each step is an array with a string message as the first element
     * and optional debug detail (i.e. like a post body) as the second
     * element.
     *
     * @return mixed If things go well this returns true.
     * If this goes badly, this returns a string with an error message.
     */
    public static function sendJSONGrade($grade, $comment, $result_url, $key_key, $secret, &$debug_log=false) {
        global $LastJSONGradeResponse;
        $LastJSONGradeResponse = false;

        $content_type = "application/vnd.ims.lis.v2.result+json";

        if ( is_array($debug_log) ) $debug_log[] = array('Sending '.$grade.' to result_url='.$result_url);

        $addStructureRequest = self::getResultJSON($grade, $comment);

        $postBody = jsonIndent(json_encode($addStructureRequest));
        if ( is_array($debug_log) )  $debug_log[] = array('Grade JSON Request',$postBody);

        $response = self::sendOAuthBody("PUT", $result_url, $key_key,
            $secret, $content_type, $postBody);

        if ( is_array($debug_log) )  $debug_log[] = array('Grade JSON Response',$response);

        global $LastOAuthBodyBaseString;
        $lbs = $LastOAuthBodyBaseString;
        if ( is_array($debug_log) )  $debug_log[] = array('Our base string',$lbs);

        // TODO: Be smarter about this :)
        return true;
    }

    /**
     * Return an array suitable for sending to the LTI 2.x result_url
     */
    public static function getResultJSON($grade, $comment) {
        $resultArray = array(
            "@context" => "http://purl.imsglobal.org/ctx/lis/v2/Result",
            "@type" => "Result",
            "comment" => $comment,
            "resultScore" => array(
                "@type" => "decimal",
                "@value" => $grade
            ),
        );
        return $resultArray;
    }

    /**
     * Send setings data using the JSON protocol from IMS LTI 2.x
     *
     * @param debug_log This can either be false or an empty array.  If
     * this is an array, it is filled with data as the steps progress.
     * Each step is an array with a string message as the first element
     * and optional debug detail (i.e. like a post body) as the second
     * element.
     *
     * @return mixed If things go well this returns true.
     * If this goes badly, this returns a string with an error message.
     */
    public static function sendJSONSettings($settings, $settings_url, $key_key, $secret, &$debug_log=false) {
        $content_type = "application/vnd.ims.lti.v2.toolsettings.simple+json";

        if ( is_array($debug_log) ) $debug_log[] = array('Sending '.count($settings).' settings to settings_url='.$settings_url);
        // Make sure everything is a string
        $sendsettings = array();
        foreach ( $settings as $k => $v ) {
            $sendsettings[$k] = "".$v;
        }

        $postBody = jsonIndent(json_encode($sendsettings));
        if ( is_array($debug_log) )  $debug_log[] = array('Settings JSON Request',$postBody);

        $response = self::sendOAuthBody("PUT", $settings_url, $key_key,
            $secret, $content_type, $postBody);

        if ( is_array($debug_log) )  $debug_log[] = array('Settings JSON Response',$response);

        global $LastOAuthBodyBaseString;
        $lbs = $LastOAuthBodyBaseString;
        if ( is_array($debug_log) )  $debug_log[] = array('Our base string',$lbs);

        // TODO: Be better at error checking...
        return true;
    }

    /**
     * Send a JSON body LTI 2.x Style
     *
     * @param debug_log This can either be false or an empty array.  If
     * this is an array, it is filled with data as the steps progress.
     * Each step is an array with a string message as the first element
     * and optional debug detail (i.e. like a post body) as the second
     * element.
     *
     * @return mixed If things go well this returns true.
     * If this goes badly, this returns a string with an error message.
     */
    public static function sendJSONBody($method, $postBody, $content_type,
            $rest_url, $key_key, $secret, &$debug_log=false)
    {

        if ( is_array($debug_log) ) $debug_log[] = array('Sending '.strlen($postBody).' bytes to rest_url='.$rest_url);

        $response = self::sendOAuthBody($method, $rest_url, $key_key,
            $secret, $content_type, $postBody);

        if ( is_array($debug_log) )  $debug_log[] = array('Caliper JSON Response',$response);

        global $LastOAuthBodyBaseString;
        $lbs = $LastOAuthBodyBaseString;
        if ( is_array($debug_log) )  $debug_log[] = array('Our base string',$lbs);

        return true;
    }

    // Compares base strings, start of the mis-match
    // Returns true if the strings are identical
    // This is setup to be displayed in
 tags as newlines are added
    public static function compareBaseStrings($string1, $string2)
    {
    	if ( $string1 == $string2 ) return true;

    	$out2 = "";
    	$out1 = "";
        $chars = 0;
    	$oops = false;
        for($i=0; $i<strlen($string1)&&$i<strlen($string2); $i++) {
    		if ( $oops || $string1[$i] == $string2[$i] ) {
    			$out1 = $out1 . $string1[$i];
    			$out2 = $out2 . $string2[$i];
    		} else {
    			$out1 = $out1 . ' ->' . $string1[$i] .'<- ';
    			$out2 = $out2 . ' ->' . $string2[$i] .'<- ';
    			$oops = true;
    		}
    		$chars = $chars + 1;
    		if ( $chars > 79 ) {
    			$out1 .= "\n";
    			$out2 .= "\n";
    			$chars = 0;
    		}
    	}
    	if ( $i < strlen($string1) ) {
    		$out2 = $out2 . ' -> truncated ';
    		for($i=0; $i<strlen($string1); $i++) {
    			$out1 = $out1 . $string1[$i];
    			$chars = $chars + 1;
    			if ( $chars > 79 ) {
    				$out1 .= "\n";
    				$chars = 0;
    			}
    		}
    	}

    	if ( $i < strlen($string2) ) {
    		$out1 = $out1 . ' -> truncated ';
    		for($i=0; $i<strlen($string2); $i++) {
    			$out2 = $out2 . $string2[$i];
    			$chars = $chars + 2;
    			if ( $chars > 79 ) {
    				$out2 .= "\n";
    				$chars = 0;
    			}
    		}
    	}
    	return $out1 . "\n-------------\n" . $out2 . "\n";
    }
}


text:
=begin

Copyright 2012-2013 inBloom, Inc. and its affiliates.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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.

=end

require 'selenium-webdriver'

And /^there are "([^"]*)" Tabs$/ do |tabCount|
  allTabs = @driver.find_element(:id, "tabs").find_element(:tag_name, "ul")
  tab = allTabs.find_elements(:tag_name, "li")
  tabsToIgnore = 0
  # dashboard builder has the "+" tab that we need to ignore
  if (@driver.current_url.include? "builder")
    tabsToIgnore = 1
  end
  assert(tabCount.to_i == tab.length - tabsToIgnore, "Actual Tab Count: " + tab.length.to_s)
end

Given /^Tab "([^"]*)" is titled "([^"]*)"$/ do |tabIndex, tabTitle|
  allTabs = @driver.find_element(:id, "tabs").find_element(:tag_name, "ul")
  tab = allTabs.find_elements(:tag_name, "li")
  title = tab[tabIndex.to_i-1].find_element(:tag_name, "a")
  assert(title.text == tabTitle, "Actual Title: " + title.text)
end

When /^in Tab ID "([^"]*)", there is "([^"]*)" Panels$/ do |tabId, panelCount|
  element = @driver.find_element(:id, tabId)
  tabs = element.find_elements(:class, "panel")
  assert(tabs.length == panelCount.to_i, "Actual # of Panels: " + tabs.length.to_s)
end

Then /^in "([^"]*)" tab, there are "([^"]*)" Panels$/ do |tabName, panelCount|
  tab = getTab(tabName)
  actualPanels = tab.find_elements(:class, "panel")
  assert(actualPanels.length == panelCount.to_i, "Actual # of Panels: " + actualPanels.length.to_s)
end

When /^Tab has a title named "([^"]*)"$/ do |tabTitle|
  getTabIndex(tabTitle)
end

When /^I click on "([^"]*)" Tab$/ do |tabName|
  tab = getTabIndex(tabName)
  searchPattern = "a[href*='" + tab + "']"
  @driver.find_element(:css, searchPattern).click()
  @currentTab = getTab(tabName)
end

When /^I see the following tab order "(.*?)"$/ do |pages|
  checkPageOrder(pages)
end

def getTab(tabName)
  tabIndex = getTabIndex(tabName)
  return @driver.find_element(:id, tabIndex)
end

# Given a tabname, find the tab ID index to know which tab to read from
def getTabIndex(tabName)
  allTabs = @driver.find_element(:id, "tabs").find_element(:tag_name, "ul")
  links = allTabs.find_elements(:tag_name, "a")
  found = nil
  tabIndex = nil
  links.each do |tab|
    if (tab.text.include? tabName)
      found = tab
      url = tab["href"]
      i = url.index('#page') +1
      tabIndex = url[i, url.length-i]
      return tabIndex
    end
  end
  assert(found != nil, "Tab was not found")
end

# checks whether panel name exists in a particular tab
def checkPanelNameExists(tab, panelName)
  found = false;
  if tab.attribute("innerHTML").to_s.lstrip.rstrip.include?(panelName)
    found = true;
  end
  assert(found == true, "Panel Name is not found: " + panelName)
end

#Given a tabName and panelName, return the panel
#Note: exact panelName is not required
# if panelName is nil, return the first panel
def getPanel(tabName, panelName = nil)
  tab = getTab(tabName)
  panelsInTab = tab.find_elements(:class, "panel")
  if (panelName != nil)
    checkPanelNameExists(tab, panelName)
  else
    return panelsInTab[0]
  end

  panelsInTab.each do |panel|
    panelHeader = panel.find_element(:class, "panel-header")
    if (panelHeader.text.include? panelName)
      return panel
    end
  end
  assert(false, "Panel name: " + panelName + " is not found in tab: " + tabName)
end

def checkPageOrder(expectedPages)
  expected = expectedPages.split(';')
  actual = @driver.find_element(:id, "tabs").find_element(:tag_name, "ul").find_elements(:tag_name, "li")
  assert(expected.length == actual.length, "size of pages are not equal Actual: " + actual.length.to_s + " Expected: " + expected.length.to_s )
  for index in 0..actual.length - 1
    page = actual[index]
    pageText = page.find_element(:tag_name,"a").text
    assert((pageText.include? expected[index]), "Order is incorrect. Expected #{expected[index]} Actual #{pageText}")
  end
end


text:
/*
LCD4Bit v0.1 16/Oct/2006 neillzero http://abstractplain.net

What is this?
An arduino library for comms with HD44780-compatible LCD, in 4-bit mode (saves pins)

Sources:
- The original "LiquidCrystal" 8-bit library and tutorial
    http://www.arduino.cc/en/uploads/Tutorial/LiquidCrystal.zip
    http://www.arduino.cc/en/Tutorial/LCDLibrary
- DEM 16216 datasheet http://www.maplin.co.uk/Media/PDFs/N27AZ.pdf
- Massimo's suggested 4-bit code (I took initialization from here) http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1144924220/8
See also:
- glasspusher's code (probably more correct): http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1160586800/0#0

Tested only with a DEM 16216 (maplin "N27AZ" - http://www.maplin.co.uk/Search.aspx?criteria=N27AZ)
If you use this successfully, consider feeding back to the arduino wiki with a note of which LCD it worked on.

Usage:
see the examples folder of this library distribution.

*/

#include "LCD4Bit_mod.h"
#include "arduino.h"		//all things wiring / arduino

extern "C" {
  #include <stdio.h>		//not needed yet
  #include <string.h>		//needed for strlen()
  #include <inttypes.h>
}

//command bytes for LCD
#define CMD_CLR		0x01
#define CMD_RIGHT	0x1C
#define CMD_LEFT	0x18
#define CMD_HOME	0x02

// --------- PINS -------------------------------------
//is the RW pin of the LCD under our control?  If we're only ever going to write to the LCD, we can use one less microcontroller pin, and just tie the LCD pin to the necessary signal, high or low.
//this stops us sending signals to the RW pin if it isn't being used.
int USING_RW = false;

//RS, RW and Enable can be set to whatever you like
int RS = 8;
int RW = 11;
int Enable = 9;
//DB should be an unseparated group of pins  - because of lazy coding in pushNibble()
int DB[] = {4, 5, 6, 7};  //wire these to DB4~7 on LCD.

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

//how many lines has the LCD? (don't change here - specify on calling constructor)
int g_num_lines = 2;

//pulse the Enable pin high (for a microsecond).
//This clocks whatever command or data is in DB4~7 into the LCD controller.
void LCD4Bit_mod::pulseEnablePin(){
  digitalWrite(Enable,LOW);
  delayMicroseconds(1);
  // send a pulse to enable
  digitalWrite(Enable,HIGH);
  delayMicroseconds(1);
  digitalWrite(Enable,LOW);
  delay(1);  // pause 1 ms.  TODO: what delay, if any, is necessary here?
}

//push a nibble of data through the the LCD's DB4~7 pins, clocking with the Enable pin.
//We don't care what RS and RW are, here.
void LCD4Bit_mod::pushNibble(int value){
  int val_nibble= value & 0x0F;  //clean the value.  (unnecessary)

  for (int i=DB[0]; i <= DB[3]; i++) {
    digitalWrite(i,val_nibble & 01);
    val_nibble >>= 1;
  }
  pulseEnablePin();
}

//push a byte of data through the LCD's DB4~7 pins, in two steps, clocking each with the enable pin.
void LCD4Bit_mod::pushByte(int value){
  int val_lower = value & 0x0F;
  int val_upper = value >> 4;
  pushNibble(val_upper);
  pushNibble(val_lower);
}

//stuff the library user might call---------------------------------
//constructor.  num_lines must be 1 or 2, currently.
LCD4Bit_mod::LCD4Bit_mod (int num_lines) {
  g_num_lines = num_lines;
  if (g_num_lines < 1 || g_num_lines > 2)
  {
    g_num_lines = 1;
  }
}

void LCD4Bit_mod::commandWriteNibble(int nibble) {
  digitalWrite(RS, LOW);
  if (USING_RW) { digitalWrite(RW, LOW); }
  pushNibble(nibble);
}

void LCD4Bit_mod::commandWrite(int value) {
  digitalWrite(RS, LOW);
  if (USING_RW) { digitalWrite(RW, LOW); }
  pushByte(value);
  //TODO: perhaps better to add a delay after EVERY command, here.  many need a delay, apparently.
}

//print the given character at the current cursor position. overwrites, doesn't insert.
void LCD4Bit_mod::print(int value) {
  //set the RS and RW pins to show we're writing data
  digitalWrite(RS, HIGH);
  if (USING_RW) { digitalWrite(RW, LOW); }

  //let pushByte worry about the intricacies of Enable, nibble order.
  pushByte(value);
}

//print the given string to the LCD at the current cursor position.  overwrites, doesn't insert.
//While I don't understand why this was named printIn (PRINT IN?) in the original LiquidCrystal library, I've preserved it here to maintain the interchangeability of the two libraries.
void LCD4Bit_mod::printIn(char msg[]) {
  uint8_t i;  //fancy int.  avoids compiler warning when comparing i with strlen()'s uint8_t
  for (i=0;i < strlen(msg);i++){
    print(msg[i]);
  }
}

//send the clear screen command to the LCD
void LCD4Bit_mod::clear(){
  commandWrite(CMD_CLR);
  delay(1);
}

// initiatize lcd after a short pause
//while there are hard-coded details here of lines, cursor and blink settings, you can override these original settings after calling .init()
void LCD4Bit_mod::init () {
  pinMode(Enable,OUTPUT);
  pinMode(RS,OUTPUT);
  if (USING_RW) { pinMode(RW,OUTPUT); }
  pinMode(DB[0],OUTPUT);
  pinMode(DB[1],OUTPUT);
  pinMode(DB[2],OUTPUT);
  pinMode(DB[3],OUTPUT);

  delay(50);

  //The first 4 nibbles and timings are not in my DEM16217 SYH datasheet, but apparently are HD44780 standard...
  commandWriteNibble(0x03);
  delay(5);
  commandWriteNibble(0x03);
  delayMicroseconds(100);
  commandWriteNibble(0x03);
  delay(5);

  // needed by the LCDs controller
  //this being 2 sets up 4-bit mode.
  commandWriteNibble(0x02);
  commandWriteNibble(0x02);
  //todo: make configurable by the user of this library.
  //NFXX where
  //N = num lines (0=1 line or 1=2 lines).
  //F= format (number of dots (0=5x7 or 1=5x10)).
  //X=don't care

  int num_lines_ptn = g_num_lines - 1 << 3;
  int dot_format_ptn = 0x00;      //5x7 dots.  0x04 is 5x10

  commandWriteNibble(num_lines_ptn | dot_format_ptn);
  delayMicroseconds(60);

  //The rest of the init is not specific to 4-bit mode.
  //NOTE: we're writing full bytes now, not nibbles.

  // display control:
  // turn display on, cursor off, no blinking
  commandWrite(0x0C);
  delayMicroseconds(60);

  //clear display
  commandWrite(0x01);
  delay(3);

  // entry mode set: 06
  // increment automatically, display shift, entire shift off
  commandWrite(0x06);

  delay(1);//TODO: remove unnecessary delays
}

//non-core stuff --------------------------------------
//move the cursor to the given absolute position.  line numbers start at 1.
//if this is not a 2-line LCD4Bit_mod instance, will always position on first line.
void LCD4Bit_mod::cursorTo(int line_num, int x){
  //first, put cursor home
  commandWrite(CMD_HOME);

  //if we are on a 1-line display, set line_num to 1st line, regardless of given
  if (g_num_lines==1){
    line_num = 1;
  }
  //offset 40 chars in if second line requested
  if (line_num == 2){
    x += 40;
  }
  //advance the cursor to the right according to position. (second line starts at position 40).
  for (int i=0; i<x; i++) {
    commandWrite(0x14);
  }
}

//scroll whole display to left
void LCD4Bit_mod::leftScroll(int num_chars, int delay_time){
  for (int i=0; i<num_chars; i++) {
    commandWrite(CMD_LEFT);
    delay(delay_time);
  }
}

//Improvements ------------------------------------------------
//Remove the unnecessary delays (e.g. from the end of pulseEnablePin()).
//Allow the user to pass the pins to be used by the LCD in the constructor, and store them as member variables of the class instance.
//-------------------------------------------------------------


text:
package com.monitor.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ValidateFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		// 避免调用缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		int userID = -1;
		HttpSession session = request.getSession(true);
		Integer iuserID = (Integer) session.getAttribute("UserID");// 得到用户的ID号
		if (iuserID != null) {
			userID = iuserID.intValue();
		}
		PrintWriter outPut = response.getWriter();
		String path = request.getContextPath();
		String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		String href =basePath+"system/login/login.jsp";
		if (userID != -1) {// 有权限
			chain.doFilter(request, response);// 可以继续下面的操作
		} else {// 没有权限
			outPut.print("<script language='javascript'>alert('请登录');window.location.href='"+ href + "';</script>;");
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}


text:
/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * Jeroen Domburg <jeroen@spritesmods.com> wrote this file. As long as you retain
 * this notice you can do whatever you want with this stuff. If we meet some day,
 * and you think this stuff is worth it, you can buy me a beer in return.
 * ----------------------------------------------------------------------------
 */

#include "c_types.h"
#include "user_interface.h"
#include "espconn.h"
#include "mem.h"
#include "osapi.h"
#include "gpio.h"
#include "espmissingincludes.h"

#define LEDGPIO 2
#define BTNGPIO 0

static ETSTimer resetBtntimer;

void ICACHE_FLASH_ATTR ioLed(int ena) {
	//gpio_output_set is overkill. ToDo: use better mactos
	if (ena) {
		gpio_output_set((1<<LEDGPIO), 0, (1<<LEDGPIO), 0);
	} else {
		gpio_output_set(0, (1<<LEDGPIO), (1<<LEDGPIO), 0);
	}
}

static void ICACHE_FLASH_ATTR resetBtnTimerCb(void *arg) {
	static int resetCnt=0;
	if (!GPIO_INPUT_GET(BTNGPIO)) {
		resetCnt++;
	} else {
		if (resetCnt>=6) { //3 sec pressed
			wifi_station_disconnect();
			wifi_set_opmode(0x3); //reset to AP+STA mode
			os_printf("Reset to AP mode. Restarting system...\n");
			system_restart();
		}
		resetCnt=0;
	}
}

void ioInit() {
	PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2);
	PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0);
	gpio_output_set(0, 0, (1<<LEDGPIO), (1<<BTNGPIO));
	os_timer_disarm(&resetBtntimer);
	os_timer_setfn(&resetBtntimer, resetBtnTimerCb, NULL);
	os_timer_arm(&resetBtntimer, 500, 1);
}


text:
package com.taobao.tddl.qatest.matrix.template;

import java.util.List;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.taobao.tddl.qatest.BaseTemplateTestCase;

/**
 * Comment for TransactionTemplateTest
 * <p/>
 * Author By: zhuoxue.yll Created Date: 2013-4-10 上午10:43:54
 */

public class TransactionTemplateTest extends BaseTemplateTestCase {

    private DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(tddlDatasource);
    private TransactionTemplate          andorTransaction   = new TransactionTemplate(transactionManager);

    @Test
    public void transactionTest() throws Exception {
        andorTransaction.execute(new TransactionCallback() {

            @Override
            public Object doInTransaction(TransactionStatus status) {
                try {
                    sql = String.format("insert into %s (pk,name) values(?,?)", normaltblTableName);
                    andorJT.update(sql, new Object[] { RANDOM_ID, name });
                    sql = String.format("select * from %s where pk= ?", normaltblTableName);
                    Map re = andorJT.queryForMap(sql, new Object[] { RANDOM_ID });
                    Assert.assertEquals(name, String.valueOf(re.get("name")));
                } catch (Exception ex) {
                    status.setRollbackOnly();
                }
                return null;
            }
        });
        sql = String.format("select * from %s where pk= ?", normaltblTableName);
        Map re = andorJT.queryForMap(sql, new Object[] { RANDOM_ID });
        Assert.assertEquals(name, String.valueOf(re.get("name")));
    }

    @Test
    public void rollbackTest() throws Exception {
        andorTransaction.execute(new TransactionCallback() {

            @Override
            public Object doInTransaction(TransactionStatus status) {
                try {
                    sql = String.format("insert into %s (pk,name) values(?,?)", normaltblTableName);
                    andorJT.update(sql, new Object[] { RANDOM_ID, name });
                    sql = String.format("select * from %s where pk= ?", normaltblTableName);
                    Map re = andorJT.queryForMap(sql, new Object[] { RANDOM_ID });
                    Assert.assertEquals(name, String.valueOf(re.get("name")));
                    status.setRollbackOnly();
                } catch (Exception ex) {
                    status.setRollbackOnly();
                }
                return null;
            }
        });
        // 验证查询不到数据
        sql = String.format("select * from %s where pk= ?", normaltblTableName);
        List le = andorJT.queryForList(sql, new Object[] { RANDOM_ID });
        Assert.assertEquals(0, le.size());
    }
}


text:
<!doctype html>

    <title>jQuery Smpl Share</title>
    <meta name="author" content="Ammar Alakkad">
    <meta name="description"
          content="Very simple (extensible) sharing buttons boilerplate for developers, supports: Facebook, Twitter, Google+ and Linkedin.">
    <meta name="keywords"
          content="jQuery, Simple, Sharing, Share Buttons, Facebook, Twitter, Google, Google+, GooglePlus, Linkedin">
    <meta charset="utf-8">
    <link rel="stylesheet" href="smpl-share.css"/>

Smpl Share


text:
my-old-projects
===============

archive of My old projects ON Dos[Pascal,FoxPro,...]


text:
package mcaligares.utils.reflections;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * A set of useful methods to work with reflection and annotation
 *
 * @author miguel
 *
 */
public final class ReflectionUtils {

    private ReflectionUtils() {
    }

    /**
     * Return a list of Field objects reflecting all the fields declared by the Class object. This
     * includes public, protected, default (package) access, and private fields, includes inherited
     * fields. This method returns null if the class or interface declares no fields.
     *
     * @param clazz
     *            where will try to get the fields
     * @return a list of field objects just if contain at least one element, otherwise return null
     * @see {@link #getFieldsInClass(Class)} {@link #getFieldsInSuperclass(Class)}
     */
    public static final List<Field> getFields(final Class<?> clazz) {
        if (clazz == null) return null;

        // Get fields in class
        List<Field> fields = getFieldsInClass(clazz);
        if (fields == null) fields = new ArrayList<Field>();
        // Add all fields in superclass
        fields.addAll(getFieldsInSuperclass(clazz));

        return fields.isEmpty() ? null : fields;
    }

    /**
     * Return a list of Field objects reflecting all the fields declared by the Class object. This
     * includes public, protected, default (package) access, and private fields, not includes
     * inherited fields. This method returns null if the class or interface declares no fields.
     *
     * @param clazz
     *            where will try to get the fields
     * @return a list of field objects just if contain at least one element, otherwise return null
     * @see {@link #getFields(Class)} {@link #getFieldsInSuperclass(Class)}
     */
    public static final List<Field> getFieldsInClass(final Class<?> clazz) {
        if (clazz == null) return null;

        // Get fields in class
        List<Field> fields = new ArrayList<Field>();
        for (Field field : clazz.getDeclaredFields()) {
            fields.add(field);
        }

        return fields.isEmpty() ? null : fields;
    }

    /**
     * Return a list of Field objects reflecting all the fields declared by the superclass object.
     * This includes public, protected, default (package) access, and private fields, includes
     * inherited fields. This method returns null if the class or interface declares no fields.
     *
     * @param clazz
     *            where will try to get the fields
     * @return a list of field objects just if contain at least one element, otherwise return null
     * @see {@link #getFields(Class)} {@link #getFieldsInClass(Class)}
     */
    public static final List<Field> getFieldsInSuperclass(final Class<?> clazz) {
        if (clazz == null) return null;

        // Get superclass
        Class<?> superClass = clazz.getSuperclass();
        List<Field> fieldsSuperclass = new ArrayList<Field>();

        // Recursive loop to get field in superclass
        while (superClass != Object.class) {
            List<Field> fields = new ArrayList<Field>();
            for (Field field : superClass.getDeclaredFields()) {
                fields.add(field);
            }

            if (fields != null && !fields.isEmpty()) {
                fieldsSuperclass.addAll(fields);
            }
            superClass = superClass.getSuperclass();
        }

        return fieldsSuperclass;
    }

    /**
     * An convenience method, equivalent to {@link #getFieldsWithAnyAnnotations(Class, Class...)} <p/>
     * Return a list of Field objects reflecting any fields that has at least one annotation class
     * declared by the Class object. This includes public, protected, default (package) access, and
     * private fields, includes inherited fields. This method returns null if the class or interface
     * declares no fields.
     */
    public static final <T extends Annotation> List<Field> getFieldsWithAnnotations(Class<?> clazz,
            Class<?>... annotationClasses) {
        return getFieldsWithAnyAnnotations(clazz, annotationClasses);
    }

    /**
     * @see {@link #getFieldsWithAnnotations(Class, Class...)}
     */
    public static final <T extends Annotation> List<Field> getFieldsWithAnyAnnotations(Class<?> clazz,
            Class... annotationClasses) {
        // Get fields of class
        List<Field> fields = getFields(clazz);
        if (fields == null || fields.isEmpty()) return null;

        // Checking for fields with annotations
        List<Field> fieldsWithAnnotation = new ArrayList<Field>();
        for (Field field : fields) {
            if (hasAnyAnnotations(field, annotationClasses)) {
                fieldsWithAnnotation.add(field);
            }
        }

        return fieldsWithAnnotation.isEmpty() ? null : fieldsWithAnnotation;
    }

    /**
     * @see {@link #getFieldsWithAnnotations(Class, Class...)}
     */
    public static final <T extends Annotation> List<Field> getFieldsWithAllAnnotations(Class<?> clazz,
            Class... annotationClasses) {
        // Get fields of class
        List<Field> fields = getFields(clazz);
        if (fields == null || fields.isEmpty()) return null;

        // Checking for fields with annotations
        List<Field> fieldsWithAnnotation = new ArrayList<Field>();
        for (Field field : fields) {
            if (hasAllAnnotations(field, annotationClasses)) {
                fieldsWithAnnotation.add(field);
            }
        }

        return fieldsWithAnnotation.isEmpty() ? null : fieldsWithAnnotation;
    }

    /**
     * An convenience method, equivalent to {@link #getFieldByName(Class, String)}
     */
    public static final Field getFieldByName(Object obj, String fieldName) {
        return obj != null ? getFieldByName(obj.getClass(), fieldName) : null;
    }

    /**
     * Return a field objects of the class if and only if the field name represents the same
     * sequence of characters as the specified String
     *
     * @param clazz
     * @param fieldName
     *            corresponding to the specified String
     * @return Return field object if and only if the field name is equal to the specified String,
     *         otherwise return null
     * @see {@link #getFields(Class)}
     */
    public static final Field getFieldByName(Class<?> clazz, String fieldName) {
        // Checking for filed name
        if (fieldName == null || fieldName.length() == 0) return null;

        // Get fields list of class
        List<Field> fields = getFields(clazz);
        if (fields == null || fields.isEmpty()) return null;

        // Search by field name
        for (Field field : fields) {
            if (fieldName.equals(field.getName())) return field;
        }

        // Not found
        return null;
    }

    /**
     * Return true if field has at least one annotation class, otherwise return false
     * @param field
     * @param classes
     *            corresponding to the annotation class
     * @return true if field has at least one annotation class, otherwise return false
     * @see {@link #hasAnyAnnotations(Field, Class...)} {@link #hasAllAnnotations(Field, Class...)}
     */
    public static final <T extends Annotation> boolean hasAnnotations(Field field, Class<?>... classes) {
        return hasAnyAnnotations(field, classes);
    }

    /**
     * @see {@link #hasAnnotations(Field, Class...)}
     */
    public static final <T extends Annotation> boolean hasAnyAnnotations(Field field, Class... classes) {
        if (classes == null || classes.length == 0) return false;

        for (Class<T> clazz : classes) {
            if (field.isAnnotationPresent(clazz)) return true;
        }

        return false;
    }

    /**
     * @see {@link #hasAnnotations(Field, Class...)}
     */
    public static final <T extends Annotation> boolean hasAllAnnotations(Field field, Class... classes) {
        if (classes == null || classes.length == 0) return false;

        for (Class<T> clazz : classes) {
            if (!field.isAnnotationPresent(clazz)) return false;
        }

        return true;
    }

    /**
     * An convenience method, equivalent to {@link #hasAnnotationClass(Class, Class)}
     */
    public static final <T extends Annotation> boolean hasAnnotationClass(Object object, Class<T> annotationClass) {
        return object != null ? hasAnnotationClass(object.getClass(), annotationClass) : null;
    }

    /**
     * Return true if class object has a specific annotation class, otherwise return false
     *
     * @param entityClass
     * @param annotationClass
     * @return Return true if class object has a specific annotation class, otherwise return false
     * @see {@link #hasAnnotation(Field, Class)}
     */
    public static final <T extends Annotation> boolean hasAnnotationClass(Class<?> entityClass, Class<T> annotationClass) {
        return entityClass != null && entityClass.isAnnotationPresent(annotationClass);
    }

    /**
     * Return a specific annotation class if exist in class, otherwise return false
     *
     * @param entityClass
     * @param annotationClass
     * @return a specific annotation class if exist in class, otherwise return false
     * @see {@link #hasAnnotationClass(Class, Class)}
     */
    public static final <T extends Annotation> T getAnnotationClass(Class<?> entityClass, Class<T> annotationClass) {
        return hasAnnotationClass(entityClass, annotationClass) ? entityClass.getAnnotation(annotationClass) : null;
    }

    /**
     * Return the field value as a Object
     *
     * @param object
     * @param field
     * @return the field value as a Object
     * @see {@link #getValue(Object, Field, Class)} {@link java.lang.reflect.Field#get(Object)}
     */
    public static final Object getValue(final Object object, final Field field) {
        // Checking for objects
        if (field == null || object == null) return null;

        try {
            // Suppress java language access
            field.setAccessible(true);
            // Get the value
            return field.get(object);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Return the field value as a specific type
     *
     * @param object
     * @param field
     * @param clazz
     *            corresponding to the specific type
     * @return the field value as a specific type
     * @see {@link #getValue(Object, Field)} {@link java.lang.reflect.Field#get(Object)}
     */
    public static final <T> T getValue(final Object object, final Field field, final Class<T> clazz) {
        Object value = getValue(object, field);
        return value != null && value.getClass().equals(clazz) ? clazz.cast(value) : null;
    }

    public static final void setValue(final Object obj, final Object value, final Field field) {
        // Checking for objects
        if (field == null || obj == null) return;

        try {
            // Get the old value
            Object oldValue = getValue(obj, field);
            // If is the same value
            if (oldValue == value) return;
            // Set the new value
            field.set(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Return true if the object is a instance of collection, otherwise return false
     *
     * @param object
     * @return true if the object is a instance of collection, otherwise return false
     */
    public static final boolean isFieldIsCollection(Object object) {
        return ((object instanceof java.util.AbstractList) || (object instanceof java.util.AbstractSet));
    }

    /**
     * Return true if the object is a array, otherwise return false
     *
     * @param object
     * @return true if the object is a array, otherwise return false
     */
    public static final boolean isFieldIsArray(Object object) {
        return object != null && object.getClass().getComponentType() != null;
    }

}


text:
module Cask::Staged
  def info_plist
    "#{staged_path}/#{@cask.artifacts[:link].first.first}/Contents/Info.plist"
  end

  def plist_exec(cmd)
    # todo: don't use external interface system_command
    system_command("/usr/libexec/PlistBuddy", :args => ["-c", cmd, info_plist])
  end

  def plist_set(key, value)
    plist_exec("Set #{key} #{value}")
  end

  def bundle_identifier
    plist_exec("Print CFBundleIdentifier")
  end
end


text:
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     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.
namespace BusDriver.Commands
{
	using System;
	using System.IO;
	using System.Linq;
	using System.Text;
	using Formatting;
	//
	using Magnum.Extensions;
	using Magnum.FileSystem;
	using Magnum.FileSystem.Internal;
	using MassTransit;
	using MassTransit.Context;
	using MassTransit.Exceptions;
	using MassTransit.Transports;

	public class LoadCommand :
		Command
	{
		// // = //ger.Get(typeof (LoadCommand));
		readonly int _count;
		readonly string _name;
		readonly bool _remove;
		readonly string _uriString;

		public LoadCommand(string uriString, string name, int count, bool remove)
		{
			_uriString = uriString;
			_name = name;
			_count = count;
			_remove = remove;
		}

		public bool Execute()
		{
			Uri uri = _uriString.ToUri("The from URI was invalid");

			AbsolutePathName fullPath = PathName.GetAbsolutePathName(_name, Environment.CurrentDirectory);
			//.DebugFormat("Using output path name: {0}", fullPath);

			string directoryName = Path.GetDirectoryName(fullPath.GetPath());
			if (!System.IO.Directory.Exists(directoryName))
				System.IO.Directory.CreateDirectory(directoryName);

			IOutboundTransport toTransport = Program.Transports.GetTransport(uri);

			ITextBlock text = new TextBlock()
				.BeginBlock("Load messages to URI: " + uri, "");

			string[] files = System.IO.Directory.GetFiles(directoryName, fullPath.GetName() + "*", SearchOption.TopDirectoryOnly)
				.OrderBy(x => x).ToArray();

			int loadCount = 0;
			for (int i = 0; i < files.Length && loadCount < _count; i++)
			{
				string file = files[i];

				string fileName = Path.Combine(directoryName, file);

				text.BodyFormat("Message File: {0}", file);

				ISendContext context = LoadMessageFromFile(fileName);

				toTransport.Send(context);

				if(_remove)
					System.IO.File.Delete(fileName);

				loadCount++;
			}

			//.Info(text.ToString());

			return true;
		}

		ISendContext LoadMessageFromFile(string fileName)
		{
			using (StreamReader stream = System.IO.File.OpenText(fileName))
			{
				string contentType = null;

				string line;
				do
				{
					line = stream.ReadLine();
					if (line != null)
					{
						string[] values = line.Split(':');
						if (values.Length == 2)
						{
							if (values[0] == "Content-Type")
							{
								contentType = values[1].Trim();
							}
						}
					}
				} while (line.IsNotEmpty());

				string body = stream.ReadToEnd();
				stream.Close();

				return new LoadMessageSendContext(contentType, Encoding.UTF8.GetBytes(body));
			}
		}

		class LoadMessageSendContext :
			MessageContext,
			ISendContext
		{
			readonly byte[] _body;
			readonly Action<Stream> _bodyWriter;

			public LoadMessageSendContext(string contentType, byte[] body)
			{
				SetContentType(contentType);
				_body = body;

				_bodyWriter = stream => stream.Write(_body, 0, _body.Length);
			}

			public Guid Id { get; set; }

			public Type DeclaringMessageType
			{
				get { return typeof (object); }
			}

			public void SerializeTo(Stream stream)
			{
				_bodyWriter(stream);
			}

			public bool TryGetContext<T>(out IBusPublishContext<T> context)
				where T : class
			{
				throw new MessageException(typeof (T), "The message type is unknown and can not be type-cast");
			}

			public void NotifySend(IEndpointAddress address)
			{
			}
		}
	}
}


text:
package net.fec.openrq.util.array;

import java.lang.reflect.Array;

import net.fec.openrq.util.checking.Indexables;

/**
 */
public final class ArrayUtils {

    /**
     * @param componentType
     *            The {@code Class} object representing the component type of the new array
     * @param length
     *            The length of the new array
     * @return a new array with a specific component type and length
     * @exception NullPointerException
     *                If the specified {@code componentType} parameter is null
     * @exception IllegalArgumentException
     *                If {@code componentType} is {@link Void#TYPE}
     * @exception NegativeArraySizeException
     *                If the specified {@code length} is negative
     */
    public static <T> T[] newArray(Class<T> componentType, int length) {

        @SuppressWarnings("unchecked")
        final T[] array = (T[])Array.newInstance(componentType, length);
        return array;
    }

    /**
     * Returns {@code true} iff an array of ints is sorted.
     *
     * @param array
     *            An array of ints
     * @return {@code true} iff an array of ints is sorted
     */
    public static boolean isSorted(int[] array) {

        return isSorted(array, 0, array.length);
    }

    /**
     * Returns {@code true} iff an array of ints is sorted.
     *
     * @param array
     *            An array of ints
     * @param from
     *            The starting index (inclusive)
     * @param to
     *            The ending index (exclusive)
     * @return {@code true} iff an array of ints is sorted
     */
    public static boolean isSorted(int[] array, int from, int to) {

        Indexables.checkFromToBounds(from, to, array.length);

        for (int i = from; i < to - 1; i++) {
            if (array[i + 1] < array[i]) {
                return false;
            }
        }

        return true;
    }

    /**
     * Swaps two non intersecting blocks inside an array of bytes.
     *
     * @param array
     *            The array
     * @param fromA
     *            The starting index of block A (inclusive)
     * @param toA
     *            The ending index of block B (exclusive)
     * @param fromB
     *            The starting index of block B (inclusive)
     * @param toB
     *            The ending index of block B (exclusive)
     */
    public static void swapBlocks(byte[] array, int fromA, int toA, int fromB, int toB) {

        checkArrayBlocksRanges(fromA, toA, fromB, toB, array.length);

        final int lFrom = Math.min(fromA, fromB);
        final int lTo = Math.min(toA, toB);
        final int rFrom = Math.max(fromA, fromB);
        final int rTo = Math.max(toA, toB);

        reverseBytes(array, lFrom, lTo); // reverse the leftmost block
        reverseBytes(array, lTo, rFrom); // reverse the region between the two blocks
        reverseBytes(array, rFrom, rTo); // reverse the rightmost block

        reverseBytes(array, lFrom, rTo); // reverse the total region spanning the two blocks
    }

    /**
     * Swaps two non intersecting blocks inside an array of ints.
     *
     * @param array
     *            The array
     * @param fromA
     *            The starting index of block A (inclusive)
     * @param toA
     *            The ending index of block B (exclusive)
     * @param fromB
     *            The starting index of block B (inclusive)
     * @param toB
     *            The ending index of block B (exclusive)
     */
    public static void swapBlocks(int[] array, int fromA, int toA, int fromB, int toB) {

        checkArrayBlocksRanges(fromA, toA, fromB, toB, array.length);

        final int lFrom = Math.min(fromA, fromB);
        final int lTo = Math.min(toA, toB);
        final int rFrom = Math.max(fromA, fromB);
        final int rTo = Math.max(toA, toB);

        reverseInts(array, lFrom, lTo); // reverse the leftmost block
        reverseInts(array, lTo, rFrom); // reverse the region between the two blocks
        reverseInts(array, rFrom, rTo); // reverse the rightmost block

        reverseInts(array, lFrom, rTo); // reverse the total region spanning the two blocks
    }

    private static void checkArrayBlocksRanges(int fromA, int toA, int fromB, int toB, int arrayLen) {

        if (fromA < 0) throw new IndexOutOfBoundsException("fromA < 0");
        if (toA < fromA) throw new IndexOutOfBoundsException("toA < fromA");
        if (arrayLen < toA) throw new IndexOutOfBoundsException("toA > array length");

        if (fromB < 0) throw new IndexOutOfBoundsException("fromB < 0");
        if (toB < fromB) throw new IndexOutOfBoundsException("toB < fromB");
        if (arrayLen < toB) throw new IndexOutOfBoundsException("toB > array length");

        if (Math.max(fromA, fromB) < Math.min(toA, toB)) {
            throw new IllegalArgumentException("the two blocks intersect");
        }
    }

    // from is inclusive, to is exclusive
    private static void reverseBytes(byte[] array, int from, int to) {

        while (from < to) {
            swapBytes(array, from++, --to);
        }
    }

    // from is inclusive, to is exclusive
    private static void reverseInts(int[] array, int from, int to) {

        while (from < to) {
            swapInts(array, from++, --to);
        }
    }

    /**
     * Swaps two bytes in an array of bytes.
     *
     * @param array
     *            The array of bytes
     * @param a
     *            One of the indices of the values to be swapped
     * @param b
     *            One of the indices of the values to be swapped
     */
    public static void swapBytes(byte[] array, int a, int b) {

        byte tmp = array[a]; // checks for null array and illegal a index
        array[a] = array[b]; // checks for illegal b index before any changes can be made to the array
        array[b] = tmp;
    }

    /**
     * Swaps two ints in an array of ints.
     *
     * @param array
     *            The array of ints
     * @param a
     *            One of the indices of the values to be swapped
     * @param b
     *            One of the indices of the values to be swapped
     */
    public static void swapInts(int[] array, int a, int b) {

        int tmp = array[a]; // checks for null array and illegal a index
        array[a] = array[b]; // checks for illegal b index before any changes can be made to the array
        array[b] = tmp;
    }

    /**
     * Swaps two Objects in an array of Objects.
     *
     * @param array
     *            The array of Objects
     * @param a
     *            One of the indices of the values to be swapped
     * @param b
     *            One of the indices of the values to be swapped
     */
    public static void swapObjects(Object[] array, int a, int b) {

        Object tmp = array[a]; // checks for null array and illegal a index
        array[a] = array[b]; // checks for illegal b index before any changes can be made to the array
        array[b] = tmp;
    }

    /**
     * Provides empty array instances.
     */
    public static final class EmptyArrayOf {

        private static final byte[] BYTES = {};
        private static final char[] CHARS = {};
        private static final short[] SHORTS = {};
        private static final int[] INTS = {};
        private static final long[] LONGS = {};
        private static final float[] FLOATS = {};
        private static final double[] DOUBLES = {};
        private static final Object[] OBJECTS = {};

        /**
         * Returns an empty array of bytes.
         *
         * @return an empty array of bytes
         */
        public static byte[] bytes() {

            return BYTES;
        }

        /**
         * Returns an empty array of chars.
         *
         * @return an empty array of chars
         */
        public static char[] chars() {

            return CHARS;
        }

        /**
         * Returns an empty array of shorts.
         *
         * @return an empty array of shorts
         */
        public static short[] shorts() {

            return SHORTS;
        }

        /**
         * Returns an empty array of ints.
         *
         * @return an empty array of ints
         */
        public static int[] ints() {

            return INTS;
        }

        /**
         * Returns an empty array of longs.
         *
         * @return an empty array of longs
         */
        public static long[] longs() {

            return LONGS;
        }

        /**
         * Returns an empty array of floats.
         *
         * @return an empty array of floats
         */
        public static float[] floats() {

            return FLOATS;
        }

        /**
         * Returns an empty array of doubles.
         *
         * @return an empty array of doubles
         */
        public static double[] doubles() {

            return DOUBLES;
        }

        /**
         * Returns an empty array of objects.
         *
         * @param <T>
         *            The container type of the array
         * @return an empty array of objects
         */
        public static <T> T[] objects() {

            @SuppressWarnings("unchecked")
            final T[] array = (T[])OBJECTS;
            return array;
        }
    }

    private ArrayUtils() {

        // not instantiable
    }
}


text:
using System;
using EntityFX.Gdcame.Common.Contract;
using EntityFX.Gdcame.Common.Contract.Counters;
using EntityFX.Gdcame.Common.Contract.Incrementors;
using EntityFX.Gdcame.Common.Contract.Items;

namespace EntityFx.GdCame.Test.Shared
{
    public abstract class GameRunnerBase
    {
        protected static readonly object _stdLock = new {};

        private bool IsFundsDriverAvailableForBuy(CounterBase rootCounter, Item item)
        {
            return item.UnlockValue <= rootCounter.Value;
        }

        private bool IsCounterAvailableForActivate(DelayedCounter counter, decimal currentFunds)
        {
            return counter.UnlockValue <= currentFunds;
        }

        private bool IsCounterWithInflation(GenericCounter counter)
        {
            return counter.Inflation > 0;
        }

        private bool IsCounterIsMining(DelayedCounter counter)
        {
            return counter.SecondsRemaining > 0;
        }

        private string GetIncrementorValueById(Item item, int incrmentorId)
        {
            var incrementor = item.Incrementors[incrmentorId];
            if (incrementor != null)
            {
                return string.Format("{0}{1}", incrementor.Value,
                    incrementor.IncrementorType == IncrementorTypeEnum.PercentageIncrementor ? "%" : string.Empty);
            }
            return "0";
        }

        public abstract GameData GetGameData();

        public virtual void DisplayGameData(GameData gameData)
        {
            lock (_stdLock)
            {
                Console.WriteLine("Funds: {0:C}; Total Funds: {1:C}", gameData.Cash.OnHand,
                    gameData.Cash.Total);
                Console.WriteLine("Manual Steps: {0}, Automatic Steps: {1}",
                    gameData.ManualStepsCount, gameData.AutomatedStepsCount);
                PrettyConsole.WriteLineColor(ConsoleColor.Red, "{1,15}: {0,12}", gameData.Cash.Counters[0].Value,
                    gameData.Cash.Counters[0].Name);
                PrettyConsole.WriteLineColor(ConsoleColor.Cyan, "{1,15}: {0,12:C} ",
                    ((GenericCounter) gameData.Cash.Counters[1]).SubValue, gameData.Cash.Counters[1].Name);
                PrettyConsole.WriteLineColor(ConsoleColor.Cyan, "{1,15}: {0,12:C} ({2}%)"
                    , ((GenericCounter) gameData.Cash.Counters[1]).Bonus, "Bonus"
                    , ((GenericCounter) gameData.Cash.Counters[1]).BonusPercentage);
                PrettyConsole.WriteColor(ConsoleColor.Cyan, "{1,15}: {0,12}%"
                    , ((GenericCounter) gameData.Cash.Counters[1]).Inflation, "Inflation");
                PrettyConsole.WriteLineColor(ConsoleColor.DarkGray, " StepsToIncrInflation: {0}, Current Steps: {1}",
                    ((GenericCounter) gameData.Cash.Counters[1]).InflationIncreaseSteps,
                    ((GenericCounter) gameData.Cash.Counters[1]).CurrentSteps);
                PrettyConsole.WriteLineColor(ConsoleColor.Cyan, "{1,15}: {0,12:C}"
                    , ((GenericCounter) gameData.Cash.Counters[1]).Value, "Total");
                PrettyConsole.WriteLineColor(ConsoleColor.Green, "{1,15}: {0,12:C}",
                    ((GenericCounter) gameData.Cash.Counters[2]).SubValue, gameData.Cash.Counters[2].Name);
                PrettyConsole.WriteLineColor(ConsoleColor.Green, "{1,15}: {0,12:C} ({2}%)"
                    , ((GenericCounter) gameData.Cash.Counters[2]).Bonus, "Bonus"
                    , ((GenericCounter) gameData.Cash.Counters[2]).BonusPercentage);
                PrettyConsole.WriteColor(ConsoleColor.Green, "{1,15}: {0,12}%"
                    , ((GenericCounter) gameData.Cash.Counters[2]).Inflation, "Corruption");
                PrettyConsole.WriteLineColor(ConsoleColor.DarkGray, " StepsToIncrInflation: {0}, Current Steps: {1}",
                    ((GenericCounter) gameData.Cash.Counters[2]).InflationIncreaseSteps,
                    ((GenericCounter) gameData.Cash.Counters[2]).CurrentSteps);
                PrettyConsole.WriteLineColor(ConsoleColor.Green, "{1,15}: {0,12:C}"
                    , ((GenericCounter) gameData.Cash.Counters[2]).Value, "Total");
                PrettyConsole.WriteLineColor(ConsoleColor.Magenta, "{1,15}: +{0,12:C} {2}/{3}",
                    gameData.Cash.Counters[3].Value, gameData.Cash.Counters[3].Name
                    , TimeSpan.FromSeconds(((DelayedCounter) gameData.Cash.Counters[3]).SecondsRemaining)
                    , TimeSpan.FromSeconds(((DelayedCounter) gameData.Cash.Counters[3]).MiningTimeSeconds));

                Console.WriteLine();
                var charIndex = 65;
                PrettyConsole.WriteLineColor(
                    IsCounterWithInflation((GenericCounter) gameData.Cash.Counters[2])
                        ? ConsoleColor.Yellow
                        : ConsoleColor.DarkYellow, "{0,2}:   Fight Against Corruption", "*");
                if (IsCounterAvailableForActivate((DelayedCounter) gameData.Cash.Counters[3],
                    gameData.Cash.Counters[0].Value))
                {
                    PrettyConsole.WriteLineColor(
                        IsCounterIsMining((DelayedCounter) gameData.Cash.Counters[3])
                            ? ConsoleColor.DarkMagenta
                            : ConsoleColor.Magenta, "{0,2}:         Do Five Year Plan", "+");
                }
                else
                {
                    PrettyConsole.WriteLineColor(ConsoleColor.DarkMagenta,
                        "{0,2}:         Do Five Year Plan: need {1} {2} to unlock", "+",
                        ((DelayedCounter) gameData.Cash.Counters[3]).UnlockValue, gameData.Cash.Counters[0].Name);
                }
                foreach (var item in gameData.Items)
                {
                    if (!IsFundsDriverAvailableForBuy(gameData.Cash.Counters[0], item))
                    {
                        PrettyConsole.WriteColor(ConsoleColor.Gray,
                            "{0,2}:             Need money to buy:     {1,8}. x{2,-4} ", ((char) charIndex).ToString(),
                            item.UnlockValue, item.Bought);
                    }
                    else
                    {
                        PrettyConsole.WriteColor(ConsoleColor.White, "{3,2}: {0,28} {1,15:C} x{2,-4} ", item.Name,
                            item.Price, item.Bought, ((char) charIndex).ToString());
                    }
                    PrettyConsole.WriteColor(ConsoleColor.Red, "+{0, -4} ", GetIncrementorValueById(item, 0));
                    PrettyConsole.WriteColor(ConsoleColor.Cyan, "+{0, -7} ", GetIncrementorValueById(item, 1));
                    PrettyConsole.WriteColor(ConsoleColor.Green, "+{0,-7} ", GetIncrementorValueById(item, 2));
                    Console.WriteLine();
                    charIndex++;
                }
            }
        }
    }
}