text:
package com.afollestad.silk.http;

import android.content.Context;
import android.os.Handler;
import ch.boye.httpclientandroidlib.client.methods.HttpDelete;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.client.methods.HttpPost;
import ch.boye.httpclientandroidlib.client.methods.HttpPut;

/**
 * A Apache HTTP Client wrapper that makes http faster and easier.
 *
 * @author Aidan Follestad (afollestad)
 */
public class SilkHttpClient extends SilkHttpBase {

    public interface ResponseProcessor {
        public void onProcessError(SilkHttpException exception) throws Exception;
    }

    private String mHost;

    /**
     * Initializes a new SilkHttpClient.
     */
    public SilkHttpClient(Context context) {
        super(context);
    }

    /**
     * Initializes a new SilkHttpClient.
     *
     * @param handler The handler used to post to a thread for async callbacks.
     */
    public SilkHttpClient(Context context, Handler handler) {
        super(context, handler);
    }

    private String getUrl(String url) {
        if ((url == null || url.trim().isEmpty()) && (mHost == null || mHost.trim().isEmpty()))
            throw new RuntimeException("The URL cannot be null.");
        if (mHost != null) {
            if (url == null) return mHost;
            if (!url.startsWith("/")) url = "/" + url;
            return mHost + url;
        }
        return url;
    }

    /**
     * Sets a host that is automatically put before every request's URL or used as a request's URL if a null string is passed
     * to GET/POST/PUT/DELETE...
     */
    public SilkHttpClient setHost(String host) {
        if (host != null) {
            host = host.trim();
            if (host.isEmpty()) host = null;
            else {
                if (host.endsWith("/"))
                    host = host.substring(0, host.length() - 1);
                if (!host.startsWith("http://") && !host.startsWith("https://"))
                    host = "http://" + host;
            }
        }
        mHost = host;
        return this;
    }

    /**
     * Adds an HTTP header to the client, which will be used for the next request. Headers are cleared after a request is performed.
     */
    public SilkHttpClient addHeader(SilkHttpHeader header) {
        super.mHeaders.add(header);
        return this;
    }

    /**
     * Adds an HTTP header to the client, which will be used for the next request. Headers are cleared after a request is performed.
     */
    public SilkHttpClient addHeader(String name, String value) {
        if (name == null || name.trim().isEmpty())
            throw new RuntimeException("The header name cannot be null.");
        addHeader(new SilkHttpHeader(name, value));
        return this;
    }

    /**
     * Makes a GET request on the calling thread.
     */
    public SilkHttpResponse get(String url) throws Exception {
        return performRequest(new HttpGet(getUrl(url)));
    }

    /**
     * Makes a POST request on the calling thread.
     */
    public SilkHttpResponse post(String url) throws Exception {
        return post(url, null);
    }

    /**
     * Makes a POST request on the calling thread, with a POST entity (body).
     */
    public SilkHttpResponse post(String url, SilkHttpBody body) throws Exception {
        HttpPost post = new HttpPost(getUrl(url));
        if (body != null) post.setEntity(body.getEntity());
        return performRequest(post);
    }

    /**
     * Makes a PUT request on the calling thread.
     */
    public SilkHttpResponse put(String url) throws Exception {
        return put(url, null);
    }

    /**
     * Makes a GET request on the calling thread, with a PUT entity (body).
     */
    public SilkHttpResponse put(String url, SilkHttpBody body) throws Exception {
        HttpPut post = new HttpPut(getUrl(url));
        if (body != null) post.setEntity(body.getEntity());
        return performRequest(post);
    }

    /**
     * Makes a DELETE request on the calling thread.
     */
    public SilkHttpResponse delete(String url) throws Exception {
        return performRequest(new HttpDelete(getUrl(url)));
    }

    // Async methods

    /**
     * Makes a GET request from a separate thread and posts the results to a callback.
     */
    public void getAsync(final String url, final SilkHttpCallback callback) {
        if (callback == null) throw new IllegalArgumentException("The callback cannot be null.");
        runOnPriorityThread(new Runnable() {
            @Override
            public void run() {
                try {
                    final SilkHttpResponse response = get(url);
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onComplete(response);
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(e);
                        }
                    });
                }
            }
        });
    }

    /**
     * Makes a POST request from a separate thread and posts the results to a callback.
     */
    public void postAsync(String url, SilkHttpCallback callback) {
        if (callback == null) throw new IllegalArgumentException("The callback cannot be null.");
        postAsync(url, null, callback);
    }

    /**
     * Makes a POST request from a separate thread (with a POST entity, or body) and posts the results to a callback.
     */
    public void postAsync(final String url, final SilkHttpBody body, final SilkHttpCallback callback) {
        if (callback == null) throw new IllegalArgumentException("The callback cannot be null.");
        runOnPriorityThread(new Runnable() {
            @Override
            public void run() {
                try {
                    final SilkHttpResponse response = post(url, body);
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onComplete(response);
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(e);
                        }
                    });
                }
            }
        });
    }

    /**
     * Makes a PUT request from a separate thread and posts the results to a callback.
     */
    public void putAsync(String url, SilkHttpCallback callback) {
        if (callback == null) throw new IllegalArgumentException("The callback cannot be null.");
        putAsync(url, null, callback);
    }

    /**
     * Makes a PUT request from a separate thread (with a PUT entity, or body) and posts the results to a callback.
     */
    public void putAsync(final String url, final SilkHttpBody body, final SilkHttpCallback callback) {
        if (callback == null) throw new IllegalArgumentException("The callback cannot be null.");
        runOnPriorityThread(new Runnable() {
            @Override
            public void run() {
                try {
                    final SilkHttpResponse response = put(url, body);
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onComplete(response);
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(e);
                        }
                    });
                }
            }
        });
    }

    /**
     * Makes a DELETE request from a separate thread and posts the results to a callback.
     */
    public void deleteAsync(final String url, final SilkHttpCallback callback) {
        if (callback == null) throw new IllegalArgumentException("The callback cannot be null.");
        runOnPriorityThread(new Runnable() {
            @Override
            public void run() {
                try {
                    final SilkHttpResponse response = delete(url);
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onComplete(response);
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(e);
                        }
                    });
                }
            }
        });
    }
}


text:
require 'spec_helper'

describe <%= class_name %>Controller do
  subject { response }
<% for action in actions -%>

  describe 'GET :<%= action %>' do
    before { get(:<%= action %>) }

    it { should be_success }
    it { should render_template(:<%= action %>) }
  end
<% end -%>
end

redpajama_set_name: RedPajamaGithub


text:
/* Auto generated file: with makeref.py .  Docs go in src/ *.doc . */
#define DOC_PYGAMECURSORS "pygame module for cursor resources"

#define DOC_PYGAMECURSORSCOMPILE "compile(strings, black='X', white='.', xor='o') -> data, mask\ncreate binary cursor data from simple strings"

#define DOC_PYGAMECURSORSLOADXBM "load_xbm(cursorfile) -> cursor_args\nload_xbm(cursorfile, maskfile) -> cursor_args\nload cursor data from an xbm file"

/* Docs in a comment... slightly easier to read. */

/*

pygame.cursors
pygame module for cursor resources

pygame.cursors.compile
 compile(strings, black='X', white='.', xor='o') -> data, mask
create binary cursor data from simple strings

pygame.cursors.load_xbm
 load_xbm(cursorfile) -> cursor_args
 load_xbm(cursorfile, maskfile) -> cursor_args
load cursor data from an xbm file

*/


text:
package networkserver

