text:
package io.disassemble.asm.util;

import io.disassemble.asm.ClassFactory;
import io.disassemble.asm.ClassField;
import io.disassemble.asm.ClassMethod;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import org.objectweb.asm.util.Printer;

import java.util.*;
import java.util.function.Predicate;

import static org.objectweb.asm.tree.AbstractInsnNode.*;

/**
 * @author Tyler Sedlar
 * @author Christopher Carpenter
 * @since 2/1/16
 */
public final class Assembly {
    private static final String[] JAVA_IDENTIFIERS = {"abstract", "assert", "boolean",
            "break", "byte", "case", "catch", "char", "class", "const",
            "continue", "default", "do", "double", "else","enum", "extends", "false",
            "final", "finally", "float", "for", "goto", "if", "implements",
            "import", "instanceof", "int", "interface", "long", "native",
            "new", "null", "package", "private", "protected", "public",
            "return", "short", "static", "strictfp", "super", "switch",
            "synchronized", "this", "throw", "throws", "transient", "true",
            "try", "void", "volatile", "while"};

    static {
        Arrays.sort(JAVA_IDENTIFIERS);
    }

    private Assembly() {
    }

    /**
     * Creates a predicate that matches any of the given opcodes.
     *
     * @param opcodes The opcodes to match.
     * @return A predicate that matches any of the given opcodes.
     */
    public static Predicate<AbstractInsnNode> createOpcodePredicate(int... opcodes) {
        Arrays.sort(opcodes);
        return insn -> (Arrays.binarySearch(opcodes, insn.getOpcode()) >= 0);
    }

    /**
     * Gets a list of instructions matching the given predicate.
     *
     * @param list      The list of instructions.
     * @param predicate The predicate to match.
     * @param <E>       A subclass of {@code AbstractInsnNode}
     * @return A list of instructions matching the given predicate.
     */
    @SuppressWarnings("unchecked")
    public static <E extends AbstractInsnNode> List<E> findAll(InsnList list, Predicate<AbstractInsnNode> predicate) {
        ListIterator<AbstractInsnNode> instructions = list.iterator();
        if (instructions.hasNext()) {
            List<E> results = new ArrayList<>(Math.min(10, list.size()));
            do {
                AbstractInsnNode insn = instructions.next();
                if (predicate.test(insn)) {
                    results.add((E) insn);
                }
            } while (instructions.hasNext());
            return results;
        }
        return new ArrayList<>();
    }

    /**
     * Checks how many instructions from the given list match the given predicate.
     *
     * @param list      The list of instructions.
     * @param predicate The predicate to match.
     * @return The amount of instructions from the given list matching the given predicate.
     */
    public static int count(InsnList list, Predicate<AbstractInsnNode> predicate) {
        return findAll(list, predicate).size();
    }

    /**
     * Finds the first occurrence of an instruction matching the given predicate.
     *
     * @param list      The list of instructions.
     * @param predicate The predicate to match.
     * @param <E>       A subclass of {@code AbstractInsnNode}
     * @return The first occurrence of an instruction matching the given predicate.
     */
    @SuppressWarnings("unchecked")
    public static <E extends AbstractInsnNode> E findFirst(InsnList list, Predicate<AbstractInsnNode> predicate) {
        AbstractInsnNode[] instructions = list.toArray();
        for (AbstractInsnNode insn : instructions) {
            if (predicate.test(insn)) {
                return (E) insn;
            }
        }
        return null;
    }

    /**
     * Finds The first occurrence of an instruction matching the given predicate, occurring after the given instruction.
     *
     * @param insn      The instruction to search after.
     * @param predicate The predicate to match.
     * @param dist      The maximum distance to search.
     * @param <E>       A subclass of {@code AbstractInsnNode}
     * @return The first occurrence of an instruction matching the given predicate, occurring after the given instruction.
     */
    @SuppressWarnings("unchecked")
    public static <E extends AbstractInsnNode> E findNext(AbstractInsnNode insn, Predicate<AbstractInsnNode> predicate,
                                                          int dist) {
        int jump = 0;
        while ((insn = insn.getNext()) != null && (dist == -1 || jump++ < dist)) {
            if (predicate.test(insn)) {
                return (E) insn;
            }
        }
        return null;
    }

    /**
     * Finds The first occurrence of an instruction matching the given predicate, occurring after the given instruction.
     *
     * @param insn      The instruction to search after.
     * @param predicate The predicate to match.
     * @param <E>       A subclass of {@code AbstractInsnNode}
     * @return The first occurrence of an instruction matching the given predicate, occurring after the given instruction.
     */
    public static <E extends AbstractInsnNode> E findNext(AbstractInsnNode insn, Predicate<AbstractInsnNode> predicate) {
        return findNext(insn, predicate, -1);
    }

    /**
     * Finds The first occurrence of an instruction matching the given predicate, occurring before the given instruction.
     *
     * @param insn      The instruction to search after.
     * @param predicate The predicate to match.
     * @param dist      The maximum distance to search.
     * @param <E>       A subclass of {@code AbstractInsnNode}
     * @return The first occurrence of an instruction matching the given predicate, occurring before the given instruction.
     */
    @SuppressWarnings("unchecked")
    public static <E extends AbstractInsnNode> E findPrevious(AbstractInsnNode insn,
                                                              Predicate<AbstractInsnNode> predicate, int dist) {
        int jump = 0;
        while ((insn = insn.getPrevious()) != null && (dist == -1 || jump++ < dist)) {
            if (predicate.test(insn)) {
                return (E) insn;
            }
        }
        return null;
    }

    /**
     * Finds The first occurrence of an instruction matching the given predicate, occurring before the given instruction.
     *
     * @param insn      The instruction to search after.
     * @param predicate The predicate to match.
     * @param <E>       A subclass of {@code AbstractInsnNode}
     * @return The first occurrence of an instruction matching the given predicate, occurring before the given instruction.
     */
    public static <E extends AbstractInsnNode> E findPrevious(AbstractInsnNode insn,
                                                              Predicate<AbstractInsnNode> predicate) {
        return findPrevious(insn, predicate, -1);
    }

    /**
     * Gets the name of the given opcode.
     *
     * @param opcode The opcode.
     * @return The name of the given opcode.
     */
    public static String opname(int opcode) {
        if (opcode >= 0 && opcode < Printer.OPCODES.length) {
            return Printer.OPCODES[opcode];
        }
        return Integer.toString(opcode);
    }

    /**
     * Renames the given field throughout the ClassFactory map with to given name.
     *
     * @param classes The map of classes to rename within.
     * @param fn      The field to rename.
     * @param newName The name to rename the field to.
     */
    public static void rename(Map<String, ClassFactory> classes, ClassField fn, String newName) {
        for (ClassFactory factory : classes.values()) {
            for (ClassMethod method : factory.methods) {
                for (AbstractInsnNode ain : method.instructions().toArray()) {
                    if (ain instanceof FieldInsnNode) {
                        FieldInsnNode fin = (FieldInsnNode) ain;
                        ClassFactory realOwner = classes.get(fin.owner);
                        while (realOwner != null) {
                            if (realOwner.findField(cf -> cf.name().equals(fin.name)) != null) {
                                break;
                            }
                            realOwner = classes.get(realOwner.superName());
                        }
                        if (realOwner != null && realOwner.name().equals(fn.owner.name()) &&
                                fin.name.equals(fn.field.name)) {
                            fin.name = newName;
                        }
                    }
                }
            }
        }
        fn.field.name = newName;
    }

    /**
     * Renames the given method throughout the ClassFactory map with to given name.
     *
     * @param classes The map of classes to rename within.
     * @param cm      The method to rename.
     * @param newName The name to rename the method to.
     */
    public static void rename(Map<String, ClassFactory> classes, ClassMethod cm, String newName) {
        for (ClassFactory factory : classes.values()) {
            for (ClassMethod method : factory.methods) {
                for (AbstractInsnNode ain : method.instructions().toArray()) {
                    if (ain instanceof MethodInsnNode) {
                        MethodInsnNode min = (MethodInsnNode) ain;
                        ClassFactory realOwner = classes.get(min.owner);
                        while (realOwner != null) {
                            if (realOwner.findMethod(
                                    m -> m.name().equals(min.name) && m.desc().equals(min.desc)
                            ) != null) {
                                break;
                            }
                            realOwner = classes.get(realOwner.superName());
                        }
                        if (realOwner != null && realOwner.name().equals(cm.owner.name()) &&
                                min.name.equals(cm.method.name)) {
                            min.name = newName;
                        }
                    }
                }
            }
        }
        cm.method.name = newName;
    }

    /**
     * Renames the given class throughout the ClassFactory map with to given name.
     *
     * @param classes The map of classes to rename within.
     * @param cf      The class to rename.
     * @param newName The name to rename the class to.
     */
    public static void rename(Map<String, ClassFactory> classes, ClassFactory cf, String newName) {
        for (ClassFactory factory : classes.values()) {
            if (factory.superName().equals(cf.name())) {
                factory.setSuperName(newName);
            }
            if (factory.interfaces().contains(cf.name())) {
                factory.interfaces().remove(cf.name());
                factory.interfaces().add(newName);
            }
            //TODO if the class factory being renamed is an annotation, check the annotations on classes to see if they need to be adjusted.
            for (ClassField field : factory.fields) {
                //Check the field annotations and their default values to determine if they should be renamed.
                if (field.desc().endsWith('L' + cf.name() + ';')) {
                    field.setDescriptor(field.desc().replace('L' + cf.name() + ';', 'L' + newName + ';'));
                }
            }
            for (ClassMethod method : factory.methods) {
                //Check if we need to rename any of the thrown exceptions or the annotation default.
                if (method.desc().contains('L' + cf.name() + ';')) {
                    method.setDescriptor(method.desc().replaceAll('L' + cf.name() + ';', 'L' + newName + ';'));
                }
                for (AbstractInsnNode ain : method.instructions().toArray()) {
                    if (ain instanceof FieldInsnNode) {
                        FieldInsnNode fin = (FieldInsnNode) ain;
                        if (fin.owner.equals(cf.name())) {
                            fin.owner = newName;
                        }
                        if (fin.desc.contains('L' + cf.name() + ';')) {
                            fin.desc = fin.desc.replace('L' + cf.name() + ';', 'L' + newName + ';');
                        }
                    } else if (ain instanceof MethodInsnNode) {
                        MethodInsnNode min = (MethodInsnNode) ain;
                        if (min.owner.equals(cf.name())) {
                            min.owner = newName;
                        }
                        if (min.desc.contains('L' + cf.name() + ';')) {
                            min.desc = min.desc.replaceAll('L' + cf.name() + ';', 'L' + newName + ';');
                        }
                    } else if (ain instanceof TypeInsnNode) {
                        TypeInsnNode tin = (TypeInsnNode) ain;
                        if (tin.desc.equals(cf.name())) {
                            tin.desc = newName;
                        } else if (tin.desc.contains('L' + cf.name() + ';')) {
                            tin.desc = tin.desc.replace('L' + cf.name() + ';', 'L' + newName + ';');
                        }
                    } else if (ain instanceof MultiANewArrayInsnNode) {
                        MultiANewArrayInsnNode manain = (MultiANewArrayInsnNode) ain;
                        if (manain.desc.contains('L' + cf.name() + ';')) {
                            manain.desc = manain.desc.replace('L' + cf.name() + ';', 'L' + newName + ';');
                        }
                    } else if (ain instanceof LdcInsnNode) {
                        LdcInsnNode ldc = (LdcInsnNode) ain;
                        Object cst = ldc.cst;
                        if (cst != null && cst instanceof String) {
                            String cstString = (String) cst;
                            if (cstString.startsWith(cf.name() + '.') && cstString.contains("(")) {
                                ldc.cst = cstString.replace(cf.name() + '.', newName + '.');
                            }
                        }
                    }
                }
            }
        }
        cf.setName(newName);
    }

