text:
package com.google.caliper;

import com.google.caliper.UserException.ExceptionFromUserCodeException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * A convenience class for implementing benchmarks in plain code.
 * Implementing classes must have a no-arguments constructor.
 *
 *
Benchmarks

 * The benchmarks of a suite are defined by . They may be
 * static. They are not permitted to take parameters . . ..
 *
 *
Parameters

 * See the {@link Param} documentation to learn about parameters.
 */
public abstract class SimpleBenchmark
    extends com.google.caliper.api.Benchmark // TEMPORARY for transition
    implements Benchmark {
  private static final Class<?>[] ARGUMENT_TYPES = { int.class };

  private final Map<String, Parameter<?>> parameters;
  private final Map<String, Method> methods;

  protected SimpleBenchmark() {
    parameters = Parameter.forClass(getClass());
    methods = createTimedMethods();

    if (methods.isEmpty()) {
      throw new ConfigurationException(
          "No benchmarks defined in " + getClass().getName());
    }
  }

  @Override protected void setUp() throws Exception {}

  @Override protected void tearDown() throws Exception {}

  @Override public Set<String> parameterNames() {
    return ImmutableSet.<String>builder()
        .add("benchmark")
        .addAll(parameters.keySet())
        .build();
  }

  @Override public Set<String> parameterValues(String parameterName) {
    if ("benchmark".equals(parameterName)) {
      return methods.keySet();
    }

    Parameter<?> parameter = parameters.get(parameterName);
    if (parameter == null) {
      throw new IllegalArgumentException();
    }
    try {
      Iterable<?> values = parameter.values();

      ImmutableSet.Builder<String> result = ImmutableSet.builder();
      for (Object value : values) {
        result.add(String.valueOf(value));
      }
      return result.build();
    } catch (Exception e) {
      throw new ExceptionFromUserCodeException(e);
    }
  }

    @Override public ConfiguredBenchmark createBenchmark(String methodName) {
    final Method method = methods.get(methodName);
    if (method == null) {
      throw new IllegalArgumentException("Invalid parameters specified. \"time" + methodName + "\" "
          + "is not a method of this benchmark.");
    }

    try {
      @SuppressWarnings({"ClassNewInstance"}) // can throw any Exception, so we catch all Exceptions
      final SimpleBenchmark copyOfSelf = getClass().newInstance();

      // for (Map.Entry<String, String> entry : parameterValues.entrySet()) {
      //   String parameterName = entry.getKey();
      //   if ("benchmark".equals(parameterName)) {
      //     continue;
      //   }

      //   Parameter<?> parameter = parameters.get(parameterName);
      //   Object value = TypeConverter.fromString(entry.getValue(), parameter.getType());
      //   parameter.set(copyOfSelf, value);
      // }
      copyOfSelf.setUp();

      return new ConfiguredBenchmark(copyOfSelf) {
        @Override public Object run(int reps) throws Exception {
          try {
            return method.invoke(copyOfSelf, reps);
          } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof Exception) {
              throw (Exception) cause;
            } else if (cause instanceof Error) {
              throw (Error) cause;
            } else {
              throw e;
            }
          }
        }

        @Override public void close() throws Exception {
          copyOfSelf.tearDown();
        }
      };
    } catch (Exception e) {
      throw new ExceptionFromUserCodeException(e);
    }
  }

  public Scenario normalizeScenario(Scenario scenario) {
    Map<String, String> variables =
      new LinkedHashMap<String, String>(scenario.getVariables());
    // Make sure the scenario contains method names without the prefixed "time". If
    // it has "time" prefixed, then remove it. Also check whether the user has
    // accidentally put a lower cased letter first, and fix it if necessary.
    String benchmark = variables.get("benchmark");
    Map<String, Method> timedMethods = createTimedMethods();
    if (timedMethods.get(benchmark) == null) {
      // try to upper case first character
      char[] benchmarkChars = benchmark.toCharArray();
      benchmarkChars[0] = Character.toUpperCase(benchmarkChars[0]);
      String upperCasedBenchmark = String.valueOf(benchmarkChars);
      if (timedMethods.get(upperCasedBenchmark) != null) {
        variables.put("benchmark", upperCasedBenchmark);
      } else if (benchmark.startsWith("time")) {
        variables.put("benchmark", benchmark.substring(4));
      }
    }
    return new Scenario(variables);
  }

  /**
   * Returns a spec for each benchmark defined in the specified class. The
   * returned specs have no parameter values; those must be added separately.
   */
  private Map<String, Method> createTimedMethods() {
    ImmutableMap.Builder<String, Method> result = ImmutableMap.builder();
    for (Method method : getClass().getDeclaredMethods()) {
      int modifiers = method.getModifiers();
      if (!method.getName().startsWith("time")) {
        continue;
      }

      if (!Modifier.isPublic(modifiers)
          || Modifier.isStatic(modifiers)
          || Modifier.isAbstract(modifiers)
          || !Arrays.equals(method.getParameterTypes(), ARGUMENT_TYPES)) {
        throw new ConfigurationException("Timed methods must be public, "
            + "non-static, non-abstract and take a single int parameter. "
            + "But " + method + " violates these requirements.");
      }

      result.put(method.getName().substring(4), method);
    }

    return result.build();
  }

  @Override public Map<String, Integer> getTimeUnitNames() {
    return ImmutableMap.of("ns", 1,
        "us", 1000,
        "ms", 1000000,
        "s", 1000000000);
  }

  @Override public double nanosToUnits(double nanos) {
    return nanos;
  }

  @Override public Map<String, Integer> getInstanceUnitNames() {
    return ImmutableMap.of(" instances", 1,
        "K instances", 1000,
        "M instances", 1000000,
        "B instances", 1000000000);
  }

  @Override public double instancesToUnits(long instances) {
    return instances;
  }

  @Override public Map<String, Integer> getMemoryUnitNames() {
    return ImmutableMap.of("B", 1,
        "KiB", 1024,
        "MiB", 1048576,
        "GiB", 1073741824);
  }

  @Override public double bytesToUnits(long bytes) {
    return bytes;
  }
}


