text:
\section{ems.\+idls.\+session.\+Session\+\_\+\+I\+P\+OA Class Reference}
\label{classems_1_1idls_1_1session_1_1Session__IPOA}\index{ems.\+idls.\+session.\+Session\+\_\+\+I\+P\+OA@{ems.\+idls.\+session.\+Session\+\_\+\+I\+P\+OA}}
Inheritance diagram for ems.\+idls.\+session.\+Session\+\_\+\+I\+P\+OA\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=2.424242cm]{classems_1_1idls_1_1session_1_1Session__IPOA}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
org.\+omg.\+C\+O\+R\+B\+A.\+portable.\+Output\+Stream {\bf \+\_\+invoke} (String \$method, org.\+omg.\+C\+O\+R\+B\+A.\+portable.\+Input\+Stream in, org.\+omg.\+C\+O\+R\+B\+A.\+portable.\+Response\+Handler \$rh)
\item
String[$\,$] {\bfseries \+\_\+all\+\_\+interfaces} (org.\+omg.\+Portable\+Server.\+P\+OA poa, byte[$\,$] object\+Id)\label{classems_1_1idls_1_1session_1_1Session__IPOA_aebe253b42c08e42848754b3406fab969}

\item
{\bf Session\+\_\+I} {\bfseries \+\_\+this} ()\label{classems_1_1idls_1_1session_1_1Session__IPOA_ad3cdf8aafd2d1d03114184209bf80d87}

\item
{\bf Session\+\_\+I} {\bfseries \+\_\+this} (org.\+omg.\+C\+O\+R\+B\+A.\+O\+RB orb)\label{classems_1_1idls_1_1session_1_1Session__IPOA_a0e68fdb2f7d153acbd7a0200a5b91d6b}

\end{DoxyCompactItemize}

\subsection{Detailed Description}
ems/idls/session/\+Session\+\_\+\+I\+P\+O\+A.\+java . Generated by the I\+D\+L-\/to-\/\+Java compiler (portable), version \char`\"{}3.\+2\char`\"{} from \doxyref{session.\+idl}{p.}{session_8idl_source} Tuesday, January 15, 2015 5\+:02\+:24 PM C\+ST

The \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} interface provides capabilities to manage the client-\/server connection. Its main purpose is to enable either a client or server to detect the loss of communication with the associated party.

For a single communication session between an N\+MS and an E\+MS, there are two \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} objects. One is maintained on the N\+MS; the other one is maintained on the E\+MS. The \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} object maintained on the E\+MS is actually an Ems\+Session\+\_\+I, while the \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} object maintained on the N\+MS is actually an Nms\+Session\+\_\+I (both inherit from \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I}).

Each \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} object is responsible to \char`\"{}ping\char`\"{} the other \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} object periodically to detect communication failures. Exactly when this is done is up to the implementation.

When a \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} object detects a communication failure, or when the end\+Session operation is called on it, all resources allocated with that communication session must be freed and the \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} object must be deleted.

