text:
#include <string.h>
#include <stdlib.h>

#include <misc/hashfun.h>
#include <misc/strdup.h>
#include <misc/array_length.h>
#include <base/BLog.h>

#include "NCDStringIndex.h"

#include "NCDStringIndex_hash.h"
#include <structure/CHash_impl.h>

#define GROWARRAY_NAME Array
#define GROWARRAY_OBJECT_TYPE NCDStringIndex
#define GROWARRAY_ARRAY_MEMBER entries
#define GROWARRAY_CAPACITY_MEMBER entries_capacity
#define GROWARRAY_MAX_CAPACITY NCD_STRING_ID_MAX
#include <misc/grow_array.h>

#include <generated/blog_channel_ncd.h>

// NOTE: keep synchronized with static_strings.h
static const char *static_strings[] = {
    "",
    "_args",
    "_arg0",
    "_arg1",
    "_arg2",
    "_arg3",
    "_arg4",
    "_arg5",
    "_arg6",
    "_arg7",
    "_arg8",
    "_arg9",
    "_arg10",
    "_arg11",
    "_arg12",
    "_arg13",
    "_arg14",
    "_arg15",
    "_arg16",
    "_arg17",
    "_arg18",
    "_arg19",
    "true",
    "false",
    "<none>",
    "_caller",
    "succeeded",
    "is_error",
    "not_eof",
    "length",
    "type",
    "exit_status",
    "size",
    "eof",
    "_scope",
};

static NCD_string_id_t do_get (NCDStringIndex *o, const char *str, size_t str_len)
{
    ASSERT(str)

    NCDStringIndex_hash_key key = {str, str_len};
    NCDStringIndex__HashRef ref = NCDStringIndex__Hash_Lookup(&o->hash, o->entries, key);
    ASSERT(ref.link == -1 || ref.link >= 0)
    ASSERT(ref.link == -1 || ref.link < o->entries_size)
    ASSERT(ref.link == -1 || (ref.ptr->str_len == str_len && !memcmp(ref.ptr->str, str, str_len)))

    if (ref.link != -1) {
        return ref.link;
    }

    if (o->entries_size == o->entries_capacity) {
        if (!Array_DoubleUp(o)) {
            BLog(BLOG_ERROR, "Array_DoubleUp failed");
            return -1;
        }

        if (!NCDStringIndex__Hash_MultiplyBuckets(&o->hash, o->entries, 1)) {
            BLog(BLOG_ERROR, "NCDStringIndex__Hash_MultiplyBuckets failed");
            return -1;
        }
    }

    ASSERT(o->entries_size < o->entries_capacity)

    struct NCDStringIndex__entry *entry = &o->entries[o->entries_size];

    if (!(entry->str = b_strdup_bin(str, str_len))) {
        BLog(BLOG_ERROR, "b_strdup_bin failed");
        return -1;
    }
    entry->str_len = str_len;
    entry->has_nulls = !!memchr(str, '\0', str_len);

    NCDStringIndex__HashRef newref = {entry, o->entries_size};
    int res = NCDStringIndex__Hash_Insert(&o->hash, o->entries, newref, NULL);
    ASSERT_EXECUTE(res)

    return o->entries_size++;
}

int NCDStringIndex_Init (NCDStringIndex *o)
{
    o->entries_size = 0;

    if (!Array_Init(o, NCDSTRINGINDEX_INITIAL_CAPACITY)) {
        BLog(BLOG_ERROR, "Array_Init failed");
        goto fail0;
    }

    if (!NCDStringIndex__Hash_Init(&o->hash, NCDSTRINGINDEX_INITIAL_HASH_BUCKETS)) {
        BLog(BLOG_ERROR, "NCDStringIndex__Hash_Init failed");
        goto fail1;
    }

    for (size_t i = 0; i < B_ARRAY_LENGTH(static_strings); i++) {
        if (do_get(o, static_strings[i], strlen(static_strings[i])) < 0) {
            goto fail2;
        }
    }

    DebugObject_Init(&o->d_obj);
    return 1;

fail2:
    for (NCD_string_id_t i = 0; i < o->entries_size; i++) {
        free(o->entries[i].str);
    }
    NCDStringIndex__Hash_Free(&o->hash);
fail1:
    Array_Free(o);
fail0:
    return 0;
}

void NCDStringIndex_Free (NCDStringIndex *o)
{
    DebugObject_Free(&o->d_obj);

    for (NCD_string_id_t i = 0; i < o->entries_size; i++) {
        free(o->entries[i].str);
    }

    NCDStringIndex__Hash_Free(&o->hash);
    Array_Free(o);
}

NCD_string_id_t NCDStringIndex_Lookup (NCDStringIndex *o, const char *str)
{
    DebugObject_Access(&o->d_obj);
    ASSERT(str)

    return NCDStringIndex_LookupBin(o, str, strlen(str));
}

NCD_string_id_t NCDStringIndex_LookupBin (NCDStringIndex *o, const char *str, size_t str_len)
{
    DebugObject_Access(&o->d_obj);
    ASSERT(str)

    NCDStringIndex_hash_key key = {str, str_len};
    NCDStringIndex__HashRef ref = NCDStringIndex__Hash_Lookup(&o->hash, o->entries, key);
    ASSERT(ref.link == -1 || ref.link >= 0)
    ASSERT(ref.link == -1 || ref.link < o->entries_size)
    ASSERT(ref.link == -1 || (ref.ptr->str_len == str_len && !memcmp(ref.ptr->str, str, str_len)))

    return ref.link;
}

NCD_string_id_t NCDStringIndex_Get (NCDStringIndex *o, const char *str)
{
    DebugObject_Access(&o->d_obj);
    ASSERT(str)

    return NCDStringIndex_GetBin(o, str, strlen(str));
}

NCD_string_id_t NCDStringIndex_GetBin (NCDStringIndex *o, const char *str, size_t str_len)
{
    DebugObject_Access(&o->d_obj);
    ASSERT(str)

    return do_get(o, str, str_len);
}

NCD_string_id_t NCDStringIndex_GetBinMr (NCDStringIndex *o, MemRef str)
{
    return NCDStringIndex_GetBin(o, str.ptr, str.len);
}

MemRef NCDStringIndex_Value (NCDStringIndex *o, NCD_string_id_t id)
{
    DebugObject_Access(&o->d_obj);
    ASSERT(id >= 0)
    ASSERT(id < o->entries_size)
    ASSERT(o->entries[id].str)

    return MemRef_Make(o->entries[id].str, o->entries[id].str_len);
}

int NCDStringIndex_HasNulls (NCDStringIndex *o, NCD_string_id_t id)
{
    DebugObject_Access(&o->d_obj);
    ASSERT(id >= 0)
    ASSERT(id < o->entries_size)
    ASSERT(o->entries[id].str)

    return o->entries[id].has_nulls;
}

int NCDStringIndex_GetRequests (NCDStringIndex *o, struct NCD_string_request *requests)
{
    DebugObject_Access(&o->d_obj);
    ASSERT(requests)

    while (requests->str) {
        NCD_string_id_t id = NCDStringIndex_Get(o, requests->str);
        if (id < 0) {
            return 0;
        }
        requests->id = id;
        requests++;
    }

    return 1;
}


text:
import sys

if sys.version_info[0] <= 2:
    range = xrange  # permits using  for x in range()
    uchr = unichr
    PYTHON3 = False
else:
    uchr = chr
    PYTHON3 = True

# from http://docs.python.org/py3k/howto/pyporting.html
class UnicodeMixin(object):
    """Mixin class to handle defining the proper __str__/__unicode__
       methods in Python 2 or 3."""

    if sys.version_info[0] >= 3:
        def __str__(self):
            return self.__unicode__()
    else:
        def __str__(self):
            return self.__unicode__().encode('utf8')

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import { push } from 'react-router-redux';

// **********  Data Content for Feature Page and Homepage Feature List
import featureList from './list';

// ************************************************************************
// Collection of Bootstrap/Styles formatting components
// ************************************************************************

import { Grid, Row, Col } from 'react-bootstrap';
import UGFourRowWrapper from './UGFourRowWrapper';
import UGFeatureWrapper from './UGFeatureWrapper';
import UGFeatureHeaderStyle from './UGFeatureHeaderStyle';
import UGFeatureFixHeight from './UGFeatureFixheight';
import UGFeatureImageStyle from './UGFeatureImageStyle';
import UGFeatureDescriptionStyle from './UGFeatureDescriptionStyle';
import UGFeatureButtonStyle from './UGFeatureButtonStyle';

// ************************************************************************
// Wrapper Components
// ************************************************************************
import UGFeatureBox from './UGFeatureBox';
import UGFeatureHeader from './UGFeatureHeader';

const FeaturesListing = featureList.map((items, index) =>
  <UGFeatureWrapper key={index}>
    <Col md={3} sm={6}>
      <UGFeatureBox>
        <UGFeatureFixHeight>
          <UGFeatureImageStyle>

          </UGFeatureImageStyle>

            <UGFeatureHeaderStyle>{items.title}</UGFeatureHeaderStyle>

          <UGFeatureDescriptionStyle>{items.description}</UGFeatureDescriptionStyle>
        </UGFeatureFixHeight>
        <UGFeatureButtonStyle>{items.label}</UGFeatureButtonStyle>
      </UGFeatureBox>
    </Col>
  </UGFeatureWrapper>
);

// ************************************************************************
// Main Feature Listing component
// ************************************************************************

export class UGFeatureListing extends React.Component {
  openUGFeatureListing = () => {
    this.props.dispatch(push('/'));
  };
  render() {
    return (
      <UGFourRowWrapper>
        <Grid>
          <Row>
            <UGFeatureHeader
              title="ügroop Features"
              description="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eu ante mattis"
            />
          </Row>
          <Row>
            {FeaturesListing}
          </Row>
        </Grid>
      </UGFourRowWrapper>
    );
  }
}

// ************************************************************************
// Components Props type definition
// ************************************************************************

UGFeatureListing.propTypes = {
  dispatch: React.PropTypes.func,
};

export default UGFeatureListing;


text:
package com.satvaimal.hellopersistence.dao.impl;

import com.satvaimal.hellopersistence.CommonTestConfig;
import com.satvaimal.hellopersistence.AppConfig;
import com.satvaimal.hellopersistence.dao.AuthorDao;
import com.satvaimal.hellopersistence.domain.Author;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@CommonTestConfig
public class AuthorDaoImplSaveTests {

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @PersistenceContext
  private EntityManager em;

  @Autowired
  private AuthorDao authorDao;

  @Test
  public void entityPersistedSuccessfully() throws Exception {

    Author author = new Author();
    author.setName( "J. R. Tolkien" );
    author.setBirthdate( new Date() );
    authorDao.save( author );
    assertEquals( 1, em.createQuery(
        "select a from Author a" ).getResultList().size() );

  }// End of method