text:
[//000000001]: # (treeql \- Tree Query Language)
[//000000002]: # (Generated from file 'treeql\.man' by tcllib/doctools with format 'markdown')
[//000000003]: # (Copyright © 2004 Colin McCormack <coldstore@users\.sourceforge\.net>)
[//000000004]: # (Copyright © 2004 Andreas Kupries <andreas\_kupries@users\.sourceforge\.net>)
[//000000005]: # (treeql\(n\) 1\.3\.1 tcllib "Tree Query Language")

 [ Main Table Of Contents | Table Of Contents | Keyword Index | Categories | Modules | Applications ]

# NAME

treeql \- Query tree objects

# Table Of Contents

  - [Table Of Contents](#toc)

  - [Synopsis](#synopsis)

  - [Description](#section1)

  - [API](#section2)

      - [TreeQL CLASS API](#subsection1)

      - [TreeQL OBJECT API](#subsection2)

  - [The Tree Query Language](#section3)

      - [TreeQL Concepts](#subsection3)

      - [Structural generators](#subsection4)

      - [Attribute Filters](#subsection5)

      - [Attribute Mutators](#subsection6)

      - [Attribute String Accessors](#subsection7)

      - [Sub\-queries](#subsection8)

      - [Node Set Operators](#subsection9)

      - [Node Set Iterators](#subsection10)

      - [Typed node support](#subsection11)

  - [Examples](#section4)

  - [References](#section5)

  - [Bugs, Ideas, Feedback](#section6)

  - [Keywords](#keywords)

  - [Category](#category)

  - [Copyright](#copyright)

# SYNOPSIS

package require Tcl 8\.2
package require snit
package require struct::list
package require struct::set
package require treeql ?1\.3\.1?

[__treeql__ *objectname* __\-tree__ *tree* ?__\-query__ *query*? ?__\-nodes__ *nodes*? ?*args*\.\.\.?](#1)
[*qo* __query__ *args*\.\.\.](#2)
[*qo* __result__](#3)
[*qo* __discard__](#4)

# DESCRIPTION

This package provides objects which can be used to query and transform tree
objects following the API of tree objects created by the package
__[struct::tree](\.\./struct/struct\_tree\.md)__\.

The tree query and manipulation language used here, TreeQL, is inspired by Cost
\(See section [References](#section5) for more information\)\.

__treeql__, the package, is a fairly thin query facility over
tree\-structured data types\. It implements an ordered set of nodes \(really a
list\) which are generated and filtered through the application of TreeQL
operators to each node in turn\.

# API

## TreeQL CLASS API

The command __treeql__ is a __[snit](\.\./snit/snit\.md)__::type which
implements the Treeql Query Language\. This means that it follows the API for
class commands as specified by the package __[snit](\.\./snit/snit\.md)__\.
Its general syntax is

  - __treeql__ *objectname* __\-tree__ *tree* ?__\-query__ *query*? ?__\-nodes__ *nodes*? ?*args*\.\.\.?

    The command creates a new tree query object and returns the fully qualified
    name of the object command as its result\. The API the returned command is
    following is described in the section [TreeQL OBJECT API](#subsection2)

    Each query object is associated with a single *tree* object\. This is the
    object all queries will be run against\.

    If the option __\-nodes__ was specified then its argument is treated as a
    list of nodes\. This list is used to initialize the node set\. It defaults to
    the empty list\.

    If the option __\-query__ was specified then its argument will be
    interpreted as an object, the *parent query* of this query\. It defaults to
    the object itself\. All queries will be interpreted in the environment of
    this object\.

    Any arguments coming after the options are treated as a query and run
    immediately, after the *node set* has been initialized\. This uses the same
    syntax for the query as the method __query__\.

    The operations of the TreeQL available for this are explained in the section
    about [The Tree Query Language](#section3)\. This section also explains
    the term *node set* used above\.

## TreeQL OBJECT API

As __treeql__ has been implemented in __[snit](\.\./snit/snit\.md)__
all the standard methods of __[snit](\.\./snit/snit\.md)__\-based classes
are available to the user and therefore not listed here\. Please read the
documentation for __[snit](\.\./snit/snit\.md)__ for what they are and what
functionality they provide

The methods provided by the package __treeql__ itself are listed and
explained below\.

  - *qo* __query__ *args*\.\.\.

    This method interprets its arguments as a series of TreeQL operators and
    interpretes them from the left to right \(i\.e\. first to last\)\. Note that the
    first operator uses the *node set* currently known to the object to
    perform its actions\. In other words, the *node set* is *not* cleared, or
    modified in other ways, before the query is run\. This allows the user to run
    several queries one after the other and have each use the results of the
    last\. Any initialization has to be done by any query itself, using TreeQL
    operators\. The result of the method is the *node set* after the last
    operator of the query has been executed\.

    *Note* that uncaught errors will leave the *node set* of the object in
    an intermediate state, per the TreeQL operators which were executed
    successfully before the error occurred\.

    The above means in detail that:

      1. The first argument is interpreted as the name of a query operator, the
         number of arguments required by that operator is then determined, and
         taken from the immediately following arguments\.

         Because of this operators cannot have optional arguments, all arguments
         have to be present as defined\. Failure to do this will, at least,
         confuse the query interpreter, but more likely cause errors\.

      1. The operator is applied to the current node set, yielding a new node
         set, and/or manipulating the tree object the query object is connected
         to\.

      1. The arguments used \(i\.e\. operator name and arguments\) are removed from
         the list of method arguments, and then the whole process is repeated
         from step \[1\], until the list of arguments is empty or an error
         occurred\.

            # q is the query object.

            q query root children get data

            # The above query
            # - Resets the node set to the root node - root
            # - Adds the children of root to the set - children
            # - Replaces the node set with the       - get data
            #   values for the attribute 'data',
            #   for all nodes in the set which
            #   have such an attribute.
            # - And returns this information.

            # Below we can see the same query, but rewritten
            # to show the structure as it is seen by the query
            # interpreter.

            q query \
        	    root \
        	    children \
        	    get data

    The operators of the TreeQL language available for this are explained in the
    section about [The Tree Query Language](#section3)\. This section also
    explains the term *node set* used above\.

  - *qo* __result__

    This method returns a list containing the current node set\.

  - *qo* __discard__

    This method returns the current node set \(like method __result__\), but
    also destroys the query object \(*qo*\)\. This is useful when constructing
    and using sub\-queries \(%AUTO% objects immediately destroyed after use\)\.

# The Tree Query Language

This and the following sections specify the Tree Query Language used by the
query objects of this package in detail\.

First we explain the general concepts underneath the language which are required
to comprehend it\. This is followed by the specifications for all the available
query operators\. They fall into eight categories, and each category has its own
section\.

  1. [TreeQL Concepts](#subsection3)

  1. [Structural generators](#subsection4)

  1. [Attribute Filters](#subsection5)

  1. [Attribute Mutators](#subsection6)

  1. [Attribute String Accessors](#subsection7)

  1. [Sub\-queries](#subsection8)

  1. [Node Set Operators](#subsection9)

  1. [Node Set Iterators](#subsection10)

  1. [Typed node support](#subsection11)

## TreeQL Concepts

The main concept which has to be understood is that of the *node set*\. Each
query object maintains exactly one such *node set*, and essentially all
operators use it and input argument and for their result\. This structure simply
contains the handles of all nodes which are currently of interest to the query
object\. To name it a *[set](\.\./\.\./\.\./\.\./index\.md\#set)* is a bit of a
misnomer, because

  1. A node \(handle\) can occur in the structure more than once, and

  1. the order of nodes in the structure is important as well\. Whenever an
     operator processes all nodes in the node set it will do so in the order
     they occur in the structure\.

Regarding the possible multiple occurrence of a node, consider a node set
containing two nodes A and B, both having node P as their immediate parent\.
Application of the TreeQL operator "parent" will then add P to the new node set
twice, once per node it was parent of\. I\.e\. the new node set will then be \{P P\}\.

## Structural generators

All tree\-structural operators locate nodes in the tree based on a structural
relation ship to the nodes currently in the set and then replace the current
node set with the set of nodes found Nodes which fulfill such a relationship
multiple times are added to the result as often as they fulfill the
relationship\.

It is important to note that the found nodes are collected in a separate storage
area while processing the node set, and are added to \(or replacing\) the current
node set only after the current node set has been processed completely\. In other
words, the new nodes are *not* processed by the operator as well and do not
affect the iteration\.

When describing an operator the variable __N__ will be used to refer to any
node in the node set\.

  - __ancestors__

    Replaces the current node set with the ancestors for all nodes __N__ in
    the node set, should __N__ have a parent\. In other words, nodes without
    a parent do not contribute to the new node set\. In other words, uses all
    nodes on the path from node __N__ to root, in this order \(root last\),
    for all nodes __N__ in the node set\. This includes the root, but not the
    node itself\.

  - __rootpath__

    Replaces the current node set with the ancestors for all nodes __N__ in
    the node set, should __N__ have a parent\. In other words, nodes without
    a parent do not contribute to the new node set\. In contrast to the operator
    __ancestors__ the nodes are added in reverse order however, i\.e\. the
    root node first\.

  - __parent__

    Replaces the current node set with the parent of node __N__, for all
    nodes __N__ in the node set, should __N__ have a parent\. In other
    words, nodes without a parent do not contribute to the new node set\.

  - __children__

    Replaces the current node set with the immediate children of node __N__,
    for all nodes __N__ in the node set, should __N__ have children\. In
    other words, nodes without children do not contribute to the new node set\.

  - __left__

    Replaces the current node set with the previous/left sibling for all nodes
    __N__ in the node set, should __N__ have siblings to the left\. In
    other words, nodes without left siblings do not contribute to the new node
    set\.

  - __right__

    Replaces the current node set with the next/right sibling for all nodes
    __N__ in the node set, should __N__ have siblings to the right\. In
    other words, nodes without right siblings do not contribute to the new node
    set\.

  - __prev__

    Replaces the current node set with all previous/left siblings of node
    __N__, for all nodes __N__ in the node set, should __N__ have
    siblings to the left\. In other words, nodes without left siblings are
    ignored\. The left sibling adjacent to the node is added first, and the
    leftmost sibling last \(reverse tree order\)\.

  - __esib__

    Replaces the current node set with all previous/left siblings of node
    __N__, for all nodes __N__ in the node set, should __N__ have
    siblings to the left\. In other words, nodes without left siblings are
    ignored\. The leftmost sibling is added first, and the left sibling adjacent
    to the node last \(tree order\)\.

    The method name is a shorthand for *Earlier SIBling*\.

  - __next__

    Replaces the current node set with all next/right siblings of node
    __N__, for all nodes __N__ in the node set, should __N__ have
    siblings to the right\. In other words, nodes without right siblings do not
    contribute to the new node set\. The right sibling adjacent to the node is
    added first, and the rightmost sibling last \(tree order\)\.

  - __root__

    Replaces the current node set with a node set containing a single node, the
    root of the tree\.

  - __tree__

    Replaces the current node set with a node set containing all nodes found in
    the tree\. The nodes are added in pre\-order \(parent first, then children, the
    latter from left to right, first to last\)\.

  - __descendants__

    Replaces the current node set with the nodes in all subtrees rooted at node
    __N__, for all nodes __N__ in the node set, should __N__ have
    children\. In other words, nodes without children do not contribute to the
    new node set\.

    This is like the operator __children__, but covers the children of
    children as well, i\.e\. all the *proper descendants*\. "Rooted at __N__"
    means that __N__ itself is not added to the new set, which is also
    implied by *proper descendants*\.

  - __subtree__

    Like operator __descendants__, but includes the node __N__\. In other
    words:

    Replaces the current node set with the nodes of the subtree of node
    __N__, for all nodes __N__ in the node set, should __N__ have
    children\. In other words, nodes without children do not contribute to the
    new node set\. I\.e this is like the operator __children__, but covers the
    children of children, etc\. as well\. "Of __N__" means that __N__
    itself is added to the new set\.

  - __forward__

    Replaces the current node set with the nodes in the subtrees rooted at the
    right siblings of node __N__, for all nodes __N__ in the node set,
    should __N__ have right siblings, and they children\. In other words,
    nodes without right siblings, and them without children are ignored\.

    This is equivalent to the operator sequence

        next descendants

  - __later__

    This is an alias for the operator __forward__\.

  - __backward__

    Replaces the current node set with the nodes in the flattened previous
    subtrees, in reverse tree order\.

    This is nearly equivalent to the operator sequence

        prev descendants

    The only difference is that this uses the nodes in reverse order\.

  - __earlier__

    Replaces the current node set with the nodes in the flattened previous
    subtrees, in tree order\.

    This is equivalent to the operator sequence

        prev subtree

## Attribute Filters

These operators filter the node set by reference to attributes of nodes and
their properties\. Filter means that all nodes not fulfilling the criteria are
removed from the node set\. In other words, the node set is replaced by the set
of nodes fulfilling the filter criteria\.

  - __hasatt__ *attr*

    Reduces the node set to nodes which have an attribute named *attr*\.

  - __withatt__ *attr* *value*

    Reduces the node set to nodes which have an attribute named *attr*, and
    where the value of that attribute is equal to *value* \(The "==" operator
    is __string equal \-nocase__\)\.

  - __withatt\!__ *attr* *val*

    This is the same as __withatt__, but all nodes in the node set have to
    have the attribute, and the "==" operator is __string equal__, i\.e\. no
    __\-nocase__\. The operator will fail with an error if they don't have the
    attribute\.

  - __attof__ *attr* *vals*

    Reduces the node set to nodes which which have an attribute named *attr*
    and where the value of that attribute is contained in the list *vals* of
    legal values\. The contained\-in operator used here does glob matching \(using
    the attribute value as pattern\) and ignores the case of the attribute value,
    *but not* for the elements of *vals*\.

  - __attmatch__ *attr* *match*

    Same as __withatt__, but __string match__ is used as the "=="
    operator, and *match* is the pattern checked for\.

    *Note* that *match* is a interpreted as a partial argument *list* for
    __string match__\. This means that it is interpreted as a list containing
    the pattern, and the pattern element can be preceded by options understand
    by __string match__, like __\-nocase__\. This is especially important
    should the pattern contain spaces\. It has to be wrapped into a list for
    correct interpretation by this operator

## Attribute Mutators

These operators change node attributes within the underlying tree\. In other
words, all these operators have *side effects*\.

  - __set__ *attr* *val*

    Sets the attribute *attr* to the value *val*, for all nodes __N__ in
    the node set\. The operator will fail if a node does not have an attribute
    named *attr*\. The tree will be left in a partially modified state\.

  - __unset__ *attr*

    Unsets the attribute *attr*, for all nodes __N__ in the node set\. The
    operator will fail if a node does not have an attribute named *attr*\. The
    tree will be left in a partially modified state\.

## Attribute String Accessors

These operators retrieve the values of node attributes from the underlying tree\.
The collected results are stored in the node set, but are not actually nodes\.

In other words, they redefine the semantics of the node set stored by the query
object to contain non\-node data after their completion\.

The query interpreter will terminate after it has finished processing one of
these operators, silently discarding any later query elements\. It also means
that our talk about maintenance of a node set is not quite true\. It is a node
set while the interpreter is processing commands, but can be left as an
attribute value set at the end of query processing\.

  - __string__ *op* *attr*

    Applies the string operator *op* to the attribute named *attr*, for all
    nodes __N__ in the node set, collects the results of that application
    and places them into the node set\.

    The operator will fail if a node does not have an attribute named *attr*\.

    The argument *op* is interpreted as partial argument list for the builtin
    command __[string](\.\./\.\./\.\./\.\./index\.md\#string)__\. Its first word
    has to be any of the sub\-commands understood by
    __[string](\.\./\.\./\.\./\.\./index\.md\#string)__\. This has to be followed
    by all arguments required for the subcommand, except the last\. that last
    argument is supplied by the attribute value\.

  - __get__ *pattern*

    For all nodes __N__ in the node set it determines all their attributes
    with names matching the glob *pattern*, then the values of these
    attributes, at last it replaces the node set with the list of these
    attribute values\.

  - __attlist__

    This is a convenience definition for the operator __getvals \*__\. In
    other words, it replaces the node set with a list of the attribute values
    for all attributes for all nodes __N__ in the node set\.

  - __attrs__ *glob*

    Replaces the current node set with a list of attribute lists, one attribute
    list per for all nodes __N__ in the node set\.

  - __attval__ *attname*

    Reduces the current node set with the operator __hasatt__, and then
    replaces it with a list containing the values of the attribute named
    *attname* for all nodes __N__ in the node set\.

## Sub\-queries

Sub\-queries yield node sets which are then used to augment, reduce or replace
the current node set\.

  - __andq__ *query*

    Replaces the node set with the set\-intersection of the node set generated by
    the sub\-query *query* and itself\.

    The execution of the sub\-query uses the current node set as its own initial
    node set\.

  - __orq__ *query*

    Replaces the node set with the set\-union of the node set generated by the
    sub\-query *query* and itself\. Duplicate nodes are removed\.

    The execution of the sub\-query uses the current node set as its own initial
    node set\.

  - __notq__ *query*

    Replaces the node set with the set of nodes generated by the sub\-query
    *query* which are also not in the current node set\. In other word the set
    difference of itself and the node set generated by the sub\-query\.

    The execution of the sub\-query uses the current node set as its own initial
    node set\.

## Node Set Operators

These operators change the node set directly, without referring to the tree\.

  - __unique__

    Removes duplicate nodes from the node set, preserving order\. In other words,
    the earliest occurrence of a node handle is preserved, every other
    occurrence is removed\.

  - __select__

    Replaces the current node set with a node set containing only the first node
    from the current node set

  - __transform__ *query* *var* *body*

    First it interprets the sub\-query *query*, using the current node set as
    its initial node set\. Then it iterates over the result of that query,
    binding the handle of each node to the variable named in *var*, and
    executing the script *body*\. The collected results of these executions is
    made the new node set, replacing the current one\.

    The script *body* is executed in the context of the caller\.

  - __map__ *var* *body*

    Iterates over the current node set, binding the handle of each node to the
    variable named in *var*, and executing the script *body*\. The collected
    results of these executions is made the new node set, replacing the current
    one\.

    The script *body* is executed in the context of the caller\.

  - __quote__ *val*

    Appends the literal value *val* to the current node set\.

  - __replace__ *val*

    Replaces the current node set with the literal list value *val*\.

## Node Set Iterators

  - __foreach__ *query* *var* *body*

    Interprets the sub\-query *query*, then performs the equivalent of operator
    __over__ on the nodes in the node set created by that query\. The current
    node set is not changed, except through side effects from the script
    *body*\.

    The script *body* is executed in the context of the caller\.

  - __with__ *query* *body*

    Interprets the *query*, then runs the script *body* on the node set
    generated by the query\. At last it restores the current node set as it was
    before the execution of the query\.

    The script *body* is executed in the context of the caller\.

  - __over__ *var* *body*

    Executes the script *body* for each node in the node set, with the
    variable named by *var* bound to the name of the current node\. The script
    *body* is executed in the context of the caller\.

    This is like the builtin
    __[foreach](\.\./\.\./\.\./\.\./index\.md\#foreach)__, with the node set as
    the source of the list to iterate over\.

    The results of executing the *body* are ignored\.

  - __delete__

    Deletes all the nodes contained in the current node set from the tree\.

## Typed node support

These filters and accessors assume the existence of an attribute called
__@type__, and are short\-hand forms useful for cost\-like tree query, html
tree editing, and so on\.

  - __nodetype__

    Returns the node type of nodes\. Attribute string accessor\. This is
    equivalent to

        get @type

  - __oftype__ *t*

    Reduces the node set to nodes whose type is equal to *t*, with letter case
    ignored\.

  - __nottype__ *t*

    Reduces the node set to nodes whose type is not equal to *t*, with letter
    case ignored\.

  - __oftypes__ *attrs*

    Reduces set to nodes whose @type is an element in the list *attrs* of
    types\. The value of @type is used as a glob pattern, and letter case is
    relevant\.

# Examples

\.\.\. TODO \.\.\.

# References

  1. [COST](http://wiki\.tcl\.tk/COST) on the Tcler's Wiki\.

  1. [TreeQL](http://wiki\.tcl\.tk/treeql) on the Tcler's Wiki\. Discuss this
     package there\.

# Bugs, Ideas, Feedback

This document, and the package it describes, will undoubtedly contain bugs and
other problems\. Please report such in the category *treeql* of the [Tcllib
Trackers](http://core\.tcl\.tk/tcllib/reportlist)\. Please also report any ideas
for enhancements you may have for either package and/or documentation\.

When proposing code changes, please provide *unified diffs*, i\.e the output of
__diff \-u__\.

Note further that *attachments* are strongly preferred over inlined patches\.
Attachments can be made by going to the __Edit__ form of the ticket
immediately after its creation, and then using the left\-most button in the
secondary navigation bar\.

# KEYWORDS

[Cost](\.\./\.\./\.\./\.\./index\.md\#cost), [DOM](\.\./\.\./\.\./\.\./index\.md\#dom),
[TreeQL](\.\./\.\./\.\./\.\./index\.md\#treeql),
[XPath](\.\./\.\./\.\./\.\./index\.md\#xpath), [XSLT](\.\./\.\./\.\./\.\./index\.md\#xslt),
[structured queries](\.\./\.\./\.\./\.\./index\.md\#structured\_queries),
[tree](\.\./\.\./\.\./\.\./index\.md\#tree), [tree query
language](\.\./\.\./\.\./\.\./index\.md\#tree\_query\_language)

# CATEGORY

Data structures

# COPYRIGHT

Copyright © 2004 Colin McCormack <coldstore@users\.sourceforge\.net>
Copyright © 2004 Andreas Kupries <andreas\_kupries@users\.sourceforge\.net>

redpajama_set_name: RedPajamaGithub


text:
{% extends "registration/base.html" %}
{% load i18n %}

{% block registration_content %}
    {{ block.super }}

            {% if validlink %}
                <form method="post" action="." class="simple">
                    {% csrf_token %}

                        {{ form.as_p }}

                            <input type="submit" class="submit button" value="{% trans 'Submit' %}">

                </form>
            {% else %}

{% trans "Password reset failed." %}

            {% endif %}

{% endblock %}


text:
package pager

import (
	"net/url"
	"time"

	"config"
	proto "github.com/golang/protobuf/proto"

	"appengine"
	"appengine/datastore"
	"appengine/taskqueue"
)

type Escalation struct {
	key                  *datastore.Key
	Mail                 []byte
	Subject              []byte
	Body                 []byte
	NotificationSequence []byte
	LastContact          int
	Acknowledged         bool
}

func getEscalation(c appengine.Context, id string) (*Escalation, error) {
	k, err := datastore.DecodeKey(id)
	if err != nil {
		return nil, err
	}
	esc := new(Escalation)
	if err = datastore.Get(c, k, esc); err != nil {
		return nil, err
	}
	esc.key = k
	return esc, nil
}

func (e *Escalation) scheduleNotification(c appengine.Context) (err error) {
	seq, err := e.GetNotificationSequence(c)
	if err != nil {
		return err
	}
	t := taskqueue.NewPOSTTask("/admin/notify", url.Values{
		"k": []string{e.key.Encode()},
	})
	if e.LastContact > -1 {
		t.Delay = time.Second * time.Duration(seq.Contact[e.LastContact].GetTimeout())
	}
	if _, err := taskqueue.Add(c, t, ""); err != nil {
		return err
	}
	return nil
}

func (e *Escalation) save(c appengine.Context) (err error) {
	if e.key == nil {
		e.key = datastore.NewIncompleteKey(c, "Escalation", nil)
	}
	e.key, err = datastore.Put(c, e.key, e)
	return err
}

func (e *Escalation) GetNotificationSequence(c appengine.Context) (ns *config.NotificationSequence, err error) {
	seq := new(config.NotificationSequence)
	if err := proto.Unmarshal(e.NotificationSequence, seq); err != nil {
		return nil, err
	}
	return seq, nil
}


text: raise NotImplementedError("getpass is not yet implemented in Skulpt")


text:
[![Stories in Ready](https://badge.waffle.io/skeate/seque.png?label=ready&title=Ready)](https://waffle.io/skeate/seque)
[![Build Status](https://travis-ci.org/skeate/seque.svg?branch=master)](https://travis-ci.org/skeate/seque)
[![Test Coverage](https://codeclimate.com/github/skeate/seque/badges/coverage.svg)](https://codeclimate.com/github/skeate/seque/coverage)
[![Code Climate](https://codeclimate.com/github/skeate/seque/badges/gpa.svg)](https://codeclimate.com/github/skeate/seque)
[![npm version](https://badge.fury.io/js/seque.svg)](http://badge.fury.io/js/seque)
[![bower version](https://badge.fury.io/bo/seque.svg)](http://badge.fury.io/bo/seque)
[![Dev Status](https://david-dm.org/skeate/seque/dev-status.svg)](https://david-dm.org/skeate/seque#info=devDependencies&view=table)

[![Sauce Test Status](https://saucelabs.com/browser-matrix/seque-tests.svg)](https://saucelabs.com/u/seque-tests)

# seque

[![Greenkeeper badge](https://badges.greenkeeper.io/skeate/seque.svg)](https://greenkeeper.io/)
chainable control flow methods for javascript

# what?

```javascript
let arr = [1, 2, 3, 4, 5, 6];
let useEvens = Math.random() > .5;
arr
  .if(useEvens)
  .filter(x => x % 2 == 0)
  .else()
  .filter(x => x % 2)
  .endif()
  // at this point we have either [2,4,6] or [1,3,5] depending on the value
  // of useEvens
```

see also: https://skeate.github.io/2015/07/17/Seque-What-It-Is-and-How-It-Works.html

# why?

why not

# the catch

unless your platform supports proxies (check compatibility with [kangax's
compat-table](https://kangax.github.io/compat-table/es6/#Proxy)) this won't work
completely seamlessly. if a link in a chain returns an object with a method not
on the link in the chain right before a seque method, *and* you then try to call
that method, things'll break, unless you deliberately specify that method's name
in the seque method call.


text:
import randomBytes = require('random-bytes');

// Callback-based signature.
randomBytes(16, (err, buff) => {
    if (err) {
        console.error(err);
    } else {
        console.log(buff);
    }
});

// Promise-based signature.
randomBytes(32)
    .then((buff) => {
        console.log(buff);
    });

// Synchronous signature.
const buff = randomBytes.sync(64);
console.log(buff);


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(dead_code)]

// The USB stack currently expects 7 strings, at these indices.
pub const STRING_LANG: u8       = 0;
pub const STRING_VENDOR: u8     = 1;
pub const STRING_BOARD: u8      = 2;
pub const STRING_PLATFORM: u8   = 3;
pub const STRING_INTERFACE1: u8 = 4;  // Shell
pub const STRING_BLAH: u8       = 5;  // Garbage?
pub const STRING_INTERFACE2: u8 = 6;  // Hotel_U2F

const MAX_CONTROL_ENDPOINTS: u16 =  3;
const MAX_NORMAL_ENDPOINTS:  u16 = 16;
pub const MAX_PACKET_SIZE:   u16 = 64;
pub const U2F_REPORT_SIZE:   u16 = 64;

// Constants defining buffer sizes for all endpoints.
pub const EP_BUFFER_SIZE_BYTES:    usize = MAX_PACKET_SIZE as usize;
pub const EP_BUFFER_SIZE_WORDS:    usize = EP_BUFFER_SIZE_BYTES / 4;

// Complicated FIFP size formula specified in reference manual
pub const RX_FIFO_SIZE: u16 = (4 * MAX_CONTROL_ENDPOINTS + 6) +
                              (2 * (MAX_PACKET_SIZE / 4 + 1)) +
                              (2 * MAX_NORMAL_ENDPOINTS) + 1;
pub const TX_FIFO_SIZE: u16 = 2 * MAX_PACKET_SIZE / 4;

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(dead_code)]
pub enum Descriptor {
    Device          = 0x01,
    Configuration   = 0x02,
    String          = 0x03,
    Interface       = 0x04,
    Endpoint        = 0x05,
    DeviceQualifier = 0x06,
    HidDevice       = 0x21,
    Report          = 0x22,
    Unknown         = 0xFF,
}

impl Descriptor {
    pub fn from_u8(t: u8) -> Descriptor {
        match t {
            0x01 => Descriptor::Device,
            0x02 => Descriptor::Configuration,
            0x03 => Descriptor::String,
            0x04 => Descriptor::Interface,
            0x05 => Descriptor::Endpoint,
            0x06 => Descriptor::Endpoint,
            0x21 => Descriptor::HidDevice,
            0x22 => Descriptor::Report,
            _    => Descriptor::Unknown,
        }
    }
}

#[allow(dead_code)]
pub const GET_DESCRIPTOR_DEVICE: u32           = 1;
pub const GET_DESCRIPTOR_CONFIGURATION: u32    = 2;
pub const GET_DESCRIPTOR_STRING: u32           = 3;
pub const GET_DESCRIPTOR_INTERFACE: u32        = 4;
pub const GET_DESCRIPTOR_ENDPOINT: u32         = 5;
pub const GET_DESCRIPTOR_DEVICE_QUALIFIER: u32 = 6;
pub const GET_DESCRIPTOR_DEBUG: u32            = 10;

// Copied from Cr52 usb_hidu2f.c - pal
pub const U2F_REPORT_DESCRIPTOR: [u8; 34] = [
    0x06, 0xD0, 0xF1, /* Usage Page (FIDO Alliance), FIDO_USAGE_PAGE */
    0x09, 0x01,       /* Usage (U2F HID Authenticator Device),
                         FIDO_USAGE_U2FHID */
    0xA1, 0x01,       /* Collection (Application), HID_APPLICATION */
    0x09, 0x20,       /*   Usage (Input Report Data), FIDO_USAGE_DATA_IN */
    0x15, 0x00,       /*   Logical Minimum (0) */
    0x26, 0xFF, 0x00, /*   Logical Maximum (255) */
    0x75, 0x08,       /*   Report Size (8) */
    0x95, 0x40,       /*   Report Count (64), HID_INPUT_REPORT_BYTES */
    0x81, 0x02,       /*   Input (Data, Var, Abs), Usage */
    0x09, 0x21,       /*   Usage (Output Report Data), FIDO_USAGE_DATA_OUT */
    0x15, 0x00,       /*   Logical Minimum (0) */
    0x26, 0xFF, 0x00, /*   Logical Maximum (255) */
    0x75, 0x08,       /*   Report Size (8) */
    0x95, 0x40,       /*   Report Count (64), HID_OUTPUT_REPORT_BYTES */
    0x91, 0x02,       /*   Output (Data, Var, Abs), Usage */
    0xC0              /* End Collection */
];

pub enum U2fHidCommand {
    Error = 0xbf,
}


text:
package org.mule.modules.selenium;

import org.openqa.selenium.android.AndroidDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.iphone.IPhoneDriver;

/**
 * List of Selenium Web drivers.
 */
public enum SeleniumWebDriver {
    /**
     * Firefox
     */
    FIREFOX(FirefoxDriver.class),

    /**
     * Google Chrome
     */
    CHROME(ChromeDriver.class),

    /**
     * Html Unit
     */
    HTMLUNIT(HtmlUnitDriver.class),

    /**
     * Android
     */
    ANDROID(AndroidDriver.class),

    /**
     * iPhone
     */
    IPHONE(IPhoneDriver.class),

    /**
     * Internet Explorer
     */
    INTERNET_EXPLORER(InternetExplorerDriver.class);

    private Class<?> driverClass;

    private SeleniumWebDriver(Class<?> driverClass) {
        this.driverClass = driverClass;
    }

    public Class<?> getDriverClass() {
        return driverClass;
    }
}


text:
<?php
//  Copyright (c) 2007-2008 Facebook
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
// See accompanying file LICENSE or visit the Scribe site at:
// http://developers.facebook.com/scribe/

include_once 'tests.php';

if ($argc > 1) {
  $numconnections = $argv[1];
} else {
  $numconnections = 200;
}

if ($argc > 2) {
  $client = $argv[2];
} else {
  $client = "client1";
}

if ($argc > 3) {
  $category = $argv[3];
} else {
  $category = "context";
}

print 'starting test...';

many_connections_test($category, $client, $numconnections, 10000, 200000, 20, 100);

print 'done';

?>


text:
#include "SkStream.h"
#include "SkData.h"
#include "SkFixed.h"
#include "SkString.h"
#include "SkOSFile.h"

SK_DEFINE_INST_COUNT(SkStream)
SK_DEFINE_INST_COUNT(SkWStream)
SK_DEFINE_INST_COUNT(SkFILEStream)
SK_DEFINE_INST_COUNT(SkFDStream)
SK_DEFINE_INST_COUNT(SkMemoryStream)
SK_DEFINE_INST_COUNT(SkBufferStream)
SK_DEFINE_INST_COUNT(SkFILEWStream)
SK_DEFINE_INST_COUNT(SkMemoryWStream)
SK_DEFINE_INST_COUNT(SkDynamicMemoryWStream)
SK_DEFINE_INST_COUNT(SkDebugWStream)

///////////////////////////////////////////////////////////////////////////////

const char* SkStream::getFileName()
{
    // override in subclass if you represent a file
    return NULL;
}

const void* SkStream::getMemoryBase()
{
    // override in subclass if you represent a memory block
    return NULL;
}

size_t SkStream::skip(size_t size)
{
    /*  Check for size == 0, and just return 0. If we passed that
        to read(), it would interpret it as a request for the entire
        size of the stream.
    */
    return size ? this->read(NULL, size) : 0;
}

int8_t SkStream::readS8() {
    int8_t value;
    SkDEBUGCODE(size_t len =) this->read(&value, 1);
    SkASSERT(1 == len);
    return value;
}

int16_t SkStream::readS16() {
    int16_t value;
    SkDEBUGCODE(size_t len =) this->read(&value, 2);
    SkASSERT(2 == len);
    return value;
}

int32_t SkStream::readS32() {
    int32_t value;
    SkDEBUGCODE(size_t len =) this->read(&value, 4);
    SkASSERT(4 == len);
    return value;
}

SkScalar SkStream::readScalar() {
    SkScalar value;
    SkDEBUGCODE(size_t len =) this->read(&value, sizeof(SkScalar));
    SkASSERT(sizeof(SkScalar) == len);
    return value;
}

#define SK_MAX_BYTE_FOR_U8          0xFD
#define SK_BYTE_SENTINEL_FOR_U16    0xFE
#define SK_BYTE_SENTINEL_FOR_U32    0xFF

size_t SkStream::readPackedUInt() {
    uint8_t byte;
    if (!this->read(&byte, 1)) {
        return 0;
    }
    if (SK_BYTE_SENTINEL_FOR_U16 == byte) {
        return this->readU16();
    } else if (SK_BYTE_SENTINEL_FOR_U32 == byte) {
        return this->readU32();
    } else {
        return byte;
    }
}

SkData* SkStream::readData() {
    size_t size = this->readU32();
    if (0 == size) {
        return SkData::NewEmpty();
    } else {
        void* buffer = sk_malloc_throw(size);
        this->read(buffer, size);
        return SkData::NewFromMalloc(buffer, size);
    }
}

//////////////////////////////////////////////////////////////////////////////////////

SkWStream::~SkWStream()
{
}

void SkWStream::newline()
{
    this->write("\n", 1);
}

void SkWStream::flush()
{
}

bool SkWStream::writeText(const char text[])
{
    SkASSERT(text);
    return this->write(text, strlen(text));
}

bool SkWStream::writeDecAsText(int32_t dec)
{
    SkString    tmp;
    tmp.appendS32(dec);
    return this->write(tmp.c_str(), tmp.size());
}

bool SkWStream::writeBigDecAsText(int64_t dec, int minDigits)
{
    SkString    tmp;
    tmp.appendS64(dec, minDigits);
    return this->write(tmp.c_str(), tmp.size());
}

bool SkWStream::writeHexAsText(uint32_t hex, int digits)
{
    SkString    tmp;
    tmp.appendHex(hex, digits);
    return this->write(tmp.c_str(), tmp.size());
}

bool SkWStream::writeScalarAsText(SkScalar value)
{
    SkString    tmp;
    tmp.appendScalar(value);
    return this->write(tmp.c_str(), tmp.size());
}

bool SkWStream::write8(U8CPU value) {
    uint8_t v = SkToU8(value);
    return this->write(&v, 1);
}

bool SkWStream::write16(U16CPU value) {
    uint16_t v = SkToU16(value);
    return this->write(&v, 2);
}

bool SkWStream::write32(uint32_t value) {
    return this->write(&value, 4);
}

bool SkWStream::writeScalar(SkScalar value) {
    return this->write(&value, sizeof(value));
}

bool SkWStream::writePackedUInt(size_t value) {
    uint8_t data[5];
    size_t len = 1;
    if (value <= SK_MAX_BYTE_FOR_U8) {
        data[0] = value;
        len = 1;
    } else if (value <= 0xFFFF) {
        uint16_t value16 = value;
        data[0] = SK_BYTE_SENTINEL_FOR_U16;
        memcpy(&data[1], &value16, 2);
        len = 3;
    } else {
        uint32_t value32 = value;
        data[0] = SK_BYTE_SENTINEL_FOR_U32;
        memcpy(&data[1], &value32, 4);
        len = 5;
    }
    return this->write(data, len);
}

bool SkWStream::writeStream(SkStream* stream, size_t length) {
    char scratch[1024];
    const size_t MAX = sizeof(scratch);

    while (length != 0) {
        size_t n = length;
        if (n > MAX) {
            n = MAX;
        }
        stream->read(scratch, n);
        if (!this->write(scratch, n)) {
            return false;
        }
        length -= n;
    }
    return true;
}

bool SkWStream::writeData(const SkData* data) {
    if (data) {
        this->write32(data->size());
        this->write(data->data(), data->size());
    } else {
        this->write32(0);
    }
    return true;
}

///////////////////////////////////////////////////////////////////////////////

SkFILEStream::SkFILEStream(const char file[]) : fName(file)
{
    fFILE = file ? sk_fopen(fName.c_str(), kRead_SkFILE_Flag) : NULL;
}

SkFILEStream::~SkFILEStream()
{
    if (fFILE)
        sk_fclose(fFILE);
}

void SkFILEStream::setPath(const char path[])
{
    fName.set(path);
    if (fFILE)
    {
        sk_fclose(fFILE);
        fFILE = NULL;
    }
    if (path)
        fFILE = sk_fopen(fName.c_str(), kRead_SkFILE_Flag);
}

const char* SkFILEStream::getFileName()
{
    return fName.c_str();
}

bool SkFILEStream::rewind()
{
    if (fFILE)
    {
        if (sk_frewind(fFILE))
            return true;
        // we hit an error
        sk_fclose(fFILE);
        fFILE = NULL;
    }
    return false;
}

size_t SkFILEStream::read(void* buffer, size_t size)
{
    if (fFILE)
    {
        if (buffer == NULL && size == 0)    // special signature, they want the total size
            return sk_fgetsize(fFILE);
        else
            return sk_fread(buffer, size, fFILE);
    }
    return 0;
}

///////////////////////////////////////////////////////////////////////////////

static SkData* newFromParams(const void* src, size_t size, bool copyData) {
    if (copyData) {
        return SkData::NewWithCopy(src, size);
    } else {
        return SkData::NewWithProc(src, size, NULL, NULL);
    }
}

SkMemoryStream::SkMemoryStream() {
    fData = SkData::NewEmpty();
    fOffset = 0;
}

SkMemoryStream::SkMemoryStream(size_t size) {
    fData = SkData::NewFromMalloc(sk_malloc_throw(size), size);
    fOffset = 0;
}

SkMemoryStream::SkMemoryStream(const void* src, size_t size, bool copyData) {
    fData = newFromParams(src, size, copyData);
    fOffset = 0;
}

SkMemoryStream::~SkMemoryStream() {
    fData->unref();
}

void SkMemoryStream::setMemoryOwned(const void* src, size_t size) {
    fData->unref();
    fData = SkData::NewFromMalloc(src, size);
    fOffset = 0;
}

void SkMemoryStream::setMemory(const void* src, size_t size, bool copyData) {
    fData->unref();
    fData = newFromParams(src, size, copyData);
    fOffset = 0;
}

SkData* SkMemoryStream::copyToData() const {
    fData->ref();
    return fData;
}

SkData* SkMemoryStream::setData(SkData* data) {
    SkRefCnt_SafeAssign(fData, data);
    return data;
}

void SkMemoryStream::skipToAlign4() {
    // cast to remove unary-minus warning
    fOffset += -(int)fOffset & 0x03;
}

bool SkMemoryStream::rewind() {
    fOffset = 0;
    return true;
}

size_t SkMemoryStream::read(void* buffer, size_t size) {
    size_t dataSize = fData->size();

    if (buffer == NULL && size == 0)    // special signature, they want the total size
        return dataSize;

    // if buffer is NULL, seek ahead by size

    if (size == 0) {
        return 0;
    }
    if (size > dataSize - fOffset) {
        size = dataSize - fOffset;
    }
    if (buffer) {
        memcpy(buffer, fData->bytes() + fOffset, size);
    }
    fOffset += size;
    return size;
}

const void* SkMemoryStream::getMemoryBase() {
    return fData->data();
}

const void* SkMemoryStream::getAtPos() {
    return fData->bytes() + fOffset;
}

size_t SkMemoryStream::seek(size_t offset) {
    if (offset > fData->size()) {
        offset = fData->size();
    }
    fOffset = offset;
    return offset;
}

///////////////////////////////////////////////////////////////////////////////

SkBufferStream::SkBufferStream(SkStream* proxy, size_t bufferSize)
    : fProxy(proxy)
{
    SkASSERT(proxy != NULL);
    proxy->ref();
    this->init(NULL, bufferSize);
}

SkBufferStream::SkBufferStream(SkStream* proxy, void* buffer, size_t bufferSize)
    : fProxy(proxy)
{
    SkASSERT(proxy != NULL);
    SkASSERT(buffer == NULL || bufferSize != 0);    // init(addr, 0) makes no sense, we must know how big their buffer is
    proxy->ref();
    this->init(buffer, bufferSize);
}

void SkBufferStream::init(void* buffer, size_t bufferSize)
{
    if (bufferSize == 0)
        bufferSize = kDefaultBufferSize;

    fOrigBufferSize = bufferSize;
    fBufferSize = bufferSize;
    fBufferOffset = bufferSize; // to trigger a reload on the first read()

    if (buffer == NULL)
    {
        fBuffer = (char*)sk_malloc_throw(fBufferSize);
        fWeOwnTheBuffer = true;
    }
    else
    {
        fBuffer = (char*)buffer;
        fWeOwnTheBuffer = false;
    }
}

SkBufferStream::~SkBufferStream()
{
    fProxy->unref();
    if (fWeOwnTheBuffer)
        sk_free(fBuffer);
}

bool SkBufferStream::rewind()
{
    fBufferOffset = fBufferSize = fOrigBufferSize;
    return fProxy->rewind();
}

const char* SkBufferStream::getFileName()
{
    return fProxy->getFileName();
}

#ifdef SK_DEBUG
//  #define SK_TRACE_BUFFERSTREAM
#endif

size_t SkBufferStream::read(void* buffer, size_t size) {
#ifdef SK_TRACE_BUFFERSTREAM
    SkDebugf("Request %d", size);
#endif

    if (buffer == NULL && size == 0) {
        return fProxy->read(buffer, size);    // requesting total size
    }

    if (0 == size) {
        return 0;
    }

    // skip size bytes
    if (NULL == buffer) {
        size_t remaining = fBufferSize - fBufferOffset;
        if (remaining >= size) {
            fBufferOffset += size;
            return size;
        }
        // if we get here, we are being asked to skip beyond our current buffer
        // so reset our offset to force a read next time, and skip the diff
        // in our proxy
        fBufferOffset = fOrigBufferSize;
        return remaining + fProxy->read(NULL, size - remaining);
    }

    size_t s = size;
    size_t actuallyRead = 0;

    // flush what we can from our fBuffer
    if (fBufferOffset < fBufferSize)
    {
        if (s > fBufferSize - fBufferOffset)
            s = fBufferSize - fBufferOffset;
        memcpy(buffer, fBuffer + fBufferOffset, s);
#ifdef SK_TRACE_BUFFERSTREAM
        SkDebugf(" flush %d", s);
#endif
        size -= s;
        fBufferOffset += s;
        buffer = (char*)buffer + s;
        actuallyRead = s;
    }

    // check if there is more to read
    if (size)
    {
        SkASSERT(fBufferOffset >= fBufferSize); // need to refill our fBuffer

        if (size < fBufferSize) // lets try to read more than the request
        {
            s = fProxy->read(fBuffer, fBufferSize);
#ifdef SK_TRACE_BUFFERSTREAM
            SkDebugf(" read %d into fBuffer", s);
#endif
            if (size > s)   // they asked for too much
                size = s;
            if (size)
            {
                memcpy(buffer, fBuffer, size);
                actuallyRead += size;
#ifdef SK_TRACE_BUFFERSTREAM
                SkDebugf(" memcpy %d into dst", size);
#endif
            }

            fBufferOffset = size;
            fBufferSize = s;        // record the (possibly smaller) size for the buffer
        }
        else    // just do a direct read
        {
            actuallyRead += fProxy->read(buffer, size);
#ifdef SK_TRACE_BUFFERSTREAM
            SkDebugf(" direct read %d", size);
#endif
        }
    }
#ifdef SK_TRACE_BUFFERSTREAM
    SkDebugf("\n");
#endif
    return actuallyRead;
}

const void* SkBufferStream::getMemoryBase()
{
    return fProxy->getMemoryBase();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////

SkFILEWStream::SkFILEWStream(const char path[])
{
    fFILE = sk_fopen(path, kWrite_SkFILE_Flag);
}

SkFILEWStream::~SkFILEWStream()
{
    if (fFILE)
        sk_fclose(fFILE);
}

bool SkFILEWStream::write(const void* buffer, size_t size)
{
    if (fFILE == NULL)
        return false;

    if (sk_fwrite(buffer, size, fFILE) != size)
    {
        SkDEBUGCODE(SkDebugf("SkFILEWStream failed writing %d bytes\n", size);)
        sk_fclose(fFILE);
        fFILE = NULL;
        return false;
    }
    return true;
}

void SkFILEWStream::flush()
{
    if (fFILE)
        sk_fflush(fFILE);
}

////////////////////////////////////////////////////////////////////////

SkMemoryWStream::SkMemoryWStream(void* buffer, size_t size)
    : fBuffer((char*)buffer), fMaxLength(size), fBytesWritten(0)
{
}

bool SkMemoryWStream::write(const void* buffer, size_t size)
{
    size = SkMin32(size, fMaxLength - fBytesWritten);
    if (size > 0)
    {
        memcpy(fBuffer + fBytesWritten, buffer, size);
        fBytesWritten += size;
        return true;
    }
    return false;
}

////////////////////////////////////////////////////////////////////////

#define SkDynamicMemoryWStream_MinBlockSize   256

struct SkDynamicMemoryWStream::Block {
    Block*  fNext;
    char*   fCurr;
    char*   fStop;

    const char* start() const { return (const char*)(this + 1); }
    char*   start() { return (char*)(this + 1); }
    size_t  avail() const { return fStop - fCurr; }
    size_t  written() const { return fCurr - this->start(); }

    void init(size_t size)
    {
        fNext = NULL;
        fCurr = this->start();
        fStop = this->start() + size;
    }

    const void* append(const void* data, size_t size)
    {
        SkASSERT((size_t)(fStop - fCurr) >= size);
        memcpy(fCurr, data, size);
        fCurr += size;
        return (const void*)((const char*)data + size);
    }
};

SkDynamicMemoryWStream::SkDynamicMemoryWStream()
    : fHead(NULL), fTail(NULL), fBytesWritten(0), fCopy(NULL)
{
}

SkDynamicMemoryWStream::~SkDynamicMemoryWStream()
{
    reset();
}

void SkDynamicMemoryWStream::reset()
{
    this->invalidateCopy();

    Block*  block = fHead;

    while (block != NULL) {
        Block*  next = block->fNext;
        sk_free(block);
        block = next;
    }
    fHead = fTail = NULL;
    fBytesWritten = 0;
}

bool SkDynamicMemoryWStream::write(const void* buffer, size_t count)
{
    if (count > 0) {
        this->invalidateCopy();

        fBytesWritten += count;

        size_t  size;

        if (fTail != NULL && fTail->avail() > 0) {
            size = SkMin32(fTail->avail(), count);
            buffer = fTail->append(buffer, size);
            SkASSERT(count >= size);
            count -= size;
            if (count == 0)
                return true;
        }

        size = SkMax32(count, SkDynamicMemoryWStream_MinBlockSize);
        Block* block = (Block*)sk_malloc_throw(sizeof(Block) + size);
        block->init(size);
        block->append(buffer, count);

        if (fTail != NULL)
            fTail->fNext = block;
        else
            fHead = fTail = block;
        fTail = block;
    }
    return true;
}

bool SkDynamicMemoryWStream::write(const void* buffer, size_t offset, size_t count)
{
    if (offset + count > fBytesWritten) {
        return false; // test does not partially modify
    }

    this->invalidateCopy();

    Block* block = fHead;
    while (block != NULL) {
        size_t size = block->written();
        if (offset < size) {
            size_t part = offset + count > size ? size - offset : count;
            memcpy(block->start() + offset, buffer, part);
            if (count <= part)
                return true;
            count -= part;
            buffer = (const void*) ((char* ) buffer + part);
        }
        offset = offset > size ? offset - size : 0;
        block = block->fNext;
    }
    return false;
}

bool SkDynamicMemoryWStream::read(void* buffer, size_t offset, size_t count)
{
    if (offset + count > fBytesWritten)
        return false; // test does not partially modify
    Block* block = fHead;
    while (block != NULL) {
        size_t size = block->written();
        if (offset < size) {
            size_t part = offset + count > size ? size - offset : count;
            memcpy(buffer, block->start() + offset, part);
            if (count <= part)
                return true;
            count -= part;
            buffer = (void*) ((char* ) buffer + part);
        }
        offset = offset > size ? offset - size : 0;
        block = block->fNext;
    }
    return false;
}

void SkDynamicMemoryWStream::copyTo(void* dst) const
{
    if (fCopy) {
        memcpy(dst, fCopy->data(), fBytesWritten);
    } else {
        Block* block = fHead;

        while (block != NULL) {
            size_t size = block->written();
            memcpy(dst, block->start(), size);
            dst = (void*)((char*)dst + size);
            block = block->fNext;
        }
    }
}

void SkDynamicMemoryWStream::padToAlign4()
{
    // cast to remove unary-minus warning
    int padBytes = -(int)fBytesWritten & 0x03;
    if (padBytes == 0)
        return;
    int zero = 0;
    write(&zero, padBytes);
}

SkData* SkDynamicMemoryWStream::copyToData() const {
    if (NULL == fCopy) {
        void* buffer = sk_malloc_throw(fBytesWritten);
        this->copyTo(buffer);
        fCopy = SkData::NewFromMalloc(buffer, fBytesWritten);
    }
    fCopy->ref();
    return fCopy;
}

void SkDynamicMemoryWStream::invalidateCopy() {
    if (fCopy) {
        fCopy->unref();
        fCopy = NULL;
    }
}

///////////////////////////////////////////////////////////////////////////////

void SkDebugWStream::newline()
{
#ifdef SK_DEBUG
    SkDebugf("\n");
#endif
}

bool SkDebugWStream::write(const void* buffer, size_t size)
{
#ifdef SK_DEBUG
    char* s = new char[size+1];
    memcpy(s, buffer, size);
    s[size] = 0;
    SkDebugf("%s", s);
    delete[] s;
#endif
    return true;
}


text:
package org.auraframework.components.ui.inputText;

import org.auraframework.test.WebDriverTestCase;
import org.auraframework.test.WebDriverUtil.BrowserType;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

/**
 * UI Tests for inputSearch Component
 */
public class InputCutCopyPasteUITest extends WebDriverTestCase {

    public InputCutCopyPasteUITest(String name) {
        super(name);

    }

    @ExcludeBrowsers({ BrowserType.ANDROID_PHONE, BrowserType.ANDROID_TABLET, BrowserType.IPAD, BrowserType.IPHONE,
            BrowserType.SAFARI })
    public void testCutCopyPasteEvents() throws Exception {
        if (System.getProperty("os.name").startsWith("Mac")) {
            // Selenium's key event injection are simulated for OSX, and not actually received by
            // the real browser (see https://code.google.com/p/selenium/issues/detail?id=3101),
            // which means that there's no way to generate cut/copy/paste events under Selenium.
            // So, on Mac, skip this whole test. No, changing Keys.CONTROL to Keys.COMMAND below
            // doesn't do it, they aren't "real keypresses" to the browser at all.
            return;
        }

        WebDriver d = getDriver();
        open("/uitest/inputText_CutCopyPasteEventTest.cmp");
        WebElement input = d.findElement(By.xpath("//input"));
        WebElement output = d.findElement(By.xpath("//span[@class='uiOutputText']"));
        input.click();
        input.sendKeys(Keys.CONTROL, "a");

        // Fire Copy Event
        String copyValueExpression = auraUITestingUtil.getValueFromRootExpr("v.copyEventFired");
        copyValueExpression = auraUITestingUtil.prepareReturnStatement(copyValueExpression);
        assertFalse("Copy event should not have been triggered yet",
                auraUITestingUtil.getBooleanEval(copyValueExpression));
        input.sendKeys(Keys.CONTROL, "c");
        assertTrue("Copy event should have been triggered", auraUITestingUtil.getBooleanEval(copyValueExpression));
        waitForElementTextPresent(output, "Copy Event Fired");

        // Fire Cut Event
        String cutValueExpression = auraUITestingUtil.getValueFromRootExpr("v.cutEventFired");
        cutValueExpression = auraUITestingUtil.prepareReturnStatement(cutValueExpression);
        assertFalse("Cut event should not have been triggered yet",
                auraUITestingUtil.getBooleanEval(cutValueExpression));
        input.sendKeys(Keys.CONTROL, "a");
        input.sendKeys(Keys.CONTROL, "x");
        assertTrue("Cut event should have been triggered", auraUITestingUtil.getBooleanEval(cutValueExpression));
        waitForElementTextPresent(output, "Cut Event Fired");

        // Fire Paste Event
        String pasteValueExpression = auraUITestingUtil.getValueFromRootExpr("v.pasteEventFired");
        pasteValueExpression = auraUITestingUtil.prepareReturnStatement(pasteValueExpression);
        assertFalse("Paste event should not have been triggered yet",
                auraUITestingUtil.getBooleanEval(pasteValueExpression));
        input.click();
        input.sendKeys(Keys.CONTROL, "v");
        assertTrue("Paste event should have been triggered", auraUITestingUtil.getBooleanEval(pasteValueExpression));
        waitForElementTextPresent(output, "Paste Event Fired");
    }
}


text:
package lombok.javac;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.core.AnnotationValues;
import lombok.core.TypeLibrary;
import lombok.core.TypeResolver;
import lombok.core.AST.Kind;
import lombok.core.AnnotationValues.AnnotationValue;

import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;

/**
 * Container for static utility methods relevant to lombok's operation on javac.
 */
public class Javac {
	private Javac() {
		//prevent instantiation
	}

	/**
	 * Checks if the Annotation AST Node provided is likely to be an instance of the provided annotation type.
	 *
	 * @param type An actual annotation type, such as {@code lombok.Getter.class}.
	 * @param node A Lombok AST node representing an annotation in source code.
	 */
	public static boolean annotationTypeMatches(Class<? extends Annotation> type, JavacNode node) {
		if (node.getKind() != Kind.ANNOTATION) return false;
		String typeName = ((JCAnnotation)node.get()).annotationType.toString();

		TypeLibrary library = new TypeLibrary();
		library.addType(type.getName());
		TypeResolver resolver = new TypeResolver(library, node.getPackageDeclaration(), node.getImportStatements());
		Collection<String> typeMatches = resolver.findTypeMatches(node, typeName);

		for (String match : typeMatches) {
			if (match.equals(type.getName())) return true;
		}

		return false;
	}

	/**
	 * Creates an instance of {@code AnnotationValues} for the provided AST Node.
	 *
	 * @param type An annotation class type, such as {@code lombok.Getter.class}.
	 * @param node A Lombok AST node representing an annotation in source code.
	 */
	public static <A extends Annotation> AnnotationValues<A> createAnnotation(Class<A> type, final JavacNode node) {
		Map<String, AnnotationValue> values = new HashMap<String, AnnotationValue>();
		JCAnnotation anno = (JCAnnotation) node.get();
		List<JCExpression> arguments = anno.getArguments();
		for (Method m : type.getDeclaredMethods()) {
			if (!Modifier.isPublic(m.getModifiers())) continue;
			String name = m.getName();
			List<String> raws = new ArrayList<String>();
			List<Object> guesses = new ArrayList<Object>();
			List<Object> expressions = new ArrayList<Object>();
			final List<DiagnosticPosition> positions = new ArrayList<DiagnosticPosition>();
			boolean isExplicit = false;

			for (JCExpression arg : arguments) {
				String mName;
				JCExpression rhs;

				if (arg instanceof JCAssign) {
					JCAssign assign = (JCAssign) arg;
					mName = assign.lhs.toString();
					rhs = assign.rhs;
				} else {
					rhs = arg;
					mName = "value";
				}

				if (!mName.equals(name)) continue;
				isExplicit = true;
				if (rhs instanceof JCNewArray) {
					List<JCExpression> elems = ((JCNewArray)rhs).elems;
					for (JCExpression inner : elems) {
						raws.add(inner.toString());
						expressions.add(inner);
						guesses.add(calculateGuess(inner));
						positions.add(inner.pos());
					}
				} else {
					raws.add(rhs.toString());
					expressions.add(rhs);
					guesses.add(calculateGuess(rhs));
					positions.add(rhs.pos());
				}
			}

			values.put(name, new AnnotationValue(node, raws, expressions, guesses, isExplicit) {
				@Override public void setError(String message, int valueIdx) {
					if (valueIdx < 0) node.addError(message);
					else node.addError(message, positions.get(valueIdx));
				}
				@Override public void setWarning(String message, int valueIdx) {
					if (valueIdx < 0) node.addWarning(message);
					else node.addWarning(message, positions.get(valueIdx));
				}
			});
		}

		return new AnnotationValues<A>(type, values, node);
	}

	/**
	 * Turns an expression into a guessed intended literal. Only works for literals, as you can imagine.
	 *
	 * Will for example turn a TrueLiteral into 'Boolean.valueOf(true)'.
	 */
	private static Object calculateGuess(JCExpression expr) {
		if (expr instanceof JCLiteral) {
			JCLiteral lit = (JCLiteral)expr;
			if (lit.getKind() == com.sun.source.tree.Tree.Kind.BOOLEAN_LITERAL) {
				return ((Number)lit.value).intValue() == 0 ? false : true;
			}
			return lit.value;
		} else if (expr instanceof JCIdent || expr instanceof JCFieldAccess) {
			String x = expr.toString();
			if (x.endsWith(".class")) x = x.substring(0, x.length() - 6);
			else {
				int idx = x.lastIndexOf('.');
				if (idx > -1) x = x.substring(idx + 1);
			}
			return x;
		} else return null;
	}
}


text:
from django.apps import AppConfig

class EstoqueConfig(AppConfig):
    name = 'estoque'


text:
from .concat import concat
from pyramda.private.asserts import assert_iterables_equal

def concat_nocurry_test():
    assert_iterables_equal(concat([1, 2], [3, 4]), [1, 2, 3, 4])

def concat_curry_test():
    assert_iterables_equal(concat([1, 2])([3, 4]), [1, 2, 3, 4])


text:
using namespace v8;
using namespace Pylon;

class PylonDeviceWrap : public node::ObjectWrap
{
public:
    static NAN_MODULE_INIT(Initialize);
    static Nan::Persistent<v8::FunctionTemplate> prototype;

    IPylonDevice* GetWrapped() const
    {
        return m_PylonDevice;
    };

    void SetWrapped(IPylonDevice* pylonDevice)
    {
        m_PylonDevice = pylonDevice;
    };

    static v8::Handle<v8::Value> NewInstance(IPylonDevice* pylonDevice);

private:
    static Nan::Persistent<v8::Function> constructor;
    PylonDeviceWrap(Nan::NAN_METHOD_ARGS_TYPE info);
    ~PylonDeviceWrap();
    static NAN_METHOD(New);

    // Wrapped methods
    static NAN_METHOD(GetNumStreamGrabberChannels);
    static NAN_METHOD(GetStreamGrabber);
    static NAN_METHOD(GetEventGrabber);
    static NAN_METHOD(GetNodeMap);
    static NAN_METHOD(GetTLNodeMap);
    static NAN_METHOD(CreateChunkParser);
    static NAN_METHOD(DestroyChunkParser);
    static NAN_METHOD(CreateEventAdapter);
    static NAN_METHOD(DestroyEventAdapter);
    static NAN_METHOD(CreateSelfReliantChunkParser);
    static NAN_METHOD(DestroySelfReliantChunkParser);
    static NAN_METHOD(RegisterRemovalCallback);
    static NAN_METHOD(DeregisterRemovalCallback);

    // Wrapped object
    IPylonDevice* m_PylonDevice;
};


text:
import sys
from types import TracebackType

from . import Frame
from . import Traceback

if sys.version_info.major >= 3:
    import copyreg
else:
    import copy_reg as copyreg

def unpickle_traceback(tb_frame, tb_lineno, tb_next):
    ret = object.__new__(Traceback)
    ret.tb_frame = tb_frame
    ret.tb_lineno = tb_lineno
    ret.tb_next = tb_next
    return ret.as_traceback()

def pickle_traceback(tb):
    return unpickle_traceback, (Frame(tb.tb_frame), tb.tb_lineno, tb.tb_next and Traceback(tb.tb_next))

def unpickle_exception(func, args, cause, tb):
    inst = func(*args)
    inst.__cause__ = cause
    inst.__traceback__ = tb
    return inst

def pickle_exception(obj):
    # All exceptions, unlike generic Python objects, define __reduce_ex__
    # __reduce_ex__(4) should be no different from __reduce_ex__(3).
    # __reduce_ex__(5) could bring benefits in the unlikely case the exception
    # directly contains buffers, but PickleBuffer objects will cause a crash when
    # running on protocol=4, and there's no clean way to figure out the current
    # protocol from here. Note that any object returned by __reduce_ex__(3) will
    # still be pickled with protocol 5 if pickle.dump() is running with it.
    rv = obj.__reduce_ex__(3)
    if isinstance(rv, str):
        raise TypeError("str __reduce__ output is not supported")
    assert isinstance(rv, tuple) and len(rv) >= 2

    return (unpickle_exception, rv[:2] + (obj.__cause__, obj.__traceback__)) + rv[2:]

def _get_subclasses(cls):
    # Depth-first traversal of all direct and indirect subclasses of cls
    to_visit = [cls]
    while to_visit:
        this = to_visit.pop()
        yield this
        to_visit += list(this.__subclasses__())

def install(*exc_classes_or_instances):
    copyreg.pickle(TracebackType, pickle_traceback)

    if sys.version_info.major < 3:
        # Dummy decorator?
        if len(exc_classes_or_instances) == 1:
            exc = exc_classes_or_instances[0]
            if isinstance(exc, type) and issubclass(exc, BaseException):
                return exc
        return

    if not exc_classes_or_instances:
        for exception_cls in _get_subclasses(BaseException):
            copyreg.pickle(exception_cls, pickle_exception)
        return

    for exc in exc_classes_or_instances:
        if isinstance(exc, BaseException):
            while exc is not None:
                copyreg.pickle(type(exc), pickle_exception)
                exc = exc.__cause__
        elif isinstance(exc, type) and issubclass(exc, BaseException):
            copyreg.pickle(exc, pickle_exception)
            # Allow using @install as a decorator for Exception classes
            if len(exc_classes_or_instances) == 1:
                return exc
        else:
            raise TypeError(
                "Expected subclasses or instances of BaseException, got %s"
                % (type(exc))
            )


text:
Reports calls on a setter with the value of the same object's getter.
For example: bean.setPayerId(bean.getPayerId());
In regular circumstances this code is a no-op and probably not what was intended.


text:
/*
 * @test
 * @bug 7201053
 * @summary Krb5LoginModule shows NPE when both useTicketCache and storeKey
 *          are set to true
 * @compile -XDignore.symbol.file UseCacheAndStoreKey.java
 * @run main/othervm UseCacheAndStoreKey
 */

import java.io.FileOutputStream;
import javax.security.auth.login.LoginException;

// The basic krb5 test skeleton you can copy from
public class UseCacheAndStoreKey {

    public static void main(String[] args) throws Exception {

        new OneKDC(null).writeJAASConf();

        // KDC would save ccache for client
        System.setProperty("test.kdc.save.ccache", "cache.here");
        try (FileOutputStream fos = new FileOutputStream(OneKDC.JAAS_CONF)) {
            fos.write((
                "me {\n" +
                "    com.sun.security.auth.module.Krb5LoginModule required\n" +
                "    principal=\"" + OneKDC.USER + "\"\n" +
                "    useTicketCache=true\n" +
                "    ticketCache=cache.here\n" +
                "    isInitiator=true\n" +
                "    storeKey=true;\n};\n"
                ).getBytes());
        }

        // The first login will use default callback and succeed
        Context.fromJAAS("me");

        // The second login uses ccache and won't be able to store the keys
        try {
            Context.fromJAAS("me");
            throw new Exception("Should fail");
        } catch (LoginException le) {
            if (le.getMessage().indexOf("NullPointerException") >= 0
                    || le.getCause() instanceof NullPointerException) {
                throw new Exception("NPE");
            }
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    email_confirmed = models.BooleanField(default=False)
    employer = models.BooleanField(default = False)

    def get_fields(self):
        return [(field.name, field.value_to_string(self)) for field in Profile._meta.fields]

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

class ContactUs(models.Model):
    surname = models.TextField(max_length=30, blank=False)
    email = models.EmailField(max_length=254, blank=False)
    subject = models.TextField(max_length=1000, blank=False)
    email_body = models.TextField(max_length=2000, blank=False)
    phone_number = models.IntegerField(blank=True)
    current_occupation = models.TextField(max_length=500, blank=True)
    location = models.TextField(max_length=500, blank=True)

    def get_fields(self):
        return [(field.name, field.value_to_string(self)) for field in ContactUs._meta.fields]


text:
package org.xbmc.kore.ui;

import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import org.xbmc.kore.R;
import org.xbmc.kore.host.HostInfo;
import org.xbmc.kore.host.HostManager;
import org.xbmc.kore.jsonrpc.ApiException;
import org.xbmc.kore.jsonrpc.event.MediaSyncEvent;
import org.xbmc.kore.service.LibrarySyncService;
import org.xbmc.kore.service.SyncUtils;
import org.xbmc.kore.utils.LogUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.greenrobot.event.EventBus;

public abstract class AbstractListFragment extends Fragment
		implements LoaderManager.LoaderCallbacks<Cursor>,
		SyncUtils.OnServiceListener,
		SearchView.OnQueryTextListener,
		SwipeRefreshLayout.OnRefreshListener {
    private static final String TAG = LogUtils.makeLogTag(AbstractListFragment.class);

	private ServiceConnection serviceConnection;
	private CursorAdapter adapter;

	private HostInfo hostInfo;
	private EventBus bus;

	// Loader IDs
	private static final int LOADER = 0;

	// The search filter to use in the loader
	private String searchFilter = null;

	private boolean isSyncing;

	@InjectView(R.id.swipe_refresh_layout) SwipeRefreshLayout swipeRefreshLayout;
	@InjectView(R.id.list) GridView gridView;
	@InjectView(android.R.id.empty) TextView emptyView;

	abstract protected AdapterView.OnItemClickListener createOnItemClickListener();
	abstract protected CursorAdapter createAdapter();
	abstract protected CursorLoader createCursorLoader();

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_generic_media_list, container, false);
		ButterKnife.inject(this, root);

		bus = EventBus.getDefault();
		HostManager hostManager = HostManager.getInstance(getActivity());
		hostInfo = hostManager.getHostInfo();

		swipeRefreshLayout.setOnRefreshListener(this);

		return root;
	}

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

		gridView.setEmptyView(emptyView);
		gridView.setOnItemClickListener(createOnItemClickListener());

		// Configure the adapter and start the loader
		adapter = createAdapter();
		gridView.setAdapter(adapter);

		getLoaderManager().initLoader(LOADER, null, this);

		setHasOptionsMenu(true);
	}

	@Override
	public void onStart() {
		super.onStart();
		serviceConnection = SyncUtils.connectToLibrarySyncService(getActivity(), this);
	}

	@Override
	public void onResume() {
		bus.register(this);
		super.onResume();
	}

	@Override
	public void onPause() {
		bus.unregister(this);
		super.onPause();
	}

	@Override
	public void onStop() {
		super.onStop();
		SyncUtils.disconnectFromLibrarySyncService(getActivity(), serviceConnection);
	}

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case R.id.action_refresh:
				onRefresh();
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Swipe refresh layout callback
	 */
	/** {@inheritDoc} */
	@Override
	public void onRefresh() {
		if (hostInfo != null) {
			showRefreshAnimation();
			onSwipeRefresh();
		} else {
			swipeRefreshLayout.setRefreshing(false);
			Toast.makeText(getActivity(), R.string.no_xbmc_configured, Toast.LENGTH_SHORT)
					.show();
		}
	}

	/**
	 * Should return the {@link org.xbmc.kore.service.LibrarySyncService} SyncType that
	 * this list initiates
	 * @return {@link org.xbmc.kore.service.LibrarySyncService} SyncType
	 */
	abstract protected String getListSyncType();

	/**
	 * Event bus post. Called when the syncing process ended
	 *
	 * @param event Refreshes data
	 */
	public void onEventMainThread(MediaSyncEvent event) {
		onSyncProcessEnded(event);
	}

	/**
	 * Called each time a MediaSyncEvent is received.
	 * @param event
	 */
	protected void onSyncProcessEnded(MediaSyncEvent event) {
        boolean silentSync = false;
        if (event.syncExtras != null) {
            silentSync = event.syncExtras.getBoolean(LibrarySyncService.SILENT_SYNC, false);
        }

		if (event.syncType.equals(getListSyncType())) {
			swipeRefreshLayout.setRefreshing(false);
			if (event.status == MediaSyncEvent.STATUS_SUCCESS) {
				refreshList();
                if (!silentSync) {
                    Toast.makeText(getActivity(), R.string.sync_successful, Toast.LENGTH_SHORT)
                        .show();
                }
            } else if (!silentSync) {
				String msg = (event.errorCode == ApiException.API_ERROR) ?
					String.format(getString(R.string.error_while_syncing), event.errorMessage) :
					getString(R.string.unable_to_connect_to_xbmc);
				Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
			}
		}
	}

    @Override
    public void onServiceConnected(LibrarySyncService librarySyncService) {
        if(SyncUtils.isLibrarySyncing(
              librarySyncService,
              HostManager.getInstance(getActivity()).getHostInfo(),
              getListSyncType())) {
            showRefreshAnimation();
        }
    }

    protected void onSwipeRefresh() {
		LogUtils.LOGD(TAG, "Swipe, starting sync for: " + getListSyncType());
        // Start the syncing process
        Intent syncIntent = new Intent(this.getActivity(), LibrarySyncService.class);
        syncIntent.putExtra(getListSyncType(), true);
        getActivity().startService(syncIntent);
    }

    /**
     * Search view callbacks
     */
	/** {@inheritDoc} */
	@Override
	public boolean onQueryTextChange(String newText) {
		searchFilter = newText;
		getLoaderManager().restartLoader(LOADER, null, this);
		return true;
	}

	/** {@inheritDoc} */
	@Override
	public boolean onQueryTextSubmit(String newText) {
		// All is handled in onQueryTextChange
		return true;
	}

	/**
	 * Loader callbacks
	 */
	/** {@inheritDoc} */
	@Override
	public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
		return createCursorLoader();
	}

	/** {@inheritDoc} */
	@Override
	public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
		adapter.swapCursor(cursor);
		// To prevent the empty text from appearing on the first load, set it now
		emptyView.setText(getString(R.string.swipe_down_to_refresh));
	}

	/** {@inheritDoc} */
	@Override
	public void onLoaderReset(Loader<Cursor> cursorLoader) {
		adapter.swapCursor(null);
	}

	/**
	 * @return text entered in searchview
	 */
	public String getSearchFilter() {
		return searchFilter;
	}

	/**
	 * Use this to reload the items in the list
	 */
	public void refreshList() {
		getLoaderManager().restartLoader(LOADER, null, this);
	}

	public void showRefreshAnimation() {
		/**
		 * Fixes issue with refresh animation not showing when using appcompat library (from version 20?)
		 * See https://code.google.com/p/android/issues/detail?id=77712
		 */
		swipeRefreshLayout.post(new Runnable() {
			@Override
			public void run() {
				swipeRefreshLayout.setRefreshing(true);
			}
		});
	}
}


text:
var expectedLastErrorMessage =
    ('Extension has not been invoked for the current page (see activeTab ' +
     'permission). Chrome pages cannot be captured.');

var afterWhitelistExtension = function(msg) {
  chrome.tabCapture.capture({audio: true, video: true}, function(stream) {
    chrome.test.assertNoLastError();
    chrome.test.assertTrue(!!stream);
    stream.getVideoTracks()[0].stop();
    stream.getAudioTracks()[0].stop();
    chrome.test.succeed();
  });
};

var afterOpenNewTab = function(msg) {
  chrome.tabCapture.capture({audio: true, video: true}, function(stream) {
    chrome.test.assertLastError(expectedLastErrorMessage);
    chrome.test.assertTrue(!stream);
    chrome.test.sendMessage('ready4', afterWhitelistExtension);
  });
};

var afterGrantPermission = function(msg) {
  chrome.tabCapture.capture({audio: true, video: true}, function(stream) {
    chrome.test.assertNoLastError();
    chrome.test.assertTrue(!!stream);
    stream.getVideoTracks()[0].stop();
    stream.getAudioTracks()[0].stop();
    chrome.test.sendMessage('ready3', afterOpenNewTab);
  });
};

var afterOpenTab = function(msg) {
  chrome.tabCapture.capture({audio: true, video: true}, function(stream) {
    chrome.test.assertLastError(expectedLastErrorMessage);
    chrome.test.assertTrue(!stream);

    chrome.test.sendMessage('ready2', afterGrantPermission);
  });
};

chrome.test.notifyPass();
chrome.test.sendMessage('ready1', afterOpenTab);


text:
module OnTheFlyCalc
  # Compute total score for this assignment by summing the scores given on all questionnaires.
  # Only scores passed in are included in this sum.
  def compute_total_score(scores)
    total = 0
    self.questionnaires.each {|questionnaire| total += questionnaire.get_weighted_score(self, scores) }
    total
  end

  def compute_reviews_hash
    @review_scores = {}
    @response_type = 'ReviewResponseMap'
    if self.varying_rubrics_by_round?
      @response_maps = ResponseMap.where('reviewed_object_id = ? && type = ?', self.id, @response_type)
      scores_varying_rubrics
    else
      @response_maps = ResponseMap.where('reviewed_object_id = ? && type = ?', self.id, @response_type)
      scores_non_varying_rubrics
    end
    @review_scores
  end

  # calculate the avg score and score range for each reviewee(team), only for peer-review
  def compute_avg_and_ranges_hash
    scores = {}
    contributors = self.contributors # assignment_teams
    if self.varying_rubrics_by_round?
      rounds = self.rounds_of_reviews
      (1..rounds).each do |round|
        review_questionnaire_id = review_questionnaire_id(round)
        questions = Question.where('questionnaire_id = ?', review_questionnaire_id)
        contributors.each do |contributor|
          assessments = ReviewResponseMap.get_assessments_for(contributor)
          assessments = assessments.reject {|assessment| assessment.round != round }
          scores[contributor.id] = {} if round == 1
          scores[contributor.id][round] = {}
          scores[contributor.id][round] = Answer.compute_scores(assessments, questions)
        end
      end
    else
      review_questionnaire_id = review_questionnaire_id()
      questions = Question.where('questionnaire_id = ?', review_questionnaire_id)
      contributors.each do |contributor|
        assessments = ReviewResponseMap.get_assessments_for(contributor)
        scores[contributor.id] = {}
        scores[contributor.id] = Answer.compute_scores(assessments, questions)
      end
    end
    scores
  end

  def scores(questions)
    score_assignment
    self.teams.each do |team|
      score_team = {}
      score_team[:team] = team
      if self.varying_rubrics_by_round?
        calculate_rounds
        calculate_score
        calculate_assessment
      else
        assessments = ReviewResponseMap.get_assessments_for(team)
        score_team[:scores] = Answer.compute_scores(assessments, questions[:review])
      end
      index += 1
    end
    scores
  end
end

private

def score_assignment
  scores = {}
  score_team = scores[:teams][index.to_s.to_sym]
  scores[:participants] = {}
  participant_score
  scores[:teams] = {}
  index = 0
end

def calculate_rounds
  self.num_review_rounds.each do |i|
    total_score = 0
    total_num_of_assessments = 0 # calculate grades for each rounds
    grades_by_rounds = {}
    assessments = ReviewResponseMap.get_responses_for_team_round(team, i)
    round_sym = ("review" + i.to_s).to_sym
    grades_by_rounds[round_sym] = Answer.compute_scores(assessments, questions[round_sym])
    total_num_of_assessments += assessments.size
    total_score += grades_by_rounds[round_sym][:avg] * assessments.size.to_f unless grades_by_rounds[round_sym][:avg].nil?
  end
end

def calculate_score
  score = {}
  score[:max] = -999_999_999
  score[:min] = 999_999_999
  score[:avg] = 0
  grades_by_rounds = {}
  self.num_review_rounds.each do |i|
    round_sym = ("review" + i.to_s).to_sym
    grades_by_rounds = {}
    score[:max] = grades_by_rounds[round_sym][:max] if max_condition
    score[:min] = grades_by_rounds[round_sym][:min] if min_condition
  end
end

def max_condition
  !round[:max].nil? && score[:max] < round[:max]
end

def min_condition
  !round[:min].nil? && score[:min] > round[:min]
end

def participant_score
  self.participants.each do |participant|
    scores[:participants][participant.id.to_s.to_sym] = participant.scores(questions)
  end
end

def calculate_assessment
  if total_num_of_assessments.nonzero?
    score[:avg] = total_score / total_num_of_assessments
  else
    score[:avg] = nil
    score[:max] = 0
    score[:min] = 0
  end
end

def calc_review_score
  if !@corresponding_response.empty?
    @this_review_score_raw = Answer.get_total_score(response: @corresponding_response, questions: @questions)
    if @this_review_score_raw
      @this_review_score = ((@this_review_score_raw * 100) / 100.0).round if @this_review_score_raw >= 0.0
    end
  else
    @this_review_score = -1.0
  end
end

def scores_varying_rubrics
  rounds = self.rounds_of_reviews
  (1..rounds).each do |round|
    review_questionnaire_id = review_questionnaire_id(round)
    @questions = Question.where('questionnaire_id = ?', review_questionnaire_id)
    @response_maps.each do |response_map|
      reviewer = @review_scores[response_map.reviewer_id]
      @corresponding_response = Response.where('map_id = ?', response_map.id)
      @corresponding_response = @corresponding_response.reject {|response| response.round != round } unless @corresponding_response.empty?
      @respective_scores = {}
      @respective_scores = reviewer[round] if !reviewer.nil? && !reviewer[round].nil?
      calc_review_score
      @respective_scores[response_map.reviewee_id] = @this_review_score
      reviewer = {} if reviewer.nil?
      reviewer[round] = {} if reviewer[round].nil?
      reviewer[round] = @respective_scores
    end
  end
end

def scores_non_varying_rubrics
  review_questionnaire_id = review_questionnaire_id()
  @questions = Question.where('questionnaire_id = ?', review_questionnaire_id)
  @response_maps.each do |response_map|
    reviewer = @review_scores[response_map.reviewer_id]
    @corresponding_response = Response.where('map_id = ?', response_map.id)
    @respective_scores = {}
    @respective_scores = reviewer unless reviewer.nil?
    calc_review_score
    @respective_scores[response_map.reviewee_id] = @this_review_score
    @review_scores[response_map.reviewer_id] = @respective_scores
  end
end


text:
    <title>Test jQuery.gooAutoComplete.js</title>
    <link rel="stylesheet" type="text/css" href="jQuery.gooAutoComplete.TestAzureSearchProxy.css" />

Test Azure Search Proxy

            <input goo-azure-ac type="text" id="testAzureSearchProxy" placeholder="Azure Search Service..."
                   ac-listtemplate="search_results_template"
                   ac-selectedtemplate="selectedTemplate"
                   ac-listitemtemplate="listItemTemplate"
                   ac-altlistitemtemplate="altListItemTemplate"
                   ac-filter="azureAc_filter"
                   ac-afterrender="azureAc_afterRender"
                   ac-apikey="C268C94FA246D88615046408593F3118"
                   ac-host="mtw.search.windows.net"
                   ac-index="publicsite"
                   ac-count="true"
                   ac-top="5"
                   ac-highlight="title,search_markdown,meta_description,slug,author"
                   ac-select="title,slug,my_tags"
                   ac-searchresultstitle=" Search results for {keywords}"
                   ac-facetstitle="Refine Results By:"
                   ac-facet="my_tags,sort:count;publish_date,interval:month"
                   ac-showbutton="false"
                   ac-position="free" />

Download CSS.