text:
/* @flow */
import createReducer from 'create-reducer-map'
import _ from 'lodash'

const values = (o: Object) => Object.keys(o).map((k) => o[k])

// ------------------------------------
// Flow checked contants
// ------------------------------------
export const GAME_STATUSES = {
  notStarted: 0,
  generateHighlighting: 1,
  waitingForUserInput: 2,
  error: 3,
  finised: 4
}
let GA_check: string[] = values(GAME_STATUSES)

export const GAME_SECTORS = {
  topRight: 0,
  bottomRight: 1,
  bottomLeft:2,
  topLeft: 3
}
let GS_check: Array<string> = values(GAME_SECTORS)

export const GAME_MAX_LEVEL = 20

/* -----------------------------
  Redux constants
----------------------------- */
const GO_TO_NEXT_LEVEL = 'simon/GO_TO_NEXT_LEVEL'
const RESET_GAME = 'simon/RESET_GAME'
const TOGGLE_STRICT_MODE = 'simon/TOGGLE_STRICT_MODE'
const TOGGLE_HARD_MODE = 'simon/TOGGLE_HARD_MODE'
const CHANGE_GAME_STATUS = 'simon/CHANGE_GAME_STATUS'

// ------------------------------------
// Actions
// ------------------------------------
export const goToNextLevel = (): Action => ({
  type: GO_TO_NEXT_LEVEL
})
export const resetGame = (): Action => ({
  type: RESET_GAME
})
export const toggleStrictMode = (): Action => ({
  type: TOGGLE_STRICT_MODE
})
export const toggleHardMode = (): Action => ({
  type: TOGGLE_HARD_MODE
})
export const changeGameStatus = (status: number): Action => ({
  type: CHANGE_GAME_STATUS,
  payload: {status}
})

// ------------------------------------
// Utils
// ------------------------------------
const progressFlash = (flashes: Array<number> = []): Array<number> => ([
  ...flashes, _.random(0, 3)
])
const progressUniqueFlash = (flashes: Array<number> = []): Array<number> => {
  const last = _.last(flashes)
  let rnd
  do rnd = _.random(0, 3)
  while (rnd === last)
  return [...flashes, rnd]
}

// ------------------------------------
// Reducer
// ------------------------------------
type initialStateType = {
  level: number,
  status: number,
  isStrict: boolean,
  isHard: boolean,
  flashes: ?Array<Object>
}

export const initialState: initialStateType = {
  level: 0,
  status: GAME_STATUSES.notStarted,
  isStrict: false,
  isHard: false,
  flashes: []
}
export default createReducer(initialState, {
  [GO_TO_NEXT_LEVEL]: (state) => ({
    ...state,
    level: state.level + 1,
    flashes: [
      ...state.flashes,
      state.isHard
        ? progressUniqueFlash(_.last(state.flashes))
        : progressFlash(_.last(state.flashes))
    ]
  }),
  [TOGGLE_STRICT_MODE]: (state) => ({
    ...state,
    isStrict: !state.isStrict
  }),
  [TOGGLE_HARD_MODE]: (state) => ({
    ...state,
    isHard: !state.isHard
  }),
  [CHANGE_GAME_STATUS]: (state, {status}) => ({
    ...state,
    status
  }),
  [RESET_GAME]: (state) => ({...initialState})
  // [THUNK]: () => (dispatch, getState) => {}
})


text:
package com.strategicgains.hyperexpress.domain.siren;

import static org.junit.Assert.*;

import java.util.UUID;

import org.junit.Test;

import com.strategicgains.hyperexpress.AbstractResourceFactoryStrategy;
import com.strategicgains.hyperexpress.domain.Resource;
import com.strategicgains.hyperexpress.domain.siren.SirenResource;
import com.strategicgains.hyperexpress.domain.siren.SirenResourceFactory;

public class SirenResourceFactoryTest
{
	@Test
	public void shouldCreateBlogResourceWithDefaultFields()
	{
		SirenResourceFactory factory = new SirenResourceFactory();
		Blog b = new Blog();
		UUID blogId = UUID.randomUUID();
		UUID ownerId = UUID.randomUUID();
		b.setDescription("Blog Description");
		b.setId(blogId);
		b.setName("Blog Name");
		b.setOwnerId(ownerId);
		Resource r = factory.createResource(b);
		assertEquals("Blog Description", r.getProperty("description"));
		assertEquals("Blog Name", r.getProperty("name"));
		assertEquals(blogId, r.getProperty("id"));
		assertEquals(ownerId, r.getProperty("ownerId"));
		assertNull(r.getProperty("somethingTransient"));
		assertNull(r.getProperty("somethingVolatile"));
		assertNull(r.getProperty("somethingStatic"));
		assertNull(r.getProperty("IGNORED"));
	}

	@Test
	public void shouldCreateBlogResourceWithAnnotatedFields()
	{
		AbstractResourceFactoryStrategy factory = new SirenResourceFactory()
			.includeAnnotations(Include.class)
			.excludeAnnotations(Exclude.class);
		Blog b = new Blog();
		UUID blogId = UUID.randomUUID();
		UUID ownerId = UUID.randomUUID();
		b.setDescription("Blog Description");
		b.setId(blogId);
		b.setName("Blog Name");
		b.setOwnerId(ownerId);
		Resource r = factory.createResource(b);
		assertEquals("Blog Description", r.getProperty("description"));
		assertNull(r.getProperty("name"));
		assertEquals(blogId, r.getProperty("id"));
		assertEquals(ownerId, r.getProperty("ownerId"));
		assertNotNull(r.getProperty("somethingTransient"));
		assertNotNull(r.getProperty("somethingVolatile"));
		assertNotNull(r.getProperty("somethingStatic"));
		assertNotNull(r.getProperty("IGNORED"));
	}

	@Test
	public void shouldCreateResourceFromNull()
	{
		SirenResourceFactory factory = new SirenResourceFactory();
		Resource r = factory.createResource(null);
		assertNotNull(r);
		assertFalse(r.hasLinks());
		assertFalse(r.hasNamespaces());
		assertFalse(r.hasProperties());
		assertFalse(r.hasResources());
	}