    /**
     * Checks whether the given instructions are similar to each other.
     *
     * @param insn1 The first instruction to compare.
     * @param insn2 The second instruction to compare.
     * @return true if the instructions are similar, otherwise false.
     */
    public static boolean instructionsEqual(AbstractInsnNode insn1, AbstractInsnNode insn2) {
        if (insn1 == insn2) {
            return true;
        }
        if (insn1 == null || insn2 == null) {
            return false;
        }
        if (insn1.getType() != insn2.getType() || insn1.getOpcode() != insn2.getOpcode()) {
            return false;
        }
        int size;
        switch (insn1.getType()) {
            case INSN: {
                return true;
            }
            case INT_INSN: {
                IntInsnNode iin1 = (IntInsnNode) insn1, iin2 = (IntInsnNode) insn2;
                return iin1.operand == iin2.operand;
            }
            case VAR_INSN: {
                VarInsnNode vin1 = (VarInsnNode) insn1, vin2 = (VarInsnNode) insn2;
                return vin1.var == vin2.var;
            }
            case TYPE_INSN: {
                TypeInsnNode tin1 = (TypeInsnNode) insn1, tin2 = (TypeInsnNode) insn2;
                return tin1.desc.equals(tin2.desc);
            }
            case FIELD_INSN: {
                FieldInsnNode fin1 = (FieldInsnNode) insn1, fin2 = (FieldInsnNode) insn2;
                return fin1.desc.equals(fin2.desc) && fin1.name.equals(fin2.name) && fin1.owner.equals(fin2.owner);
            }
            case METHOD_INSN: {
                MethodInsnNode min1 = (MethodInsnNode) insn1, min2 = (MethodInsnNode) insn2;
                return min1.desc.equals(min2.desc) && min1.name.equals(min2.name) && min1.owner.equals(min2.owner);
            }
            case INVOKE_DYNAMIC_INSN: {
                InvokeDynamicInsnNode idin1 = (InvokeDynamicInsnNode) insn1, idin2 = (InvokeDynamicInsnNode) insn2;
                return idin1.bsm.equals(idin2.bsm) && Arrays.equals(idin1.bsmArgs, idin2.bsmArgs) &&
                        idin1.desc.equals(idin2.desc) && idin1.name.equals(idin2.name);
            }
            case JUMP_INSN: {
                JumpInsnNode jin1 = (JumpInsnNode) insn1, jin2 = (JumpInsnNode) insn2;
                return instructionsEqual(jin1.label, jin2.label);
            }
            case LABEL: {
                Label label1 = ((LabelNode) insn1).getLabel(), label2 = ((LabelNode) insn2).getLabel();
                return label1 == null ? label2 == null : label1.info == null ? label2.info == null :
                        label1.info.equals(label2.info);
            }
            case LDC_INSN: {
                LdcInsnNode lin1 = (LdcInsnNode) insn1, lin2 = (LdcInsnNode) insn2;
                return lin1.cst.equals(lin2.cst);
            }
            case IINC_INSN: {
                IincInsnNode iiin1 = (IincInsnNode) insn1, iiin2 = (IincInsnNode) insn2;
                return iiin1.incr == iiin2.incr && iiin1.var == iiin2.var;
            }
            case TABLESWITCH_INSN: {
                TableSwitchInsnNode tsin1 = (TableSwitchInsnNode) insn1, tsin2 = (TableSwitchInsnNode) insn2;
                size = tsin1.labels.size();
                if (size != tsin2.labels.size()) {
                    return false;
                }
                for (int i = 0; i < size; i++) {
                    if (!instructionsEqual(tsin1.labels.get(i), tsin2.labels.get(i))) {
                        return false;
                    }
                }
                return instructionsEqual(tsin1.dflt, tsin2.dflt) && tsin1.max == tsin2.max && tsin1.min == tsin2.min;
            }
            case LOOKUPSWITCH_INSN: {
                LookupSwitchInsnNode lsin1 = (LookupSwitchInsnNode) insn1, lsin2 = (LookupSwitchInsnNode) insn2;
                size = lsin1.labels.size();
                if (size != lsin2.labels.size()) {
                    return false;
                }
                for (int i = 0; i < size; i++) {
                    if (!instructionsEqual(lsin1.labels.get(i), lsin2.labels.get(i))) {
                        return false;
                    }
                }
                return instructionsEqual(lsin1.dflt, lsin2.dflt) && lsin1.keys.equals(lsin2.keys);
            }
            case MULTIANEWARRAY_INSN: {
                MultiANewArrayInsnNode manain1 = (MultiANewArrayInsnNode) insn1, manain2 = (MultiANewArrayInsnNode) insn2;
                return manain1.desc.equals(manain2.desc) && manain1.dims == manain2.dims;
            }
            case FRAME: {
                FrameNode fn1 = (FrameNode) insn1, fn2 = (FrameNode) insn2;
                return fn1.local.equals(fn2.local) && fn1.stack.equals(fn2.stack);
            }
            case LINE: {
                LineNumberNode lnn1 = (LineNumberNode) insn1, lnn2 = (LineNumberNode) insn2;
                return lnn1.line == lnn2.line && instructionsEqual(lnn1.start, lnn2.start);
            }
        }
        return false;
    }

    /**
     * Checks whether the given instruction arrays are similar.
     *
     * @param insns  The first instruction array to compare.
     * @param insns2 The second instruction array to compare.
     * @return true if the given instruction arrays are similar, otherwise false.
     */
    public static boolean instructionsEqual(AbstractInsnNode[] insns, AbstractInsnNode[] insns2) {
        if (insns == insns2) {
            return true;
        }
        if (insns == null || insns2 == null) {
            return false;
        }
        int length = insns.length;
        if (insns2.length != length) {
            return false;
        }
        for (int i = 0; i < length; i++) {
            AbstractInsnNode insn1 = insns[i], insn2 = insns2[i];
            if (!(insn1 == null ? insn2 == null : instructionsEqual(insn1, insn2))) {
                return false;
            }
        }
        return true;
    }

    /**
     * Gives a string representation of the given instruction.
     *
     * @param insn The instruction to represent.
     * @return A string representation of the given instruction.
     */
    public static String toString(AbstractInsnNode insn) {
        if (insn == null) {
            return "null";
        }
        int op = insn.getOpcode();
        if (op == -1) {
            if (insn instanceof LabelNode) {
                return (insn.getClass().getSimpleName() + insn.toString().split(insn.getClass().getSimpleName())[1]);
            }
            return insn.toString();
        }
        StringBuilder builder = new StringBuilder();
        builder.append(Printer.OPCODES[op]);
        switch (insn.getType()) {
            case INT_INSN: {
                builder.append(' ');
                builder.append(((IntInsnNode) insn).operand);
                break;
            }
            case VAR_INSN: {
                builder.append(' ');
                builder.append('#');
                builder.append(((VarInsnNode) insn).var);
                break;
            }
            case TYPE_INSN: {
                builder.append(' ');
                builder.append(((TypeInsnNode) insn).desc);
                break;
            }
            case FIELD_INSN: {
                FieldInsnNode fin = (FieldInsnNode) insn;
                builder.append(' ');
                builder.append(fin.owner);
                builder.append('.');
                builder.append(fin.name);
                builder.append(' ');
                builder.append(fin.desc);
                break;
            }
            case METHOD_INSN: {
                MethodInsnNode min = (MethodInsnNode) insn;
                builder.append(' ');
                builder.append(min.owner);
                builder.append('.');
                builder.append(min.name);
                builder.append(' ');
                builder.append(min.desc);
                break;
            }
            case JUMP_INSN:
            case TABLESWITCH_INSN:
            case LOOKUPSWITCH_INSN: {
                if (op == Opcodes.GOTO) {
                    JumpInsnNode jin = (JumpInsnNode) insn;
                    builder.append(' ');
                    builder.append(Assembly.toString(jin.label));
                }
                break;
            }
            case LDC_INSN: {
                Object cst = ((LdcInsnNode) insn).cst;
                builder.append(' ');
                builder.append(cst.getClass().getName());
                builder.append(' ');
                builder.append(cst);
                break;
            }
            case IINC_INSN: {
                IincInsnNode iin = (IincInsnNode) insn;
                builder.append(' ');
                builder.append('#');
                builder.append(iin.var);
                builder.append(' ');
                builder.append(iin.incr);
                break;
            }
            case MULTIANEWARRAY_INSN: {
                MultiANewArrayInsnNode m = (MultiANewArrayInsnNode) insn;
                builder.append(' ');
                builder.append(m.desc);
                builder.append(' ');
                builder.append(m.dims);
                break;
            }
        }
        return builder.toString();
    }