  @Test
  public void entityWithErrors() throws Exception {

    Author author = new Author();
    author.setName( null );
    author.setBirthdate( new Date() );

    thrown.expect( IllegalArgumentException.class );
    thrown.expectMessage( "authorDaoImpl.save.error: " );
    thrown.expectMessage(
        "not-null property references a null or transient value" );
    authorDao.save( author );

  }// End of method

  @Test
  public void entityIsNull() throws Exception {

    thrown.expect( IllegalArgumentException.class );
    thrown.expectMessage( "authorDaoImpl.save.error: " );
    thrown.expectMessage( "attempt to create create event with null entity" );
    authorDao.save( null );

  }// End of method

}// End of class


text:
package com.kanven.schedual.transport.client.command;

import com.kanven.schedual.network.protoc.MessageTypeProto.MessageType;

public enum CommandType {

	TASK_ADD(MessageType.TASK_ADD), TASK_PAUSE(MessageType.TASK_PAUSE), TASK_RECORVE(
			MessageType.TASK_ECOVER), TASK_DELETE(MessageType.TASK_DELETE), TASK_REPORT(MessageType.TASK_REPORT);

	private CommandType(MessageType type) {
		this.type = type;
	}

	private MessageType type;

	public MessageType getType() {
		return this.type;
	}

}


text:
package imageshare.servlets;

import imageshare.model.Image;
import imageshare.oraclehandler.OracleHandler;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class displays the results of the indexed search by querying the
 * database which is including keyword and/or date search.
 */

public class SearchServlet extends HttpServlet implements SingleThreadModel {

    private static final long serialVersionUID = 1L;

    private static final String SEARCH_JSP = "/webapp/jsp/search.jsp";

	String user = "";
	private OracleHandler database;
	private String keywords;
	private String fromDate;
	private String toDate;
	private String fromdatesql;
	private String todatesql;
	private List<Image> results = new ArrayList<Image>();
	private String sortby;
	private String thumbs;

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

		response.setContentType("text/html;charset=UTF-8");
		user = (String) request.getSession(true).getAttribute("user");
		/* if no user logged in, redirect to login page */
		if (user == null) {
			response.sendRedirect("index");
			return;
		};