	@Test
	public void shouldReturnHalResourceClass()
	{
		SirenResourceFactory factory = new SirenResourceFactory();
		Class<?> type = factory.getResourceType();
		assertEquals(SirenResource.class, type);
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace syncer {

namespace {
// TODO(timsteele): Should use PathService here. See Chromium Issue 3113.
const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data");
}

class SyncHttpBridgeTest : public testing::Test {
 public:
  SyncHttpBridgeTest()
      : test_server_(net::TestServer::TYPE_HTTP,
                     net::TestServer::kLocalhost,
                     FilePath(kDocRoot)),
        fake_default_request_context_getter_(NULL),
        bridge_for_race_test_(NULL),
        io_thread_("IO thread") {
  }

  virtual void SetUp() {
    base::Thread::Options options;
    options.message_loop_type = MessageLoop::TYPE_IO;
    io_thread_.StartWithOptions(options);
  }

  virtual void TearDown() {
    if (fake_default_request_context_getter_) {
      GetIOThreadLoop()->ReleaseSoon(FROM_HERE,
          fake_default_request_context_getter_);
      fake_default_request_context_getter_ = NULL;
    }
    io_thread_.Stop();
  }

  HttpBridge* BuildBridge() {
    if (!fake_default_request_context_getter_) {
      fake_default_request_context_getter_ =
          new net::TestURLRequestContextGetter(io_thread_.message_loop_proxy());
      fake_default_request_context_getter_->AddRef();
    }
    HttpBridge* bridge = new HttpBridge(
        new HttpBridge::RequestContextGetter(
            fake_default_request_context_getter_,
            "user agent"));
    return bridge;
  }

  static void Abort(HttpBridge* bridge) {
    bridge->Abort();
  }

  // Used by AbortAndReleaseBeforeFetchCompletes to test an interesting race
  // condition.
  void RunSyncThreadBridgeUseTest(base::WaitableEvent* signal_when_created,
                                  base::WaitableEvent* signal_when_released);

  static void TestSameHttpNetworkSession(MessageLoop* main_message_loop,
                                         SyncHttpBridgeTest* test) {
    scoped_refptr<HttpBridge> http_bridge(test->BuildBridge());
    EXPECT_TRUE(test->GetTestRequestContextGetter());
    net::HttpNetworkSession* test_session =
        test->GetTestRequestContextGetter()->GetURLRequestContext()->
        http_transaction_factory()->GetSession();
    EXPECT_EQ(test_session,
              http_bridge->GetRequestContextGetterForTest()->
                  GetURLRequestContext()->
                  http_transaction_factory()->GetSession());
    main_message_loop->PostTask(FROM_HERE, MessageLoop::QuitClosure());
  }

  MessageLoop* GetIOThreadLoop() {
    return io_thread_.message_loop();
  }

  // Note this is lazy created, so don't call this before your bridge.
  net::TestURLRequestContextGetter* GetTestRequestContextGetter() {
    return fake_default_request_context_getter_;
  }

  net::TestServer test_server_;

  base::Thread* io_thread() { return &io_thread_; }

  HttpBridge* bridge_for_race_test() { return bridge_for_race_test_; }

 private:
  // A make-believe "default" request context, as would be returned by
  // Profile::GetDefaultRequestContext().  Created lazily by BuildBridge.
  net::TestURLRequestContextGetter* fake_default_request_context_getter_;

  HttpBridge* bridge_for_race_test_;

  // Separate thread for IO used by the HttpBridge.
  base::Thread io_thread_;
  MessageLoop loop_;
};

// An HttpBridge that doesn't actually make network requests and just calls
// back with dummy response info.
// TODO(tim): Instead of inheriting here we should inject a component
// responsible for the MakeAsynchronousPost bit.
class ShuntedHttpBridge : public HttpBridge {
 public:
  // If |never_finishes| is true, the simulated request never actually
  // returns.
  ShuntedHttpBridge(net::URLRequestContextGetter* baseline_context_getter,
                    SyncHttpBridgeTest* test, bool never_finishes)
      : HttpBridge(
          new HttpBridge::RequestContextGetter(
              baseline_context_getter, "user agent")),
        test_(test), never_finishes_(never_finishes) { }
 protected:
  virtual void MakeAsynchronousPost() {
    ASSERT_TRUE(MessageLoop::current() == test_->GetIOThreadLoop());
    if (never_finishes_)
      return;

    // We don't actually want to make a request for this test, so just callback
    // as if it completed.
    test_->GetIOThreadLoop()->PostTask(FROM_HERE,
        base::Bind(&ShuntedHttpBridge::CallOnURLFetchComplete, this));
  }
 private:
  ~ShuntedHttpBridge() {}

  void CallOnURLFetchComplete() {
    ASSERT_TRUE(MessageLoop::current() == test_->GetIOThreadLoop());
    // We return no cookies and a dummy content response.
    net::ResponseCookies cookies;

    std::string response_content = "success!";
    net::TestURLFetcher fetcher(0, GURL(), NULL);
    fetcher.set_url(GURL("www.google.com"));
    fetcher.set_response_code(200);
    fetcher.set_cookies(cookies);
    fetcher.SetResponseString(response_content);
    OnURLFetchComplete(&fetcher);
  }
  SyncHttpBridgeTest* test_;
  bool never_finishes_;
};

void SyncHttpBridgeTest::RunSyncThreadBridgeUseTest(
    base::WaitableEvent* signal_when_created,
    base::WaitableEvent* signal_when_released) {
  scoped_refptr<net::URLRequestContextGetter> ctx_getter(
      new net::TestURLRequestContextGetter(io_thread_.message_loop_proxy()));
  {
    scoped_refptr<ShuntedHttpBridge> bridge(new ShuntedHttpBridge(
        ctx_getter, this, true));
    bridge->SetURL("http://www.google.com", 9999);
    bridge->SetPostPayload("text/plain", 2, " ");
    bridge_for_race_test_ = bridge;
    signal_when_created->Signal();

    int os_error = 0;
    int response_code = 0;
    bridge->MakeSynchronousPost(&os_error, &response_code);
    bridge_for_race_test_ = NULL;
  }
  signal_when_released->Signal();
}

TEST_F(SyncHttpBridgeTest, TestUsesSameHttpNetworkSession) {
  // Run this test on the IO thread because we can only call
  // URLRequestContextGetter::GetURLRequestContext on the IO thread.
  io_thread()->message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&SyncHttpBridgeTest::TestSameHttpNetworkSession,
                 MessageLoop::current(), this));
  MessageLoop::current()->Run();
}

// Test the HttpBridge without actually making any network requests.
TEST_F(SyncHttpBridgeTest, TestMakeSynchronousPostShunted) {
  scoped_refptr<net::URLRequestContextGetter> ctx_getter(
      new net::TestURLRequestContextGetter(io_thread()->message_loop_proxy()));
  scoped_refptr<HttpBridge> http_bridge(new ShuntedHttpBridge(
      ctx_getter, this, false));
  http_bridge->SetURL("http://www.google.com", 9999);
  http_bridge->SetPostPayload("text/plain", 2, " ");

  int os_error = 0;
  int response_code = 0;
  bool success = http_bridge->MakeSynchronousPost(&os_error, &response_code);
  EXPECT_TRUE(success);
  EXPECT_EQ(200, response_code);
  EXPECT_EQ(0, os_error);

  EXPECT_EQ(8, http_bridge->GetResponseContentLength());
  EXPECT_EQ(std::string("success!"),
            std::string(http_bridge->GetResponseContent()));
}

// Full round-trip test of the HttpBridge, using default UA string and
// no request cookies.
TEST_F(SyncHttpBridgeTest, TestMakeSynchronousPostLiveWithPayload) {
  ASSERT_TRUE(test_server_.Start());

  scoped_refptr<HttpBridge> http_bridge(BuildBridge());

  std::string payload = "this should be echoed back";
  GURL echo = test_server_.GetURL("echo");
  http_bridge->SetURL(echo.spec().c_str(), echo.IntPort());
  http_bridge->SetPostPayload("application/x-www-form-urlencoded",
                              payload.length() + 1, payload.c_str());
  int os_error = 0;
  int response_code = 0;
  bool success = http_bridge->MakeSynchronousPost(&os_error, &response_code);
  EXPECT_TRUE(success);
  EXPECT_EQ(200, response_code);
  EXPECT_EQ(0, os_error);

  EXPECT_EQ(payload.length() + 1,
            static_cast<size_t>(http_bridge->GetResponseContentLength()));
  EXPECT_EQ(payload, std::string(http_bridge->GetResponseContent()));
}

// Full round-trip test of the HttpBridge.
TEST_F(SyncHttpBridgeTest, TestMakeSynchronousPostLiveComprehensive) {
  ASSERT_TRUE(test_server_.Start());

  scoped_refptr<HttpBridge> http_bridge(BuildBridge());

  GURL echo_header = test_server_.GetURL("echoall");
  http_bridge->SetURL(echo_header.spec().c_str(), echo_header.IntPort());

  std::string test_payload = "###TEST PAYLOAD###";
  http_bridge->SetPostPayload("text/html", test_payload.length() + 1,
                              test_payload.c_str());

  int os_error = 0;
  int response_code = 0;
  bool success = http_bridge->MakeSynchronousPost(&os_error, &response_code);
  EXPECT_TRUE(success);
  EXPECT_EQ(200, response_code);
  EXPECT_EQ(0, os_error);

  std::string response(http_bridge->GetResponseContent(),
                       http_bridge->GetResponseContentLength());
  EXPECT_EQ(std::string::npos, response.find("Cookie:"));
  EXPECT_NE(std::string::npos, response.find("User-Agent: user agent"));
  EXPECT_NE(std::string::npos, response.find(test_payload.c_str()));
}

TEST_F(SyncHttpBridgeTest, TestExtraRequestHeaders) {
  ASSERT_TRUE(test_server_.Start());

  scoped_refptr<HttpBridge> http_bridge(BuildBridge());

  GURL echo_header = test_server_.GetURL("echoall");

  http_bridge->SetURL(echo_header.spec().c_str(), echo_header.IntPort());
  http_bridge->SetExtraRequestHeaders("test:fnord");

  std::string test_payload = "###TEST PAYLOAD###";
  http_bridge->SetPostPayload("text/html", test_payload.length() + 1,
                              test_payload.c_str());

  int os_error = 0;
  int response_code = 0;
  bool success = http_bridge->MakeSynchronousPost(&os_error, &response_code);
  EXPECT_TRUE(success);
  EXPECT_EQ(200, response_code);
  EXPECT_EQ(0, os_error);

  std::string response(http_bridge->GetResponseContent(),
                       http_bridge->GetResponseContentLength());

  EXPECT_NE(std::string::npos, response.find("fnord"));
  EXPECT_NE(std::string::npos, response.find(test_payload.c_str()));
}

TEST_F(SyncHttpBridgeTest, TestResponseHeader) {
  ASSERT_TRUE(test_server_.Start());

  scoped_refptr<HttpBridge> http_bridge(BuildBridge());

  GURL echo_header = test_server_.GetURL("echoall");
  http_bridge->SetURL(echo_header.spec().c_str(), echo_header.IntPort());

  std::string test_payload = "###TEST PAYLOAD###";
  http_bridge->SetPostPayload("text/html", test_payload.length() + 1,
                              test_payload.c_str());

  int os_error = 0;
  int response_code = 0;
  bool success = http_bridge->MakeSynchronousPost(&os_error, &response_code);
  EXPECT_TRUE(success);
  EXPECT_EQ(200, response_code);
  EXPECT_EQ(0, os_error);

  EXPECT_EQ(http_bridge->GetResponseHeaderValue("Content-type"), "text/html");
  EXPECT_TRUE(http_bridge->GetResponseHeaderValue("invalid-header").empty());
}

TEST_F(SyncHttpBridgeTest, Abort) {
  scoped_refptr<net::URLRequestContextGetter> ctx_getter(
      new net::TestURLRequestContextGetter(io_thread()->message_loop_proxy()));
  scoped_refptr<ShuntedHttpBridge> http_bridge(new ShuntedHttpBridge(
      ctx_getter, this, true));
  http_bridge->SetURL("http://www.google.com", 9999);
  http_bridge->SetPostPayload("text/plain", 2, " ");

  int os_error = 0;
  int response_code = 0;

  io_thread()->message_loop_proxy()->PostTask(
      FROM_HERE,
      base::Bind(&SyncHttpBridgeTest::Abort, http_bridge));
  bool success = http_bridge->MakeSynchronousPost(&os_error, &response_code);
  EXPECT_FALSE(success);
  EXPECT_EQ(net::ERR_ABORTED, os_error);
}

TEST_F(SyncHttpBridgeTest, AbortLate) {
  scoped_refptr<net::URLRequestContextGetter> ctx_getter(
      new net::TestURLRequestContextGetter(io_thread()->message_loop_proxy()));
  scoped_refptr<ShuntedHttpBridge> http_bridge(new ShuntedHttpBridge(
      ctx_getter, this, false));
  http_bridge->SetURL("http://www.google.com", 9999);
  http_bridge->SetPostPayload("text/plain", 2, " ");

  int os_error = 0;
  int response_code = 0;

  bool success = http_bridge->MakeSynchronousPost(&os_error, &response_code);
  ASSERT_TRUE(success);
  http_bridge->Abort();
  // Ensures no double-free of URLFetcher, etc.
}

// Tests an interesting case where code using the HttpBridge aborts the fetch
// and releases ownership before a pending fetch completed callback is issued by
// the underlying URLFetcher (and before that URLFetcher is destroyed, which
// would cancel the callback).
TEST_F(SyncHttpBridgeTest, AbortAndReleaseBeforeFetchComplete) {
  base::Thread sync_thread("SyncThread");
  sync_thread.Start();

  // First, block the sync thread on the post.
  base::WaitableEvent signal_when_created(false, false);
  base::WaitableEvent signal_when_released(false, false);
  sync_thread.message_loop()->PostTask(FROM_HERE,
      base::Bind(&SyncHttpBridgeTest::RunSyncThreadBridgeUseTest,
                 base::Unretained(this),
                 &signal_when_created,
                 &signal_when_released));

  // Stop IO so we can control order of operations.
  base::WaitableEvent io_waiter(false, false);
  ASSERT_TRUE(io_thread()->message_loop_proxy()->PostTask(
      FROM_HERE,
      base::Bind(&base::WaitableEvent::Wait, base::Unretained(&io_waiter))));

  signal_when_created.Wait();  // Wait till we have a bridge to abort.
  ASSERT_TRUE(bridge_for_race_test());

  // Schedule the fetch completion callback (but don't run it yet). Don't take
  // a reference to the bridge to mimic URLFetcher's handling of the delegate.
  net::URLFetcherDelegate* delegate =
      static_cast<net::URLFetcherDelegate*>(bridge_for_race_test());
  net::ResponseCookies cookies;
  std::string response_content = "success!";
  net::TestURLFetcher fetcher(0, GURL(), NULL);
  fetcher.set_url(GURL("www.google.com"));
  fetcher.set_response_code(200);
  fetcher.set_cookies(cookies);
  fetcher.SetResponseString(response_content);
  ASSERT_TRUE(io_thread()->message_loop_proxy()->PostTask(
      FROM_HERE,
      base::Bind(&net::URLFetcherDelegate::OnURLFetchComplete,
          base::Unretained(delegate), &fetcher)));

  // Abort the fetch. This should be smart enough to handle the case where
  // the bridge is destroyed before the callback scheduled above completes.
  bridge_for_race_test()->Abort();

  // Wait until the sync thread releases its ref on the bridge.
  signal_when_released.Wait();
  ASSERT_FALSE(bridge_for_race_test());

  // Unleash the hounds. The fetch completion callback should fire first, and
  // succeed even though we Release()d the bridge above because the call to
  // Abort should have held a reference.
  io_waiter.Signal();

  // Done.
  sync_thread.Stop();
  io_thread()->Stop();
}

}  // namespace syncer


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace Stratus.Analytics
{
  public class AnalyticsWindow : EditorWindow
  {
    //------------------------------------------------------------------------/
    // Fields
    //------------------------------------------------------------------------/
    private Vector2 ScrollPosition;
    private AnimationCurve curve = new AnimationCurve();

    //------------------------------------------------------------------------/
    // Methods
    //------------------------------------------------------------------------/
    [MenuItem("Stratus/Experimental/Analytics")]
    public static void Open()
    {
      EditorWindow.GetWindow(typeof(AnalyticsWindow), false, "Stratus Analytics");
    }

    //------------------------------------------------------------------------/
    // Messages
    //------------------------------------------------------------------------/
    private void OnEnable()
    {

    }

    private void OnGUI()
    {
      EditorGUILayout.BeginVertical();
      this.ScrollPosition = EditorGUILayout.BeginScrollView(this.ScrollPosition, false, false);
      {
        DrawVisualization();
      }
      EditorGUILayout.EndScrollView();
      EditorGUILayout.EndVertical();
    }

    private void DrawVisualization()
    {
      EditorGUILayout.CurveField("Example", curve);
    }

  }
}