    public static boolean isJavaIdentifier(String string) {
        return Arrays.binarySearch(JAVA_IDENTIFIERS, string) >= 0;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>net.jini.core.transaction (River-Internet vtrunk API Documentation)</title>
<meta name="date" content="2016-03-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

net.jini.core.transaction

Interfaces

NestableTransaction

Transaction

Classes

NestableTransaction.Created

Transaction.Created

TransactionFactory

Exceptions

CannotAbortException

CannotCommitException

CannotJoinException

CannotNestException

TimeoutExpiredException

TransactionException

UnknownTransactionException

redpajama_set_name: RedPajamaGithub


text:
package hska.iwi.eShopMaster.controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import hska.iwi.eShopMaster.model.businessLogic.manager.CategoryManager;
import hska.iwi.eShopMaster.model.businessLogic.manager.ProductManager;
import hska.iwi.eShopMaster.model.businessLogic.manager.entity.Category;
import hska.iwi.eShopMaster.model.businessLogic.manager.entity.User;
import hska.iwi.eShopMaster.model.businessLogic.manager.impl.CategoryManagerImpl;
import hska.iwi.eShopMaster.model.businessLogic.manager.impl.ProductManagerImpl;
import java.util.List;
import java.util.Map;

public class AddProductAction extends ActionSupport {

  private static final long serialVersionUID = 39979991339088L;

  private String name = null;
  private String price = null;
  private int categoryId = 0;
  private String details = null;
  private List<Category> categories;

  public String execute() throws Exception {
    String result = "input";
    Map<String, Object> session = ActionContext.getContext().getSession();
    User user = (User) session.get("webshop_user");

    if (user instanceof User && user.getRole().equals("Admin")) {

      ProductManager productManager = new ProductManagerImpl(user);
      int productId = productManager.addProduct(name, Double.parseDouble(price), categoryId,
          details);

      if (productId > 0) {
        result = "success";
      }
    }

    return result;
  }

  @Override
  public void validate() {
    Map<String, Object> session = ActionContext.getContext().getSession();
    User user = (User) session.get("webshop_user");

    CategoryManager categoryManager = new CategoryManagerImpl(user);
    this.setCategories(categoryManager.getCategories());
    // Validate name:

    if (getName() == null || getName().length() == 0) {
      addActionError(getText("error.product.name.required"));
    }

    // Validate price:

    if (String.valueOf(getPrice()).length() > 0) {
      if (!getPrice().matches("[0-9]+(.[0-9][0-9]?)?")
          || Double.parseDouble(getPrice()) < 0.0) {
        addActionError(getText("error.product.price.regex"));
      }
    } else {
      addActionError(getText("error.product.price.required"));
    }
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPrice() {
    return price;
  }

  public void setPrice(String price) {
    this.price = price;
  }

  public int getCategoryId() {
    return categoryId;
  }

  public void setCategoryId(int categoryId) {
    this.categoryId = categoryId;
  }

  public String getDetails() {
    return details;
  }

  public void setDetails(String details) {
    this.details = details;
  }

  public List<Category> getCategories() {
    return categories;
  }

  public void setCategories(List<Category> categories) {
    this.categories = categories;
  }
}


text:
TEST_F(TiledFixture, ImageLayer_should_have_parsed_properly)
{
    auto img = _parsedMap->getImageLayer("Image Layer 1");
    auto image = img.get_image();
    ASSERT_EQ(img.get_name(), "Image Layer 1");
    ASSERT_EQ(image.source, "../Pictures/newclass.PNG");
    ASSERT_EQ(image.width, 876);
    ASSERT_EQ(image.height, 622);
}


text:
package dao;

import com.google.inject.Singleton;
import conf.Caches;
import models.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.cache.annotation.CacheDefaults;
import javax.cache.annotation.CacheResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author James Moger
 */
@Singleton
@CacheDefaults(cacheName = Caches.ITEMS_CACHE)
public class ItemDao {

    final Map<Integer, Item> items;
    private final Logger log = LoggerFactory.getLogger(ItemDao.class);

    public ItemDao() {
        this.items = new TreeMap<Integer, Item>() {{
            put(1, new Item(1, "Apples"));
            put(2, new Item(2, "Bananas"));
            put(3, new Item(3, "Strawberries"));
            put(4, new Item(4, "Grapes"));
            put(5, new Item(5, "Kiwi"));
        }};
    }

    @CacheResult
    public Item get(int id) {
        log.info("Getting Item #{} by id", id);
        return items.get(id);
    }

    @CacheResult
    public List<Item> getAll() {
        log.info("Getting all items");
        return new ArrayList<>(items.values());
    }
}


text:
@interface TGMeView : UITableView

@end


text:
'Expression'.subclass(I => {
  "use strict";
  I.am({
    Abstract: false
  });
  I.know({
    pushEvaluation: function(evaluation) {
      return evaluation.typespace.numberType;
    }
  });
})


text:
package org.apache.sling.commons.osgi;

import java.util.Map;

import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;

/**
 * The ServiceUtil is a utility class providing some
 * useful utility methods for service handling.
 * @since 2.1
 */
public class ServiceUtil {

    /**
     * @deprecated Use {@link #getComparableForServiceRanking(Map, Order)} instead.
     * @param props The service properties.
     * @return the same comparable as returned by {@code getComparableForServiceRanking(Map, Order.ASCENDING)}
     * @see #getComparableForServiceRanking(Map, Order)
     */
    @Deprecated
    public static Comparable<Object> getComparableForServiceRanking(final Map<String, Object> props) {
        return getComparableForServiceRanking(props, Order.ASCENDING);
    }

    /**
     * Create a comparable object out of the service properties. With the result
     * it is possible to compare service properties based on the service ranking
     * of a service. This object acts like {@link ServiceReference#compareTo(Object)}.
     * The comparator will return the services in the given order. In ascending order the
     * service with the lowest ranking comes first, in descending order the service with the
     * highest ranking comes first. The latter is useful if you want to have the service
     * returned first which is also chosen by {@link BundleContext#getServiceReference(String)}.
     * @param props The service properties.
     * @param order The order (either ascending or descending).
     * @return A comparable for the ranking of the service
     * @since 2.4
     */
    public static Comparable<Object> getComparableForServiceRanking(final Map<String, Object> props, Order order) {
        return new ComparableImplementation(props, order);
    }

    private static final class ComparableImplementation implements Comparable<Object> {

        private final Map<String, Object> props;
        private final Order order;

        private ComparableImplementation(Map<String, Object> props, Order order) {
            this.props = props;
            this.order = order;
        }

        @SuppressWarnings("unchecked")
        public int compareTo(Object reference) {
            final Long otherId;
            Object otherRankObj;
            if ( reference instanceof ServiceReference ) {
                final ServiceReference other = (ServiceReference) reference;
                otherId = (Long) other.getProperty(Constants.SERVICE_ID);
                otherRankObj = other.getProperty(Constants.SERVICE_RANKING);
            } else if (reference instanceof Map){
                final Map<String, Object> otherProps = (Map<String, Object>)reference;
                otherId = (Long) otherProps.get(Constants.SERVICE_ID);
                otherRankObj = otherProps.get(Constants.SERVICE_RANKING);
            } else {
                final ComparableImplementation other = (ComparableImplementation)reference;
                otherId = (Long) other.props.get(Constants.SERVICE_ID);
                otherRankObj = other.props.get(Constants.SERVICE_RANKING);
            }
            final Long id = (Long) props.get(Constants.SERVICE_ID);
            if (id.equals(otherId)) {
                return 0; // same service
            }

            Object rankObj = props.get(Constants.SERVICE_RANKING);

            // If no rank, then spec says it defaults to zero.
            rankObj = (rankObj == null) ? new Integer(0) : rankObj;
            otherRankObj = (otherRankObj == null) ? new Integer(0) : otherRankObj;

            // If rank is not Integer, then spec says it defaults to zero.
            Integer rank = (rankObj instanceof Integer)
                ? (Integer) rankObj : new Integer(0);
            Integer otherRank = (otherRankObj instanceof Integer)
                ? (Integer) otherRankObj : new Integer(0);

            // Sort by rank.
            if (rank.compareTo(otherRank) < 0) {
                return order.lessThan; // lower rank
            } else if (rank.compareTo(otherRank) > 0) {
                return order.greaterThan; // higher rank
            }

            // If ranks are equal, then sort by service id.
            return (id.compareTo(otherId) < 0) ? order.greaterThan : order.lessThan;
        }

        @Override
        public boolean equals(Object obj) {
            if ( obj instanceof ComparableImplementation ) {
                return this.props.equals(((ComparableImplementation)obj).props);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return this.props.hashCode();
        }
    }
}


text:
package org.avantssar.aslan;

public interface ISymbol extends INamed {

	IType getType();

}


text:
'use strict';

exports.BattleFormats = {
	pokemon: {
		effectType: 'Banlist',
		onValidateSet: function (set, format) {
			let template = this.getTemplate(set.species);
			let problems = [];
			if (set.species === set.name) delete set.name;

			if (template.gen > this.gen) {
				problems.push(set.species + ' does not exist in gen ' + this.gen + '.');
			} else if (template.isNonstandard) {
				problems.push(set.species + ' is not a real Pokemon.');
			}
			if (set.moves) {
				for (let i = 0; i < set.moves.length; i++) {
					let move = this.getMove(set.moves[i]);
					if (move.gen > this.gen && move.id !== 'hiddenpower') {
						problems.push(move.name + ' does not exist in gen ' + this.gen + '.');
					} else if (move.isNonstandard) {
						problems.push(move.name + ' is not a real move.');
					}
				}
			}
			if (set.moves && set.moves.length > 4) {
				problems.push((set.name || set.species) + ' has more than four moves.');
			}

			// Let's manually delete items.
			set.item = '';

			// Automatically set ability to None
			set.ability = 'None';

			// Maximise EVs by default
			if (!set.evs) {
				set.evs = {hp: 255, atk: 255, def: 255, spa: 255, spd: 255, spe: 255};
			} else {
				// If EVs are set manually to lower attack for confusion damage, make attack minimum possible.
				// Each EV is 257 Stat points, that is, 30 EVs.
				// Minimum attack you can have at level 100 is 30.
				set.evs.hp = 255;
				set.evs.def = 255;
				set.evs.spa = 255;
				set.evs.spd = 255;
				set.evs.spe = 255;
				if (set.evs.atk < 30) {
					set.evs.atk = 30;
				} else {
					set.evs.atk = 255;
				}
			}

			// IVs worked different (DVs, 0 to 15, 2 points each) so we put all IVs to 30
			if (!set.ivs) {
				set.ivs = {hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30};
			} else {
				// Unless minimising Attack DV for confusion damage.
				set.ivs.hp = 30;
				set.ivs.def = 30;
				set.ivs.spa = 30;
				set.ivs.spd = 30;
				set.ivs.spe = 30;
				if (set.ivs.atk < 30) {
					// Make it odd DVs (1 DV = 2 IV) so we still have max HP.
					set.ivs.atk = 2;
				} else {
					set.ivs.atk = 30;
				}
			}

			// They also get a useless nature, since that didn't exist
			set.nature = 'Serious';

			// No shinies
			set.shiny = false;

			return problems;
		},
	},
	standard: {
		effectType: 'Banlist',
		ruleset: ['Sleep Clause Mod', 'Freeze Clause Mod', 'Species Clause', 'OHKO Clause', 'Evasion Moves Clause', 'HP Percentage Mod', 'Cancel Mod'],
		banlist: ['Unreleased', 'Illegal', 'Dig', 'Fly',
			'Kakuna + Poison Sting + Harden', 'Kakuna + String Shot + Harden',
			'Beedrill + Poison Sting + Harden', 'Beedrill + String Shot + Harden',
			'Nidoking + Fury Attack + Thrash',
			'Exeggutor + Poison Powder + Stomp', 'Exeggutor + Sleep Powder + Stomp', 'Exeggutor + Stun Spore + Stomp',
			'Eevee + Tackle + Growl',
			'Vaporeon + Tackle + Growl',
			'Jolteon + Tackle + Growl', 'Jolteon + Focus Energy + Thunder Shock',
			'Flareon + Tackle + Growl', 'Flareon + Focus Energy + Ember',
		],
		onValidateSet: function (set) {
			// limit one of each move in Standard
			let moves = [];
			if (set.moves) {
				let hasMove = {};
				for (let i = 0; i < set.moves.length; i++) {
					let move = this.getMove(set.moves[i]);
					let moveid = move.id;
					if (hasMove[moveid]) continue;
					hasMove[moveid] = true;
					moves.push(set.moves[i]);
				}
			}
			set.moves = moves;
		},
	},
};


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.1.1.3_A3.1;
 * @section: 15.1.1.3, 11.4.1;
 * @assertion: The undefined is DontDelete;
 * @description: Use delete;
*/

// CHECK#1
if (delete undefined !== false) {
	$ERROR('#1: delete undefined === false. Actual: ' + (delete undefined));
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var Subject_1 = require('rxjs/Subject');
var ToastService = (function () {
    function ToastService() {
        this._toastSubject = new Subject_1.Subject();
        this.toastState = this._toastSubject.asObservable();
    }
    ToastService.prototype.activate = function (message, success) {
        this._toastSubject.next({ message: message, success: success });
    };
    ToastService = __decorate([
        core_1.Injectable(),
        __metadata('design:paramtypes', [])
    ], ToastService);
    return ToastService;
}());
exports.ToastService = ToastService;
//# sourceMappingURL=toast.service.js.map


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <versioning>
    <release>1.12.2</release>
    <versions>
      <version>1.12.2</version>
    </versions>
    <lastUpdated>20150125035121</lastUpdated>
  </versioning>
</metadata>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>New Test</title>

New Test

	open
	/run/com.vaadin.tests.components.tabsheet.TabSheetIndexOperations?restartApplication

	click
	vaadin=runcomvaadintestscomponentstabsheetTabSheetIndexOperations::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[1]/VButton[0]/domChild[0]/domChild[0]

	assertText
	vaadin=runcomvaadintestscomponentstabsheetTabSheetIndexOperations::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[0]/VTabsheet[0]/domChild[0]/domChild[0]/domChild[0]/domChild[0]/domChild[2]/domChild[0]/domChild[0]/domChild[0]
	Added Tab 1

	click
	vaadin=runcomvaadintestscomponentstabsheetTabSheetIndexOperations::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[2]/VButton[0]/domChild[0]/domChild[0]

	assertText
	vaadin=runcomvaadintestscomponentstabsheetTabSheetIndexOperations::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[0]/VTabsheet[0]/domChild[0]/domChild[0]/domChild[0]/domChild[0]/domChild[2]/domChild[0]/domChild[0]/domChild[0]
	1 baT deddA

	click
	vaadin=runcomvaadintestscomponentstabsheetTabSheetIndexOperations::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[3]/VButton[0]/domChild[0]/domChild[0]

	assertText
	vaadin=runcomvaadintestscomponentstabsheetTabSheetIndexOperations::/VVerticalLayout[0]/ChildComponentContainer[1]/VVerticalLayout[0]/ChildComponentContainer[0]/VTabsheet[0]/domChild[0]/domChild[0]/domChild[0]/domChild[0]/domChild[2]/domChild[0]/domChild[0]/domChild[0]
	Tab 1


text:
package com.lrother.suse.access;

@FunctionalInterface
public interface AccessKey{

    String getKey();

}


text:
import basic_container

class RubyContainer(basic_container.BasicContainer):

    def __init__(self):
	super(self.__class__, self).__init__()

	self.image = "ruby"
	self.command = "ruby main.rb"
	self.file_extension = ".rb"


text:
@implementation LUBAPI

+ (void)postToMicroBlogWithTitleText:(nullable NSString *)titleTextOrNil
                            postText:(NSString *)postText
                    customPostingURL:(nullable NSString *)customPostingURLOrNil
                            appToken:(NSString *)appToken
                          completion:(void (^)(BOOL success, NSString * _Nullable postURL))completion;
{
    NSString *postingURLString = @"https://micro.blog/micropub";
    if (customPostingURLOrNil) {
        postingURLString = customPostingURLOrNil;
    }

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:postingURLString]];
    request.HTTPMethod = @"POST";

    [request addValue:[NSString stringWithFormat:@"Bearer %@", appToken]
   forHTTPHeaderField:@"Authorization"];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSMutableDictionary *bodyParams = [@{
                                         @"h": @"entry",
                                         @"content": postText ?: @"",
                                         } mutableCopy];
    if (titleTextOrNil) {
        bodyParams[@"name"] = titleTextOrNil;
    }

    request.HTTPBody = [[self queryStringFromParameters:[bodyParams copy]] dataUsingEncoding:NSUTF8StringEncoding];

    [[NSURLSession.sharedSession dataTaskWithRequest:request
                                   completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                       DLog(@"%@", response);
                                       if (error) {
                                           NSLog(@"%@", error);
                                       }

                                       NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;

                                       NSInteger statusCode = urlResponse.statusCode;
                                       BOOL requestWasSuccessful = (statusCode == 201 || statusCode == 202);

                                       [NSOperationQueue.mainQueue addOperationWithBlock:^{
                                           NSString *postURL = urlResponse.allHeaderFields[@"Location"];
                                           completion(requestWasSuccessful, postURL);
                                       }];
                                   }] resume];
}

+ (nullable NSString *)queryStringFromParameters:(NSDictionary *)parameters
{
    NSMutableArray<NSURLQueryItem *> *queryItems = [NSMutableArray arrayWithCapacity:parameters.count];

    [parameters enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL *_Nonnull stop) {
        [queryItems addObject:[NSURLQueryItem queryItemWithName:key value:value]];
    }];

    NSURLComponents *urlComponents = [[NSURLComponents alloc] init];
    urlComponents.queryItems = queryItems;

    return urlComponents.percentEncodedQuery;
}

@end


text:
#ifndef JUCE_BOOLEANPROPERTYCOMPONENT_H_INCLUDED
#define JUCE_BOOLEANPROPERTYCOMPONENT_H_INCLUDED

//==============================================================================
/**
    A PropertyComponent that contains an on/off toggle button.

    This type of property component can be used if you have a boolean value to
    toggle on/off.

    @see PropertyComponent
*/
class JUCE_API  BooleanPropertyComponent  : public PropertyComponent,
                                            private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
{
protected:
    //==============================================================================
    /** Creates a button component.

        If you use this constructor, you must override the getState() and setState()
        methods.

        @param propertyName         the property name to be passed to the PropertyComponent
        @param buttonTextWhenTrue   the text shown in the button when the value is true
        @param buttonTextWhenFalse  the text shown in the button when the value is false
    */
    BooleanPropertyComponent (const String& propertyName,
                              const String& buttonTextWhenTrue,
                              const String& buttonTextWhenFalse);

public:
    /** Creates a button component.

        Note that if you call this constructor then you must use the Value to interact with the
        button state, and you can't override the class with your own setState or getState methods.
        If you want to use getState and setState, call the other constructor instead.

        @param valueToControl       a Value object that this property should refer to.
        @param propertyName         the property name to be passed to the PropertyComponent
        @param buttonText           the text shown in the ToggleButton component
    */
    BooleanPropertyComponent (const Value& valueToControl,
                              const String& propertyName,
                              const String& buttonText);

    /** Destructor. */
    ~BooleanPropertyComponent();

    //==============================================================================
    /** Called to change the state of the boolean value. */
    virtual void setState (bool newState);

    /** Must return the current value of the property. */
    virtual bool getState() const;

    //==============================================================================
    /** A set of colour IDs to use to change the colour of various aspects of the component.

        These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
        methods.

        @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
    */
    enum ColourIds
    {
        backgroundColourId          = 0x100e801,    /**< The colour to fill the background of the button area. */
        outlineColourId             = 0x100e803,    /**< The colour to use to draw an outline around the text area. */
    };

    //==============================================================================
    /** @internal */
    void paint (Graphics&) override;
    /** @internal */
    void refresh() override;
    /** @internal */
    void buttonClicked (Button*) override;

private:
    ToggleButton button;
    String onText, offText;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent)
};