import (
	pb_broker "github.com/TheThingsNetwork/api/broker"
	"github.com/TheThingsNetwork/ttn/core/networkserver/device"
)

func (n *networkServer) handleDownlinkMAC(message *pb_broker.DownlinkMessage, dev *device.Device) error {
	if err := n.handleDownlinkADR(message, dev); err != nil {
		return err
	}
	return nil
}


text:
<?php

namespace components\app;
use KZ\db;

/**
 * Class Registry
 * @package app
 *
 * Following properties are available via magic methods (get/set):
 * @property \PDO $mysql
 *
 */
class Registry extends \KZ\app\Registry
{
	/**
	 * @return \PDO
	 */
	public function getMysql()
	{
		$mysql = $this->getConnectionStorage()->getByType(db\interfaces\ConnectionStorage::MYSQL);

		if (!$mysql)
			return null;

		return $mysql[array_keys($mysql)[0]];
	}
}


text:
You can choose to
* Run kube-bench from inside a container (sharing PID namespace with the host). See [Running inside a container](./running.md#running-inside-a-container) for additional details.
* Run a container that installs kube-bench on the host, and then run kube-bench directly on the host. See [Installing from a container](#installing-from-a-container) for additional details.
* install the latest binaries from the [Releases page](https://github.com/aquasecurity/kube-bench/releases), though please note that you also need to download the config and test files from the `cfg` directory. See [Download and Install binaries](#download-and-install-binaries) for details.
* Compile it from source. See [Installing from sources](#installing-from-sources) for details.

### Download and Install binaries

It is possible to manually install and run kube-bench release binaries. In order to do that, you must have access to your Kubernetes cluster nodes. Note that if you're using one of the managed Kubernetes services (e.g. EKS, AKS, GKE, ACK, OCP), you will not have access to the master nodes of your cluster and you can't perform any tests on the master nodes.

First, log into one of the nodes using SSH.

Install kube-bench binary for your platform using the commands below. Note that there may be newer releases available. See [releases page](https://github.com/aquasecurity/kube-bench/releases).

Ubuntu/Debian:

```
curl -L https://github.com/aquasecurity/kube-bench/releases/download/v0.6.2/kube-bench_0.6.2_linux_amd64.deb -o kube-bench_0.6.2_linux_amd64.deb

sudo apt install ./kube-bench_0.6.2_linux_amd64.deb -f
```

RHEL:

```
curl -L https://github.com/aquasecurity/kube-bench/releases/download/v0.6.2/kube-bench_0.6.2_linux_amd64.rpm -o kube-bench_0.6.2_linux_amd64.rpm

sudo yum install kube-bench_0.6.2_linux_amd64.rpm -y
```

Alternatively, you can manually download and extract the kube-bench binary:

```
curl -L https://github.com/aquasecurity/kube-bench/releases/download/v0.6.2/kube-bench_0.6.2_linux_amd64.tar.gz -o kube-bench_0.6.2_linux_amd64.tar.gz

tar -xvf kube-bench_0.6.2_linux_amd64.tar.gz
```

You can then run kube-bench directly:
```
kube-bench
```

If you manually downloaded the kube-bench binary (using curl command above), you have to specify the location of configuration directory and file. For example:
```
./kube-bench --config-dir `pwd`/cfg --config `pwd`/cfg/config.yaml
```

See previous section on [Running kube-bench](./running.md#running-kube-bench) for further details on using the kube-bench binary.

### Installing from sources

If Go is installed on the target machines, you can simply clone this repository and run as follows (assuming your [`GOPATH` is set](https://github.com/golang/go/wiki/GOPATH)) as per this example:

```shell
# Create a target directory for the clone, inside the $GOPATH
mkdir -p $GOPATH/src/github.com/aquasecurity/kube-bench

# Clone this repository, using SSH
git clone git@github.com:aquasecurity/kube-bench.git $GOPATH/src/github.com/aquasecurity/kube-bench

# Install the pre-requisites
go get github.com/aquasecurity/kube-bench

# Change to the kube-bench directory
cd $GOPATH/src/github.com/aquasecurity/kube-bench

# Build the kube-bench binary
go build -o kube-bench .

# See all supported options
./kube-bench --help

# Run all checks
./kube-bench
```

### Installing from a container

This command copies the kube-bench binary and configuration files to your host from the Docker container:
**binaries compiled for linux-x86-64 only (so they won't run on macOS or Windows)**
```
docker run --rm -v `pwd`:/host docker.io/aquasec/kube-bench:latest install
```

You can then run `./kube-bench`.


text:
package org.museautomation.extensions.install;

import org.museautomation.extensions.registry.*;

import java.io.*;

/**
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
public class ExtensionUninstallers
    {
    public static ExtensionUninstaller findUninstaller(ExtensionRegistryEntry entry, File folder)
        {
        return new DeleteFilesUninstaller();
        }
    }


text:
package test.ssl;

import java.io.InputStream;
import java.net.Socket;
import java.net.URL;

import nl.uva.vlet.net.ssl.CertificateStore;
import nl.uva.vlet.net.ssl.SslUtil;

public class TestSSLtoLB
{

    public static void main(String args[])
    {
        SslUtil.init();

        CertificateStore certStore;

        try
        {
            certStore = CertificateStore.getDefault();
            certStore.addPEMCertificate("/home/ptdeboer/.vletrc/certificates/16da7552.0",true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        testSSLv3();
        testSSL();
        testURL();
    }

    public static void testSSLv3()
    {
        try
        {
            Socket socket = SslUtil.openSSLv3Socket("wms.grid.sara.nl",9000);
            InputStream inps=socket.getInputStream();
            inps.close();

            socket.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public static void testSSL()
    {
        try
        {
            Socket socket = SslUtil.openSSLSocket("wms.grid.sara.nl",9000);
            InputStream inps=socket.getInputStream();
            inps.close();

            socket.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public static void testURL()
    {
        try
        {
            URL url=new URL("https://wms.grid.sara.nl:9000");
            url.openConnection().connect();
            Object cont = url.getContent();

            System.out.println("URL Connection ok?\ncontent="+cont);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}


text:
class AddAccountRoleRefToAccount < ActiveRecord::Migration

  def self.up
    add_reference :accounts, :account_role, index: true

    # Create Account Roles
    roles = AccountRole::ROLES.map(&:to_s).map(&:titlecase)
    roles.each {|n| AccountRole.find_or_create_by(name: n)}

    # Assign default Account Roles
    Account.where(account_role:nil).each do |a|
      a.account_role = AccountRole.get(:basic)
      a.save
    end
  end

  def self.down
    remove_reference :accounts, :account_role
  end

end


text:
package org.jvnet.hudson.test;

import hudson.Extension;
import hudson.ExtensionFinder.GuiceExtensionAnnotation;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Loads {@link TestExtension}s.
 *
 * @author Kohsuke Kawaguchi
 */
@Extension
public class TestExtensionLoader extends GuiceExtensionAnnotation<TestExtension> {
    public TestExtensionLoader() {
        super(TestExtension.class);
    }

    @Override
    protected boolean isOptional(TestExtension annotation) {
        return false;
    }

    @Override
    protected double getOrdinal(TestExtension annotation) {
        return 0;
    }

    @Override
    protected boolean isActive(AnnotatedElement e) {
        TestEnvironment env = TestEnvironment.get();

        TestExtension a = e.getAnnotation(TestExtension.class);
        if (a==null)        return false;   // stale index
        String testName = a.value();
        if (testName.length()>0 && env!=null && env.testCase!=null && !env.testCase.getName().equals(testName))
            return false;   // doesn't apply to this test

        if (e instanceof Class) {
            return isActive(env, (Class)e);
        }
        if (e instanceof Field) {
            Field f = (Field) e;
            return f.getDeclaringClass().isInstance(env.testCase);
        }
        if (e instanceof Method) {
            Method m = (Method) e;
            return m.getDeclaringClass().isInstance(env.testCase);
        }
        return false;
    }

    private boolean isActive(TestEnvironment env, Class<?> extType) {
        if (env == null || env.testCase == null)
            return false;
        for (Class<?> outer = extType; outer!=null; outer=outer.getEnclosingClass())
            if (outer.isInstance(env.testCase))
                return true;      // enclosed
        return false;
    }
}


text:
package bdv.tools.brightness;

import net.imglib2.type.numeric.ARGBType;

import org.scijava.listeners.Listeners;

import bdv.viewer.RequestRepaint;
import mpicbg.spim.data.generic.sequence.BasicViewSetup;

/**
 * Modify the range and color of the converter for a source. Because each source
 * can have its own converter, this is used to adjust brightness, contrast, and
 * color of individual sources.
 *
 * @author Tobias Pietzsch
 */
public interface ConverterSetup
{
	/**
	 * {@link SetupChangeListener}s are notified about changes to a
	 * {@code ConverterSetup}.
	 */
	interface SetupChangeListener
	{
		void setupParametersChanged( ConverterSetup setup );
	}

	/**
	 * {@code SetupChangeListener}s can be added/removed here, and will be
	 * notified about changes to this {@code ConverterSetup}.
	 */
	Listeners< SetupChangeListener > setupChangeListeners();

	/**
	 * Get the id of the {@link BasicViewSetup} this converter acts on.
	 *
	 * @return the id of the {@link BasicViewSetup} this converter acts on.
	 */
	int getSetupId();

	/**
	 * Set the range of source values that is mapped to the full range of the
	 * target type. Source values outside of the specified range are clamped.
	 *
	 * @param min
	 * 		source value to map to minimum of the target range.
	 * @param max
	 * 		source value to map to maximum of the target range.
	 */
	void setDisplayRange( double min, double max );

	/**
	 * Set the color for this converter.
	 */
	void setColor( ARGBType color );

	boolean supportsColor();

	/**
	 * Get the (largest) source value that is mapped to the minimum of the
	 * target range.
	 *
	 * @return source value that is mapped to the minimum of the target range.
	 */
	double getDisplayRangeMin();

	/**
	 * Get the (smallest) source value that is mapped to the maximum of the
	 * target range.
	 *
	 * @return source value that is mapped to the maximum of the target range.
	 */
	double getDisplayRangeMax();

	/**
	 * Get the color for this converter.
	 *
	 * @return the color for this converter.
	 */
	ARGBType getColor();

	/**
	 * Deprecated: Use "{@code setupChangeListeners().add( s -> viewer.requestRepaint() )}" instead.
	 * <p>
	 * Set the {@link RequestRepaint} that should be notified if
	 * {@link ConverterSetup} settings change.
	 *
	 * @param viewer
	 */
	@Deprecated
	default void setViewer( RequestRepaint viewer )
	{
		setupChangeListeners().add( s -> viewer.requestRepaint() );
	}
}


text:
enum {
  kGTMFileSystemKQueueDeleteEvent = NOTE_DELETE,
  kGTMFileSystemKQueueWriteEvent = NOTE_WRITE,
  kGTMFileSystemKQueueExtendEvent = NOTE_EXTEND,
  kGTMFileSystemKQueueAttributeChangeEvent = NOTE_ATTRIB,
  kGTMFileSystemKQueueLinkChangeEvent = NOTE_LINK,
  kGTMFileSystemKQueueRenameEvent = NOTE_RENAME,
  kGTMFileSystemKQueueRevokeEvent = NOTE_REVOKE,
  kGTMFileSystemKQueueAllEvents = NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND |
                                  NOTE_ATTRIB | NOTE_LINK | NOTE_RENAME |
                                  NOTE_REVOKE,
};
typedef unsigned int GTMFileSystemKQueueEvents;

// GTMFileSystemKQueue.
//
// This is a very simple, easy-to-use class for registering handlers that get
// called when a events happen to a given file system path.
//
// The default runloop for the first path kqueued is used for notification
// delivery, so keep that in mind when you're using this class.  This class
// explicitly does not handle arbitrary runloops and threading.
//
@interface GTMFileSystemKQueue : NSObject {
 @private
  NSString *path_;
  int fd_;
  GTMFileSystemKQueueEvents events_;
  BOOL acrossReplace_;
  __weak id target_;
  SEL action_;
}

// |path| is the full path to monitor.  |events| is a combination of events
// listed above that you want notification of.  |acrossReplace| will cause this
// object to reattach when a the file is deleted & recreated or moved out of the
// way and a new one put in place.  |selector| should be of the signature:
//    - (void)fileSystemKQueue:(GTMFileSystemKQueue *)fskq
//                      events:(GTMFileSystemKQueueEvents)events;
// where the events can be one or more of the events listed above ORed together.
//
// NOTE: |acrossReplace| is not fool proof.  If the file is renamed/deleted,
// then the object will make one attempt at the time it gets the rename/delete
// to reopen the file.  If the new file has not been created, no more action is
// taken.  To handle the file coming into existance later, you need to monitor
// the directory in some other way.
- (id)initWithPath:(NSString *)path
         forEvents:(GTMFileSystemKQueueEvents)events
     acrossReplace:(BOOL)acrossReplace
            target:(id)target
            action:(SEL)action;

- (NSString *)path;

@end


text:
package com.amazonaws.services.simpledb.model.transform;

import org.w3c.dom.Node;
import javax.annotation.Generated;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.util.XpathUtils;
import com.amazonaws.transform.LegacyErrorUnmarshaller;

import com.amazonaws.services.simpledb.model.DuplicateItemNameException;

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DuplicateItemNameExceptionUnmarshaller extends LegacyErrorUnmarshaller {

    public DuplicateItemNameExceptionUnmarshaller() {
        super(DuplicateItemNameException.class);
    }

    @Override
    public AmazonServiceException unmarshall(Node node) throws Exception {
        // Bail out if this isn't the right error code that this
        // marshaller understands
        String errorCode = parseErrorCode(node);
        if (errorCode == null || !errorCode.equals("DuplicateItemName"))
            return null;

        DuplicateItemNameException e = (DuplicateItemNameException) super.unmarshall(node);
        e.setBoxUsage(XpathUtils.asFloat(getErrorPropertyPath("BoxUsage"), node));

        return e;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="issues">
    <option name="index">
      <map>
        <entry key="/Dummy.groovy">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/README.md">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/build.gradle">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/main/java/it/lisik/springutils/RevocationRequest.java">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/main/java/it/lisik/springutils/RevokationRequest.java">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/main/java/it/lisik/springutils/RevokeTokenEndpoint.java">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/main/java/it/lisik/springutils/TokenType.java">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/test/groovy/TokenRevocationITest.groovy">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/test/java/it/lisik/springutils/DemoApplicationTests.java">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/test/java/it/lisik/springutils/OAuth2Config.java">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/test/java/it/lisik/springutils/TestApplication.java">
          <value>
            <set />
          </value>
        </entry>
        <entry key="$PROJECT_DIR$/src/test/resources/application-test.properties">
          <value>
            <set />
          </value>
        </entry>
        <entry key="/fragment.java">
          <value>
            <set />
          </value>
        </entry>
      </map>
    </option>
  </component>
</project>


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: David Weese <david.weese@fu-berlin.de>
// ==========================================================================

#ifndef SEQAN_HEADER_MODIFIER_SHORTCUTS_H
#define SEQAN_HEADER_MODIFIER_SHORTCUTS_H

namespace seqan
{

// ==========================================================================
// Shortcuts for Modified Strings.
// ==========================================================================

/**
.Shortcut.ModComplementDna:
..cat:Modifier
..summary:Modifier specialization type for the complement of @Spec.Dna@ alphabet sequences.
..signature:DnaStringComplement
..shortcutfor:Spec.ModView
...signature:ModView< FunctorComplement<Dna> >
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/**
.Shortcut.ModComplementDna5:
..cat:Modifier
..summary:Modifier specialization type for the complement of @Spec.Dna5@ alphabet sequences.
..signature:Dna5StringComplement
..shortcutfor:Spec.ModView
...signature:ModView< FunctorComplement<Dna5> >
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/**
.Shortcut.ModComplementRna:
..cat:Modifier
..summary:Modifier specialization type for the complement of @Spec.Rna@ alphabet sequences.
..signature:RnaStringComplement
..shortcutfor:Spec.ModView
...signature:ModView< FunctorComplement<Rna> >
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/**
.Shortcut.ModComplementRna5:
..cat:Modifier
..summary:Modifier specialization type for the complement of @Spec.Rna5@ alphabet sequences.
..signature:Rna5StringComplement
..shortcutfor:Spec.ModView
...signature:ModView< FunctorComplement<Rna5> >
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/*!
 * @typedef DnaStringComplement
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the complement of DnaString.
 *
 * @signature typedef ModifiedString<DnaString, ModView<FunctorComplementDna> > > DnaStringComplement;
 */

/**
.Shortcut.DnaStringComplement:
..cat:Modifier
..summary:Modifier for the complement of a @Shortcut.DnaString@.
..signature:DnaStringComplement
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<DnaString, ModView< FunctorComplement<Dna> > >
..see:Shortcut.DnaString
..see:Class.ModifiedString
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/*!
 * @typedef Dna5StringComplement
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the complement of Dna5String.
 *
 * @signature typedef ModifiedString<Dna5String, ModView<FunctorComplementDna> > > DnaStringComplement;
 */

/**
.Shortcut.Dna5StringComplement:
..cat:Modifier
..summary:Modifier for the complement of a @Shortcut.Dna5String@.
..signature:Dna5StringComplement
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<Dna5String, ModView< FunctorComplement<Dna5> > >
..see:Shortcut.Dna5String
..see:Class.ModifiedString
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/*!
 * @typedef RnaStringComplement
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the complement of RnaString.
 *
 * @signature typedef ModifiedString<RnaString, ModView<FunctorComplementDna> > > DnaStringComplement;
 */

/**
.Shortcut.RnaStringComplement:
..cat:Modifier
..summary:Modifier for the complement of a @Shortcut.RnaString@.
..signature:RnaStringComplement
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<RnaString, ModView< FunctorComplement<Rna> > >
..see:Shortcut.RnaString
..see:Class.ModifiedString
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/*!
 * @typedef Rna5StringComplement
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the complement of Rna5String.
 *
 * @signature typedef ModifiedString<Rna5String, ModView<FunctorComplementDna> > > DnaStringComplement;
 */

/**
.Shortcut.Rna5StringComplement:
..cat:Modifier
..summary:Modifier for the complement of a @Shortcut.Rna5String@.
..signature:Rna5StringComplement
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<Rna5String, ModView< FunctorComplement<Rna5> > >
..see:Shortcut.Rna5String
..see:Class.ModifiedString
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/*!
 * @typedef DnaStringReverse
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the reverse of a DnaString.
 *
 * @signature typedef ModifiedString<DnaString, ModReverse> DnaStringReverse;
 */

/**
.Shortcut.DnaStringReverse:
..cat:Modifier
..summary:Modifier for the reverse of a @Shortcut.DnaString@.
..signature:DnaStringReverse
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<DnaString, ModReverse>
..see:Shortcut.DnaString
..see:Class.ModifiedString
..see:Spec.ModReverse
*/

/*!
 * @typedef Dna5StringReverse
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the reverse of a Dna5String.
 *
 * @signature typedef ModifiedString<Dna5String, ModReverse> DnaStringReverse;
 */

/**
.Shortcut.Dna5StringReverse:
..cat:Modifier
..summary:Modifier for the reverse of a @Shortcut.Dna5String@.
..signature:Dna5StringReverse
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<Dna5String, ModReverse>
..see:Shortcut.Dna5String
..see:Class.ModifiedString
..see:Spec.ModReverse
*/

/*!
 * @typedef RnaStringReverse
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the reverse of a RnaString.
 *
 * @signature typedef ModifiedString<RnaString, ModReverse> DnaStringReverse;
 */

/**
.Shortcut.RnaStringReverse:
..cat:Modifier
..summary:Modifier for the reverse of a @Shortcut.RnaString@.
..signature:RnaStringReverse
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<RnaString, ModReverse>
..see:Shortcut.RnaString
..see:Class.ModifiedString
..see:Spec.ModReverse
*/

/*!
 * @typedef Rna5StringReverse
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the reverse of a Rna5String.
 *
 * @signature typedef ModifiedString<Rna5String, ModReverse> DnaStringReverse;
 */

/**
.Shortcut.Rna5StringReverse:
..cat:Modifier
..summary:Modifier for the reverse of a @Shortcut.Rna5String@.
..signature:Rna5StringReverse
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<Rna5String, ModReverse>
..see:Shortcut.Rna5String
..see:Class.ModifiedString
..see:Spec.ModReverse
*/

/*!
 * @typedef DnaStringReverseComplement
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the reverse-complement of a DnaString.
 *
 * @signature typedef ModifiedString<ModifiedString<DnaString, ModView<FunctorComplement<Dna5> >, ModReverse> DnaStringReverseComplement;
 */

/**
.Shortcut.DnaStringReverseComplement:
..cat:Modifier
..summary:Modifier for the reverse complement of a @Shortcut.DnaString@.
..signature:DnaStringReverseComplement
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<ModifiedString<DnaString, ModView< FunctorComplement<Dna> > >, ModReverse>
..see:Shortcut.DnaString
..see:Class.ModifiedString
..see:Spec.ModReverse
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/*!
 * @typedef Dna5StringReverseComplement
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the reverse-complement of a Dna5String.
 *
 * @signature typedef ModifiedString<ModifiedString<Dna5String, ModView<FunctorComplement<Dna55> >, ModReverse> Dna5StringReverseComplement;
 */

/**
.Shortcut.Dna5StringReverseComplement:
..cat:Modifier
..summary:Modifier for the reverse complement of a @Shortcut.Dna5String@.
..signature:Dna5StringReverseComplement
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<ModifiedString<Dna5String, ModView< FunctorComplement<Dna> > >, ModReverse>
..see:Shortcut.Dna5String
..see:Class.ModifiedString
..see:Spec.ModReverse
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/*!
 * @typedef RnaStringReverseComplement
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the reverse-complement of a RnaString.
 *
 * @signature typedef ModifiedString<ModifiedString<RnaString, ModView<FunctorComplement<Rna5> >, ModReverse> RnaStringReverseComplement;
 */

/**
.Shortcut.RnaStringReverseComplement:
..cat:Modifier
..summary:Modifier for the reverse complement of a @Shortcut.RnaString@.
..signature:RnaStringReverseComplement
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<ModifiedString<RnaString, ModView< FunctorComplement<Rna> > >, ModReverse>
..see:Shortcut.RnaString
..see:Class.ModifiedString
..see:Spec.ModReverse
..see:Spec.ModView
..see:Class.FunctorComplement
*/

/*!
 * @typedef Rna5StringReverseComplement
 * @headerfile <seqan/modifier.h>
 * @brief Modifier for the reverse-complement of a Rna5String.
 *
 * @signature typedef ModifiedString<ModifiedString<Rna5String, ModView<FunctorComplement<Rna55> >, ModReverse> Rna5StringReverseComplement;
 */

/**
.Shortcut.Rna5StringReverseComplement:
..cat:Modifier
..summary:Modifier for the reverse complement of a @Shortcut.Rna5String@.
..signature:Rna5StringReverseComplement
..shortcutfor:Class.ModifiedString
...signature:ModifiedString<ModifiedString<Rna5String, ModView< FunctorComplement<Rna> > >, ModReverse>
..see:Shortcut.Rna5String
..see:Class.ModifiedString
..see:Spec.ModReverse
..see:Spec.ModView
..see:Class.FunctorComplement
*/

typedef ModView<FunctorComplement<Dna> >	ModComplementDna;
typedef ModView<FunctorComplement<Dna5> >	ModComplementDna5;
typedef ModView<FunctorComplement<Rna> >	ModComplementRna;
typedef ModView<FunctorComplement<Rna5> >	ModComplementRna5;

typedef ModifiedString<DnaString, ModView<FunctorComplement<Dna> > >		DnaStringComplement;
typedef ModifiedString<Dna5String, ModView<FunctorComplement<Dna5> > >		Dna5StringComplement;
typedef ModifiedString<RnaString, ModView<FunctorComplement<Rna> > >		RnaStringComplement;
typedef ModifiedString<Rna5String, ModView<FunctorComplement<Rna5> > >		Rna5StringComplement;

typedef ModifiedString<DnaString, ModReverse>		DnaStringReverse;
typedef ModifiedString<Dna5String, ModReverse>		Dna5StringReverse;
typedef ModifiedString<RnaString, ModReverse>		RnaStringReverse;
typedef ModifiedString<Rna5String, ModReverse>		Rna5StringReverse;

//////////////////////////////////////////////////////////////////////////////
/*
typedef ModifiedString<DnaStringReverse, ModComplementDna>		DnaStringReverseComplement;
typedef ModifiedString<Dna5StringReverse, ModComplementDna5>	Dna5StringReverseComplement;
*/

typedef ModifiedString<
			ModifiedString<DnaString, ModView< FunctorComplement<Dna> > >,
			ModReverse
		>	DnaStringReverseComplement;

typedef ModifiedString<
			ModifiedString<	Dna5String, ModView< FunctorComplement<Dna5> > >,
			ModReverse
		>	Dna5StringReverseComplement;

typedef ModifiedString<
			ModifiedString<RnaString, ModView< FunctorComplement<Rna> > >,
			ModReverse
		>	RnaStringReverseComplement;

typedef ModifiedString<
			ModifiedString<	Rna5String, ModView< FunctorComplement<Rna5> > >,
			ModReverse
		>	Rna5StringReverseComplement;

// --------------------------------------------------------------------------
// Function complement()
// --------------------------------------------------------------------------

/*!
 * @fn complement
 * @headerfile <seqan/modifier.h>
 * @brief Complement a sequence or a StringSet in-place.
 *
 * @signature void complement(sequence);
 * @signature void complement(stringSet);
 *
 * @param[in,out] stringSet The StringSet to complement.
 * @param[in,out] sequence  The SequenceConcept to complement.
 *
 * @section Remarks
 *
 * Complementing only works for alphabets where a <tt>FunctorComplement<T></tt> is implemented.  SeqAn comes with
 * such definitions for Dna, Dna5, Rna, Rna5.
 */

/**
.Function.complement
..cat:Modifier
..summary:Complement a sequence or a @Class.StringSet@ in-place.
..signature:complement(sequence)
..param.sequence:The sequence to complement.
...type:Class.String
...type:Class.Segment
..include:seqan/modifier.h
..see:Function.reverseComplement
..see:Function.toLower
..see:Function.toUpper
*/

template <typename TSequence >
inline void complement(TSequence & sequence)
{
	convert(sequence, FunctorComplement<typename Value<TSequence>::Type>());
}

template <typename TSequence >
inline void complement(TSequence const & sequence)
{
	convert(sequence, FunctorComplement<typename Value<TSequence>::Type>());
}

// --------------------------------------------------------------------------
// Function complement()
// --------------------------------------------------------------------------

/**
.Function.complement
..signature:complement(stringSet)
..param.stringSet:The @Class.StringSet@ to complement.
...type:Class.StringSet
..include:seqan/modifier.h
*/

template < typename TSequence, typename TSpec >
inline void complement(StringSet<TSequence, TSpec> & stringSet)
{
	unsigned seqCount = length(stringSet);
	for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo)
		complement(stringSet[seqNo]);
}

template < typename TSequence, typename TSpec >
inline void complement(StringSet<TSequence, TSpec> const & stringSet)
{
	unsigned seqCount = length(stringSet);
	for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo)
		complement(stringSet[seqNo]);
}

// --------------------------------------------------------------------------
// Function reverseComplement()
// --------------------------------------------------------------------------

/*!
 * @fn reverseComplement
 * @headerfile <seqan/modifier.h>
 * @brief Reverse-complement a sequence or a StringSet in-place.
 *
 * @signature void reverseComplement(sequence);
 * @signature void reverseComplement(stringSet);
 *
 * @param[in,out] stringSet The StringSet to complement.
 * @param[in,out] sequence  The SequenceConcept to complement.
 *
 * @section Remarks
 *
 * StringSet objects are reverse-complemented element-wise, i.e. the order of the sequences stays the same but the
 * sequences in the StringSet themselves are reverse-complemented.
 *
 * Complementing only works for alphabets where a <tt>FunctorComplement<T></tt> is implemented.  SeqAn comes with
 * such definitions for Dna, Dna5, Rna, Rna5.
 */

/**
.Function.reverseComplement:
..cat:Modifier
..summary:Reverse and complement a sequence or a @Class.StringSet@ in-place.
..signature:reverseComplement(sequence)
..param.sequence:The sequence to complement.
...type:Class.String
...type:Class.Segment
..include:seqan/modifier.h
..see:Function.complement
..see:Function.toLower
..see:Function.toUpper
 */
template < typename TSequence >
inline void reverseComplement(TSequence & sequence)
{
	convert(sequence, FunctorComplement<typename Value<TSequence>::Type>());
	reverse(sequence);
}

// TODO(holtgrew): How is doing anything in-place on a const value possible?
template < typename TSequence >
inline void reverseComplement(TSequence const & sequence)
{
	convert(sequence, FunctorComplement<typename Value<TSequence>::Type>());
	reverse(sequence);
}

/**
.Function.reverseComplement:
..signature:reverseComplement(stringSet)
..param.stringSet:The @Class.StringSet@ to complement.
...type:Class.StringSet
..include:seqan/modifier.h
 */
template < typename TSequence, typename TSpec >
inline void reverseComplement(StringSet<TSequence, TSpec> & stringSet)
{
	unsigned seqCount = length(stringSet);
	for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo)
		reverseComplement(stringSet[seqNo]);
}

// TODO(holtgrew): How is doing anything in-place on a const value possible?
template < typename TSequence, typename TSpec >
inline void reverseComplement(StringSet<TSequence, TSpec> const & stringSet)
{
	unsigned seqCount = length(stringSet);
	for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo)
		reverseComplement(stringSet[seqNo]);
}

// --------------------------------------------------------------------------
// Function toLower()
// --------------------------------------------------------------------------

/*!
 * @fn toLower
 * @headerfile <seqan/modifier.h>
 * @brief Convert characters in sequence or StringSet to lower case in-place.
 *
 * @signature void toLower(sequence);
 * @signature void toLower(stringSet);
 *
 * @param[in,out] sequence  The SequenceConcept to convert to lower-case.
 * @param[in,out] stringSet The StringSet to convert to lower-case.
 */

/**
.Function.toLower:
..cat:Modifier
..summary:Convert characters in sequence or @Class.StringSet@ to lower case in-place.
..signature:toLower(sequence)
..param.sequence:The sequence to convert into lowercase.
...type:Class.String
...type:Class.Segment
..include:seqan/modifier.h
..see:Function.toUpper
..see:Function.reverseComplement
..see:Function.complement
 */

template < typename TSequence >
inline void toLower(TSequence & sequence)
{
	convert(sequence, FunctorLowcase<typename Value<TSequence>::Type>());
}

// TODO(holtgrew): How is doing anything in-place on a const value possible?
template < typename TSequence >
inline void toLower(TSequence const & sequence)
{
	convert(sequence, FunctorLowcase<typename Value<TSequence>::Type>());
}

/**
.Function.toLower:
..signature:toLower(stringSet)
..param.stringSet:The @Class.StringSet@ to convert into lowercase.
...type:Class.StringSet
..include:seqan/modifier.h
 */
template < typename TSequence, typename TSpec >
inline void toLower(StringSet<TSequence, TSpec> & stringSet)
{
	unsigned seqCount = length(stringSet);
	for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo)
		toLower(stringSet[seqNo]);
}

// TODO(holtgrew): How is doing anything in-place on a const value possible?
template < typename TSequence, typename TSpec >
inline void toLower(StringSet<TSequence, TSpec> const & stringSet)
{
	unsigned seqCount = length(stringSet);
	for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo)
		toLower(stringSet[seqNo]);
}

// --------------------------------------------------------------------------
// Function toUpper()
// --------------------------------------------------------------------------

/*!
 * @fn toUpper
 * @headerfile <seqan/modifier.h>
 * @brief Convert characters in sequence or StringSet to upper case in-place.
 *
 * @signature void toUpper(sequence);
 * @signature void toUpper(stringSet);
 *
 * @param[in,out] sequence  The SequenceConcept to convert to upper-case.
 * @param[in,out] stringSet The StringSet to convert to upper-case.
 */

/**
.Function.toUpper:
..cat:Modifier
..summary:Convert characters in sequence or @Class.StringSet@ to lower case in-place.
..signature:toUpper(sequence)
..param.sequence:The sequence to convert into uppercase.
...type:Class.String
...type:Class.Segment
..include:seqan/modifier.h
..see:Function.toLower
..see:Function.reverseComplement
..see:Function.complement
 */
template < typename TSequence >
inline void toUpper(TSequence & sequence)
{
	convert(sequence, FunctorUpcase<typename Value<TSequence>::Type>());
}

// TODO(holtgrew): How is doing anything in-place on a const value possible?
template < typename TSequence >
inline void toUpper(TSequence const & sequence)
{
	convert(sequence, FunctorUpcase<typename Value<TSequence>::Type>());
}

/**
.Function.toUpper:
..signature:toUpper(stringSet)
..param.stringSet:The @Class.StringSet@ to convert into uppercase.
...type:Class.StringSet
..include:seqan/modifier.h
 */
template < typename TSequence, typename TSpec >
inline void toUpper(StringSet<TSequence, TSpec> & stringSet)
{
	unsigned seqCount = length(stringSet);
	for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo)
		toUpper(stringSet[seqNo]);
}

// TODO(holtgrew): How is doing anything in-place on a const value possible?
template < typename TSequence, typename TSpec >
inline void toUpper(StringSet<TSequence, TSpec> const & stringSet)
{

	unsigned seqCount = length(stringSet);
	for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo)
		toUpper(stringSet[seqNo]);
}

}

#endif


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;

namespace TestAndRemember.Data.Migrations
{
    public partial class InitialQuestionSetQuestion : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<long>(
                name: "UserId",
                table: "AspNetUsers",
                nullable: false,
                defaultValue: 0L);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "UserId",
                table: "AspNetUsers");
        }
    }
}