text:
import { StyleSheet } from 'react-native';
import { colors, dimensions } from '../../styles';

const styles = StyleSheet.create({
  separator: {
    width: StyleSheet.hairlineWidth,
    marginLeft: dimensions.indent,
    marginRight: dimensions.indent,
    backgroundColor: colors.border,
  },
});

export default styles;


text:
package com.example.android.bluetoothchat;

import android.bluetooth.BluetoothSocket;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 * This thread runs during a connection with a remote device.
 * It handles all incoming and outgoing transmissions.
 */
class ConnectedThread extends Thread {

    private static final String TAG = "ConnectedThread";
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    private final BluetoothChatService service;

    public ConnectedThread(BluetoothChatService service, BluetoothSocket socket) {
        this.service = service;
        Log.d(TAG, "create ConnectedThread");
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    byte[] sizeBuf = new byte[4];

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];

        int bytes;

        boolean fileRead = false;
        FileOutputStream stream = null;
        long size = 0, saved = 0;
        int msgLen;
        File file = null;
        int percent = 0;

        // Keep listening to the InputStream while connected
        while (true) {
            try {

                msgLen = readSize();

//                service.sendToast("log: msg lenght" + msgLen);

                readMsg(buffer, msgLen);
                String received = new String(buffer, 0, msgLen);

                if (received.equals(Constants.FILE_START)) {
                    saved = 0;

                    //file name
                    msgLen = readSize();
                    readMsg(buffer, msgLen);
                    String name = new String(buffer, 0, msgLen);
                    service.sendToast("file : " + name);

                    //file size
                    mmInStream.read(buffer, 0, 8);
                    size = ByteBuffer.wrap(buffer).getLong();
                    service.sendToast("log: size " + size);
                    //create file
                    file = new File(Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/" + name);
                    file.createNewFile();
                    stream = new FileOutputStream(file);

                    service.mHandler.obtainMessage(Constants.MESSAGE_START).sendToTarget();
                    fileRead = true;
                } else if (received.equals(Constants.FILE_END)) {
                    fileRead = false;
                    saved = percent = 0;
                    stream.close();
                    service.mHandler.obtainMessage(Constants.MESSAGE_END, file).sendToTarget();
                    file = null;
                } else if (received.equals(Constants.FILE_ERROR)) {
                    file = null;
                    saved = percent = 0;
                    if (stream != null) stream.close();
                    if (fileRead) service.mHandler.obtainMessage(Constants.MESSAGE_FILE_ERROR).sendToTarget();

                    fileRead = false;
                } else if (fileRead) {
                    stream.write(buffer, 0, msgLen);
                    saved += msgLen;
                    int newPerc =  (int) ((saved * 100 ) / size);
                    if (newPerc != percent) {
                        percent = newPerc;
                        service.mHandler.obtainMessage(Constants.MESSAGE_PERCENT, newPerc, 0)
                                .sendToTarget();
                    }
                } else {
                    // Send the obtained bytes to the UI Activity
                    service.mHandler.obtainMessage(Constants.MESSAGE_READ, msgLen, -1, buffer)
                            .sendToTarget();
                }

            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                service.connectionLost();
                // Start the service over to restart listening mode
                service.start();
                break;
            } catch (ArrayIndexOutOfBoundsException ae) {
                Log.e(TAG, "disconnected", ae);
                if (fileRead) {
                    service.mHandler.obtainMessage(Constants.MESSAGE_FILE_ERROR).sendToTarget();
                }
                service.connectionLost();
                service.start();
                break;
            }
        }
    }

    private void readMsg(byte[] buffer, final int msgLen) throws IOException {
        int bytes, all = 0, left = msgLen;
        while (all != msgLen) {
            bytes = mmInStream.read(buffer, all, left);
            all += bytes;
            left -= bytes;
        }
    }

    private int readSize() throws IOException {
        readMsg(sizeBuf, 4);
        return toInt(sizeBuf);
    }

    public void writeMsg(byte[] buffer) {
        if (fileWrite)
            return;
        try {

            mmOutStream.write(toBytes(buffer.length));
            mmOutStream.write(buffer);
            // Share the sent message back to the UI Activity
            service.mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

    void write(byte[] buffer, int len) throws IOException {
        mmOutStream.write(toBytes(len));
        mmOutStream.write(buffer, 0, len);
    }

    public void write(byte[] buffer) throws IOException {
            mmOutStream.write(toBytes(buffer.length));
            mmOutStream.write(buffer);
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }

    volatile boolean fileWrite;

    /**
     * writes in stream FILE_START -> FILE_NAME + FILE_LENGTH + DATA -> FILE_END
     * @param f
     */

    public void writeFile(final File f) {
        (new Thread() {
            @Override
            public void run() {
                fileWrite = true;
                FileInputStream stream = null;
                try {
                    stream = new FileInputStream(f);
                    byte[] buffer = new byte[1024];
                    int readCount, percent = 0;
                    write(Constants.FILE_START.getBytes());
                    service.sendToast("sending file " + f.getName());

                    write(f.getName().getBytes());  //filename

                    //file size in long
                    long size = f.length();
                    ByteBuffer bb = ByteBuffer.allocate(8).putLong(size);
                    mmOutStream.write(bb.array());   //write just long

                    service.mHandler.obtainMessage(Constants.MESSAGE_START).sendToTarget();
                    long writen = 0;
                    while ((readCount = stream.read(buffer)) != -1) {
                        write(buffer, readCount);
                        writen += readCount;
//                        try {
//                            Thread.sleep(150);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
                        int newPerc =  (int) ((writen * 100 ) / size);
                        if (newPerc != percent) {
                            percent = newPerc;
                            service.mHandler.obtainMessage(Constants.MESSAGE_PERCENT, newPerc, 0)
                                    .sendToTarget();
                        }
                    }
                    write(Constants.FILE_END.getBytes());
                    service.mHandler.obtainMessage(Constants.MESSAGE_END, null).sendToTarget();
                } catch (Exception e) {
                    e.printStackTrace();
                    service.mHandler.obtainMessage(Constants.MESSAGE_FILE_ERROR).sendToTarget();
                    try {
                        write(Constants.FILE_ERROR.getBytes());
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                } finally {
                    if (stream != null) {
                        try {
                            stream.close();
                        } catch (IOException e) {
                        }
                    }
                    fileWrite = false;
                }
            }
        }).start();
    }

    private byte[] toBytes(int i) {
        byte[] result = new byte[4];
        result[0] = (byte) (i >> 24);
        result[1] = (byte) (i >> 16);
        result[2] = (byte) (i >> 8);
        result[3] = (byte) (i /*>> 0*/);

        return result;
    }

    private int toInt(byte[] a) {
        return   (a[3] & 0xFF) |
                (a[2] & 0xFF) << 8 |
                (a[1] & 0xFF) << 16 |
                (a[0] & 0xFF) << 24;
    }
}


text:
package com.planet_ink.coffee_mud.Abilities.Prayers;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire;
import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Move;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class Prayer_MassGrave extends Prayer
{
	@Override
	public String ID()
	{
		return "Prayer_MassGrave";
	}

	private final static String	localizedName	= CMLib.lang().L("Mass Grave");

	@Override
	public String name()
	{
		return localizedName;
	}

	private final static String	localizedStaticDisplay	= CMLib.lang().L("(Mass Grave)");

	@Override
	public String displayText()
	{
		return localizedStaticDisplay;
	}

	@Override
	public int classificationCode()
	{
		return Ability.ACODE_PRAYER | Ability.DOMAIN_DEATHLORE;
	}

	@Override
	public int abstractQuality()
	{
		return Ability.QUALITY_INDIFFERENT;
	}

	@Override
	public long flags()
	{
		return Ability.FLAG_UNHOLY;
	}

	@Override
	protected int canAffectCode()
	{
		return CAN_ROOMS;
	}

	@Override
	protected int canTargetCode()
	{
		return CAN_ROOMS;
	}

	public Room previousLocation=null;
	public Room shelter=null;

	public Room getPreviousLocation(MOB mob)
	{
		if((previousLocation==null)||(previousLocation.amDestroyed()))
		{
			if(text().length()>0)
				previousLocation=CMLib.map().getRoom(text());
			while((previousLocation==null)||(previousLocation.amDestroyed())||(!CMLib.flags().canAccess(mob, previousLocation)))
				previousLocation=CMLib.map().getRandomRoom();
		}
		return previousLocation;
	}

	@Override
	public void unInvoke()
	{
		if(!(affected instanceof MOB))
			return;
		final MOB M=(MOB)affected;

		if(canBeUninvoked())
		{
			Room shelter=this.shelter;
			if(shelter==null)
				shelter=M.location();
			if(shelter != null)
			{
				this.shelter=null;
				Room backToRoom=M.getStartRoom();
				int i=0;
				final LinkedList<MOB> mobs=new LinkedList<MOB>();
				for(final Enumeration<MOB> m=shelter.inhabitants();m.hasMoreElements();)
					mobs.add(m.nextElement());
				for(final MOB mob : mobs)
				{
					if(mob==null)
						break;
					mob.tell(L("You return to world of the living."));

					final CMMsg enterMsg=CMClass.getMsg(mob,previousLocation,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,L("<S-NAME> crawl(s) out of the ground!"));
					backToRoom=getPreviousLocation(mob);
					if(backToRoom==null)
						backToRoom=mob.getStartRoom();
					backToRoom.bringMobHere(mob,false);
					backToRoom.send(mob,enterMsg);
					CMLib.commands().postLook(mob,true);
				}
				final LinkedList<Item> items=new LinkedList<Item>();
				for(final Enumeration<Item> e=shelter.items();e.hasMoreElements();)
					items.add(e.nextElement());
				for(final Item I : items)
				{
					if(I.container()==null)
						backToRoom.moveItemTo(I, Expire.Player_Drop, Move.Followers);
				}
				i=0;
				while(i<shelter.numItems())
				{
					final Item I=shelter.getItem(i);
					backToRoom.moveItemTo(I, Expire.Player_Drop, Move.Followers);
					if(shelter.isContent(I))
						i++;
				}
				this.shelter=null;
				previousLocation=null;
			}
		}
		super.unInvoke();
	}

	@Override
	public boolean okMessage(Environmental host, CMMsg msg)
	{
		if(((msg.sourceMinor()==CMMsg.TYP_QUIT)
			||(msg.sourceMinor()==CMMsg.TYP_SHUTDOWN)
			||((msg.targetMinor()==CMMsg.TYP_EXPIRE)&&(msg.target()==shelter))
			||(msg.sourceMinor()==CMMsg.TYP_DEATH)
			||(msg.sourceMinor()==CMMsg.TYP_ROOMRESET))
		&&(shelter!=null)
		&&(shelter.isInhabitant(msg.source())))
		{
			getPreviousLocation(msg.source()).bringMobHere(msg.source(),false);
			unInvoke();
		}
		return super.okMessage(host,msg);
	}

	@Override
	public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
	{
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		if(mob.fetchEffect(ID())!=null)
		{
			mob.fetchEffect(ID()).unInvoke();
			return false;
		}

		switch(mob.location().domainType())
		{
		case Room.DOMAIN_INDOORS_CAVE:
		case Room.DOMAIN_OUTDOORS_WOODS:
		case Room.DOMAIN_OUTDOORS_ROCKS:
		case Room.DOMAIN_OUTDOORS_PLAINS:
		case Room.DOMAIN_OUTDOORS_JUNGLE:
		case Room.DOMAIN_OUTDOORS_SWAMP:
		case Room.DOMAIN_OUTDOORS_DESERT:
		case Room.DOMAIN_OUTDOORS_HILLS:
		case Room.DOMAIN_OUTDOORS_MOUNTAINS:
			break;
		default:
			mob.tell(L("This magic will only work on soil or natural stone."));
			return false;
		}

		final boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,null,this,somanticCastCode(mob,null,auto),auto?"":L("^S<S-NAME> @x1 for an immediate burial.^?",prayWord(mob)));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				final Set<MOB> h=properTargets(mob,givenTarget,false);
				if(h==null)
					return false;

				final Room thisRoom=mob.location();
				previousLocation=thisRoom;
				final Room newRoom=CMClass.getLocale("CaveRoom");
				shelter = newRoom;
				newRoom.setDisplayText(L("An underground grave"));
				newRoom.setDescription(L("You are in a dark dirty place!"));
				newRoom.setArea(mob.location().getArea());
				newRoom.setAtmosphere(RawMaterial.RESOURCE_NOTHING);
				Ability A=CMClass.getAbility("Prop_PeaceMaker");
				if(A!=null)
					newRoom.addEffect(A);
				A=CMClass.getAbility("Prop_NoRecall");
				if(A!=null)
					newRoom.addEffect(A);
				A=CMClass.getAbility("Prop_NoSummon");
				if(A!=null)
					newRoom.addEffect(A);
				A=CMClass.getAbility("Prop_NoTeleport");
				if(A!=null)
					newRoom.addEffect(A);
				A=CMClass.getAbility("Prop_NoTeleportOut");
				if(A!=null)
					newRoom.addEffect(A);
				shelter.setArea(mob.location().getArea());
				miscText=CMLib.map().getExtendedRoomID(mob.location());
				for (final Object element : h)
				{
					final MOB follower=(MOB)element;
					final CMMsg enterMsg=CMClass.getMsg(follower,newRoom,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,L("<S-NAME> <S-IS-ARE> buried here."));
					final CMMsg leaveMsg=CMClass.getMsg(follower,thisRoom,this,somanticCastCode(mob,newRoom,auto),L("<S-NAME> <S-IS-ARE> buried underground."));
					if(thisRoom.okMessage(follower,leaveMsg)&&newRoom.okMessage(follower,enterMsg))
					{
						if(follower.isInCombat())
						{
							CMLib.commands().postFlee(follower,("NOWHERE"));
							follower.makePeace(false);
						}
						thisRoom.send(follower,leaveMsg);
						newRoom.bringMobHere(follower,false);
						thisRoom.delInhabitant(follower);
						newRoom.send(follower,enterMsg);
						follower.tell(L("\n\r\n\r"));
						CMLib.commands().postLook(follower,true);
						if(follower==mob)
							beneficialAffect(mob,mob,asLevel,999999);
					}
				}
			}
		}
		else
			beneficialVisualFizzle(mob,null,L("<S-NAME> wave(s) <S-HIS-HER> arms and and speak(s), but nothing happens."));

		return success;
	}
}


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

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

  <title>EasyMock 3.0</title>

    Clover Coverage  Report - EasyMock 3.0