\subsection{Member Function Documentation}
\index{ems\+::idls\+::session\+::\+Session\+\_\+\+I\+P\+OA@{ems\+::idls\+::session\+::\+Session\+\_\+\+I\+P\+OA}!\+\_\+invoke@{\+\_\+invoke}}
\index{\+\_\+invoke@{\+\_\+invoke}!ems\+::idls\+::session\+::\+Session\+\_\+\+I\+P\+OA@{ems\+::idls\+::session\+::\+Session\+\_\+\+I\+P\+OA}}
\subsubsection[{\+\_\+invoke(\+String \$method, org.\+omg.\+C\+O\+R\+B\+A.\+portable.\+Input\+Stream in, org.\+omg.\+C\+O\+R\+B\+A.\+portable.\+Response\+Handler \$rh)}]{\setlength{\rightskip}{0pt plus 5cm}org.\+omg.\+C\+O\+R\+B\+A.\+portable.\+Output\+Stream ems.\+idls.\+session.\+Session\+\_\+\+I\+P\+O\+A.\+\_\+invoke (
\begin{DoxyParamCaption}
\item[{String}]{\$method, }
\item[{org.\+omg.\+C\+O\+R\+B\+A.\+portable.\+Input\+Stream}]{in, }
\item[{org.\+omg.\+C\+O\+R\+B\+A.\+portable.\+Response\+Handler}]{\$rh}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{classems_1_1idls_1_1session_1_1Session__IPOA_af705ef2097be3c504ce0b6da1e95f7cc}
This attribute contains a reference to the \doxyref{Session\+\_\+I}{p.}{interfaceems_1_1idls_1_1session_1_1Session__I} on the other side (N\+M\+S/\+E\+MS) to which the object is associated. This attribute can be checked to make sure the Nms\+Session\+\_\+\+I/\+Ems\+Session\+\_\+I association is still valid (in particular in case of communication failures).

Allows for the detection of loss of communication. It is implementation specific to differenciate intermittent problems from loss of connection.

Allows for a controlled disconnect between parties. All resources allocated for the session are deleted by operation.

References ems.\+idls.\+session.\+Session\+\_\+\+I\+Operations.\+associated\+Session(), ems.\+idls.\+session.\+Session\+\_\+\+I\+Operations.\+end\+Session(), and ems.\+idls.\+session.\+Session\+\_\+\+I\+Operations.\+ping().

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
Session\+\_\+\+I\+P\+O\+A.\+java\end{DoxyCompactItemize}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    package="com.dorukkangal.analytics.sample"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:name=".SampleApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity android:name=".SampleActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>

        <meta-data
            android:name="com.google.android.gms.analytics.globalConfigResource"
            android:resource="@xml/analytics_config"/>

        <receiver
            android:name="com.google.android.gms.analytics.AnalyticsReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH"/>
            </intent-filter>
        </receiver>

        <service
            android:name="com.google.android.gms.analytics.AnalyticsService"
            android:enabled="true"
            android:exported="false"/>

    </application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
import os

# Project modules

def data_file(src_path_str):
  """ Returns absolute location of data file """
  return os.path.join(os.path.dirname(__file__), 'data', src_path_str)


text:
The OpenJDK JRE provides Java runtimes from the [OpenJDK][] project.  Versions of Java from the `1.6`, `1.7`, and `1.8` lines are available.  Unless otherwise configured, the version of Java that will be used is specified in [`config/open_jdk_jre.yml`][].

    Detection Criterion
    Unconditional

    Tags
    <tt>open-jdk=⟨version⟩, open-jdk-like-memory-calculator=⟨version⟩</tt>

Tags are printed to standard output by the buildpack detect script

## Configuration
For general information on configuring the buildpack, refer to [Configuration and Extension][].

The JRE can be configured by modifying the [`config/open_jdk_jre.yml`][] file in the buildpack fork.  The JRE uses the [`Repository` utility support][repositories] and so it supports the [version syntax][]  defined there.

| Name | Description
| ---- | -----------
| `memory_sizes` | Optional memory sizes, described below under "Memory Sizes".
| `memory_heuristics` | Default memory size weightings, described below under "Memory Weightings".
| `memory_initials` | Initial memory sizes, described below under "Memory Initials".
| `repository_root` | The URL of the OpenJDK repository index ([details][repositories]).
| `version` | The version of Java runtime to use.  Candidate versions can be found in the listings for [centos6][], [lucid][], [mountainlion][], and [precise][]. Note: version 1.8.0 and higher require the `memory_sizes` and `memory_heuristics` mappings to specify `metaspace` rather than `permgen`.

### Additional Resources
The JRE can also be configured by overlaying a set of resources on the default distribution. To do this, add files to the `resources/open_jdk_jre` directory in the buildpack fork. For example, to add the JCE Unlimited Strength `local_policy.jar` add your file to `resources/open_jdk_jre/lib/security/local_policy.jar`.

### Memory
The total available memory is specified when an application is pushed as part of it's configuration. The Java buildpack uses this value to control the JRE's use of various regions of memory. The JRE memory settings can be influenced by configuring the `memory_sizes`, `memory_heuristics`, `memory_initials` and/or `stack_threads` mappings.

Note: if the total available memory is scaled up or down, the Java buildpack will re-calculate the JRE memory settings the next time the application is started.

#### Memory Sizes
The following optional properties may be specified in the `memory_sizes` mapping.

| Name | Description
| ---- | -----------
| `heap` | The maximum heap size to use. It may be a single value such as `64m` or a range of acceptable values such as `128m..256m`. It is used to calculate the value of the Java command line options `-Xmx` and `-Xms`.
| `metaspace` | The maximum Metaspace size to use. It is applicable to versions of OpenJDK from 1.8 onwards. It may be a single value such as `64m` or a range of acceptable values such as `128m..256m`. It is used to calculate the value of the Java command line options `-XX:MaxMetaspaceSize=` and `-XX:MetaspaceSize=`.
| `native` | The amount of memory to reserve for native memory allocation. It should normally be omitted or specified as a range with no upper bound such as `100m..`. It does not correspond to a switch on the Java command line.
| `permgen` | The maximum PermGen size to use. It is applicable to versions of OpenJDK earlier than 1.8. It may be a single value such as `64m` or a range of acceptable values such as `128m..256m`. It is used to calculate the value of the Java command line options `-XX:MaxPermSize=` and `-XX:PermSize=`.
| `stack` | The stack size to use. It may be a single value such as `2m` or a range of acceptable values such as `2m..4m`. It is used to calculate the value of the Java command line option `-Xss`.

Memory sizes together with _memory weightings_ (described in the next section) are used to calculate the amount of memory for each memory type. The calculation is described later.

Memory sizes consist of a non-negative integer followed by a unit (`k` for kilobytes, `m` for megabytes, `g` for gigabytes; the case is not significant). Only the memory size `0` may be specified without a unit.

The above memory size properties may be omitted with an empty value, specified as a single value, or specified as a range. Ranges use the syntax `<lower bound>..<upper bound>`, although either bound may be omitted in which case the defaults of zero and the total available memory are used for the lower bound and upper bound, respectively. Examples of ranges are `100m..200m` (any value between 100 and 200 megabytes, inclusive) and `100m..` (any value greater than or equal to 100 megabytes).

Each form of memory size is equivalent to a range. Omitting a memory size is equivalent to specifying the range `0..`. Specifying a single value is equivalent to specifying the range with that value as both the lower and upper bound, for example `128m` is equivalent to the range `128m..128m`.

#### Memory Weightings
Memory weightings are configured in the `memory_heuristics` mapping of [`config/open_jdk_jre.yml`][]. Each weighting is a non-negative number and represents a proportion of the total available memory (represented by the sum of all the weightings). For example, the following weightings:

```yaml
memory_heuristics:
  heap: 15
  native: 2
  permgen: 5
  stack: 1
```

represent a maximum heap size three times as large as the maximum PermGen size, and so on.

Memory weightings are used together with memory ranges to calculate the amount of memory for each memory type, as follows.

#### Memory Initials
Memory initials are configured in the `memory_initials` mapping of [`config/open_jdk_jre.yml`][]. Each initial is a percentage of the given type of memory. Valid memory types are `heap`, `permgen`, and `metaspace`. For example, the following initials:

```yaml
memory_initials:
  heap: 50%
  permgen: 25%
```

Given a maximum heap (Xmx) of 1G and a maximum permgen (-XX:MaxPermsize) of 256M an initial heap (Xms) of 512M and an initial permgen (-XX:Permsize) of 64M would be used.

If no initial value is specified for a memory type the JVM default will be used.

A value of 100% for each memory types is generally recommended for best performance.  Smaller values will potentially preserve unused system memory for other tenants on the same host.  Using the G1 garbage collector along with aggressive `MinHeapFreeRatio` and `MaxHeapFreeRatio` values the JVM will actually release unused heap back to the system up to the initial value.

#### Stack Threads

The amount of memory that should be allocated to the stack is given as an amount of memory per thread with the command line option `-Xss`. The default behaviour is to use an estimate of the number of threads based on the total memory for the application. If an explicit number of threads should be used for the calculation of stack memory then it should be specified like the following example:

```yaml
stack_threads: 500
```

#### Memory Calculation
Memory calculation happens before every `start` of an application and is performed by an external program, the [Java Buildpack Memory Calculator]. There is no need to `restage` an application after scaling the memory as restarting will cause the memory settings to be recalculated.

The total available memory is allocated into heap, Metaspace or PermGen (depending on the version of Oracle), stack, and native memory types.

The total available memory is first allocated to each memory type in proportion to its weighting (this is called 'balancing'). If the resultant size of any memory type lies outside its range, the size is constrained to the range, the constrained size is excluded from the remaining memory, and no further calculation is required for that memory type. The remaining memory is then balanced against the memory types that are left, and the check is repeated until no calculated memory sizes lie outside their ranges. The remaining memory is then allocated to the remaining memory types according to the last balance step. This iteration terminates when none of the sizes of the remaining memory types is constrained by their corresponding ranges.

Termination is guaranteed since there is a finite number of memory types and in each iteration either none of the remaining memory sizes is constrained by the corresponding range and allocation terminates or at least one memory size is constrained by the corresponding range and is omitted from the next iteration.

[`config/open_jdk_jre.yml`]: ../config/open_jdk_jre.yml
[Configuration and Extension]: ../README.md#configuration-and-extension
[centos6]: http://download.pivotal.io.s3.amazonaws.com/openjdk/centos6/x86_64/index.yml
[Java Buildpack Memory Calculator]: https://github.com/cloudfoundry/java-buildpack-memory-calculator
[lucid]: http://download.pivotal.io.s3.amazonaws.com/openjdk/lucid/x86_64/index.yml
[mountainlion]: http://download.pivotal.io.s3.amazonaws.com/openjdk/mountainlion/x86_64/index.yml
[OpenJDK]: http://openjdk.java.net
[precise]: http://download.pivotal.io.s3.amazonaws.com/openjdk/precise/x86_64/index.yml
[repositories]: extending-repositories.md
[version syntax]: extending-repositories.md#version-syntax-and-ordering


text:
package com.taobao.zeus.web.platform.client.module.jobdisplay;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.taobao.zeus.web.platform.client.app.PlacePath;
import com.taobao.zeus.web.platform.client.app.PlacePath.App;
import com.taobao.zeus.web.platform.client.app.PlacePath.JobType;
import com.taobao.zeus.web.platform.client.module.jobmanager.GroupModel;
import com.taobao.zeus.web.platform.client.module.jobmanager.JobModel;
import com.taobao.zeus.web.platform.client.module.jobmanager.TreeKeyProviderTool;
import com.taobao.zeus.web.platform.client.module.jobmanager.event.TreeNodeSelectEvent;
import com.taobao.zeus.web.platform.client.util.PlatformContext;
import com.taobao.zeus.web.platform.client.util.RPCS;
import com.taobao.zeus.web.platform.client.util.async.AbstractAsyncCallback;
import com.taobao.zeus.web.platform.client.util.place.PlatformPlaceChangeEvent;

public class JobDisplayPresenterImpl implements JobDisplayPresenter{

	private JobDisplayView jobDisplayView;
	private PlatformContext context;
	public JobDisplayPresenterImpl(PlatformContext context){
		jobDisplayView=new JobDisplayViewImpl(this,context);
		this.context=context;
		this.context.getPlatformBus().addHandler(TreeNodeSelectEvent.type, new TreeNodeSelectEvent.TreeNodeSelectHandler() {
			public void onSelect(TreeNodeSelectEvent event) {
				String providerKey=event.getProviderKey();
				open(providerKey);
			}
		});
		context.getPlatformBus().registPlaceHandler(this);
	}

    private void open(final String providerKey) {
        if(TreeKeyProviderTool.parseIsJob(providerKey)){
            RPCS.getJobService().getUpstreamJob(TreeKeyProviderTool.parseId(providerKey), new AbstractAsyncCallback<JobModel>() {
                public void onSuccess(JobModel result) {
                    jobDisplayView.display(result);
                }
            });
        }else{
            RPCS.getGroupService().getUpstreamGroup(TreeKeyProviderTool.parseId(providerKey), new AbstractAsyncCallback<GroupModel>() {
                public void onSuccess(GroupModel result) {
                    jobDisplayView.display(result);
                }
            });
        }
    }

	@Override
	public void go(HasWidgets hasWidgets) {
		hasWidgets.add(jobDisplayView.asWidget());
	}
	@Override
	public PlatformContext getPlatformContext() {
		return context;
	}
    @Override
    public void handle(PlatformPlaceChangeEvent event) {
        String id = event.getNewPlace().getCurrent().value;
        open(id);
    }
    @Override
    public String getHandlerTag() {
        return TAG;
    }

}


text:
CREATE TABLE products (
  id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  description VARCHAR(512),
  weight FLOAT
);
ALTER TABLE products AUTO_INCREMENT = 101;

INSERT INTO products
VALUES (default,"scooter","Small 2-wheel scooter",3.14),
       (default,"car battery","12V car battery",8.1),
       (default,"12-pack drill bits","12-pack of drill bits with sizes ranging from #40 to #3",0.8),
       (default,"hammer","12oz carpenter's hammer",0.75),
       (default,"hammer","14oz carpenter's hammer",0.875),
       (default,"hammer","16oz carpenter's hammer",1.0),
       (default,"rocks","box of assorted rocks",5.3),
       (default,"jacket","water resistent black wind breaker",0.1),
       (default,"spare tire","24 inch spare tire",22.2);

-- Create and populate the products on hand using multiple inserts
CREATE TABLE products_on_hand (
  product_id INTEGER NOT NULL PRIMARY KEY,
  quantity INTEGER NOT NULL,
  FOREIGN KEY (product_id) REFERENCES products(id)
);

INSERT INTO products_on_hand VALUES (101,3);
INSERT INTO products_on_hand VALUES (102,8);
INSERT INTO products_on_hand VALUES (103,18);
INSERT INTO products_on_hand VALUES (104,4);
INSERT INTO products_on_hand VALUES (105,5);
INSERT INTO products_on_hand VALUES (106,0);
INSERT INTO products_on_hand VALUES (107,44);
INSERT INTO products_on_hand VALUES (108,2);
INSERT INTO products_on_hand VALUES (109,5);

-- Create some customers ...
CREATE TABLE customers (
  id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
  first_name VARCHAR(255) NOT NULL,
  last_name VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL UNIQUE KEY
) AUTO_INCREMENT=1001;

INSERT INTO customers
VALUES (default,"Sally","Thomas","sally.thomas@acme.com"),
       (default,"George","Bailey","gbailey@foobar.com"),
       (default,"Edward","Walker","ed@walker.com"),
       (default,"Anne","Kretchmar","annek@noanswer.org");

-- Create some very simple orders
CREATE TABLE orders (
  order_number INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
  order_date DATE NOT NULL,
  purchaser INTEGER NOT NULL,
  quantity INTEGER NOT NULL,
  product_id INTEGER NOT NULL,
  FOREIGN KEY order_customer (purchaser) REFERENCES customers(id),
  FOREIGN KEY ordered_product (product_id) REFERENCES products(id)
) AUTO_INCREMENT = 10001;

INSERT INTO orders
VALUES (default, '2016-01-16', 1001, 1, 102),
       (default, '2016-01-17', 1002, 2, 105),
       (default, '2016-02-18', 1004, 3, 109),
       (default, '2016-02-19', 1002, 2, 106),
       (default, '2016-02-21', 1003, 1, 107);

-- Temporary table statements should be ignored
CREATE TEMPORARY TABLE ids (id int);
CREATE TEMPORARY TABLE ids2 (id int);
INSERT INTO ids VALUES(1);
INSERT INTO ids2 VALUES(1);
DROP TEMPORARY TABLE ids;
DROP TEMPORARY TABLE ids2;

-- DBZ-342 handle TIME values that exceed the value range of java.sql.Time
CREATE TABLE dbz_342_timetest (
  c1 TIME(2) PRIMARY KEY,
  c2 TIME(0),
  c3 TIME(3),
  c4 TIME(3),
  c5 TIME(6)
);
INSERT INTO dbz_342_timetest VALUES ('517:51:04.777', '-13:14:50', '-733:00:00.0011', '-1:59:59.0011', '-838:59:58.999999');


text:
package old.linkist;

import org.junit.Before;
import org.junit.Test;

/**
 * @author pinker on 2017/11/29
 */
public class PartionListTest {

  /**
   * Given 1->4->3->2->5->2 and x = 3,
   * return 1->2->2->4->3->5.
   *
   * @throws Exception yichang
   */
  private PartionList solution;

  @Before
  public void setUp() {
    solution = new PartionList();
  }

  @Test
  public void partition() throws Exception {
    ListNode root = new ListNode(1), node = root;
    node.next = new ListNode(4);
    node = node.next;
    node.next = new ListNode(3);
    node = node.next;
    node.next = new ListNode(2);
    node = node.next;
    node.next = new ListNode(5);
    node = node.next;
    node.next = new ListNode(2);
    node = solution.partition(root, 3);
    while (node != null) {
      System.out.print(node.val + "\t");
      node = node.next;
    }
    System.out.println();
  }
}


text:
<?php

namespace Org\Schema\Thing\Action\AssessAction;

/**
 * Class ChooseAction.
 * The act of expressing a preference from a set of options or
 * a large or unbounded set of choices/options.
 * @author      AppBels <app.bels@gmail.com>
 * @name        ChooseAction
 * @namespace   Org\Schema\Thing\Action\AssessAction
 * @package     Org\Schema
 * @see         https://schema.org/ChooseAction
 * Date:        26/02/2017
 */
class ChooseAction extends \Org\Schema\Thing\Action\AssessAction
{

	/**
	 * A sub property of object. The options subject to this action. Supersedes option.
	 * @access  public
	 * @var     string|\Org\Schema\Thing
	 */
	public $actionOption;

	/**
	 * ChooseAction constructor.
	 * @access  public
	 * @see     \Org\Schema\Thing\Action\AssessAction::__construct()
	 */
	public function __construct ()
	{
		parent::__construct();
	}

	/**
	 * ChooseAction toString.
	 * @access  public
	 * @see     \Org\Schema\Thing\Action\AssessAction::__toString()
	 *
	 * @return  string
	 */
	public function __toString ()
	{
		return parent::__toString();
	}

	/**
	 * ChooseAction destructor.
	 * @access  public
	 * @see     \Org\Schema\Thing\Action\AssessAction::__destruct()
	 */
	public function __destruct ()
	{
		parent::__destruct();
	}

}

?>


text:
package com.cinchapi.concourse.server.storage.temp;

import org.junit.Assert;
import org.junit.Test;

import com.cinchapi.concourse.server.io.ByteableTest;
import com.cinchapi.concourse.server.storage.temp.Write;
import com.cinchapi.concourse.thrift.TObject;
import com.cinchapi.concourse.util.TestData;

/**
 * Unit tests for {@link Write}.
 *
 * @author Jeff Nelson
 */
public class WriteTest extends ByteableTest {

    @Test
    public void testMatchesSameType() {
        String key = TestData.getString();
        TObject value = TestData.getTObject();
        long record = TestData.getLong();
        Assert.assertTrue(Write.add(key, value, record).matches(
                Write.add(key, value, record)));
        Assert.assertTrue(Write.remove(key, value, record).matches(
                Write.remove(key, value, record)));
        Assert.assertTrue(Write.notStorable(key, value, record).matches(
                Write.notStorable(key, value, record)));
    }

    @Test
    public void testMatchesDiffType() {
        String key = TestData.getString();
        TObject value = TestData.getTObject();
        long record = TestData.getLong();
        Assert.assertFalse(Write.add(key, value, record).matches(
                Write.remove(key, value, record)));
        Assert.assertFalse(Write.add(key, value, record).matches(
                Write.notStorable(key, value, record)));
        Assert.assertFalse(Write.remove(key, value, record).matches(
                Write.notStorable(key, value, record)));
    }

    @Test
    public void testEqualsDiffType() {
        String key = TestData.getString();
        TObject value = TestData.getTObject();
        long record = TestData.getLong();
        Assert.assertEquals(Write.add(key, value, record),
                Write.remove(key, value, record));
        Assert.assertEquals(Write.add(key, value, record),
                Write.notStorable(key, value, record));
        Assert.assertEquals(Write.remove(key, value, record),
                Write.notStorable(key, value, record));
    }

    @Test
    public void testEqualsSameType() {
        String key = TestData.getString();
        TObject value = TestData.getTObject();
        long record = TestData.getLong();
        Assert.assertEquals(Write.add(key, value, record),
                Write.add(key, value, record));
        Assert.assertEquals(Write.remove(key, value, record),
                Write.remove(key, value, record));
        Assert.assertEquals(Write.notStorable(key, value, record),
                Write.notStorable(key, value, record));
    }

    @Override
    protected Class<Write> getTestClass() {
        return Write.class;
    }

}


text:
package org.drools.eclipse.flow.ruleflow.editor.editpart.figure.bpmn;

import org.drools.eclipse.DroolsEclipsePlugin;
import org.drools.eclipse.flow.common.editor.editpart.figure.AbstractElementFigure;
import org.eclipse.draw2d.RoundedRectangle;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;

public class BPMNStateFigure extends AbstractElementFigure {

    private static final Image ICON = ImageDescriptor.createFromURL(
        DroolsEclipsePlugin.getDefault().getBundle().getEntry("icons/question.gif")).createImage();

    private RoundedRectangle rectangle;

    public BPMNStateFigure() {
        setSize(80, 48);
    }

    protected void customizeFigure() {
        rectangle = new RoundedRectangle();
        rectangle.setCornerDimensions(new Dimension(25, 25));
        add(rectangle, 0);
        rectangle.setBounds(getBounds());
        setSelected(false);
        setIcon(ICON);
    }

    public void setBounds(Rectangle rectangle) {
        super.setBounds(rectangle);
        this.rectangle.setBounds(rectangle);
    }

    public void setSelected(boolean b) {
        super.setSelected(b);
        rectangle.setLineWidth(b ? 3 : 1);
        repaint();
    }
}


text:
Cross-platform OpenGL skeleton for multiple frameworks. Fork and select from GLFW3, GLFW2,
Glut, SDL and Cinder with a simple tweak to a CMake variable.

The build process requires CMake and Python 2.7. Python is used to generate
a C++ source header with hardcoded strings for shader source in text files under shaders/.

## Setup
### Windows
    Create the directory build/ in project's home(alongside CMakeLists.txt)
    Shift+right-click it in Explorer->"Open command window here"
    ...\build> cmake .. -G "Visual Studio 10"
    Double-click the only .sln file in build to open it in Visual Studio
    Right-click the GLSkeleton project in Solution Explorer, "Set as StartUp Project"
    F7 to build, F5 to build and run

### Linux
    $> mkdir build
    $> cd build
    $> cmake .. && make
    $> ./GLSkeleton


text:
package connect.ui.activity.chat.bean;

import connect.db.MemoryDataManager;
import connect.db.SharedPreferenceUtil;
import connect.ui.activity.R;
import connect.ui.activity.locmap.bean.GeoAddressBean;
import connect.ui.base.BaseApplication;

import java.io.Serializable;

/**
 * content bean
 * Created by gtq on 2016/11/23.
 */
public class MsgDefinBean implements Serializable{
    private int type;
    private String user_name;
    private long sendtime;
    private String message_id;
    private String publicKey;
    private String user_id;
    private String ext;
    private String content;
    private String url;
    private String ext1;
    private GeoAddressBean locationExt;
    private int size;
    private float imageOriginWidth;
    private float imageOriginHeight;

    private MsgSender senderInfoExt;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public long getSendtime() {
        return sendtime;
    }

    public void setSendtime(long sendtime) {
        this.sendtime = sendtime;
    }

    public String getMessage_id() {
        return message_id;
    }

    public void setMessage_id(String message_id) {
        this.message_id = message_id;
    }

    public String getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }

    public String getUser_id() {
        return user_id;
    }

    public void setUser_id(String user_id) {
        this.user_id = user_id;
    }

    public String getExt() {
        return ext;
    }

    public void setExt(String ext) {
        this.ext = ext;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getExt1() {
        return ext1;
    }

    public void setExt1(String ext1) {
        this.ext1 = ext1;
    }

    public GeoAddressBean getLocationExt() {
        return locationExt;
    }

    public void setLocationExt(GeoAddressBean locationExt) {
        this.locationExt = locationExt;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public float getImageOriginWidth() {
        return imageOriginWidth;
    }

    public void setImageOriginWidth(float imageOriginWidth) {
        this.imageOriginWidth = imageOriginWidth;
    }

    public float getImageOriginHeight() {
        return imageOriginHeight;
    }

    public void setImageOriginHeight(float imageOriginHeight) {
        this.imageOriginHeight = imageOriginHeight;
    }

    public MsgSender getSenderInfoExt() {
        return senderInfoExt;
    }

    public void setSenderInfoExt(MsgSender senderInfoExt) {
        this.senderInfoExt = senderInfoExt;
    }

    /**
     * Display the list in the session
     *
     * @return
     */
    public String showContentTxt(int type) {
        String content = "";
        switch (getType()) {
            case 1://text
                content = getContent();
                break;
            case 2://voice
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Audio);
                break;
            case 3://picture
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Picture);
                break;
            case 4://video
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Video);
                break;
            case 5://expression
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Expression);
                break;
            case 11://burn message
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Snapchat);
                break;
            case 12://burn back
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Snapchat);
                break;
            case 14:
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Funding);
                break;
            case 15:
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Transfer);
                break;
            case 16:
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Red_packet);
                break;
            case 17:
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Location);
                break;
            case 18:
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Visting_card);
                break;
            case 23:
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Group_Namecard);
                break;
            case 24:
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Group_certification);
                break;
            default:
                content = BaseApplication.getInstance().getBaseContext().getString(R.string.Chat_Tips);
                break;
        }

        switch (type) {
            case 0:
                break;
            case 1://show group member nickname
                MsgSender msgSender = getSenderInfoExt();
                if (msgSender != null && !msgSender.publickey.equals(MemoryDataManager.getInstance().getPubKey())) {
                    content = msgSender.username + ": " + content;
                }
                break;
            case 2:
                break;
        }
        return content;
    }
}


text:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace Common.Controls
{
    public partial class Numeric_Box : UserControl, ICalculatorTextBox
    {

        public decimal Value {
            get { return vb_box.Value; }
            set { vb_box.Value = value; }
        }

        public new event EventHandler TextChanged {
            add {
                vb_box.TextChanged += value;
            }
            remove {
                vb_box.TextChanged -= value;
            }
        }

        public event EventHandler ValueChanged {
            add {
                vb_box.ValueChanged += value;
            }
            remove {
                vb_box.ValueChanged -= value;
            }
        }

        public static implicit operator Validating_Box(Numeric_Box nb) {

            nb.vb_box.Name = nb.Name;

            return nb.vb_box;
        }

        // TextBox positioning
        const int c_TextLocationX = 2;
        const int c_TextLocationY = 3;

        const int c_TextBoxWidthOffset = 24;
        const int c_TextBoxHeight = 14;

        int _txt_Y;
        public int TextLowered {
            get {
                return _txt_Y;
            }
            set {
                if (value != _txt_Y) {
                    _txt_Y = value;
                    vb_box.Location = new Point(c_TextLocationX, c_TextLocationY + _txt_Y);
                }
            }
        }
        //

        public void SimulateEntered() {
            b_flag = true;

            vb_box.TextAlign = HorizontalAlignment.Left;

            b_flag = false;
        }

        public void SimulateLeft() {
            b_flag = true;

            BeginInvoke((MethodInvoker)(() =>
            {
                vb_box.TextAlign = HorizontalAlignment.Right;
            }));

            b_flag = false;
        }

        [DebuggerStepThrough]
        public void Clear() {
            vb_box.ResetText();
        }

        // Reimplementations
        [DefaultValue(true)]
        public bool AutoHighlight {
            get {
                return this.vb_box.AutoHighlight;

            }
            set {
                this.vb_box.AutoHighlight = value;
            }
        }
        public int SelectionStart {
            get { return vb_box.SelectionStart; }
            set { vb_box.SelectionStart = value; }
        }
        public int SelectionLength {
            get { return vb_box.SelectionLength; }
            set { vb_box.SelectionLength = value; }
        }
        public void SelectAll() {
            vb_box.SelectAll();
        }
        public HorizontalAlignment TextAlign {
            get { return vb_box.TextAlign; }
            set { vb_box.TextAlign = value; }
        }

        public int DecimalPlaces {
            get { return vb_box.Decimal_Places; }
            set { vb_box.Decimal_Places = value; }
        }

        public int MaxLength {
            get { return vb_box.MaxLength; }
            set { vb_box.MaxLength = value; }
        }
        public override string Text {
            [DebuggerStepThrough]
            get { return vb_box.Text.Trim(); }
            set {
                vb_box.Text = value;
            }
        }
        /// <summary>
        /// Returns whether the box contains the same
        /// text as it did when it was last selected.
        /// </summary>
        public bool Has_Text_Changed_Since_Entered {
            get { return vb_box.Has_Text_Changed_Since_Entered; }

        }

        public bool Check_Typed_Text() {
            bool ret = vb_box.Check_Typed_Text();
            return ret;

        }

        /// <summary>
        /// This property returns whether the user has typed
        /// or pasted any text using the keyboard or mouse
        /// since it was last reset.
        /// This property is only reset when calling ResetText();
        /// The caller can set it to false himself if he wants to
        /// indicate that the change has been handled.
        /// </summary>
        public bool Has_User_Typed_Text {
            get { return vb_box.Has_User_Typed_Text; }
            set { vb_box.Has_User_Typed_Text = value; }

        }

        /// <summary>
        /// Returns whether the box contains the
        /// default text (0, 0.0, 0.00 etc)
        /// </summary>
        public bool Has_Default_Text {
            get { return vb_box.Has_Default_Text; }
        }
        //

        void textBox_GotFocus(object sender, EventArgs e) {

            b_flag = true;

            vb_box.Text = vb_box.Text.Trim();
            vb_box.SelectAll();

            b_flag = false;
        }
    }
}