#endif   // JUCE_BOOLEANPROPERTYCOMPONENT_H_INCLUDED


text:
package kbasesearchengine.main;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import kbasesearchengine.tools.Utils;

import com.google.common.base.Ticker;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.Weigher;

/** A caching layer for workspace and narrative info. Caches the results in memory for quick access.
 * @author gaprice@lbl.gov
 * @author ganapathy@bnl.gov
 */

public class NarrativeInfoCache implements NarrativeInfoProvider {

    private final LoadingCache<Long, NarrativeInfo> cache;

    /** Create a cache.
     * @param provider the {@link NarrativeInfoProvider} whose results will be cached.
     * @param cacheLifeTimeInSec the number of seconds a set of narrative info for a user should
     * remain in the cache.
     * @param cacheSizeInNarrativeInfo the maximum number of narrative info, across all users, to
     * store in the cache.
     */
    public NarrativeInfoCache(
            final NarrativeInfoProvider provider,
            final int cacheLifeTimeInSec,
            final int cacheSizeInNarrativeInfo) {
        this(provider, cacheLifeTimeInSec, cacheSizeInNarrativeInfo, Ticker.systemTicker());
    }

    /** Create a cache for testing purposes.
     * @param cacheLifeTimeInSec the number of seconds an set of narrative info for a user should
     * remain in the cache.
     * @param cacheSizeInNarrativeInfo the maximum number of narrative info, across all users, to
     * store in the cache.
     * @param ticker a ticker implementation that allows controlling cache expiration with the
     * provided ticker rather than waiting for the system clock. This is exposed for testing
     * purposes.
     */
    public NarrativeInfoCache(
            final NarrativeInfoProvider provider,
            final int cacheLifeTimeInSec,
            final int cacheSizeInNarrativeInfo,
            final Ticker ticker) {

        Utils.nonNull(provider, "provider");

        if (cacheLifeTimeInSec < 1) {
            throw new IllegalArgumentException("cache lifetime must be at least one second");
        }
        if (cacheSizeInNarrativeInfo < 1) {
            throw new IllegalArgumentException("cache size must be at least one");
        }
        cache = CacheBuilder.newBuilder()
                .ticker(ticker)
                .expireAfterWrite(cacheLifeTimeInSec, TimeUnit.SECONDS)
                .maximumWeight(cacheSizeInNarrativeInfo)
                .weigher(new Weigher<Long, NarrativeInfo>() {

                    @Override
                    public int weigh(Long wsId, NarrativeInfo narrativeInfo)
                    {
                        return narrativeInfo.getNumElements();
                    }
                })
                .build(new CacheLoader<Long, NarrativeInfo>() {

                    @Override
                    public NarrativeInfo load(Long wsId) throws Exception {
                        return provider.findNarrativeInfo(wsId);
                    }
                });
    }

    @Override
    public NarrativeInfo findNarrativeInfo(final Long wsId) throws IOException {
        try {
            return cache.get(wsId);
        } catch (ExecutionException e) {
            throw (IOException) e.getCause(); // IOE is the only checked exception
            // unchecked exceptions are wrapped in UncheckedExcecutionException
        }
    }
}


text:
import six
import time

from airflow.exceptions import AirflowException
from airflow.contrib.hooks.databricks_hook import DatabricksHook
from airflow.models import BaseOperator