Coverage timestamp: sam. mai 8 2010 14:37:27 CEST

Overview   Package   File

        FRAMES
        NO FRAMES
        SHOW HELP

           Statistics for file UsageStrictMockTest.java:

           Stmts:
                 95

           LOC:
                 208

           Total cmp:
                 22

           Stmts/Method:
                 11,88

           Branches:
                 14

           NCLOC:
                 160

           Cmp density:
                 0,23

           Methods/Class:
                 8

           Methods:
                 8

           Avg method cmp:
                 2,75

            Classes:
                  1

           Statistics for file UsageStrictMockTest.java:

           Stmts:
                 95

           LOC:
                 208

           Total cmp:
                 22

           Stmts/Method:
                 11,88

           Branches:
                 14

           NCLOC:
                 160

           Cmp density:
                 0,23

           Methods/Class:
                 8

           Methods:
                 8

           Avg method cmp:
                 2,75

            Classes:
                  1

Legend

line#	hit count

1	86
               line hit by 1 or more tests which passed

2	17
               line was covered, but not by a test case

3	7
               line hit by 1 or more tests which did not pass

4	5
               line hit by more than one (selected) test

5	3
               line hit by one test only

6	2
               line hit by one or more (selected) tests that failed

7	1
               line has an expression (e.g. a branch) or statement that was not fully covered

8	1
               line has an expression that was not fully covered and not hit by any test

9	0
               line was not covered at all

10
               line was filtered

  Expand All

                                 UsageStrictMockTest

                Line # 31

                    Total Statements
                    95

                    % Filtered
                    0%

                    Complexity
                    22

                    Uncovered Elements
                    14

                    TOTAL Coverage
                    88%

0.8803419

                setup() : void
                  setup() : void

                34
                34

                4.0
              4

                0.0
              0%

                1.0
              1

                0.0
              0

                1.0
              100%

1.0

                orderedCallsSucces() : void
                  orderedCallsSucces() : void

                42
                42

                3.0
              3

                0.0
              0%

                1.0
              1

                0.0
              0

                1.0
              100%

1.0

                unorderedCallsFailure() : void
                  unorderedCallsFailure() : void

                49
                49

                6.0
              6

                0.0
              0%

                3.0
              3

                2.0
              2

                0.75
              75%

0.75

                tooManyCallsFailure() : void
                  tooManyCallsFailure() : void

                62
                62

                8.0
              8

                0.0
              0%

                3.0
              3

                2.0
              2

                0.8
              80%

0.8

                tooFewCallsFailure() : void
                  tooFewCallsFailure() : void

                78
                78

                8.0
              8

                0.0
              0%

                3.0
              3

                2.0
              2

                0.8
              80%

0.8

                differentMethods() : void
                  differentMethods() : void

                94
                94

                26.0
              26

                0.0
              0%

                5.0
              5

                4.0
              4

                0.8666667
              86,7%

0.8666667

                range() : void
                  range() : void

                141
                141

                22.0
              22

                0.0
              0%

                3.0
              3

                2.0
              2

                0.9166667
              91,7%

0.9166667

                stubBehavior() : void
                  stubBehavior() : void

                179
                179

                18.0
              18

                0.0
              0%

                3.0
              3

                2.0
              2

                0.9
              90%

0.9

          Show Tests (14) Select All  Deselect All

        Highlight

        Test Contribution

        Test

    Result

            <input type="checkbox" id="cb-845" value="845" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.23076923

            org.easymock.tests2.UsageStrictMockTest.differentMethods

            org.easymock.tests2.UsageStrictMockTest.differentMethods

                  1
    PASS

            <input type="checkbox" id="cb-1011" value="1011" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.23076923

            org.easymock.tests2.UsageStrictMockTest.differentMethods

            org.easymock.tests2.UsageStrictMockTest.differentMethods

                  1
    PASS

            <input type="checkbox" id="cb-998" value="998" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.1965812

            org.easymock.tests2.UsageStrictMockTest.range

            org.easymock.tests2.UsageStrictMockTest.range

                  1
    PASS

            <input type="checkbox" id="cb-266" value="266" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.1965812

            org.easymock.tests2.UsageStrictMockTest.range

            org.easymock.tests2.UsageStrictMockTest.range

                  1
    PASS

            <input type="checkbox" id="cb-858" value="858" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.16239317

            org.easymock.tests2.UsageStrictMockTest.stubBehavior

            org.easymock.tests2.UsageStrictMockTest.stubBehavior

                  1
    PASS

            <input type="checkbox" id="cb-249" value="249" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.16239317

            org.easymock.tests2.UsageStrictMockTest.stubBehavior

            org.easymock.tests2.UsageStrictMockTest.stubBehavior

                  1
    PASS

            <input type="checkbox" id="cb-655" value="655" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.07692308

            org.easymock.tests2.UsageStrictMockTest.tooFewCallsFailure

            org.easymock.tests2.UsageStrictMockTest.tooFewCallsFailure

                  1
    PASS

            <input type="checkbox" id="cb-61" value="61" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.07692308

            org.easymock.tests2.UsageStrictMockTest.tooManyCallsFailure

            org.easymock.tests2.UsageStrictMockTest.tooManyCallsFailure

                  1
    PASS

            <input type="checkbox" id="cb-935" value="935" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.07692308

            org.easymock.tests2.UsageStrictMockTest.tooManyCallsFailure

            org.easymock.tests2.UsageStrictMockTest.tooManyCallsFailure

                  1
    PASS

            <input type="checkbox" id="cb-983" value="983" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.07692308

            org.easymock.tests2.UsageStrictMockTest.tooFewCallsFailure

            org.easymock.tests2.UsageStrictMockTest.tooFewCallsFailure

                  1
    PASS

            <input type="checkbox" id="cb-150" value="150" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.05982906

            org.easymock.tests2.UsageStrictMockTest.unorderedCallsFailure

            org.easymock.tests2.UsageStrictMockTest.unorderedCallsFailure

                  1
    PASS

            <input type="checkbox" id="cb-603" value="603" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.05982906

            org.easymock.tests2.UsageStrictMockTest.unorderedCallsFailure

            org.easymock.tests2.UsageStrictMockTest.unorderedCallsFailure

                  1
    PASS

            <input type="checkbox" id="cb-265" value="265" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.034188036

            org.easymock.tests2.UsageStrictMockTest.orderedCallsSucces

            org.easymock.tests2.UsageStrictMockTest.orderedCallsSucces

                  1
    PASS

            <input type="checkbox" id="cb-645" value="645" name="testMethod" onclick="hiLightByTest(this.value, this.checked); return true;"/>

            0.034188036

            org.easymock.tests2.UsageStrictMockTest.orderedCallsSucces

            org.easymock.tests2.UsageStrictMockTest.orderedCallsSucces

                  1
    PASS

