text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Kent Tester</title>
    <link rel="stylesheet" href="css/kent.css">

                        Dropdown

                            Dang k-nav can even have dropdowns!

                            How cool is that?

                    Docs

            Github
            Twitter
            Blog

Welcome to Kent CSS

We have headings (this ones an h2)

Its all pretty straight forward. We can write all sorts of styled text inside of a .k-type element. This makes our paragraphs and headers look all professional like. We are also inside of a k-container which constricts our content to 70% of the page, but it stays centered so your page can look modern as heck.

                    Yeah we even have cool blockquotes to make what we are saying seem cool and important. - Jared

We have lists! (this ones an h3 btw)

Some cool unordered list item

Wow more than one list item, this is awesome

That was pretty neat.

Holy Moly, this one is ordered

Look at those numbers

k-grid system

                        k-column one-half

                        k-column one-half

                        k-column one-quarter

                        k-column one-half

                        k-column one-quarter

                        k-column one-third

                        k-column one-third

                        k-column one-third

k-button

Button

Info

                    Warning

                    <button type="button" class="k-button error">Error</button>

                    <button type="button" class="k-button success">Success</button>

Button

Info

                    Warning

                    <button type="button" class="k-button error rounded">Error</button>

                    <button type="button" class="k-button success rounded">Success</button>

Button

Info

                    Warning

                    <button type="button" class="k-button error bordered">Error</button>

                    <button type="button" class="k-button success bordered">Success</button>

Button

Info

                    Warning

                    <button type="button" class="k-button error bordered rounded">Error</button>

                    <button type="button" class="k-button success bordered rounded">Success</button>

k-form

                            Input field
                            <input type="text" class="k-input" placeholder="Check out these nifty inputs">

                            Dropdown

                                <select name="">
                                    <option value="">Option 1</option>
                                    <option value="">Option 2</option>
                                </select>

                    Textarea
                    <textarea class="k-textarea" placeholder="Write a whole bunch of cool text"></textarea>

                 <input class="k-button primary" type="submit" value="Submit">

k-table

                        Num.
                        Song Title
                        Artist
                        Year

                        1
                        Silver Screen
                        Beat Connection
                        2011

                        2
                        Cayucas
                        Oregon Bike Trails
                        2011

                        3
                        m'lover
                        Kishi Bashi
                        2016

redpajama_set_name: RedPajamaGithub


text:
package org.apache.drill.exec.store;

import org.apache.drill.common.logical.StoragePluginConfig;
import org.apache.drill.exec.planner.logical.StoragePlugins;
import org.apache.drill.exec.store.sys.PersistentStore;

/**
 * Storage plugins handler is an additional service for updating storage plugins configs from the file
 */
public interface StoragePluginsHandler {

  /**
   * Update incoming storage plugins configs from persistence store if present, otherwise bootstrap plugins configs.
   *
   * @param persistentStore the last storage plugins configs from persistence store
   * @param bootstrapPlugins bootstrap storage plugins, which are used in case of first Drill start up
   * @return all storage plugins, which should be loaded into persistence store
   */
  void loadPlugins(PersistentStore<StoragePluginConfig> persistentStore, StoragePlugins bootstrapPlugins);

}


text:
<?php
/**
 * @Author: Sebastian Castro
 * @Date:   2017-03-28 15:29:03
 * @Last Modified by:   Sebastian Castro
 * @Last Modified time: 2017-09-22 10:31:02
 */
namespace Biopen\CoreBundle\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;

class WrapperAdmin extends AbstractAdmin
{
    protected $datagridValues = array(
        '_page' => 1,
        '_sort_order' => 'ASC',
        '_sort_by' => 'position',
    );

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper->add('title', 'text');
        $formMapper->add('content', 'sonata_simple_formatter_type', array(
                'format' => 'richhtml',
                'label' => 'Contenu du bandeau',
                'required' => false,
                'ckeditor_context' => 'full',
            ));
        $formMapper->add('rawContent', 'textarea', array(
                'label' => 'Contenu en raw html (optionel)',
                'required' => false,
            ));
        $formMapper->add('textColor', 'text', ['required' => false, 'attr' => ['class' => 'gogo-color-picker']]);
        $formMapper->add('backgroundColor', 'text', ['required' => false, 'attr' => ['class' => 'gogo-color-picker']]);
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper->add('title');
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('title')
            ->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array(),
                    'move' => array(
                        'template' => 'PixSortableBehaviorBundle:Default:_sort.html.twig'
                    )
                )
            ));
    }

    protected function configureRoutes(RouteCollection $collection)
		{
		    $collection->add('move', $this->getRouterIdParameter().'/move/{position}');
		}
}


text:
package com.dremio.exec.fn.hive;

import static org.junit.Assert.assertTrue;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.rules.TestRule;

import com.dremio.common.util.TestTools;
import com.dremio.exec.hive.HiveTestBase;
import com.dremio.exec.planner.physical.PlannerSettings;
import com.dremio.sabot.rpc.user.QueryDataBatch;
import com.google.common.base.Charsets;

public class ITSampleHiveUDFs extends HiveTestBase {

  @ClassRule
  public static final TestRule CLASS_TIMEOUT = TestTools.getTimeoutRule(1100, TimeUnit.SECONDS);

  private void helper(String query, String expected) throws Exception {
    List<QueryDataBatch> results = testSqlWithResults(query);
    String actual = getResultString(results, ",");
    assertTrue(String.format("Result:\n%s\ndoes not match:\n%s", actual, expected), expected.equals(actual));
  }

  @Test
  public void booleanInOut() throws Exception{
    String query = "SELECT " +
        "testHiveUDFBoolean(true) as col1," +
        "testHiveUDFBoolean(false) as col2," +
        "testHiveUDFBoolean(cast(null as boolean)) as col3 " +
        "FROM hive.kv LIMIT 1";

    String expected = "col1,col2,col3\n" + "true,false,null\n";
    helper(query, expected);
  }

  @Ignore("DRILL-2470")
  @Test
  public void byteInOut() throws Exception{
    String query = "SELECT testHiveUDFByte(tinyint_field) as col1 FROM hive.readtest";
    String expected = "col1\n" + "34\n" + "null\n";
    helper(query, expected);
  }

  @Ignore("DRILL-2470")
  @Test
  public void shortInOut() throws Exception{
    String query = "SELECT testHiveUDFShort(smallint_field) as col1 FROM hive.readtest";
    String expected = "col1\n" + "3455\n" + "null\n";
    helper(query, expected);
  }

  @Test
  public void intInOut() throws Exception{
    String query = "SELECT testHiveUDFInt(int_field) as col1 FROM hive.readtest";
    String expected = "col1\n" + "123456\n" + "null\n";
    helper(query, expected);
  }

  @Test
  public void longInOut() throws Exception{
    String query = "SELECT testHiveUDFLong(bigint_field) as col1 FROM hive.readtest";
    String expected = "col1\n" + "234235\n" + "null\n";
    helper(query, expected);
  }

  @Test
  public void floatInOut() throws Exception{
    String query = "SELECT testHiveUDFFloat(float_field) as col1 FROM hive.readtest";
    String expected = "col1\n" + "4.67\n" + "null\n";    helper(query, expected);
  }

  @Test
  public void doubleInOut() throws Exception{
    String query = "SELECT testHiveUDFDouble(double_field) as col1 FROM hive.readtest";
    String expected = "col1\n" + "8.345\n" + "null\n";
    helper(query, expected);
  }

  @Test
  public void stringInOut() throws Exception{
    String query = "SELECT testHiveUDFString(string_field) as col1 FROM hive.readtest";
    String expected = "col1\n" + "stringfield\n" + "null\n";
    helper(query, expected);
  }

  @Test
  public void binaryInOut() throws Exception{
    String query = "SELECT testHiveUDFBinary(binary_field) as col1 FROM hive.readtest";
    String expected = "col1\n" + "binaryfield\n" + "null\n";
    helper(query, expected);    helper(query, expected);
  }

  @Test
  public void varcharInOut() throws Exception{
    String query = "SELECT " +
        "testHiveUDFVarChar('This is a varchar') as col1," +
        "testHiveUDFVarChar(cast(null as varchar)) as col2 " +
        "FROM hive.kv LIMIT 1";

    String expected = "col1,col2\n" + "This is a varchar,null\n";
    helper(query, expected);
  }

  @Test
  public void varcharInCharOut() throws Exception {
    String query = "SELECT " +
        "testHiveUDFChar(cast ('This is a char' as char(20))) as col1," +
        "testHiveUDFChar(cast(null as char)) as col2 " +
        "FROM hive.kv LIMIT 1";

    String expected = "col1,col2\n" + "This is a char,null\n";
    helper(query, expected);
  }

  @Test
  @Ignore("doesn't work across timezones")
  public void dateInOut() throws Exception{
    String query = "SELECT " +
        "testHiveUDFDate(cast('1970-01-02 10:20:33' as date)) as col1," +
        "testHiveUDFDate(cast(null as date)) as col2 " +
        "FROM hive.kv LIMIT 1";

    String expected = "col1,col2\n" + "1970-01-01T08:00:00.000-08:00,null\n";
    helper(query, expected);
  }

  @Test
  @Ignore("doesn't work across timezones")
  public void timestampInOut() throws Exception{
    String query = "SELECT " +
        "testHiveUDFTimeStamp(cast('1970-01-02 10:20:33' as timestamp)) as col1," +
        "testHiveUDFTimeStamp(cast(null as timestamp)) as col2 " +
        "FROM hive.kv LIMIT 1";

    String expected = "col1,col2\n" + "1970-01-02T10:20:33.000-08:00,null\n";
    helper(query, expected);
  }

  @Test
  @Ignore("decimal")
  public void decimalInOut() throws Exception{
    try {
      test(String.format("alter session set \"%s\" = true", PlannerSettings.ENABLE_DECIMAL_DATA_TYPE_KEY));
      String query = "SELECT " +
          "testHiveUDFDecimal(cast('1234567891234567891234567891234567891.4' as decimal(38, 1))) as col1 " +
          "FROM hive.kv LIMIT 1";

      String expected = "col1\n" + "1234567891234567891234567891234567891.4\n";
      helper(query, expected);
    } finally {
      test(String.format("alter session set \"%s\" = false", PlannerSettings.ENABLE_DECIMAL_DATA_TYPE_KEY));
    }
  }

  @Test // DX-10234
  public void testLargeOutputValues() throws Exception {
    final String longVal1 = "Not every application requires security. Random assignment can be an efficient way for " +
        "multiple entities to generate identifiers in a shared space without any coordination or partitioning. " +
        "Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space " +
        "causes problems when entities end up with shares that are too small or too big";
    final String longVal2 = longVal1 + longVal1 + longVal1;

    String query = String.format("SELECT " +
        "testHiveUDFCHAR(col) as c1, " +
        "testHiveUDFVARCHAR(col) as c2, " +
        "testHiveUDFBINARY(convert_to(col, 'UTF8')) as c3 FROM " +
        "(values('%s'), ('%s'), (cast(null as varchar))) as t(col)", longVal1, longVal2);

    testBuilder()
        .sqlQuery(query)
        .unOrdered()
        .baselineColumns("c1", "c2", "c3")
        .baselineValues(longVal1.substring(0, 255) /* CHAR return type returns max of 255 chars */,
            longVal1, longVal1.getBytes(Charsets.UTF_8))
        .baselineValues(longVal2.substring(0, 255) /* CHAR return type returns max of 255 chars */,
            longVal2, longVal2.getBytes(Charsets.UTF_8))
        .baselineValues(null, null, null)
        .go();
  }