		thumbs = "";
		request.getSession(true).setAttribute("galHTML", thumbs);
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(SEARCH_JSP);
		requestDispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] keywordsList;

		user = (String) request.getSession(true).getAttribute("user");
		/* if no user logged in, redirect to login page */
		if (user == null) {
			response.sendRedirect("index");
			return;
		};

		String orderStr = "";
		thumbs = "";
		database = OracleHandler.getInstance();

		keywords = request.getParameter("query");
		fromDate = request.getParameter("fromdate");
		toDate = request.getParameter("todate");
		sortby = request.getParameter("sortby");

		/*
		 * Changing format from yyyy-MM-dd to dd-MMM-yy for sql
		 */
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yy");

		try {
			Date date = sdf.parse(fromDate);
			Date date1 = sdf.parse(toDate);
			fromdatesql = sdf1.format(date);
			todatesql = sdf1.format(date1);
		}
		catch (Exception e) {
			e.getMessage();
		}

		/*
		 * Get how query will be sorted
		 */
		String order = null;
		// time descending
		if (sortby.equals("1"))
		{
			orderStr = "Most Recent Time First";
			order = "order by timing DESC";
		}
		// time ascending
		else if (sortby.equals("2")) {
			orderStr = "Most Recent Time Last";
			order = "order by timing";
		}
		// rank
		else {
			orderStr = "Rank";
			order = "order by score DESC";
		}

		/*
		 * The user has to input from and to dates otherwise
		 * only keyword search to get resultset of query
		 */
		if (!(keywords.equals(""))) {
			keywordsList = keywords.split("\\s+");
			if((fromDate.equals("")) || (toDate.equals(""))) {
				try {
					results = database.getImagesByKeywords(user, keywordsList, order);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				thumbs = thumbs + "
Your results for: " + keywords + "" +
						" ordered by " + orderStr + "
";
				writeThumbnails(request, response);
			}
			else {
				try {
					results = database.getImagesByDateAndKeywords(user, fromdatesql,
							todatesql, keywordsList, order);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				thumbs = thumbs + "
Your results for " + keywords + "" +
						" between " +
						fromDate + " and " + toDate + "" +
						" ordered by  " + orderStr + "
";
				writeThumbnails(request, response);
			}
		}
		else if (!((fromDate.equals("")) || (toDate.equals("")))) {

			if (!(order.equals("order by 1 DESC"))) {

				try {
					results = database.getImagesByDate(user, fromdatesql, todatesql, order);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				thumbs = thumbs + "
Your results for images between " + fromDate
						+ " and " + toDate + "" +
						" ordered by " + orderStr + "
";
				writeThumbnails(request, response);
			}
			else {
				thumbs = thumbs + "

Cannot sort by rank with just time, please" +
						" sort differently or add keywords

";
			}
		}
		else {
			thumbs = thumbs + "

Please enter a valid search query

";
		}

		request.getSession(true).setAttribute("galHTML", thumbs);
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(SEARCH_JSP);
		requestDispatcher.forward(request, response);
	}

	private void writeThumbnails(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Generate and append all user visible thumbnails to the page.
		thumbs = thumbs + "<hgroup class='mb20'>
" +
				"" +
				Integer.toString(results.size()) +
				" images were found:
</hgroup>
";

		for (int i = 0; i < results.size(); ++i) {
			String getURL = "thumbnail?" + results.get(i).getPhotoId();
			String editURL = "updateimage?" + results.get(i).getPhotoId();
			String displayURL = "display?" + results.get(i).getPhotoId();

			thumbs = thumbs + "
"+
					""+
					Integer.toString(i+1) + "
";

			//display ranking is that is the option
			if(!sortby.equals("1") && !sortby.equals("2"))
			{
				thumbs = thumbs + ""+"Ranking: "  + Integer.toString(results.get(i).getScore()) +  "
";
			}

			thumbs = thumbs + ""+"Date Created: " + results.get(i).getDate().toString() +  "
";
			if (results.get(i).getOwnerName().equals(user)) {
				thumbs = thumbs + "Edit";
			}

			thumbs = thumbs + "

";

		}
	}
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />

<link rel="shortcut icon" type="image/x-icon" href="../../favicon.ico" />
<title>Android Interface Definition Language (AIDL) | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../assets/css/default.css" rel="stylesheet" type="text/css">

          	Quicknav
			      Quicknav

                  Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../')"
onkeyup="return search_changed(event, false, '../../')" />
      </form>

        close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Publishing

Promoting

App Quality

Spotlight

Open Distribution

Results

Loading...

Training

API Guides

Reference

Tools

Google Services

to top

        App Components

            App Fundamentals

            Activities

              Fragments

              Loaders

              Tasks and Back Stack

            Services

              Bound Services

              AIDL

            Content Providers

              Content Provider Basics

              Creating a Content Provider

              Calendar Provider

              Contacts Provider

              Storage Access Framework

          Intents and Intent Filters

          Processes and Threads

          Permissions

            App Widgets

              App Widget Host

          Android Manifest

<action>

<activity>

<activity-alias>

<application>

<category>

<compatible-screens>

<data>

<grant-uri-permission>

<instrumentation>

<intent-filter>

<manifest>

<meta-data>

<path-permission>

<permission>

<permission-group>

<permission-tree>

<provider>

<receiver>

<service>

<supports-gl-texture>

<supports-screens>

<uses-configuration>

<uses-feature>

<uses-library>

<uses-permission>

<uses-sdk>

        User Interface

          Overview

            Layouts

              Linear Layout

              Relative Layout

              List View

              Grid View

            Input Controls

              Buttons

              Text Fields

              Checkboxes

              Radio Buttons

              Toggle Buttons

              Spinners

              Pickers

          Input Events

          Menus

           Action Bar

            Settings

           Dialogs

          Notifications

          Toasts

            Search

Creating a Search Interface

Adding Recent Query Suggestions

Adding Custom Suggestions

Searchable Configuration

          Drag and Drop

            Accessibility

              Making Applications Accessible

              Accessibility Developer Checklist

              Building Accessibility Services

          Styles and Themes

          Custom Components

           App Resources

            Overview

            Providing Resources

            Accessing Resources

              Handling Runtime Changes

            Localization

              Resource Types

Animation

Color State List

Drawable

Layout

Menu

String

Style

More Types

          Animation and Graphics

            Overview

            Property Animation

            View Animation

            Drawable Animation

            Canvas and Drawables

            OpenGL ES

            Hardware Acceleration

              Computation

                    RenderScript

                    Advanced RenderScript

                    Runtime API Reference

            Media and Camera

                  Media Playback

                   Supported Media Formats

                  Audio Capture

                  JetPlayer

                  Camera

              Location and Sensors

               Location and Maps

               Location Strategies

              Sensors Overview

              Motion Sensors

              Position Sensors

              Environment Sensors

               Connectivity

          Bluetooth

Bluetooth Low Energy

          NFC

NFC Basics

Advanced NFC

Host-based Card Emulation

            Wi-Fi P2P

            USB

Accessory

Host

            SIP

            Text and Input

              Copy and Paste

              Creating an IME

              Spelling Checker

          Data Storage

            Storage Options

            Data Backup

            App Install Location

               Administration

                Device Policies

    Web Apps

            Overview

            Targeting Screens from Web Apps

            Building Web Apps in WebView

            Migrating to WebView in Android 4.4

            Debugging Web Apps

            Best Practices for Web Apps

      Best Practices
      Bewährte Verfahren
      Prácticas recomendadas
      Meilleures pratiques
      Best practice
      ベスト プラクティス
      最佳实践
      最佳實務

            Compatibility

          Supporting Multiple Screens

            Distributing to Specific Screens

            Screen Compatibility Mode

            Supporting Tablets and Handsets

Android Interface Definition Language (AIDL)

In this document

Defining an AIDL Interface

Create the .aidl file

Implement the interface

Expose the interface to clients

Passing Objects over IPC

Calling an IPC Method

See also

Bound Services

AIDL (Android Interface Definition Language) is similar to other IDLs you might have
worked with. It allows you to define the programming interface that both
the client and service agree upon in order to communicate with each other using
interprocess communication (IPC). On Android, one process cannot normally access the
memory of another process. So to talk, they need to decompose their objects into primitives that the
operating system can understand, and marshall the objects across that boundary for you. The code to
do that marshalling is tedious to write, so Android handles it for you with AIDL.

Note: Using AIDL is necessary only if you allow clients from
different applications to access your service for IPC and want to handle multithreading in your
service. If you do not need to perform concurrent IPC across
different applications, you should create your interface by implementing a
Binder or, if you want to perform IPC, but do not need to handle multithreading,
implement your interface using a Messenger.
Regardless, be sure that you understand Bound Services before
implementing an AIDL.

Before you begin designing your AIDL interface, be aware that calls to an AIDL interface are
direct function calls.  You should not make assumptions about the thread in which the call
occurs.  What happens is different depending on whether the call is from a thread in the
local process or a remote process. Specifically:

Calls made from the local process are executed in the same thread that is making the call. If
this is your main UI thread, that thread continues to execute in the AIDL interface.  If it is
another thread, that is the one that executes your code in the service.  Thus, if only local
threads are accessing the service, you can completely control which threads are executing in it (but
if that is the case, then you shouldn't be using AIDL at all, but should instead create the
interface by implementing a
Binder).

Calls from a remote process are dispatched from a thread pool the platform maintains inside of
your own process.  You must be prepared for incoming calls from unknown threads, with multiple calls
happening at the same time.  In other words, an implementation of an AIDL interface must be
completely thread-safe.

The oneway keyword modifies the behavior of remote calls.  When used, a remote call does
not block; it simply sends the transaction data and immediately returns.
The implementation of the interface eventually receives this as a regular call from the Binder thread pool as a normal remote call. If oneway is used with a local call,
there is no impact and the call is still synchronous.

Defining an AIDL Interface

You must define your AIDL interface in an .aidl file using the Java
programming language syntax, then save it in the source code (in the src/ directory) of both
the application hosting the service and any other application that binds to the service.

When you build each application that contains the .aidl file, the Android SDK tools
generate an IBinder interface based on the .aidl file and save it in
the project's gen/ directory. The service must implement the IBinder
interface as appropriate. The client applications can then bind to the service and call methods from
the IBinder to perform IPC.

To create a bounded service using AIDL, follow these steps:

Create the .aidl file

This file defines the programming interface with method signatures.

Implement the interface

The Android SDK tools generate an interface in the Java programming language, based on your
.aidl file. This interface has an inner abstract class named Stub that extends
Binder and implements methods from your AIDL interface. You must extend the
Stub class and implement the methods.

Expose the interface to clients

Implement a Service and override onBind() to return your implementation of the Stub
class.

Caution: Any changes that you make to your AIDL interface after
your first release must remain backward compatible in order to avoid breaking other applications
that use your service. That is, because your .aidl file must be copied to other applications
in order for them to access your service's interface, you must maintain support for the original
interface.

1. Create the .aidl file

AIDL uses a simple syntax that lets you declare an interface with one or more methods that can
take parameters and return values. The parameters and return values can be of any type, even other
AIDL-generated interfaces.

You must construct the .aidl file using the Java programming language. Each .aidl
file must define a single interface and requires only the interface declaration and method
signatures.

By default, AIDL supports the following data types:

All primitive types in the Java programming language (such as int, long,
char, boolean, and so on)

String

CharSequence

List

All elements in the List must be one of the supported data types in this
list or one of the other AIDL-generated interfaces or parcelables you've declared. A List may optionally be used as a "generic" class (for example,
List<String>).
The actual concrete class that the other side receives is always an ArrayList, although the method is generated to use the List interface.

Map

All elements in the Map must be one of the supported data types in this
list or one of the other AIDL-generated interfaces or parcelables you've declared.  Generic maps,
(such as those of the form
Map<String,Integer> are not supported. The actual concrete class that the other side
receives is always a HashMap, although the method is generated to
use the Map interface.

You must include an import statement for each additional type not listed above, even if
they are defined in the same package as your interface.

When defining your service interface, be aware that:

Methods can take zero or more parameters, and return a value or void.

All non-primitive parameters require a directional tag indicating which way the data goes.
Either in, out, or inout (see the example below).

Primitives are in by default, and cannot be otherwise.

Caution: You should limit the direction to what is truly
needed, because marshalling parameters is expensive.

All code comments included in the .aidl file are included in the generated IBinder interface (except for comments before the import and package
statements).

Only methods are supported; you cannot expose static fields in AIDL.

Here is an example .aidl file:

// IRemoteService.aidl
package com.example.android;

// Declare any non-default types here with import statements

/** Example service interface */
interface IRemoteService {
    /** Request the process ID of this service, to do evil things with it. */
    int getPid();

    /** Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
}

Simply save your .aidl file in your project's src/ directory and when you
build your application, the SDK tools generate the IBinder interface file in your
project's gen/ directory. The generated file name matches the .aidl file name, but
with a .java extension (for example, IRemoteService.aidl results in IRemoteService.java).

If you use Eclipse, the incremental build generates the binder class almost immediately. If you
do not use Eclipse, then the Ant tool generates the binder class next time you build your
application—you should build your project with ant debug (or ant
release) as soon as you're finished writing the .aidl file, so that your code can
link against the generated class.

2. Implement the interface

When you build your application, the Android SDK tools generate a .java interface file
named after your .aidl file. The generated interface includes a subclass named Stub
that is an abstract implementation of its parent interface (for example, YourInterface.Stub) and declares all the methods from the .aidl file.

Note: Stub also
defines a few helper methods, most notably asInterface(), which takes an IBinder (usually the one passed to a client's onServiceConnected() callback method) and
returns an instance of the stub interface. See the section Calling an IPC
Method for more details on how to make this cast.

To implement the interface generated from the .aidl, extend the generated Binder interface (for example, YourInterface.Stub) and implement the methods
inherited from the .aidl file.

Here is an example implementation of an interface called IRemoteService (defined by the
IRemoteService.aidl example, above) using an anonymous instance:

private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    public int getPid(){
        return Process.myPid();
    }
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
        float aFloat, double aDouble, String aString) {
        // Does nothing
    }
};

Now the mBinder is an instance of the Stub class (a Binder),
which defines the RPC interface for the service. In the next step, this instance is exposed to
clients so they can interact with the service.

There are a few rules you should be aware of when implementing your AIDL interface:

Incoming calls are not guaranteed to be executed on the main thread, so you need to think
about multithreading from the start and properly build your service to be thread-safe.

By default, RPC calls are synchronous. If you know that the service takes more than a few
milliseconds to complete a request, you should not call it from the activity's main thread, because
it might hang the application (Android might display an "Application is Not Responding"
dialog)—you should usually call them from a separate thread in the client.

No exceptions that you throw are sent back to the caller.

3. Expose the interface to clients

Once you've implemented the interface for your service, you need to expose it to
clients so they can bind to it. To expose the interface
for your service, extend Service and implement onBind() to return an instance of your class that implements
the generated Stub (as discussed in the previous section). Here's an example
service that exposes the IRemoteService example interface to clients.

public class RemoteService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the interface
        return mBinder;
    }

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public int getPid(){
            return Process.myPid();
        }
        public void basicTypes(int anInt, long aLong, boolean aBoolean,
            float aFloat, double aDouble, String aString) {
            // Does nothing
        }
    };
}

Now, when a client (such as an activity) calls bindService() to connect to this service, the client's onServiceConnected() callback receives the
mBinder instance returned by the service's onBind()
method.

The client must also have access to the interface class, so if the client and service are in
separate applications, then the client's application must have a copy of the .aidl file
in its src/ directory (which generates the android.os.Binder
interface—providing the client access to the AIDL methods).

When the client receives the IBinder in the onServiceConnected() callback, it must call
YourServiceInterface.Stub.asInterface(service) to cast the returned
parameter to YourServiceInterface type. For example:

IRemoteService mIRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Following the example above for an AIDL interface,
        // this gets an instance of the IRemoteInterface, which we can use to call on the service
        mIRemoteService = IRemoteService.Stub.asInterface(service);
    }

    // Called when the connection with the service disconnects unexpectedly
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "Service has unexpectedly disconnected");
        mIRemoteService = null;
    }
};

For more sample code, see the RemoteService.java class in ApiDemos.

Passing Objects over IPC

If you have a class that you would like to send from one process to another through
an IPC interface, you can do that. However, you must ensure that the code for your class is
available to the other side of the IPC channel and your class must support the Parcelable interface. Supporting the Parcelable interface is
important because it allows the Android system to decompose objects into primitives that can be
marshalled across processes.

To create a class that supports the Parcelable protocol, you must do the
following:

Make your class implement the Parcelable interface.

Implement writeToParcel, which takes the
current state of the object and writes it to a Parcel.

Add a static field called CREATOR to your class which is an object implementing
the Parcelable.Creator interface.

Finally, create an .aidl file that declares your parcelable class (as shown for the
Rect.aidl file, below).

If you are using a custom build process, do not add the .aidl file to your
build. Similar to a header file in the C language, this .aidl file isn't compiled.

AIDL uses these methods and fields in the code it generates to marshall and unmarshall
your objects.

For example, here is a Rect.aidl file to create a Rect class that's
parcelable:

package android.graphics;

// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;

And here is an example of how the Rect class implements the
Parcelable protocol.

import android.os.Parcel;
import android.os.Parcelable;

public final class Rect implements Parcelable {
    public int left;
    public int top;
    public int right;
    public int bottom;

    public static final Parcelable.Creator<Rect> CREATOR = new
Parcelable.Creator<Rect>() {
        public Rect createFromParcel(Parcel in) {
            return new Rect(in);
        }

        public Rect[] newArray(int size) {
            return new Rect[size];
        }
    };

    public Rect() {
    }

    private Rect(Parcel in) {
        readFromParcel(in);
    }

    public void writeToParcel(Parcel out) {
        out.writeInt(left);
        out.writeInt(top);
        out.writeInt(right);
        out.writeInt(bottom);
    }

    public void readFromParcel(Parcel in) {
        left = in.readInt();
        top = in.readInt();
        right = in.readInt();
        bottom = in.readInt();
    }
}

The marshalling in the Rect class is pretty simple.  Take a look at the other
methods on Parcel to see the other kinds of values you can write
to a Parcel.

Warning: Don't forget the security implications of receiving
data from other processes.  In this case, the Rect reads four numbers from the Parcel, but it is up to you to ensure that these are within the acceptable range of
values for whatever the caller is trying to do.  See Security and Permissions for more
information about how to keep your application secure from malware.

Calling an IPC Method

Here are the steps a calling class must take to call a remote interface defined with AIDL:

Include the .aidl file in the project src/ directory.

Declare an instance of the IBinder interface (generated based on the
AIDL).

Implement ServiceConnection.

Call Context.bindService(), passing in your ServiceConnection implementation.

In your implementation of onServiceConnected(),
you will receive an IBinder instance (called service). Call
YourInterfaceName.Stub.asInterface((IBinder)service) to
        cast the returned parameter to YourInterface type.

Call the methods that you defined on your interface. You should always trap
        DeadObjectException exceptions, which are thrown when
        the connection has broken; this will be the only exception thrown by remote
        methods.

To disconnect, call Context.unbindService() with the instance of your interface.

A few comments on calling an IPC service:

Objects are reference counted across processes.

You can send anonymous objects
        as method arguments.

For more information about binding to a service, read the Bound Services
document.

Here is some sample code demonstrating calling an AIDL-created service, taken
    from the Remote Service sample in the ApiDemos project.

public static class Binding extends Activity {
    /** The primary interface we will be calling on the service. */
    IRemoteService mService = null;
    /** Another interface we use on the service. */
    ISecondary mSecondaryService = null;

    Button mKillButton;
    TextView mCallbackText;

    private boolean mIsBound;

    /**
     * Standard initialization of this activity.  Set up the UI, then wait
     * for the user to poke it before doing anything.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.remote_service_binding);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.bind);
        button.setOnClickListener(mBindListener);
        button = (Button)findViewById(R.id.unbind);
        button.setOnClickListener(mUnbindListener);
        mKillButton = (Button)findViewById(R.id.kill);
        mKillButton.setOnClickListener(mKillListener);
        mKillButton.setEnabled(false);

        mCallbackText = (TextView)findViewById(R.id.callback);
        mCallbackText.setText("Not attached.");
    }

    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            mService = IRemoteService.Stub.asInterface(service);
            mKillButton.setEnabled(true);
            mCallbackText.setText("Attached.");

            // We want to monitor the service for as long as we are
            // connected to it.
            try {
                mService.registerCallback(mCallback);
            } catch (RemoteException e) {
                // In this case the service has crashed before we could even
                // do anything with it; we can count on soon being
                // disconnected (and then reconnected if it can be restarted)
                // so there is no need to do anything here.
            }

            // As part of the sample, tell the user what happened.
            Toast.makeText(Binding.this, R.string.remote_service_connected,
                    Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
            mKillButton.setEnabled(false);
            mCallbackText.setText("Disconnected.");

            // As part of the sample, tell the user what happened.
            Toast.makeText(Binding.this, R.string.remote_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * Class for interacting with the secondary interface of the service.
     */
    private ServiceConnection mSecondaryConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // Connecting to a secondary interface is the same as any
            // other interface.
            mSecondaryService = ISecondary.Stub.asInterface(service);
            mKillButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            mSecondaryService = null;
            mKillButton.setEnabled(false);
        }
    };

    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {
            // Establish a couple connections with the service, binding
            // by interface names.  This allows other applications to be
            // installed that replace the remote service by implementing
            // the same interface.
            bindService(new Intent(IRemoteService.class.getName()),
                    mConnection, Context.BIND_AUTO_CREATE);
            bindService(new Intent(ISecondary.class.getName()),
                    mSecondaryConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
            mCallbackText.setText("Binding.");
        }
    };

    private OnClickListener mUnbindListener = new OnClickListener() {
        public void onClick(View v) {
            if (mIsBound) {
                // If we have received the service, and hence registered with
                // it, then now is the time to unregister.
                if (mService != null) {
                    try {
                        mService.unregisterCallback(mCallback);
                    } catch (RemoteException e) {
                        // There is nothing special we need to do if the service
                        // has crashed.
                    }
                }

                // Detach our existing connection.
                unbindService(mConnection);
                unbindService(mSecondaryConnection);
                mKillButton.setEnabled(false);
                mIsBound = false;
                mCallbackText.setText("Unbinding.");
            }
        }
    };

    private OnClickListener mKillListener = new OnClickListener() {
        public void onClick(View v) {
            // To kill the process hosting our service, we need to know its
            // PID.  Conveniently our service has a call that will return
            // to us that information.
            if (mSecondaryService != null) {
                try {
                    int pid = mSecondaryService.getPid();
                    // Note that, though this API allows us to request to
                    // kill any process based on its PID, the kernel will
                    // still impose standard restrictions on which PIDs you
                    // are actually able to kill.  Typically this means only
                    // the process running your application and any additional
                    // processes created by that app as shown here; packages
                    // sharing a common UID will also be able to kill each
                    // other's processes.
                    Process.killProcess(pid);
                    mCallbackText.setText("Killed service process.");
                } catch (RemoteException ex) {
                    // Recover gracefully from the process hosting the
                    // server dying.
                    // Just for purposes of the sample, put up a notification.
                    Toast.makeText(Binding.this,
                            R.string.remote_call_failed,
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    // ----------------------------------------------------------------------
    // Code showing how to deal with callbacks.
    // ----------------------------------------------------------------------

    /**
     * This implementation is used to receive callbacks from the remote
     * service.
     */
    private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
        /**
         * This is called by the remote service regularly to tell us about
         * new values.  Note that IPC calls are dispatched through a thread
         * pool running in each process, so the code executing here will
         * NOT be running in our main thread like most other things -- so,
         * to update the UI, we need to use a Handler to hop over there.
         */
        public void valueChanged(int value) {
            mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
        }
    };

    private static final int BUMP_MSG = 1;

    private Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
                case BUMP_MSG:
                    mCallbackText.setText("Received from service: " + msg.arg1);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }

    };
}

  Except as noted, this content is
  licensed under
  Creative Commons Attribution 2.5. For details and
  restrictions, see the Content
  License.

    About Android  |
    Legal  |
    Support


text:
package com.google.code.play;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;

import org.codehaus.plexus.util.FileUtils;

import org.sonatype.plexus.build.incremental.BuildContext;

/**
 * Initialize Play! Maven project.
 *
 * - Checks Play! home directory and creates temporary Play! home in "target" directory
 * if no Play! home directory defined and there is Play! framework zip dependency
 * in the project.
 * - Adds application and dependent modules sources to Maven project as compile source roots.
 * - Adds application resources to Maven project as resources.
 * - Adds application test sources to Maven project as test compile source roots.
 *
 * @author Grzegorz Slowikowski
 * @since 1.0.0
 */
@Mojo( name = "initialize", defaultPhase = LifecyclePhase.INITIALIZE, requiresDependencyResolution = ResolutionScope.COMPILE )
public class PlayInitializeMojo
    extends AbstractPlayMojo
{

    public static final String playFrameworkVersionFilePath = "framework/src/play/version";

    /**
     * Default Play! id (profile).
     *
     * @since 1.0.0
     */
    @Parameter( property = "play.id", defaultValue = "" )
    private String playId;

    /**
     * Should temporary Play! home directory be cleaned before it's reinitializing.
     * If true, homeOverwrite is meaningless.
     *
     * @since 1.0.0
     */
    @Parameter( property = "play.homeClean", defaultValue = "false" )
    private boolean homeClean;

    /**
     * Should existing temporary Play! home content be overwritten.
     *
     * @since 1.0.0
     */
    @Parameter( property = "play.homeOverwrite", defaultValue = "false" )
    private boolean homeOverwrite;

    /**
     * To look up Archiver/UnArchiver implementations.
     *
     */
    @Component
    private ArchiverManager archiverManager;

    /**
     * For M2E integration.
     */
    @Component
    private BuildContext buildContext;

    protected void internalExecute()
        throws MojoExecutionException, MojoFailureException, IOException
    {
        String playVersion = null;
        Set<?> artifacts = project.getArtifacts();
        for ( Iterator<?> iter = artifacts.iterator(); iter.hasNext(); )
        {
            Artifact artifact = (Artifact) iter.next();
            // System.out.println("artifact: " + artifact.getGroupId() + ":" + artifact.getArtifactId());
            if ( "play".equals( artifact.getArtifactId() ) )
            {
                // temporary solution, maybe use zip to unzip resource from a jar file
                playVersion = artifact.getBaseVersion();
                // System.out.println("Play version: " + playVersion);
                // java.net.URL artifactUrl = artifact.getFile().toURI().toURL();
                break;
            }
        }

        getLog().debug( "Play! version: " + playVersion );
        File playHome = prepareAndGetPlayHome( playVersion );

        File baseDir = project.getBasedir();

        ConfigurationParser configParser = getConfiguration( playId );
        // Get modules
        Map<String, File> modules = new HashMap<String, File>();

        // Play 1.1.x
        Map<String, String> modulePaths = configParser.getModules();
        for ( Map.Entry<String, String> modulePathEntry : modulePaths.entrySet() )
        {
            String moduleName = modulePathEntry.getKey();
            String modulePath = modulePathEntry.getValue();
            modulePath = modulePath.replace( "${play.path}", playHome.getPath() );
            modules.put( moduleName, new File( modulePath ) );
        }
        // Play 1.2.x
        if ( ( playVersion != null/* I don't like it */ ) && "1.2".compareTo( /* Play.version */playVersion ) <= 0 )
        {
            File modulesDir = new File( baseDir, "modules" );
            if ( modulesDir.isDirectory() )
            {
                File[] files = modulesDir.listFiles();
                if ( files != null )
                {
                    for ( File file : files )
                    {
                        String moduleName = file.getName();
                        if ( file.isDirectory() )
                        {
                            // module itself
                            getLog().debug( "Added module '" + moduleName + "': " + file.getAbsolutePath() );
                            modules.put( moduleName, file );
                        }
                        else if ( file.isFile() )
                        {
                            // shortcut to module located in "modules" subdirectory of Play! framework location
                            String realModulePath = readFileFirstLine( file );
                            // String realModulePath = play.libs.IO.readContentAsString( file );
                            file = new File( realModulePath );
                            if ( !file.isAbsolute() )
                            {
                                file = new File( baseDir, realModulePath );
                            }
                            getLog().debug( "Added module '" + moduleName + "': " + file.getAbsolutePath() );
                            modules.put( moduleName, file );
                        }
                    }
                }
            }
        }

        File appPath = new File( baseDir, "app" );
        if ( !project.getCompileSourceRoots().contains( appPath.getAbsolutePath() ) )
        {
            project.addCompileSourceRoot( appPath.getAbsolutePath() );
            getLog().debug( "Added source directory: " + appPath.getAbsolutePath() );
        }

        File confPath = new File( baseDir, "conf" );
        boolean confResourceAlreadyAdded = false;
        @SuppressWarnings( "unchecked" )
        List<Resource> projectResources = project.getResources();
        for ( Resource resource: projectResources )
        {
            if ( resource.getDirectory().equals( confPath.getAbsolutePath() ) )
            {
                confResourceAlreadyAdded = true;
                break;
            }
        }
        if ( !confResourceAlreadyAdded )
        {
            Resource resource = new Resource();
            resource.setDirectory( confPath.getAbsolutePath() );
            project.addResource( resource );
            getLog().debug( "Added resource: " + resource.getDirectory() );
        }

        for ( File modulePath : modules.values() )
        {
            File moduleAppPath = new File( modulePath, "app" );
            if ( moduleAppPath.isDirectory() )
            {
                if ( !project.getCompileSourceRoots().contains( moduleAppPath.getAbsolutePath() ) )
                {
                    project.addCompileSourceRoot( moduleAppPath.getAbsolutePath() );
                    getLog().debug( "Added source directory: " + moduleAppPath.getAbsolutePath() );
                }
            }
        }

        File testPath = new File( baseDir, "test" );
        if ( !project.getTestCompileSourceRoots().contains( testPath.getAbsolutePath() ) )
        {
            project.addTestCompileSourceRoot( testPath.getAbsolutePath() );
            getLog().debug( "Added test source directory: " + testPath.getAbsolutePath() );
        }
    }

    protected File prepareAndGetPlayHome( String playDependencyVersion )
        throws MojoExecutionException, IOException
    {
        File targetDir = new File( project.getBuild().getDirectory() );
        File playTmpDir = new File( targetDir, "play" );
        File playTmpHomeDir = new File( playTmpDir, "home" );
        Artifact frameworkArtifact = findFrameworkArtifact( true );
        Map<String, Artifact> moduleArtifacts = findAllModuleArtifacts( true );

        if ( frameworkArtifact != null )
        {
            try
            {
                decompressFrameworkAndSetPlayHome( frameworkArtifact, moduleArtifacts, playDependencyVersion,
                                                   playTmpHomeDir );
            }
            catch ( ArchiverException e )
            {
                throw new MojoExecutionException( "Failed to initialize Play! framework home directory: " + e.getMessage(), e );
            }
            catch ( NoSuchArchiverException e )
            {
                throw new MojoExecutionException( "Failed to initialize Play! framework home directory: " + e.getMessage(), e );
            }
        }
        else
        {
            throw new MojoExecutionException( "Missing Play! framework dependency" );
        }
        return playTmpHomeDir;
    }

    private void decompressFrameworkAndSetPlayHome( Artifact frameworkAtifact, Map<String, Artifact> moduleArtifacts,
                                                    String playDependencyVersion, File playTmpHomeDir )
        throws MojoExecutionException, NoSuchArchiverException, IOException
    {
        File warningFile = new File( playTmpHomeDir, "WARNING.txt" );

        if ( homeClean )
        {
            FileUtils.deleteDirectory( playTmpHomeDir );
        }

        if ( playTmpHomeDir.exists() )
        {
            if ( playTmpHomeDir.isDirectory() )
            {
                // Additional check whether the temporary Play! home directory is created by this plugin
                if ( warningFile.exists() )
                {
                    if ( !warningFile.isFile() )
                    {
                        throw new MojoExecutionException(
                                                          String.format( "Play! home directory warning file \"%s\" is not a file",
                                                                         warningFile.getCanonicalPath() ) );
                    }
                }
                else
                {
                    throw new MojoExecutionException(
                                                      String.format( "Play! home directory warning file \"%s\" does not exist",
                                                                     warningFile.getCanonicalPath() ) );
                }
            }
            else
            {
                throw new MojoExecutionException( String.format( "Play! home directory \"%s\" is not a directory",
                                                                 playTmpHomeDir.getCanonicalPath() ) );
            }
        }

        // decompress framework
        createDir( playTmpHomeDir );
        if ( !warningFile.exists() )
        {
            writeToFile( warningFile, "This directory is generated automatically. Don't change its content." );
        }
        File frameworkDir = new File( playTmpHomeDir, "framework" );
        if ( !frameworkDir.exists() || frameworkDir.lastModified() < frameworkAtifact.getFile().lastModified() )
        {
            UnArchiver zipUnArchiver = archiverManager.getUnArchiver( "zip" );
            zipUnArchiver.setSourceFile( frameworkAtifact.getFile() );
            zipUnArchiver.setDestDirectory( playTmpHomeDir );
            zipUnArchiver.setOverwrite( false/* ??true */ );
            zipUnArchiver.extract();

            File playFrameworkVersionFile = new File( playTmpHomeDir, playFrameworkVersionFilePath );
            createDir( playFrameworkVersionFile.getParentFile() );
            writeToFile( playFrameworkVersionFile, playDependencyVersion );
            frameworkDir.setLastModified( System.currentTimeMillis() );
            buildContext.refresh( frameworkDir );
        }

        // decompress provided-scoped modules
        File modulesDirectory = new File( playTmpHomeDir, "modules" );
        for ( Map.Entry<String, Artifact> moduleArtifactEntry : moduleArtifacts.entrySet() )
        {
            String moduleName = moduleArtifactEntry.getKey();
            Artifact moduleArtifact = moduleArtifactEntry.getValue();

            if ( Artifact.SCOPE_PROVIDED.equals( moduleArtifact.getScope() ) )
            {
                File zipFile = moduleArtifact.getFile();
                String moduleSubDir =
                                String.format( "%s-%s", moduleName, moduleArtifact.getBaseVersion() );
                if ( isFrameworkEmbeddedModule( moduleName ) )
                {
                    moduleSubDir = moduleName;
                }
                File moduleDirectory = new File( modulesDirectory, moduleSubDir );
                createModuleDirectory( moduleDirectory,
                                       homeOverwrite || moduleDirectory.lastModified() < zipFile.lastModified() );
                if ( moduleDirectory.list().length == 0 )
                {
                    UnArchiver zipUnArchiver = archiverManager.getUnArchiver( "zip" );
                    zipUnArchiver.setSourceFile( zipFile );
                    zipUnArchiver.setDestDirectory( moduleDirectory );
                    zipUnArchiver.setOverwrite( false/* ??true */ );
                    zipUnArchiver.extract();
                    moduleDirectory.setLastModified( System.currentTimeMillis() );
                    buildContext.refresh( moduleDirectory );
                    // Scala module hack
                    if ( "scala".equals( moduleName ) )
                    {
                        scalaHack( moduleDirectory );
                    }
                }
            }
        }
    }

    private void createDir( File directory )
        throws IOException
    {
        if ( directory.exists() )
        {
            if ( directory.isDirectory() )
            {
                if ( homeOverwrite )
                {
                    FileUtils.cleanDirectory( directory );
                }
            }
            else
            {
                throw new IOException( String.format( "\"%s\" is not a directory", directory.getCanonicalPath() ) );
            }
        }
        else
        {
            if ( !directory.mkdirs() )
            {
                throw new IOException( String.format( "Cannot create \"%s\" directory", directory.getCanonicalPath() ) );
            }
        }

        if ( !directory.exists() )
        {
            if ( !directory.mkdirs() )
            {
                throw new IOException( String.format( "Cannot create \"%s\" directory", directory.getCanonicalPath() ) );
            }
        }
    }

    private void scalaHack( File scalaModuleDirectory ) throws IOException
    {
        Set<?> projectArtifacts = project.getArtifacts();
        for ( Iterator<?> iter = projectArtifacts.iterator(); iter.hasNext(); )
        {
            Artifact artifact = (Artifact) iter.next();
            if ( "org.scala-lang".equals( artifact.getGroupId() )
                && ( "scala-compiler".equals( artifact.getArtifactId() ) || "scala-library".equals( artifact.getArtifactId() ) )
                && "jar".equals( artifact.getType() ) )
            {
                File jarFile = artifact.getFile();
                //FileUtils.copyFileToDirectoryIfModified( jarFile, new File(scalaModuleDirectory, "lib" ) );
                FileUtils.copyFileIfModified( jarFile,
                                              new File( scalaModuleDirectory, "lib/" + artifact.getArtifactId()
                                                  + ".jar" ) );
            }
        }
    }

}


text:
PgQueryProtobuf pg_query_nodes_to_protobuf(const void *obj);

char *pg_query_nodes_to_json(const void *obj);

#endif


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe DonaldPiret::MailchimpFu::MailchimpSubscriber do
  before do
    User.stub(:mailchimp_list_id).and_return('xxxxxxxx')
    UserWithMergeVars.stub(:mailchimp_list_id).and_return('xxxxxxxx')
  end

  describe :initialize do

    it "should correctly fetch the mailchimp list id" do
      User.mailchimp_list_name.should_not be_blank
      User.mailchimp_list_id.should_not be_blank
    end
  end

  describe :create do

    before(:each) do

    end

    it "should call the after_mailchimp_subscriber_create method on an object that has mailchimp_subscriber mixed in" do
      @user = User.new
      @user.should_receive(:after_mailchimp_subscriber_create)
      @user.save
    end

    it "should call MailChimp.list_subscribe with 'sample' as list name and the user's email on user creation if the user's wants email is tue" do
      @user = User.new(:email => 'test@test.com', :wants_email => true)
      Gibbon.any_instance.should_receive(:list_subscribe).with({:id=>"xxxxxxxx", :email_address=>"test@test.com", :merge_vars=>{}}).and_return(true)
      @user.save
    end

    it "should correctly set the mailchimp_vars" do
      @user = UserWithMergeVars.new(:email => 'donald@donaldpiret.com', :first_name => 'Donald', :last_name => 'Piret', :username => 'donaldpiret', :city => 'waterloo', :age => 24, :male => true)
      Gibbon.any_instance.should_receive(:list_subscribe).with({:id => 'xxxxxxxx', :email_address => 'donald@donaldpiret.com', :merge_vars => {:FIRST_NAME => 'Donald', :LAST_NAME => 'Piret', :USERNAME => 'donaldpiret', :MY_CITY => 'WATERLOO', :AGE => 24, :MALE => true, :STATIC => 'Static'}}).and_return(true)
      @user.save
    end

  end

  describe :update do
    it "should call the after_mailchimp_subscriber_update method on an object that has the mailchimp subscriber mixed in" do
      @user = User.create(:email => 'donald@donaldpiret.com', :first_name => 'donald', :wants_email => true)
      @user.should_receive(:around_mailchimp_subscriber_update)
      @user.update_attribute(:first_name, 'piret')
    end

    it "should call MailChimp.list_update_member with the old email address if the email address was changed" do
      @user = User.create(:email => 'donald@donaldpiret.com', :first_name => 'donald', :wants_email => true)
      Gibbon.any_instance.should_receive(:list_update_member).with({:id => 'xxxxxxxx', :email_address => 'donald@donaldpiret.com', :merge_vars => {:EMAIL => 'test@test.com'}})
      @user.update_attribute(:email, 'test@test.com')
    end

    it "should correctly set the mailchimp_vars" do
      Gibbon.any_instance.should_receive(:list_subscribe).with({:id => 'xxxxxxxx', :email_address => 'donald@donaldpiret.com', :merge_vars => {:FIRST_NAME => 'Donald', :LAST_NAME => 'Piret', :USERNAME => 'donaldpiret', :MY_CITY => 'WATERLOO', :AGE => 24, :MALE => true, :STATIC => 'Static'}}).and_return(true)
      @user = UserWithMergeVars.create(:email => 'donald@donaldpiret.com', :first_name => 'Donald', :last_name => 'Piret', :username => 'donaldpiret', :city => 'waterloo', :age => 24, :male => true)
      Gibbon.any_instance.should_receive(:list_update_member).with({:id => 'xxxxxxxx', :email_address => 'donald@donaldpiret.com', :merge_vars => {:EMAIL => 'test@test.com', :FIRST_NAME => 'Daniel', :LAST_NAME => 'Piret', :USERNAME => 'donaldpiret', :MY_CITY => 'WATERLOO', :AGE => 24, :MALE => true, :STATIC => 'Static'}})
      @user.update_attributes!({:email => 'test@test.com', :first_name => 'Daniel'})
    end

    it "should call the MailChimp.list_subscribe method if the enabled method was changed from false to true" do
      @user = User.create(:email => 'donald@donaldpiret.com', :first_name => 'donald', :wants_email => false)
      @user.wants_email.should eql(false)
      Gibbon.any_instance.should_receive(:list_subscribe).with({:id => 'xxxxxxxx', :email_address => 'donald@donaldpiret.com', :merge_vars => {}})
      @user.update_attribute(:wants_email, true)
    end

    it "should call the MailChimp.list_unsubscribe method if the enabled method was changed from true to false" do
      @user = User.create(:email => 'donald@donaldpiret.com', :first_name => 'donald', :wants_email => true)
      @user.wants_email.should eql(true)
      Gibbon.any_instance.should_receive(:list_unsubscribe).with({:id => 'xxxxxxxx', :email_address => 'donald@donaldpiret.com'})
      @user.update_attribute(:wants_email, false)
    end

  end

  describe :destroy do

    before(:each) do
      @user = User.create(:email => 'donald@donaldpiret.com', :first_name => 'donald')
    end

    it "should call the after_mailchimp_subscriber_destroy method on an object that has the mailchimp subscriber mixed in" do
      @user.should_receive(:after_mailchimp_subscriber_destroy)
      @user.destroy
    end

    it "should call MailChimp.list_unsubscribe with the user's email" do
      Gibbon.any_instance.should_receive(:list_unsubscribe).with({:id => 'xxxxxxxx', :email_address => 'donald@donaldpiret.com'})
      @user.destroy
    end

  end

end


text:
package _11Threeuple;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String[] firstLine = reader.readLine().split("\\s+");
        Threeuple<String, String, String> threeuple1 = new ThreeupleImpl<>
                (firstLine[0] + " " + firstLine[1], firstLine[2], firstLine[3]);
        String[] secLine = reader.readLine().split("\\s+");
        Threeuple<String, Integer, Boolean> threeuple2 = new ThreeupleImpl<>(secLine[0], Integer.parseInt(secLine[1]), secLine[2].equals("drunk") );
        String[] thirdLine = reader.readLine().split("\\s+");
        Threeuple<String, Double, String> threeuple3 = new ThreeupleImpl<>(thirdLine[0], Double.parseDouble(thirdLine[1]), thirdLine[2]);

        System.out.println(threeuple1);
        System.out.println(threeuple2);
        System.out.println(threeuple3);
    }
}