text:
var Emitter     = require('./emitter'),
    Observer    = require('./observer'),
    config      = require('./config'),
    utils       = require('./utils'),
    Binding     = require('./binding'),
    Directive   = require('./directive'),
    TextParser  = require('./text-parser'),
    DepsParser  = require('./deps-parser'),
    ExpParser   = require('./exp-parser'),

    // cache methods
    slice       = Array.prototype.slice,
    log         = utils.log,
    makeHash    = utils.hash,
    extend      = utils.extend,
    def         = utils.defProtected,
    hasOwn      = Object.prototype.hasOwnProperty,

    // hooks to register
    hooks = [
        'created', 'ready',
        'beforeDestroy', 'afterDestroy',
        'enteredView', 'leftView'
    ]

/**
 *  The DOM compiler
 *  scans a DOM node and compile bindings for a ViewModel
 */
function Compiler (vm, options) {

    var compiler = this
    // indicate that we are intiating this instance
    // so we should not run any transitions
    compiler.init = true

    // process and extend options
    options = compiler.options = options || makeHash()
    utils.processOptions(options)

    // copy data, methods & compiler options
    var data = compiler.data = options.data || {}
    extend(vm, data, true)
    extend(vm, options.methods, true)
    extend(compiler, options.compilerOptions)

    // initialize element
    var el = compiler.setupElement(options)
    log('\nnew VM instance:', el.tagName, '\n')

    // set compiler properties
    compiler.vm  = vm
    compiler.bindings = makeHash()
    compiler.dirs = []
    compiler.deferred = []
    compiler.exps = []
    compiler.computed = []
    compiler.childCompilers = []
    compiler.emitter = new Emitter()

    // set inenumerable VM properties
    def(vm, '$', makeHash())
    def(vm, '$el', el)
    def(vm, '$compiler', compiler)
    def(vm, '$root', getRoot(compiler).vm)

    // set parent VM
    // and register child id on parent
    var parent = compiler.parentCompiler,
        childId = utils.attr(el, 'component-id')
    if (parent) {
        parent.childCompilers.push(compiler)
        def(vm, '$parent', parent.vm)
        if (childId) {
            compiler.childId = childId
            parent.vm.$[childId] = vm
        }
    }

    // setup observer
    compiler.setupObserver()

    // create bindings for computed properties
    var computed = options.computed
    if (computed) {
        for (var key in computed) {
            compiler.createBinding(key)
        }
    }

    // beforeCompile hook
    compiler.execHook('created')

    // the user might have set some props on the vm
    // so copy it back to the data...
    extend(data, vm)

    // observe the data
    Observer.observe(data, '', compiler.observer)

    // for repeated items, create an index binding
    // which should be inenumerable but configurable
    if (compiler.repeat) {
        //data.$index = compiler.repeatIndex
        def(data, '$index', compiler.repeatIndex, false, true)
        compiler.createBinding('$index')
    }

    // allow the $data object to be swapped
    Object.defineProperty(vm, '$data', {
        enumerable: false,
        get: function () {
            return compiler.data
        },
        set: function (newData) {
            var oldData = compiler.data
            Observer.unobserve(oldData, '', compiler.observer)
            compiler.data = newData
            Observer.copyPaths(newData, oldData)
            Observer.observe(newData, '', compiler.observer)
        }
    })

    // now parse the DOM, during which we will create necessary bindings
    // and bind the parsed directives
    compiler.compile(el, true)

    // bind deferred directives (child components)
    compiler.deferred.forEach(compiler.bindDirective, compiler)

    // extract dependencies for computed properties
    compiler.parseDeps()

    // done!
    compiler.init = false

    // post compile / ready hook
    compiler.execHook('ready')
}