Collapse All

    1

    16

    17

      package org.easymock.tests2;

    18

    19

      import static org.easymock.EasyMock.*;

    20

      import static org.junit.Assert.*;

    21

    22

      import org.easymock.internal.ReplayState;

    23

      import org.easymock.tests.IMethods;

    24

      import org.easymock.tests.Util;

    25

      import org.junit.Before;

    26

      import org.junit.Test;

    27

    28

      /**

    29

       * @author OFFIS, Tammo Freese

    30

       */

	88%
           Uncovered Elements: 14 (117)
           Complexity: 22
           Complexity Density: 0,23

    31

      public class UsageStrictMockTest {

    32

          private IMethods mock;

    33

	100%
           Uncovered Elements: 0 (4)
           Complexity: 1
           Complexity Density: 0,25

    34

           14

          @Before...

    35

          public void setup() {

    36

           14

              mock = createStrictMock(IMethods.class);

    37

           14

              mock.simpleMethodWithArgument("1");

    38

           14

              mock.simpleMethodWithArgument("2");

    39

           14

              replay(mock);

    40

          }

    41

	100%
           Uncovered Elements: 0 (3)
           Complexity: 1
           Complexity Density: 0,33
                              1
    PASS

    42

           2

          @Test...

    43

          public void orderedCallsSucces() {

    44

           2

              mock.simpleMethodWithArgument("1");

    45

           2

              mock.simpleMethodWithArgument("2");

    46

           2

              verify(mock);

    47

          }

    48

	75%
           Uncovered Elements: 2 (8)
           Complexity: 3
           Complexity Density: 0,5
                              1
    PASS

    49

           2

          @Test...

    50

          public void unorderedCallsFailure() {

    51

           2

              boolean failed = false;

    52

           2

              try {

    53

           2

                  mock.simpleMethodWithArgument("2");

    54

              } catch (final AssertionError expected) {

    55

           2

                  failed = true;

    56

              }

    57

           2

              if (!failed) {

    58

           0

                  fail("unordered calls accepted");

    59

              }

    60

          }

    61

	80%
           Uncovered Elements: 2 (10)
           Complexity: 3
           Complexity Density: 0,38
                              1
    PASS

    62

           2

          @Test...

    63

          public void tooManyCallsFailure() {

    64

           2

              mock.simpleMethodWithArgument("1");

    65

           2

              mock.simpleMethodWithArgument("2");

    66

    67

           2

              boolean failed = false;

    68

           2

              try {

    69

           2

                  mock.simpleMethodWithArgument("2");

    70

              } catch (final AssertionError expected) {

    71

           2

                  failed = true;

    72

              }

    73

           2

              if (!failed) {

    74

           0

                  fail("too many calls accepted");

    75

              }

    76

          }

    77

	80%
           Uncovered Elements: 2 (10)
           Complexity: 3
           Complexity Density: 0,38
                              1
    PASS

    78

           2

          @Test...

    79

          public void tooFewCallsFailure() {

    80

           2

              mock.simpleMethodWithArgument("1");

    81

           2

              boolean failed = false;

    82

           2

              try {

    83

           2

                  verify(mock);

    84

              } catch (final AssertionError expected) {

    85

           2

                  failed = true;

    86

           2

                  assertTrue("stack trace must be filled in", Util.getStackTrace(expected).indexOf(

    87

                          ReplayState.class.getName()) == -1);

    88

              }

    89

           2

              if (!failed) {

    90

           0

                  fail("too few calls accepted");

    91

              }

    92

          }

    93

	86,7%
           Uncovered Elements: 4 (30)
           Complexity: 5
           Complexity Density: 0,19
                              1
    PASS

    94

           2

          @Test...

    95

          public void differentMethods() {

    96

    97

           2

              reset(mock);

    98

    99

           2

              mock.booleanReturningMethod(0);

    100

           2

              expectLastCall().andReturn(true);

    101

           2

              mock.simpleMethod();

    102

           2

              mock.booleanReturningMethod(1);

    103

           2

              expectLastCall().andReturn(false).times(2, 3);

    104

           2

              mock.simpleMethod();

    105

           2

              expectLastCall().atLeastOnce();

    106

    107

           2

              replay(mock);

    108

           2

              assertEquals(true, mock.booleanReturningMethod(0));

    109

           2

              mock.simpleMethod();

    110

    111

           2

              boolean failed = false;

    112

           2

              try {

    113

           2

                  verify(mock);

    114

              } catch (final AssertionError expected) {

    115

           2

                  failed = true;

    116

           2

                  assertEquals("\n  Expectation failure on verify:"

    117

                          + "\n    simpleMethod(): expected: 1, actual: 1"

    118

                          + "\n    booleanReturningMethod(1): expected: between 2 and 3, actual: 0"

    119

                          + "\n    simpleMethod(): expected: at least 1, actual: 0", expected.getMessage());

    120

              }

    121

           2

              if (!failed) {

    122

           0

                  fail("too few calls accepted");

    123

              }

    124

    125

           2

              assertEquals(false, mock.booleanReturningMethod(1));

    126

    127

           2

              failed = false;

    128

           2

              try {

    129

           2

                  mock.simpleMethod();

    130

              } catch (final AssertionError expected) {

    131

           2

                  failed = true;

    132

           2

                  assertEquals("\n  Unexpected method call simpleMethod():"

    133

                          + "\n    booleanReturningMethod(1): expected: between 2 and 3, actual: 1", expected

    134

                          .getMessage());

    135

              }

    136

           2

              if (!failed) {

    137

           0

                  fail("wrong call accepted");

    138

              }

    139

          }

    140

	91,7%
           Uncovered Elements: 2 (24)
           Complexity: 3
           Complexity Density: 0,14
                              1
    PASS

    141

           2

          @Test...

    142

          public void range() {

    143

    144

           2

              reset(mock);

    145

    146

           2

              mock.booleanReturningMethod(0);

    147

           2

              expectLastCall().andReturn(true);

    148

           2

              mock.simpleMethod();

    149

           2

              mock.booleanReturningMethod(1);

    150

           2

              expectLastCall().andReturn(false).times(2, 3);

    151

           2

              mock.simpleMethod();

    152

           2

              expectLastCall().atLeastOnce();

    153

           2

              expect(mock.booleanReturningMethod(1)).andReturn(false);

    154

    155

           2

              replay(mock);

    156

    157

           2

              mock.booleanReturningMethod(0);

    158

           2

              mock.simpleMethod();

    159

    160

           2

              mock.booleanReturningMethod(1);

    161

           2

              mock.booleanReturningMethod(1);

    162

           2

              mock.booleanReturningMethod(1);

    163

    164

           2

              boolean failed = false;

    165

    166

           2

              try {

    167

           2

                  mock.booleanReturningMethod(1);

    168

              } catch (final AssertionError expected) {

    169

           2

                  failed = true;

    170

           2

                  assertEquals("\n  Unexpected method call booleanReturningMethod(1):"

    171

                          + "\n    booleanReturningMethod(1): expected: between 2 and 3, actual: 4"

    172

                          + "\n    simpleMethod(): expected: at least 1, actual: 0", expected.getMessage());

    173

              }

    174

           2

              if (!failed) {

    175

           0

                  fail("too many calls accepted");

    176

              }

    177

          }

    178

	90%
           Uncovered Elements: 2 (20)
           Complexity: 3
           Complexity Density: 0,17
                              1
    PASS

    179

           2

          @Test...

    180

          public void stubBehavior() {

    181

           2

              reset(mock);

    182

    183

           2

              mock.booleanReturningMethod(1);

    184

           2

              expectLastCall().andReturn(true).andReturn(false).andReturn(true);

    185

           2

              mock.booleanReturningMethod(anyInt());

    186

           2

              expectLastCall().andStubReturn(true);

    187

    188

           2

              replay(mock);

    189

    190

           2

              assertEquals(true, mock.booleanReturningMethod(2));

    191

           2

              assertEquals(true, mock.booleanReturningMethod(3));

    192

           2

              assertEquals(true, mock.booleanReturningMethod(1));

    193

           2

              assertEquals(false, mock.booleanReturningMethod(1));

    194

           2

              assertEquals(true, mock.booleanReturningMethod(3));

    195

    196

           2

              boolean failed = false;

    197

           2

              try {

    198

           2

                  verify(mock);

    199

              } catch (final AssertionError expected) {

    200

           2

                  failed = true;

    201

           2

                  assertEquals("\n  Expectation failure on verify:"

    202

                          + "\n    booleanReturningMethod(1): expected: 3, actual: 2", expected.getMessage());

    203

              }

    204

           2

              if (!failed) {

    205

           0

                  fail("too few calls accepted");

    206

              }

    207

          }

    208

      }

 	Report generated by Clover Code Coverage v3.0.1
sam. mai 8 2010 14:37:33 CEST.
 	 	Clover: Open Source License registered to EasyMock .


text:
<?php
class Kwc_Composite_LinkImage_Admin extends Kwc_Abstract_Composite_Admin
{
    public function gridColumns()
    {
        $ret = parent::gridColumns();
        unset($ret['string']);
        return $ret;
    }
}


text:
    #include "wx/wx.h"
#endif // WX_PRECOMP

#include "wx/xlocale.h"

// --------------------------------------------------------------------------
// test class
// --------------------------------------------------------------------------

class XLocaleTestCase : public CppUnit::TestCase
{
public:
    XLocaleTestCase() { }

private:
    CPPUNIT_TEST_SUITE( XLocaleTestCase );
        CPPUNIT_TEST( TestCtor );
        CPPUNIT_TEST( PreserveLocale );
        CPPUNIT_TEST( TestCtypeFunctions );
        CPPUNIT_TEST( TestStdlibFunctions );
    CPPUNIT_TEST_SUITE_END();

    void TestCtor();
    void PreserveLocale();
    void TestCtypeFunctions();
    void TestStdlibFunctions();

    void TestCtypeFunctionsWith(const wxXLocale& loc);
    void TestStdlibFunctionsWith(const wxXLocale& loc);

    wxDECLARE_NO_COPY_CLASS(XLocaleTestCase);
};

// register in the unnamed registry so that these tests are run by default
CPPUNIT_TEST_SUITE_REGISTRATION( XLocaleTestCase );

// also include in its own registry so that these tests can be run alone
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( XLocaleTestCase, "XLocaleTestCase" );

// test the different wxXLocale ctors
void XLocaleTestCase::TestCtor()
{
    CPPUNIT_ASSERT( !wxXLocale().IsOk() );
    CPPUNIT_ASSERT( wxCLocale.IsOk() );
    CPPUNIT_ASSERT( wxXLocale("C").IsOk() );
    CPPUNIT_ASSERT( !wxXLocale("bloordyblop").IsOk() );

#ifdef wxHAS_XLOCALE_SUPPORT
    if ( wxXLocale(wxLANGUAGE_FRENCH).IsOk() )
    {
#ifdef __WINDOWS__
        CPPUNIT_ASSERT( wxXLocale("french").IsOk() );
#else
        CPPUNIT_ASSERT( wxXLocale("fr_FR").IsOk() );
#endif
    }
#endif // wxHAS_XLOCALE_SUPPORT
}

void XLocaleTestCase::PreserveLocale()
{
    // Test that using locale functions doesn't change the global C locale.
    const wxString origLocale(setlocale(LC_ALL, NULL));

    wxStrtod_l(wxT("1.234"), NULL, wxCLocale);

    CPPUNIT_ASSERT_EQUAL( origLocale, setlocale(LC_ALL, NULL) );
}

