text:
from qinfer import FiniteOutcomeModel
import numpy as np

class MultiCosModel(FiniteOutcomeModel):

    @property
    def n_modelparams(self):
        return 2

    @property
    def is_n_outcomes_constant(self):
        return True
    def n_outcomes(self, expparams):
        return 2

    def are_models_valid(self, modelparams):
        return np.all(np.logical_and(modelparams > 0, modelparams <= 1), axis=1)

    @property
    def expparams_dtype(self):
        return [('ts', 'float', 2)]

    def likelihood(self, outcomes, modelparams, expparams):
        # We first call the superclass method, which basically
        # just makes sure that call count diagnostics are properly
        # logged.
        super(MultiCosModel, self).likelihood(outcomes, modelparams, expparams)

        # Next, since we have a two-outcome model, everything is defined by
        # Pr(0 | modelparams; expparams), so we find the probability of 0
        # for each model and each experiment.
        #
        # We do so by taking a product along the modelparam index (len 2,
        # indicating omega_1 or omega_2), then squaring the result.
        pr0 = np.prod(
            np.cos(
                # shape (n_models, 1, 2)
                modelparams[:, np.newaxis, :] *
                # shape (n_experiments, 2)
                expparams['ts']
            ), # <- broadcasts to shape (n_models, n_experiments, 2).
            axis=2 # <- product over the final index (len 2)
        ) ** 2 # square each element

        # Now we use pr0_to_likelihood_array to turn this two index array
        # above into the form expected by SMCUpdater and other consumers
        # of likelihood().
        return FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0)


text:
'use strict'

const distances = require('../json/distance-data')

// Computes the fitness of this solution based on the total distance traveled
module.exports = solution => {
	let fitness = 0.0

	for (let i = 0; i < solution.length; i++) {
		const waypoint1 = solution[i]
		const waypoint2 = solution[i + 1] || solution[0] // Wrap back to beginning for last element
		const key = [waypoint1, waypoint2].sort()

		fitness += distances[key]
	}

	return fitness
}

redpajama_set_name: RedPajamaGithub


text:
package org.bouncycastle.mail.smime.test;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.mail.Session;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute;
import org.bouncycastle.asn1.smime.SMIMECapability;
import org.bouncycastle.asn1.smime.SMIMECapabilityVector;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.cms.jcajce.JcaX509CertSelectorConverter;
import org.bouncycastle.cms.jcajce.ZlibCompressor;
import org.bouncycastle.cms.jcajce.ZlibExpanderProvider;
import org.bouncycastle.cms.test.CMSTestUtil;
import org.bouncycastle.mail.smime.SMIMECompressed;
import org.bouncycastle.mail.smime.SMIMECompressedGenerator;
import org.bouncycastle.mail.smime.SMIMECompressedParser;
import org.bouncycastle.mail.smime.SMIMESigned;
import org.bouncycastle.mail.smime.SMIMESignedGenerator;
import org.bouncycastle.mail.smime.SMIMEUtil;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Store;

public class SMIMECompressedTest
    extends TestCase
{
    private static final String COMPRESSED_CONTENT_TYPE = "application/pkcs7-mime; name=\"smime.p7z\"; smime-type=compressed-data";

    private static final JcaX509CertSelectorConverter selectorConverter = new JcaX509CertSelectorConverter();

    boolean DEBUG = true;

    MimeBodyPart    msg;

    String          signDN;
    KeyPair         signKP;
    X509Certificate signCert;

    String          origDN;
    KeyPair         origKP;
    X509Certificate origCert;

    String          reciDN;
    KeyPair         reciKP;
    X509Certificate reciCert;

    KeyPair         dsaSignKP;
    X509Certificate dsaSignCert;

    KeyPair         dsaOrigKP;
    X509Certificate dsaOrigCert;

    /*
     *
     *  INFRASTRUCTURE
     *
     */

    public SMIMECompressedTest(
         String name)
        throws Exception
    {
        super(name);

        msg      = SMIMETestUtil.makeMimeBodyPart("Hello world!");

        signDN   = "O=Bouncy Castle, C=AU";
        signKP   = CMSTestUtil.makeKeyPair();
        signCert = CMSTestUtil.makeCertificate(signKP, signDN, signKP, signDN);

        origDN   = "CN=Eric H. Echidna, E=eric@bouncycastle.org, O=Bouncy Castle, C=AU";
        origKP   = CMSTestUtil.makeKeyPair();
        origCert = CMSTestUtil.makeCertificate(origKP, origDN, signKP, signDN);
    }

    public static void main(String args[])
    {
        junit.textui.TestRunner.run(SMIMECompressedTest.class);
    }

    public static Test suite()
    {
        return new SMIMETestSetup(new TestSuite(SMIMECompressedTest.class));
    }

    public void testHeaders()
        throws Exception
    {
        SMIMECompressedGenerator    cgen = new SMIMECompressedGenerator();

        MimeBodyPart cbp = cgen.generate(msg, new ZlibCompressor());

        assertEquals(COMPRESSED_CONTENT_TYPE, cbp.getHeader("Content-Type")[0]);
        assertEquals("attachment; filename=\"smime.p7z\"", cbp.getHeader("Content-Disposition")[0]);
        assertEquals("S/MIME Compressed Message", cbp.getHeader("Content-Description")[0]);
    }

    public void testBasic()
        throws Exception
    {
        SMIMECompressedGenerator    cgen = new SMIMECompressedGenerator();
        ByteArrayOutputStream       bOut = new ByteArrayOutputStream();
        MimeBodyPart cbp = cgen.generate(msg, new ZlibCompressor());

        SMIMECompressed sc = new SMIMECompressed(cbp);

        msg.writeTo(bOut);

        assertTrue(Arrays.areEqual(bOut.toByteArray(), sc.getContent(new ZlibExpanderProvider())));
    }

    public void testParser()
        throws Exception
    {
        SMIMECompressedGenerator    cgen = new SMIMECompressedGenerator();
        ByteArrayOutputStream       bOut1 = new ByteArrayOutputStream();
        ByteArrayOutputStream       bOut2 = new ByteArrayOutputStream();
        MimeBodyPart                cbp = cgen.generate(msg, new ZlibCompressor());
        SMIMECompressedParser       sc = new SMIMECompressedParser(cbp);

        msg.writeTo(bOut1);

        InputStream in = sc.getContent(new ZlibExpanderProvider()).getContentStream();
        int ch;

        while ((ch = in.read()) >= 0)
        {
            bOut2.write(ch);
        }

        assertTrue(Arrays.areEqual(bOut1.toByteArray(), bOut2.toByteArray()));
    }

    /*
     * test compressing and uncompressing of a multipart-signed message.
     */
    public void testCompressedSHA1WithRSA()
        throws Exception
    {
        List           certList = new ArrayList();

        certList.add(origCert);
        certList.add(signCert);

        Store certs = new JcaCertStore(certList);

        ASN1EncodableVector         signedAttrs = new ASN1EncodableVector();
        SMIMECapabilityVector       caps = new SMIMECapabilityVector();

        caps.addCapability(SMIMECapability.dES_EDE3_CBC);
        caps.addCapability(SMIMECapability.rC2_CBC, 128);
        caps.addCapability(SMIMECapability.dES_CBC);

        signedAttrs.add(new SMIMECapabilitiesAttribute(caps));

        SMIMESignedGenerator gen = new SMIMESignedGenerator();

        gen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(signedAttrs)).build("SHA1withRSA", origKP.getPrivate(), origCert));

        gen.addCertificates(certs);

        MimeMultipart smp = gen.generate(msg);

        MimeMessage bp2 = new MimeMessage((Session)null);

        bp2.setContent(smp);

        bp2.saveChanges();

        SMIMECompressedGenerator    cgen = new SMIMECompressedGenerator();

        MimeBodyPart cbp = cgen.generate(bp2, new ZlibCompressor());

        SMIMECompressed cm = new SMIMECompressed(cbp);

        MimeMultipart mm = (MimeMultipart)SMIMEUtil.toMimeBodyPart(cm.getContent(new ZlibExpanderProvider())).getContent();

        SMIMESigned s = new SMIMESigned(mm);

        ByteArrayOutputStream _baos = new ByteArrayOutputStream();
        msg.writeTo(_baos);
        _baos.close();
        byte[] _msgBytes = _baos.toByteArray();
        _baos = new ByteArrayOutputStream();
        s.getContent().writeTo(_baos);
        _baos.close();
        byte[] _resBytes = _baos.toByteArray();

        assertEquals(true, Arrays.areEqual(_msgBytes, _resBytes));

        certs = s.getCertificates();

        SignerInformationStore  signers = s.getSignerInfos();
        Collection              c = signers.getSigners();
        Iterator                it = c.iterator();

        while (it.hasNext())
        {
            SignerInformation   signer = (SignerInformation)it.next();
            Collection          certCollection = certs.getMatches(signer.getSID());

            Iterator            certIt = certCollection.iterator();
            X509CertificateHolder     cert = (X509CertificateHolder)certIt.next();

            assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)));
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 8: 592 (1889)

#### Original name
Dermatea ulicis Cooke, 1875

### Remarks
null


text:
/* eslint-disable ember/no-classic-components */
import Component from '@ember/component';

import template from './template';
import { tagName, layout } from '@ember-decorators/component';

@tagName('')
@layout(template)
export default class PaperAutocompleteResetButton extends Component {

  handleClick(onReset, e) {
    if (onReset) { onReset(e) }
  }
}


text:
package org.wso2.carbon.caching.module;

import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisDescription;
import org.apache.axis2.description.PolicySubject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.caching.core.CacheConfiguration;
import org.wso2.carbon.caching.core.CachingConstants;
import org.wso2.carbon.caching.core.CachingException;
import org.wso2.carbon.caching.core.policy.CachingPolicyProcessor;

public class CachingEngageUtils {