text:
namespace FTC_Scouting_App
{
    partial class Form4
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.compBox = new System.Windows.Forms.ComboBox();
            this.teamBox = new System.Windows.Forms.ComboBox();
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.matchBox = new System.Windows.Forms.ComboBox();
            this.SuspendLayout();
            //
            // compBox
            //
            this.compBox.FormattingEnabled = true;
            this.compBox.Location = new System.Drawing.Point(26, 16);
            this.compBox.Name = "compBox";
            this.compBox.Size = new System.Drawing.Size(186, 21);
            this.compBox.TabIndex = 0;
            this.compBox.Text = "Competition";
            this.compBox.SelectionChangeCommitted += new System.EventHandler(this.selectChange);
            //
            // teamBox
            //
            this.teamBox.FormattingEnabled = true;
            this.teamBox.Location = new System.Drawing.Point(527, 16);
            this.teamBox.Name = "teamBox";
            this.teamBox.Size = new System.Drawing.Size(223, 21);
            this.teamBox.TabIndex = 1;
            this.teamBox.Text = "Team";
            this.teamBox.SelectedValueChanged += new System.EventHandler(this.teamChange);
            //
            // listBox1
            //
            this.listBox1.DataSource = this.listBox1.CustomTabOffsets;
            this.listBox1.FormattingEnabled = true;
            this.listBox1.Location = new System.Drawing.Point(34, 100);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(177, 238);
            this.listBox1.TabIndex = 2;
            //
            // matchBox
            //
            this.matchBox.FormattingEnabled = true;
            this.matchBox.Location = new System.Drawing.Point(34, 345);
            this.matchBox.Name = "matchBox";
            this.matchBox.Size = new System.Drawing.Size(121, 21);
            this.matchBox.TabIndex = 3;
            this.matchBox.Text = "Match Number";
            //
            // Form4
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(777, 454);
            this.Controls.Add(this.matchBox);
            this.Controls.Add(this.listBox1);
            this.Controls.Add(this.teamBox);
            this.Controls.Add(this.compBox);
            this.Name = "Form4";
            this.Text = "Form4";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.ComboBox compBox;
        private System.Windows.Forms.ComboBox teamBox;
        private System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.ComboBox matchBox;
    }
}