// test the ctype functions with the given locale
void XLocaleTestCase::TestCtypeFunctionsWith(const wxXLocale& loc)
{
    // NOTE: here go the checks which must pass under _any_ locale "loc";
    //       checks for specific locales are in TestCtypeFunctions()

    // isalnum
    CPPUNIT_ASSERT( wxIsalnum_l('0', loc) );
    CPPUNIT_ASSERT( wxIsalnum_l('9', loc) );
    CPPUNIT_ASSERT( wxIsalnum_l('A', loc) );
    CPPUNIT_ASSERT( wxIsalnum_l('Z', loc) );
    CPPUNIT_ASSERT( wxIsalnum_l('a', loc) );
    CPPUNIT_ASSERT( wxIsalnum_l('z', loc) );
    CPPUNIT_ASSERT( !wxIsalnum_l('*', loc) );
    CPPUNIT_ASSERT( !wxIsalnum_l('@', loc) );
    CPPUNIT_ASSERT( !wxIsalnum_l('+', loc) );

    // isalpha
    CPPUNIT_ASSERT( !wxIsalpha_l('0', loc) );
    CPPUNIT_ASSERT( !wxIsalpha_l('9', loc) );
    CPPUNIT_ASSERT( wxIsalpha_l('A', loc) );
    CPPUNIT_ASSERT( wxIsalpha_l('Z', loc) );
    CPPUNIT_ASSERT( wxIsalpha_l('a', loc) );
    CPPUNIT_ASSERT( wxIsalpha_l('z', loc) );
    CPPUNIT_ASSERT( !wxIsalpha_l('*', loc) );
    CPPUNIT_ASSERT( !wxIsalpha_l('@', loc) );
    CPPUNIT_ASSERT( !wxIsalpha_l('+', loc) );

    // TODO: iscntrl

    // isdigit
    CPPUNIT_ASSERT( wxIsdigit_l('0', loc) );
    CPPUNIT_ASSERT( wxIsdigit_l('9', loc) );
    CPPUNIT_ASSERT( !wxIsdigit_l('A', loc) );
    CPPUNIT_ASSERT( !wxIsdigit_l('Z', loc) );
    CPPUNIT_ASSERT( !wxIsdigit_l('a', loc) );
    CPPUNIT_ASSERT( !wxIsdigit_l('z', loc) );

    // TODO: isgraph

    // islower
    CPPUNIT_ASSERT( !wxIslower_l('A', loc) );
    CPPUNIT_ASSERT( !wxIslower_l('Z', loc) );
    CPPUNIT_ASSERT( wxIslower_l('a', loc) );
    CPPUNIT_ASSERT( wxIslower_l('z', loc) );
    CPPUNIT_ASSERT( !wxIslower_l('0', loc) );
    CPPUNIT_ASSERT( !wxIslower_l('9', loc) );

    // TODO: isprint
    // TODO: ispunct

    // isspace
    CPPUNIT_ASSERT( wxIsspace_l(' ', loc) );
    CPPUNIT_ASSERT( wxIsspace_l('\t', loc) );
    CPPUNIT_ASSERT( wxIsspace_l('\r', loc) );
    CPPUNIT_ASSERT( wxIsspace_l('\n', loc) );
    CPPUNIT_ASSERT( !wxIsspace_l('0', loc) );
    CPPUNIT_ASSERT( !wxIsspace_l('a', loc) );
    CPPUNIT_ASSERT( !wxIsspace_l('A', loc) );

    // isupper
    CPPUNIT_ASSERT( !wxIsupper_l('0', loc) );
    CPPUNIT_ASSERT( !wxIsupper_l('9', loc) );
    CPPUNIT_ASSERT( wxIsupper_l('A', loc) );
    CPPUNIT_ASSERT( wxIsupper_l('Z', loc) );
    CPPUNIT_ASSERT( !wxIsupper_l('a', loc) );
    CPPUNIT_ASSERT( !wxIsupper_l('z', loc) );

    // isxdigit
    CPPUNIT_ASSERT( wxIsxdigit_l('0', loc) );
    CPPUNIT_ASSERT( wxIsxdigit_l('9', loc) );
    CPPUNIT_ASSERT( wxIsxdigit_l('A', loc) );
    CPPUNIT_ASSERT( wxIsxdigit_l('F', loc) );
    CPPUNIT_ASSERT( !wxIsxdigit_l('Z', loc) );
    CPPUNIT_ASSERT( wxIsxdigit_l('a', loc) );
    CPPUNIT_ASSERT( wxIsxdigit_l('f', loc) );
    CPPUNIT_ASSERT( !wxIsxdigit_l('z', loc) );

    // tolower
    CPPUNIT_ASSERT_EQUAL( 'a', (char)wxTolower_l('A', loc) );
    CPPUNIT_ASSERT_EQUAL( 'a', (char)wxTolower_l('a', loc) );
    CPPUNIT_ASSERT_EQUAL( 'z', (char)wxTolower_l('Z', loc) );
    CPPUNIT_ASSERT_EQUAL( 'z', (char)wxTolower_l('z', loc) );
    CPPUNIT_ASSERT_EQUAL( '0', (char)wxTolower_l('0', loc) );
    CPPUNIT_ASSERT_EQUAL( '9', (char)wxTolower_l('9', loc) );

    // toupper
    CPPUNIT_ASSERT_EQUAL( 'A', (char)wxToupper_l('A', loc) );
    CPPUNIT_ASSERT_EQUAL( 'A', (char)wxToupper_l('a', loc) );
    CPPUNIT_ASSERT_EQUAL( 'Z', (char)wxToupper_l('Z', loc) );
    CPPUNIT_ASSERT_EQUAL( 'Z', (char)wxToupper_l('z', loc) );
    CPPUNIT_ASSERT_EQUAL( '0', (char)wxToupper_l('0', loc) );
    CPPUNIT_ASSERT_EQUAL( '9', (char)wxToupper_l('9', loc) );
}

// test the stdlib functions with the given locale
void XLocaleTestCase::TestStdlibFunctionsWith(const wxXLocale& loc)
{
    // NOTE: here go the checks which must pass under _any_ locale "loc";
    //       checks for specific locales are in TestStdlibFunctions()

#if wxUSE_UNICODE
    wchar_t* endptr;
#else
    char* endptr;
#endif

    // strtod (don't use decimal separator as it's locale-specific)
    CPPUNIT_ASSERT_EQUAL( 0.0,        wxStrtod_l(wxT("0"), NULL, loc) );
    CPPUNIT_ASSERT_EQUAL( 1234.0,     wxStrtod_l(wxT("1234"), NULL, loc) );

    // strtol
    endptr = NULL;
    CPPUNIT_ASSERT_EQUAL( 100,        wxStrtol_l(wxT("100"), NULL, 0, loc) );
    CPPUNIT_ASSERT_EQUAL( 0xFF,       wxStrtol_l(wxT("0xFF"), NULL, 0, loc) );
    CPPUNIT_ASSERT_EQUAL( 2001,       wxStrtol_l(wxT("2001 60c0c0 -1101110100110100100000 0x6fffff"), &endptr, 10, loc) );
    CPPUNIT_ASSERT_EQUAL( 0x60c0c0,   wxStrtol_l(endptr, &endptr, 16, loc) );
    CPPUNIT_ASSERT_EQUAL( -0x374D20,  wxStrtol_l(endptr, &endptr, 2, loc) );
    CPPUNIT_ASSERT_EQUAL( 0x6fffff,   wxStrtol_l(endptr, NULL, 0, loc) );

    // strtoul
    // NOTE: 3147483647 and 0xEE6B2800 are greater than LONG_MAX (on 32bit machines) but
    //       smaller than ULONG_MAX
    CPPUNIT_ASSERT_EQUAL( 3147483647ul,  wxStrtoul_l(wxT("3147483647"), NULL, 0, loc) );
    CPPUNIT_ASSERT_EQUAL( 0xEE6B2800ul, wxStrtoul_l(wxT("0xEE6B2800"), NULL, 0, loc) );

    // TODO: test for "failure" behaviour of the functions above
}

void XLocaleTestCase::TestCtypeFunctions()
{
    SECTION("C")
    {
        TestCtypeFunctionsWith(wxCLocale);
    }

#ifdef wxHAS_XLOCALE_SUPPORT
    SECTION("French")
    {
        wxXLocale locFR(wxLANGUAGE_FRENCH);
        if ( !locFR.IsOk() )
        {
            // Not an error, not all systems have French locale support.
            return;
        }

        TestCtypeFunctionsWith(locFR);

        CPPUNIT_ASSERT( wxIsalpha_l(wxT('\xe9'), locFR) );
        CPPUNIT_ASSERT( wxIslower_l(wxT('\xe9'), locFR) );
        CPPUNIT_ASSERT( !wxIslower_l(wxT('\xc9'), locFR) );
        CPPUNIT_ASSERT( wxIsupper_l(wxT('\xc9'), locFR) );
        CPPUNIT_ASSERT( wxIsalpha_l(wxT('\xe7'), locFR) );
        CPPUNIT_ASSERT( wxIslower_l(wxT('\xe7'), locFR) );
        CPPUNIT_ASSERT( wxIsupper_l(wxT('\xc7'), locFR) );
    }

    SECTION("Italian")
    {
        wxXLocale locIT(wxLANGUAGE_ITALIAN);
        if ( !locIT.IsOk() )
            return;

        TestCtypeFunctionsWith(locIT);

        CPPUNIT_ASSERT( wxIsalpha_l(wxT('\xe1'), locIT) );
        CPPUNIT_ASSERT( wxIslower_l(wxT('\xe1'), locIT) );
    }
#endif // wxHAS_XLOCALE_SUPPORT
}

void XLocaleTestCase::TestStdlibFunctions()
{
    SECTION("C")
    {
        TestStdlibFunctionsWith(wxCLocale);

#if wxUSE_UNICODE
        wchar_t* endptr;
#else
        char* endptr;
#endif

        // strtod checks specific for C locale
        endptr = NULL;
        CPPUNIT_ASSERT_EQUAL( 0.0,        wxStrtod_l(wxT("0.000"), NULL, wxCLocale) );
        CPPUNIT_ASSERT_EQUAL( 1.234,      wxStrtod_l(wxT("1.234"), NULL, wxCLocale) );
        CPPUNIT_ASSERT_EQUAL( -1.234E-5,  wxStrtod_l(wxT("-1.234E-5"), NULL, wxCLocale) );
        CPPUNIT_ASSERT_EQUAL( 365.24,     wxStrtod_l(wxT("365.24 29.53"), &endptr, wxCLocale) );
        CPPUNIT_ASSERT_EQUAL( 29.53,      wxStrtod_l(endptr, NULL, wxCLocale) );
    }

#ifdef wxHAS_XLOCALE_SUPPORT
    SECTION("French")
    {
        wxXLocale locFR(wxLANGUAGE_FRENCH);
        if ( !locFR.IsOk() )
            return;

        TestCtypeFunctionsWith(locFR);

        // comma as decimal point:
        CPPUNIT_ASSERT_EQUAL( 1.234, wxStrtod_l(wxT("1,234"), NULL, locFR) );

        // space as thousands separator is not recognized by wxStrtod_l():
        CPPUNIT_ASSERT( 1234.5 != wxStrtod_l(wxT("1 234,5"), NULL, locFR) );
    }

    SECTION("Italian")
    {
        wxXLocale locIT(wxLANGUAGE_ITALIAN);
        if ( !locIT.IsOk() )
            return;

        TestStdlibFunctionsWith(locIT);

        // comma as decimal point:
        CPPUNIT_ASSERT_EQUAL( 1.234, wxStrtod_l(wxT("1,234"), NULL, locIT) );

        // dot as thousands separator is not recognized by wxStrtod_l():
        CPPUNIT_ASSERT( 1234.5 != wxStrtod_l(wxT("1.234,5"), NULL, locIT) );
    }
#endif // wxHAS_XLOCALE_SUPPORT
}

#endif // wxUSE_XLOCALE