    private static Log log = LogFactory.getLog(CachingEngageUtils.class);

    public static void enguage(AxisDescription axisDescription) throws AxisFault {
        CacheConfiguration cacheConfig;
        PolicySubject policySubject = axisDescription.getPolicySubject();

        if (policySubject != null) {
            try {
                cacheConfig = CachingPolicyProcessor.processCachingPolicy(policySubject);
            } catch (CachingException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Unable to engage the caching module:" +
                              "Error in processing caching policy", e);
                }
                throw new AxisFault("Unable to engage the caching module:" +
                                    "Error in processing caching policy");
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Using the default initializer for the CacheConfiguration");
            }
            cacheConfig = new CacheConfiguration();
        }

        // if there is a caching policy, set the cache config if not inherited from the parent
        if (cacheConfig != null) {
            axisDescription.addParameter(CachingConstants.CACHE_CONFIGURATION, cacheConfig);
        }
    }
}


text:
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-nav-navbar-collapse" aria-expanded="false">
        Toggle navigation

      </button>

Home

Adventures

Users

About

Register

Log in

      <form [hidden]="!isAuthenticated" name="form" (ngSubmit)="logout()" class="form-horizontal" role="form">

            Hello {{user.email}} !

            <button class="btn btn-link">Log off</button>

      </form>


text:
"""Module for dealing with configurations. Also includes a default
configuration. You shouldn't need to edit this file; instead, copy one of the
example ``.cfg``s and make your changes to that, then pass a path to your
modified file to ``train.py``."""

from ConfigParser import SafeConfigParser
from StringIO import StringIO

# Path to Caffe models (saves space in the default config)
MOD_PATH = "./caffe-models/chen-and-yuille-nips-14/lsp"
# Default configuration, in Python's .cfg syntax
# DON'T CHANGE THIS. Instead, write your own .cfg file with the options you
# wish to change (e.g. add a [graphical_model] section with centroids_per_limb
# = 20 if you just need to change the number of centroids per limb) and load
# that with the --conf option.
DEFAULTS = """
[graphical_model]
centroids_per_limb: 13

[dataset]
loader: LSP
path: ../datasets/lsp/lsp_dataset.zip

[cnn]
solver: {MOD_PATH}/lsp_solver.prototxt
train_net: {MOD_PATH}/lsp_train_val.prototxt
test_net: {MOD_PATH}/lsp_deploy.prototxt
fully_conv_test_net: {MOD_PATH}/lsp_deploy_conv.prototxt
""".format(MOD_PATH=MOD_PATH)

def from_files(files):
    """Read a config file from a given list of file pointers."""
    rv = SafeConfigParser()
    rv.readfp(StringIO(DEFAULTS))
    for fp in files:
        rv.readfp(fp)
    return rv


text:
package krasa.core.frontend.commons.listeditor;

public class RemoveButton extends EditorButton {

	public RemoveButton(String id) {
		super(id);
		setDefaultFormProcessing(false);
	}

	@Override
	public void onSubmit() {
		int idx = getItem().getIndex();

		for (int i = idx + 1; i < getItem().getParent().size(); i++) {

			//TODO
			ListItem<?> item = (ListItem<?>) getItem().getParent().get(String.valueOf(i));
			item.setIndex(item.getIndex() - 1);
		}

		getList().remove(idx);
		getEditor().remove(getItem());
	}

	@Override
	public boolean isEnabled() {
		return getEditor().checkRemove(getItem());
	}
}


text:
module Configus

  class Builder::Proxy

    attr_reader :config

    def initialize(block)
      @config = {}
      instance_eval &block
    end

    def self.build(block)
      b = new(block)
      b.config
    end

    def method_missing(meth, *args, &block)
      if !block
    	  @config[meth] = args[0]
      else
        b = self.class.new(block)
        @config[meth] = b.config
      end
    end

  end

end


text:
package org.swingeasy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * @author Jurgen
 */
public final class MethodInvoker {
	public static final class InvocationException extends Exception {

		private static final long serialVersionUID = -4908577741649536787L;

		private InvocationException(String message) {
			super(message);
		}

		private InvocationException(Throwable cause) {
			super(cause);
		}
	}

	private static Method fuzzy(boolean static0, Object invoker, String methodName, Class<?>[] types) {
		Class<?> clazz = static0 ? (Class<?>) invoker : invoker.getClass();

		do {
			for (Method method : clazz.getDeclaredMethods()) {
				if (method.getName().equals(methodName) && (types.length == method.getParameterTypes().length)) {
					for (int i = 0; i < types.length; i++) {
						if (method.getParameterTypes()[i].isAssignableFrom(types[i])) {
							return method;
						}
					}
				}
			}

			clazz = clazz.getSuperclass();
		} while (clazz != null);

		return null;
	}

	/**
	 * find method
	 *
	 * @param invoker
	 * @param methodName
	 * @param types
	 *
	 * @return
	 *
	 * @throws InvocationException
	 */
	public static final Method getMethod(Object invoker, String methodName, Class<?>[] types) throws InvocationException {
		if (invoker == null) {
			throw new InvocationException("invoker cannot be <null>");
		}

		if (methodName == null) {
			throw new InvocationException("methodName cannot be <null>");
		}

		if (types == null) {
			types = new Class[0];
		}

		boolean static0 = invoker instanceof Class<?>;
		Class<?> clazz = static0 ? (Class<?>) invoker : invoker.getClass();
		Method method = null;

		try {
			method = clazz.getMethod(methodName, types);
		} catch (Exception ex) {
			do {
				try {
					method = clazz.getDeclaredMethod(methodName, types);
				} catch (Exception ex2) {
					clazz = clazz.getSuperclass();
				}
			} while ((method == null) && (clazz != null));
		}

		if (method == null) {
			method = MethodInvoker.fuzzy(static0, invoker, methodName, types);

			if (method == null) {
				throw new InvocationException("method '" + methodName + "' not found");
			}
		}

		if (!Modifier.isStatic(method.getModifiers()) && static0) {
			throw new InvocationException("can not invoke non-static method on class");
		}

		return method;
	}

	public static final Object invoke(Object invoker, String methodName) throws InvocationException {
		return MethodInvoker.invoke(invoker, methodName, (Class[]) null, (Object[]) null, Object.class);
	}

	public static final Object invoke(Object invoker, String methodName, Class<?> type, Object parameter) throws InvocationException {
		return MethodInvoker.invoke(invoker, methodName, new Class[] { type }, new Object[] { parameter }, Object.class);
	}

	public static final <T> T invoke(Object invoker, String methodName, Class<?> type, Object parameter, Class<T> returns) throws InvocationException {
		return MethodInvoker.invoke(invoker, methodName, new Class[] { type }, new Object[] { parameter }, returns);
	}

	public static final Object invoke(Object invoker, String methodName, Class<?>[] types, Object[] parameters) throws InvocationException {
		return MethodInvoker.invoke(invoker, methodName, types, parameters, Object.class);
	}

	public static final <T> T invoke(Object invoker, String methodName, Class<?>[] types, Object[] parameters, Class<T> returns) throws InvocationException {
		Method method = MethodInvoker.getMethod(invoker, methodName, types);
		Object invoked = MethodInvoker.invoke0(method, invoker, parameters);
		return returns.cast(invoked);
	}

	public static final <T> T invoke(Object invoker, String methodName, Class<T> returns) throws InvocationException {
		return MethodInvoker.invoke(invoker, methodName, (Class[]) null, (Object[]) null, returns);
	}

	public static final Object invoke(Object invoker, String methodName, Object parameter) throws InvocationException {
		MethodInvoker.nn(parameter, "parameter cannot be <null>");
		return MethodInvoker.invoke(invoker, methodName, parameter.getClass(), parameter);
	}

	private static final Object invoke0(Method method, Object invoker, Object[] parameters) throws InvocationException {
		try {
			boolean accessible = method.isAccessible();

			if (!accessible) {
				method.setAccessible(true);
			}

			Object returns;

			if (method.getReturnType() == Void.TYPE) {
				method.invoke(invoker, parameters);
				returns = Void.TYPE;
			} else {
				returns = method.invoke(invoker, parameters);
			}

			if (!accessible) {
				method.setAccessible(accessible);
			}

			return returns;
		} catch (RuntimeException ex) {
			throw new InvocationException(ex);
		} catch (IllegalAccessException ex) {
			throw new RuntimeException(ex);
		} catch (InvocationTargetException ex) {
			if (ex.getTargetException() instanceof InvocationException) {
				throw (InvocationException) ex.getTargetException();
			}

			if (ex.getTargetException() instanceof RuntimeException) {
				throw new InvocationException(ex.getTargetException());
			}

			throw new InvocationException(ex.getTargetException());
		}
	}

	private static final <T> T nn(T o, String msg) throws InvocationException {
		if (o == null) {
			throw new InvocationException(msg);
		}

		return o;
	}

	/**
	 * conversie
	 *
	 * @return
	 */
	public static Class<?>[] toTypes(Object... params) {
		Class<?>[] cl = new Class[params.length];

		for (int i = 0; i < params.length; i++) {
			cl[i] = (params[i] == null) ? Object.class : params[i].getClass();
		}

		return cl;
	}

	/** method */
	private Method method;

	/** invoker */
	private final Object invoker;

	/** methodName */
	private final String methodName;

	/** returns */
	private Object returns;

	/** parameters */
	private Object[] parameters;

	/** types */
	private Class<?>[] types;

	/**
	 * Creates a new MethodInvoker object.
	 *
	 * @param invoker
	 * @param methodName
	 * @param types
	 * @param parameters
	 *
	 * @throws InvocationException
	 */
	public MethodInvoker(Object invoker, String methodName, Class<?>... types) throws InvocationException {
		this.invoker = invoker;
		this.methodName = methodName;
		this.types = types;
	}