text:
/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 2013 by Delphix. All rights reserved.
 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
 */

#ifndef	_DTRACE_H
#define	_DTRACE_H

#include <sys/dtrace.h>
#include <stdarg.h>
#include <stdio.h>
#include <gelf.h>
#include <libproc.h>
#if !defined(sun)
#include <rtld_db.h>
#endif

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * DTrace Dynamic Tracing Software: Library Interfaces
 *
 * Note: The contents of this file are private to the implementation of the
 * Solaris system and DTrace subsystem and are subject to change at any time
 * without notice.  Applications and drivers using these interfaces will fail
 * to run on future releases.  These interfaces should not be used for any
 * purpose except those expressly outlined in dtrace(7D) and libdtrace(3LIB).
 * Please refer to the "Solaris Dynamic Tracing Guide" for more information.
 */

#define	DTRACE_VERSION	3		/* library ABI interface version */

struct ps_prochandle;
typedef struct dtrace_hdl dtrace_hdl_t;
typedef struct dtrace_prog dtrace_prog_t;
typedef struct dtrace_vector dtrace_vector_t;
typedef struct dtrace_aggdata dtrace_aggdata_t;

#define	DTRACE_O_NODEV		0x01	/* do not open dtrace(7D) device */
#define	DTRACE_O_NOSYS		0x02	/* do not load /system/object modules */
#define	DTRACE_O_LP64		0x04	/* force D compiler to be LP64 */
#define	DTRACE_O_ILP32		0x08	/* force D compiler to be ILP32 */
#define	DTRACE_O_MASK		0x0f	/* mask of valid flags to dtrace_open */