text:
Philips Hue plugin for [Homenet](http://www.denwilliams.net/homenet-core/)

> Requires `homenet-core` version `4.0.0-beta.15` or above.

## Installing

```
npm install -g homenet-hue
```

## Usage

Once installed globally it should be automatically discovered when you run `homenet4`.

## Configuration

In the configuration file create a `hue.hubs` key and register each Hue hub/controller.

> Note: at present

```json
{
  "hue": {
    "hubs": [
      { "id": "main", "name": "Main", "host": "192.168.0.123", "key": "valid_hue_api_key" }
    ]
  }
}
```

## Classes

Only the light class for Homenet is implemented.

To add an instance use the type `hue`.

For options specify the Hue `groupId` or `lightId` (should be an integer), and the ID of the hub registered above.

```json
{
  "instances": [
    { "class": "light", "id": "lounge-room", "type": "hue", "options": { "groupId": 3, "hub": "main" } }
  ]
}
```

## Example Config

```json
{
  "instances": [
    { "class": "light", "id": "lounge-room", "type": "hue", "options": { "groupId": 3, "hub": "main" } }
  ],
  "hue": {
    "hubs": [
      { "id": "main", "name": "Main", "host": "192.168.0.123", "key": "valid_hue_api_key" }
    ]
  }
}
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>7081 Schützen am Gebirge, Austria</formatted_address>
  <address_component>
   <long_name>Schützen am Gebirge</long_name>
   <short_name>Schützen am Gebirge</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Schützen am Gebirge</long_name>
   <short_name>Gemeinde Schützen am Gebirge</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Eisenstadt-Umgebung</long_name>
   <short_name>Eisenstadt-Umgebung</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Burgenland</long_name>
   <short_name>Burgenland</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>7081</long_name>
   <short_name>7081</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>47.8513884</lat>
    <lng>16.6293943</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>47.8477771</lat>
     <lng>16.6139930</lng>
    </southwest>
    <northeast>
     <lat>47.8577029</lat>
     <lng>16.6379854</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>47.8477771</lat>
     <lng>16.6139930</lng>
    </southwest>
    <northeast>
     <lat>47.8577029</lat>
     <lng>16.6379854</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJb8ANhAlHbEcRRakOyYYkxQ4</place_id>
 </result>
</GeocodeResponse>


text:
package com.evolveum.midpoint.wf.impl.processes.common;

import com.evolveum.midpoint.model.impl.expr.ModelExpressionThreadLocalHolder;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple;
import com.evolveum.midpoint.repo.common.expression.*;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.MiscUtil;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;

import static com.evolveum.midpoint.wf.impl.processes.common.SpringApplicationContextHolder.getExpressionFactory;

/**
 * @author mederly
 */
@Component
public class WfExpressionEvaluationHelper {

	public List<ObjectReferenceType> evaluateRefExpressions(List<ExpressionType> expressions,
			ExpressionVariables variables, String contextDescription,
			Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException {
		List<ObjectReferenceType> retval = new ArrayList<>();
		for (ExpressionType expression : expressions) {
			retval.addAll(evaluateRefExpression(expression, variables, contextDescription, task, result));
		}
		return retval;
	}

	public List<ObjectReferenceType> evaluateRefExpression(ExpressionType expressionType, ExpressionVariables variables,
			String contextDescription, Task task, OperationResult result)
			throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
		return evaluateExpression(expressionType, variables, contextDescription, ObjectReferenceType.class,
				ObjectReferenceType.COMPLEX_TYPE, false, ExpressionUtil.createRefConvertor(UserType.COMPLEX_TYPE), task, result);
	}

	@SuppressWarnings("unchecked")
	@NotNull
	public <T> List<T> evaluateExpression(ExpressionType expressionType, ExpressionVariables variables,
			String contextDescription, Class<T> clazz, QName typeName,
			boolean multiValued, Function<Object, Object> additionalConvertor, Task task,
			OperationResult result)
			throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
		ExpressionFactory expressionFactory = getExpressionFactory();
		PrismContext prismContext = expressionFactory.getPrismContext();
		ItemDefinition<?> resultDef;
		QName resultName = new QName(SchemaConstants.NS_C, "result");
		if (QNameUtil.match(typeName, ObjectReferenceType.COMPLEX_TYPE)) {
			resultDef = new PrismReferenceDefinitionImpl(resultName, typeName, prismContext);
		} else {
			resultDef = new PrismPropertyDefinitionImpl<>(resultName, typeName, prismContext);
		}
		if (multiValued) {
			resultDef.setMaxOccurs(-1);
		}
		Expression<?,?> expression = expressionFactory.makeExpression(expressionType, resultDef, contextDescription, task, result);
		ExpressionEvaluationContext context = new ExpressionEvaluationContext(null, variables, contextDescription, task, result);
		context.setAdditionalConvertor(additionalConvertor);
		PrismValueDeltaSetTriple<?> exprResultTriple = ModelExpressionThreadLocalHolder
				.evaluateAnyExpressionInContext(expression, context, task, result);
		List<T> list = new ArrayList<>();
		for (PrismValue pv : exprResultTriple.getZeroSet()) {
			T realValue;
			if (pv instanceof PrismReferenceValue) {
				// pv.getRealValue sometimes returns synthesized Referencable, not ObjectReferenceType
				// If we would stay with that we would need to make many changes throughout workflow module.
				// So it is safer to stay with ObjectReferenceType.
				ObjectReferenceType ort = new ObjectReferenceType();
				ort.setupReferenceValue((PrismReferenceValue) pv);
				realValue = (T) ort;
			} else {
				realValue = pv.getRealValue();
			}
			list.add(realValue);
		}
		return list;
	}

	public boolean evaluateBooleanExpression(ExpressionType expressionType, ExpressionVariables expressionVariables,
			String contextDescription, Task task, OperationResult result)
			throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
		Collection<Boolean> values = evaluateExpression(expressionType, expressionVariables, contextDescription,
				Boolean.class, DOMUtil.XSD_BOOLEAN, false, null, task, result);
		return MiscUtil.getSingleValue(values, false, contextDescription);
	}

	public String evaluateStringExpression(ExpressionType expressionType, ExpressionVariables expressionVariables,
			String contextDescription, Task task, OperationResult result)
			throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
		Collection<String> values = evaluateExpression(expressionType, expressionVariables, contextDescription,
				String.class, DOMUtil.XSD_STRING, false, null, task, result);
		return MiscUtil.getSingleValue(values, null, contextDescription);
	}
}


text:
import { useCallback, useEffect, useState } from 'react';
import * as React from 'react';
import * as fp from 'lodash/fp';
import { Column } from 'primereact/column';
import { DataTable } from 'primereact/datatable';
import { Dropdown } from 'primereact/dropdown';

import { EgressEvent } from 'generated/fetch';

import { AdminUserLink } from 'app/components/admin/admin-user-link';
import { StyledRouterLink } from 'app/components/buttons';
import { egressEventsAdminApi } from 'app/services/swagger-fetch-clients';
import { mutableEgressEventStatuses } from 'app/utils/egress-events';

interface Props {
  sourceUserEmail?: string;
  sourceWorkspaceNamespace?: string;
  displayPageSize?: number;
}

export const EgressEventsTable = ({
  sourceUserEmail,
  sourceWorkspaceNamespace,
  displayPageSize = 20,
}: Props) => {
  const [loading, setLoading] = useState(false);
  const [first, setFirst] = useState(0);
  const [events, setEvents] = useState<EgressEvent[]>(null);
  const [nextPageToken, setNextPageToken] = useState<string>(null);
  const [totalRecords, setTotalRecords] = useState<number>(null);
  const [pendingUpdateEvent, setPendingUpdateEvent] =
    useState<EgressEvent>(null);

  // This callback fetches more events and appends to the events array, if needed.
  // This works by continuing to walk the paginated stream until the given event count
  // is satisfied. Note that the backend pages are independent of the displayed pages
  // within the DataTable.
  const maybeFetchMoreEvents = useCallback(
    async (atLeastCount: number): Promise<void> => {
      if (loading || events?.length >= atLeastCount) {
        return;
      }
      if (events && !nextPageToken) {
        // We've loaded at least one page, and there's no more data to load.
        return;
      }
      setLoading(true);

      let pageToken = nextPageToken;
      const allLoadedEvents = [...(events || [])];
      do {
        const resp = await egressEventsAdminApi().listEgressEvents({
          sourceUserEmail,
          sourceWorkspaceNamespace,
          pageToken,
        });
        setTotalRecords(resp.totalSize);

        allLoadedEvents.push(...resp.events);
        pageToken = resp.nextPageToken;
      } while (pageToken && allLoadedEvents.length < atLeastCount);
      setEvents(allLoadedEvents);
      setNextPageToken(pageToken);
      setLoading(false);
    },
    [loading, events, nextPageToken]
  );

  const onRowEditSave = useCallback(async () => {
    if (!pendingUpdateEvent) {
      return;
    }

    const i = events.findIndex(
      ({ egressEventId }) => egressEventId === pendingUpdateEvent.egressEventId
    );
    if (fp.isEqual(events[i], pendingUpdateEvent)) {
      return;
    }

    setLoading(true);
    const updatedEvent = await egressEventsAdminApi().updateEgressEvent(
      pendingUpdateEvent.egressEventId,
      { egressEvent: pendingUpdateEvent }
    );
    const updatedEvents = events.slice();
    updatedEvents.splice(i, 1, updatedEvent);
    setEvents(updatedEvents);
    setPendingUpdateEvent(null);
    setLoading(false);
  }, [events, pendingUpdateEvent]);

  const statusEditor = ({ rowData }) => {
    return (
      <Dropdown
        value={pendingUpdateEvent?.status ?? rowData.status}
        options={mutableEgressEventStatuses}
        onChange={(e) => {
          setPendingUpdateEvent({
            ...rowData,
            status: e.value,
          });
        }}
        placeholder='Select a Status'
      />
    );
  };

  useEffect(() => {
    maybeFetchMoreEvents(2 * displayPageSize);
  }, []);

  const displayEvents = events?.slice(first, first + displayPageSize);
  return (
    <DataTable
      lazy
      paginator
      loading={loading}
      editMode='row'
      onRowEditSave={onRowEditSave}
      onRowEditCancel={() => setPendingUpdateEvent(null)}
      value={displayEvents}
      onPage={async (e) => {
        await maybeFetchMoreEvents(e.first + e.rows - 1);
        setFirst(e.first);
      }}
      first={first}
      rows={displayPageSize}
      totalRecords={totalRecords}
    >
      <Column
        field='egressEventId'
        body={({ egressEventId }) => (
          <StyledRouterLink
            data-test-id='egress-event-id'
            path={`/admin/egress-events/${egressEventId}`}
          >
            {egressEventId}
          </StyledRouterLink>
        )}
        header='Event ID'
        headerStyle={{ width: '100px' }}
      />
      <Column
        field='creationTime'
        header='Time'
        headerStyle={{ width: '150px' }}
        body={({ creationTime }) => new Date(creationTime).toLocaleString()}
      />
      <Column
        field='sourceUserEmail'
        body={({ sourceUserEmail: email }) => {
          const [username] = email.split('@');
          return <AdminUserLink {...{ username }}>{email}</AdminUserLink>;
        }}
        header='Source User'
        headerStyle={{ width: '300px' }}
      />
      <Column
        field='sourceWorkspaceNamespace'
        body={({ sourceWorkspaceNamespace: namespace }) => {
          return (
            <StyledRouterLink path={`/admin/workspaces/${namespace}`}>
              {namespace}
            </StyledRouterLink>
          );
        }}
        header='Source Workspace Namespace'
        headerStyle={{ width: '250px' }}
      />
      <Column
        field='status'
        editor={(options) => statusEditor(options)}
        header='Status'
        headerStyle={{ width: '200px' }}
      />
      <Column
        rowEditor
        headerStyle={{ width: '10%', minWidth: '8rem' }}
        bodyStyle={{ textAlign: 'center' }}
      ></Column>
    </DataTable>
  );
};


text:
class AddTmdbImagesToMovies < ActiveRecord::Migration[5.2]
  def change
    add_column :movies, :tmdb_images, :jsonb, :null => false, :default => {}
  end
end


text:
namespace exjs {
    export function anonymous<T>(iterator: (en: IEnumerator<T>) => boolean): IEnumerableEx<T> {
        var enumerable = new Enumerable<T>();
        enumerable.getEnumerator = () => {
            var enumerator = {
                current: undefined,
                moveNext: () => iterator(enumerator)
            };
            return enumerator;
        };
        return enumerable;
    }
}


text:
extern crate bitflags;
extern crate libc;

#[cfg(target_os="macos")]
pub mod appkit;
#[cfg(target_os="macos")]
pub mod base;


text:
//
//  KBYourTube.h
//  yourTube
//
//  Created by Kevin Bradley on 12/21/15.
//  Copyright © 2015 nito. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import "KBYourTube+Categories.h"
#import "APDeviceController.h"
#if TARGET_OS_IOS
#import "KBYTMessagingCenter.h"
#endif
#import "YTKBPlayerViewController.h"
#import "KBYTQueuePlayer.h"
// Logging

/*

 //music channel = UC-9-kyTW8ZkZNDHQJ6FgpwQ
 //popular on yt = UCF0pVplsI8R5kcAqgtoRqoA
 //sports = UCEgdi0XIXXZ-qJOFPf4JSKw
 //gaming = UCOpNcN46UbXVtpKMrmU4Abg
 //360 = UCzuqhhs6NWbgTzMuM09WKDQ

 dont have videos

 //news = UCYfdidRxbB8Qhf0Nx7ioOYw
 //live = UC4R8DWoMoI7CAwX8_LjQHig

 */

static NSString *const KBYTMusicChannelID   =  @"UC-9-kyTW8ZkZNDHQJ6FgpwQ";
static NSString *const KBYTPopularChannelID =  @"UCF0pVplsI8R5kcAqgtoRqoA";
static NSString *const KBYTSportsChannelID  =  @"UCEgdi0XIXXZ-qJOFPf4JSKw";
static NSString *const KBYTGamingChannelID  =  @"UCOpNcN46UbXVtpKMrmU4Abg";
static NSString *const KBYT360ChannelID     =  @"UCzuqhhs6NWbgTzMuM09WKDQ";

@protocol YTPlayerItemProtocol <NSObject>
- (NSString *)duration;
- (NSString *)title;
- (NSString *)videoId;
@end

@interface YTBrowserHelper : NSObject

+ (id)sharedInstance;
- (void)importFileWithJO:(NSString *)theFile duration:(NSInteger)duration;
- (void)fixAudio:(NSString *)theFile volume:(NSInteger)volume completionBlock:(void(^)(NSString *newFile))completionBlock;
- (void)fileCopyTest:(NSString *)theFile;

@end

typedef NS_ENUM(NSUInteger, YTSearchResultType) {

    YTSearchResultTypeUnknown,
    YTSearchResultTypeVideo,
    YTSearchResultTypePlaylist,
    YTSearchResultTypeChannel,
    YTSearchResultTypeChannelList,
};

@interface KBYTLocalMedia : NSObject <YTPlayerItemProtocol>

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *author;
@property (nonatomic, strong) NSString *videoId;
@property (nonatomic, strong) NSString *views;
@property (nonatomic, strong) NSString *duration;
@property (nonatomic, strong) NSDictionary *images;
@property (nonatomic, strong) NSString *extension;
@property (nonatomic, strong) NSString *format;
@property (nonatomic, strong) NSString *filePath;
@property (nonatomic, strong) NSString *outputFilename;
@property (readwrite, assign) BOOL inProgress;

- (id)initWithDictionary:(NSDictionary *)inputDict;
- (NSDictionary *)dictionaryValue;

@end

@interface YTPlayerItem: AVPlayerItem

@property (nonatomic, weak) NSObject <YTPlayerItemProtocol> *associatedMedia;

@end

@interface KBYTMedia : NSObject <YTPlayerItemProtocol>

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *author;
@property (nonatomic, strong) NSString *keywords;
@property (nonatomic, strong) NSString *videoId;
@property (nonatomic, strong) NSString *channelId; //what channel does video belong to
@property (nonatomic, strong) NSString *views;
@property (nonatomic, strong) NSString *duration;
@property (nonatomic, strong) NSDictionary *images;
@property (nonatomic, strong) NSArray *streams;
@property (nonatomic, strong) NSString *details; //description
@property (readwrite, assign) NSInteger expireTime;

- (BOOL)isExpired;
- (NSDictionary *)dictionaryRepresentation;
- (YTPlayerItem *)playerItemRepresentation;
@end

@interface KBYTSearchResult: NSObject

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *author;
@property (nonatomic, strong) NSString *videoId;
@property (nonatomic, strong) NSString *channelPath; //what channel does video belong to
@property (nonatomic, strong) NSString *channelId; //what channel does video belong to
@property (nonatomic, strong) NSString *duration;
@property (nonatomic, strong) NSString *imagePath;
@property (nonatomic, strong) NSString *age;
@property (nonatomic, strong) NSString *views;
@property (nonatomic, strong) NSString *details;
@property (nonatomic, strong) KBYTMedia *media;
@property (readwrite, assign) YTSearchResultType resultType;
@property (nonatomic, strong) NSArray *items; //only relevant for channel list

- (id)initWithDictionary:(NSDictionary *)resultDict;
- (NSString *)readableSearchType;
@end

@interface KBYTStream : NSObject

@property (readwrite, assign) BOOL multiplexed;
@property (nonatomic, strong) NSString *outputFilename;
@property (nonatomic, strong) NSString *quality;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *format;
@property (nonatomic, strong) NSNumber *height;
@property (readwrite, assign) NSInteger itag;
@property (nonatomic, strong) NSString *s;
@property (nonatomic, strong) NSString *extension;
@property (nonatomic, strong) NSURL *url;
@property (readwrite, assign) BOOL playable;
@property (nonatomic, assign) KBYTStream *audioStream; //will be empty if its multiplexed
@property (readwrite, assign) NSInteger expireTime;

- (id)initWithDictionary:(NSDictionary *)streamDict;
- (NSDictionary *)dictionaryValue;
- (BOOL)isExpired;

@end

#import "Ono/ONOXMLDocument.h"

@interface KBYourTube : NSObject
{
    NSInteger bestTag;
}

@property (nonatomic, strong) APDeviceController *deviceController;
@property (nonatomic, strong) NSString *yttimestamp;
@property (nonatomic, strong) NSString *ytkey;
@property (nonatomic, strong) NSString *airplayIP;
@property (nonatomic, strong) NSString *lastSearch;
@property (nonatomic, strong) NSDictionary *userDetails;

+ (YTSearchResultType)resultTypeForString:(NSString *)string;
+ (id)sharedInstance;
- (BOOL)isSignedIn;
- (void)documentFromURL:(NSString *)theURL completion:(void(^)(ONOXMLDocument *document))block;
- (ONOXMLDocument *)documentFromURL:(NSString *)theURL;
- (NSDictionary *)channelIDAndWatchLaterCount;
- (NSString *)videoDescription:(NSString *)videoID;
- (NSDictionary *)videoDetailsFromID:(NSString *)videoID;

- (void)getUserDetailsDictionaryWithCompletionBlock:(void(^)(NSDictionary *outputResults))completionBlock
                                       failureBlock:(void(^)(NSString *error))failureBlock;

- (void)loadMoreVideosFromHREF:(NSString *)loadMoreLink
               completionBlock:(void(^)(NSDictionary *outputResults))completionBlock
                  failureBlock:(void(^)(NSString *error))failureBlock;

- (void)loadMorePlaylistVideosFromHREF:(NSString *)loadMoreLink
                       completionBlock:(void(^)(NSDictionary *outputResults))completionBlock
                          failureBlock:(void(^)(NSString *error))failureBlock;

/**

 searchQuery is just a basic unescaped search string, this will return a dictionary with
 results, pageCount, resultCount. Beware this is super fragile, if youtube website changes
 this will almost definitely break. that being said its MUCH quicker then getSearchResults

 */

- (void)getOrganizedChannelData:(NSString *)channelID
                completionBlock:(void(^)(NSDictionary* searchDetails))completionBlock
                   failureBlock:(void(^)(NSString* error))failureBlock;

- (void)youTubeSearch:(NSString *)searchQuery
           pageNumber:(NSInteger)page
    includeAllResults:(BOOL)includeAl
      completionBlock:(void(^)(NSDictionary* searchDetails))completionBlock
         failureBlock:(void(^)(NSString* error))failureBlock;

- (void)getPlaylistVideos:(NSString *)listID
          completionBlock:(void(^)(NSDictionary * playlistDetails))completionBlock
             failureBlock:(void(^)(NSString *error))failureBlock;

- (void)getUserVideos:(NSString *)channelID
      completionBlock:(void(^)(NSDictionary *searchDetails))completionBlock
         failureBlock:(void(^)(NSString *error))failureBlock;

- (void)getChannelVideos:(NSString *)channelID
         completionBlock:(void(^)(NSDictionary *searchDetails))completionBlock
            failureBlock:(void(^)(NSString *error))failureBlock;

- (void)getAllFeaturedVideosWithFilter:(NSString *)filter
                       completionBlock:(void(^)(NSDictionary* searchDetails))completionBlock
                          failureBlock:(void(^)(NSString* error))failureBlock;

- (void)getFeaturedVideosWithCompletionBlock:(void(^)(NSDictionary* searchDetails))completionBlock
                                failureBlock:(void(^)(NSString* error))failureBlock;

- (void)getVideoDetailsForSearchResults:(NSArray*)searchResults
                        completionBlock:(void(^)(NSArray* videoArray))completionBlock
                           failureBlock:(void(^)(NSString* error))failureBlock;

- (void)getSearchResults:(NSString *)searchQuery
              pageNumber:(NSInteger)page
         completionBlock:(void(^)(NSDictionary* searchDetails))completionBlock
            failureBlock:(void(^)(NSString* error))failureBlock;

- (void)getVideoDetailsForIDs:(NSArray*)videoIDs
              completionBlock:(void(^)(NSArray* videoArray))completionBlock
                 failureBlock:(void(^)(NSString* error))failureBlock;

- (void)getVideoDetailsForID:(NSString*)videoID
             completionBlock:(void(^)(KBYTMedia* videoDetails))completionBlock
                failureBlock:(void(^)(NSString* error))failureBlock;

- (NSString *)decodeSignature:(NSString *)theSig;

+ (NSDictionary *)formatFromTag:(NSInteger)tag;
- (void)playMedia:(KBYTMedia *)media ToDeviceIP:(NSString *)deviceIP;
- (void)airplayStream:(NSString *)stream ToDeviceIP:(NSString *)deviceIP;
- (void)pauseAirplay;
- (NSInteger)airplayStatus;
@end


text:
#pragma once

#include <string>

#include <asl.h>

#include <osquery/core/tables.h>
#include <osquery/logger/logger.h>

#ifndef ASL_API_VERSION
#define OLD_ASL_API
#endif

namespace osquery {
namespace tables {

#ifdef OLD_ASL_API
inline void asl_release(aslmsg msg) { asl_free(msg); }

inline void asl_release(aslresponse resp) { aslresponse_free(resp); }

inline aslmsg asl_next(aslresponse resp) { return aslresponse_next(resp); }
#endif

/**
 * @brief Add a new operation to the query.
 *
 * All of the operations are logically ANDed when performing the query.
 *
 * @param query The query on which to add the operation
 * @param key Key to match on
 * @param value Value that should match for the key and operation.
 * @param op The (osquery) operator to use. Will be converted to the equivalent
 * ASL operator.
 * @param col_type Type of the column that this operation is performed on.
 */
void addQueryOp(aslmsg& query,
                const std::string& key,
                const std::string& value,
                ConstraintOperator op,
                ColumnType col_type);

/**
 * @brief Create an ASL query object from the QueryContext.
 *
 * @param context QueryContext used to form the query.
 *
 * @return An ASL query object corresponding to the context.
 */
aslmsg createAslQuery(const QueryContext& context);

/**
 * @brief Read a row of ASL data into an osquery Row.
 *
 * @param row The ASL row to read data from.
 * @param r The osquery Row to write data into.
 */
void readAslRow(aslmsg row, Row& r);

/**
 * @brief Convert a LIKE format string into a regex
 *
 * @param like_str The LIKE style string to convert
 *
 * @return A regex corresponding to the input LIKE string
 */
std::string convertLikeRegex(const std::string& like_str);
}
}