var CompilerProto = Compiler.prototype

/**
 *  Initialize the VM/Compiler's element.
 *  Fill it in with the template if necessary.
 */
CompilerProto.setupElement = function (options) {
    // create the node first
    var el = this.el = typeof options.el === 'string'
        ? document.querySelector(options.el)
        : options.el || document.createElement(options.tagName || 'div')

    var template = options.template
    if (template) {
        // replace option: use the first node in
        // the template directly
        if (options.replace && template.childNodes.length === 1) {
            var replacer = template.childNodes[0].cloneNode(true)
            if (el.parentNode) {
                el.parentNode.insertBefore(replacer, el)
                el.parentNode.removeChild(el)
            }
            el = replacer
        } else {
            el.innerHTML = ''
            el.appendChild(template.cloneNode(true))
        }
    }

    // apply element options
    if (options.id) el.id = options.id
    if (options.className) el.className = options.className
    var attrs = options.attributes
    if (attrs) {
        for (var attr in attrs) {
            el.setAttribute(attr, attrs[attr])
        }
    }

    return el
}

/**
 *  Setup observer.
 *  The observer listens for get/set/mutate events on all VM
 *  values/objects and trigger corresponding binding updates.
 *  It also listens for lifecycle hooks.
 */
CompilerProto.setupObserver = function () {

    var compiler = this,
        bindings = compiler.bindings,
        options  = compiler.options,
        observer = compiler.observer = new Emitter()

    // a hash to hold event proxies for each root level key
    // so they can be referenced and removed later
    observer.proxies = makeHash()

    // add own listeners which trigger binding updates
    observer
        .on('get', function (key) {
            check(key)
            DepsParser.catcher.emit('get', bindings[key])
        })
        .on('set', function (key, val) {
            observer.emit('change:' + key, val)
            check(key)
            bindings[key].update(val)
        })
        .on('mutate', function (key, val, mutation) {
            observer.emit('change:' + key, val, mutation)
            check(key)
            bindings[key].pub()
        })

    // register hooks
    hooks.forEach(function (hook) {
        var fns = options[hook]
        if (Array.isArray(fns)) {
            var i = fns.length
            // since hooks were merged with child at head,
            // we loop reversely.
            while (i--) {
                register(hook, fns[i])
            }
        } else if (fns) {
            register(hook, fns)
        }
    })

    function register (hook, fn) {
        observer.on('hook:' + hook, function () {
            fn.call(compiler.vm, options)
        })
    }

    function check (key) {
        if (!bindings[key]) {
            compiler.createBinding(key)
        }
    }
}