class DatabricksSubmitRunOperator(BaseOperator):
    """
    Submits an Spark job run to Databricks using the
    `api/2.0/jobs/runs/submit
    <https://docs.databricks.com/api/latest/jobs.html#runs-submit>`_
    API endpoint.

    There are two ways to instantiate this operator.

    In the first way, you can take the JSON payload that you typically use
    to call the ``api/2.0/jobs/runs/submit`` endpoint and pass it directly
    to our ``DatabricksSubmitRunOperator`` through the ``json`` parameter.
    For example ::
        json = {
          'new_cluster': {
            'spark_version': '2.1.0-db3-scala2.11',
            'num_workers': 2
          },
          'notebook_task': {
            'notebook_path': '/Users/airflow@example.com/PrepareData',
          },
        }
        notebook_run = DatabricksSubmitRunOperator(task_id='notebook_run', json=json)

    Another way to accomplish the same thing is to use the named parameters
    of the ``DatabricksSubmitRunOperator`` directly. Note that there is exactly
    one named parameter for each top level parameter in the ``runs/submit``
    endpoint. In this method, your code would look like this: ::
        new_cluster = {
          'spark_version': '2.1.0-db3-scala2.11',
          'num_workers': 2
        }
        notebook_task = {
          'notebook_path': '/Users/airflow@example.com/PrepareData',
        }
        notebook_run = DatabricksSubmitRunOperator(
            task_id='notebook_run',
            new_cluster=new_cluster,
            notebook_task=notebook_task)

    In the case where both the json parameter **AND** the named parameters
    are provided, they will be merged together. If there are conflicts during the merge,
    the named parameters will take precedence and override the top level ``json`` keys.

    Currently the named parameters that ``DatabricksSubmitRunOperator`` supports are
        - ``spark_jar_task``
        - ``notebook_task``
        - ``new_cluster``
        - ``existing_cluster_id``
        - ``libraries``
        - ``run_name``
        - ``timeout_seconds``

    :param json: A JSON object containing API parameters which will be passed
        directly to the ``api/2.0/jobs/runs/submit`` endpoint. The other named parameters
        (i.e. ``spark_jar_task``, ``notebook_task``..) to this operator will
        be merged with this json dictionary if they are provided.
        If there are conflicts during the merge, the named parameters will
        take precedence and override the top level json keys. This field will be
        templated.

        .. seealso::
            For more information about templating see :ref:`jinja-templating`.
            https://docs.databricks.com/api/latest/jobs.html#runs-submit
    :type json: dict
    :param spark_jar_task: The main class and parameters for the JAR task. Note that
        the actual JAR is specified in the ``libraries``.
        *EITHER* ``spark_jar_task`` *OR* ``notebook_task`` should be specified.
        This field will be templated.

        .. seealso::
            https://docs.databricks.com/api/latest/jobs.html#jobssparkjartask
    :type spark_jar_task: dict
    :param notebook_task: The notebook path and parameters for the notebook task.
        *EITHER* ``spark_jar_task`` *OR* ``notebook_task`` should be specified.
        This field will be templated.

        .. seealso::
            https://docs.databricks.com/api/latest/jobs.html#jobsnotebooktask
    :type notebook_task: dict
    :param new_cluster: Specs for a new cluster on which this task will be run.
        *EITHER* ``new_cluster`` *OR* ``existing_cluster_id`` should be specified.
        This field will be templated.

        .. seealso::
            https://docs.databricks.com/api/latest/jobs.html#jobsclusterspecnewcluster
    :type new_cluster: dict
    :param existing_cluster_id: ID for existing cluster on which to run this task.
        *EITHER* ``new_cluster`` *OR* ``existing_cluster_id`` should be specified.
        This field will be templated.
    :type existing_cluster_id: string
    :param libraries: Libraries which this run will use.
        This field will be templated.

        .. seealso::
            https://docs.databricks.com/api/latest/libraries.html#managedlibrarieslibrary
    :type libraries: list of dicts
    :param run_name: The run name used for this task.
        By default this will be set to the Airflow ``task_id``. This ``task_id`` is a
        required parameter of the superclass ``BaseOperator``.
        This field will be templated.
    :type run_name: string
    :param timeout_seconds: The timeout for this run. By default a value of 0 is used
        which means to have no timeout.
        This field will be templated.
    :type timeout_seconds: int32
    :param databricks_conn_id: The name of the Airflow connection to use.
        By default and in the common case this will be ``databricks_default``. To use
        token based authentication, provide the key ``token`` in the extra field for the
        connection.
    :type databricks_conn_id: string
    :param polling_period_seconds: Controls the rate which we poll for the result of
        this run. By default the operator will poll every 30 seconds.
    :type polling_period_seconds: int
    :param databricks_retry_limit: Amount of times retry if the Databricks backend is
        unreachable. Its value must be greater than or equal to 1.
    :type databricks_retry_limit: int
    """
    # Used in airflow.models.BaseOperator
    template_fields = ('json',)
    # Databricks brand color (blue) under white text
    ui_color = '#1CB1C2'
    ui_fgcolor = '#fff'

    def __init__(
            self,
            json=None,
            spark_jar_task=None,
            notebook_task=None,
            new_cluster=None,
            existing_cluster_id=None,
            libraries=None,
            run_name=None,
            timeout_seconds=None,
            databricks_conn_id='databricks_default',
            polling_period_seconds=30,
            databricks_retry_limit=3,
            **kwargs):
        """
        Creates a new ``DatabricksSubmitRunOperator``.
        """
        super(DatabricksSubmitRunOperator, self).__init__(**kwargs)
        self.json = json or {}
        self.databricks_conn_id = databricks_conn_id
        self.polling_period_seconds = polling_period_seconds
        self.databricks_retry_limit = databricks_retry_limit
        if spark_jar_task is not None:
            self.json['spark_jar_task'] = spark_jar_task
        if notebook_task is not None:
            self.json['notebook_task'] = notebook_task
        if new_cluster is not None:
            self.json['new_cluster'] = new_cluster
        if existing_cluster_id is not None:
            self.json['existing_cluster_id'] = existing_cluster_id
        if libraries is not None:
            self.json['libraries'] = libraries
        if run_name is not None:
            self.json['run_name'] = run_name
        if timeout_seconds is not None:
            self.json['timeout_seconds'] = timeout_seconds
        if 'run_name' not in self.json:
            self.json['run_name'] = run_name or kwargs['task_id']

        self.json = self._deep_string_coerce(self.json)
        # This variable will be used in case our task gets killed.
        self.run_id = None

    def _deep_string_coerce(self, content, json_path='json'):
        """
        Coerces content or all values of content if it is a dict to a string. The
        function will throw if content contains non-string or non-numeric types.

        The reason why we have this function is because the ``self.json`` field must be a dict
        with only string values. This is because ``render_template`` will fail for numerical values.
        """
        c = self._deep_string_coerce
        if isinstance(content, six.string_types):
            return content
        elif isinstance(content, six.integer_types+(float,)):
            # Databricks can tolerate either numeric or string types in the API backend.
            return str(content)
        elif isinstance(content, (list, tuple)):
            return [c(e, '{0}[{1}]'.format(json_path, i)) for i, e in enumerate(content)]
        elif isinstance(content, dict):
            return {k: c(v, '{0}[{1}]'.format(json_path, k))
                    for k, v in list(content.items())}
        else:
            param_type = type(content)
            msg = 'Type {0} used for parameter {1} is not a number or a string' \
                    .format(param_type, json_path)
            raise AirflowException(msg)

    def _log_run_page_url(self, url):
        self.log.info('View run status, Spark UI, and logs at %s', url)

    def get_hook(self):
        return DatabricksHook(
            self.databricks_conn_id,
            retry_limit=self.databricks_retry_limit)

    def execute(self, context):
        hook = self.get_hook()
        self.run_id = hook.submit_run(self.json)
        run_page_url = hook.get_run_page_url(self.run_id)
        self.log.info('Run submitted with run_id: %s', self.run_id)
        self._log_run_page_url(run_page_url)
        while True:
            run_state = hook.get_run_state(self.run_id)
            if run_state.is_terminal:
                if run_state.is_successful:
                    self.log.info('%s completed successfully.', self.task_id)
                    self._log_run_page_url(run_page_url)
                    return
                else:
                    error_message = '{t} failed with terminal state: {s}'.format(
                        t=self.task_id,
                        s=run_state)
                    raise AirflowException(error_message)
            else:
                self.log.info('%s in run state: %s', self.task_id, run_state)
                self._log_run_page_url(run_page_url)
                self.log.info('Sleeping for %s seconds.', self.polling_period_seconds)
                time.sleep(self.polling_period_seconds)

    def on_kill(self):
        hook = self.get_hook()
        hook.cancel_run(self.run_id)
        self.log.info(
            'Task: %s with run_id: %s was requested to be cancelled.',
            self.task_id, self.run_id
        )


text:
package kubernetes

import (
	"strings"

	clientv1 "k8s.io/api/core/v1"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/fake"
	"k8s.io/client-go/kubernetes/scheme"
	v1core "k8s.io/client-go/kubernetes/typed/core/v1"
	kube_record "k8s.io/client-go/tools/record"
)

const (
	// Rate of refill for the event spam filter in client go
	// 1 per event key per 5 minutes.
	defaultQPS = 1. / 300.
	// Number of events allowed per event key before rate limiting is triggered
	// Has to greater than or equal to 1.
	defaultBurstSize = 1
	// Number of distinct event keys in the rate limiting cache.
	defaultLRUCache = 8192
)

// CreateEventRecorder creates an event recorder to send custom events to Kubernetes to be recorded for targeted Kubernetes objects
func CreateEventRecorder(kubeClient clientset.Interface, recordDuplicatedEvents bool) kube_record.EventRecorder {
	var eventBroadcaster kube_record.EventBroadcaster
	if recordDuplicatedEvents {
		eventBroadcaster = kube_record.NewBroadcaster()
	} else {
		eventBroadcaster = kube_record.NewBroadcasterWithCorrelatorOptions(getCorrelationOptions())
	}
	if _, isfake := kubeClient.(*fake.Clientset); !isfake {
		actualSink := &v1core.EventSinkImpl{Interface: v1core.New(kubeClient.CoreV1().RESTClient()).Events("")}
		// EventBroadcaster has a StartLogging() method but the throttling options from getCorrelationOptions() get applied only to
		// actual sinks, which makes it throttle the actual events, but not the corresponding log lines. This leads to massive spam
		// in the Cluster Autoscaler log which can eventually fill up a whole disk. As a workaround, event logging is added
		// as a wrapper to the actual sink.
		// TODO: Do this natively if https://github.com/kubernetes/kubernetes/issues/90168 gets implemented.
		sinkWithLogging := WrapEventSinkWithLogging(actualSink)
		eventBroadcaster.StartRecordingToSink(sinkWithLogging)
	}
	return eventBroadcaster.NewRecorder(scheme.Scheme, clientv1.EventSource{Component: "cluster-autoscaler"})
}