extern dtrace_hdl_t *dtrace_open(int, int, int *);
extern dtrace_hdl_t *dtrace_vopen(int, int, int *,
    const dtrace_vector_t *, void *);

extern int dtrace_go(dtrace_hdl_t *);
extern int dtrace_stop(dtrace_hdl_t *);
extern void dtrace_sleep(dtrace_hdl_t *);
extern void dtrace_close(dtrace_hdl_t *);

extern int dtrace_errno(dtrace_hdl_t *);
extern const char *dtrace_errmsg(dtrace_hdl_t *, int);
extern const char *dtrace_faultstr(dtrace_hdl_t *, int);
extern const char *dtrace_subrstr(dtrace_hdl_t *, int);

extern int dtrace_setopt(dtrace_hdl_t *, const char *, const char *);
extern int dtrace_getopt(dtrace_hdl_t *, const char *, dtrace_optval_t *);

extern void dtrace_update(dtrace_hdl_t *);
extern int dtrace_ctlfd(dtrace_hdl_t *);

/*
 * DTrace Program Interface
 *
 * DTrace programs can be created by compiling ASCII text files containing
 * D programs or by compiling in-memory C strings that specify a D program.
 * Once created, callers can examine the list of program statements and
 * enable the probes and actions described by these statements.
 */

typedef struct dtrace_proginfo {
	dtrace_attribute_t dpi_descattr; /* minimum probedesc attributes */
	dtrace_attribute_t dpi_stmtattr; /* minimum statement attributes */
	uint_t dpi_aggregates;	/* number of aggregates specified in program */
	uint_t dpi_recgens;	/* number of record generating probes in prog */
	uint_t dpi_matches;	/* number of probes matched by program */
	uint_t dpi_speculations; /* number of speculations specified in prog */
} dtrace_proginfo_t;

#define	DTRACE_C_DIFV	0x0001	/* DIF verbose mode: show each compiled DIFO */
#define	DTRACE_C_EMPTY	0x0002	/* Permit compilation of empty D source files */
#define	DTRACE_C_ZDEFS	0x0004	/* Permit probe defs that match zero probes */
#define	DTRACE_C_EATTR	0x0008	/* Error if program attributes less than min */
#define	DTRACE_C_CPP	0x0010	/* Preprocess input file with cpp(1) utility */
#define	DTRACE_C_KNODEF	0x0020	/* Permit unresolved kernel symbols in DIFO */
#define	DTRACE_C_UNODEF	0x0040	/* Permit unresolved user symbols in DIFO */
#define	DTRACE_C_PSPEC	0x0080	/* Intepret ambiguous specifiers as probes */
#define	DTRACE_C_ETAGS	0x0100	/* Prefix error messages with error tags */
#define	DTRACE_C_ARGREF	0x0200	/* Do not require all macro args to be used */
#define	DTRACE_C_DEFARG	0x0800	/* Use 0/"" as value for unspecified args */
#define	DTRACE_C_NOLIBS	0x1000	/* Do not process D system libraries */
#define	DTRACE_C_CTL	0x2000	/* Only process control directives */
#define	DTRACE_C_MASK	0x3bff	/* mask of all valid flags to dtrace_*compile */

extern dtrace_prog_t *dtrace_program_strcompile(dtrace_hdl_t *,
    const char *, dtrace_probespec_t, uint_t, int, char *const []);

extern dtrace_prog_t *dtrace_program_fcompile(dtrace_hdl_t *,
    FILE *, uint_t, int, char *const []);

extern int dtrace_program_exec(dtrace_hdl_t *, dtrace_prog_t *,
    dtrace_proginfo_t *);
extern void dtrace_program_info(dtrace_hdl_t *, dtrace_prog_t *,
    dtrace_proginfo_t *);

#define	DTRACE_D_STRIP	0x01	/* strip non-loadable sections from program */
#define	DTRACE_D_PROBES	0x02	/* include provider and probe definitions */
#define	DTRACE_D_MASK	0x03	/* mask of valid flags to dtrace_dof_create */

extern int dtrace_program_link(dtrace_hdl_t *, dtrace_prog_t *,
    uint_t, const char *, int, char *const []);

extern int dtrace_program_header(dtrace_hdl_t *, FILE *, const char *);

extern void *dtrace_dof_create(dtrace_hdl_t *, dtrace_prog_t *, uint_t);
extern void dtrace_dof_destroy(dtrace_hdl_t *, void *);

extern void *dtrace_getopt_dof(dtrace_hdl_t *);
extern void *dtrace_geterr_dof(dtrace_hdl_t *);

typedef struct dtrace_stmtdesc {
	dtrace_ecbdesc_t *dtsd_ecbdesc;		/* ECB description */
	dtrace_actdesc_t *dtsd_action;		/* action list */
	dtrace_actdesc_t *dtsd_action_last;	/* last action in action list */
	void *dtsd_aggdata;			/* aggregation data */
	void *dtsd_fmtdata;			/* type-specific output data */
	void *dtsd_strdata;			/* type-specific string data */
	void (*dtsd_callback)(void);		/* callback function for EPID */
	void *dtsd_data;			/* callback data pointer */
	dtrace_attribute_t dtsd_descattr;	/* probedesc attributes */
	dtrace_attribute_t dtsd_stmtattr;	/* statement attributes */
} dtrace_stmtdesc_t;

typedef int dtrace_stmt_f(dtrace_hdl_t *, dtrace_prog_t *,
    dtrace_stmtdesc_t *, void *);

extern dtrace_stmtdesc_t *dtrace_stmt_create(dtrace_hdl_t *,
    dtrace_ecbdesc_t *);