  @Test
  public void testDecimalPow() throws Exception {
    try {
      setSystemOption(PlannerSettings.ENABLE_DECIMAL_DATA_TYPE, "true");
      final String query = "select pow(c,2) from cp" +
        ".\"powHiveFunction.parquet\"";
      test(query);
    } finally {
      setSystemOption(PlannerSettings.ENABLE_DECIMAL_DATA_TYPE, PlannerSettings
        .ENABLE_DECIMAL_DATA_TYPE.getDefault().getBoolVal().toString());
    }
  }

  @Test
  public void testDX17216() throws Exception {
    try {
      setSystemOption(PlannerSettings.ENABLE_DECIMAL_DATA_TYPE, "true");
      setSystemOption(PlannerSettings.ENABLE_DECIMAL_V2, "true");

      final String query = "SELECT " +
        "pow(1 + CAST(c AS NUMERIC(12,2)),2.0) from cp" +
        ".\"powHiveFunction.parquet\"";
      test(query);
    } finally {
      setSystemOption(PlannerSettings.ENABLE_DECIMAL_DATA_TYPE, PlannerSettings
        .ENABLE_DECIMAL_DATA_TYPE.getDefault().getBoolVal().toString());
      setSystemOption(PlannerSettings.ENABLE_DECIMAL_V2, PlannerSettings
        .ENABLE_DECIMAL_V2.getDefault().getBoolVal().toString());
    }
  }
}


text:
package space

import (
	"fmt"
	"strings"

	"github.com/cloudfoundry/cli/cf/command_registry"
	. "github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/models"
	"github.com/cloudfoundry/cli/flags"
	"github.com/cloudfoundry/cli/flags/flag"
	"github.com/cloudfoundry/cli/plugin/models"

	"github.com/cloudfoundry/cli/cf/api/space_quotas"
	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	"github.com/cloudfoundry/cli/cf/formatters"
	"github.com/cloudfoundry/cli/cf/requirements"
	"github.com/cloudfoundry/cli/cf/terminal"
)

type ShowSpace struct {
	ui          terminal.UI
	config      core_config.Reader
	spaceReq    requirements.SpaceRequirement
	quotaRepo   space_quotas.SpaceQuotaRepository
	pluginModel *plugin_models.GetSpace_Model
	pluginCall  bool
}

func init() {
	command_registry.Register(&ShowSpace{})
}

func (cmd *ShowSpace) MetaData() command_registry.CommandMetadata {
	fs := make(map[string]flags.FlagSet)
	fs["guid"] = &cliFlags.BoolFlag{Name: "guid", Usage: T("Retrieve and display the given space's guid.  All other output for the space is suppressed.")}
	fs["security-group-rules"] = &cliFlags.BoolFlag{Name: "security-group-rules", Usage: T("Retrieve the rules for all the security groups associated with the space")}
	return command_registry.CommandMetadata{
		Name:        "space",
		Description: T("Show space info"),
		Usage:       T("CF_NAME space SPACE"),
		Flags:       fs,
	}
}

func (cmd *ShowSpace) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) (reqs []requirements.Requirement, err error) {
	if len(fc.Args()) != 1 {
		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + command_registry.Commands.CommandUsage("space"))
	}

	cmd.spaceReq = requirementsFactory.NewSpaceRequirement(fc.Args()[0])
	reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedOrgRequirement(),
		cmd.spaceReq,
	}
	return
}

func (cmd *ShowSpace) SetDependency(deps command_registry.Dependency, pluginCall bool) command_registry.Command {
	cmd.ui = deps.Ui
	cmd.config = deps.Config
	cmd.quotaRepo = deps.RepoLocator.GetSpaceQuotaRepository()
	cmd.pluginCall = pluginCall
	cmd.pluginModel = deps.PluginModels.Space
	return cmd
}

func (cmd *ShowSpace) Execute(c flags.FlagContext) {
	space := cmd.spaceReq.GetSpace()
	if cmd.pluginCall {
		cmd.populatePluginModel(space)
		return
	}
	if c.Bool("guid") {
		cmd.ui.Say(space.Guid)
	} else {
		cmd.ui.Say(T("Getting info for space {{.TargetSpace}} in org {{.OrgName}} as {{.CurrentUser}}...",
			map[string]interface{}{
				"TargetSpace": terminal.EntityNameColor(space.Name),
				"OrgName":     terminal.EntityNameColor(space.Organization.Name),
				"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
			}))

		quotaString := cmd.quotaString(space)
		cmd.ui.Ok()
		cmd.ui.Say("")
		table := terminal.NewTable(cmd.ui, []string{terminal.EntityNameColor(space.Name), "", ""})
		table.Add("", T("Org:"), terminal.EntityNameColor(space.Organization.Name))

		apps := []string{}
		for _, app := range space.Applications {
			apps = append(apps, terminal.EntityNameColor(app.Name))
		}
		table.Add("", T("Apps:"), strings.Join(apps, ", "))

		domains := []string{}
		for _, domain := range space.Domains {
			domains = append(domains, terminal.EntityNameColor(domain.Name))
		}
		table.Add("", T("Domains:"), strings.Join(domains, ", "))

		services := []string{}
		for _, service := range space.ServiceInstances {
			services = append(services, terminal.EntityNameColor(service.Name))
		}
		table.Add("", T("Services:"), strings.Join(services, ", "))

		securityGroups := []string{}
		for _, group := range space.SecurityGroups {
			securityGroups = append(securityGroups, terminal.EntityNameColor(group.Name))
		}
		table.Add("", T("Security Groups:"), strings.Join(securityGroups, ", "))

		table.Add("", T("Space Quota:"), quotaString)

		table.Print()
	}
	if c.Bool("security-group-rules") {
		cmd.ui.Say("")
		for _, group := range space.SecurityGroups {
			cmd.ui.Say(T("Getting rules for the security group  : {{.SecurityGroupName}}...",
				map[string]interface{}{"SecurityGroupName": terminal.EntityNameColor(group.Name)}))
			table := terminal.NewTable(cmd.ui, []string{"", "", "", ""})
			for _, rules := range group.Rules {
				for ruleName, ruleValue := range rules {
					table.Add("", ruleName, ":", fmt.Sprintf("%v", ruleValue))
				}
				table.Add("", "", "", "")
			}
			table.Print()
		}
	}

}

func (cmd *ShowSpace) quotaString(space models.Space) string {
	var instance_memory string

	if space.SpaceQuotaGuid == "" {
		return ""
	}

	quota, err := cmd.quotaRepo.FindByGuid(space.SpaceQuotaGuid)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return ""
	}

	if quota.InstanceMemoryLimit == -1 {
		instance_memory = "-1"
	} else {
		instance_memory = formatters.ByteSize(quota.InstanceMemoryLimit * formatters.MEGABYTE)
	}
	memory := formatters.ByteSize(quota.MemoryLimit * formatters.MEGABYTE)

	spaceQuota := fmt.Sprintf("%s (%s memory limit, %s instance memory limit, %d routes, %d services, paid services %s)", quota.Name, memory, instance_memory, quota.RoutesLimit, quota.ServicesLimit, formatters.Allowed(quota.NonBasicServicesAllowed))
	//	spaceQuota := fmt.Sprintf(T("{{.QuotaName}} ({{.MemoryLimit}} memory limit, {{.InstanceMemoryLimit}} instance memory limit, {{.RoutesLimit}} routes, {{.ServicesLimit}} services, paid services {{.NonBasicServicesAllowed}})",
	//		map[string]interface{}{
	//			"QuotaName":               quota.Name,
	//			"MemoryLimit":             memory,
	//			"InstanceMemoryLimit":     instance_memory,
	//			"RoutesLimit":             quota.RoutesLimit,
	//			"ServicesLimit":           quota.ServicesLimit,
	//			"NonBasicServicesAllowed": formatters.Allowed(quota.NonBasicServicesAllowed)}))

	return spaceQuota
}

func (cmd *ShowSpace) populatePluginModel(space models.Space) {
	cmd.pluginModel.Name = space.Name
	cmd.pluginModel.Guid = space.Guid

	cmd.pluginModel.Organization.Name = space.Organization.Name
	cmd.pluginModel.Organization.Guid = space.Organization.Guid

	for _, app := range space.Applications {
		a := plugin_models.GetSpace_Apps{
			Name: app.Name,
			Guid: app.Guid,
		}
		cmd.pluginModel.Applications = append(cmd.pluginModel.Applications, a)
	}

	for _, domain := range space.Domains {
		d := plugin_models.GetSpace_Domains{
			Name: domain.Name,
			Guid: domain.Guid,
			OwningOrganizationGuid: domain.OwningOrganizationGuid,
			Shared:                 domain.Shared,
		}
		cmd.pluginModel.Domains = append(cmd.pluginModel.Domains, d)
	}

	for _, service := range space.ServiceInstances {
		si := plugin_models.GetSpace_ServiceInstance{
			Name: service.Name,
			Guid: service.Guid,
		}
		cmd.pluginModel.ServiceInstances = append(cmd.pluginModel.ServiceInstances, si)
	}
	for _, group := range space.SecurityGroups {
		sg := plugin_models.GetSpace_SecurityGroup{
			Name:  group.Name,
			Guid:  group.Guid,
			Rules: group.Rules,
		}
		cmd.pluginModel.SecurityGroups = append(cmd.pluginModel.SecurityGroups, sg)
	}

	quota, err := cmd.quotaRepo.FindByGuid(space.SpaceQuotaGuid)
	if err == nil {
		cmd.pluginModel.SpaceQuota.Name = quota.Name
		cmd.pluginModel.SpaceQuota.Guid = quota.Guid
		cmd.pluginModel.SpaceQuota.MemoryLimit = quota.MemoryLimit
		cmd.pluginModel.SpaceQuota.InstanceMemoryLimit = quota.InstanceMemoryLimit
		cmd.pluginModel.SpaceQuota.RoutesLimit = quota.RoutesLimit
		cmd.pluginModel.SpaceQuota.ServicesLimit = quota.ServicesLimit
		cmd.pluginModel.SpaceQuota.NonBasicServicesAllowed = quota.NonBasicServicesAllowed
	}
}