func getCorrelationOptions() kube_record.CorrelatorOptions {
	return kube_record.CorrelatorOptions{
		QPS:          defaultQPS,
		BurstSize:    defaultBurstSize,
		LRUCacheSize: defaultLRUCache,
		SpamKeyFunc:  getCustomSpamKeyFunc(),
	}
}

// getCustomSpamKeyFunc returns EventSpamKeyFunc to be used by EventBroadcaster.
// By default only defaultBurstSize events are allowed to be sent per each
// event.Source-event.InvolvedObject combination. We want to emit defaultBurstSize events per each
// Reason-Source-InvolvedObject combination and for cluster-autoscaler-status ConfigMap we
// want to emit all of the events, thus we provide custom SpamKeyFunc
func getCustomSpamKeyFunc() kube_record.EventSpamKeyFunc {
	return func(event *clientv1.Event) string {
		elementsToJoin := []string{
			event.Reason,
			event.Source.Component,
			event.Source.Host,
			event.InvolvedObject.Kind,
			event.InvolvedObject.Namespace,
			event.InvolvedObject.Name,
			string(event.InvolvedObject.UID),
			event.InvolvedObject.APIVersion,
		}
		// In case of cluster-autoscaler-status config map we want to emit all of the events, so we use event.Message as a key.
		if event.InvolvedObject.Name == "cluster-autoscaler-status" && event.InvolvedObject.Namespace == "kube-system" && event.InvolvedObject.Kind == "ConfigMap" {
			elementsToJoin = []string{event.Message}
		}
		return strings.Join(elementsToJoin, "")
	}
}


text:
namespace v8 {
namespace internal {

namespace {

MaybeHandle<JSObject> InstantiateObject(Isolate* isolate,
                                        Handle<ObjectTemplateInfo> data,
                                        bool is_hidden_prototype);

MaybeHandle<JSFunction> InstantiateFunction(Isolate* isolate,
                                            Handle<FunctionTemplateInfo> data,
                                            Handle<Name> name = Handle<Name>());

MaybeHandle<Object> Instantiate(Isolate* isolate, Handle<Object> data,
                                Handle<Name> name = Handle<Name>()) {
  if (data->IsFunctionTemplateInfo()) {
    return InstantiateFunction(isolate,
                               Handle<FunctionTemplateInfo>::cast(data), name);
  } else if (data->IsObjectTemplateInfo()) {
    return InstantiateObject(isolate, Handle<ObjectTemplateInfo>::cast(data),
                             false);
  } else {
    return data;
  }
}

MaybeHandle<Object> DefineAccessorProperty(
    Isolate* isolate, Handle<JSObject> object, Handle<Name> name,
    Handle<Object> getter, Handle<Object> setter, PropertyAttributes attributes,
    bool force_instantiate) {
  DCHECK(!getter->IsFunctionTemplateInfo() ||
         !FunctionTemplateInfo::cast(*getter)->do_not_cache());
  DCHECK(!setter->IsFunctionTemplateInfo() ||
         !FunctionTemplateInfo::cast(*setter)->do_not_cache());
  if (force_instantiate) {
    if (getter->IsFunctionTemplateInfo()) {
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, getter,
          InstantiateFunction(isolate,
                              Handle<FunctionTemplateInfo>::cast(getter)),
          Object);
    }
    if (setter->IsFunctionTemplateInfo()) {
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, setter,
          InstantiateFunction(isolate,
                              Handle<FunctionTemplateInfo>::cast(setter)),
          Object);
    }
  }
  RETURN_ON_EXCEPTION(isolate, JSObject::DefineAccessor(object, name, getter,
                                                        setter, attributes),
                      Object);
  return object;
}

MaybeHandle<Object> DefineDataProperty(Isolate* isolate,
                                       Handle<JSObject> object,
                                       Handle<Name> name,
                                       Handle<Object> prop_data,
                                       PropertyAttributes attributes) {
  Handle<Object> value;
  ASSIGN_RETURN_ON_EXCEPTION(isolate, value,
                             Instantiate(isolate, prop_data, name), Object);

  LookupIterator it = LookupIterator::PropertyOrElement(
      isolate, object, name, LookupIterator::OWN_SKIP_INTERCEPTOR);

#ifdef DEBUG
  Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
  DCHECK(maybe.IsJust());
  if (it.IsFound()) {
    THROW_NEW_ERROR(
        isolate,
        NewTypeError(MessageTemplate::kDuplicateTemplateProperty, name),
        Object);
  }
#endif

  MAYBE_RETURN_NULL(
      Object::AddDataProperty(&it, value, attributes, Object::THROW_ON_ERROR,
                              Object::CERTAINLY_NOT_STORE_FROM_KEYED));
  return value;
}

void DisableAccessChecks(Isolate* isolate, Handle<JSObject> object) {
  Handle<Map> old_map(object->map());
  // Copy map so it won't interfere constructor's initial map.
  Handle<Map> new_map = Map::Copy(old_map, "DisableAccessChecks");
  new_map->set_is_access_check_needed(false);
  JSObject::MigrateToMap(Handle<JSObject>::cast(object), new_map);
}

void EnableAccessChecks(Isolate* isolate, Handle<JSObject> object) {
  Handle<Map> old_map(object->map());
  // Copy map so it won't interfere constructor's initial map.
  Handle<Map> new_map = Map::Copy(old_map, "EnableAccessChecks");
  new_map->set_is_access_check_needed(true);
  JSObject::MigrateToMap(object, new_map);
}

class AccessCheckDisableScope {
 public:
  AccessCheckDisableScope(Isolate* isolate, Handle<JSObject> obj)
      : isolate_(isolate),
        disabled_(obj->map()->is_access_check_needed()),
        obj_(obj) {
    if (disabled_) {
      DisableAccessChecks(isolate_, obj_);
    }
  }
  ~AccessCheckDisableScope() {
    if (disabled_) {
      EnableAccessChecks(isolate_, obj_);
    }
  }

 private:
  Isolate* isolate_;
  const bool disabled_;
  Handle<JSObject> obj_;
};

Object* GetIntrinsic(Isolate* isolate, v8::Intrinsic intrinsic) {
  Handle<Context> native_context = isolate->native_context();
  DCHECK(!native_context.is_null());
  switch (intrinsic) {
#define GET_INTRINSIC_VALUE(name, iname) \
  case v8::k##name:                      \
    return native_context->iname();
    V8_INTRINSICS_LIST(GET_INTRINSIC_VALUE)
#undef GET_INTRINSIC_VALUE
  }
  return nullptr;
}

// Returns parent function template or null.
FunctionTemplateInfo* GetParent(FunctionTemplateInfo* data) {
  Object* parent = data->parent_template();
  return parent->IsUndefined() ? nullptr : FunctionTemplateInfo::cast(parent);
}

// Starting from given object template's constructor walk up the inheritance
// chain till a function template that has an instance template is found.
ObjectTemplateInfo* GetParent(ObjectTemplateInfo* data) {
  Object* maybe_ctor = data->constructor();
  if (maybe_ctor->IsUndefined()) return nullptr;
  FunctionTemplateInfo* ctor = FunctionTemplateInfo::cast(maybe_ctor);
  while (true) {
    ctor = GetParent(ctor);
    if (ctor == nullptr) return nullptr;
    Object* maybe_obj = ctor->instance_template();
    if (!maybe_obj->IsUndefined()) return ObjectTemplateInfo::cast(maybe_obj);
  }
}

template <typename TemplateInfoT>
MaybeHandle<JSObject> ConfigureInstance(Isolate* isolate, Handle<JSObject> obj,
                                        Handle<TemplateInfoT> data,
                                        bool is_hidden_prototype) {
  HandleScope scope(isolate);
  // Disable access checks while instantiating the object.
  AccessCheckDisableScope access_check_scope(isolate, obj);

  // Walk the inheritance chain and copy all accessors to current object.
  int max_number_of_properties = 0;
  TemplateInfoT* info = *data;
  while (info != nullptr) {
    if (!info->property_accessors()->IsUndefined()) {
      Object* props = info->property_accessors();
      if (!props->IsUndefined()) {
        Handle<Object> props_handle(props, isolate);
        NeanderArray props_array(props_handle);
        max_number_of_properties += props_array.length();
      }
    }
    info = GetParent(info);
  }

  if (max_number_of_properties > 0) {
    int valid_descriptors = 0;
    // Use a temporary FixedArray to accumulate unique accessors.
    Handle<FixedArray> array =
        isolate->factory()->NewFixedArray(max_number_of_properties);

    info = *data;
    while (info != nullptr) {
      // Accumulate accessors.
      if (!info->property_accessors()->IsUndefined()) {
        Handle<Object> props(info->property_accessors(), isolate);
        valid_descriptors =
            AccessorInfo::AppendUnique(props, array, valid_descriptors);
      }
      info = GetParent(info);
    }

    // Install accumulated accessors.
    for (int i = 0; i < valid_descriptors; i++) {
      Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
      JSObject::SetAccessor(obj, accessor).Assert();
    }
  }

  auto property_list = handle(data->property_list(), isolate);
  if (property_list->IsUndefined()) return obj;
  // TODO(dcarney): just use a FixedArray here.
  NeanderArray properties(property_list);
  if (properties.length() == 0) return obj;

  int i = 0;
  for (int c = 0; c < data->number_of_properties(); c++) {
    auto name = handle(Name::cast(properties.get(i++)), isolate);
    auto bit = handle(properties.get(i++), isolate);
    if (bit->IsSmi()) {
      PropertyDetails details(Smi::cast(*bit));
      PropertyAttributes attributes = details.attributes();
      PropertyKind kind = details.kind();

      if (kind == kData) {
        auto prop_data = handle(properties.get(i++), isolate);
        RETURN_ON_EXCEPTION(isolate, DefineDataProperty(isolate, obj, name,
                                                        prop_data, attributes),
                            JSObject);
      } else {
        auto getter = handle(properties.get(i++), isolate);
        auto setter = handle(properties.get(i++), isolate);
        RETURN_ON_EXCEPTION(
            isolate, DefineAccessorProperty(isolate, obj, name, getter, setter,
                                            attributes, is_hidden_prototype),
            JSObject);
      }
    } else {
      // Intrinsic data property --- Get appropriate value from the current
      // context.
      PropertyDetails details(Smi::cast(properties.get(i++)));
      PropertyAttributes attributes = details.attributes();
      DCHECK_EQ(kData, details.kind());

      v8::Intrinsic intrinsic =
          static_cast<v8::Intrinsic>(Smi::cast(properties.get(i++))->value());
      auto prop_data = handle(GetIntrinsic(isolate, intrinsic), isolate);

      RETURN_ON_EXCEPTION(isolate, DefineDataProperty(isolate, obj, name,
                                                      prop_data, attributes),
                          JSObject);
    }
  }
  return obj;
}

void CacheTemplateInstantiation(Isolate* isolate, Handle<Smi> serial_number,
                                Handle<JSObject> object) {
  auto cache = isolate->template_instantiations_cache();
  auto new_cache = ObjectHashTable::Put(cache, serial_number, object);
  isolate->native_context()->set_template_instantiations_cache(*new_cache);
}

void UncacheTemplateInstantiation(Isolate* isolate, Handle<Smi> serial_number) {
  auto cache = isolate->template_instantiations_cache();
  bool was_present = false;
  auto new_cache = ObjectHashTable::Remove(cache, serial_number, &was_present);
  DCHECK(was_present);
  isolate->native_context()->set_template_instantiations_cache(*new_cache);
}

MaybeHandle<JSObject> InstantiateObject(Isolate* isolate,
                                        Handle<ObjectTemplateInfo> info,
                                        bool is_hidden_prototype) {
  // Enter a new scope.  Recursion could otherwise create a lot of handles.
  HandleScope scope(isolate);
  // Fast path.
  Handle<JSObject> result;
  auto constructor = handle(info->constructor(), isolate);
  Handle<JSFunction> cons;
  if (constructor->IsUndefined()) {
    cons = isolate->object_function();
  } else {
    auto cons_templ = Handle<FunctionTemplateInfo>::cast(constructor);
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, cons, InstantiateFunction(isolate, cons_templ), JSFunction);
  }
  auto serial_number = handle(Smi::cast(info->serial_number()), isolate);
  if (serial_number->value()) {
    // Probe cache.
    auto cache = isolate->template_instantiations_cache();
    Object* boilerplate = cache->Lookup(serial_number);
    if (boilerplate->IsJSObject()) {
      result = handle(JSObject::cast(boilerplate), isolate);
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, result, JSObject::DeepCopyApiBoilerplate(result), JSObject);
      return scope.CloseAndEscape(result);
    }
  }
  auto object = isolate->factory()->NewJSObject(cons);
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, result,
      ConfigureInstance(isolate, object, info, is_hidden_prototype),
      JSFunction);
  // TODO(dcarney): is this necessary?
  JSObject::MigrateSlowToFast(result, 0, "ApiNatives::InstantiateObject");

  if (serial_number->value()) {
    CacheTemplateInstantiation(isolate, serial_number, result);
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, result, JSObject::DeepCopyApiBoilerplate(result), JSObject);
  }
  return scope.CloseAndEscape(result);
}