/**
 *  Compile a DOM node (recursive)
 */
CompilerProto.compile = function (node, root) {

    var compiler = this,
        nodeType = node.nodeType,
        tagName  = node.tagName

    if (nodeType === 1 && tagName !== 'SCRIPT') { // a normal node

        // skip anything with v-pre
        if (utils.attr(node, 'pre') !== null) return

        // special attributes to check
        var repeatExp,
            withKey,
            partialId,
            directive,
            componentId = utils.attr(node, 'component') || tagName.toLowerCase(),
            componentCtor = compiler.getOption('components', componentId)

        // It is important that we access these attributes
        // procedurally because the order matters.
        //
        // `utils.attr` removes the attribute once it gets the
        // value, so we should not access them all at once.

        // v-repeat has the highest priority
        // and we need to preserve all other attributes for it.
        /* jshint boss: true */
        if (repeatExp = utils.attr(node, 'repeat')) {

            // repeat block cannot have v-id at the same time.
            directive = Directive.parse('repeat', repeatExp, compiler, node)
            if (directive) {
                directive.Ctor = componentCtor
                // defer child component compilation
                // so by the time they are compiled, the parent
                // would have collected all bindings
                compiler.deferred.push(directive)
            }

        // v-with has 2nd highest priority
        } else if (root !== true && ((withKey = utils.attr(node, 'with')) || componentCtor)) {

            directive = Directive.parse('with', withKey || '', compiler, node)
            if (directive) {
                directive.Ctor = componentCtor
                compiler.deferred.push(directive)
            }

        } else {

            // check transition property
            node.vue_trans = utils.attr(node, 'transition')

            // replace innerHTML with partial
            partialId = utils.attr(node, 'partial')
            if (partialId) {
                var partial = compiler.getOption('partials', partialId)
                if (partial) {
                    node.innerHTML = ''
                    node.appendChild(partial.cloneNode(true))
                }
            }

            // finally, only normal directives left!
            compiler.compileNode(node)
        }

    } else if (nodeType === 3) { // text node

        compiler.compileTextNode(node)

    }

}