	/**
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(final Object other) {
		if (this == other) {
			return true;
		}

		if (!(other instanceof MethodInvoker)) {
			return false;
		}

		MethodInvoker castOther = (MethodInvoker) other;

		return new EqualsBuilder().append(this.invoker, castOther.invoker).append(this.methodName, castOther.methodName).append(this.types, castOther.types).isEquals();
	}

	/**
	 * Getter voor invoker
	 *
	 * @return Returns the invoker.
	 */
	public final Object getInvoker() {
		return this.invoker;
	}

	/**
	 * Getter voor method
	 *
	 * @return Returns the method.
	 *
	 * @throws InvocationException
	 */
	public final Method getMethod() throws InvocationException {
		if (this.method == null) {
			this.method = MethodInvoker.getMethod(this.invoker, this.methodName, this.types);
			this.types = this.method.getParameterTypes();
		}

		return this.method;
	}

	/**
	 * Getter voor methodName
	 *
	 * @return Returns the methodName.
	 */
	public final String getMethodName() {
		return this.methodName;
	}

	/**
	 * Getter voor parameters
	 *
	 * @return Returns the parameters.
	 */
	public final Object[] getParameters() {
		return this.parameters;
	}

	/**
	 * Getter voor returns
	 *
	 * @return Returns the returns.
	 */
	public final Object getReturns() {
		return this.returns;
	}

	/**
	 * Getter voor types
	 *
	 * @return Returns the types.
	 */
	public final Class<?>[] getTypes() {
		return this.types;
	}

	/**
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		return new HashCodeBuilder(1859497571, 1345127631).append(this.invoker).append(this.methodName).append(this.types).toHashCode();
	}

	/**
	 * invoke method with parameters
	 *
	 * @return
	 *
	 * @throws InvocationException
	 */
	public final Object invoke(Object... p) throws InvocationException {
		Method method2 = this.getMethod();

		if ((p == null) || ((p.length == 0) && (this.types.length != 0))) {
			throw new InvocationException("incorrect number or types of parameters");
		}

		if (p.length != this.types.length) {
			throw new InvocationException("incorrect number of parameters");
		}

		for (int i = 0; i < p.length; i++) {
			if (!((p[i] == null) || this.types[i].isAssignableFrom(p[i].getClass()))) {
				throw new InvocationException("incorrect types of parameters");
			}
		}

		this.parameters = p;
		this.returns = MethodInvoker.invoke0(method2, this.invoker, p);

		return this.returns;
	}

	@SuppressWarnings("unused")
	private final void setMethod(Method method) {
		//
	}

	@SuppressWarnings("unused")
	private final void setParameters(Object[] parameters) {
		//
	}

	@SuppressWarnings("unused")
	private final void setReturns(Object returns) {
		//
	}

	@SuppressWarnings("unused")
	private final void setTypes(Class<?>[] types) {
		//
	}