text:
Sprout Orchard is a set of scripts (bash & ruby) which run a selection of
[Chef](http://www.opscode.com/chef/)
recipes in [Pivotal Sprout](https://github.com/pivotal-sprout/sprout)
as specified by the meta-recipes in [Sprout Wrap](https://github.com/pivotal-sprout/sprout-wrap)
in order to create OS X disk images which are deployed via
[DeployStudio](http://www.deploystudio.com/Home.html).

## Why?

Sprout Orchard delivers a disk image which we can use to quickly (~20 minutes)
bring a freshly-unboxed OS X machine to a useful state.

In our case, we use it for our developer workstations.  Our developers
use a variety of tools (IDEs such as RubyMine, editors such as vim and TextMate,
databases such as MySQL and PostgrSQL, applications such as Chrome and Skype).
When we give a developer a new machine, it is pre-loaded with those items.

Our process of building a developer workstation is encapsulated in a series
of Chef recipes (i.e. Sprout, Sprout-wrap).  Sprout Orchard pre-bakes those
recipes in a disk image.  Installing the disk image is faster than running
the Chef recipes on each new workstation. Also, having a disk image spares the
developer from problems such as inaccessible download servers, stale URLs, etc.

The process is fairly automated.  A typical workflow is as follows:

* A developer updates a recipe (e.g. Sublime Text) and pushes to Pivotal-sprout's sprout repo on github
* A Sprout Orchard Jenkins server detects that there has been an update to the repo and begins a build
* At the end of the build (assuming success), the resulting disk image, with the new TextMate, is copied to the DeployStudio server

## How do I set it up?

If you're interested in setting it up yourself, please refer to the
[wiki](https://github.com/pivotal-sprout/sprout-orchard/wiki/)

## What will I need?

You'll need the following:

1.  A DeployStudio server
2.  A [Jenkins](http://jenkins-ci.org/)  server (can also be the same machine as the DeployStudio server)
3.  An OS X build machine (it can be a virtual machine running under VMWare Fusion)

## Bugs

This process doesn't capture recovery partitions
(i.e. a newly-imaged machine won't have a recovery partition); however, this
is workable by creating a package which installs a recovery partition.
[This blogpost](http://derflounder.wordpress.com/2012/06/26/creating-an-updated-recovery-hd/)
has good information.

The build process will frequently fail, a success rate of 20% is good.
Failures can be caused by the DeployStudio share not mounted on boot by
the OS X machine's "Persistent" personality, by stale download URLs, by offline
download servers, by flawed gem dependencies, etc....

# To whom do we complain?
**sprout-orchard** started as a side project of [Matthew
Kocher](https://github.com/mkocher) and [Brian
Cunnie](https://github.com/briancunnie) of Pivotal Labs in Summer 2011.


text:
import React, { Component } from 'react'

import firebase from 'firebase'

import RaisedButton from 'material-ui/RaisedButton'

import LocalizedStrings from 'react-localization'

let strings = new LocalizedStrings({
 en:{
   logout:"Logout"
 },
 ja: {
   logout:"ログアウト"
 }
})

class LogoutBtn extends Component {

  onLogoutBtnClick(){
    firebase.auth().signOut();
  }

  render () {
    return (
        <RaisedButton
          label={strings.logout}
          secondary={true}
          onClick={this.onLogoutBtnClick}
          style={{verticalAlign: 'middle'}}
        />
    )
  }
}

export default LogoutBtn


text:
;(function (root, factory) {
		if (typeof define === 'function' && define.amd) {
				// AMD. Register as an anonymous module.
				define(function () {
						return factory();
				});
		} else if (typeof module === 'object' && module.exports) {
				// Node. Does not work with strict CommonJS, but
				// only CommonJS-like environments that support module.exports,
				// like Node.
				module.exports = factory();
		} else {
				// Browser globals
				root.mmirConfig = factory();
		}
}(typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : typeof global !== 'undefined' ? global : this, function () {

//copied requirejs config from mmirf/mainConfig.js
//MODIFICATIONS:
//  * added path.logger = 'mmirf/tools/logger'
//  * added path.jquery = 'empty:'
//FIXME need solution for pre-init in mainConfig.js
return {

	//[MOD START] requirejs-build: additional dependencies that should be included in build
	include: [
		'mmirf/logger',
		'mmirf/stacktrace'
	],
	//[MOD STOP] requirejs-build

	/** @memberOf mmir.require.config */
	baseUrl: './'

	//configurations for the modules:
	, config: {

		/** @memberOf mmir.require.config.moduleConfig */
		'mmirf/inputManager': {
			modelUri: 'config/states/input.xml'
			// simple | extended
			, mode: 'extended'
			//EXAMPLE: set module-specific log-level to 'info'
			//, logLevel: 'info'
		}
		/** @memberOf mmir.require.config.moduleConfig */
		, 'mmirf/dialogManager': {
			modelUri: 'config/states/dialog.xml'
			// simple | extended
			, mode: 'extended'
			//EXAMPLE: set module-specific log-level to 'verbose'
			//, logLevel: 'verbose'
		}

		//EXAMPLE: set module-specific log-level to 'warn'
		//         log-levels: 'verbose' | 'debug' | 'info' | 'warn' | 'error' | 'critical' | 'disabled'
		//         or number:     0           1        2        3         4           5           6
		//, 'mmirf/view': { logLevel: 'warn' }

	}

	//definition for the module IDs and their (file) paths
	, paths : {

		/** @memberOf mmir.require.config.paths */

		//[MOD START] requirejs-build
		'jquery': 'empty:',
		'mmirf/logger': 'tools/logger',//<- DEFAULT links to enabled logger implementation
		//[MOD STOP] requirejs-build

		// core
			'mmirf/core': 'core'
		, 'mmirf/main': 'main'

		// lib
		, 'mmirf/scion': 'vendor/libs/scion-amd-mod.min'
		, 'mmirf/scionRuntimeLib': 'vendor/libs/scion-core-lib'

		// globals and AMDs
		, 'mmirf/resources': 'tools/resources'
		, 'mmirf/commonUtils': 'tools/commonUtils'
		, 'mmirf/paramsParseFunc': 'tools/paramsParseFunc'
		, 'mmirf/env': 'tools/envDetect'

		, 'mmirf/codeGenUtils': 'tools/codeGenUtils'

		, 'mmirf/asyncUtils': 'tools/asyncUtils'

		// dialog/input manager
		, 'mmirf/inputManager': 'manager/dialog/inputManager'
		, 'mmirf/dialogManager': 'manager/dialog/dialogManager'
		, 'mmirf/managerFactory': 'manager/dialog/managerFactory'
		, 'mmirf/engineConfig': 'manager/dialog/engineConfig'

		, 'mmirf/scionEngine': 'manager/dialog/scion/scionEngine'
		, 'mmirf/scionUtil': 'manager/dialog/scion/scionUtil'
		, 'mmirf/scionRuntime': 'manager/dialog/scion/scionRuntime'

		// controllers/models
		//FIXME replace controller manager:
		, 'mmirf/controllerManager': 'manager/controllerManager'
		// , 'mmirf/controllerManager': 'requirejs_build/appjs/ionicControllerManager'
		, 'mmirf/controller': 'mvc/controllers/controller'
		, 'mmirf/helper': 'mvc/controllers/helper'
		, 'mmirf/modelManager': 'manager/modelManager'

		// #####################################################################
		// ####################### PRESENTATION LAYER ##########################
		// #####################################################################

		, 'mmirf/presentationManager': 'manager/presentationManager'

		//FIXME replace view engine:
//		//simple viewEngine for inserting/rendering views into the HTML page
//		, 'mmirf/simpleViewEngine': 'env/view/simpleViewEngine'
		// , 'mmirf/simpleViewEngine': 'requirejs_build/appjs/ionicViewEngine'
			, 'mmirf/simpleViewEngine': 'env/view/stubViewEngine'

		//helper module that provides a "please wait"-kind of overlay dialog
		, 'mmirf/waitDialog': 'tools/stdlne-wait-dlg'

		, 'mmirf/configurationManager': 'manager/settings/configurationManager'

		// @chsc03 required by contentElement, renderUtils, declared in presentationManager [@russa not really...]
		, 'mmirf/languageManager': 'manager/settings/languageManager'

		, 'mmirf/mediaManager': 'manager/mediaManager'
		, 'mmirf/notificationManager': 'manager/notificationManager'

		, 'mmirf/viewConstants': 'mvc/views/viewConstants'
		// @chsc03 depends on parseUtils, renderUtils, yield, required in presentationManager
		, 'mmirf/layout': 'mvc/views/layout'
		// @chsc03 depends on parseUtils, renderUtils, contentElement, required in presentationManager
		, 'mmirf/view': 'mvc/views/view'
		// @chsc03 depends on parseUtils, renderUtils, contentElement, required in presentationManager
		, 'mmirf/partial': 'mvc/views/partial'
		, 'mmirf/contentElement': 'mvc/views/contentElement'
		, 'mmirf/yield': 'mvc/views/yield'

		//FIXME replace view loader:
		// view loader: loads compiled views or raw views & compiles them:
//		, 'mmirf/viewLoader': 'env/view/viewLoader'
		, 'mmirf/viewLoader': 'env/view/stubViewLoader'

		// @chsc03 renderUtils required by viewInitializer and depends on parserModule
		, 'mmirf/renderUtils': 'mvc/parser/templateRenderUtils'
		, 'mmirf/parserModule': 'mvc/parser/parserModule'

		, 'mmirf/storageUtils': 'mvc/parser/storageUtils'

		//// template processing / compiling: ////////////

		// @chsc03 required by parseUtils and all its dependencies declared in presentationManager
		, 'mmirf/antlr3': 'vendor/libs/antlr3-all_amd'
		// @chsc03 parseUtils depends on the following paths
		, 'mmirf/parseUtils': 'mvc/parser/templateParseUtils'
		, 'mmirf/ES3Lexer': 'mvc/parser/gen/ES3Lexer_amd'
		, 'mmirf/ES3Parser': 'mvc/parser/gen/ES3Parser_amd'
		, 'mmirf/scriptLexer': 'mvc/parser/gen/MmirScriptLexer_amd'
		, 'mmirf/scriptParser': 'mvc/parser/gen/MmirScriptParser_amd'
		, 'mmirf/contentLexer': 'mvc/parser/gen/MmirScriptContentLexer_amd'
		, 'mmirf/contentParser': 'mvc/parser/gen/MmirScriptContentParser_amd'
		, 'mmirf/templateLexer': 'mvc/parser/gen/MmirTemplateLexer_amd'
		, 'mmirf/templateParser': 'mvc/parser/gen/MmirTemplateParser_amd'

		// @chsc03 templateProcessor depends on parsingResult
		, 'mmirf/templateProcessor': 'mvc/parser/templateProcessor'
		, 'mmirf/parsingResult': 'mvc/parser/parsingResult'

		// #####################################################################
		// ########                SEMANTIC PROCESSING              ############
		// ######## (grammar generation/compilation, execution etc) ############
		// #####################################################################
		, 'mmirf/grammarConverter': 'semantic/grammarConverter'
		, 'mmirf/semanticInterpreter': 'semantic/semanticInterpreter'
		, 'mmirf/positionUtils': 'semantic/positionUtils'
		, 'mmirf/asyncGrammar': 'semantic/asyncGrammar'
		, 'mmirf/stemmer': 'semantic/stemmer'
		, 'mmirf/jscc': 'vendor/libs/jscc-umd'
		, 'mmirf/jison': 'vendor/libs/jison'
		, 'mmirf/pegjs': 'vendor/libs/peg-0.10.0'
		, 'mmirf/baseGen': 'env/grammar/baseGenerator'
		, 'mmirf/asyncGen': 'env/grammar/asyncGenerator'
		, 'mmirf/jsccGen': 'env/grammar/jsccGenerator'
		, 'mmirf/jsccAsyncGen': 'env/grammar/jsccAsyncGenerator'
		, 'mmirf/jisonGen': 'env/grammar/jisonGenerator'
		, 'mmirf/jisonAsyncGen': 'env/grammar/jisonAsyncGenerator'
		, 'mmirf/pegjsGen': 'env/grammar/pegjsGenerator'
		, 'mmirf/pegjsAsyncGen': 'env/grammar/pegjsAsyncGenerator'

		//utility for loading event handling (registering / emitting / ...)
		, 'mmirf/events': 'tools/eventEmitter'

		//MD5 checksum computation: for checking pre-compiled resources, e.g.
		//    grammars (JSON->JS), and templates (eHTML->JS)
		, 'mmirf/md5': 'vendor/libs/md5'
		, 'mmirf/checksumUtils': 'tools/checksumUtils'

		//utility function for loading LINK tags (i.e. CSS files) into the current document
		, 'mmirf/loadCss': 'tools/loadCss'

		//extension for mmirf/events adding a function for creating event handler properties
		, 'mmirf/events/propertyHandler': 'tools/extensions/EventEmitterPropertyHandler'

		//"backward compatibility-restorer":
		, 'mmirf/encodeUtils': 'tools/extensions/EncodeUtils'
		, 'mmirf/jsonUtils': 'tools/extensions/JsonUtils'
		, 'mmirf/stringUtils': 'tools/extensions/StringUtils'
		, 'mmirf/resizeToFit': 'tools/extensions/ResizeFitToSourroundingBox'
		, 'mmirf/stringExtension': 'tools/extensions/StringExtensions'
		, 'mmirf/core1Compatibility' : 'tools/extensions/Core1Compatibility'
		, 'mmirf/commonUtilsCompatibility': 'tools/extensions/CommonUtilsV1Compatibility'
		, 'mmirf/languageManagerCompatibility': 'tools/extensions/LanguageManagerV1Compatibility'
		, 'mmirf/core2Compatibility' : 'tools/extensions/Core2Compatibility'
		, 'mmirf/core3Compatibility' : 'tools/extensions/Core3Compatibility'
		, 'mmirf/semanticInterpreterCompatibility' : 'tools/extensions/SemanticInterpreterV3Compatibility'
		, 'mmirf/core3ModuleIdCompatibility' : 'tools/extensions/Core3ModuleIdCompatibility'
		, 'mmirf/dictionary': 'tools/extensions/dictionary'
		, 'mmirf/moduleIdCompatibilityFunc': 'tools/extensions/ModuleIdCompatibilityFunc'
		, 'mmirf/core4Compatibility' : 'tools/extensions/Core4Compatibility'
		, 'mmirf/core4ModuleIdCompatibility' : 'tools/extensions/Core4ModuleIdCompatibility'
		, 'mmirf/dialogManager4Compatibility': 'tools/extensions/DialogManager4Compatibility'

		//optional or "dynamically" loaded modules

		// #####################################################################
		// #####         OPTIONAL / DYNAMICALLY LOADED MODULES          ########
		// ##### (depending on configuration in core.js or global vars) ########
		// #####################################################################

		//add missing functionality by applying polyfill (if impl. is missing), for:
		// * Map
		// * Set
		// * Symbol
		// * Array.from
		// * Array[@iterator]
		, 'mmirf/polyfill': 'vendor/libs/es6-map-set-polyfill'

		// (console) logging related modules (either 'mmirf/loggerEnabled' or 'mmirf/loggerDisabled' will be mapped to 'mmirf/logger', depending on configuration
		, 'mmirf/loggerEnabled': 'tools/logger'
		, 'mmirf/loggerDisabled': 'tools/loggerDisabled'
		, 'mmirf/stacktrace': 'vendor/libs/stacktrace-v2.0.2'

	},//END: paths : {...

	packages: [{
		'name': 'mmirf/util',
		'location': 'tools/util_purejs'
	}]

};

}));


text:
#ifndef TEST_NSDL_ACCESS_HELPER_H
#define TEST_NSDL_ACCESS_HELPER_H

#include "nsdlaccesshelper.h"
#include "common_stub.h"

class TestObserver;

class Test_NsdlAccessHelper
{
public:
    Test_NsdlAccessHelper();

    virtual ~Test_NsdlAccessHelper();

    void test_nsdl_c_callback();

    void test_nsdl_c_memory_alloc();

    void test_nsdl_c_memory_free();

    void test_nsdl_c_send_to_server();

    void test_nsdl_c_received_from_server();

    void test_socket_malloc();

    void test_socket_free();

    TestObserver *observer;
    M2MConnectionHandler *connection_handler;
private:
    void clear_list();
};

#endif // TEST_NSDL_ACCESS_HELPER_H


text:
package sqlx

import (
	"testing"
)

// Устанавливаем драйвер для всех тестов
func init() {
	Driver("postgres")
}

func TestSqlTable1(t *testing.T) {
	expect := `SELECT * FROM "users"`
	result := Table("users").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlTable1.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlTable2(t *testing.T) {
	expect := `SELECT * FROM ( SELECT "group_id", MAX("created_at") as "lastdate" FROM "users" GROUP BY "group_id" ) as "users" ORDER BY "lastdate" DESC`
	result := Table(func(builder *Builder) {
		builder.Select("group_id").From("users").GroupBy("group_id").Max("created_at", "lastdate")
	}).OrderBy("lastdate", "DESC").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlTable2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlTable3(t *testing.T) {
	expect := `SELECT * FROM ( SELECT * FROM "users" WHERE "id" = $1 ) as users`
	subque := Table("users").Where("id", "=", 1)
	result := Table(Raw("( "+subque.Sql()+" ) as users", subque.Data()...)).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlTable3.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlTable4(t *testing.T) {
	expect := `SELECT * FROM ( SELECT * FROM "users" WHERE "id" = $1 ) as "users"`
	subque := Table("users").Where("id", "=", 1)
	result := Table(subque).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlTable4.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlTable5(t *testing.T) {
	expect := `SELECT * FROM (SELECT * FROM users WHERE id IN ($1, $2, $3)) as users WHERE "age" > $4`
	result := Table(Raw("(SELECT * FROM users WHERE id IN (?, ?, ?)) as users", 1, 2, 3)).Where("age", ">", 21).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlTable5.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlSelect1(t *testing.T) {
	expect := `SELECT "id" FROM "users"`
	result := Table("users").Select("id").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlSelect1.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlSelect2(t *testing.T) {
	expect := `SELECT "id", "name", "age" FROM "users"`
	result := Table("users").Select("id", "name", "age").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlSelect2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlSelect3(t *testing.T) {
	expect := `SELECT "id", "name", "age", COUNT(*) as count FROM "users"`
	result := Table("users").Select("id", "name", "age", Raw("COUNT(*) as count")).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlSelect3.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlSelect4(t *testing.T) {
	expect := `SELECT "id", "name", "age", COUNT(*) as count FROM "users"`
	result := Table("users").Select("id", "name").Select("age").SelectRaw("COUNT(*) as count").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlSelect4.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlSelectRaw1(t *testing.T) {
	expect := `SELECT COUNT(*) as count FROM "users"`
	result := Table("users").Select(Raw("COUNT(*) as count")).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlSelectRaw1.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlSelectRaw2(t *testing.T) {
	expect := `SELECT COUNT(*) as count FROM "users"`
	result := Table("users").SelectRaw("COUNT(*) as count").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlSelectRaw2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlSelectRaw3(t *testing.T) {
	expect := `SELECT "name", (SELECT age FROM ag WHERE id = $1 LIMIT 1) as age FROM "users"`
	result := Table("users").Select("name", Raw("(SELECT age FROM ag WHERE id = ? LIMIT 1) as age", 1)).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlSelectRaw3.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlSelectRaw4(t *testing.T) {
	expect := `SELECT name, (SELECT age FROM ag WHERE id = $1 LIMIT 1) as age FROM "users"`
	result := Table("users").SelectRaw("name, (SELECT age FROM ag WHERE id = ? LIMIT 1) as age", 1).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlSelectRaw4.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereBase1(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "id" = $1`
	result := Table("users").Where("id", "=", 1).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereBase1.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereBase2(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "id" = $1 OR "id" = $2`
	result := Table("users").Where("id", "=", 1).OrWhere("id", "=", 2).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereBase2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereBase3(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "id" = $1 AND "age" = $2`
	result := Table("users").Where("id", "=", 1).Where("age", "=", 31).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereBase3.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereBase4(t *testing.T) {
	expect := `SELECT "timestamp"::date FROM "users" WHERE "timestamp"::date = $1`
	result := Table("users").Where("timestamp::date", "=", "2018-02-10").Select("timestamp::date").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereBase4.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereGroup(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "id" = $1 OR ( "id" = $2 OR "id" = $3 )`
	result := Table("users").Where("id", "=", 1).OrWhereGroup(func(builder *Builder) {
		builder.Where("id", "=", 2).OrWhere("id", "=", 3)
	}).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereGroup.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereRaw1(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE id = 1 OR "age" = 2`
	result := Table("users").WhereRaw("id = 1").OrWhere("age", "=", Raw("2")).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereRaw1.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereRaw2(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "age" = $1 OR age = $2`
	result := Table("users").Where("age", "=", 1).OrWhereRaw("age = ?", 2).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereRaw2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereRaw3(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "age" = $1 OR "age" = (SELECT age FROM ag WHERE id = $2 OR id = $3 LIMIT 1)`
	result := Table("users").Where("age", "=", 1).OrWhere("age", "=", Raw("(SELECT age FROM ag WHERE id = ? OR id = ? LIMIT 1)", 2, 3)).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereRaw3.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereNull(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "country" IS NULL AND "city" IS NOT NULL`
	result := Table("users").WhereNull("country").WhereNotNull("city").Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereNull.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereBETWEEN(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "create_at" BETWEEN $1 AND $2 AND "create_at" NOT BETWEEN $3 AND $4`
	result := Table("users").
		WhereBetween("create_at", "2007-01-01", "2007-12-31").
		WhereNotBetween("create_at", "2007-02-01", "2007-02-31").
		Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereBETWEEN.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereInList(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "id" IN ( $1, $2, $3, $4, $5, $6 )`
	result := Table("users").WhereIn("id", List{1, 2, 3, 4, 5, 6}).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereInList.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereInSub1(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "id" IN ( SELECT "user_id" FROM "orders" WHERE "city" = $1 )`
	result := Table("users").WhereIn("id", func(builder *Builder) {
		builder.Select("user_id").From("orders").Where("city", "=", "Moscow")
	}).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereInSub1.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereInSub2(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "deleted" = $1 AND "id" IN ( SELECT "user_id" FROM "orders" WHERE "city" = $2 )`
	result := Table("users").Where("deleted", "=", "1").
		WhereIn("id", func(builder *Builder) {
			builder.Select("user_id").From("orders").Where("city", "=", "Moscow")
		}).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereInSub2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlWhereInSub3(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "deleted" = $1 AND "id" IN ( SELECT "user_id" FROM "orders" WHERE "city" = $2 )`
	subque := Table("orders").Where("city", "=", "Moscow").Select("user_id")
	result := Table("users").Where("deleted", "=", "1").WhereIn("id", subque).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlWhereInSub3.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlGroupBy(t *testing.T) {
	expect := `SELECT "country", "city", COUNT(*) as "count" FROM "users" WHERE "age" > $1 GROUP BY "country", "city"`
	result := Table("users").Where("age", ">", 31).GroupBy("country", "city").Select("country", "city").Count("*", "count").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlGroupBy.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlHavingBase(t *testing.T) {
	expect := `SELECT "country", COUNT(*) as "count" FROM "users" WHERE "age" > $1 GROUP BY "country" HAVING "count" > $2`
	result := Table("users").Where("age", ">", 31).GroupBy("country").Having("count", ">", 10).Select("country").Count("*", "count").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlHavingBase.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlHavingRaw(t *testing.T) {
	expect := `SELECT "country", COUNT(*) as "count" FROM "users" WHERE "age" > $1 GROUP BY "country" HAVING count > 10`
	result := Table("users").Where("age", ">", 31).GroupBy("country").HavingRaw("count > 10").Select("country").Count("*", "count").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlHavingRaw.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlHavingGroup(t *testing.T) {
	expect := `SELECT "country", COUNT(*) as "count" FROM "users" WHERE "age" > $1 GROUP BY "country" HAVING ( "count" > $2 AND "count" < $3 )`
	result := Table("users").Where("age", ">", 31).GroupBy("country").HavingGroup(func(builder *Builder) {
		builder.Having("count", ">", 10).Having("count", "<", 20)
	}).Select("country").Count("*", "count").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlHavingGroup.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlOrderBy1(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "city" = $1 ORDER BY "id" DESC`
	result := Table("users").Where("city", "=", "Moscow").OrderBy("id", "DESC").Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlOrderBy1.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlOrderBy2(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "city" = $1 ORDER BY "age" ASC, "name" DESC`
	result := Table("users").Where("city", "=", "Moscow").OrderBy("age", "ASC").OrderBy("name", "DESC").Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlOrderBy2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlLimit(t *testing.T) {
	expect := `SELECT * FROM "users" WHERE "city" = $1 ORDER BY "age" ASC LIMIT $2 OFFSET $3`
	result := Table("users").Where("city", "=", "Moscow").OrderBy("age", "ASC").Limit(10).Offset(50).Select("*").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlLimit.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlJoin(t *testing.T) {
	expect := `SELECT * FROM "users" as "us" INNER JOIN "info" as "inf" ON ( "us"."id" = "inf"."user_id" AND "us"."group" = $1 ) INNER JOIN "city" as "c" ON ( "c"."id" = "inf"."city_id" )`
	result := Table("users as us").Join("info as inf", func(joiner *Joiner) {
		joiner.On("us.id", "=", "inf.user_id")
		joiner.Where("us.group", "=", "admin")
	}).Join("city as c", func(joiner *Joiner) {
		joiner.On("c.id", "=", "inf.city_id")
	}).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlJoin.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlLeftJoin(t *testing.T) {
	expect := `SELECT * FROM "users" as "us" LEFT JOIN "orders" as "ord" ON ( "us"."id" = "ord"."user_id" ) WHERE "ord"."user_id" IS NOT NULL`
	result := Table("users as us").LeftJoin("orders as ord", func(joiner *Joiner) {
		joiner.On("us.id", "=", "ord.user_id")
	}).WhereNotNull("ord.user_id").Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlLeftJoin.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlDelete(t *testing.T) {
	expect := `DELETE FROM "users" WHERE "id" = $1`
	result := Table("users").Where("id", "=", 15).Delete().Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlDelete.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlDelete2(t *testing.T) {
	expect := `DELETE FROM "users" WHERE "id" = $1 RETURNING "id"`
	result := Table("users").Where("id", "=", 15).Delete().ReturnId().Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlDelete2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlUpdate(t *testing.T) {
	expect := `UPDATE "users" SET "city" = $1, "name" = $2 WHERE "id" = $3`
	result := Table("users").Where("id", "=", 15).Update(Data{"name": "Jack", "city": "Moscow"}).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlUpdate.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlUpdate2(t *testing.T) {
	expect := `UPDATE "users" SET "city" = $1, "name" = $2 WHERE "id" = $3 RETURNING "id"`
	result := Table("users").Where("id", "=", 15).Update(Data{"name": "Jack", "city": "Moscow"}).ReturnId().Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlUpdate2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlInsert1(t *testing.T) {
	expect := `INSERT INTO "users" ( "id", "name" ) VALUES ( $1, $2 )`
	result := Table("users").Insert(Data{"id": 1, "name": "Jack"}).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlInsert1.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlInsert2(t *testing.T) {
	expect := `INSERT INTO "users" ( "id", "name" ) VALUES ( $1, $2 ), ( $3, $4 )`
	result := Table("users").Insert(Data{"id": 1, "name": "Jack"}, Data{"id": 2, "name": "Mike"}).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlInsert2.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlInsert3(t *testing.T) {
	expect := `INSERT INTO "users" ( "id", "name" ) VALUES ( $1, $2 ), ( $3, $4 )`
	result := Table("users").Insert(Data{"id": 1, "name": "Jack"}).Insert(Data{"id": 2, "name": "Mike"}).Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlInsert3.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlInsert4(t *testing.T) {
	expect := `INSERT INTO "users" ( "id", "name" ) VALUES ( $1, $2 ), ( $3, $4 ) ON CONFLICT DO NOTHING`
	result := Table("users").Insert(Data{"id": 1, "name": "Jack"}).Insert(Data{"id": 2, "name": "Mike"}).OrIgnore().Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlInsert4.\nResult: %s\nExpect: %s", result, expect)
	}
}

func TestSqlInsert5(t *testing.T) {
	Driver("mysql")
	expect := "INSERT IGNORE INTO `users` ( `id`, `name` ) VALUES ( ?, ? ), ( ?, ? )"
	result := Table("users").Insert(Data{"id": 1, "name": "Jack"}).Insert(Data{"id": 2, "name": "Mike"}).OrIgnore().Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlInsert5.\nResult: %s\nExpect: %s", result, expect)
	}
	Driver("postgres")
}

func TestSqlInsert6(t *testing.T) {
	expect := `INSERT INTO "users" ( "id", "name" ) VALUES ( $1, $2 ) ON CONFLICT DO NOTHING RETURNING "id"`
	result := Table("users").Insert(Data{"id": 1, "name": "Jack"}).OrIgnore().ReturnId().Sql()
	if result != expect {
		t.Errorf("Expect result to equal in func TestSqlInsert6.\nResult: %s\nExpect: %s", result, expect)
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/temples/the-gila-valley-arizona#gila-valley-temple-lds-810267" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its">
  <search-meta>
      <uri-title its:translate="no">gila-valley-temple-lds-810267</uri-title>
      <source>gila-valley-temple-lds-810267</source>
      <publication-type its:translate="no">image</publication-type>
      <media-type its:translate="no">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-12-14">2012-12-14</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no">global-search</collection>
          <collection its:translate="no">media</collection>
          <collection its:translate="no">images</collection>
      </collections>
      <subjects>
          <subject>the gila valley arizona temple</subject>
          <subject>lds</subject>
          <subject>temple</subject>
          <subject>exterior</subject>
          <subject>daytime</subject>
          <subject>mountains</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/temples/the-gila-valley-arizona/gila-valley-temple-lds-810267-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/temples/the-gila-valley-arizona/gila-valley-temple-lds-810267-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>169 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/the-gila-valley-arizona/gila-valley-temple-lds-810267-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>190 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/the-gila-valley-arizona/gila-valley-temple-lds-810267-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>430 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/the-gila-valley-arizona/gila-valley-temple-lds-810267-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>885 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/the-gila-valley-arizona/gila-valley-temple-lds-810267-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
</ldswebml>


text:
var qs = require('querystring')
  , http = require('http')
  , url = require('url')

var concat = require('concat-stream')

var packagify = require('../packagify')
  , readmeify = require('../readmeify')
  , template = require('../template')
  , errors = require('./errors')

var package_template = template('package')

module.exports = serve_package

function serve_package(req, res, route, config) {
  var registry = url.parse(config.registry)
    , complete = 0

  var name = route.params.name

  if(route.params.scope) {
    name = route.params.scope + '/' + name
  }

  var endpoint = {
      hostname: registry.hostname
    , port: registry.port || 80
    , agent: false
  }

  var dependents_path = '/-/_view/dependedUpon/'
    , dependents_query
    , dependents = {}
    , package_data

  dependents_query = '?' + qs.stringify({
      startkey: '["' + name + '"]'
    , endkey: '["' + name + '", {}]'
    , group_level: 2
  })

  endpoint.path = dependents_path + dependents_query

  http.get(endpoint, parse_dependents).on('error', function() {
    errors.server_error(req, res)
  })

  endpoint.path = '/' + name.replace('/', '%2f')

  http.get(endpoint, parse_response).on('error', function() {
    errors.server_error(req, res)
  })

  function parse_dependents(response) {
    if(response.statusCode !== 200) return ++complete && next()

    response.pipe(concat(parse_dependents_data))

    function parse_dependents_data(data) {
      var dep_data = JSON.parse('' + data)
        , total = dep_data.rows.length

      dependents.list = []

      for(var i = 0; i < total && i < 10; ++i) {
        dependents.list.push(dep_data.rows[i].key[1])
      }

      dependents.remain = Math.max(0, total - 10)

      ++complete
      next()
    }
  }

  function parse_response(response) {
    if(response.statusCode === 404) return errors.not_found(req, res)

    response.pipe(concat(parse_package))

    function parse_package(data) {
      try{
        package_data = JSON.parse('' + data)
      } catch(e) {
        return errors.server_error(req, res)
      }

      package_data = packagify(package_data)
      package_data.dependents = dependents
      package_data.config = config
      package_data.base = route.params.scope ? '../../' : '../'

      readmeify(package_data.readme, to_next)

      function to_next(err, html) {
        if(err) return errors.server_error(req, res)
        package_data.readme = html

        ++complete
        next()
      }
    }
  }

  function next() {
    if(complete < 2) return

    res.writeHead(200, {'content-type': 'text/html; charset=utf-8'})
    res.end(package_template(package_data))
  }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Description of {{ model_name }}
 *
 * @author No-CMS Module Generator
 */
class {{ model_name }}  extends Grocery_crud_automatic_model{

    public function __construct(){
        parent::__construct();
    }
}


text:
require_relative '../../automated_init'

context "Handles" do
  context "MessageData" do
    context "Handler Implements Message Handler for MessageData's Type" do
      message_data = Controls::MessageData::Read.example(type: 'SomeMessage')
      handles = Controls::Handler::Example.handles? message_data

      test "Handles" do
        assert(handles)
      end
    end

    context "Handler Does not Implement Message Handler for MessageData's Type" do
      message_data = Controls::MessageData::Read.example(type: SecureRandom.hex)
      handles = Controls::Handler::Example.handles? message_data

      test "Does not Handle" do
        refute(handles)
      end
    end
  end
end


text:
#pragma once
#include "aNode.h"
#include "aBinarySearchTree.h"
#include <iostream>

/*
aAVLTree definition. implementation is below because it needs to reside within the h file

template <typename Type>
class aAVLTree : public aBinarySearchTree<Type>
{
  //NOTE: root is defined in base class as tNode<Type>*, but in this tree, we create tNodeAVL<Type> objects in it (polymorphism)

  tNode<Type>* LeftRotateS(tNode<Type>* node);
  tNode<Type>* RightRotateS(tNode<Type>* node);
  tNode<Type>* LeftRotateD(tNode<Type>* node);
  tNode<Type>* RightRotateD(tNode<Type>* node);

  tNode<Type>* rebalance(tNode<Type>* node);
  tNode<Type>* add_element(tNode<Type>* node, const Type& element);
  void copy_tree(const tNode<Type> *root_source);

  INHERITED:
  tNode<Type> *root;

  void pre_order(const tNode<Type>* node) const;
  void in_order(const tNode<Type>* node) const;
  void post_order(const tNode<Type>* node) const;

  bool element_exists(const tNode<Type> *node, const Type& element) const;
  unsigned int count_nodes(const tNode<Type> *node) const;

  void delete_tree(const tNode<Type> *node);
  void output(std::ostream& out, const tNode<Type> *node) const;

  INHERITED AND OVERLOADED:
  void copy_tree(tNode<Type> *root_dest, const tNode<Type> *root_source); //we don't want to use this, we defined or own
  tNode<Type>* delete_element(tNode<Type>* node, const Type& element, bool& found); //we also want to rebalance

public:
  aAVLTree() : aBinarySearchTree<Type>();
  aAVLTree(const aAVLTree<Type>& rhs);
  aAVLTree<Type>& operator=(const aAVLTree<Type>& rhs);

  void Add(const Type& element);
  bool Delete(const Type& element);

  INHERITED:
  ~aBinarySearchTree();
  unsigned int Total_Nodes() const;
  bool Exists(const Type& element) const;

  void PreOrder() const;
  void InOrder() const;
  void PostOrder() const;

  friend std::ostream& operator<<(std::ostream& out, const aBinarySearchTree<Type>& rhs);
};

*/

template <typename Type>
class aAVLTree : public aBinarySearchTree<Type>
{
  static void copy_tree(tNode<Type> *root_dest, const tNode<Type> *root_source);

  tNode<Type>* LeftRotateS(tNode<Type>* node)
  {
    tNode<Type>* temp;
    temp = node->right;
    node->right = temp->left;
    temp->left = node;
    ((tNodeAVL<Type>*)node)->calculate_balance();
    ((tNodeAVL<Type>*)temp)->calculate_balance();
    node = temp;
    return node;
  }

  tNode<Type>* RightRotateS(tNode<Type>* node)
  {
    tNode<Type>* temp;
    temp = node->left;
    node->left = temp->right;
    temp->right = node;
    ((tNodeAVL<Type>*)node)->calculate_balance();
    ((tNodeAVL<Type>*)temp)->calculate_balance();
    node = temp;
    return node;
  }

  tNode<Type>* LeftRotateD(tNode<Type>* node)
  {
    node->right = RightRotateS(node->right);
    node = LeftRotateS(node);
    return node;
  }

  tNode<Type>* RightRotateD(tNode<Type>* node)
  {
    node->left = LeftRotateS(node->left);
    node = RightRotateS(node);
    return node;
  }

  tNode<Type>* rebalance(tNode<Type>* node)
  {
    tNode<Type>* temp;
    ((tNodeAVL<Type>*)node)->calculate_balance();
    if(((tNodeAVL<Type>*)node)->balance == -2)
    {
      temp = node->left;
      if (((tNodeAVL<Type>*)temp)->balance == 1)
        node = RightRotateD(node);
      else
        node = RightRotateS(node);
    }
    else
    if(((tNodeAVL<Type>*)node)->balance == 2)
    {
      temp = node->right;
      if (((tNodeAVL<Type>*)temp)->balance == -1)
        node = LeftRotateD(node);
      else
        node = LeftRotateS(node);
    }
    return node;
  }

  tNode<Type>* delete_element(tNode<Type>* node, const Type& element, bool& found)
  {
    if(node == NULL)
      return NULL;

    if(element < node->data)
    {
      node->left = delete_element(node->left, element, found);
      node = rebalance(node);
    }
    else
    if(element > node->data)
    {
      node->right = delete_element(node->right, element, found);
      node = rebalance(node);
    }
    else
    {
      if(node->left == NULL && node->right == NULL)
      {
        delete node;
        found = true;
        node = NULL;
      }

      else
      if(node->left == NULL)
      {
        tNode<Type> *temp = node;
        node = node->right;
        delete temp;
        found = true;
      }

      else
      if(node->right == NULL)
      {
        tNode<Type> *temp = node;
        node = node->left;
        delete temp;
        found = true;
      }
      else
      {
        tNode<Type> *temp = node->right;
        while(temp->left)
          temp = temp->left;

        node->data = temp->data;  //it's easier to interchange elements in between than to change children, etc
        node->right = delete_element(node->right, temp->data, found);
      }
    }

    return node; // parent node can update reference
  }

  tNode<Type>* add_element(tNode<Type>* node, const Type& element)
  {
    if(!node)
    {
      tNode<Type>* e = new tNodeAVL<Type>(element);
      if(!e)
        throw "allocation problem";
      return e;
    }

    if(element < node->data)
      node->left = add_element(node->left, element);
    else
    if(element > node->data)
      node->right = add_element(node->right, element);
    else
      std::cout<<"Informatia deja exista!"<<std::endl;

    node = rebalance(node);
    return node;
  }

  void copy_tree(const tNode<Type> *root_source)
  {
    if(root_source == NULL)
      return;

    Add(root_source->data);
    copy_tree(root_source->left);
    copy_tree(root_source->right);
  }

public:
  aAVLTree() : aBinarySearchTree<Type>()
  {
  }

  aAVLTree(const aAVLTree<Type>& rhs)
  {
    this->root = NULL;
    copy_tree(rhs.root);
  }

  aAVLTree<Type>& operator=(const aAVLTree<Type>& rhs)
  {
    if(this != &rhs)
    {
      delete_tree(this->root);
      this->root = NULL;
      if(rhs.root)
        copy_tree(rhs.root);
    }
    return *this;
  }

  void Add(const Type& element)
  {
    this->root = add_element(this->root, element);
  }

  bool Delete(const Type& element)
  {
    if(this->root == NULL)
      return false;

    bool found;
    found = false;

    this->root = delete_element(this->root, element, found);
    return found;
  }
};


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="cover">

        <roleset framnet="-" id="cover.01" name="has responsibility for, handles" vncls="-">
            <roles>
                <role descr="coverer" f="" n="0">

                </role>
                <role descr="thing covered" f="" n="1">

                </role>
                <role descr="instrument, covered by" f="" n="2">

                </role>

                <note/>
            </roles>

            <example name="agentive subject" src="" type="">
                <text>Market-makers-1 are shopping *trace*-1 to cover book requirements in
                    FTSE 100 shares.
                </text>
                <arg f="" n="0">*trace*-1</arg>
                <rel f="">cover</rel>
                <arg f="" n="1">book requirements in FTSE 100 shares.</arg>

                <note/>
            </example>

            <example name="instrumental subject" src="" type="">
                <text>The training wage covers only workers who are 16 to 19 years old.</text>
                <arg f="" n="2">The training wage</arg>
                <rel f="">covers</rel>
                <arg f="adv" n="m">only</arg>
                <arg f="" n="1">workers who are 16 to 19 years old</arg>

                <note/>
            </example>

            <example name="passive" src="" type="">
                <text>At least costs-1 should be covered *trace*-1.</text>
                <arg f="adv" n="m">At least</arg>

                <arg f="mod" n="m">should</arg>
                <rel f="">covered</rel>

                <arg f="" n="1">*trace*-1</arg>
                <note/>
            </example>

            <note>VN updated by Julia. No Vncls, because of physicality constraints on fill-9.8 and contiguous_location-47.8, but  this can be construed as a metaphorical extension of those classes.</note>
        </roleset>

        <roleset framnet="Filling , Adorning , Eclipse" id="cover.02" name="smear, put over" vncls="9.8  47.8">
            <roles>
                <role descr="causer of covering" f="" n="0">
                    <vnrole vncls="9.8" vntheta="agent"/>
                </role>
                <role descr="thing covered" f="" n="1">
                    <vnrole vncls="9.8" vntheta="destination"/>
                    <vnrole vncls="47.8" vntheta="theme2"/>
                </role>
                <role descr="covered with" f="" n="2">
                    <vnrole vncls="9.8" vntheta="theme"/>
                    <vnrole vncls="47.8" vntheta="theme1"/>
                </role>

                <note>Please note the similarity between the two rolesets. Arg2 may occur as subject in either sense, but potentially more often in cover.01. Use cover.02 for physical covering.</note>
            </roles>

            <example name="lunchtime" src="" type="">
                <text>John covered the bread with peanut butter.</text>
                <arg f="" n="0">John</arg>
                <rel f="">covered</rel>
                <arg f="" n="1">the bread</arg>
                <arg f="" n="2">with peanut butter</arg>

                <note/>
            </example>

            <example name="Arg2 as active subject" src="internet" type="-">
                <inflection aspect="ns" form="participle" person="third" tense="past" voice="active"/>
                <text>The substance covered the ground completely .</text>

                <arg f="" n="2">The substance</arg>
                <rel f="">covered</rel>
                <arg f="" n="1">the ground</arg>
                <arg f="ext" n="m">completely</arg>

                <note/>
            </example>

            <note>Updated by Julia. Member of VNcls fill-9.8 and contiguous_location-47.8.</note>
        </roleset>

        <roleset framnet="Topic" id="cover.03" name="broadcast" vncls="-">
            <roles>
                <role descr="news organization, media" f="" n="0"/>
                <role descr="event, thing covered" f="" n="1"/>

                <note/>
            </roles>

            <example name="broadcast news" src="" type="">
                <text>Give television-1 a chance *trace*-1 to cover live any breaking of the law...</text>
                <arg f="" n="0">*trace*</arg>
                <rel f="">cover</rel>
                <arg f="mnr" n="m">live</arg>
                <arg f="" n="1">any breaking of the law</arg>

                <note/>
            </example>

            <note/>
        </roleset>

        <note>Frames file for 'cover' based on survey of initial sentences of big
            corpus.
        </note>
    </predicate>

    <predicate lemma="cover_up">

        <roleset framnet="-" id="cover.04" name="obscure" vncls="9.8">
            <roles>
                <role descr="coverer" f="" n="0">
                    <vnrole vncls="9.8" vntheta="agent"/>
                </role>
                <role descr="thing covered" f="" n="1">
                    <vnrole vncls="9.8" vntheta="theme"/>
                </role>

                <note/>
            </roles>

            <example name="CYA" src="" type="">
                <text>[Its officials and utility subsidiaries]-1 tried *trace-1* to cover up their
                    accounting for spare parts *trace-2* to evade federal income taxes.
                </text>
                <arg f="" n="0">*trace-1*</arg>
                <rel f="">cover up</rel>
                <arg f="" n="1">their accounting for spare parts</arg>
                <arg f="prp" n="m">*trace-2* to evade federal income taxes</arg>

                <note/>
            </example>

            <note/>
        </roleset>

        <note/>
    </predicate>

    <predicate lemma="cover_over">

        <roleset framnet="-" id="cover.05" name="cover completely" vncls="-">
            <roles>
                <role descr="agent" f="" n="0"/>

                <role descr="thing being covered" f="" n="1"/>
                <role descr="the cover itself" f="" n="2"/>

                <note>Note that in this usage, 'over' is not construed as the head of a PP because what would then be the PP would not end up being the location of the covering, but rather the thing covered.</note>
            </roles>

            <example name="all args" src="Brown" type="-">
                <inflection aspect="ns" form="participle" person="third" tense="past" voice="active"/>
                <text>They -1 wet the lightweight cloth in a basin and *trace*-1 covered it over with clay that Argiento brought from the bank of the Tiber</text>

                <arg f="" n="0">*trace*-1</arg>
                <rel f="">[covered] [over]</rel>
                <arg f="" n="1">it</arg>
                <arg f="" n="2">with clay that Argiento brought from the bank of the Tiber.</arg>

                <note/>
            </example>

            <note>Added by Julia based on Brown corpus. Comparison to close_over. No Vncls.</note>
        </roleset>

        <note/>
    </predicate>

    <note/>
</frameset>


text:
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.gui;

import java.awt.Component;
import java.awt.Container;
import java.awt.Desktop;
import java.io.File;
import java.net.URL;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.filechooser.FileFilter;

import org.bridgedb.bio.Organism;
import org.pathvisio.core.ApplicationEvent;
import org.pathvisio.core.Engine;
import org.pathvisio.core.Engine.ApplicationEventListener;
import org.pathvisio.core.Globals;
import org.pathvisio.core.data.GdbManager;
import org.pathvisio.core.debug.Logger;
import org.pathvisio.core.model.ConverterException;
import org.pathvisio.core.model.GpmlFormat;
import org.pathvisio.core.model.Pathway;
import org.pathvisio.core.model.Pathway.StatusFlagEvent;
import org.pathvisio.core.model.PathwayIO;
import org.pathvisio.core.preferences.GlobalPreference;
import org.pathvisio.core.preferences.Preference;
import org.pathvisio.core.preferences.PreferenceManager;
import org.pathvisio.core.util.ProgressKeeper;
import org.pathvisio.core.util.Utils;
import org.pathvisio.core.view.VPathwayWrapper;
import org.pathvisio.gui.dialogs.NewPathwayDialog;
import org.pathvisio.gui.dialogs.OkCancelDialog;
import org.pathvisio.gui.dialogs.PopupDialogHandler;
import org.pathvisio.gui.view.VPathwaySwing;

/**
 * SwingEngine ties together a number of global objects needed both in the
 * WikiPathways applet and in the Standalone App, but not in command-line tools.
 *
 * It keeps the main panel, the main frame and has
 * helper functions for opening, closing, importing and exporting Pathways.
 */
public class SwingEngine implements ApplicationEventListener, Pathway.StatusFlagListener, HyperlinkListener
{
	private MainPanel mainPanel;

	private CommonActions actions;
	private JFrame frame; // may be null (for applet...)

	private Engine engine;
	private GdbManager gdbManager = null;
	//private final Compat compat;

	public Engine getEngine() { return engine; }

	public SwingEngine(Engine engine)
	{
		this.engine = engine;
		gdbManager = new GdbManager();
		actions = new CommonActions(this);
		engine.addApplicationEventListener(this);
		//compat = new Compat(this);
		//engine.addApplicationEventListener(compat);
	}

	public GdbManager getGdbManager()
	{
		return gdbManager;
	}

	public CommonActions getActions() {
		return actions;
	}

	public MainPanel getApplicationPanel() {
		return getApplicationPanel(false);
	}

	public MainPanel getApplicationPanel(boolean forceNew) {
		if(forceNew || !hasApplicationPanel()) {
			mainPanel = new MainPanel(this);
		}
		return mainPanel;
	}

	public void setApplicationPanel(MainPanel mp) {
		if(mainPanel != null) {
			Container parent = mainPanel.getParent();
			if(parent != null) parent.remove(mainPanel);
		}
		mainPanel = mp;
	}

	public boolean hasApplicationPanel() {
		return mainPanel != null;
	}

	public void handleConverterException(String message, Component c, Throwable e) {
		if (e.getMessage() != null &&
				e.getMessage().contains("Cannot find the declaration of element 'Pathway'"))
		{
			JOptionPane.showMessageDialog(c,
					Utils.formatExceptionMsg(message) + "\n\n" +
					"The most likely cause for this error is that you are trying to open an old Gpml file. " +
					"Please note that the Gpml format has changed as of March 2007. " +
					"The standard pathway set can be re-downloaded from http://pathvisio.org " +
					"Non-standard pathways need to be recreated or upgraded. " +
					"Please contact the authors at " + Globals.DEVELOPER_EMAIL + " if you need help with this.\n"
					, "Error", JOptionPane.ERROR_MESSAGE);
			Logger.log.error("Converter exception", e);
		}
		else
		{
			JOptionPane.showMessageDialog(c,
					Utils.formatExceptionMsg(message) + "\nSee error log for details\n" + e.getClass(), "Error", JOptionPane.ERROR_MESSAGE);
			Logger.log.error("Converter exception", e);
		}
	}

	public void handleMalformedURLException(String message, Component c, Throwable e) {
		if(e.getMessage() != null && e.getMessage().contains("no protocol:")) {
			JOptionPane.showMessageDialog(c,
					Utils.formatExceptionMsg(message) + "\n\n" +
					"Please correct the specified hyperlink for this Label in the \"properties pane\" on the right.\n" +
					"(http://www.example.com)\n\n" +
					"Please contact the authors at " + Globals.DEVELOPER_EMAIL + " if you need help with this.\n"
					, "Error", JOptionPane.ERROR_MESSAGE);
			Logger.log.error("MalformedURLException", e);
		} else {
			JOptionPane.showMessageDialog(c, Utils.formatExceptionMsg(message) + "\nSee error log for details\n" + e.getClass(), "Error", JOptionPane.ERROR_MESSAGE);
			Logger.log.error("MalformedURLException", e);
		}
	}

	public VPathwayWrapper createWrapper() {
		 return new VPathwaySwing(getApplicationPanel().getScrollPane());
	}

	//TODO: deprecate
	public boolean processTask(ProgressKeeper pk, ProgressDialog d, SwingWorker<Boolean, Boolean> sw) {
		sw.execute();
		d.setVisible(true);
		try {
			return sw.get();
		} catch (ExecutionException e)
		{
			handleConverterException("Exception during conversion", null, e.getCause());
			return false;
		} catch (InterruptedException e) {
			handleConverterException("Conversion was cancelled or interrupted", null, e);
			return false;
		}
	}

	public boolean openPathway(final URL url) {
		final ProgressKeeper pk = new ProgressKeeper();
		final ProgressDialog d = new ProgressDialog(JOptionPane.getFrameForComponent(getApplicationPanel()),
				"", pk, false, true);

		SwingWorker<Boolean, Boolean> sw = new SwingWorker<Boolean, Boolean>() {
			protected Boolean doInBackground() {
				pk.setTaskName("Opening pathway");
				try {
					engine.setWrapper (createWrapper());
					engine.openPathway(url);
					return true;
				} catch(ConverterException e) {
					handleConverterException(e.getMessage(), null, e);
					return false;
				} finally {
					pk.finished();
				}
			}
		};

		return processTask(pk, d, sw);
	}

	public boolean openPathway(final File f)
	{
		final ProgressKeeper pk = new ProgressKeeper();
		final ProgressDialog d = new ProgressDialog(JOptionPane.getFrameForComponent(getApplicationPanel()),
				"", pk, false, true);

		engine.setWrapper (createWrapper());
		SwingWorker<Boolean, Boolean> sw = new SwingWorker<Boolean, Boolean>() {
			protected Boolean doInBackground() {
				pk.setTaskName("Opening pathway");
				try {
					engine.openPathway(f);
					return true;
				} catch(ConverterException e) {
					handleConverterException(e.getMessage(), null, e);
					return false;
				} finally {
					pk.finished();
				}
			}
		};

		return processTask(pk, d, sw);
	}

	public boolean importPathway(final File f) {
		final ProgressKeeper pk = new ProgressKeeper();
		final ProgressDialog d = new ProgressDialog(JOptionPane.getFrameForComponent(getApplicationPanel()),
				"", pk, false, true);

		SwingWorker<Boolean, Boolean> sw = new SwingWorker<Boolean,Boolean>() {
			protected Boolean doInBackground() {
				pk.setTaskName("Importing pathway");
				try {
					boolean editMode = engine.hasVPathway() ? engine.getActiveVPathway().isEditMode() : true;
					engine.setWrapper (createWrapper());
					engine.importPathway(f);
					engine.getActiveVPathway().setEditMode(editMode);
					return true;
				} catch(ConverterException e) {
					handleConverterException(e.getMessage(), frame, e);
					return false;
				} finally {
					pk.finished();
				}
			}
		};

	return processTask(pk, d, sw);

	}

	public void newPathway() {
		engine.setWrapper (createWrapper());
		engine.newPathway();
		NewPathwayDialog dlg = new NewPathwayDialog(this, "Pathway attributes");
		dlg.setVisible(true);
	}

	public boolean exportPathway()
	{
		PathwayChooser pc = new PathwayChooser("Export", JFileChooser.SAVE_DIALOG, GlobalPreference.DIR_LAST_USED_EXPORT, engine.getPathwayExporters());
		int status = pc.show();

		if(status == JFileChooser.APPROVE_OPTION)
		{
			File f = pc.getSelectedFile();

			PathwayFileFilter ff = (PathwayFileFilter)pc.getFileFilter();
			if(!f.toString().toUpperCase().endsWith("." + ff.getDefaultExtension().toUpperCase())) {
				f = new File(f.toString() + "." + ff.getDefaultExtension());
			}
//			return exportPathway(f);
			return exportPathway(f,ff.name);

		}
		return false;
	}

	/**
	 * A wrapper around JFileChooser that has the right defaults and File Filters.
	 */
	private class PathwayChooser
	{
		private final JFileChooser jfc;
		private final String taskName;
		private final Preference dirPreference;

		public PathwayChooser(String taskName, int dialogType, Preference dirPreference, Set<? extends PathwayIO> set)
		{
			jfc = new JFileChooser();
			this.taskName = taskName;
			this.dirPreference = dirPreference;
			createFileFilters(set);
			jfc.setDialogTitle(taskName + " pathway");
			jfc.setDialogType(dialogType);
			jfc.setCurrentDirectory(PreferenceManager.getCurrent().getFile(dirPreference));
		}

		/** create a file chooser populated with file filters for the given pathway importers / exporters */
		private void createFileFilters(Set<? extends PathwayIO> set)
		{
			jfc.setAcceptAllFileFilterUsed(false);

			SortedSet<PathwayIO> exporters = new TreeSet<PathwayIO>(
					new Comparator<PathwayIO>() {
						public int compare(PathwayIO o1, PathwayIO o2) {
							return o1.getName().compareTo(o2.getName());
						}
					}
			);
			exporters.addAll(set);

			FileFilter selectedFilter = null;
			for(PathwayIO exp : exporters) {
				FileFilter ff = new PathwayFileFilter(exp);
				jfc.addChoosableFileFilter(ff);
				if(exp instanceof GpmlFormat) {
					selectedFilter = ff;
				}
			}
			if(selectedFilter != null) jfc.setFileFilter(selectedFilter);
		}

		public FileFilter getFileFilter()
		{
			return jfc.getFileFilter();
		}

		public int show ()
		{
			int status = jfc.showDialog(getApplicationPanel(), taskName);
			if(status == JFileChooser.APPROVE_OPTION)
			{
				PreferenceManager.getCurrent().setFile(dirPreference, jfc.getCurrentDirectory());
			}
			return status;
		}

		public File getSelectedFile()
		{
			return jfc.getSelectedFile();
		}
	}

	public boolean exportPathway(final File f, final String exporterName) {
		if(mayOverwrite(f)) {
			final ProgressKeeper pk = new ProgressKeeper();
			final ProgressDialog d = new ProgressDialog(JOptionPane.getFrameForComponent(getApplicationPanel()),
					"", pk, false, true);

			// create a clone so we can safely act on it in a worker thread.
			final Pathway clone = engine.getActivePathway().clone();

			SwingWorker<Boolean, Boolean> sw = new SwingWorker<Boolean, Boolean>()
			{
				private List<String> warnings;

				@Override
				protected Boolean doInBackground() {
					try {
						pk.setTaskName("Exporting pathway");
						warnings = engine.exportPathway(f, clone,exporterName);
						return true;
					} catch(Exception e) {
						handleConverterException(e.getMessage(), frame, e);
						return false;
					} finally {
						pk.finished();
					}
				}

				@Override
				public void done()
				{
					if (warnings != null && warnings.size() > 0)
					{
						OkCancelDialog dlg = new OkCancelDialog(frame, "Conversion warnings", getFrame(), true);
						JTextArea area = new JTextArea(60, 30);
						for (String w : warnings)
							area.append(w + "\n");
						dlg.setDialogComponent(area);
						dlg.pack();
						dlg.setVisible(true);
					}
				}
			};

			return processTask(pk, d, sw);
		}
		return false;
	}

	public boolean exportPathway(final File f) {
		if(mayOverwrite(f)) {
			final ProgressKeeper pk = new ProgressKeeper();
			final ProgressDialog d = new ProgressDialog(JOptionPane.getFrameForComponent(getApplicationPanel()),
					"", pk, false, true);

			// create a clone so we can safely act on it in a worker thread.
			final Pathway clone = engine.getActivePathway().clone();

			SwingWorker<Boolean, Boolean> sw = new SwingWorker<Boolean, Boolean>()
			{
				private List<String> warnings;

				@Override
				protected Boolean doInBackground() {
					try {
						pk.setTaskName("Exporting pathway");
						warnings = engine.exportPathway(f, clone);
						return true;
					} catch(ConverterException e) {
						handleConverterException(e.getMessage(), frame, e);
						return false;
					} finally {
						pk.finished();
					}
				}

				@Override
				public void done()
				{
					if (warnings != null && warnings.size() > 0)
					{
						OkCancelDialog dlg = new OkCancelDialog(frame, "Conversion warnings", getFrame(), true);
						JTextArea area = new JTextArea(60, 30);
						for (String w : warnings)
							area.append(w + "\n");
						dlg.setDialogComponent(area);
						dlg.pack();
						dlg.setVisible(true);
					}
				}
			};

			return processTask(pk, d, sw);
		}
		return false;
	}

	public boolean importPathway()
	{
		PathwayChooser pc = new PathwayChooser("Import", JFileChooser.OPEN_DIALOG, GlobalPreference.DIR_LAST_USED_IMPORT, engine.getPathwayImporters());
		int status = pc.show();

		if(status == JFileChooser.APPROVE_OPTION)
		{
			File f = pc.getSelectedFile();
			return importPathway(f);
		}
		return false;
	}

	private final Set<PathwayIO> GPML_FORMAT_ONLY = Utils.setOf((PathwayIO)new GpmlFormat());

	/**
	 * Opens a file chooser dialog, and opens the chosen pathway.
	 * @return true if a pathway was openend, false if the operation was
	 * cancelled
	 */
	public boolean openPathway()
	{
		PathwayChooser pc = new PathwayChooser("Open", JFileChooser.OPEN_DIALOG, GlobalPreference.DIR_LAST_USED_OPEN, GPML_FORMAT_ONLY);
		int status = pc.show ();

		if(status == JFileChooser.APPROVE_OPTION)
		{
			File f = pc.getSelectedFile();
			return openPathway(f);
		}
		return false;
	}

	public boolean mayOverwrite(File f) {
		boolean allow = true;
		if(f.exists()) {
			int status = JOptionPane.showConfirmDialog(frame, "File " + f.getName() + " already exists, overwrite?",
					"File already exists", JOptionPane.YES_NO_OPTION);
			allow = status == JOptionPane.YES_OPTION;
		}
		return allow;
	}

	public boolean savePathwayAs()
	{
		PathwayChooser pc = new PathwayChooser("Save", JFileChooser.SAVE_DIALOG, GlobalPreference.DIR_LAST_USED_SAVE, GPML_FORMAT_ONLY);
		int status = pc.show ();

		if(status == JFileChooser.APPROVE_OPTION)
		{
			File toFile = pc.getSelectedFile();
			String fn = toFile.toString();
			if(!fn.toLowerCase().endsWith(Engine.PATHWAY_FILE_EXTENSION)) {
				toFile = new File(fn + "." + Engine.PATHWAY_FILE_EXTENSION);
			}
			try {
				if(mayOverwrite(toFile)) {
					engine.savePathway(toFile);
					return true;
				}
			} catch(ConverterException e) {
				handleConverterException(e.getMessage(), null, e);
			}
		}
		return false;
	}

	public boolean savePathway()
	{
		Pathway pathway = engine.getActivePathway();

		boolean result = true;

        // Overwrite the existing xml file.
		// If the target file is read-only, let the user select a new pathway
		if (pathway.getSourceFile() != null && pathway.getSourceFile().canWrite())
		{
			try {
				engine.savePathway(pathway.getSourceFile());
			} catch (ConverterException e) {
				handleConverterException(e.getMessage(), null, e);
			}
		}
		else {
			result = savePathwayAs();
		}

		return result;
	}

	/**
	 * Call this when the user is about to perform an
	 * action that could lead to discarding the current pathway.
	 * (For example when creating a new pathway)
	 *
	 * Checks if there are any unsaved changes, and
	 * asks the user if they want to save those changes.
	 *
	 * @return true if the user allows discarding the pathway, possibly after saving.
	 */
	public boolean canDiscardPathway()
	{
		Pathway pathway = engine.getActivePathway();
        // checking not necessary if there is no pathway or if pathway is not changed.

		if (pathway == null || !pathway.hasChanged()) return true;
		int result = JOptionPane.showConfirmDialog
			(frame, "Save changes?",
					"Your pathway has changed. Do you want to save?",
					JOptionPane.YES_NO_CANCEL_OPTION,
					JOptionPane.QUESTION_MESSAGE);
		if (result == JOptionPane.CANCEL_OPTION) // cancel
		{
			return false;
		}
		else if (result == JOptionPane.YES_OPTION) // yes
		{
			// return false if save is cancelled.
			return (savePathway());
		}
		// yes or no
		return true;
	}

	public void applicationEvent(ApplicationEvent e)
	{
		switch (e.getType()) {
		case PATHWAY_OPENED:
		case PATHWAY_NEW:
			updateTitle();
			engine.getActivePathway().addStatusFlagListener(SwingEngine.this);
			break;
		}
	}

	public void updateTitle()
	{
		if (frame != null)
		{
			if (engine.getActivePathway() == null)
			{
				frame.setTitle(engine.getApplicationName());
			}
			else
			{
				boolean changeStatus = engine.getActivePathway().hasChanged();
				// get filename, or (New Pathway) if current pathway hasn't been opened yet
				String fname = (engine.getActivePathway().getSourceFile() == null) ? "(New Pathway)" :
					engine.getActivePathway().getSourceFile().getName();
				frame.setTitle(
					(changeStatus ? "*" : "") + fname + " - " +
					engine.getApplicationName()
					);
			}
		}
	}

	public void statusFlagChanged(StatusFlagEvent e)
	{
		updateTitle();
	}

	public void setFrame(JFrame frame)
	{
		this.frame = frame;
	}

	public JFrame getFrame()
	{
		return frame;
	}

	private Browser browser = null;

	/**
	 * Set the browser launcher that will be used to open urls in the
	 * system's default web browser.
	 */
	public void setUrlBrowser(Browser b) {
		this.browser = b;
	}

	/**
	 * Opens an URL in the system's default browser if a browser is set
	 * @see #setUrlBrowser
	 * @throws UnsupportedOperationException when there is no browser set.
	 */
	public void openUrl(URL url) throws UnsupportedOperationException {
		if(browser != null) browser.openUrl(url);
	}

	/**
	 * Simple interface to allow different browser launcher implementations.
	 * Note: Java 1.6 provides an easy method to open an url in the default system browser
	 * using {@link Desktop#browse(java.net.URI)}, we should use this in the future.
	 * @author thomas
	 */
	public interface Browser {
		public void openUrl(URL url);
	}

	private boolean disposed = false;
	/**
	 * free all resources (such as listeners) held by this class.
	 * Owners of this class must explicitly dispose of it to clean up.
	 */
	public void dispose()
	{
		assert (!disposed);
		engine.removeApplicationEventListener(this);
		//engine.removeApplicationEventListener(compat);
		disposed = true;
	}

	/**
	 * Returns the organism set in the active pathway.
	 * May return null if there is no current organism set
	 */
	public Organism getCurrentOrganism()
	{
		String organism = getEngine().getActivePathway().getMappInfo().getOrganism();
		return Organism.fromLatinName(organism);
	}

	public void hyperlinkUpdate(HyperlinkEvent e)
	{
		if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
			try {
				openUrl(e.getURL());
			} catch(UnsupportedOperationException ex) {
				Logger.log.error("Unable to open URL", ex);
				JOptionPane.showMessageDialog(
						mainPanel,
						"No browser launcher specified",
						"Unable to open link",
						JOptionPane.ERROR_MESSAGE
				);
			}
		}
		else
		{
			//TODO: show URL in status bar when mousing over
		}
	}

	private PopupDialogHandler popupDlgHandler = new PopupDialogHandler(this);

	public PopupDialogHandler getPopupDialogHandler()
	{
		return popupDlgHandler;
	}
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI.Windows.Components;
#if UNITY_PS4
using UnityEngine.PS4;
#endif

namespace UnityEngine.UI.Windows.Movies {

	#if UNITY_PS4
	[System.Serializable]
	public class MoviePS4Module : MovieModuleBase {

		public class Item {

			public Material material;
			public PS4VideoPlayer player;

			public void Update() {

				this.player.Update();

				/*int cropleft, cropright, croptop, cropbottom, width, height;
				this.player.GetVideoCropValues(out cropleft, out cropright, out croptop, out cropbottom, out width, out height);

				float scalex = 1.0f;
				float scaley = 1.0f;
				float offx = 0.0f;
				float offy = 0.0f;
				if ((width > 0) && (height > 0)) {

					int fullwidth = width + cropleft + cropright;
					scalex = (float)width / (float)fullwidth;
					offx = (float)cropleft / (float)fullwidth;
					int fullheight = height + croptop + cropbottom;
					scaley = (float)height / (float)fullheight;
					offy = (float)croptop /(float)fullheight;

				}*/

			}

		};

		private Dictionary<string, Item> playingInstances = new Dictionary<string, Item>();

		public override bool IsMaterialLoadingType() {

			return true;

		}

		protected override void OnInit() {

			base.OnInit();

		}

		protected override System.Collections.Generic.IEnumerator<byte> LoadTexture_YIELD(ResourceAsyncOperation asyncOperation, IImageComponent component, ResourceBase resource) {

			var filePath = resource.GetStreamPath();

			//Debug.Log("LOADING: " + filePath);

			Item item = null;
			var instance = this.FindInstance(resource);
			if (instance != null) {

				item = instance;

			} else {

				item = this.CreatePlayerInstance();
				this.playingInstances.Add(filePath, item);

			}

			//Debug.Log ("DONE: " + item.material);
			asyncOperation.SetValues(isDone: true, progress: 1f, asset: item.material);

			yield return 0;

		}

		public override void Update() {

			foreach (var item in this.playingInstances) {

				item.Value.Update();

			}

		}

		private Item CreatePlayerInstance() {

			var item = new Item();

			var player = new PS4VideoPlayer();
			player.PerformanceLevel = PS4VideoPlayer.Performance.Default;
			//player.demuxVideoBufferSize = 2 * 1024 * 1024;	// change the demux buffer from it's 1mb default
			player.demuxVideoBufferSize = 1024;
			player.numOutputVideoFrameBuffers = 20;		// increasing this can stop frame stuttering
			player.videoMemoryType = PS4VideoPlayer.MemoryType.WB_ONION;

			var lumaTex = new UnityEngine.PS4.PS4ImageStream();
			lumaTex.Create(1920, 1080, PS4ImageStream.Type.R8, 0);
			var chromaTex = new UnityEngine.PS4.PS4ImageStream();
			chromaTex.Create(1920 / 2, 1080 / 2, PS4ImageStream.Type.R8G8, 0);

			player.Init(lumaTex, chromaTex);

			item.player = player;
			item.material = new Material(Shader.Find("FMVTexture"));
			item.material.mainTexture = lumaTex.GetTexture();
			item.material.SetTexture("_CromaTex", chromaTex.GetTexture());

			return item;

		}

		public override bool IsMovie(Texture texture) {

			return true;//string.IsNullOrEmpty(resource.streamingAssetsPath);

		}

		protected override void OnPlay(ResourceBase resource, Texture movie) {

			var path = resource.GetStreamPath();
			var instance = this.FindInstance(resource);
			if (instance != null) {

				instance.player.Play(path, PS4VideoPlayer.Looping.None);

			}

		}

		protected override void OnPlay(ResourceBase resource, Texture movie, bool loop) {

			var path = resource.GetStreamPath();
			var instance = this.FindInstance(resource);
			//Debug.Log ("-----------------------OnPlay: " + path + " :: " + (instance != null));
			if (instance != null) {

				instance.player.Play(path, loop == true ? PS4VideoPlayer.Looping.Continuous : PS4VideoPlayer.Looping.None);

			}

		}

		protected override void OnPause(ResourceBase resource, Texture movie) {

			var instance = this.FindInstance(resource);
			if (instance != null) {

				instance.player.Pause();

			}

		}

		protected override void OnStop(ResourceBase resource, Texture movie) {

			var instance = this.FindInstance(resource);
			if (instance != null) {

				instance.player.Stop();
				this.playingInstances.Remove(resource.GetStreamPath());

			}

		}

		protected override bool IsPlaying(ResourceBase resource, Texture movie) {

			var instance = this.FindInstance(resource);
			if (instance != null) {

				return (instance.player.playerState != PS4VideoPlayer.VidState.STOP &&
					instance.player.playerState != PS4VideoPlayer.VidState.PAUSE);

			}

			return false;

		}

		private Item FindInstance(ResourceBase resource) {

			Item value;
			if (this.playingInstances.TryGetValue(resource.GetStreamPath(), out value) == true) {

				return value;

			}

			return null;

		}

	}
	#endif

}