/**
 *  Compile a normal node
 */
CompilerProto.compileNode = function (node) {
    var i, j,
        attrs = slice.call(node.attributes),
        prefix = config.prefix + '-'
    // parse if has attributes
    if (attrs && attrs.length) {
        var attr, isDirective, exps, exp, directive
        // loop through all attributes
        i = attrs.length
        while (i--) {
            attr = attrs[i]
            isDirective = false

            if (attr.name.indexOf(prefix) === 0) {
                // a directive - split, parse and bind it.
                isDirective = true
                exps = Directive.split(attr.value)
                // loop through clauses (separated by ",")
                // inside each attribute
                j = exps.length
                while (j--) {
                    exp = exps[j]
                    directive = Directive.parse(attr.name.slice(prefix.length), exp, this, node)
                    if (directive) {
                        this.bindDirective(directive)
                    }
                }
            } else {
                // non directive attribute, check interpolation tags
                exp = TextParser.parseAttr(attr.value)
                if (exp) {
                    directive = Directive.parse('attr', attr.name + ':' + exp, this, node)
                    if (directive) {
                        this.bindDirective(directive)
                    }
                }
            }

            if (isDirective) node.removeAttribute(attr.name)
        }
    }
    // recursively compile childNodes
    if (node.childNodes.length) {
        slice.call(node.childNodes).forEach(this.compile, this)
    }
}