MaybeHandle<JSFunction> InstantiateFunction(Isolate* isolate,
                                            Handle<FunctionTemplateInfo> data,
                                            Handle<Name> name) {
  auto serial_number = handle(Smi::cast(data->serial_number()), isolate);
  if (serial_number->value()) {
    // Probe cache.
    auto cache = isolate->template_instantiations_cache();
    Object* element = cache->Lookup(serial_number);
    if (element->IsJSFunction()) {
      return handle(JSFunction::cast(element), isolate);
    }
  }
  // Enter a new scope.  Recursion could otherwise create a lot of handles.
  HandleScope scope(isolate);
  Handle<JSObject> prototype;
  if (!data->remove_prototype()) {
    auto prototype_templ = handle(data->prototype_template(), isolate);
    if (prototype_templ->IsUndefined()) {
      prototype = isolate->factory()->NewJSObject(isolate->object_function());
    } else {
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, prototype,
          InstantiateObject(isolate,
                            Handle<ObjectTemplateInfo>::cast(prototype_templ),
                            data->hidden_prototype()),
          JSFunction);
    }
    auto parent = handle(data->parent_template(), isolate);
    if (!parent->IsUndefined()) {
      Handle<JSFunction> parent_instance;
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, parent_instance,
          InstantiateFunction(isolate,
                              Handle<FunctionTemplateInfo>::cast(parent)),
          JSFunction);
      // TODO(dcarney): decide what to do here.
      Handle<Object> parent_prototype;
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, parent_prototype,
          JSObject::GetProperty(parent_instance,
                                isolate->factory()->prototype_string()),
          JSFunction);
      MAYBE_RETURN(JSObject::SetPrototype(prototype, parent_prototype, false,
                                          Object::THROW_ON_ERROR),
                   MaybeHandle<JSFunction>());
    }
  }
  auto function = ApiNatives::CreateApiFunction(
      isolate, data, prototype, ApiNatives::JavaScriptObjectType);
  if (!name.is_null() && name->IsString()) {
    function->shared()->set_name(*name);
  }
  if (serial_number->value()) {
    // Cache the function.
    CacheTemplateInstantiation(isolate, serial_number, function);
  }
  auto result =
      ConfigureInstance(isolate, function, data, data->hidden_prototype());
  if (result.is_null()) {
    // Uncache on error.
    if (serial_number->value()) {
      UncacheTemplateInstantiation(isolate, serial_number);
    }
    return MaybeHandle<JSFunction>();
  }
  return scope.CloseAndEscape(function);
}

class InvokeScope {
 public:
  explicit InvokeScope(Isolate* isolate)
      : isolate_(isolate), save_context_(isolate) {}
  ~InvokeScope() {
    bool has_exception = isolate_->has_pending_exception();
    if (has_exception) {
      isolate_->ReportPendingMessages();
    } else {
      isolate_->clear_pending_message();
    }
  }

 private:
  Isolate* isolate_;
  SaveContext save_context_;
};

void AddPropertyToPropertyList(Isolate* isolate, Handle<TemplateInfo> templ,
                               int length, Handle<Object>* data) {
  auto list = handle(templ->property_list(), isolate);
  if (list->IsUndefined()) {
    list = NeanderArray(isolate).value();
    templ->set_property_list(*list);
  }
  templ->set_number_of_properties(templ->number_of_properties() + 1);
  NeanderArray array(list);
  for (int i = 0; i < length; i++) {
    Handle<Object> value =
        data[i].is_null()
            ? Handle<Object>::cast(isolate->factory()->undefined_value())
            : data[i];
    array.add(isolate, value);
  }
}

}  // namespace

MaybeHandle<JSFunction> ApiNatives::InstantiateFunction(
    Handle<FunctionTemplateInfo> data) {
  Isolate* isolate = data->GetIsolate();
  InvokeScope invoke_scope(isolate);
  return ::v8::internal::InstantiateFunction(isolate, data);
}

MaybeHandle<JSObject> ApiNatives::InstantiateObject(
    Handle<ObjectTemplateInfo> data) {
  Isolate* isolate = data->GetIsolate();
  InvokeScope invoke_scope(isolate);
  return ::v8::internal::InstantiateObject(isolate, data, false);
}

void ApiNatives::AddDataProperty(Isolate* isolate, Handle<TemplateInfo> info,
                                 Handle<Name> name, Handle<Object> value,
                                 PropertyAttributes attributes) {
  const int kSize = 3;
  PropertyDetails details(attributes, DATA, 0, PropertyCellType::kNoCell);
  auto details_handle = handle(details.AsSmi(), isolate);
  Handle<Object> data[kSize] = {name, details_handle, value};
  AddPropertyToPropertyList(isolate, info, kSize, data);
}

void ApiNatives::AddDataProperty(Isolate* isolate, Handle<TemplateInfo> info,
                                 Handle<Name> name, v8::Intrinsic intrinsic,
                                 PropertyAttributes attributes) {
  const int kSize = 4;
  auto value = handle(Smi::FromInt(intrinsic), isolate);
  auto intrinsic_marker = isolate->factory()->true_value();
  PropertyDetails details(attributes, DATA, 0, PropertyCellType::kNoCell);
  auto details_handle = handle(details.AsSmi(), isolate);
  Handle<Object> data[kSize] = {name, intrinsic_marker, details_handle, value};
  AddPropertyToPropertyList(isolate, info, kSize, data);
}

void ApiNatives::AddAccessorProperty(Isolate* isolate,
                                     Handle<TemplateInfo> info,
                                     Handle<Name> name,
                                     Handle<FunctionTemplateInfo> getter,
                                     Handle<FunctionTemplateInfo> setter,
                                     PropertyAttributes attributes) {
  const int kSize = 4;
  PropertyDetails details(attributes, ACCESSOR, 0, PropertyCellType::kNoCell);
  auto details_handle = handle(details.AsSmi(), isolate);
  Handle<Object> data[kSize] = {name, details_handle, getter, setter};
  AddPropertyToPropertyList(isolate, info, kSize, data);
}

void ApiNatives::AddNativeDataProperty(Isolate* isolate,
                                       Handle<TemplateInfo> info,
                                       Handle<AccessorInfo> property) {
  auto list = handle(info->property_accessors(), isolate);
  if (list->IsUndefined()) {
    list = NeanderArray(isolate).value();
    info->set_property_accessors(*list);
  }
  NeanderArray array(list);
  array.add(isolate, property);
}

Handle<JSFunction> ApiNatives::CreateApiFunction(
    Isolate* isolate, Handle<FunctionTemplateInfo> obj,
    Handle<Object> prototype, ApiInstanceType instance_type) {
  Handle<Code> code;
  if (obj->call_code()->IsCallHandlerInfo() &&
      CallHandlerInfo::cast(obj->call_code())->fast_handler()->IsCode()) {
    code = isolate->builtins()->HandleFastApiCall();
  } else {
    code = isolate->builtins()->HandleApiCall();
  }
  Handle<Code> construct_stub =
      prototype.is_null() ? isolate->builtins()->ConstructedNonConstructable()
                          : isolate->builtins()->JSConstructStubApi();

  obj->set_instantiated(true);
  Handle<JSFunction> result;
  if (obj->remove_prototype()) {
    result = isolate->factory()->NewFunctionWithoutPrototype(
        isolate->factory()->empty_string(), code);
  } else {
    int internal_field_count = 0;
    if (!obj->instance_template()->IsUndefined()) {
      Handle<ObjectTemplateInfo> instance_template = Handle<ObjectTemplateInfo>(
          ObjectTemplateInfo::cast(obj->instance_template()));
      internal_field_count =
          Smi::cast(instance_template->internal_field_count())->value();
    }

    // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
    // JSObject::GetHeaderSize.
    int instance_size = kPointerSize * internal_field_count;
    InstanceType type;
    switch (instance_type) {
      case JavaScriptObjectType:
        type = JS_OBJECT_TYPE;
        instance_size += JSObject::kHeaderSize;
        break;
      case GlobalObjectType:
        type = JS_GLOBAL_OBJECT_TYPE;
        instance_size += JSGlobalObject::kSize;
        break;
      case GlobalProxyType:
        type = JS_GLOBAL_PROXY_TYPE;
        instance_size += JSGlobalProxy::kSize;
        break;
      default:
        UNREACHABLE();
        type = JS_OBJECT_TYPE;  // Keep the compiler happy.
        break;
    }

    result = isolate->factory()->NewFunction(
        isolate->factory()->empty_string(), code, prototype, type,
        instance_size, obj->read_only_prototype(), true);
  }

  result->shared()->set_length(obj->length());
  Handle<Object> class_name(obj->class_name(), isolate);
  if (class_name->IsString()) {
    result->shared()->set_instance_class_name(*class_name);
    result->shared()->set_name(*class_name);
  }
  result->shared()->set_function_data(*obj);
  result->shared()->set_construct_stub(*construct_stub);
  result->shared()->DontAdaptArguments();

  if (obj->remove_prototype()) {
    DCHECK(result->shared()->IsApiFunction());
    DCHECK(!result->has_initial_map());
    DCHECK(!result->has_prototype());
    return result;
  }

#ifdef DEBUG
  LookupIterator it(handle(JSObject::cast(result->prototype())),
                    isolate->factory()->constructor_string(),
                    LookupIterator::OWN_SKIP_INTERCEPTOR);
  MaybeHandle<Object> maybe_prop = Object::GetProperty(&it);
  DCHECK(it.IsFound());
  DCHECK(maybe_prop.ToHandleChecked().is_identical_to(result));
#endif

  // Down from here is only valid for API functions that can be used as a
  // constructor (don't set the "remove prototype" flag).

  Handle<Map> map(result->initial_map());

  // Mark as undetectable if needed.
  if (obj->undetectable()) {
    map->set_is_undetectable();
  }

  // Mark as needs_access_check if needed.
  if (obj->needs_access_check()) {
    map->set_is_access_check_needed(true);
  }

  // Set interceptor information in the map.
  if (!obj->named_property_handler()->IsUndefined()) {
    map->set_has_named_interceptor();
  }
  if (!obj->indexed_property_handler()->IsUndefined()) {
    map->set_has_indexed_interceptor();
  }

  // Mark instance as callable in the map.
  if (!obj->instance_call_handler()->IsUndefined()) {
    map->set_is_callable();
    map->set_is_constructor(true);
  }

  DCHECK(result->shared()->IsApiFunction());
  return result;
}

}  // namespace internal
}  // namespace v8