extern dtrace_actdesc_t *dtrace_stmt_action(dtrace_hdl_t *,
    dtrace_stmtdesc_t *);
extern int dtrace_stmt_add(dtrace_hdl_t *, dtrace_prog_t *,
    dtrace_stmtdesc_t *);
extern int dtrace_stmt_iter(dtrace_hdl_t *, dtrace_prog_t *,
    dtrace_stmt_f *, void *);
extern void dtrace_stmt_destroy(dtrace_hdl_t *, dtrace_stmtdesc_t *);

/*
 * DTrace Data Consumption Interface
 */
typedef enum {
	DTRACEFLOW_ENTRY,
	DTRACEFLOW_RETURN,
	DTRACEFLOW_NONE
} dtrace_flowkind_t;

#define	DTRACE_CONSUME_ERROR		-1	/* error while processing */
#define	DTRACE_CONSUME_THIS		0	/* consume this probe/record */
#define	DTRACE_CONSUME_NEXT		1	/* advance to next probe/rec */
#define	DTRACE_CONSUME_ABORT		2	/* abort consumption */

typedef struct dtrace_probedata {
	dtrace_hdl_t *dtpda_handle;		/* handle to DTrace library */
	dtrace_eprobedesc_t *dtpda_edesc;	/* enabled probe description */
	dtrace_probedesc_t *dtpda_pdesc;	/* probe description */
	processorid_t dtpda_cpu;		/* CPU for data */
	caddr_t dtpda_data;			/* pointer to raw data */
	dtrace_flowkind_t dtpda_flow;		/* flow kind */
	const char *dtpda_prefix;		/* recommended flow prefix */
	int dtpda_indent;			/* recommended flow indent */
} dtrace_probedata_t;

typedef int dtrace_consume_probe_f(const dtrace_probedata_t *, void *);
typedef int dtrace_consume_rec_f(const dtrace_probedata_t *,
    const dtrace_recdesc_t *, void *);

extern int dtrace_consume(dtrace_hdl_t *, FILE *,
    dtrace_consume_probe_f *, dtrace_consume_rec_f *, void *);

#define	DTRACE_STATUS_NONE	0	/* no status; not yet time */
#define	DTRACE_STATUS_OKAY	1	/* status okay */
#define	DTRACE_STATUS_EXITED	2	/* exit() was called; tracing stopped */
#define	DTRACE_STATUS_FILLED	3	/* fill buffer filled; tracing stoped */
#define	DTRACE_STATUS_STOPPED	4	/* tracing already stopped */

extern int dtrace_status(dtrace_hdl_t *);

/*
 * DTrace Formatted Output Interfaces
 *
 * To format output associated with a given dtrace_stmtdesc, the caller can
 * invoke one of the following functions, passing the opaque dtsd_fmtdata and a
 * list of record descriptions.  These functions return either -1 to indicate
 * an error, or a positive integer indicating the number of records consumed.
 * For anonymous enablings, the consumer can use the dtrd_format member of
 * the record description to obtain a format description.  The dtfd_string
 * member of the format description may be passed to dtrace_print{fa}_create()
 * to create the opaque format data.
 */
extern void *dtrace_printf_create(dtrace_hdl_t *, const char *);
extern void *dtrace_printa_create(dtrace_hdl_t *, const char *);
extern size_t dtrace_printf_format(dtrace_hdl_t *, void *, char *, size_t);

extern int dtrace_fprintf(dtrace_hdl_t *, FILE *, void *,
    const dtrace_probedata_t *, const dtrace_recdesc_t *, uint_t,
    const void *, size_t);

extern int dtrace_fprinta(dtrace_hdl_t *, FILE *, void *,
    const dtrace_probedata_t *, const dtrace_recdesc_t *, uint_t,
    const void *, size_t);

extern int dtrace_system(dtrace_hdl_t *, FILE *, void *,
    const dtrace_probedata_t *, const dtrace_recdesc_t *, uint_t,
    const void *, size_t);

extern int dtrace_freopen(dtrace_hdl_t *, FILE *, void *,
    const dtrace_probedata_t *, const dtrace_recdesc_t *, uint_t,
    const void *, size_t);

/*
 * Type-specific output printing
 *
 * The print() action will associate a string data record that is actually the
 * fully-qualified type name of the data traced by the DIFEXPR action.  This is
 * stored in the same 'format' record from the kernel, but we know by virtue of
 * the fact that the action is still DIFEXPR that it is actually a reference to
 * plain string data.
 */
extern int dtrace_print(dtrace_hdl_t *, FILE *, const char *,
    caddr_t, size_t);

/*
 * DTrace Work Interface
 */
typedef enum {
	DTRACE_WORKSTATUS_ERROR = -1,
	DTRACE_WORKSTATUS_OKAY,
	DTRACE_WORKSTATUS_DONE
} dtrace_workstatus_t;

extern dtrace_workstatus_t dtrace_work(dtrace_hdl_t *, FILE *,
    dtrace_consume_probe_f *, dtrace_consume_rec_f *, void *);

/*
 * DTrace Handler Interface
 */
#define	DTRACE_HANDLE_ABORT		-1	/* abort current operation */
#define	DTRACE_HANDLE_OK		0	/* handled okay; continue */

typedef struct dtrace_errdata {
	dtrace_hdl_t *dteda_handle;		/* handle to DTrace library */
	dtrace_eprobedesc_t *dteda_edesc;	/* enabled probe inducing err */
	dtrace_probedesc_t *dteda_pdesc;	/* probe inducing error */
	processorid_t dteda_cpu;		/* CPU of error */
	int dteda_action;			/* action inducing error */
	int dteda_offset;			/* offset in DIFO of error */
	int dteda_fault;			/* specific fault */
	uint64_t dteda_addr;			/* address of fault, if any */
	const char *dteda_msg;			/* preconstructed message */
} dtrace_errdata_t;

typedef int dtrace_handle_err_f(const dtrace_errdata_t *, void *);
extern int dtrace_handle_err(dtrace_hdl_t *, dtrace_handle_err_f *, void *);

typedef enum {
	DTRACEDROP_PRINCIPAL,			/* drop to principal buffer */
	DTRACEDROP_AGGREGATION,			/* drop to aggregation buffer */
	DTRACEDROP_DYNAMIC,			/* dynamic drop */
	DTRACEDROP_DYNRINSE,			/* dyn drop due to rinsing */
	DTRACEDROP_DYNDIRTY,			/* dyn drop due to dirty */
	DTRACEDROP_SPEC,			/* speculative drop */
	DTRACEDROP_SPECBUSY,			/* spec drop due to busy */
	DTRACEDROP_SPECUNAVAIL,			/* spec drop due to unavail */
	DTRACEDROP_STKSTROVERFLOW,		/* stack string tab overflow */
	DTRACEDROP_DBLERROR			/* error in ERROR probe */
} dtrace_dropkind_t;

typedef struct dtrace_dropdata {
	dtrace_hdl_t *dtdda_handle;		/* handle to DTrace library */
	processorid_t dtdda_cpu;		/* CPU, if any */
	dtrace_dropkind_t dtdda_kind;		/* kind of drop */
	uint64_t dtdda_drops;			/* number of drops */
	uint64_t dtdda_total;			/* total drops */
	const char *dtdda_msg;			/* preconstructed message */
} dtrace_dropdata_t;

typedef int dtrace_handle_drop_f(const dtrace_dropdata_t *, void *);
extern int dtrace_handle_drop(dtrace_hdl_t *, dtrace_handle_drop_f *, void *);

typedef void dtrace_handle_proc_f(struct ps_prochandle *, const char *, void *);
extern int dtrace_handle_proc(dtrace_hdl_t *, dtrace_handle_proc_f *, void *);

#define	DTRACE_BUFDATA_AGGKEY		0x0001	/* aggregation key */
#define	DTRACE_BUFDATA_AGGVAL		0x0002	/* aggregation value */
#define	DTRACE_BUFDATA_AGGFORMAT	0x0004	/* aggregation format data */
#define	DTRACE_BUFDATA_AGGLAST		0x0008	/* last for this key/val */

typedef struct dtrace_bufdata {
	dtrace_hdl_t *dtbda_handle;		/* handle to DTrace library */
	const char *dtbda_buffered;		/* buffered output */
	dtrace_probedata_t *dtbda_probe;	/* probe data */
	const dtrace_recdesc_t *dtbda_recdesc;	/* record description */
	const dtrace_aggdata_t *dtbda_aggdata;	/* aggregation data, if agg. */
	uint32_t dtbda_flags;			/* flags; see above */
} dtrace_bufdata_t;

typedef int dtrace_handle_buffered_f(const dtrace_bufdata_t *, void *);
extern int dtrace_handle_buffered(dtrace_hdl_t *,
    dtrace_handle_buffered_f *, void *);

typedef struct dtrace_setoptdata {
	dtrace_hdl_t *dtsda_handle;		/* handle to DTrace library */
	const dtrace_probedata_t *dtsda_probe;	/* probe data */
	const char *dtsda_option;		/* option that was set */
	dtrace_optval_t dtsda_oldval;		/* old value */
	dtrace_optval_t dtsda_newval;		/* new value */
} dtrace_setoptdata_t;

typedef int dtrace_handle_setopt_f(const dtrace_setoptdata_t *, void *);
extern int dtrace_handle_setopt(dtrace_hdl_t *,
    dtrace_handle_setopt_f *, void *);

/*
 * DTrace Aggregate Interface
 */

#define	DTRACE_A_PERCPU		0x0001
#define	DTRACE_A_KEEPDELTA	0x0002
#define	DTRACE_A_ANONYMOUS	0x0004
#define	DTRACE_A_TOTAL		0x0008
#define	DTRACE_A_MINMAXBIN	0x0010
#define	DTRACE_A_HASNEGATIVES	0x0020
#define	DTRACE_A_HASPOSITIVES	0x0040

#define	DTRACE_AGGZOOM_MAX		0.95	/* height of max bar */

#define	DTRACE_AGGWALK_ERROR		-1	/* error while processing */
#define	DTRACE_AGGWALK_NEXT		0	/* proceed to next element */
#define	DTRACE_AGGWALK_ABORT		1	/* abort aggregation walk */
#define	DTRACE_AGGWALK_CLEAR		2	/* clear this element */
#define	DTRACE_AGGWALK_NORMALIZE	3	/* normalize this element */
#define	DTRACE_AGGWALK_DENORMALIZE	4	/* denormalize this element */
#define	DTRACE_AGGWALK_REMOVE		5	/* remove this element */

struct dtrace_aggdata {
	dtrace_hdl_t *dtada_handle;		/* handle to DTrace library */
	dtrace_aggdesc_t *dtada_desc;		/* aggregation description */
	dtrace_eprobedesc_t *dtada_edesc;	/* enabled probe description */
	dtrace_probedesc_t *dtada_pdesc;	/* probe description */
	caddr_t dtada_data;			/* pointer to raw data */
	uint64_t dtada_normal;			/* the normal -- 1 for denorm */
	size_t dtada_size;			/* total size of the data */
	caddr_t dtada_delta;			/* delta data, if available */
	caddr_t *dtada_percpu;			/* per CPU data, if avail */
	caddr_t *dtada_percpu_delta;		/* per CPU delta, if avail */
	int64_t dtada_total;			/* per agg total, if avail */
	uint16_t dtada_minbin;			/* minimum bin, if avail */
	uint16_t dtada_maxbin;			/* maximum bin, if avail */
	uint32_t dtada_flags;			/* flags */
};