	/**
	 *
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).appendSuper(super.toString()).append("invoker", this.invoker).append("methodName", this.methodName)
				.append("types", this.types).append("method", this.method).append("parameters", this.parameters).append("returns", this.returns).toString();
	}
}


text:
var canvasContainer = document.querySelector("#canvasContainer");
var panzoomContainer = document.querySelector("#panzoomContainer");

var canvas = document.querySelector("#canvas");
var overlayCanvas = document.querySelector("#overlayCanvas");
var selectionCanvas = document.querySelector("#selectionCanvas");

var ctx = canvas.getContext("2d");
var overlayCtx = overlayCanvas.getContext("2d");
var selectionCtx = selectionCanvas.getContext("2d");

// var canvasContextImageData = ctx.createImageData(1,1);
// var imageData = canvasContextImageData.data;

var blockSelector = document.querySelector("#blocks");

ctx.msImageSmoothingEnabled = false;
ctx.mozImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;

overlayCtx.msImageSmoothingEnabled = false;
overlayCtx.mozImageSmoothingEnabled = false;
overlayCtx.msImageSmoothingEnabled = false;
overlayCtx.imageSmoothingEnabled = false;

selectionCtx.msImageSmoothingEnabled = false;
selectionCtx.mozImageSmoothingEnabled = false;
selectionCtx.msImageSmoothingEnabled = false;
selectionCtx.imageSmoothingEnabled = false;

var file;

var world;

var selectionX = 0;
var selectionY = 0;

var panzoom = $("#panzoomContainer").panzoom({
  cursor: "default",
  maxScale: 20,
  increment: 0.3,
});

$("#status").html("Checking File APIs...");

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  $("#file").css("visibility", "visible");
  $("#file").on('change', fileNameChanged);
	$("#status").html("Please choose a Terraria .wld file.");
} else {
	$("#status").html("The File APIs are not fully supported in this browser.");
}

resizeCanvases();

var options = [];

addTileSelectOptions();
addItemSelectOptions();
addWallSelectOptions();
sortAndAddSelectOptions();

addSetListItems();

function addSetListItems() {
  for(var i = 0; i < sets.length; i++) {
    var set = sets[i];

    for(var j = 0; j < set.Entries.length; j++) {
      var entry = set.Entries[j];
      if(entry.U || entry.V) {
        var tileInfo = getTileInfoFrom(entry.Id, entry.U, entry.V);
        if(tileInfo) {
          set.Entries[j] = tileInfo;
        }
      }
    }

    $("#setList").append('
' + set.Name + '
');
  }
}

function highlightSet(setIndex) {
  var set = sets[setIndex];

  highlightInfos(set.Entries);
}

function sortAndAddSelectOptions() {
  options.sort(compareOptions);

  for(var i = 0; i < options.length; i++) {
    var option = options[i];

    blockSelector.add(option);
  }
}

function addTileSelectOptions() {
  for(var i = 0; i < settings.Tiles.length; i++) {
    var tile = settings.Tiles[i];

    tile.isTile = true;

    var option = document.createElement("option");
    option.text = tile.Name;
    option.value = i;
    options.push(option);

    if(tile.Frames) {
      for(var frameIndex = 0; frameIndex < tile.Frames.length; frameIndex++) {
        var frame = tile.Frames[frameIndex];
        frame.isTile = true;

        option = document.createElement("option");
        option.text = tile.Name;
        option.value = i;

        var attribute = document.createAttribute("data-u");
        attribute.value = frame.U;
        option.setAttributeNode(attribute);

        attribute = document.createAttribute("data-v");
        attribute.value = frame.V;
        option.setAttributeNode(attribute);

        if(frame.Name) {
          option.text = `${option.text} - ${frame.Name}`;
        }

        if(frame.Variety) {
          option.text = `${option.text} - ${frame.Variety}`;
        }

        option.text += " (Tile)";

        options.push(option);
      }
    }
  }
}

function addItemSelectOptions() {
  for(var i = 0; i < settings.Items.length; i++) {
    var item = settings.Items[i];

    item.isItem = true;

    var option = document.createElement("option");
    option.text = `${item.Name} (Item)`;
    option.value = `item${item.Id}`;
    options.push(option);
  }
}

function addWallSelectOptions() {
  for(var i = 0; i < settings.Walls.length; i++) {
    var wall = settings.Walls[i];

    wall.isWall = true;

    var option = document.createElement("option");
    option.text = `${wall.Name} (Wall)`;
    option.value = `wall${wall.Id}`;
    options.push(option);
  }
}

function compareOptions(a,b) {
  if (a.text  b.text)
    return 1;
  return 0;
}

$('#chooseBlocksModal').on('shown.bs.modal', function () {
  $('#blocksFilter').focus();
});

$(document).bind('keydown', 'ctrl+b', function() {
  $('#chooseBlocksModal').modal();
});

// filter blocks
jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
    return this.each(function() {
        var select = this;
        var options = [];
        $(select).find('option').each(function() {
            options.push({value: $(this).val(), text: $(this).text(), u: $(this).attr('data-u'), v: $(this).attr('data-v')});
        });
        $(select).data('options', options);
        $(textbox).bind('change keyup', function() {
            var options = $(select).empty().data('options');
            var search = $.trim($(this).val());
            var regex = new RegExp(search,"gi");

            $.each(options, function(i) {
                var option = options[i];
                if(option.text.match(regex) !== null) {
                  var newOption = $('<option>');
                  newOption.text(option.text);
                  newOption.val(option.value);
                  newOption.attr('data-u', option.u);
                  newOption.attr('data-v', option.v);
                  $(select).append(newOption);
                }
            });
            if (selectSingleMatch === true && $(select).children().length === 1) {
                $(select).children().get(0).selected = true;
            }
        });
    });
};

$(function() {
    $('#blocks').filterByText($('#blocksFilter'), true);
});

$(window).resize(function () {
  $('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);
  $('#canvasContainer').css("overflow", "visible");
});

$(window).load(function () {
   $('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);
});

// handle scrolling in and out
panzoom.parent().on('mousewheel.focal', onMouseWheel);

function onMouseWheel(e) {
  e.preventDefault();

  const delta = e.delta || e.originalEvent.wheelDelta;
  const zoomOut = delta ? delta < 0 : e.originalEvent.deltaY > 0;

  const isTouchPad = Math.abs(delta) < 120;
  const multiplier = isTouchPad ? 0.025 : 0.3;

  // console.log({ isTouchPad, multiplier, delta, zoomOut });

  const transform = $(panzoomContainer).panzoom('getMatrix');
  const scale = transform[0];

  panzoom.panzoom('zoom', zoomOut, {
      increment   : multiplier * scale,
      animate     : true,
      focal       : e
  });
}

$(document).bind('keydown', 'e', zoomIn);
$(document).bind('keydown', 'c', zoomOut);

function zoomIn() {
  var transform = $(panzoomContainer).panzoom('getMatrix');
  var scale = transform[0];

  panzoom.panzoom('zoom', false, {
      increment   : 0.3 * scale,
      animate     : true
  });
}

function zoomOut() {
  var transform = $(panzoomContainer).panzoom('getMatrix');
  var scale = transform[0];

  panzoom.panzoom('zoom', true, {
      increment   : 0.3 * scale,
      animate     : true
  });
}

function previousBlock(e) {
  findBlock(-1);
}

function nextBlock(e) {
  findBlock(1);
}

function isTileMatch(tile, selectedInfos, x, y) {
  for(var j = 0; j < selectedInfos.length; j++) {
    var info = selectedInfos[j];

    // check the tile first
    if(tile.info && info.isTile && (tile.info == info || (!info.parent && tile.Type == info.Id)))
      return true;

    // check the wall
    if(info.isWall && tile.WallType == info.Id)
      return true;

    // see if it's a chest
    var chest = tile.chest;
    if(chest && info.isItem) {
      // see if the chest contains the item
      for(var i = 0; i < chest.items.length; i++) {
        var item = chest.items[i];

        if(info.Id == item.id) {
          return true;
        }
      }
    }
  }

  return false;
}

function findBlock(direction) {
  if(!world)
    return;

  var x = selectionX;
  var y = selectionY + direction;

  var start = x * world.height + y;

  var selectedInfos = getSelectedInfos();

  if(selectedInfos.length > 0) {
    for(var i = start; i >= 0 && i < world.tiles.length; i += direction) {
      var tile = world.tiles[i];

      var foundMatch = false;

      if(isTileMatch(tile, selectedInfos, x, y)) {
        selectionX = x;
        selectionY = y;

        drawSelectionIndicator();
        // panzoom.panzoom('pan', (-overlayCanvas.width / 2) - x, (-overlayCanvas.height / 2) - y, { relative: false });

        foundMatch = true;

        break;
      }

      y += direction;

      if(y < 0 || y >= world.height) {
        if(direction > 0)
          y = 0;
        else
          y = world.height - 1;
        x += direction;
      }

      if(foundMatch)
        break;
    }
  }
}

function highlightAll() {
  if(!world)
    return;

  var selectedInfos = getSelectedInfos();

  highlightInfos(selectedInfos);
}

function highlightInfos(selectedInfos) {
  var x = 0;
  var y = 0;

  overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
  overlayCtx.fillStyle = "rgba(0, 0, 0, 0.75)";
  overlayCtx.fillRect(0, 0, overlayCanvas.width, overlayCanvas.height);

  if(selectedInfos.length > 0) {
    for(var i = 0; i < world.tiles.length; i++) {
      var tile = world.tiles[i];

      if(isTileMatch(tile, selectedInfos)) {
        overlayCtx.fillStyle = "rgb(255, 255, 255)";
        overlayCtx.fillRect(x, y, 1, 1);
      }

      y++;
      if(y >= world.height) {
        y = 0;
        x++;
      }
    }
  }
}

function getSelectedInfos() {
  var selectedInfos = [];

  var j;
  var option;

  for(j = 0; j < blockSelector.options.length; j++) {
    option = blockSelector.options[j];
    if(!option.selected)
      continue;

    var tileInfo = getTileInfoFromOption(option);

    if(tileInfo) {
      selectedInfos.push(tileInfo);
    }
    else {
      var itemInfo = getItemInfoFromOption(option);
      if(itemInfo) {
        selectedInfos.push(itemInfo);
      }
      else {
        var wallInfo = getWallInfoFromOption(option);
        if(wallInfo) {
          selectedInfos.push(wallInfo);
        }
      }
    }
  }

  return selectedInfos;
}

function getTileInfoFromOption(option) {
  var tileInfo = getTileInfoFrom(option.value, option.getAttribute("data-u"), option.getAttribute("data-v"));

  return tileInfo;
}

function getTileInfoFrom(id, u, v) {
  var tileInfo = settings.Tiles[id];

  if(tileInfo && tileInfo.Frames) {
    for(var frameIndex = 0; frameIndex < tileInfo.Frames.length; frameIndex++) {
      var frame = tileInfo.Frames[frameIndex];

      if(u != frame.U)
        continue;

      if(v != frame.V)
        continue;

      frame.parent = tileInfo;

      return frame;
    }
  }

  return tileInfo;
}

function getItemInfoFromOption(option) {
  for(var i = 0; i < settings.Items.length; i++) {
    var item = settings.Items[i];

    if(option.value == `item${item.Id}`) {
      return item;
    }
  }

  return null;
}

function getWallInfoFromOption(option) {
  for(var i = 0; i < settings.Walls.length; i++) {
    var wall = settings.Walls[i];

    if(option.value == `wall${wall.Id}`) {
      return wall;
    }
  }

  return null;
}

function getTileInfo(tile) {
  var tileInfo = settings.Tiles[tile.Type];

  if(!tileInfo) return tileInfo;

  if(!tileInfo.Frames)
    return tileInfo;

  var matchingFrame;

  for(var i = 0; i < tileInfo.Frames.length; i++) {
    var frame = tileInfo.Frames[i];

    if((!frame.U && !tile.TextureU) || frame.U <= tile.TextureU) {
      if((!frame.V && !tile.TextureV) || frame.V <= tile.TextureV)
        matchingFrame = frame;
    }
  }

  if(!matchingFrame)
    return tileInfo;

  matchingFrame.parent = tileInfo;

  return matchingFrame;
}

function clearHighlight() {
  overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
  selectionCtx.clearRect(0, 0, selectionCanvas.width, selectionCanvas.height);
}

function clearSelection() {
  selectionCtx.clearRect(0, 0, selectionCanvas.width, selectionCanvas.height);
}

function resetPanZoom(e) {
  panzoom.panzoom('reset');
}

function resizeCanvases() {
  var width = window.innerWidth * 0.99;

  var ratio = panzoomContainer.height/panzoomContainer.width;
  var height = width * ratio;

  panzoomContainer.style.width = width+'px';
  panzoomContainer.style.height = height+'px';
  canvas.style.width = width+'px';
  overlayCanvas.style.width = width+'px';
  selectionCanvas.style.width = width + 'px';
  $('#canvasContainer').css("overflow", "visible");
}

function getMousePos(canvas, evt) {
  var rect = panzoomContainer.getBoundingClientRect();
  var transform = $(panzoomContainer).panzoom('getMatrix');

  var scale = transform[0];

  scale = rect.width / panzoomContainer.width;

  var mousePos =  {
    x: Math.floor((evt.clientX - rect.left) / scale),
    y: Math.floor((evt.clientY - rect.top) / scale)
  };

  // console.log(`${evt.clientX}\t${evt.clientY}\t${rect.left}\t${rect.top}\t${scale}\t${mousePos.x}\t${mousePos.y}`);

  return mousePos;
}

panzoomContainer.addEventListener('mousemove', evt => {
  if(!world)
    return;

  var mousePos = getMousePos(panzoomContainer, evt);
  var x = mousePos.x;
  var y = mousePos.y;

  $("#status").html(mousePos.x + ',' + (mousePos.y));

  if(world.tiles) {
    var tile = getTileAt(mousePos.x, mousePos.y);

    if(tile) {
      var text = getTileText(tile);

      $("#status").html(`${text} (${mousePos.x}, ${mousePos.y})`);
    }
  }
});

$("#panzoomContainer").on('panzoomend', function(evt, panzoom, matrix, changed) {
  if (changed) return;

  var mousePos = getMousePos(panzoomContainer, evt);
  var x = mousePos.x;
  var y = mousePos.y;

  selectionX = x;
  selectionY = y;

  drawSelectionIndicator();

  var tile = getTileAt(x, y);
  if(tile) {
    var text = getTileText(tile);

    $("#tileInfoList").html("");

    var chest = tile.chest;
    if(chest) {
      if(chest.name.length > 0)
      text = `${text} - ${chest.name}`;

      for(var i = 0; i < chest.items.length; i++) {
        var item = chest.items[i];
        var prefix = "";

        if(item.prefixId > 0 && item.prefixId < settings.ItemPrefix.length)
          prefix = settings.ItemPrefix[item.prefixId].Name;

        var itemName = item.id;
        for(var itemIndex = 0; itemIndex < settings.Items.length; itemIndex++) {
          var itemSettings = settings.Items[itemIndex];
          if(itemSettings.Id == item.id) {
            itemName = itemSettings.Name;
            break;
          }
        }

        $("#tileInfoList").append(`<li>${prefix} ${itemName} (${item.count})</li>`);
      }
    }

    var sign = tile.sign;
    if(sign && sign.text) {
      if(sign.text.length > 0)
        $("#tileInfoList").append(`<li>${sign.text}</li>`);
    }

    $("#tile").html(text);
  }

});

function getTileAt(x, y) {
  if(!world) return;

  var index = x * world.height + y;
  if(index >= 0 && index < world.tiles.length) {
    return world.tiles[index];
  }

  return null;
}

function selectPoint(x, y) {
  selectionX = x;
  selectionY = y;
  drawSelectionIndicator();
}

function drawSelectionIndicator() {
  var x = selectionX + 0.5;
  var y = selectionY + 0.5;

  var lineWidth = 12;
  var targetWidth = 39;
  var halfTargetWidth = targetWidth / 2;

  selectionCtx.clearRect(0, 0, selectionCanvas.width, selectionCanvas.height);
  selectionCtx.lineWidth = lineWidth;
  selectionCtx.strokeStyle="rgb(255, 0, 0)";
  selectionCtx.strokeRect(x - halfTargetWidth, y - halfTargetWidth, targetWidth, targetWidth);

  // draw cross-hairs
  selectionCtx.lineWidth=1;
  selectionCtx.beginPath();
  selectionCtx.moveTo(x - halfTargetWidth, y);
  selectionCtx.lineTo(x - 1, y);
  selectionCtx.stroke();
  selectionCtx.beginPath();
  selectionCtx.moveTo(x + halfTargetWidth, y);
  selectionCtx.lineTo(x + 1, y);
  selectionCtx.stroke();
  selectionCtx.beginPath();
  selectionCtx.moveTo(x, y - halfTargetWidth);
  selectionCtx.lineTo(x, y - 1);
  selectionCtx.stroke();
  selectionCtx.beginPath();
  selectionCtx.moveTo(x, y + halfTargetWidth);
  selectionCtx.lineTo(x, y + 1);
  selectionCtx.stroke();
}

function getTileText (tile) {
  var text = "Nothing";

  if(!tile) {
    return text;
  }

  var tileInfo = tile.info;

  if(tileInfo) {
    if(!tileInfo.parent || !tileInfo.parent.Name) {
       text = tileInfo.Name;
    }
    else if(tileInfo.parent && tileInfo.parent.Name) {
      text = tileInfo.parent.Name;

      if(tileInfo.Name) {
        text = `${text} - ${tileInfo.Name}`;

        if(tileInfo.Variety)
        text = `${text} - ${tileInfo.Variety}`;
      }
      else if (tileInfo.Variety) {
        text = `${text} - ${tileInfo.Variety}`;
      }
    }

    if(tile.TextureU > 0 && tile.TextureV > 0)
      text = `${text} (${tile.Type}, ${tile.TextureU}, ${tile.TextureV})`;
    else if(tile.TextureU > 0)
      text = `${text} (${tile.Type}, ${tile.TextureU})`;
    else
      text = `${text} (${tile.Type})`;
  }
  else if (tile.WallType || tile.WallType === 0) {
    if(tile.WallType < settings.Walls.length) {
      text = `${settings.Walls[tile.WallType].Name} (${tile.WallType})`;
    }
    else {
      text = `Unknown Wall (${tile.WallType})`;
    }
  }

  if (tile.IsLiquidPresent) {
    if (text === "Nothing") text = "";

    if(tile.IsLiquidLava) {
      text += text ? " Lava" : "Lava";
    }
    else if (tile.IsLiquidHoney) {
      text += text ? " Honey" : "Honey";
    }
    else if (tile.Shimmer) {
      text += text ? " Shimmer" : "Shimmer";
    }
    else {
      text += text ? " Water" : "Water";
    }
  }

  if(tile.IsRedWirePresent)
    text += " (Red Wire)";

  if(tile.IsGreenWirePresent)
    text += " (Green Wire)";

  if(tile.IsBlueWirePresent)
    text += " (Blue Wire)";

  if(tile.IsYellowWirePresent)
    text += " (Yellow Wire)";

  return text;
}

function fileNameChanged (evt) {
  file = evt.target.files[0];

  $("#help").hide();

  reloadWorld();
}

function reloadWorld() {
  var worker = new Worker('resources/js/WorldLoader.js');
  worker.addEventListener('message', onWorldLoaderWorkerMessage);

  worker.postMessage(file);
}

function onWorldLoaderWorkerMessage(e) {
  if(e.data.status)
    $("#status").html(e.data.status);

  if(e.data.tiles) {
	  let xlimit = e.data.x + e.data.tiles.length / world.height;
	  let i = 0;
	  for(let x = e.data.x; x < xlimit; x++) {
	    for(let y = 0; y < world.height; y++) {
	      let tile = e.data.tiles[i++];
	      if(tile) {
	        tile.info = getTileInfo(tile);
	        world.tiles.push(tile);

	        var c = getTileColor(y, tile, world);
	        if(!c) c = {"r": 0, "g": 0, "b": 0 };

	        ctx.fillStyle = `rgb(${c.r}, ${c.g}, ${c.b})`;
	        ctx.fillRect(x, y, 1, 1);
	      }
	    }
		}
  }

  if(e.data.chests) {
    world.chests = e.data.chests;

    for(i = 0; i < e.data.chests.length; i++) {
      var chest = e.data.chests[i];

      var idx = chest.x * world.height + chest.y;
      world.tiles[idx].chest = chest;
      world.tiles[idx + 1].chest = chest;

      idx = (chest.x + 1) * world.height + chest.y;
      world.tiles[idx].chest = chest;
      world.tiles[idx + 1].chest = chest;
    }
  }

  if(e.data.signs) {
    world.signs = e.data.signs;

    for(i = 0; i < e.data.signs.length; i++) {
      var sign = e.data.signs[i];

      var tileIndex = sign.x * world.height + sign.y;
      world.tiles[tileIndex].sign = sign;
      world.tiles[tileIndex + 1].sign = sign;

      tileIndex = (sign.x + 1) * world.height + sign.y;
      world.tiles[tileIndex].sign = sign;
      world.tiles[tileIndex + 1].sign = sign;
    }
  }

  if(e.data.npcs) {
    addNpcs(e.data.npcs);
  }

  if(e.data.world) {
    world = e.data.world;

    panzoomContainer.width = world.width;
    panzoomContainer.height = world.height;
    canvas.width = world.width;
    canvas.height = world.height;
    overlayCanvas.width = world.width;
    overlayCanvas.height = world.height;
    selectionCanvas.width = world.width;
    selectionCanvas.height = world.height;

    world.tiles = [];

    resizeCanvases();

    $("#worldPropertyList").empty();

    Object.keys(world).filter(key => {
      const value = world[key];
      const type = typeof value;
      return type === 'string' || type === 'number' || type === 'boolean' || type === 'bigint';
    }).sort()
    .forEach(key =>
      $("#worldPropertyList").append(`<li>${key}: ${world[key]}</li>`)
    );
  }
}

function addNpcs(npcs) {
  world.npcs = npcs;

  for(var i = 0; i < npcs.length; i++) {
    var npc = npcs[i];

    var npcText = npc.name;
    if(npc.type != npc.name) {
      npcText = `${npcText} the ${npc.type}`;
    }

    $("#npcList").append(`<li><a href="#" onclick="selectPoint(${npc.x}, ${npc.y})">${npcText}</a></li>`);
  }
}

function getTileColor(y, tile, world) {
  if(tile.IsActive) {
    return tileColors[tile.Type][0];
  }

  if (tile.IsLiquidPresent) {
    if(tile.IsLiquidLava)
      return liquidColors[1];
    else if (tile.IsLiquidHoney)
      return liquidColors[2];
    else
      return liquidColors[0];
  }

  if (tile.IsWallPresent) {
    return wallColors[tile.WallType][0];
  }

  if(y < world.worldSurfaceY)
    return { "r": 132, "g": 170, "b": 248 };

  if(y < world.rockLayerY)
    return { "r": 88, "g": 61, "b": 46 };

  if(y < world.hellLayerY)
    return { "r": 74, "g": 67, "b": 60 };

  return { "r": 0, "g": 0, "b": 0 };
}

function saveMapImage() {
  var newCanvas = document.createElement("canvas");
  var newContext = newCanvas.getContext("2d");

  newCanvas.height = world.height;
  newCanvas.width = world.width;

  newContext.drawImage(canvas, 0, 0);
  newContext.drawImage(overlayCanvas, 0, 0);
  newContext.drawImage(selectionCanvas, 0, 0);

  newCanvas.toBlob(function(blob) {
    saveAs(blob, `${world.name}.png`);
  });
}


text:
using System;
using System.Threading.Tasks;
using MR.AspNetCore.Jobs.Models;

namespace MR.AspNetCore.Jobs
{
	public abstract class EFCoreStorageTransaction<TContext, TOptions> : IStorageTransaction, IDisposable
		where TContext : EFCoreJobsDbContext
		where TOptions : EFCoreOptions
	{
		public EFCoreStorageTransaction(EFCoreStorageConnection<TContext, TOptions> connection)
		{
			Connection = connection;
		}

		protected EFCoreStorageConnection<TContext, TOptions> Connection { get; }

		public virtual void UpdateJob(Job job)
		{
			if (job == null) throw new ArgumentNullException(nameof(job));

			job.Updated = DateTime.UtcNow;

			// NOOP. EF will detect changes.
		}

		public virtual void EnqueueJob(Job job)
		{
			if (job == null) throw new ArgumentNullException(nameof(job));

			Connection.Context.Add(new JobQueue
			{
				JobId = job.Id
			});
		}

		public virtual Task CommitAsync()
		{
			return Connection.Context.SaveChangesAsync();
		}

		public virtual void Dispose()
		{
		}
	}
}


text:
#include <utils/String8.h>
#include <binder/IServiceManager.h>
#include <drm/DrmManagerClient.h>

#include "DrmManagerClientImpl.h"

using namespace android;

DrmManagerClient::DrmManagerClient():
        mUniqueId(0), mDrmManagerClientImpl(NULL) {
    mDrmManagerClientImpl = DrmManagerClientImpl::create(&mUniqueId, true);
    mDrmManagerClientImpl->addClient(mUniqueId);
}

DrmManagerClient::~DrmManagerClient() {
    DrmManagerClientImpl::remove(mUniqueId);
    mDrmManagerClientImpl->removeClient(mUniqueId);
    mDrmManagerClientImpl->setOnInfoListener(mUniqueId, NULL);
}

status_t DrmManagerClient::setOnInfoListener(
                    const sp<DrmManagerClient::OnInfoListener>& infoListener) {
    return mDrmManagerClientImpl->setOnInfoListener(mUniqueId, infoListener);
}

DrmConstraints* DrmManagerClient::getConstraints(const String8* path, const int action) {
    return mDrmManagerClientImpl->getConstraints(mUniqueId, path, action);
}

DrmMetadata* DrmManagerClient::getMetadata(const String8* path) {
    return mDrmManagerClientImpl->getMetadata(mUniqueId, path);
}

bool DrmManagerClient::canHandle(const String8& path, const String8& mimeType) {
    return mDrmManagerClientImpl->canHandle(mUniqueId, path, mimeType);
}

DrmInfoStatus* DrmManagerClient::processDrmInfo(const DrmInfo* drmInfo) {
    return mDrmManagerClientImpl->processDrmInfo(mUniqueId, drmInfo);
}

DrmInfo* DrmManagerClient::acquireDrmInfo(const DrmInfoRequest* drmInfoRequest) {
    return mDrmManagerClientImpl->acquireDrmInfo(mUniqueId, drmInfoRequest);
}

status_t DrmManagerClient::saveRights(
        const DrmRights& drmRights, const String8& rightsPath, const String8& contentPath) {
    return mDrmManagerClientImpl->saveRights(mUniqueId, drmRights, rightsPath, contentPath);
}

String8 DrmManagerClient::getOriginalMimeType(const String8& path, int fd) {
    return mDrmManagerClientImpl->getOriginalMimeType(mUniqueId, path, fd);
}

int DrmManagerClient::getDrmObjectType(const String8& path, const String8& mimeType) {
    return mDrmManagerClientImpl->getDrmObjectType( mUniqueId, path, mimeType);
}

int DrmManagerClient::checkRightsStatus(const String8& path, int action) {
    return mDrmManagerClientImpl->checkRightsStatus(mUniqueId, path, action);
}

status_t DrmManagerClient::consumeRights(
            sp<DecryptHandle> &decryptHandle, int action, bool reserve) {
    return mDrmManagerClientImpl->consumeRights(mUniqueId, decryptHandle, action, reserve);
}

status_t DrmManagerClient::setPlaybackStatus(
            sp<DecryptHandle> &decryptHandle, int playbackStatus, int64_t position) {
    return mDrmManagerClientImpl
            ->setPlaybackStatus(mUniqueId, decryptHandle, playbackStatus, position);
}

bool DrmManagerClient::validateAction(
            const String8& path, int action, const ActionDescription& description) {
    return mDrmManagerClientImpl->validateAction(mUniqueId, path, action, description);
}

status_t DrmManagerClient::removeRights(const String8& path) {
    return mDrmManagerClientImpl->removeRights(mUniqueId, path);
}

status_t DrmManagerClient::removeAllRights() {
    return mDrmManagerClientImpl->removeAllRights(mUniqueId);
}

int DrmManagerClient::openConvertSession(const String8& mimeType) {
    return mDrmManagerClientImpl->openConvertSession(mUniqueId, mimeType);
}

DrmConvertedStatus* DrmManagerClient::convertData(int convertId, const DrmBuffer* inputData) {
    return mDrmManagerClientImpl->convertData(mUniqueId, convertId, inputData);
}

DrmConvertedStatus* DrmManagerClient::closeConvertSession(int convertId) {
    return mDrmManagerClientImpl->closeConvertSession(mUniqueId, convertId);
}

status_t DrmManagerClient::getAllSupportInfo(int* length, DrmSupportInfo** drmSupportInfoArray) {
    return mDrmManagerClientImpl->getAllSupportInfo(mUniqueId, length, drmSupportInfoArray);
}

sp<DecryptHandle> DrmManagerClient::openDecryptSession(
        int fd, off64_t offset, off64_t length, const char* mime) {

    return mDrmManagerClientImpl->openDecryptSession(
                    mUniqueId, fd, offset, length, mime);
}

sp<DecryptHandle> DrmManagerClient::openDecryptSession(
        const char* uri, const char* mime) {

    return mDrmManagerClientImpl->openDecryptSession(
                    mUniqueId, uri, mime);
}

sp<DecryptHandle> DrmManagerClient::openDecryptSession(
            const DrmBuffer& buf, const String8& mimeType) {
    return mDrmManagerClientImpl->openDecryptSession(mUniqueId, buf, mimeType);
}

status_t DrmManagerClient::closeDecryptSession(sp<DecryptHandle> &decryptHandle) {
    return mDrmManagerClientImpl->closeDecryptSession(mUniqueId, decryptHandle);
}

status_t DrmManagerClient::initializeDecryptUnit(
            sp<DecryptHandle> &decryptHandle, int decryptUnitId, const DrmBuffer* headerInfo) {
    return mDrmManagerClientImpl->initializeDecryptUnit(
            mUniqueId, decryptHandle, decryptUnitId, headerInfo);
}

status_t DrmManagerClient::decrypt(
            sp<DecryptHandle> &decryptHandle, int decryptUnitId,
            const DrmBuffer* encBuffer, DrmBuffer** decBuffer, DrmBuffer* IV) {
    return mDrmManagerClientImpl->decrypt(
            mUniqueId, decryptHandle, decryptUnitId, encBuffer, decBuffer, IV);
}

status_t DrmManagerClient::finalizeDecryptUnit(
            sp<DecryptHandle> &decryptHandle, int decryptUnitId) {
    return mDrmManagerClientImpl->finalizeDecryptUnit(mUniqueId,
            decryptHandle, decryptUnitId);
}

ssize_t DrmManagerClient::pread(
            sp<DecryptHandle> &decryptHandle, void* buffer, ssize_t numBytes, off64_t offset) {
    return mDrmManagerClientImpl->pread(mUniqueId, decryptHandle, buffer, numBytes, offset);
}


text:
package info.kevinlin.cloudflaremanager;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.gc.materialdesign.views.Switch;
import com.gc.materialdesign.widgets.SnackBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

public class PerformanceSettingsFragment extends Fragment {

    SwipeRefreshLayout swipeLayout;

    String developmentMode;
    String cacheLevel;
    String alwaysOnline;
    String challengeTTL;
    String expirationTTL;
    String cacheTTL;
    String rocketLoader;
    String minify;
    String spdy = null;
    String lazyLoad = null;
    String ipv6;

    String setCacheLevel;
    String setRocketLoader;
    String setMinification;

    private OnFragmentInteractionListener mListener;

    public static PerformanceSettingsFragment newInstance() {
        return new PerformanceSettingsFragment();
    }

    public PerformanceSettingsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Tell the fragment that it has menu items, so that onCreateMenuOptions() is called.
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_performance_settings, container, false);

        // Cache level spinner
        List<String> cacheLevels = new ArrayList<String>();
        cacheLevels.add("Aggressive");
        cacheLevels.add("Simplified");
        cacheLevels.add("Basic");
        Spinner cacheLevelSpinner = populateSpinner(view, R.id.cache_level_spinner, cacheLevels);
        cacheLevelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /**
             * Cache level spinner on item selected listener
             */
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                if (parent.getItemAtPosition(pos).toString().equals("Aggressive"))
                    setCacheLevel = "agg";
                if (parent.getItemAtPosition(pos).toString().equals("Simplified"))
                    setCacheLevel = "iqs";
                if (parent.getItemAtPosition(pos).toString().equals("Basic"))
                    setCacheLevel = "basic";
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // Rocket loader spinner
        List<String> rocketLoaderOptions = new ArrayList<String>();
        rocketLoaderOptions.add("Off");
        rocketLoaderOptions.add("Automatic");
        rocketLoaderOptions.add("Manual");
        Spinner rocketLoaderSpinner = populateSpinner(view, R.id.rocket_loader_spinner, rocketLoaderOptions);
        rocketLoaderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /**
             * Rocket loader spinner on item selected listener
             */
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                if (parent.getItemAtPosition(pos).toString().equals("Off"))
                    setRocketLoader = "0";
                if (parent.getItemAtPosition(pos).toString().equals("Automatic"))
                    setRocketLoader = "a";
                if (parent.getItemAtPosition(pos).toString().equals("Manual"))
                    setRocketLoader = "m";
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // Minification spinner
        List<String> minificationOptions = new ArrayList<String>();
        minificationOptions.add("Off");
        minificationOptions.add("JavaScript only");
        minificationOptions.add("CSS only");
        minificationOptions.add("JavaScript and CSS");
        minificationOptions.add("HTML only");
        minificationOptions.add("JavaScript and HTML");
        minificationOptions.add("CSS and HTML");
        minificationOptions.add("CSS, JavaScript, and HTML");
        Spinner minificationSpinner = populateSpinner(view, R.id.minification_spinner, minificationOptions);
        minificationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /**
             * Minification spinner on item selected listener
             */
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                setMinification = "" + pos;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // On click listener for cache control button
        ((Button)view.findViewById(R.id.cache_control_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), CacheControlActivity.class));
            }
        });

        return view;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Initialize SwipeRefreshLayout and set it to display refreshing
        initSwipeRefreshLayout();
        swipeLayout.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
        swipeLayout.setRefreshing(true);

        // Refresh data
        new getInfo().execute(AccountConfig.getCurrentAccountData(getActivity()));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_performance_settings, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.save) {
            // Show loading circle
            swipeLayout.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
            swipeLayout.setRefreshing(true);

            // Save settings
            new saveSettings().execute(AccountConfig.getCurrentAccountData(getActivity()));

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     */
    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }

    /**
     * Initializes the SwipeRefreshLayout and defines its onRefresh behavior.
     */
    public void initSwipeRefreshLayout() {
        swipeLayout = (SwipeRefreshLayout)getActivity().findViewById(R.id.performance_settings_swipe_container);
        swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            /**
             * Governs behavior when the fragment is refreshed.
             */
            @Override
            public void onRefresh() {
                // Get account data and get info
                new getInfo().execute(AccountConfig.getCurrentAccountData(getActivity()));
            }
        });
    }

    /**
     * Populates a spinner with a List of items.
     *
     * @param spinnerID: Resource ID of the spinner, by means of R.id.spinnerID
     * @param items: List of items to put in the spinner
     * @return: The Spinner identified by spinnerID
     */
    private Spinner populateSpinner(View view, int spinnerID, List items) {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, items);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        Spinner spinner = (Spinner)view.findViewById(spinnerID);
        try {
            spinner.setAdapter(adapter);
            return spinner;
        }
        catch (NullPointerException e) {
            Log.e("NullPointerException", "Spinner " + spinnerID + " could not be found.");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Gets current settings from CloudFlare API. Initializes the instance variables and updates the UI.
     */
    private class getInfo extends AsyncTask<String, Void, Void> {

        boolean error = true;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String[] accountData) {
            String https_url = "https://www.cloudflare.com/api_json.html?tkn=" + accountData[0] + "&email=" + accountData[1] + "&a=zone_settings&z=" + accountData[2];
            URL url;
            try {
                String result = null;
                url = new URL(https_url);
                HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
                try {
                    if ((new JSONObject(result)).getString("result").equals("success"))
                        error = false;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i("API response", "Get performance settings task " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject response = jsonObject.getJSONObject("response");
                    JSONObject jResult = response.getJSONObject("result");
                    JSONArray jsonArray = jResult.getJSONArray("objs");
                    JSONObject domainInfo = jsonArray.getJSONObject(0);
                    developmentMode = domainInfo.getString("dev_mode");
                    alwaysOnline = domainInfo.getString("ob");
                    cacheLevel = domainInfo.getString("cache_lvl");
                    rocketLoader = domainInfo.getString("async");
                    challengeTTL = domainInfo.getString("chl_ttl");
                    expirationTTL = domainInfo.getString("exp_ttl");
                    cacheTTL = domainInfo.getString("cache_ttl");
                    minify = domainInfo.getString("minify");
                    ipv6 = domainInfo.getString("ipv46");
                    lazyLoad = domainInfo.getString("lazy");
                    spdy = domainInfo.getString("spdy");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Dismiss loading circle
            swipeLayout.setRefreshing(false);

            if (error) {
                SnackBar snackBar = new SnackBar(getActivity(), "There was an error logging in. Ensure that you have network connectivity and that your API key and email are correct.", null, null);
                snackBar.show();
            }
            else if (getView() != null) {
                // Update UI elements
                if (developmentMode.equals("0"))
                    ((Switch) getView().findViewById(R.id.development_mode_switch)).setChecked(false);
                else
                    ((Switch) getView().findViewById(R.id.development_mode_switch)).setChecked(true);
                if (alwaysOnline.equals("0"))
                    ((Switch) getView().findViewById(R.id.always_online_switch)).setChecked(false);
                else
                    ((Switch) getView().findViewById(R.id.always_online_switch)).setChecked(true);

                try {
                    if (spdy.equals("0") || spdy.equals(null))
                        ((Switch) getView().findViewById(R.id.spdy_switch)).setChecked(false);
                    else
                        ((Switch) getView().findViewById(R.id.spdy_switch)).setChecked(true);
                } catch (Exception e) {
                    //lazy programmer
                }

                if (ipv6.equals("0"))
                    ((Switch) getView().findViewById(R.id.ipv6_switch)).setChecked(false);
                else
                    ((Switch) getView().findViewById(R.id.ipv6_switch)).setChecked(true);

                if (cacheLevel.equals("agg"))
                    ((Spinner) getView().findViewById(R.id.cache_level_spinner)).setSelection(0);
                if (cacheLevel.equals("iqs"))
                    ((Spinner) getView().findViewById(R.id.cache_level_spinner)).setSelection(1);
                if (cacheLevel.equals("basic"))
                    ((Spinner) getView().findViewById(R.id.cache_level_spinner)).setSelection(2);

                if (rocketLoader.equals("0"))
                    ((Spinner) getView().findViewById(R.id.rocket_loader_spinner)).setSelection(0);
                if (rocketLoader.equals("a"))
                    ((Spinner) getView().findViewById(R.id.rocket_loader_spinner)).setSelection(1);
                if (rocketLoader.equals("m"))
                    ((Spinner) getView().findViewById(R.id.rocket_loader_spinner)).setSelection(2);

                ((Spinner) getView().findViewById(R.id.minification_spinner)).setSelection(Integer.parseInt(minify));

                ((TextView) getView().findViewById(R.id.challenge_ttl)).setText("Challenge TTL: " + challengeTTL + " seconds");
                ((TextView) getView().findViewById(R.id.expire_ttl)).setText("Expire TTL: " + expirationTTL + " seconds");
                ((TextView) getView().findViewById(R.id.cache_ttl)).setText("Cache TTL: " + cacheTTL + " seconds");

                // Disable Pro-only features, as necessary
                if (!AccountConfig.isCurrentDomainPro(getActivity())) {
                    getView().findViewById(R.id.spdy_switch).setEnabled(false);
                }

                // Disable features that are not modifiable by the API
                getView().findViewById(R.id.always_online_switch).setEnabled(false);
            }
        }
    }

    private class saveSettings extends AsyncTask<String, Void, Void> {

        boolean error = true;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String[] accountData) {
            String apiKey = accountData[0];
            String email = accountData[1];
            String domain = accountData[2];

            // Development mode
            if (((Switch)getView().findViewById(R.id.development_mode_switch)).isCheck())
                POSTURL("https://www.cloudflare.com/api_json.html?tkn=" + apiKey + "&email=" + email + "&a=devmode&v=1&z=" + domain);
            else
                POSTURL("https://www.cloudflare.com/api_json.html?tkn=" + apiKey + "&email=" + email + "&a=devmode&v=0&z=" + domain);

            // Cache level
            POSTURL("https://www.cloudflare.com/api_json.html?tkn=" + apiKey + "&email=" + email + "&a=cache_lvl&v=" + setCacheLevel + "&z=" + domain);

            // Rocket loader
            POSTURL("https://www.cloudflare.com/api_json.html?tkn=" + apiKey + "&email=" + email + "&a=async&v=" + setRocketLoader + "&z=" + domain);

            // Minification
            POSTURL("https://www.cloudflare.com/api_json.html?tkn=" + apiKey + "&email=" + email + "&a=minify&v=" + setMinification + "&z=" + domain);

            // IPv6
            if (((Switch)getView().findViewById(R.id.ipv6_switch)).isCheck())
                POSTURL("https://www.cloudflare.com/api_json.html?tkn=" + apiKey + "&email=" + email + "&a=ipv46&v=3&z=" + domain);
            else
                POSTURL("https://www.cloudflare.com/api_json.html?tkn=" + apiKey + "&email=" + email + "&a=ipv46&v=0&z=" + domain);

            return null;
        }

        protected void POSTURL(String s) {
            String https_url = s;
            URL url;
            try {
                String result = null;
                url = new URL(https_url);
                HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
                Log.i("API response", "Save performance settings task " + result);
                try {
                    if ((new JSONObject(result)).getString("result").equals("success"))
                        error = false;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onPostExecute(Void result) {
            // Dismiss loading circle
            swipeLayout.setRefreshing(false);

            // Show snackbar
            if (!error) {
                SnackBar snackBar = new SnackBar(getActivity(), "Settings saved successfully!", null, null);
                snackBar.show();
            }
            else {
                SnackBar snackBar = new SnackBar(getActivity(), "There was an error saving your settings.", null, null);
                snackBar.show();
            }
        }
    }

}


text:
/**
 * This JavaScript file contains the app's logic. It uses Apigee JavaScript
 * SDK functions to access an Apigee app services database.
 */

// Be sure to set your org name and app name!
var apigeeClient = new Apigee.Client({
    orgName: '', // Your organization name. You'll find this in the admin portal.
    appName: 'sandbox', // Your App Services app name. It's in the admin portal.
    logging: true, //optional - turn on logging, off by default
    buildCurl: true //optional - log network calls in the console, off by default
});

// Variables we can use from multiple functions in the code.
var users, allGroups, currentUser, groupsForUser;

// Each of these initializes a separate page of the UI.
$(document).on("pagecreate", "#page_home", function (event) {
    $('#frm_display_add_user_to_group').on('click',
        '#btn_display_add_user_to_group',  displayAddUserToGroup);
});
$(document).on("pageinit", "#page_view_users_list", function (event) {
    getUsers();
});
$(document).on("pageinit", "#page_view_group_list", function (event) {
    getGroups();
});
$(document).on("pageinit", "#page_add_user", function (event) {
    $('#frm_add_user').on('click', '#btn_add_user', addUser);
});
$(document).on("pageinit", "#page_add_group", function (event) {
    $('#frm_add_group').on('click', '#btn_add_group', addGroup);
});
$(document).on("pageinit", "#page_add_user_to_group", function (event) {
        buildAllGroupsList('#select_groups');
        buildGroupsForUserList(currentUser, '#list_groups_with_this_user');
        $('#frm_add_user_to_group').on('click', '#btn_add_user_to_group', addUserToGroup);
});

/**
 * Gets the full list of users in the application.
 * updating a ul in the UI that lists the users.
 */
function getUsers() {
    // Create a collection instance to keep the
    // users in.
    var users = new Apigee.Collection({
        "client": apigeeClient,
        "type": "users"
    });
    // Fetch the users from the database.
    users.fetch(
        // Called if the fetch succeeded.
        function () {
        // Clear the list of old stuff.
        $('#users_list').empty();
        if (users.hasNextEntity()){
            // Loop through the returned users,
            // adding a new list item for each.
            while (users.hasNextEntity()) {
                var user = users.getNextEntity();
                $('#users_list').append(
                '
' +
                '
' + user.get("username") + '
' +
                '
');
            }
        // If there aren't any users, add a message.
        } else {
            $('#users_list').append(
            '
' +
            '
No users to display.
' +
            '
');
        }
        // Refresh the list so that it's styled correctly.
        $('#users_list').listview('refresh');
    },
    // Called if the attempt to get users failed.
    function () {
        client.logError({tag:"getUsers",
            logMessage:"Unable to retrieve users."})
    });
}

/**
 * Gets the full list of groups from the database,
 * updating a ul in the UI with the returned values.
 */
function getGroups() {
    // A local collection variable to hold the group data.
    var groups = new Apigee.Collection({
        "client": apigeeClient,
        "type": "groups"
    });
    // Attempt to get the group data.
    groups.fetch(
    // Called if the fetch attempt succeeded.
    function () {
        // Empty the HTML list of groups.
        $('#groups_list').empty();
        // Loop through users in the collection, wrapping values from
        // each in HTML for inclusion in the UI.
        if (groups.hasNextEntity()) {
            while (groups.hasNextEntity()) {
                var group = groups.getNextEntity();
                // Build out the list with jQuery.
                $('#groups_list').append(
                '
' +
                '
' + group.get("path") + '
' +
                '
');
            }
        // If there weren't any groups, display a message.
        } else {
            $('#groups_list').append(
            '
' +
            '
No groups to display.
' +
            '
');
        }
        // Refresh the list using jQuery Mobile.
        $('#groups_list').listview('refresh');
    },
    // Called if the fetch request failed.
    function () {
        apigeeClient.logError({tag:"getGroups",
            logMessage:"Unable to retrieve groups."})
    });
}

/**
 * Adds a new user to the database.
 */
function addUser() {
    // Variable to collect data to send with the request.
    var userName = $("#fld_user_name").val(); // Must be unique.
    var name = $("#fld_name").val();
    var email = $("#fld_email").val();
    var password = $("#fld_password").val();

    // Call an SDK method to create a new user with
    // data collected from the form.
    apigeeClient.signup(userName, password, email,
        name, function (error, entity, data) {
        if (error) {
            var message = "Unable to add a user. " + data;
            apigeeClient.logError({tag:"addUser", logMessage:message})
        } else {
            // Refresh the user list to include the new user.
            getUsers();
        }
    });
}

/**
 * Add a new group to the database.
 */
function addGroup() {

    // Collect values to send with the request.
    var path = $("#fld_group_path").val();
    var title = $("#fld_display_name").val(); // Must be unique.

    // Bundle values in a JSON object.
    var options = {
        "path" : path,
        "title" : title
    }

    // Call an SDK method to create the group with the collected
    // data.
    apigeeClient.createGroup(options, function (error, response) {
        // If the attempt fails, display an error message.
        if (error) {
            var message = "Unable to add a group. " + data;
            apigeeClient.logError({tag:"addGroup", logMessage:message})
        } else {
            //Reload the list of groups from the database.
            getGroups();
        }
    });
}

/**
 * Build the list of all groups into a dropdown
 * for selecting the group to which a user should
 * be added.
 */
function buildAllGroupsList(listId){
    // Create a local collection object that points
    // at groups in the datbase.
    groups = new Apigee.Collection({
        "client": apigeeClient,
        "type": "groups"
    });
    // Attempt to get the data.
    groups.fetch(
        // If the attempt succeeds, loop through
        // the results, building options that the
        // dropdown still display.
        function () {
            $(listId).empty();
            while (groups.hasNextEntity()) {
                var group = groups.getNextEntity();
                $(listId).append(
                '<option value = \"' + group.get("path") + '\">' +
                group.get("path") + '</option>');
            }
        },
        // If the attempt fails log a message.
        function () {
            var message = "Unable to create the list of groups. " + data;
            apigeeClient.logError({tag:"buildAllGroupsList", logMessage:message})
    });
}

/**
 * Builds a list of the groups in which userName
 * belongs.
 */
function buildGroupsForUserList(userName, listId) {
    var options = {
        "username" : userName,
        "type": "users"
    }
    // Use an SDK method to get an entity object
    // representing the user whose groups should be
    // displayed.
    apigeeClient.getEntity(options, function(error, entity, data){
        if (error) {
            var message = "Error getting user entity. " + data;
            apigeeClient.logError({tag:"buildGroupsForUserList", logMessage:message})
        } else {
            // Call an SDK method to get the groups to which
            // the user belongs.
            entity.getGroups(function(error, data, groups){
                if (error){
                    var message = "Couldn't get a user's groups. " + data;
                    apigeeClient.logError({tag:"buildGroupsForUserList", logMessage:message})
               } else {
                    // Clear the list into which group data will go.
                    $(listId).empty();
                    // Loop through the list of groups, adding
                    // each to the list
                    for (var i = 0; i < groups.length; i++) {
                        var group = groups[i];
                        $(listId).append(
                        '
' +
                        '
' + group.path + '
' +
                        '
');
                    }
                    // Refresh the list to make sure it's styled.
                    $(listId).listview('refresh');
               }
            });
        }
    });
}

/**
 * Add a user to a group.
 */
function addUserToGroup() {
    // Current user set from an input on
    // the home page.
    var userName = currentUser;
    // Group selected from the dropdown.
    var selectedGroupPath = $("#select_groups").val();

    var groupOptions = {
            client:apigeeClient,
            path:selectedGroupPath
    }
    // Create a local variable that points
    // at the selected group in the database.
    var group = new Apigee.Group(groupOptions);
    // Get the group data.
    group.fetch();

    // Options for the
    var options = {
        'username':currentUser,
        'type':'users'
    }
    // Call an SDK method to get an entity representing
    // the user so it can be used when adding the
    // user to the group.
    apigeeClient.getEntity(options, function(error, entity, data){
        if (error) {
            var message = "Error getting user entity. " + data;
            apigeeClient.logError({tag:"addUserToGroup", logMessage:message})
        } else {
            var addUserOptions = {
                user : entity
            }
            // Call an SDK method to add the user.
            group.add(addUserOptions, function(error, data, entities){
                if (error){
                    var message = "Error adding user to group. " + data;
                    displayPopup(message);
                    apigeeClient.logError({tag:"addUserToGroup", logMessage:message})
                } else {
                    // Refresh the list of groups the user is in.
                    buildGroupsForUserList(currentUser, '#list_groups_with_this_user');
                }
            });
        }
    });
}

/**
 * Displays a message in a popup.
 */
function displayAddUserToGroup(){
    currentUser = $("#fld_home_username").val();
    if (currentUser.isEmpty()){
        displayPopup("Please enter the username for a user in your " +
            "application.");
    } else {
        $("#link_display_add_user_to_group").click();
    }
}

/**
 * Displays a popup.
 */
function displayPopup(message){
    var options = {
        "transition" : "slideup"
    }
    $('#messagePopup').empty();
    $('#messagePopup').append(
        '
' + message + '
'
    );
    $('#messagePopup').popup('open', options );
}

/**
 * Adds an empty string check to strings.
 */
String.prototype.isEmpty = function() {
    if (!this.match(/\S/)) {
        return true;
    } else {
        return false;
    }
}


text:
import sys
from bgenlocations import TOOLBOXDIR, BGENDIR
sys.path.append(BGENDIR)
from scantools import Scanner

LONG = "Scrap"
SHORT = "scrap"

def main():
    input = "Scrap.h"
    output = SHORT + "gen.py"
    defsoutput = "@Scrap.py"
    scanner = MyScanner(input, output, defsoutput)
    scanner.scan()
    scanner.close()
##      print "=== Testing definitions output code ==="
##      execfile(defsoutput, {}, {})
    print "=== Done scanning and generating, now importing the generated code... ==="
    exec "import " + SHORT + "support"
    print "=== Done.  It's up to you to compile it now! ==="

class MyScanner(Scanner):

    def destination(self, type, name, arglist):
        classname = "Function"
        listname = "functions"
        if arglist:
            t, n, m = arglist[0]
            if t == 'ScrapRef' and m == "InMode":
                classname = "Method"
                listname = "methods"
        return classname, listname

    def makeblacklistnames(self):
        return [
                "GetScrapFlavorInfoList",
                'InfoScrap',
                'GetScrap',
                'ZeroScrap',
                'PutScrap',
                ]

    def makeblacklisttypes(self):
        return [
                'ScrapPromiseKeeperUPP',
                ]

    def makerepairinstructions(self):
        return [
                ([('void', '*', 'OutMode')], [('putscrapbuffer', '*', 'InMode')]),
                ([('void_ptr', '*', 'InMode')], [('putscrapbuffer', '*', 'InMode')]),
                ]

if __name__ == "__main__":
    main()


text:
package org.modelmapper.bugs;

import static org.testng.Assert.assertEquals;

import org.modelmapper.AbstractTest;
import org.modelmapper.PropertyMap;
import org.testng.annotations.Test;

/**
 * http://code.google.com/p/modelmapper/issues/detail?id=22
 */
@Test
public class GC22 extends AbstractTest {
  static class PersonDTO {
    String addressCity;
    StateDTO addressState;

    public StateDTO getAddressState() {
      return addressState;
    }
  }

  static class StateDTO {
    public String getCode() {
      return code;
    }

    String code;
    String desc;
  }

  static class Person {
    Address address;

    public Address getAddress() {
      return address;
    }
  }

  static class Address {
    String city;
    String state;
    String asdfasdf;

    public void setState(String state) {
      this.state = state;
    }
  }

  public void test() {
    modelMapper.addMappings(new PropertyMap<PersonDTO, Person>() {
      @Override
      protected void configure() {
        map().getAddress().setState(source.getAddressState().getCode());
      }
    });

    PersonDTO dto = new PersonDTO();
    dto.addressCity = "San Francisco";
    dto.addressState = new StateDTO();
    dto.addressState.code = "CA";
    Person p = modelMapper.map(dto, Person.class);

    assertEquals(p.address.city, "San Francisco");
    assertEquals(p.address.state, "CA");
  }
}


text:
package com.gmail.htaihm.roomwordsample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewWordActivity extends AppCompatActivity {

  public static final String EXTRA_REPLY = "com.gmail.htaihm.roomwordsample.REPLY";

  private EditText mEditWordView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_word);

    mEditWordView = findViewById(R.id.edit_word);

    Button button = findViewById(R.id.button_save);

    button.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        Intent replyIntent = new Intent();

        if (TextUtils.isEmpty(mEditWordView.getText())) {
          setResult(RESULT_CANCELED, replyIntent);
        } else {
          String word = mEditWordView.getText().toString();
          replyIntent.putExtra(EXTRA_REPLY, word);
          setResult(RESULT_OK, replyIntent);
        }

        finish();
      }
    });
  }
}