/**
 *  Compile a text node
 */
CompilerProto.compileTextNode = function (node) {

    var tokens = TextParser.parse(node.nodeValue)
    if (!tokens) return
    var el, token, directive, partial, partialId, partialNodes

    for (var i = 0, l = tokens.length; i < l; i++) {
        token = tokens[i]
        directive = partialNodes = null
        if (token.key) { // a binding
            if (token.key.charAt(0) === '>') { // a partial
                partialId = token.key.slice(1).trim()
                partial = this.getOption('partials', partialId)
                if (partial) {
                    el = partial.cloneNode(true)
                    // save an Array reference of the partial's nodes
                    // so we can compile them AFTER appending the fragment
                    partialNodes = slice.call(el.childNodes)
                }
            } else { // a real binding
                if (!token.html) { // text binding
                    el = document.createTextNode('')
                    directive = Directive.parse('text', token.key, this, el)
                } else { // html binding
                    el = document.createComment(config.prefix + '-html')
                    directive = Directive.parse('html', token.key, this, el)
                }
            }
        } else { // a plain string
            el = document.createTextNode(token)
        }

        // insert node
        node.parentNode.insertBefore(el, node)

        // bind directive
        if (directive) {
            this.bindDirective(directive)
        }

        // compile partial after appending, because its children's parentNode
        // will change from the fragment to the correct parentNode.
        // This could affect directives that need access to its element's parentNode.
        if (partialNodes) {
            partialNodes.forEach(this.compile, this)
        }

    }
    node.parentNode.removeChild(node)
}