typedef int dtrace_aggregate_f(const dtrace_aggdata_t *, void *);
typedef int dtrace_aggregate_walk_f(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);
typedef int dtrace_aggregate_walk_joined_f(const dtrace_aggdata_t **,
    const int, void *);

extern void dtrace_aggregate_clear(dtrace_hdl_t *);
extern int dtrace_aggregate_snap(dtrace_hdl_t *);
extern int dtrace_aggregate_print(dtrace_hdl_t *, FILE *,
    dtrace_aggregate_walk_f *);

extern int dtrace_aggregate_walk(dtrace_hdl_t *, dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_joined(dtrace_hdl_t *,
    dtrace_aggvarid_t *, int, dtrace_aggregate_walk_joined_f *, void *);

extern int dtrace_aggregate_walk_sorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_keysorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_valsorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_keyvarsorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_valvarsorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_keyrevsorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_valrevsorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_keyvarrevsorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

extern int dtrace_aggregate_walk_valvarrevsorted(dtrace_hdl_t *,
    dtrace_aggregate_f *, void *);

#define	DTRACE_AGD_PRINTED	0x1	/* aggregation printed in program */

/*
 * DTrace Process Control Interface
 *
 * Library clients who wish to have libdtrace create or grab processes for
 * monitoring of their symbol table changes may use these interfaces to
 * request that libdtrace obtain control of the process using libproc.
 */

extern struct ps_prochandle *dtrace_proc_create(dtrace_hdl_t *,
    const char *, char *const *, proc_child_func *, void *);

extern struct ps_prochandle *dtrace_proc_grab(dtrace_hdl_t *, pid_t, int);
extern void dtrace_proc_release(dtrace_hdl_t *, struct ps_prochandle *);
extern void dtrace_proc_continue(dtrace_hdl_t *, struct ps_prochandle *);

/*
 * DTrace Object, Symbol, and Type Interfaces
 *
 * Library clients can use libdtrace to perform symbol and C type information
 * lookups by symbol name, symbol address, or C type name, or to lookup meta-
 * information cached for each of the program objects in use by DTrace.  The
 * resulting struct contain pointers to arbitrary-length strings, including
 * object, symbol, and type names, that are persistent until the next call to
 * dtrace_update().  Once dtrace_update() is called, any cached values must
 * be flushed and not used subsequently by the client program.
 */

#define	DTRACE_OBJ_EXEC	 ((const char *)0L)	/* primary executable file */
#define	DTRACE_OBJ_RTLD	 ((const char *)1L)	/* run-time link-editor */
#define	DTRACE_OBJ_CDEFS ((const char *)2L)	/* C include definitions */
#define	DTRACE_OBJ_DDEFS ((const char *)3L)	/* D program definitions */
#define	DTRACE_OBJ_EVERY ((const char *)-1L)	/* all known objects */
#define	DTRACE_OBJ_KMODS ((const char *)-2L)	/* all kernel objects */
#define	DTRACE_OBJ_UMODS ((const char *)-3L)	/* all user objects */

typedef struct dtrace_objinfo {
	const char *dto_name;			/* object file scope name */
	const char *dto_file;			/* object file path (if any) */
	int dto_id;				/* object file id (if any) */
	uint_t dto_flags;			/* object flags (see below) */
	GElf_Addr dto_text_va;			/* address of text section */
	GElf_Xword dto_text_size;		/* size of text section */
	GElf_Addr dto_data_va;			/* address of data section */
	GElf_Xword dto_data_size;		/* size of data section */
	GElf_Addr dto_bss_va;			/* address of BSS */
	GElf_Xword dto_bss_size;		/* size of BSS */
} dtrace_objinfo_t;

#define	DTRACE_OBJ_F_KERNEL	0x1		/* object is a kernel module */
#define	DTRACE_OBJ_F_PRIMARY	0x2		/* object is a primary module */

typedef int dtrace_obj_f(dtrace_hdl_t *, const dtrace_objinfo_t *, void *);

extern int dtrace_object_iter(dtrace_hdl_t *, dtrace_obj_f *, void *);
extern int dtrace_object_info(dtrace_hdl_t *, const char *, dtrace_objinfo_t *);

typedef struct dtrace_syminfo {
	const char *dts_object;			/* object name */
	const char *dts_name;			/* symbol name */
	ulong_t dts_id;				/* symbol id */
} dtrace_syminfo_t;

extern int dtrace_lookup_by_name(dtrace_hdl_t *, const char *, const char *,
    GElf_Sym *, dtrace_syminfo_t *);

extern int dtrace_lookup_by_addr(dtrace_hdl_t *, GElf_Addr addr,
    GElf_Sym *, dtrace_syminfo_t *);

typedef struct dtrace_typeinfo {
	const char *dtt_object;			/* object containing type */
	ctf_file_t *dtt_ctfp;			/* CTF container handle */
	ctf_id_t dtt_type;			/* CTF type identifier */
	uint_t dtt_flags;			/* Misc. flags */
} dtrace_typeinfo_t;

#define	DTT_FL_USER	0x1			/* user type */

extern int dtrace_lookup_by_type(dtrace_hdl_t *, const char *, const char *,
    dtrace_typeinfo_t *);

extern int dtrace_symbol_type(dtrace_hdl_t *, const GElf_Sym *,
    const dtrace_syminfo_t *, dtrace_typeinfo_t *);

extern int dtrace_type_strcompile(dtrace_hdl_t *,
    const char *, dtrace_typeinfo_t *);

extern int dtrace_type_fcompile(dtrace_hdl_t *,
    FILE *, dtrace_typeinfo_t *);

/*
 * DTrace Probe Interface
 *
 * Library clients can use these functions to iterate over the set of available
 * probe definitions and inquire as to their attributes.  The probe iteration
 * interfaces report probes that are declared as well as those from dtrace(7D).
 */
typedef struct dtrace_probeinfo {
	dtrace_attribute_t dtp_attr;		/* name attributes */
	dtrace_attribute_t dtp_arga;		/* arg attributes */
	const dtrace_typeinfo_t *dtp_argv;	/* arg types */
	int dtp_argc;				/* arg count */
} dtrace_probeinfo_t;

typedef int dtrace_probe_f(dtrace_hdl_t *, const dtrace_probedesc_t *, void *);

extern int dtrace_probe_iter(dtrace_hdl_t *,
    const dtrace_probedesc_t *pdp, dtrace_probe_f *, void *);

extern int dtrace_probe_info(dtrace_hdl_t *,
    const dtrace_probedesc_t *, dtrace_probeinfo_t *);

/*
 * DTrace Vector Interface
 *
 * The DTrace library normally speaks directly to dtrace(7D).  However,
 * this communication may be vectored elsewhere.  Consumers who wish to
 * perform a vectored open must fill in the vector, and use the dtrace_vopen()
 * entry point to obtain a library handle.
 */
struct dtrace_vector {
#if defined(sun)
	int (*dtv_ioctl)(void *, int, void *);
#else
	int (*dtv_ioctl)(void *, u_long, void *);
#endif
	int (*dtv_lookup_by_addr)(void *, GElf_Addr, GElf_Sym *,
	    dtrace_syminfo_t *);
	int (*dtv_status)(void *, processorid_t);
	long (*dtv_sysconf)(void *, int);
};

/*
 * DTrace Utility Functions
 *
 * Library clients can use these functions to convert addresses strings, to
 * convert between string and integer probe descriptions and the
 * dtrace_probedesc_t representation, and to perform similar conversions on
 * stability attributes.
 */
extern int dtrace_addr2str(dtrace_hdl_t *, uint64_t, char *, int);
extern int dtrace_uaddr2str(dtrace_hdl_t *, pid_t, uint64_t, char *, int);

extern int dtrace_xstr2desc(dtrace_hdl_t *, dtrace_probespec_t,
    const char *, int, char *const [], dtrace_probedesc_t *);

extern int dtrace_str2desc(dtrace_hdl_t *, dtrace_probespec_t,
    const char *, dtrace_probedesc_t *);

extern int dtrace_id2desc(dtrace_hdl_t *, dtrace_id_t, dtrace_probedesc_t *);

#define	DTRACE_DESC2STR_MAX	1024	/* min buf size for dtrace_desc2str() */

extern char *dtrace_desc2str(const dtrace_probedesc_t *, char *, size_t);

#define	DTRACE_ATTR2STR_MAX	64	/* min buf size for dtrace_attr2str() */

extern char *dtrace_attr2str(dtrace_attribute_t, char *, size_t);
extern int dtrace_str2attr(const char *, dtrace_attribute_t *);

extern const char *dtrace_stability_name(dtrace_stability_t);
extern const char *dtrace_class_name(dtrace_class_t);

extern int dtrace_provider_modules(dtrace_hdl_t *, const char **, int);

extern const char *const _dtrace_version;
extern int _dtrace_debug;

#ifdef	__cplusplus
}
#endif

#if !defined(sun)
#define _SC_CPUID_MAX		_SC_NPROCESSORS_CONF
#define _SC_NPROCESSORS_MAX	_SC_NPROCESSORS_CONF
#endif

#endif	/* _DTRACE_H */


text:
(function (xhr) {
  "use strict";

  var EnvironmentsProvider = function () {
  };

  EnvironmentsProvider.prototype.get = function (callback) {
    jQuery.getJSON("/environments/", function (data) {
      callback(data);
    });
  };

  xhr.EnvironmentsProvider = EnvironmentsProvider;

}(xhr));

(function (exports, prov) {
  "use strict";

  var Environments = function (envSelector) {
    this.envSelector = envSelector;
    this.provider = new prov.EnvironmentsProvider();
  };

  Environments.prototype.load = function (env) {
    this.provider.get(jQuery.proxy(this.renderEnvironments(env),
                                   this));
  };

  Environments.prototype.bindEvents = function () {
    var envSelector = this.envSelector;
    var parentObj = this;

    this.envSelector.bind('change', function () {
      jQuery.publish( "new-environment", jQuery(this).val() );
    });

    jQuery.subscribe( "new-environment", function (env) {
      jQuery.proxy(parentObj.renderEnvironments(env), parentObj);
    });

    jQuery.subscribe( "deploy", jQuery.proxy(this.load, this));
  };

  Environments.prototype.renderEnvironments = function (env) {
    var envSelector = this.envSelector;
    return function (data) {
      var environments = jQuery(".status");
      environments.empty();

      for(var i = 0, l = data.length; i < l; ++i) {
        var status = jQuery("#environment-status").tmpl(data[i]);
        status.appendTo(environments);
      }

      envSelector.val(env);
    };
  };

  exports.Environments = Environments;

}(window, provider));