text:
// Copyright (c) 2002 Graz University of Technology. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
//
// 2. 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.
//
// 3. The end-user documentation included with the redistribution, if any, must
//    include the following acknowledgment:
//
//    "This product includes software developed by IAIK of Graz University of
//     Technology."
//
//    Alternately, this acknowledgment may appear in the software itself, if and
//    wherever such third-party acknowledgments normally appear.
//
// 4. The names "Graz University of Technology" and "IAIK of Graz University of
//    Technology" must not be used to endorse or promote products derived from this
//    software without prior written permission.
//
// 5. Products derived from this software may not be called "IAIK PKCS Wrapper",
//    nor may "IAIK" appear in their name, without prior written permission of
//    Graz University of Technology.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED 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 THE LICENSOR 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.

package iaik.pkcs.pkcs11.wrapper;

/**
 * class CK_SKIPJACK_RELAYX_PARAMS provides the parameters to the
 * CKM_SKIPJACK_RELAYX mechanism.

 * PKCS#11 structure:
 *

 * typedef struct CK_SKIPJACK_RELAYX_PARAMS {
 *   CK_ULONG ulOldWrappedXLen;
 *   CK_BYTE_PTR pOldWrappedX;
 *   CK_ULONG ulOldPasswordLen;
 *   CK_BYTE_PTR pOldPassword;
 *   CK_ULONG ulOldPublicDataLen;
 *   CK_BYTE_PTR pOldPublicData;
 *   CK_ULONG ulOldRandomLen;
 *   CK_BYTE_PTR pOldRandomA;
 *   CK_ULONG ulNewPasswordLen;
 *   CK_BYTE_PTR pNewPassword;
 *   CK_ULONG ulNewPublicDataLen;
 *   CK_BYTE_PTR pNewPublicData;
 *   CK_ULONG ulNewRandomLen;
 *   CK_BYTE_PTR pNewRandomA;
 * } CK_SKIPJACK_RELAYX_PARAMS;
 *

 *
 * @author Karl Scheibelhofer <Karl.Scheibelhofer@iaik.at>
 * @author Martin Schläffer <schlaeff@sbox.tugraz.at>
 */
public class CK_SKIPJACK_RELAYX_PARAMS {

	/**
	 * PKCS#11:
	 *

	 *   CK_BYTE_PTR pOldWrappedX;
	 *   CK_ULONG ulOldWrappedXLen;
	 *

	 */
	public byte[] pOldWrappedX;

	/**
	 * PKCS#11:
	 *

	 *
	 *
	 *

	 */
	public byte[] pOldPassword;

	/**
	 * PKCS#11:
	 *

	 *   CK_BYTE_PTR pOldPublicData;
	 *   CK_ULONG ulOldPublicDataLen;
	 *

	 */
	public byte[] pOldPublicData;

	/**
	 * PKCS#11:
	 *

	 *   CK_BYTE_PTR pOldRandomA;
	 *   CK_ULONG ulOldRandomLen;
	 *

	 */
	public byte[] pOldRandomA;

	/**
	 * PKCS#11:
	 *

	 *   CK_BYTE_PTR pNewPassword;
	 *   CK_ULONG ulNewPasswordLen;
	 *

	 */
	public byte[] pNewPassword;

	/**
	 * PKCS#11:
	 *

	 *   CK_BYTE_PTR pNewPublicData;
	 *   CK_ULONG ulNewPublicDataLen;
	 *

	 */
	public byte[] pNewPublicData;

	/**
	 * PKCS#11:
	 *

	 *   CK_BYTE_PTR pNewRandomA;
	 *   CK_ULONG ulNewRandomLen;
	 *

	 */
	public byte[] pNewRandomA;

	/**
	 * Returns the string representation of CK_SKIPJACK_RELAYX_PARAMS.
	 *
	 * @return the string representation of CK_SKIPJACK_RELAYX_PARAMS
	 */
	public String toString() {
		StringBuffer buffer = new StringBuffer();

		buffer.append(Constants.INDENT);
		buffer.append("ulOldWrappedXLen: ");
		buffer.append(pOldWrappedX.length);
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("pOldWrappedX: ");
		buffer.append(Functions.toHexString(pOldWrappedX));
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("ulOldPasswordLen: ");
		buffer.append(pOldPassword.length);
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("pOldPassword: ");
		buffer.append(Functions.toHexString(pOldPassword));
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("ulOldPublicDataLen: ");
		buffer.append(pOldPublicData.length);
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("pOldPublicData: ");
		buffer.append(Functions.toHexString(pOldPublicData));
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("ulOldRandomLen: ");
		buffer.append(pOldRandomA.length);
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("pOldRandomA: ");
		buffer.append(Functions.toHexString(pOldRandomA));
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("ulNewPasswordLen: ");
		buffer.append(pNewPassword.length);
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("pNewPassword: ");
		buffer.append(Functions.toHexString(pNewPassword));
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("ulNewPublicDataLen: ");
		buffer.append(pNewPublicData.length);
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("pNewPublicData: ");
		buffer.append(Functions.toHexString(pNewPublicData));
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("ulNewRandomLen: ");
		buffer.append(pNewRandomA.length);
		buffer.append(Constants.NEWLINE);

		buffer.append(Constants.INDENT);
		buffer.append("pNewRandomA: ");
		buffer.append(Functions.toHexString(pNewRandomA));
		//buffer.append(Constants.NEWLINE);

		return buffer.toString();
	}

}


text:
package com.google.android.exoplayer.chunk;

import com.google.android.exoplayer.MediaFormat;
import com.google.android.exoplayer.ParserException;
import com.google.android.exoplayer.SampleHolder;
import com.google.android.exoplayer.upstream.DataSource;
import com.google.android.exoplayer.upstream.DataSpec;

import java.util.Map;
import java.util.UUID;

/**
 * An abstract base class for {@link Chunk}s that contain media samples.
 */
public abstract class MediaChunk extends Chunk {

  /**
   * The start time of the media contained by the chunk.
   */
  public final long startTimeUs;
  /**
   * The end time of the media contained by the chunk.
   */
  public final long endTimeUs;
  /**
   * The index of the next media chunk, or -1 if this is the last media chunk in the stream.
   */
  public final int nextChunkIndex;

  /**
   * Constructor for a chunk of media samples.
   *
   * @param dataSource A {@link DataSource} for loading the data.
   * @param dataSpec Defines the data to be loaded.
   * @param format The format of the stream to which this chunk belongs.
   * @param trigger The reason for this chunk being selected.
   * @param startTimeUs The start time of the media contained by the chunk, in microseconds.
   * @param endTimeUs The end time of the media contained by the chunk, in microseconds.
   * @param nextChunkIndex The index of the next chunk, or -1 if this is the last chunk.
   */
  public MediaChunk(DataSource dataSource, DataSpec dataSpec, Format format, int trigger,
      long startTimeUs, long endTimeUs, int nextChunkIndex) {
    super(dataSource, dataSpec, format, trigger);
    this.startTimeUs = startTimeUs;
    this.endTimeUs = endTimeUs;
    this.nextChunkIndex = nextChunkIndex;
  }

  /**
   * Whether this is the last chunk in the stream.
   *
   * @return True if this is the last chunk in the stream. False otherwise.
   */
  public final boolean isLastChunk() {
    return nextChunkIndex == -1;
  }

  /**
   * Seeks to the beginning of the chunk.
   */
  public abstract void seekToStart();

  /**
   * Seeks to the specified position within the chunk.
   *
   * @param positionUs The desired seek time in microseconds.
   * @param allowNoop True if the seek is allowed to do nothing if the result is more accurate than
   *     seeking to a key frame. Always pass false if it is required that the next sample be a key
   *     frame.
   * @return True if the seek results in a discontinuity in the sequence of samples returned by
   *     {@link #read(SampleHolder)}. False otherwise.
   */
  public abstract boolean seekTo(long positionUs, boolean allowNoop);

  /**
   * Prepares the chunk for reading. Does nothing if the chunk is already prepared.
   *

   * Preparation may require consuming some of the chunk. If the data is not yet available then
   * this method will return {@code false} rather than block. The method can be called repeatedly
   * until the return value indicates success.
   *
   * @return True if the chunk was prepared. False otherwise.
   * @throws ParserException If an error occurs parsing the media data.
   */
  public abstract boolean prepare() throws ParserException;

  /**
   * Returns whether the next sample is available.
   *
   * @return True if the next sample is available for reading. False otherwise.
   * @throws ParserException
   */
  public abstract boolean sampleAvailable() throws ParserException;

  /**
   * Reads the next media sample from the chunk.
   *

   * Should only be called after the chunk has been successfully prepared.
   *
   * @param holder A holder to store the read sample.
   * @return True if a sample was read. False if more data is still required.
   * @throws ParserException If an error occurs parsing the media data.
   * @throws IllegalStateException If called before {@link #init}, or after {@link #release}
   */
  public abstract boolean read(SampleHolder holder) throws ParserException;

  /**
   * Returns the media format of the samples contained within this chunk.
   *

   * Should only be called after the chunk has been successfully prepared.
   *
   * @return The sample media format.
   */
  public abstract MediaFormat getMediaFormat();

  /**
   * Returns the pssh information associated with the chunk.
   *

   * Should only be called after the chunk has been successfully prepared.
   *
   * @return The pssh information.
   */
  public abstract Map<UUID, byte[]> getPsshInfo();

}