/**
 *  Add a directive instance to the correct binding & viewmodel
 */
CompilerProto.bindDirective = function (directive) {

    // keep track of it so we can unbind() later
    this.dirs.push(directive)

    // for empty or literal directives, simply call its bind()
    // and we're done.
    if (directive.isEmpty || directive.isLiteral) {
        if (directive.bind) directive.bind()
        return
    }

    // otherwise, we got more work to do...
    var binding,
        compiler = this,
        key      = directive.key

    if (directive.isExp) {
        // expression bindings are always created on current compiler
        binding = compiler.createBinding(key, true, directive.isFn)
    } else {
        // recursively locate which compiler owns the binding
        while (compiler) {
            if (compiler.hasKey(key)) {
                break
            } else {
                compiler = compiler.parentCompiler
            }
        }
        compiler = compiler || this
        binding = compiler.bindings[key] || compiler.createBinding(key)
    }

    binding.instances.push(directive)
    directive.binding = binding

    // invoke bind hook if exists
    if (directive.bind) {
        directive.bind()
    }

    // set initial value
    directive.update(binding.val(), true)
}

/**
 *  Create binding and attach getter/setter for a key to the viewmodel object
 */
CompilerProto.createBinding = function (key, isExp, isFn) {

    log('  created binding: ' + key)

    var compiler = this,
        bindings = compiler.bindings,
        computed = compiler.options.computed,
        binding  = new Binding(compiler, key, isExp, isFn)

    if (isExp) {
        // expression bindings are anonymous
        compiler.defineExp(key, binding)
    } else {
        bindings[key] = binding
        if (binding.root) {
            // this is a root level binding. we need to define getter/setters for it.
            if (computed && computed[key]) {
                // computed property
                compiler.defineComputed(key, binding, computed[key])
            } else {
                // normal property
                compiler.defineProp(key, binding)
            }
        } else {
            // ensure path in data so it can be observed
            Observer.ensurePath(compiler.data, key)
            var parentKey = key.slice(0, key.lastIndexOf('.'))
            if (!bindings[parentKey]) {
                // this is a nested value binding, but the binding for its parent
                // has not been created yet. We better create that one too.
                compiler.createBinding(parentKey)
            }
        }
    }
    return binding
}

/**
 *  Define the getter/setter for a root-level property on the VM
 *  and observe the initial value
 */
CompilerProto.defineProp = function (key, binding) {

    var compiler = this,
        data     = compiler.data,
        ob       = data.__observer__

    // make sure the key is present in data
    // so it can be observed
    if (!(key in data)) {
        data[key] = undefined
    }

    // if the data object is already observed, but the key
    // is not observed, we need to add it to the observed keys.
    if (ob && !(key in ob.values)) {
        Observer.convert(data, key)
    }

    binding.value = data[key]

    Object.defineProperty(compiler.vm, key, {
        get: function () {
            return compiler.data[key]
        },
        set: function (val) {
            compiler.data[key] = val
        }
    })
}

/**
 *  Define an expression binding, which is essentially
 *  an anonymous computed property
 */
CompilerProto.defineExp = function (key, binding) {
    var getter = ExpParser.parse(key, this)
    if (getter) {
        this.markComputed(binding, getter)
        this.exps.push(binding)
    }
}

/**
 *  Define a computed property on the VM
 */
CompilerProto.defineComputed = function (key, binding, value) {
    this.markComputed(binding, value)
    var def = {
        get: binding.value.$get,
        set: binding.value.$set
    }
    Object.defineProperty(this.vm, key, def)
}

/**
 *  Process a computed property binding
 *  so its getter/setter are bound to proper context
 */
CompilerProto.markComputed = function (binding, value) {
    binding.isComputed = true
    // bind the accessors to the vm
    if (binding.isFn) {
        binding.value = value
    } else {
        if (typeof value === 'function') {
            value = { $get: value }
        }
        binding.value = {
            $get: utils.bind(value.$get, this.vm),
            $set: value.$set
                ? utils.bind(value.$set, this.vm)
                : undefined
        }
    }
    // keep track for dep parsing later
    this.computed.push(binding)
}

/**
 *  Retrive an option from the compiler
 */
CompilerProto.getOption = function (type, id) {
    var opts = this.options,
        parent = this.parentCompiler
    return (opts[type] && opts[type][id]) || (
        parent
            ? parent.getOption(type, id)
            : utils[type] && utils[type][id]
    )
}

/**
 *  Emit lifecycle events to trigger hooks
 */
CompilerProto.execHook = function (event) {
    event = 'hook:' + event
    this.observer.emit(event)
    this.emitter.emit(event)
}

/**
 *  Check if a compiler's data contains a keypath
 */
CompilerProto.hasKey = function (key) {
    var baseKey = key.split('.')[0]
    return hasOwn.call(this.data, baseKey) ||
        hasOwn.call(this.vm, baseKey)
}

/**
 *  Collect dependencies for computed properties
 */
CompilerProto.parseDeps = function () {
    if (!this.computed.length) return
    DepsParser.parse(this.computed)
}

/**
 *  Unbind and remove element
 */
CompilerProto.destroy = function () {

    // avoid being called more than once
    // this is irreversible!
    if (this.destroyed) return

    var compiler = this,
        i, key, dir, instances, binding,
        vm          = compiler.vm,
        el          = compiler.el,
        directives  = compiler.dirs,
        exps        = compiler.exps,
        bindings    = compiler.bindings

    compiler.execHook('beforeDestroy')

    // unobserve data
    Observer.unobserve(compiler.data, '', compiler.observer)

    // unbind all direcitves
    i = directives.length
    while (i--) {
        dir = directives[i]
        // if this directive is an instance of an external binding
        // e.g. a directive that refers to a variable on the parent VM
        // we need to remove it from that binding's instances
        // * empty and literal bindings do not have binding.
        if (dir.binding && dir.binding.compiler !== compiler) {
            instances = dir.binding.instances
            if (instances) instances.splice(instances.indexOf(dir), 1)
        }
        dir.unbind()
    }

    // unbind all expressions (anonymous bindings)
    i = exps.length
    while (i--) {
        exps[i].unbind()
    }

    // unbind all own bindings
    for (key in bindings) {
        binding = bindings[key]
        if (binding) {
            binding.unbind()
        }
    }

    // remove self from parentCompiler
    var parent = compiler.parentCompiler,
        childId = compiler.childId
    if (parent) {
        parent.childCompilers.splice(parent.childCompilers.indexOf(compiler), 1)
        if (childId) {
            delete parent.vm.$[childId]
        }
    }

    // finally remove dom element
    if (el === document.body) {
        el.innerHTML = ''
    } else {
        vm.$remove()
    }

    this.destroyed = true
    // emit destroy hook
    compiler.execHook('afterDestroy')

    // finally, unregister all listeners
    compiler.observer.off()
    compiler.emitter.off()
}

// Helpers --------------------------------------------------------------------

/**
 *  shorthand for getting root compiler
 */
function getRoot (compiler) {
    while (compiler.parentCompiler) {
        compiler = compiler.parentCompiler
    }
    return compiler
}

module.exports = Compiler