text:
module Ansuz
  # Don't really know the best way to do this, just rolling with whatever works -james
  module PluginSettings
    class << self
      def included base
        base.extend ClassMethods
      end
    end

    module ClassMethods
      def plugin_settings
        SiteSetting.first.settings[self.settings_name]
      end

      def settings_name
        self.to_s.tableize.gsub(/\//,'_').to_sym
      end

      def modify_setting(name,val)
        site_setting = SiteSetting.first
        site_setting.settings[self.settings_name][name.to_sym] = val
        site_setting.save
      end
    end
  end
end


text:
package org.apache.catalina.deploy;

/**
 * @version $Id: InjectionTarget.java 1057677 2011-01-11 14:57:17Z markt $
 */
public class InjectionTarget {
    private String targetClass;
    private String targetName;

    public InjectionTarget() {
        // NOOP
    }

    public InjectionTarget(String targetClass, String targetName) {
        this.targetClass = targetClass;
        this.targetName = targetName;
    }

    public String getTargetClass() {
        return targetClass;
    }

    public void setTargetClass(String targetClass) {
        this.targetClass = targetClass;
    }

    public String getTargetName() {
        return targetName;
    }

    public void setTargetName(String targetName) {
        this.targetName = targetName;
    }

}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Config (
    CommandDictionary(..),
    constructDict
    ) where

import qualified Data.Map.Strict as M
import Control.Applicative((<$>),(<*>))
import qualified Data.ByteString.Lazy as L
import Data.List(unlines)
import Data.Maybe
import Data.Either(partitionEithers)
import Data.Tuple
import Data.Word(Word8(..))
import Numeric(readHex)
import Control.Monad(mzero,liftM,mapM)
import Data.Aeson
import Codec.Picture.Types
import Text.Regex.Posix((=~))

-- the CommandDictionary describes a mapping from pixels to strings
-- it is accessed via the translate function
data CommandDictionary = CommandDictionary {
                         des :: M.Map PixelRGB8 String
                       , bld :: M.Map PixelRGB8 String
                       , plc :: M.Map PixelRGB8 String
                       , qry :: M.Map PixelRGB8 String }
    deriving(Eq,Show)

data ConfigLists = ConfigLists { designate :: M.Map String [String]
                               , build     :: M.Map String [String]
                               , place     :: M.Map String [String]
                               , query     :: M.Map String [String] }

configTup :: ConfigLists -> (M.Map String [String],M.Map String [String],
                             M.Map String [String],M.Map String [String])
configTup cl = (designate cl,
                build cl,
                place cl,
                query cl)

instance FromJSON ConfigLists where
    parseJSON (Object v) = ConfigLists <$>
                          v .: "designate" <*>
                          v .: "build" <*>
                          v .: "place" <*>
                          v .: "query"
    parseJSON _          = mzero

constructDict :: L.ByteString -> L.ByteString -> Either String CommandDictionary
constructDict alias config = do
    aliasLists <- eitherDecode alias :: Either String ConfigLists
    commands   <- eitherDecode config :: Either String ConfigLists
    buildCommandDict aliasLists commands
  where
    buildCommandDict :: ConfigLists -> ConfigLists -> Either String CommandDictionary
    buildCommandDict al cs =
        buildCommandDict' (tmap4 (expandList . M.toList) altup)
                          (tmap4 (expandPixelList . M.toList) cstup)
            where altup = configTup al
                  cstup = configTup cs
    buildCommandDict' (a,b,c,d) (w,x,y,z) = do
       designate' <- genMap a w
       build'     <- genMap b x
       place'     <- genMap c y
       query'     <- genMap d z
       Right (CommandDictionary designate' build' place' query')

-- map a function over a 4 tuple
tmap4 :: (a -> b) -> (a,a,a,a) -> (b,b,b,b)
tmap4 f (t1,t2,t3,t4) = (f t1,f t2,f t3,f t4)

genMap :: [(String,String)] -> [(Either String PixelRGB8,String)]
                            -> Either String (M.Map PixelRGB8 String)
genMap _ []  = Right M.empty
genMap [] _  = Right M.empty
genMap al cs | not (null errorList) = Left (unlines errorList)
             | length (filter pred genList) == 0  = Right (M.fromList $ map noMaybe genList)
             | otherwise =
                Left "Error generating pixel-string map: an alias is referenced\
                      \ in pngconfig.json that is not present in alias.json"
  where
    (errorList,genList) = partitionEithers $ map (checkEither . doLookup) cs
    doLookup (pix,str) = (pix,M.lookup str dict)
    -- checkEither extracts the Either state from a tuple
    checkEither (Right p,s) = Right (p,s)
    checkEither (Left e,s) = Left e
    dict = M.fromList al

    pred (_,a) = isNothing a

    noMaybe (a,b) = (a,fromJust b)

expandList :: [(String,[String])] -> [(String,String)]
expandList = concatMap (expand . swap)

expandPixelList :: [(String,[String])] -> [(Either String PixelRGB8,String)]
expandPixelList = map (toPixel) . expandList

-- expand a tuple holding a list of keys and a value into a list of key value pairs
expand :: ([String],String) -> [(String,String)]
expand ([],_) = []
expand ((k:ks),val) = (k,val) : expand (ks,val)

-- TODO: need to make these check for malformed strings
toPixel :: (String,String) ->(Either String PixelRGB8,String)
toPixel (key,val) = (keyToPixel key,val)

-- color representations:
-- base ten: <val>:<val>:<val>:<val>
-- hex: #<val><val><val><val> or 0x<val><val><val><val>
keyToPixel :: String -> Either String PixelRGB8
keyToPixel = (liftM listToPixel) . keyToPixel'
  where keyToPixel' key | key               == "" = Left (fErr "attempted to pass null key string")
                        | fst hexResults    /= "" = Right $ parseHex (snd hexResults)
                        | fst base10Results /= "" = parse10 (snd base10Results)
                        | otherwise               = Left (fErr $ "malformed key: " ++ key)
          where matchHex      = key =~ hexPattern :: (String,String,String,[String])
                matchBaseTen  = key =~ baseTenPattern :: (String,String,String,[String])
                hexResults    = results matchHex
                base10Results = results matchBaseTen
                results (_,match,_,substrs) = (match,substrs)
                fErr s = "Error in keyToPixel: " ++ s

-- parse a list of hex strings to Word8 values
-- we're guaranteed that the list will look like [<hex prefix>,<val>,<val>,<val>]
-- from the pattern match that calls parseHex
parseHex :: [String] -> [Word8]
parseHex = (map toHex) . tail
  where toHex = fst . head . readHex

parse10 :: [String] -> Either String [Word8]
parse10  = mapM (readWithBounds)
    -- readWithBounds will either return the String as a Word8 or
    -- throw an error if the value is larger than 255
    where readWithBounds :: String -> Either String Word8
          readWithBounds s | val > 255 = Left ("key value too large: " ++ s ++
                                               " needs to be less than 256")
                           | otherwise = Right (fromInteger val)
            where val = read s :: Integer

-- listToPixel can't fail on an input of Right, the pattern matching in keyToPixel'
-- guarentees that parseHex and parse10 will return a list of the correct size
listToPixel :: [Word8] -> PixelRGB8
listToPixel (r:g:b:[]) = PixelRGB8 r g b

hexPattern :: String
hexPattern = "^(0x|#)([[:xdigit:]]{2,2})([[:xdigit:]]{2,2})([[:xdigit:]]{2,2})"

baseTenPattern :: String
baseTenPattern = "^([0-9]{1,3}):([0-9]{1,3}):([0-9]{1,3})"


text:
package java.security.interfaces;

import java.math.BigInteger;

/**
 * The interface for Digital Signature Algorithm (DSA) specific parameters.
 */
public interface DSAParams {

    /**
     * Returns the base ({@code g}) value.
     *
     * @return the base ({@code g}) value.
     */
    public BigInteger getG();

    /**
     * Returns the prime ({@code p}) value.
     *
     * @return the prime ({@code p}) value.
     */
    public BigInteger getP();

    /**
     * Returns the subprime ({@code q}) value.
     *
     * @return the subprime ({@code q}) value.
     */
    public BigInteger getQ();

}


text:
from trac.admin.api import AdminCommandError, IAdminCommandProvider, \
                           IAdminPanelProvider, console_date_format, \
                           console_datetime_format, get_console_locale
from trac.core import *
from trac.resource import ResourceNotFound
from trac.ticket import model
from trac.ticket.api import TicketSystem
from trac.ticket.roadmap import MilestoneModule
from trac.util import getuser
from trac.util.datefmt import format_date, format_datetime, \
                              get_datetime_format_hint, parse_date, user_time
from trac.util.text import exception_to_unicode, print_table, printout
from trac.util.translation import _, N_, gettext
from trac.web.chrome import Chrome, add_notice, add_script, add_warning

class TicketAdminPanel(Component):

    implements(IAdminPanelProvider, IAdminCommandProvider)

    abstract = True

    _type = 'undefined'
    _label = N_("(Undefined)"), N_("(Undefined)")
    _view_perms = ['TICKET_ADMIN']

    # i18n note: use gettext() whenever referring to the above as text labels,
    #            and don't use it whenever using them as field names (after
    #            a call to `.lower()`)

    # IAdminPanelProvider methods

    def get_admin_panels(self, req):
        if all(perm in req.perm('admin', 'ticket/' + self._type)
               for perm in self._view_perms):
            yield ('ticket', _('Ticket System'), self._type,
                   gettext(self._label[1]))

    def render_admin_panel(self, req, cat, page, path_info):
        # Trap AssertionErrors and convert them to TracErrors
        try:
            return self._render_admin_panel(req, cat, page, path_info)
        except AssertionError as e:
            raise TracError(e)

    def _save_config(self, req):
        """Try to save the config, and display either a success notice or a
        failure warning.
        """
        try:
            self.config.save()
            add_notice(req, _("Your changes have been saved."))
        except Exception as e:
            self.log.error("Error writing to trac.ini: %s",
                           exception_to_unicode(e))
            add_warning(req, _("Error writing to trac.ini, make sure it is "
                               "writable by the web server. Your changes "
                               "have not been saved."))

class ComponentAdminPanel(TicketAdminPanel):

    _type = 'components'
    _label = N_("Component"), N_("Components")

    # TicketAdminPanel methods

    def _render_admin_panel(self, req, cat, page, component):
        # Detail view?
        if component:
            comp = model.Component(self.env, component)
            if req.method == 'POST':
                if req.args.get('save'):
                    comp.name = name = req.args.get('name')
                    comp.owner = req.args.get('owner')
                    comp.description = req.args.get('description')
                    try:
                        comp.update()
                    except self.env.db_exc.IntegrityError:
                        raise TracError(_('Component "%(name)s" already '
                                          'exists.', name=name))
                    add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('cancel'):
                    req.redirect(req.href.admin(cat, page))

            Chrome(self.env).add_wiki_toolbars(req)
            data = {'view': 'detail', 'component': comp}

        else:
            default = self.config.get('ticket', 'default_component')
            if req.method == 'POST':
                # Add Component
                if req.args.get('add') and req.args.get('name'):
                    name = req.args.get('name')
                    try:
                        comp = model.Component(self.env, name=name)
                    except ResourceNotFound:
                        comp = model.Component(self.env)
                        comp.name = name
                        if req.args.get('owner'):
                            comp.owner = req.args.get('owner')
                        comp.insert()
                        add_notice(req, _('The component "%(name)s" has been '
                                          'added.', name=name))
                        req.redirect(req.href.admin(cat, page))
                    else:
                        if comp.name is None:
                            raise TracError(_("Invalid component name."))
                        raise TracError(_('Component "%(name)s" already '
                                          'exists.', name=name))

                # Remove components
                elif req.args.get('remove'):
                    sel = req.args.getlist('sel')
                    if not sel:
                        raise TracError(_("No component selected"))
                    with self.env.db_transaction:
                        for name in sel:
                            model.Component(self.env, name).delete()
                            if name == default:
                                self.config.set('ticket',
                                                'default_component', '')
                                self._save_config(req)
                    add_notice(req, _("The selected components have been "
                                      "removed."))
                    req.redirect(req.href.admin(cat, page))

                # Set default component
                elif req.args.get('apply'):
                    name = req.args.get('default')
                    if name and name != default:
                        self.log.info("Setting default component to %s", name)
                        self.config.set('ticket', 'default_component', name)
                        self._save_config(req)
                        req.redirect(req.href.admin(cat, page))

                # Clear default component
                elif req.args.get('clear'):
                    self.log.info("Clearing default component")
                    self.config.set('ticket', 'default_component', '')
                    self._save_config(req)
                    req.redirect(req.href.admin(cat, page))

            data = {'view': 'list',
                    'components': list(model.Component.select(self.env)),
                    'default': default}

        owners = TicketSystem(self.env).get_allowed_owners()
        if owners is not None:
            owners.insert(0, '')
        data.update({'owners': owners})

        return 'admin_components.html', data

    # IAdminCommandProvider methods

    def get_admin_commands(self):
        yield ('component list', '',
               'Show available components',
               None, self._do_list)
        yield ('component add', '<name> [owner]',
               'Add a new component',
               self._complete_add, self._do_add)
        yield ('component rename', '<name> <newname>',
               'Rename a component',
               self._complete_remove_rename, self._do_rename)
        yield ('component remove', '<name>',
               'Remove/uninstall a component',
               self._complete_remove_rename, self._do_remove)
        yield ('component chown', '<name> <owner>',
               'Change component ownership',
               self._complete_chown, self._do_chown)

    def get_component_list(self):
        return [c.name for c in model.Component.select(self.env)]

    def get_user_list(self):
        return TicketSystem(self.env).get_allowed_owners()

    def _complete_add(self, args):
        if len(args) == 2:
            return self.get_user_list()

    def _complete_remove_rename(self, args):
        if len(args) == 1:
            return self.get_component_list()

    def _complete_chown(self, args):
        if len(args) == 1:
            return self.get_component_list()
        elif len(args) == 2:
            return self.get_user_list()

    def _do_list(self):
        print_table([(c.name, c.owner)
                     for c in model.Component.select(self.env)],
                    [_('Name'), _('Owner')])

    def _do_add(self, name, owner=None):
        component = model.Component(self.env)
        component.name = name
        component.owner = owner
        component.insert()

    def _do_rename(self, name, newname):
        component = model.Component(self.env, name)
        component.name = newname
        component.update()

    def _do_remove(self, name):
        model.Component(self.env, name).delete()

    def _do_chown(self, name, owner):
        component = model.Component(self.env, name)
        component.owner = owner
        component.update()

class MilestoneAdminPanel(TicketAdminPanel):

    _type = 'milestones'
    _label = N_("Milestone"), N_("Milestones")
    _view_perms = TicketAdminPanel._view_perms + ['MILESTONE_VIEW']

    # TicketAdminPanel methods

    def _render_admin_panel(self, req, cat, page, milestone_name):
        perm_cache = req.perm('admin', 'ticket/' + self._type)

        # Detail view
        if milestone_name:
            milestone = model.Milestone(self.env, milestone_name)
            milestone_module = MilestoneModule(self.env)
            if req.method == 'POST':
                if 'save' in req.args:
                    perm_cache.require('MILESTONE_MODIFY')
                    if milestone_module.save_milestone(req, milestone):
                        req.redirect(req.href.admin(cat, page))

                elif 'cancel' in req.args:
                    req.redirect(req.href.admin(cat, page))

            Chrome(self.env).add_wiki_toolbars(req)
            data = {'view': 'detail',
                    'milestone': milestone,
                    'default_due': milestone_module.get_default_due(req)}

        # List view
        else:
            ticket_default = self.config.get('ticket', 'default_milestone')
            retarget_default = self.config.get('milestone',
                                               'default_retarget_to')
            if req.method == 'POST':

                # Add milestone
                if 'add' in req.args and req.args.get('name'):
                    perm_cache.require('MILESTONE_CREATE')
                    name = req.args.get('name')
                    try:
                        model.Milestone(self.env, name=name)
                    except ResourceNotFound:
                        milestone = model.Milestone(self.env)
                        milestone.name = name
                        MilestoneModule(self.env).save_milestone(req,
                                                                 milestone)
                        req.redirect(req.href.admin(cat, page))
                    else:
                        add_warning(req, _('Milestone "%(name)s" already '
                                           'exists, please choose another '
                                           'name.', name=name))

                # Remove milestone
                elif 'remove' in req.args:
                    save = False
                    perm_cache.require('MILESTONE_DELETE')
                    sel = req.args.getlist('sel')
                    if not sel:
                        raise TracError(_("No milestone selected"))
                    with self.env.db_transaction:
                        for name in sel:
                            milestone = model.Milestone(self.env, name)
                            milestone.move_tickets(None, req.authname,
                                                   "Milestone deleted")
                            milestone.delete()
                            if name == ticket_default:
                                self.config.set('ticket',
                                                'default_milestone', '')
                                save = True
                            if name == retarget_default:
                                self.config.set('milestone',
                                                'default_retarget_to', '')
                                save = True
                    if save:
                        self._save_config(req)
                    add_notice(req, _("The selected milestones have been "
                                      "removed."))
                    req.redirect(req.href.admin(cat, page))

                # Set default milestone
                elif 'apply' in req.args:
                    save = False
                    name = req.args.get('ticket_default')
                    if name and name != ticket_default:
                        self.log.info("Setting default ticket "
                                      "milestone to %s", name)
                        self.config.set('ticket', 'default_milestone', name)
                        save = True
                    retarget = req.args.get('retarget_default')
                    if retarget and retarget != retarget_default:
                        self.log.info("Setting default retargeting "
                                      "milestone to %s", retarget)
                        self.config.set('milestone', 'default_retarget_to',
                                        retarget)
                        save = True
                    if save:
                        self._save_config(req)
                        req.redirect(req.href.admin(cat, page))

                # Clear default milestone
                elif 'clear' in req.args:
                    self.log.info("Clearing default ticket milestone "
                                  "and default retarget milestone")
                    self.config.set('ticket', 'default_milestone', '')
                    self.config.set('milestone', 'default_retarget_to', '')
                    self._save_config(req)
                    req.redirect(req.href.admin(cat, page))

            query_href = lambda name: req.href.query({'groupby': 'status',
                                                      'milestone': name})

            data = {'view': 'list',
                    'milestones': model.Milestone.select(self.env),
                    'query_href': query_href,
                    'ticket_default': ticket_default,
                    'retarget_default': retarget_default}

        Chrome(self.env).add_jquery_ui(req)

        data.update({
            'datetime_hint': get_datetime_format_hint(req.lc_time),
        })
        return 'admin_milestones.html', data

    # IAdminCommandProvider methods

    def get_admin_commands(self):
        locale = get_console_locale(self.env)
        hints = {
            'datetime': get_datetime_format_hint(locale),
            'iso8601': get_datetime_format_hint('iso8601'),
        }
        yield ('milestone list', '',
               "Show milestones",
               None, self._do_list)
        yield ('milestone add', '<name> [due]',
               "Add milestone",
               None, self._do_add)
        yield ('milestone rename', '<name> <newname>',
               "Rename milestone",
               self._complete_name, self._do_rename)
        yield ('milestone due', '<name> <due>',
               """Set milestone due date

               The <due> date must be specified in the "%(datetime)s"
               or "%(iso8601)s" (ISO 8601) format.
               Alternatively, "now" can be used to set the due date to the
               current time. To remove the due date from a milestone, specify
               an empty string ("").
               """ % hints,
               self._complete_name, self._do_due)
        yield ('milestone completed', '<name> <completed>',
               """Set milestone complete date

               The <completed> date must be specified in the "%(datetime)s"
               or "%(iso8601)s" (ISO 8601) format.
               Alternatively, "now" can be used to set the completion date to
               the current time. To remove the completion date from a
               milestone, specify an empty string ("").
               """ % hints,
               self._complete_name, self._do_completed)
        yield ('milestone remove', '<name>',
               "Remove milestone",
               self._complete_name, self._do_remove)

    def get_milestone_list(self):
        return [m.name for m in model.Milestone.select(self.env)]

    def _complete_name(self, args):
        if len(args) == 1:
            return self.get_milestone_list()

    def _do_list(self):
        print_table([(m.name,
                      format_date(m.due, console_date_format)
                      if m.due else None,
                      format_datetime(m.completed, console_datetime_format)
                      if m.completed else None)
                     for m in model.Milestone.select(self.env)],
                    [_("Name"), _("Due"), _("Completed")])

    def _do_add(self, name, due=None):
        milestone = model.Milestone(self.env)
        milestone.name = name
        if due is not None:
            milestone.due = parse_date(due, hint='datetime',
                                       locale=get_console_locale(self.env))
        milestone.insert()

    def _do_rename(self, name, newname):
        milestone = model.Milestone(self.env, name)
        milestone.name = newname
        milestone.update(author=getuser())

    def _do_due(self, name, due):
        milestone = model.Milestone(self.env, name)
        milestone.due = parse_date(due, hint='datetime',
                                   locale=get_console_locale(self.env)) \
                        if due else None
        milestone.update()

    def _do_completed(self, name, completed):
        milestone = model.Milestone(self.env, name)
        milestone.completed = parse_date(completed, hint='datetime',
                                         locale=get_console_locale(self.env)) \
                              if completed else None
        milestone.update()

    def _do_remove(self, name):
        model.Milestone(self.env, name).delete(author=getuser())

class VersionAdminPanel(TicketAdminPanel):

    _type = 'versions'
    _label = N_("Version"), N_("Versions")

    # TicketAdminPanel methods

    def _render_admin_panel(self, req, cat, page, version):
        # Detail view?
        if version:
            ver = model.Version(self.env, version)
            if req.method == 'POST':
                if req.args.get('save'):
                    ver.name = name = req.args.get('name')
                    if req.args.get('time'):
                        ver.time = user_time(req, parse_date,
                                             req.args.get('time'),
                                             hint='datetime')
                    else:
                        ver.time = None  # unset
                    ver.description = req.args.get('description')
                    try:
                        ver.update()
                    except self.env.db_exc.IntegrityError:
                        raise TracError(_('Version "%(name)s" already '
                                          'exists.', name=name))

                    add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('cancel'):
                    req.redirect(req.href.admin(cat, page))

            Chrome(self.env).add_wiki_toolbars(req)
            data = {'view': 'detail', 'version': ver}

        else:
            default = self.config.get('ticket', 'default_version')
            if req.method == 'POST':
                # Add Version
                if req.args.get('add') and req.args.get('name'):
                    name = req.args.get('name')
                    try:
                        ver = model.Version(self.env, name=name)
                    except ResourceNotFound:
                        ver = model.Version(self.env)
                        ver.name = name
                        if req.args.get('time'):
                            ver.time = user_time(req, parse_date,
                                                 req.args.get('time'),
                                                 hint='datetime')
                        ver.insert()
                        add_notice(req, _('The version "%(name)s" has been '
                                          'added.', name=name))
                        req.redirect(req.href.admin(cat, page))
                    else:
                        if ver.name is None:
                            raise TracError(_("Invalid version name."))
                        raise TracError(_('Version "%(name)s" already '
                                          'exists.', name=name))

                # Remove versions
                elif req.args.get('remove'):
                    sel = req.args.getlist('sel')
                    if not sel:
                        raise TracError(_("No version selected"))
                    with self.env.db_transaction:
                        for name in sel:
                            model.Version(self.env, name).delete()
                            if name == default:
                                self.config.set('ticket', 'default_version', '')
                                self._save_config(req)
                    add_notice(req, _("The selected versions have been "
                                      "removed."))
                    req.redirect(req.href.admin(cat, page))

                # Set default version
                elif req.args.get('apply'):
                    name = req.args.get('default')
                    if name and name != default:
                        self.log.info("Setting default version to %s", name)
                        self.config.set('ticket', 'default_version', name)
                        self._save_config(req)
                        req.redirect(req.href.admin(cat, page))

                # Clear default version
                elif req.args.get('clear'):
                    self.log.info("Clearing default version")
                    self.config.set('ticket', 'default_version', '')
                    self._save_config(req)
                    req.redirect(req.href.admin(cat, page))

            data = {'view': 'list',
                    'versions': list(model.Version.select(self.env)),
                    'default': default}

        Chrome(self.env).add_jquery_ui(req)

        data.update({'datetime_hint': get_datetime_format_hint(req.lc_time)})
        return 'admin_versions.html', data

    # IAdminCommandProvider methods

    def get_admin_commands(self):
        locale = get_console_locale(self.env)
        hints = {
            'datetime': get_datetime_format_hint(locale),
            'iso8601': get_datetime_format_hint('iso8601'),
        }
        yield ('version list', '',
               "Show versions",
               None, self._do_list)
        yield ('version add', '<name> [time]',
               "Add version",
               None, self._do_add)
        yield ('version rename', '<name> <newname>',
               "Rename version",
               self._complete_name, self._do_rename)
        yield ('version time', '<name> <time>',
               """Set version date

               The <time> must be specified in the "%(datetime)s"
               or "%(iso8601)s" (ISO 8601) format.
               Alternatively, "now" can be used to set the version date to
               the current time. To remove the date from a version, specify
               an empty string ("").
               """ % hints,
               self._complete_name, self._do_time)
        yield ('version remove', '<name>',
               "Remove version",
               self._complete_name, self._do_remove)

    def get_version_list(self):
        return [v.name for v in model.Version.select(self.env)]

    def _complete_name(self, args):
        if len(args) == 1:
            return self.get_version_list()

    def _do_list(self):
        print_table([(v.name,
                      format_date(v.time, console_date_format)
                      if v.time else None)
                    for v in model.Version.select(self.env)],
                    [_("Name"), _("Time")])

    def _do_add(self, name, time=None):
        version = model.Version(self.env)
        version.name = name
        if time is not None:
            version.time = parse_date(time, hint='datetime',
                                      locale=get_console_locale(self.env)) \
                           if time else None
        version.insert()

    def _do_rename(self, name, newname):
        version = model.Version(self.env, name)
        version.name = newname
        version.update()

    def _do_time(self, name, time):
        version = model.Version(self.env, name)
        version.time = parse_date(time, hint='datetime',
                                  locale=get_console_locale(self.env)) \
                       if time else None
        version.update()

    def _do_remove(self, name):
        model.Version(self.env, name).delete()

class AbstractEnumAdminPanel(TicketAdminPanel):

    abstract = True

    _type = 'unknown'
    _enum_cls = None

    # TicketAdminPanel methods

    def _render_admin_panel(self, req, cat, page, path_info):
        label = [gettext(each) for each in self._label]
        data = {'label_singular': label[0], 'label_plural': label[1],
                'type': self._type}

        # Detail view?
        if path_info:
            enum = self._enum_cls(self.env, path_info)
            if req.method == 'POST':
                if req.args.get('save'):
                    enum.name = name = req.args.get('name')
                    try:
                        enum.update()
                    except self.env.db_exc.IntegrityError:
                        raise TracError(_('%(type)s value "%(name)s" already '
                                          'exists', type=label[0], name=name))
                    add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('cancel'):
                    req.redirect(req.href.admin(cat, page))
            data.update({'view': 'detail', 'enum': enum})

        else:
            default = self.config.get('ticket', 'default_%s' % self._type)
            if req.method == 'POST':
                # Add enum
                if req.args.get('add') and req.args.get('name'):
                    name = req.args.get('name')
                    try:
                        enum = self._enum_cls(self.env, name=name)
                    except ResourceNotFound:
                        enum = self._enum_cls(self.env)
                        enum.name = name
                        enum.insert()
                        add_notice(req, _('The %(field)s value "%(name)s" '
                                          'has been added.',
                                          field=label[0], name=name))
                        req.redirect(req.href.admin(cat, page))
                    else:
                        if enum.name is None:
                            raise TracError(_("Invalid %(type)s value.",
                                              type=label[0]))
                        raise TracError(_('%(type)s value "%(name)s" already '
                                          'exists', type=label[0], name=name))

                # Remove enums
                elif req.args.get('remove'):
                    sel = req.args.getlist('sel')
                    if not sel:
                        raise TracError(_("No %s selected") % self._type)
                    with self.env.db_transaction:
                        for name in sel:
                            self._enum_cls(self.env, name).delete()
                            if name == default:
                                self.config.set('ticket',
                                                'default_%s' % self._type, '')
                                self.config.save()
                    add_notice(req, _("The selected %(field)s values have "
                                      "been removed.", field=label[0]))
                    req.redirect(req.href.admin(cat, page))

                # Apply changes
                elif req.args.get('apply'):
                    changed = False

                    # Set default value
                    name = req.args.get('default')
                    if name and name != default:
                        self.log.info("Setting default %s to %s",
                                      self._type, name)
                        self.config.set('ticket', 'default_%s' % self._type,
                                        name)
                        try:
                            self.config.save()
                            changed = True
                        except Exception as e:
                            self.log.error("Error writing to trac.ini: %s",
                                           exception_to_unicode(e))
                            add_warning(req,
                                        _("Error writing to trac.ini, make "
                                          "sure it is writable by the web "
                                          "server. The default value has not "
                                          "been saved."))

                    # Change enum values
                    order = dict([(str(int(key[6:])),
                                   str(int(req.args.get(key)))) for key
                                  in req.args.keys()
                                  if key.startswith('value_')])
                    values = dict([(val, True) for val in order.values()])
                    if len(order) != len(values):
                        raise TracError(_("Order numbers must be unique"))
                    with self.env.db_transaction:
                        for enum in self._enum_cls.select(self.env):
                            new_value = order[enum.value]
                            if new_value != enum.value:
                                enum.value = new_value
                                enum.update()
                                changed = True

                    if changed:
                        add_notice(req, _("Your changes have been saved."))
                    req.redirect(req.href.admin(cat, page))

                # Clear default
                elif req.args.get('clear'):
                    self.log.info("Clearing default %s", self._type)
                    self.config.set('ticket', 'default_%s' % self._type, '')
                    self._save_config(req)
                    req.redirect(req.href.admin(cat, page))

            data.update(dict(enums=list(self._enum_cls.select(self.env)),
                             default=default, view='list'))

        Chrome(self.env).add_jquery_ui(req)
        add_script(req, 'common/js/admin_enums.js')
        return 'admin_enums.html', data

    # IAdminCommandProvider methods

    _command_help = {
        'list': "Show possible ticket %s",
        'add': "Add a %s value option",
        'change': "Change a %s value",
        'remove': "Remove a %s value",
        'order': "Move a %s value up or down in the list",
    }

    def get_admin_commands(self):
        enum_type = getattr(self, '_command_type', self._type)
        label = tuple(each.lower() for each in self._label)
        yield ('%s list' % enum_type, '',
               self._command_help['list'] % label[1],
               None, self._do_list)
        yield ('%s add' % enum_type, '<value>',
               self._command_help['add'] % label[0],
               None, self._do_add)
        yield ('%s change' % enum_type, '<value> <newvalue>',
               self._command_help['change'] % label[0],
               self._complete_change_remove, self._do_change)
        yield ('%s remove' % enum_type, '<value>',
               self._command_help['remove'] % label[0],
               self._complete_change_remove, self._do_remove)
        yield ('%s order' % enum_type, '<value> up|down',
               self._command_help['order'] % label[0],
               self._complete_order, self._do_order)

    def get_enum_list(self):
        return [e.name for e in self._enum_cls.select(self.env)]

    def _complete_change_remove(self, args):
        if len(args) == 1:
            return self.get_enum_list()

    def _complete_order(self, args):
        if len(args) == 1:
            return self.get_enum_list()
        elif len(args) == 2:
            return ['up', 'down']

    def _do_list(self):
        print_table([(e.name,) for e in self._enum_cls.select(self.env)],
                    [_("Possible Values")])

    def _do_add(self, name):
        enum = self._enum_cls(self.env)
        enum.name = name
        enum.insert()

    def _do_change(self, name, newname):
        enum = self._enum_cls(self.env, name)
        enum.name = newname
        enum.update()

    def _do_remove(self, value):
        self._enum_cls(self.env, value).delete()

    def _do_order(self, name, up_down):
        if up_down not in ('up', 'down'):
            raise AdminCommandError(_("Invalid up/down value: %(value)s",
                                      value=up_down))
        direction = -1 if up_down == 'up' else 1
        enum1 = self._enum_cls(self.env, name)
        enum1.value = int(float(enum1.value) + direction)
        for enum2 in self._enum_cls.select(self.env):
            if int(float(enum2.value)) == enum1.value:
                enum2.value = int(float(enum2.value) - direction)
                break
        else:
            return
        with self.env.db_transaction:
            enum1.update()
            enum2.update()

class PriorityAdminPanel(AbstractEnumAdminPanel):
    _type = 'priority'
    _enum_cls = model.Priority
    _label = N_("Priority"), N_("Priorities")

class ResolutionAdminPanel(AbstractEnumAdminPanel):
    _type = 'resolution'
    _enum_cls = model.Resolution
    _label = N_("Resolution"), N_("Resolutions")

class SeverityAdminPanel(AbstractEnumAdminPanel):
    _type = 'severity'
    _enum_cls = model.Severity
    _label = N_("Severity"), N_("Severities")

class TicketTypeAdminPanel(AbstractEnumAdminPanel):
    _type = 'type'
    _enum_cls = model.Type
    _label = N_("Ticket Type"), N_("Ticket Types")

    _command_type = 'ticket_type'
    _command_help = {
        'list': 'Show possible %s',
        'add': 'Add a %s',
        'change': 'Change a %s',
        'remove': 'Remove a %s',
        'order': 'Move a %s up or down in the list',
    }

class TicketAdmin(Component):
    """trac-admin command provider for ticket administration."""

    implements(IAdminCommandProvider)

    # IAdminCommandProvider methods

    def get_admin_commands(self):
        yield ('ticket remove', '<number>', 'Remove ticket',
               None, self._do_remove)

    def _do_remove(self, number):
        try:
            number = int(number)
        except ValueError:
            raise AdminCommandError(_("<number> must be a number"))
        with self.env.db_transaction:
            model.Ticket(self.env, number).delete()
        printout(_("Ticket #%(num)s and all associated data removed.",
                   num=number))


text:
package org.apache.clerezza.implementation.in_memory;

import org.apache.clerezza.*;
import org.apache.clerezza.implementation.graph.AbstractImmutableGraph;
import org.apache.clerezza.implementation.in_memory.SimpleGraph;

import java.util.Iterator;

/**
 * @author reto
 */
public class SimpleImmutableGraph extends AbstractImmutableGraph {

    private Graph graph;

    /**
     * Creates a ImmutableGraph with the triples in Graph
     *
     * @param Graph the collection of triples this ImmutableGraph shall consist of
     */
    public SimpleImmutableGraph(Graph Graph) {
        this.graph = new SimpleGraph(Graph.iterator());
    }

    /**
     * Creates a ImmutableGraph with the triples in Graph.
     * <p>
     * This construction allows to specify if the Graph might change
     * in future. If GraphWillNeverChange is set to true it will
     * assume that the collection never changes, in this case the collection
     * isn't copied making things more efficient.
     *
     * @param Graph                the collection of triples this ImmutableGraph shall consist of
     * @param GraphWillNeverChange true if the caller promises Graph will never change
     */
    public SimpleImmutableGraph(Graph Graph, boolean GraphWillNeverChange) {
        if (!GraphWillNeverChange) {
            this.graph = new SimpleGraph(Graph.iterator());
        } else {
            this.graph = Graph;
        }
    }

    public SimpleImmutableGraph(Iterator<Triple> tripleIter) {
        this.graph = new SimpleGraph(tripleIter);
    }

    @Override
    public int performSize() {
        return graph.size();
    }

    @Override
    public Iterator<Triple> performFilter(BlankNodeOrIRI subject, IRI predicate, RDFTerm object) {
        return graph.filter(subject, predicate, object);
    }
}


text:
class Post < ActiveRecord::Base

  validates :title, :author, presence: true
  validates :title, uniqueness: true

  belongs_to(
    :author,
    class_name: 'User',
    foreign_key: :author_id,
    primary_key: :id
  )

  # belongs_to :sub

  has_many :post_subs
  has_many :subs, through: :post_subs, source: :sub
  has_many :comments
end


text:
package org.sfu.chase.util;

public class Utils {

	public static class Rect
	{
		public Rect() {left = top = width = height = 0;}
		public Rect(float l, float t, float w, float h) {left = l; top = t; width = w; height = h;}
		public Rect clone()
		{
			return new Rect(left, top, width, height);
		}
		public float left() {return left;}
		public float right() {return left + width;}
		public float top() {return top;}
		public float bottom() {return top + height;}
		public float width() {return width;}
		public float height() {return height;}
		public float hcenter() {return left + width/2;}
		public float vcenter() {return top + height/2;}
		public int ileft() {return (int)left;}
		public int iright() {return (int)(left + width);}
		public int itop() {return (int)top;}
		public int ibottom() {return (int)(top + height);}
		public int iwidth() {return (int)width;}
		public int iheight() {return (int)height;}
		public int ihcenter() {return (int)(left + width/2);}
		public int ivcenter() {return (int)(top + height/2);}
		public void setLeft(float l) {left = l;}
		public void setRight(float r) {width = r - left;}
		public void setTop(float t) {top = t;}
		public void setBottom(float b) {height = b - top;}
		public void setWidth(float w) {width = w;}
		public void setHeight(float h) {height = h;}
		public boolean isInside(double x, double y) {return x >= left && x <= right() && y >= top && y <= bottom();}

		private float left, top, width, height;
	}

	public static class Bound2D
	{
		public Bound2D() {xmin = ymin = Double.POSITIVE_INFINITY; xmax = ymax = Double.NEGATIVE_INFINITY;}
		public Bound2D(double _xmin, double _xmax, double _ymin, double _ymax) {xmin = _xmin; ymin = _ymin; xmax = _xmax; ymax = _ymax;}
		public Bound2D clone()
		{
			return new Bound2D(xmin, xmax, ymin, ymax);
		}
		public double dx() {return xmax - xmin;}
		public double dy() {return ymax - ymin;}
		public boolean isInside(double x, double y) {return x >= xmin && x <= xmax && y >= ymin && y <= ymax;}
		public double xmin, xmax;
		public double ymin, ymax;
	}

    public static int[] intSequence(int start, int end, int step)
    {
    	int size = (end - start) / step + 1;
    	if (size <= 0)
    		return null;

    	int[] a= new int[size];
    	for (int i = 0; i < size; ++i)
    	{
    		a[i] = start + i*step;
    	}
    	return a;
    }

    public static double[] subArray (double[] original, int[] indices)
    {
    	double[] a = new double[indices.length];
    	for (int i = 0; i < indices.length; ++i)
    		a[i] = original[indices[i]];
    	return a;
    }

    /**
     * concatenates two arrays
     * @param a   {a[0], ..., a[n-1]}
     * @param b   {b[0], ..., b[m-1]}
     * @return c = {a[0], ..., a[n-1], b[0], ..., b[m-1]}
     */
    public static double[] concatArray(double[] a, double[] b)
    {
    	double[] result = new double[a.length + b.length];
    	System.arraycopy(a, 0, result, 0, a.length);
    	System.arraycopy(b, 0, result, a.length, b.length);
    	return result;
    }

    /**
     * concatenates two arrays
     * @param a   input array: {a[0], ..., a[n-1]}
     * @param b   input array: {b[0], ..., b[m-1]}
     * @return    new output array: c = {a[0], ..., a[n-1], b[0], ..., b[m-1]}
     */
    public static int[] concatArray(int[] a, int[] b)
    {
    	int[] result = new int[a.length + b.length];
    	System.arraycopy(a, 0, result, 0, a.length);
    	System.arraycopy(b, 0, result, a.length, b.length);
    	return result;
    }

    /**
     * returns element-wise addition of two arrays
     * @param a  input array
     * @param b  input array
     * @return   new output array: c[i] = a[i] + b[i]
     */
    public static double[] sumArray(double[] a, double[] b)
    {
    	if (a.length != b.length)
    		return null;

    	double[] result = new double[a.length];
    	for (int i = 0; i < a.length; ++i)
    		result[i] = a[i] + b[i];
    	return result;
    }

    /**
     * returns element-wise multiplication of an array with a scalar
     * @param a    input array
     * @param m    multiplicant
     * @return     new output array: c[i] = m * a[i]
     */
    public static double[] multArray(double[] a, double m)
    {
    	double[] result = new double[a.length];
    	for (int i = 0; i < a.length; ++i)
    		result[i] = a[i] * m;
    	return result;
    }

    /**
     * clamps the array elements between a min an max value
     * @param a     input array
     * @param min   min value to clamp against
     * @param max   max value to clamp against
     * @return      reference to input array
     */
    public static double[] clampArray(double[] a, double min, double max)
    {
    	for (int i = 0; i < a.length; ++i)
    		a[i] = Math.min(Math.max(a[i], min), max);
    	return a;
    }

    /**
     * Reverses the array elements
     * @param a     input array
     * @return      reference to input array
     */
    public static double[] reverseArray(double[] a)
    {
    	for (int i = 0; i < a.length / 2; ++i)
    	{
    		double tmp = a[i];
    		a[i] = a[a.length - i - 1];
    		a[a.length - i - 1] = tmp;
    	}
    	return a;
    }

    /*
    @SuppressWarnings("unchecked")
    public static <T> T[] concat(T[] a, T[] b) {
        final int alen = a.length;
        final int blen = b.length;
        final T[] result = (T[]) java.lang.reflect.Array.
                newInstance(a.getClass().getComponentType(), alen + blen);
        System.arraycopy(a, 0, result, 0, alen);
        System.arraycopy(b, 0, result, alen, blen);
        return result;
    }
    */

}


text:
namespace wissbi {
namespace io_policy {

template <class policy> class Tee {
public:
  Tee() {}

  ~Tee() {}

  bool Put(const MsgBuf &msg) {
    last_tee_count_ = 0;
    last_failed_count_ = 0;
    for (auto kv : branch_map_) {
      ++last_tee_count_;
      if (!kv.second->Put(msg)) {
        ++last_failed_count_;
      }
    }
    return true;
  }

  bool Get(MsgBuf *msg_ptr) {}

  void AddBranch(const std::string &branch_name,
                 std::shared_ptr<policy> branch_ptr) {
    branch_map_[branch_name] = branch_ptr;
  }

  void RemoveBranch(const std::string &branch_name) {
    branch_map_.erase(branch_name);
  }

  bool ExistsBranch(const std::string &branch_name) {
    return branch_map_.find(branch_name) != branch_map_.end();
  }

  int GetBranchCount() { return branch_map_.size(); }

  int GetLastTeeCount() { return last_tee_count_; }

  int GetLastFailedCount() { return last_failed_count_; }

private:
  std::unordered_map<std::string, std::shared_ptr<policy> > branch_map_;
  int last_tee_count_;
  int last_failed_count_;
};

}
}

#endif // WISSBI_IO_POLICY_TEE_HPP_


text:
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Microsoft.CodeAnalysis.CSharp.Structure.MetadataAsSource
{
    internal class MetadataIndexerDeclarationStructureProvider : AbstractMetadataAsSourceStructureProvider<IndexerDeclarationSyntax>
    {
        protected override SyntaxToken GetEndToken(IndexerDeclarationSyntax node)
        {
            return node.Modifiers.Count > 0
                    ? node.Modifiers.First()
                    : node.Type.GetFirstToken();
        }
    }
}


text:
autocommit off;
create view boo as select * from joe.faculty where ssn > 5 with check option;
insert into boo(ssn) values(1);
rollback;


text:
// Copyright 2012 Ofir Picazo. All Rights Reserved.

/**
 * @fileoverview Constants used across the game.
 *
 * @author ofirpicazo@gmail.com (Ofir Picazo)
 */

goog.provide('solitario.game.constants');

/**
 * Constants for card sizes.
 * @enum {number}
 * @const
 */
solitario.game.constants.Card = {
  HEIGHT: 14,
  WIDTH: 10
};

/**
 * Possible values for the color of the cards.
 * @enum {string}
 * @const
 */
solitario.game.constants.CardColor = {
  BLACK: 'black',
  RED: 'red'
};

/**
 * Representation of the number associated to each card.
 * @enum {string}
 * @const
 */
solitario.game.constants.CardNumber = {
  ACE: 'A',
  TWO: '2',
  THREE: '3',
  FOUR: '4',
  FIVE: '5',
  SIX: '6',
  SEVEN: '7',
  EIGHT: '8',
  NINE: '9',
  TEN: '10',
  JACK: 'J',
  QUEEN: 'Q',
  KING: 'K'
};

/**
 * Numeric values for each card number.
 * @type {Object.<string, number>}
 * @const
 */
solitario.game.constants.CardValue = {
  'A': 1,
  '2': 2,
  '3': 3,
  '4': 4,
  '5': 5,
  '6': 6,
  '7': 7,
  '8': 8,
  '9': 9,
  '10': 10,
  'J': 11,
  'Q': 12,
  'K': 13
};

/**
 * Duration of CSS game animations in milliseconds, keep in sync with
 * _cards.scss
 * @type {number}
 * @const
 */
solitario.game.constants.CARD_ANIMATION_DURATION = 300;

/**
 * Duration of the delay between cards when dropping them as a group. The value
 * is in milliseconds.
 * @type {number}
 * @const
 */
solitario.game.constants.CARD_GROUP_DROP_ANIMATION_DURATION = 20;

/**
 * Class names used in the various object.
 * @enum {string}
 * @const
 */
solitario.game.constants.ClassNames = {
  DRAGGING: 'dragging',
  NO_ANIMATION: 'no-animation'
};

/**
 * Custom events used in the game.
 * @enum {string}
 * @const
 */
solitario.game.constants.Events = {
  BUILD: 'build',
  DRAG_END: 'dragEnd',
  DRAG_MOVE: 'dragMove',
  DRAG_START: 'dragStart',
  GROUP_DRAG_END: 'groupDragEnd',
  GROUP_DRAG_MOVE: 'groupDragMove',
  GROUP_DRAG_START: 'groupDragStart',
  READY: 'ready',
  RESTOCK: 'restock',
  STOCK_TAKEN: 'stockTaken',
  TABLEU_REVEAL: 'tableuReveal'
};

/**
 * Maximum ZIndex level, things set to this value will always be visible.
 * @type {number}
 * @const
 */
solitario.game.constants.MAX_ZINDEX = 1000;

/**
 * Types of piles (children of solitario.game.Pile) used in the game.
 * @enum {string}
 * @const
 */
solitario.game.constants.PileTypes = {
  FOUNDATION: 'foundation',
  STOCK: 'stock',
  TABLEU: 'tableu',
  WASTE: 'waste'
};

/**
 * Score values for different moves in the game.
 * @enum {number}
 * @const
 */
solitario.game.constants.Scoring = {
  FOUNDATION_TO_TABLEU: -15,
  RESTOCK: -100,
  TABLEU_REVEAL: 5,
  TABLEU_TO_FOUNDATION: 10,
  WASTE_TO_FOUNDATION: 10,
  WASTE_TO_TABLEU: 5
};

/**
 * Card suits used in the game.
 * @enum {string}
 * @const
 */
solitario.game.constants.SUIT = {
  CLUB: 'club',
  DIAMOND: 'diamond',
  HEAD: 'heart',
  SPADE: 'spade'
};

/**
 * The relative distance (ems) between each hidden card in the Tableu.
 * @type {number}
 * @const
 */
solitario.game.constants.TABLEU_INTERCARD_DISTANCE_HIDDEN = 0.8;

/**
 * The relative distance (ems) between each revealed card in the Tableu.
 * @type {number}
 * @const
 */
solitario.game.constants.TABLEU_INTERCARD_DISTANCE_REVEALED = 2.2;


text:
<?php
// David's custom plugins controller
class PluginController extends Controller
{
	public function actions()
	{
		$id = "";
		$plugin = substr(Yii::app()->getRequest()->getRequestUri(),8);
		if(strstr($plugin, '?'))
			list($plugin, $vars) = explode('?', $plugin);
		if(strstr($plugin, '/')){
			$segment = explode('/', $plugin);
			$plugin = $segment[0];
			$method = $segment[1];
			if(isset($segment[2]))
				$id = $segment[2];
		}else{
			$method = "";
		}
		return array(
			$plugin=>array(
				'class'=>'plugins.'.$plugin,
				'method'=>$method,
				'id'=>$id,
			)
		);
	}

}


text:
| Topic    | Value
| :--      | :--
| Id       | GU0080
| Severity | Warning
| Enabled  | True
| Category | Gu.Analyzers.Correctness
| Code     | [TestMethodAnalyzer](https://github.com/DotNetAnalyzers/Gu.Analyzers/blob/master/Gu.Analyzers/Analyzers/TestMethodAnalyzer.cs)

## Description

Parameter count does not match attribute.

## Motivation

ADD MOTIVATION HERE

## How to fix violations

ADD HOW TO FIX VIOLATIONS HERE

<!-- start generated config severity -->
## Configure severity

### Via ruleset file.

Configure the severity per project, for more info see [MSDN](https://msdn.microsoft.com/en-us/library/dd264949.aspx).

### Via #pragma directive.
```C#
#pragma warning disable GU0080 // Parameter count does not match attribute.
Code violating the rule here
#pragma warning restore GU0080 // Parameter count does not match attribute.
```

Or put this at the top of the file to disable all instances.
```C#
#pragma warning disable GU0080 // Parameter count does not match attribute.
```

### Via attribute `[SuppressMessage]`.

```C#
[System.Diagnostics.CodeAnalysis.SuppressMessage("Gu.Analyzers.Correctness",
    "GU0080:Parameter count does not match attribute.",
    Justification = "Reason...")]
```
<!-- end generated config severity -->


text:
#ifndef OBDREF_DEBUG_H
#define OBDREF_DEBUG_H

#include <QObject>
#include <QMutex>
#include <QIODevice>
#include <QTextStream>
#include <QElapsedTimer>
#include <QList>

namespace obdref
{

class DebugBroadcast : public QObject
{
    Q_OBJECT

public:
    explicit DebugBroadcast(QObject * parent=0);
    ~DebugBroadcast();

    qint64 msElapsed();

signals:
    void debug(QString timestamp,QString msg);

private:
    QElapsedTimer m_timer;
};

class Debug
{
public:
    Debug();
    ~Debug();

    QTextStream * m_stream;

private:
    QByteArray m_byteArray;
    QList<QByteArray> m_listHexCodes;
};

class DebugBlackHole
{
public:
    template<typename T>
    DebugBlackHole& operator << (T const & spaceShip);
};

extern DebugBroadcast * g_debug_broadcast;

}

#ifdef OBDREF_DEBUG_BROADCAST
#define OBDREFDEBUG    (*(obdref::Debug().m_stream))
#endif

#ifdef OBDREF_DEBUG_QDEBUG
#define OBDREFDEBUG    qDebug() << "OBDREF:"
#endif

#ifdef OBDREF_DEBUG_NONE
#define OBDREFDEBUG    obdref::DebugBlackHole()
#endif

#endif // OBDREF_DEBUG_H