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

<TITLE>
Invoke (JScheme API)
</TITLE>

<META NAME="date" CONTENT="2013-07-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

jsint

Class Invoke

java.lang.Object
  jsint.Invoke

public class Invoke
extends java.lang.Object

Provides dynamic Java method invocation through Java's Reflection
    interface.  For a good discussion of a Scheme implementation, and
    the issues involved with dynamic method invocation in Java see:

 Michael Travers, Java Q & A, Dr. Dobb's Journal, Jan., 2000,
   p. 103-112.

Primitive types are not widened because it would make method
   selection more ambiguous.  By memoizing constructorTable() and
   methodTable() dynamic method lookup can be done without consing.

You'll notice that Java doesn't make this very easy.  For
   example it would be nice if Method and Constructor shared an
   Invokable interface.

Privileged methods can be invoked if the JVM allows it.

The name of a method to be invoked can be any nonnull Object
   with a .toString() that names a method.  It should probably be
   changed to String.

Field Summary

static int
BUCKET_SIZE

          Each bucket in an method table contains a Class[] of
      parameterTypes and the corresponding method or constructor.

static java.util.Hashtable
constructorCache

static java.util.Hashtable
constructorCachePriv

static java.util.Hashtable
instanceCache

          Instance method name -> Class -> parameter[]/method array.

static java.util.Hashtable
staticCache

          Static method name -> Class -> parameter[]/method array.

Constructor Summary

Invoke()

Method Summary

static java.lang.Object[]
constructorTable(java.lang.String c,
                 boolean isPrivileged)

          Return the constructor table for the named class.

static java.lang.Object[]
constructorTable0(java.lang.String c)

static java.lang.Object[]
constructorTable0Priv(java.lang.String c)

static java.lang.reflect.Constructor
findConstructor(java.lang.Object target,
                Pair types)

          Look up a particular constructor given its name, and the name of its
      declaring class, and a list of argument type names.

static java.lang.Object
findMethod(java.lang.Object[] methods,
           java.lang.Object[] args)

          Find the most applicable method.

static java.lang.reflect.Method
findMethod(java.lang.String name,
           java.lang.Object target,
           Pair types)

          Look up a particular method given its name, and the name of its
      declaring class, and a list of argument type names.

static java.lang.Object[]
getCachedMethodTable(java.lang.Class c,
                     java.lang.String name,
                     boolean isStatic)

static java.util.Hashtable
getClassTable(java.lang.String name,
              boolean isStatic)

          Returns a Class -> prameter[]/method array for the method named
 name.

static java.lang.reflect.Method[]
getMethods(java.lang.Class c,
           boolean isPrivileged)

          Return all the methods for this class.

static java.lang.Object
invokeConstructor(java.lang.String c,
                  java.lang.Object[] args)

static java.lang.Object
invokeInstance(java.lang.Object target,
               java.lang.String name,
               java.lang.Object[] args,
               boolean isPrivileged)

static java.lang.Object
invokeMethod(java.lang.Class c,
             java.lang.Object target,
             java.lang.String name,
             java.lang.Object[] args,
             boolean isStatic,
             boolean isPrivileged)

static java.lang.Object
invokeRawConstructor(java.lang.reflect.Constructor m,
                     java.lang.Object[] args)

static java.lang.Object
invokeRawMethod(java.lang.reflect.Method m,
                java.lang.Object target,
                java.lang.Object[] args)

static java.lang.Object
invokeStatic(java.lang.Class c,
             java.lang.String name,
             java.lang.Object[] args)

static boolean
isApplicable(java.lang.Class[] types,
             java.lang.Object[] args)

static java.lang.Object[]
methodTable(java.lang.Class c,
            java.lang.String name,
            boolean isStatic,
            boolean isPrivileged)

static java.lang.Object[]
methodTable0(java.lang.Class c,
             java.lang.String name,
             boolean isStatic,
             boolean isPrivileged)

static java.lang.Object[]
methodTableLookup(java.lang.Class c,
                  java.lang.String name,
                  boolean isStatic,
                  boolean isPrivileged)

static java.lang.Object[]
methodTableLookupInstance(java.lang.Class c,
                          java.lang.String name)

static java.lang.Object[]
methodTableLookupInstance(java.lang.Class c,
                          java.lang.String name,
                          boolean isPrivileged)

static java.lang.Object[]
methodTableLookupStatic(java.lang.Class c,
                        java.lang.String name,
                        boolean isPrivileged)

static java.util.Vector
methodVector(java.lang.Class c,
             java.lang.String name)

static java.util.Vector
methodVector(java.lang.Class c,
             java.lang.String name,
             boolean isPrivileged)

static java.util.Vector
methodVectorMerge(java.lang.Class c,
                  java.lang.String name,
                  java.util.Vector result)

          Add new methods to your superclasses table.

static java.util.Vector
methodVectorMerge(java.lang.Class c,
                  java.lang.String name,
                  java.util.Vector result,
                  boolean isPrivileged)

static boolean
parameterTypesMatch(java.lang.Class[] p1,
                    java.lang.Class[] p2)

          Do the paramter types of an instance method match?

static java.lang.Object
peek(java.lang.Object target,
     java.lang.String name)

static java.lang.Object
peekStatic(java.lang.Class c,
           java.lang.String name)

static java.lang.Object
poke(java.lang.Object target,
     java.lang.String name,
     java.lang.Object value)

static java.lang.Object
pokeStatic(java.lang.Class c,
           java.lang.String name,
           java.lang.Object value)

static void
putCachedMethodTable(java.lang.Class c,
                     java.lang.String name,
                     boolean isStatic,
                     java.lang.Object value)

static java.lang.Class[]
toClassArray(Pair types,
             int n)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

BUCKET_SIZE

public static final int BUCKET_SIZE

Each bucket in an method table contains a Class[] of
      parameterTypes and the corresponding method or constructor.

See Also:
Constant Field Values

constructorCache

public static final java.util.Hashtable constructorCache

constructorCachePriv

public static final java.util.Hashtable constructorCachePriv

staticCache

public static final java.util.Hashtable staticCache

Static method name -> Class -> parameter[]/method array.

instanceCache

public static final java.util.Hashtable instanceCache

Instance method name -> Class -> parameter[]/method array.

Constructor Detail

Invoke

public Invoke()

Method Detail

peek

public static java.lang.Object peek(java.lang.Object target,
                                    java.lang.String name)

peekStatic

public static java.lang.Object peekStatic(java.lang.Class c,
                                          java.lang.String name)

poke

public static java.lang.Object poke(java.lang.Object target,
                                    java.lang.String name,
                                    java.lang.Object value)

pokeStatic

public static java.lang.Object pokeStatic(java.lang.Class c,
                                          java.lang.String name,
                                          java.lang.Object value)

invokeConstructor

public static java.lang.Object invokeConstructor(java.lang.String c,
                                                 java.lang.Object[] args)

invokeRawConstructor

public static java.lang.Object invokeRawConstructor(java.lang.reflect.Constructor m,
                                                    java.lang.Object[] args)

invokeStatic

public static java.lang.Object invokeStatic(java.lang.Class c,
                                            java.lang.String name,
                                            java.lang.Object[] args)

invokeInstance

public static java.lang.Object invokeInstance(java.lang.Object target,
                                              java.lang.String name,
                                              java.lang.Object[] args,
                                              boolean isPrivileged)

invokeMethod

public static java.lang.Object invokeMethod(java.lang.Class c,
                                            java.lang.Object target,
                                            java.lang.String name,
                                            java.lang.Object[] args,
                                            boolean isStatic,
                                            boolean isPrivileged)

invokeRawMethod

public static java.lang.Object invokeRawMethod(java.lang.reflect.Method m,
                                               java.lang.Object target,
                                               java.lang.Object[] args)

constructorTable

public static java.lang.Object[] constructorTable(java.lang.String c,
                                                  boolean isPrivileged)

Return the constructor table for the named class.

constructorTable0Priv

public static java.lang.Object[] constructorTable0Priv(java.lang.String c)

constructorTable0

public static java.lang.Object[] constructorTable0(java.lang.String c)

getClassTable

public static java.util.Hashtable getClassTable(java.lang.String name,
                                                boolean isStatic)

Returns a Class -> prameter[]/method array for the method named
 name.

getCachedMethodTable

public static java.lang.Object[] getCachedMethodTable(java.lang.Class c,
                                                      java.lang.String name,
                                                      boolean isStatic)

putCachedMethodTable

public static void putCachedMethodTable(java.lang.Class c,
                                        java.lang.String name,
                                        boolean isStatic,
                                        java.lang.Object value)

methodTable0

public static java.lang.Object[] methodTable0(java.lang.Class c,
                                              java.lang.String name,
                                              boolean isStatic,
                                              boolean isPrivileged)

methodTable

public static java.lang.Object[] methodTable(java.lang.Class c,
                                             java.lang.String name,
                                             boolean isStatic,
                                             boolean isPrivileged)

methodTableLookup

public static java.lang.Object[] methodTableLookup(java.lang.Class c,
                                                   java.lang.String name,
                                                   boolean isStatic,
                                                   boolean isPrivileged)

methodTableLookupStatic

public static java.lang.Object[] methodTableLookupStatic(java.lang.Class c,
                                                         java.lang.String name,
                                                         boolean isPrivileged)

methodTableLookupInstance

public static java.lang.Object[] methodTableLookupInstance(java.lang.Class c,
                                                           java.lang.String name)

methodTableLookupInstance

public static java.lang.Object[] methodTableLookupInstance(java.lang.Class c,
                                                           java.lang.String name,
                                                           boolean isPrivileged)

methodVector

public static java.util.Vector methodVector(java.lang.Class c,
                                            java.lang.String name)

methodVector

public static java.util.Vector methodVector(java.lang.Class c,
                                            java.lang.String name,
                                            boolean isPrivileged)

methodVectorMerge

public static java.util.Vector methodVectorMerge(java.lang.Class c,
                                                 java.lang.String name,
                                                 java.util.Vector result)

Add new methods to your superclasses table.

methodVectorMerge

public static java.util.Vector methodVectorMerge(java.lang.Class c,
                                                 java.lang.String name,
                                                 java.util.Vector result,
                                                 boolean isPrivileged)

parameterTypesMatch

public static boolean parameterTypesMatch(java.lang.Class[] p1,
                                          java.lang.Class[] p2)

Do the paramter types of an instance method match?

findMethod

public static java.lang.Object findMethod(java.lang.Object[] methods,
                                          java.lang.Object[] args)

Find the most applicable method.  For instance methods
      getMethods() has already handled the "this" argument, so
      instance and static methods are matched the same way.

isApplicable

public static boolean isApplicable(java.lang.Class[] types,
                                   java.lang.Object[] args)

findMethod

public static java.lang.reflect.Method findMethod(java.lang.String name,
                                                  java.lang.Object target,
                                                  Pair types)

Look up a particular method given its name, and the name of its
      declaring class, and a list of argument type names.

This is only used by (method).

findConstructor

public static java.lang.reflect.Constructor findConstructor(java.lang.Object target,
                                                            Pair types)

Look up a particular constructor given its name, and the name of its
      declaring class, and a list of argument type names.

This is only used by (constructor).

toClassArray

public static java.lang.Class[] toClassArray(Pair types,
                                             int n)

getMethods

public static java.lang.reflect.Method[] getMethods(java.lang.Class c,
                                                    boolean isPrivileged)

Return all the methods for this class.  If you can't get all, for
 some reason,, just return the public ones.

Memoizable.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package atomic

import (
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestBool(t *testing.T) {
	atom := NewBool(false)
	require.False(t, atom.Toggle(), "Expected Toggle to return previous value.")
	require.True(t, atom.Toggle(), "Expected Toggle to return previous value.")
	require.False(t, atom.Toggle(), "Expected Toggle to return previous value.")
	require.True(t, atom.Load(), "Unexpected state after swap.")

	require.True(t, atom.CAS(true, true), "CAS should swap when old matches")
	require.True(t, atom.Load(), "CAS should have no effect")
	require.True(t, atom.CAS(true, false), "CAS should swap when old matches")
	require.False(t, atom.Load(), "CAS should have modified the value")
	require.False(t, atom.CAS(true, false), "CAS should fail on old mismatch")
	require.False(t, atom.Load(), "CAS should not have modified the value")

	atom.Store(false)
	require.False(t, atom.Load(), "Unexpected state after store.")

	prev := atom.Swap(false)
	require.False(t, prev, "Expected Swap to return previous value.")

	prev = atom.Swap(true)
	require.False(t, prev, "Expected Swap to return previous value.")

	t.Run("JSON/Marshal", func(t *testing.T) {
		atom.Store(true)
		bytes, err := json.Marshal(atom)
		require.NoError(t, err, "json.Marshal errored unexpectedly.")
		require.Equal(t, []byte("true"), bytes, "json.Marshal encoded the wrong bytes.")
	})

	t.Run("JSON/Unmarshal", func(t *testing.T) {
		err := json.Unmarshal([]byte("false"), &atom)
		require.NoError(t, err, "json.Unmarshal errored unexpectedly.")
		require.False(t, atom.Load(), "json.Unmarshal didn't set the correct value.")
	})

	t.Run("JSON/Unmarshal/Error", func(t *testing.T) {
		err := json.Unmarshal([]byte("42"), &atom)
		require.Error(t, err, "json.Unmarshal didn't error as expected.")
		assertErrorJSONUnmarshalType(t, err,
			"json.Unmarshal failed with unexpected error %v, want UnmarshalTypeError.", err)
	})

	t.Run("String", func(t *testing.T) {
		t.Run("true", func(t *testing.T) {
			assert.Equal(t, "true", NewBool(true).String(),
				"String() returned an unexpected value.")
		})

		t.Run("false", func(t *testing.T) {
			var b Bool
			assert.Equal(t, "false", b.String(),
				"String() returned an unexpected value.")
		})
	})
}

redpajama_set_name: RedPajamaGithub


text:
===================
Aggregate Functions
===================

Aggregate functions operate on a set of values to compute a single result.

Except for :func:`count`, :func:`count_if`, :func:`max_by`, :func:`min_by` and
:func:`approx_distinct`, all of these aggregate functions ignore null values
and return null for no input rows or when all values are null. For example,
:func:`sum` returns null rather than zero and :func:`avg` does not include null
values in the count. The ``coalesce`` function can be used to convert null into
zero.

Ordering During Aggregation
----------------------------

Some aggregate functions such as :func:`array_agg` produce different results
depending on the order of input values. This ordering can be specified by writing
an :ref:`order-by-clause` within the aggregate function::

    array_agg(x ORDER BY y DESC)
    array_agg(x ORDER BY x, y, z)

Filtering During Aggregation
----------------------------

The ``FILTER`` keyword can be used to remove rows from aggregation processing
with a condition expressed using a ``WHERE`` clause. This is evaluated for each
row before it is used in the aggregation and is supported for all aggregate
functions.

.. code-block:: none

    aggregate_function(...) FILTER (WHERE <condition>)

A common and very useful example is to use ``FILTER`` to remove nulls from
consideration when using ``array_agg``::

    SELECT array_agg(name) FILTER (WHERE name IS NOT NULL)
    FROM region;

As another example, imagine you want to add a condition on the count for Iris
flowers, modifying the following query::

    SELECT species,
           count(*) AS count
    FROM iris
    GROUP BY species;

.. code-block:: none

    species    | count
    -----------+-------
    setosa     |   50
    virginica  |   50
    versicolor |   50

If you just use a normal ``WHERE`` statement you loose information::

    SELECT species,
        count(*) AS count
    FROM iris
    WHERE petal_length_cm > 4
    GROUP BY species;

.. code-block:: none

    species    | count
    -----------+-------
    virginica  |   50
    versicolor |   34

Using a filter you retain all information::

    SELECT species,
           count(*) FILTER (where petal_length_cm > 4) AS count
    FROM iris
    GROUP BY species;

.. code-block:: none

    species    | count
    -----------+-------
    virginica  |   50
    setosa     |    0
    versicolor |   34

General Aggregate Functions
---------------------------

.. function:: arbitrary(x) -> [same as input]

    Returns an arbitrary non-null value of ``x``, if one exists.

.. function:: array_agg(x) -> array<[same as input]>

    Returns an array created from the input ``x`` elements.

.. function:: avg(x) -> double

    Returns the average (arithmetic mean) of all input values.

.. function:: avg(time interval type) -> time interval type
    :noindex:

    Returns the average interval length of all input values.

.. function:: bool_and(boolean) -> boolean

    Returns ``TRUE`` if every input value is ``TRUE``, otherwise ``FALSE``.

.. function:: bool_or(boolean) -> boolean

    Returns ``TRUE`` if any input value is ``TRUE``, otherwise ``FALSE``.

.. function:: checksum(x) -> varbinary

    Returns an order-insensitive checksum of the given values.

.. function:: count(*) -> bigint

    Returns the number of input rows.

.. function:: count(x) -> bigint
    :noindex:

    Returns the number of non-null input values.

.. function:: count_if(x) -> bigint

    Returns the number of ``TRUE`` input values.
    This function is equivalent to ``count(CASE WHEN x THEN 1 END)``.

.. function:: every(boolean) -> boolean

    This is an alias for :func:`bool_and`.

.. function:: geometric_mean(x) -> double

    Returns the geometric mean of all input values.

.. function:: max(x) -> [same as input]

    Returns the maximum value of all input values.

.. function:: max(x, n) -> array<[same as x]>
    :noindex:

    Returns ``n`` largest values of all input values of ``x``.

.. function:: max_by(x, y) -> [same as x]

    Returns the value of ``x`` associated with the maximum value of ``y`` over all input values.

.. function:: max_by(x, y, n) -> array<[same as x]>
    :noindex:

    Returns ``n`` values of ``x`` associated with the ``n`` largest of all input values of ``y``
    in descending order of ``y``.

.. function:: min(x) -> [same as input]

    Returns the minimum value of all input values.

.. function:: min(x, n) -> array<[same as x]>
    :noindex:

    Returns ``n`` smallest values of all input values of ``x``.

.. function:: min_by(x, y) -> [same as x]

    Returns the value of ``x`` associated with the minimum value of ``y`` over all input values.

.. function:: min_by(x, y, n) -> array<[same as x]>
    :noindex:

    Returns ``n`` values of ``x`` associated with the ``n`` smallest of all input values of ``y``
    in ascending order of ``y``.

.. function:: sum(x) -> [same as input]

    Returns the sum of all input values.

Bitwise Aggregate Functions
---------------------------

.. function:: bitwise_and_agg(x) -> bigint

    Returns the bitwise AND of all input values in 2's complement representation.

.. function:: bitwise_or_agg(x) -> bigint

    Returns the bitwise OR of all input values in 2's complement representation.

Map Aggregate Functions
-----------------------

.. function:: histogram(x) -> map(K,bigint)

    Returns a map containing the count of the number of times each input value occurs.

.. function:: map_agg(key, value) -> map(K,V)

    Returns a map created from the input ``key`` / ``value`` pairs.

.. function:: map_union(x(K,V)) -> map(K,V)

   Returns the union of all the input maps. If a key is found in multiple
   input maps, that key's value in the resulting map comes from an arbitrary input map.

.. function:: multimap_agg(key, value) -> map(K,array(V))

    Returns a multimap created from the input ``key`` / ``value`` pairs.
    Each key can be associated with multiple values.

Approximate Aggregate Functions
-------------------------------

.. function:: approx_distinct(x) -> bigint

    Returns the approximate number of distinct input values.
    This function provides an approximation of ``count(DISTINCT x)``.
    Zero is returned if all input values are null.

    This function should produce a standard error of 2.3%, which is the
    standard deviation of the (approximately normal) error distribution over
    all possible sets. It does not guarantee an upper bound on the error for
    any specific input set.

.. function:: approx_distinct(x, e) -> bigint
    :noindex:

    Returns the approximate number of distinct input values.
    This function provides an approximation of ``count(DISTINCT x)``.
    Zero is returned if all input values are null.

    This function should produce a standard error of no more than ``e``, which
    is the standard deviation of the (approximately normal) error distribution
    over all possible sets. It does not guarantee an upper bound on the error
    for any specific input set. The current implementation of this function
    requires that ``e`` be in the range of ``[0.0040625, 0.26000]``.

.. function:: approx_most_frequent(buckets, value, capacity) -> map<[same as value], bigint>

    Computes the top frequent values up to ``buckets`` elements approximately.
    Approximate estimation of the function enables us to pick up the frequent
    values with less memory. Larger ``capacity`` improves the accuracy of
    underlying algorithm with sacrificing the memory capacity. The returned
    value is a map containing the top elements with corresponding estimated
    frequency.

    The error of the function depends on the permutation of the values and its
    cardinality. We can set the capacity same as the cardinality of the
    underlying data to achieve the least error.

    ``buckets`` and ``capacity`` must be ``bigint``. ``value`` can be numeric
    or string type.

    The function uses the stream summary data structure proposed in the paper
    `Efficient Computation of Frequent and Top-k Elements in Data Streams
    <https://www.cse.ust.hk/~raywong/comp5331/References/EfficientComputationOfFrequentAndTop-kElementsInDataStreams.pdf>`_
    by A. Metwalley, D. Agrawl and A. Abbadi.

.. function:: approx_percentile(x, percentage) -> [same as x]

    Returns the approximate percentile for all input values of ``x`` at the
    given ``percentage``. The value of ``percentage`` must be between zero and
    one and must be constant for all input rows.

.. function:: approx_percentile(x, percentages) -> array<[same as x]>
    :noindex:

    Returns the approximate percentile for all input values of ``x`` at each of
    the specified percentages. Each element of the ``percentages`` array must be
    between zero and one, and the array must be constant for all input rows.

.. function:: approx_percentile(x, w, percentage) -> [same as x]
    :noindex:

    Returns the approximate weighed percentile for all input values of ``x``
    using the per-item weight ``w`` at the percentage ``p``. Weights must be
    strictly positive. Integer-value weights can be thought of as a replication
    count for the value ``x`` in the percentile set. The value of ``p`` must be
    between zero and one and must be constant for all input rows.

.. function:: approx_percentile(x, w, percentage, accuracy) -> [same as x]
    :noindex:

    Returns the approximate weighed percentile for all input values of ``x``
    using the per-item weight ``w`` at the percentage ``p``, with a maximum rank
    error of ``accuracy``. Weights must be strictly positive. Integer-value
    weights can be thought of as a replication count for the value ``x`` in the
    percentile set. The value of ``p`` must be between zero and one and must be
    constant for all input rows. ``accuracy`` must be a value greater than zero
    and less than one, and it must be constant for all input rows.

.. function:: approx_percentile(x, w, percentages) -> array<[same as x]>
    :noindex:

    Returns the approximate weighed percentile for all input values of ``x``
    using the per-item weight ``w`` at each of the given percentages specified
    in the array. Weights must be strictly positive. Integer-value weights can
    be thought of as a replication count for the value ``x`` in the percentile
    set. Each element of the array must be between zero and one, and the array
    must be constant for all input rows.

.. function:: approx_set(x) -> HyperLogLog
    :noindex:

    See :doc:`hyperloglog`.

.. function:: merge(x) -> HyperLogLog
    :noindex:

    See :doc:`hyperloglog`.

.. function:: merge(qdigest(T)) -> qdigest(T)
    :noindex:

    See :doc:`qdigest`.

.. function:: numeric_histogram(buckets, value) -> map<double, double>
    :noindex:

    Computes an approximate histogram with up to ``buckets`` number of buckets
    for all ``value``\ s. This function is equivalent to the variant of
    :func:`numeric_histogram` that takes a ``weight``, with a per-item weight of ``1``.

.. function:: numeric_histogram(buckets, value, weight) -> map<double, double>

    Computes an approximate histogram with up to ``buckets`` number of buckets
    for all ``value``\ s with a per-item weight of ``weight``. The algorithm
    is based loosely on:

    .. code-block:: none

        Yael Ben-Haim and Elad Tom-Tov, "A streaming parallel decision tree algorithm",
        J. Machine Learning Research 11 (2010), pp. 849--872.

    ``buckets`` must be a ``bigint``. ``value`` and ``weight`` must be numeric.

.. function:: qdigest_agg(x) -> qdigest<[same as x]>
    :noindex:

    See :doc:`qdigest`.

.. function:: qdigest_agg(x, w) -> qdigest<[same as x]>
    :noindex:

    See :doc:`qdigest`.

.. function:: qdigest_agg(x, w, accuracy) -> qdigest<[same as x]>
    :noindex:

    See :doc:`qdigest`.

Statistical Aggregate Functions
-------------------------------

.. function:: corr(y, x) -> double

    Returns correlation coefficient of input values.

.. function:: covar_pop(y, x) -> double

    Returns the population covariance of input values.

.. function:: covar_samp(y, x) -> double

    Returns the sample covariance of input values.

.. function:: kurtosis(x) -> double

    Returns the excess kurtosis of all input values. Unbiased estimate using
    the following expression:

    .. code-block:: none

        kurtosis(x) = n(n+1)/((n-1)(n-2)(n-3))sum[(x_i-mean)^4]/stddev(x)^4-3(n-1)^2/((n-2)(n-3))

.. function:: regr_intercept(y, x) -> double

    Returns linear regression intercept of input values. ``y`` is the dependent
    value. ``x`` is the independent value.

.. function:: regr_slope(y, x) -> double

    Returns linear regression slope of input values. ``y`` is the dependent
    value. ``x`` is the independent value.

.. function:: skewness(x) -> double

    Returns the skewness of all input values.

.. function:: stddev(x) -> double

    This is an alias for :func:`stddev_samp`.

.. function:: stddev_pop(x) -> double

    Returns the population standard deviation of all input values.

.. function:: stddev_samp(x) -> double

    Returns the sample standard deviation of all input values.

.. function:: variance(x) -> double

    This is an alias for :func:`var_samp`.

.. function:: var_pop(x) -> double

    Returns the population variance of all input values.

.. function:: var_samp(x) -> double

    Returns the sample variance of all input values.

Lambda Aggregate Functions
--------------------------

.. function:: reduce_agg(inputValue T, initialState S, inputFunction(S, T, S), combineFunction(S, S, S)) -> S

    Reduces all input values into a single value. ``inputFunction`` will be invoked
    for each non-null input value. In addition to taking the input value, ``inputFunction``
    takes the current state, initially ``initialState``, and returns the new state.
    ``combineFunction`` will be invoked to combine two states into a new state.
    The final state is returned::

        SELECT id, reduce_agg(value, 0, (a, b) -> a + b, (a, b) -> a + b)
        FROM (
            VALUES
                (1, 3),
                (1, 4),
                (1, 5),
                (2, 6),
                (2, 7)
        ) AS t(id, value)
        GROUP BY id;
        -- (1, 12)
        -- (2, 13)

        SELECT id, reduce_agg(value, 1, (a, b) -> a * b, (a, b) -> a * b)
        FROM (
            VALUES
                (1, 3),
                (1, 4),
                (1, 5),
                (2, 6),
                (2, 7)
        ) AS t(id, value)
        GROUP BY id;
        -- (1, 60)
        -- (2, 42)

    The state type must be a boolean, integer, floating-point, or date/time/interval.


text:
package com.xsx.samer.adapter;

import java.util.List;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xsx.samer.R;
import com.xsx.samer.utils.ImageLoadOptions;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import cn.bmob.im.bean.BmobChatUser;

public class BlackListAdapter extends CommonBaseAdapter<BmobChatUser>{

    public BlackListAdapter(List<BmobChatUser> list, Context context) {
        super(list, context);
        // TODO Auto-generated constructor stub
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = ViewHolder.getViewHolder(context, convertView,
                parent, R.layout.item_blacklist, position);
        final BmobChatUser contract = list.get(position);
        TextView tv_friend_name = (TextView) viewHolder.getView(R.id.tv_friend_name);
        ImageView iv_avatar = (ImageView) viewHolder.getView(R.id.img_friend_avatar);
        String avatar = contract.getAvatar();
        if (avatar != null && !avatar.equals("")) {
            ImageLoader.getInstance().displayImage(avatar, iv_avatar, ImageLoadOptions.getOptions());
        } else {
            iv_avatar.setImageResource(R.mipmap.ic_launcher);
        }
        tv_friend_name.setText(contract.getUsername());
        return super.getView(position, convertView, parent);
    }

}


text:
package skadistats.clarity.model;

import java.util.List;

public interface DTClass {

    String getDtName();

    int getClassId();
    void setClassId(int classId);

    Object[] getEmptyStateArray();

    String getNameForFieldPath(FieldPath fp);
    FieldPath getFieldPathForName(String property);

    <T> T getValueForFieldPath(FieldPath fp, Object[] state);

    List<FieldPath> collectFieldPaths(Object[] state);
    String dumpState(String title, Object[] state);

}


text:
/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

# pragma once

# include <dsn/service_api_c.h>
# include <dsn/cpp/blob.h>
# include <dsn/cpp/auto_codes.h>

namespace dsn
{
    /*!
    @addtogroup rpc-msg
    @{
    */
    class rpc_read_stream;
    class rpc_write_stream;
    typedef ::dsn::ref_ptr<rpc_read_stream> rpc_read_stream_ptr;
    typedef ::dsn::ref_ptr<rpc_write_stream> rpc_write_stream_ptr;

    class rpc_read_stream :
        public safe_handle<dsn_msg_release_ref>,
        public binary_reader
    {
    public:
        rpc_read_stream(dsn_message_t msg)
        {
            set_read_msg(msg);
        }

        rpc_read_stream()
        {
        }

        void set_read_msg(dsn_message_t msg)
        {
            assign(msg, false);

            void* ptr;
            size_t size;
            bool r = dsn_msg_read_next(msg, &ptr, &size);
            dassert(r, "read msg must have one segment of buffer ready");

            blob bb((const char*)ptr, 0, (int)size);
            init(bb);
        }

        ~rpc_read_stream()
        {
            if (native_handle())
            {
                dsn_msg_read_commit(native_handle(), (size_t)(total_size() - get_remaining_size()));
            }
        }
    };

    class rpc_write_stream :
        public safe_handle<dsn_msg_release_ref>,
        public binary_writer
    {
    public:
        // for response
        rpc_write_stream(dsn_message_t msg)
            : safe_handle<dsn_msg_release_ref>(msg, false)
        {
            _last_write_next_committed = true;
            _last_write_next_total_size = 0;
        }

        // for request
        rpc_write_stream(task_code code, int timeout_ms = 0, int thread_hash = 0, uint64_t partition_hash = 0)
            : safe_handle<dsn_msg_release_ref>(dsn_msg_create_request(code, timeout_ms, thread_hash, partition_hash), false)
        {
            _last_write_next_committed = true;
            _last_write_next_total_size = 0;
        }

        // write buffer for rpc_write_stream is allocated from
        // a per-thread pool, and it is expected that
        // the per-thread pool cannot allocated two outstanding
        // buffers at the same time.
        // e.g., alloc1, commit1, alloc2, commit2 is ok
        // while alloc1, alloc2, commit2, commit 1 is invalid
        void commit_buffer()
        {
            if (!_last_write_next_committed)
            {
                dsn_msg_write_commit(native_handle(), (size_t)(total_size() - _last_write_next_total_size));
                _last_write_next_committed = true;
            }
        }

        virtual ~rpc_write_stream()
        {
            flush();
        }

        virtual void flush() override
        {
            binary_writer::flush();
            commit_buffer();
        }

    private:
        virtual void create_new_buffer(size_t size, /*out*/blob& bb) override
        {
            commit_buffer();

            void* ptr;
            size_t sz;
            dsn_msg_write_next(native_handle(), &ptr, &sz, size);
            dbg_dassert(sz >= size, "allocated buffer size must be not less than the required size");
            bb.assign((const char*)ptr, 0, (int)sz);

            _last_write_next_total_size = total_size();
            _last_write_next_committed = false;
        }

    private:
        bool          _last_write_next_committed;
        int           _last_write_next_total_size;
    };
    /*@}*/
}


text:
require "semver"
require "pact_broker/configuration"

module PactBroker
  module Versions
    class ParseSemanticVersion

      def self.call string_version
        PactBroker.configuration.semver_formats.each do |semver_format|
          parsed_version = ::SemVer.parse(string_version, semver_format)
          return SemVerWrapper.new(parsed_version, semver_format) unless parsed_version.nil?
        end
        nil
      end

      class SemVerWrapper < SimpleDelegator

        def initialize target, semver_format
          super target
          @semver_format = semver_format
        end

        def to_s
          format(@semver_format)
        end
      end
    end
  end
end


text:
@interface SDPGistInterface : SDPConfigurableInterface<SDPSharingInterface, ASIHTTPRequestDelegate>
{
    NSStringEncoding _encoding;
@private
    NSString *_username;
    NSString *_password;
}

@end


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<artifactId>apple-orm</artifactId>
		<groupId>com.appleframework.orm</groupId>
		<version>0.2.1-SNAPSHOT</version>
	</parent>
	<artifactId>apple-orm-mybatis</artifactId>
	<name>apple-orm-mybatis</name>
	<url>http://mvnrepo.appleframework.com</url>

	<properties>
		<jsqlparser.version>0.9.5</jsqlparser.version>
	</properties>
	<dependencies>

		<dependency>
			<groupId>com.appleframework</groupId>
			<artifactId>apple-model</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>com.github.jsqlparser</groupId>
			<artifactId>jsqlparser</artifactId>
			<version>${jsqlparser.version}</version>
		</dependency>

		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
		</dependency>

	</dependencies>

</project>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict //EN">

<title>Bug: ENHANCEMENT - Automatically convert a fetch join to a query join for *ToMany joins and LIMIT OFFSET</title>
<link rel="shortcut icon" href="/image/favicon.ico" >
<link rel="stylesheet" type="text/css" href="/static/v2style.css" >

<meta name="Author" content="Rob">
<meta name="description" content="When a query uses setMaxRows etc it can t support fetch joins to ToMany properties Currently those ToMany joins are removed We should now convert them over to query joins instead Query lt Customer gt query Ebean find Customer class this will automatically get converted to a query join due to the maxRows join contacts new JoinConfig query setMaxRows 5 List lt Customer gt list query findList ">

<form action='/bugdetail-238.html' method="post" id="GLOBAL_ACTION">
<input type='hidden' name='_WOGA_CONTROLLER' >
<input type='hidden' name='_WOGA_METHOD' >
<input type='hidden' name='_WOGA_PARAM' >
<input type='hidden' name='_WOGA_RENDER' >

home
documentation
downloads
google group
forums
bugs
feedback

 Home » Bugs » ENH 238 : ENHANCEMENT - Automatically convert a fetch join to a query join for *ToMany joins and LIMIT OFFSET

 Enhancement 238 : ENHANCEMENT - Automatically convert a fetch join to a query join for *ToMany joins and LIMIT OFFSET

Priority
High

Reported Version

Logged By
Rob

Status
Fixed

Fixed Version
2.5.0

Assigned To

Product
Ebean - core

Duplicate Of

Created
09/03/2010

Updated
09/03/2010

Type
Enhancement

Attachments

No attachments

When a query uses setMaxRows etc it can't support fetch joins to *ToMany properties.

Currently those *ToMany joins are removed. We should now convert them over to query joins instead.

Query<Customer> query = Ebean.find(Customer.class)
    // this will automatically get converted to a
    // query join ... due to the maxRows
    .join("contacts")//, new JoinConfig().query())
    .setMaxRows(5);

List<Customer> list = query.findList();

Rob
09 Mar 23:06

Now will produce 2 queries ...

<sql summary='Customer' >
select c.id c0, c.status c1, c.name c2, c.smallnote c3, c.anniversary c4, c.cretime c5, c.updtime c6, c.billing_address_id c7, c.shipping_address_id c8
from o_customer c
limit 6
</sql>
<sql mode='+query' summary='Customer +many:contacts' load='path:contacts batch:100 actual:3' >
select c.id c0
        , cc.id c1, cc.first_name c2, cc.last_name c3, cc.phone c4, cc.mobile c5, cc.email c6, cc.cretime c7, cc.updtime c8, cc.customer_id c9
from o_customer c
left outer join contact cc on cc.customer_id = c.id
where c.id in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
order by c.id
</sql>

So there is a separate SQL query ... for the query join.

Rob
11 Mar 23:42

Fixed in HEAD

Fixed in HEAD.

<input type="hidden" name="f_bugid" value="238">

Add detail to this bug

*Summary:
<input class="txt wide90" type="text" id="f_title" name="f_title" value="">

*Details:
<textarea class="wide90" name="f_body" rows="10" cols="30"></textarea>

<input type="button" class="btn" value="Save" accesskey="s" onclick="woPost('app.comp.BugDetailAddComp','doPost');" >
<input type="button" class="btn" value="Cancel" accesskey="c" onclick="j('#bugDetailForm').hide();">

home | back to top

Introduction
User Guide (pdf)
Install/Configure
Public JavaDoc
Whitepapers

General
Database Specific
Byte Code
Deployment Annotations
Features

Top Bugs
Top Enhancements

woResponse

</form>

<form action='/bugdetail-238.html' method="post" id="UPLOAD" enctype="multipart/form-data">
<input type="hidden" name="f_bugid" value="238">
<input type="hidden" name="WO_HANDLER" value="app.comp.BugAttachmentUploadHandler">

Upload a file

<input type='file' name='f_file' >

<input type='submit' name='_upload' value="Upload" > <input type='button' value='Cancel' onclick="popdialog.hide();">

</form>


text:
<?php
namespace Josegonzalez\ErrorHandlers\Handler;

use Josegonzalez\ErrorHandlers\Handler\AbstractHandler;
use Raygun4php\RaygunClient;

class RaygunHandler extends AbstractHandler implements HandlerInterface
{
    /**
     * Handles a given exception
     *
     * @param Throwable|Exception $exception A Throwable or Exception instance
     * @return void
     */
    public function handle($exception)
    {
        $exception = call_user_func($this->config('exceptionCallback'), $exception);
        if (!$exception) {
            return;
        }
        $client = $this->client();
        $client = call_user_func($this->config('clientCallback'), $client);
        if ($client) {
            $client->SendException($exception);
        }
    }

    /**
     * Returns a client
     *
     * @return \Raygun4php\RaygunClient
     */
    protected function client()
    {
        $apiKey = $this->config('apiKey');
        if (!$apiKey) {
            return null;
        }

        $client = new RaygunClient($apiKey);

        return $client;
    }
}


text:
'use strict';

const pkg = require('./package.json');

module.exports = cmd;

/**
 * @param whaler
 */
async function cmd (whaler) {

    (await whaler.fetch('cli')).default

        .command(pkg.name + ' [ref]')
        .description(pkg.description, {
            ref: 'Application or container name'
        })
        .action(async (ref, options, util) => {
            ref = util.prepare('ref', ref);
            await whaler.emit('restart', { ref });
        });

}


text:
#ifndef SkTDict_DEFINED
#define SkTDict_DEFINED

#include "SkChunkAlloc.h"
#include "SkTSearch.h"
#include "SkTDArray.h"

template <typename T> class SkTDict : SkNoncopyable {
public:
    SkTDict(size_t minStringAlloc) : fStrings(minStringAlloc) {}

    void reset() {
        fArray.reset();
        fStrings.reset();
    }

    int count() const { return fArray.count(); }

    bool set(const char name[], const T& value) {
        return set(name, strlen(name), value);
    }

    bool set(const char name[], size_t len, const T& value) {
        SkASSERT(name);

        int index = this->find_index(name, len);

        if (index >= 0) {
            fArray[index].fValue = value;
            return false;
        } else {
            Pair*   pair = fArray.insert(~index);
            char*   copy = (char*)fStrings.alloc(len + 1, SkChunkAlloc::kThrow_AllocFailType);
            memcpy(copy, name, len);
            copy[len] = '\0';
            pair->fName = copy;
            pair->fValue = value;
            return true;
        }
    }

    bool find(const char name[]) const {
        return this->find_index(name) >= 0;
    }

    bool find(const char name[], size_t len) const {
        return this->find_index(name, len) >= 0;
    }

    bool find(const char name[], T* value) const {
        return find(name, strlen(name), value);
    }

    bool find(const char name[], size_t len, T* value) const {
        int index = this->find_index(name, len);

        if (index >= 0) {
            if (value) {
                *value = fArray[index].fValue;
            }
            return true;
        }
        return false;
    }

    bool findKey(T& value, const char** name) const {
        const Pair* end = fArray.end();
        for (const Pair* pair = fArray.begin(); pair < end; pair++) {
            if (pair->fValue != value) {
                continue;
            }
            *name = pair->fName;
            return true;
        }
        return false;
    }

public:
    struct Pair {
        const char* fName;
        T           fValue;

        friend int operator<(const Pair& a, const Pair& b) {
            return strcmp(a.fName, b.fName);
        }

        friend int operator!=(const Pair& a, const Pair& b) {
            return strcmp(a.fName, b.fName);
        }
    };
    friend class Iter;

public:
    class Iter {
    public:
        Iter(const SkTDict<T>& dict) {
            fIter = dict.fArray.begin();
            fStop = dict.fArray.end();
        }

        const char* next(T* value) {
            const char* name = NULL;
            if (fIter < fStop) {
                name = fIter->fName;
                if (value) {
                    *value = fIter->fValue;
                }
                fIter += 1;
            }
            return name;
        }
    private:
        const Pair*   fIter;
        const Pair*   fStop;
    };

private:
    SkTDArray<Pair> fArray;
    SkChunkAlloc    fStrings;

    int find_index(const char name[]) const {
        return find_index(name, strlen(name));
    }

    int find_index(const char name[], size_t len) const {
        SkASSERT(name);

        int count = fArray.count();
        int index = ~0;

        if (count) {
            index = SkStrSearch(&fArray.begin()->fName, count, name, len, sizeof(Pair));
        }
        return index;
    }
    friend class Iter;
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Hedy.Calcular.Restituicao
{
    public partial class CalcularRestituicao
    {
        /// <summary>
        /// Calcula Prazo Curto de acordo com tabela de restituição
        /// </summary>
        /// <param name="cancelamento">Data de cancelamento da proposta endossada</param>
        /// <returns>Valor restituição</returns>
        public decimal CalcularPrazoCurto(DateTime cancelamento)
        {
            var prazoRestante = this.PrazoRestante(cancelamento.Date);
            var prazoDecorrido = this.PrazoDecorrido(prazoRestante);
            var percentualPrazoDecorrido = this.PercentualPrazoPercorrido(prazoDecorrido);
            var premioDecorrer = this.PremioDecorrerPrazoCurto(percentualPrazoDecorrido);
            var premioReter = this.PremioReter(premioDecorrer);

            return this.Restituicao(premioReter);
        }

        private decimal PremioDecorrerPrazoCurto(decimal percentualPrazoDecorrido)
        {
            return (1 - this.PercentualRetidoPrazoCurto(percentualPrazoDecorrido)) * this.premioLiquido;
        }

        private decimal PercentualRetidoPrazoCurto(decimal percentualPrazoDecorrido)
        {
            return this.TabelaPrazoCuto().Where(x => Math.Round(x.Key / 365, 4) <= Math.Round(percentualPrazoDecorrido, 4)).Last().Value / 100;
        }

        /// <summary>
        /// Retorna Dictionary com valores para cálculo Prazo Curto
        /// </summary>
        /// <returns>Tabela de </returns>
        private Dictionary<decimal, decimal> TabelaPrazoCuto()
        {
            var valorRetorno = new Dictionary<decimal, decimal>
            {
                { 0, 0 },
                { 15, 13 },
                { 30, 20 },
                { 45, 27 },
                { 60, 30 },
                { 75, 37 },
                { 90, 40 },
                { 105, 46 },
                { 120, 50 },
                { 135, 56 },
                { 150, 60 },
                { 165, 66 },
                { 180, 70 },
                { 195, 73 },
                { 210, 75 },
                { 225, 78 },
                { 240, 80 },
                { 255, 83 },
                { 270, 85 },
                { 285, 88 },
                { 300, 90 },
                { 315, 93 },
                { 330, 95 },
                { 345, 98 },
                { 365, 100 }
            };

            return valorRetorno;
        }
    }
}


text:
namespace pwn
{
namespace render
{
    RenderBuffer::RenderBuffer(int internalFormat, int width, int height)
        : buffer(0)
    {
        glGenRenderbuffers(1, &buffer);
        pwnAssert_NoGLError();
        bind();
        glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, width, height);
        pwnAssert_NoGLError();
    }

    RenderBuffer::~RenderBuffer()
    {
        glDeleteRenderbuffers(1, &buffer);
        pwnAssert_NoGLError();
    }

    void
    RenderBuffer::bind()
    {
        glBindRenderbuffer(GL_RENDERBUFFER, buffer);
        pwnAssert_NoGLError();
    }

    unsigned int
    RenderBuffer::getBuffer() const
    {
        return buffer;
    }

    namespace
    {
        void
        Bind(const Fbo* const fbo)
        {
            unsigned int ifbo = fbo ? fbo->getId() : 0;
            glBindFramebuffer(GL_FRAMEBUFFER, ifbo);
            pwnAssert_NoGLError();
        }
    }

    Fbo::Fbo(int w, int h, bool mipmap) : fbo(0), width(w), height(h)
    {
        glGenFramebuffers(1, &fbo);
        pwnAssert_NoGLError();
        Bind(this);

        depth.reset(new RenderBuffer(GL_DEPTH_COMPONENT, width, height));
        glFramebufferRenderbuffer(
                GL_FRAMEBUFFER,
                GL_DEPTH_ATTACHMENT,
                GL_RENDERBUFFER,
                depth->getBuffer());
        pwnAssert_NoGLError();

        // todo: investigate if anistropy should be used here to...? for now we just disable it
        texture.reset(
                new Image(true, width, height, 0, mipmap, GL_RGBA, 1, false));
        const int mipmaplevel = 0;
        glFramebufferTexture2D(
                GL_FRAMEBUFFER,
                GL_COLOR_ATTACHMENT0,
                GL_TEXTURE_2D,
                texture->getId(),
                mipmaplevel);
        pwnAssert_NoGLError();

        const int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
        pwnAssert_NoGLError();
        if (status != GL_FRAMEBUFFER_COMPLETE)
            throw static_cast<string>(
                    core::Str()
                    << "Error when creating framebuffer: " << status);

        Bind(0);
    }

    void
    Fbo::bindTexture(int position)
    {
        texture->bind(position);
    }

    int
    Fbo::getWidth() const
    {
        return width;
    }

    int
    Fbo::getHeight() const
    {
        return height;
    }

    int
    Fbo::getId() const
    {
        return fbo;
    }

    bool
    Fbo::IsSupported()
    {
        // return GLEW_ARB_framebuffer_object == GL_TRUE;
        return GLEW_VERSION_3_0 == GL_TRUE;
    }

    TextureUpdator::TextureUpdator(Fbo* fbo)
    {
        Bind(fbo);
        glPushAttrib(GL_VIEWPORT_BIT);
        pwnAssert_NoGLError();
        glViewport(0, 0, fbo->getWidth(), fbo->getHeight());
        pwnAssert_NoGLError();
    }

    TextureUpdator::~TextureUpdator()
    {
        glPopAttrib();
        pwnAssert_NoGLError();
        Bind(0);
    }
}
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ComposableAsync
{
    internal class DispatcherAdapter : IDispatcher
    {
        private readonly IBasicDispatcher _BasicDispatcher;

        public DispatcherAdapter(IBasicDispatcher basicDispatcher)
        {
            _BasicDispatcher = basicDispatcher;
        }

        public IDispatcher Clone() => new DispatcherAdapter(_BasicDispatcher.Clone());

        public void Dispatch(Action action)
        {
            _BasicDispatcher.Enqueue(action, CancellationToken.None);
        }

        public Task Enqueue(Action action)
        {
            return _BasicDispatcher.Enqueue(action, CancellationToken.None);
        }

        public Task<T> Enqueue<T>(Func<T> action)
        {
            return _BasicDispatcher.Enqueue(action, CancellationToken.None);
        }

        public Task Enqueue(Func<Task> action)
        {
            return _BasicDispatcher.Enqueue(action, CancellationToken.None);
        }

        public Task<T> Enqueue<T>(Func<Task<T>> action)
        {
            return _BasicDispatcher.Enqueue(action, CancellationToken.None);
        }

        public Task<T> Enqueue<T>(Func<T> action, CancellationToken cancellationToken)
        {
            return _BasicDispatcher.Enqueue(action, cancellationToken);
        }

        public Task Enqueue(Action action, CancellationToken cancellationToken)
        {
            return _BasicDispatcher.Enqueue(action, cancellationToken);
        }

        public Task Enqueue(Func<Task> action, CancellationToken cancellationToken)
        {
            return _BasicDispatcher.Enqueue(action, cancellationToken);
        }

        public Task<T> Enqueue<T>(Func<Task<T>> action, CancellationToken cancellationToken)
        {
            return _BasicDispatcher.Enqueue(action, cancellationToken);
        }
    }
}


text:
require 'test_helper'

describe ActiveSupport::Cache::RedisStore do
  def setup
    @store  = ActiveSupport::Cache::RedisStore.new
    @dstore = ActiveSupport::Cache::RedisStore.new "redis://127.0.0.1:6380/1", "redis://127.0.0.1:6381/1"
    @rabbit = OpenStruct.new :name => "bunny"
    @white_rabbit = OpenStruct.new :color => "white"

    with_store_management do |store|
      store.write "rabbit", @rabbit
      store.delete "counter"
      store.delete "rub-a-dub"
    end
  end

  it "reads the data" do
    with_store_management do |store|
      store.read("rabbit").must_equal(@rabbit)
    end
  end

  it "writes the data" do
    with_store_management do |store|
      store.write "rabbit", @white_rabbit
      store.read("rabbit").must_equal(@white_rabbit)
    end
  end

  it "writes the data with expiration time" do
    with_store_management do |store|
      store.write "rabbit", @white_rabbit, :expires_in => 1.second
      store.read("rabbit").must_equal(@white_rabbit)
      sleep 2
      store.read("rabbit").must_be_nil
    end
  end

  it "respects expiration time in seconds" do
    with_store_management do |store|
      store.write "rabbit", @white_rabbit
      store.read("rabbit").must_equal(@white_rabbit)
      store.expire "rabbit", 1.seconds
      sleep 2
      store.read("rabbit").must_be_nil
    end
  end

  it "respects expiration time in minutes" do
    with_store_management do |store|
      store.write "rabbit", @white_rabbit
      store.read("rabbit").must_equal(@white_rabbit)
      store.expire "rabbit", 1.minutes
      sleep 61
      store.read("rabbit").must_be_nil
    end
  end

  it "does't write data if :unless_exist option is true" do
    with_store_management do |store|
      store.write "rabbit", @white_rabbit, :unless_exist => true
      store.read("rabbit").must_equal(@rabbit)
    end
  end

  if RUBY_VERSION.match /1\.9/
    it "reads raw data" do
      with_store_management do |store|
        result = store.read("rabbit", :raw => true)
        result.must_include("ActiveSupport::Cache::Entry")
        result.must_include("\x0FOpenStruct{\x06:\tnameI\"\nbunny\x06:\x06EF")
      end
    end
  else
    it "reads raw data" do
      with_store_management do |store|
        result = store.read("rabbit", :raw => true)
        result.must_include("ActiveSupport::Cache::Entry")
        result.must_include("\017OpenStruct{\006:\tname")
      end
    end
  end

  it "writes raw data" do
    with_store_management do |store|
      store.write "rabbit", @white_rabbit, :raw => true
      store.read("rabbit", :raw => true).must_equal(%(#<OpenStruct color=\"white\">))
    end
  end

  it "deletes data" do
    with_store_management do |store|
      store.delete "rabbit"
      store.read("rabbit").must_be_nil
    end
  end

  it "deletes matched data" do
    with_store_management do |store|
      store.delete_matched "rabb*"
      store.read("rabbit").must_be_nil
    end
  end

  it "verifies existence of an object in the store" do
    with_store_management do |store|
      store.exist?("rabbit").must_equal(true)
      store.exist?("rab-a-dub").must_equal(false)
    end
  end

  it "increments a key" do
    with_store_management do |store|
      3.times { store.increment "counter" }
      store.read("counter", :raw => true).to_i.must_equal(3)
    end
  end

  it "decrements a key" do
    with_store_management do |store|
      3.times { store.increment "counter" }
      2.times { store.decrement "counter" }
      store.read("counter", :raw => true).to_i.must_equal(1)
    end
  end

  it "increments a raw key" do
    with_store_management do |store|
      assert store.write("raw-counter", 1, :raw => true)
      store.increment("raw-counter", 2)
      store.read("raw-counter", :raw => true).to_i.must_equal(3)
    end
  end

  it "decrements a raw key" do
    with_store_management do |store|
      assert store.write("raw-counter", 3, :raw => true)
      store.decrement("raw-counter", 2)
      store.read("raw-counter", :raw => true).to_i.must_equal(1)
    end
  end

  it "increments a key by given value" do
    with_store_management do |store|
      store.increment "counter", 3
      store.read("counter", :raw => true).to_i.must_equal(3)
    end
  end

  it "decrements a key by given value" do
    with_store_management do |store|
      3.times { store.increment "counter" }
      store.decrement "counter", 2
      store.read("counter", :raw => true).to_i.must_equal(1)
    end
  end

  it "clears the store" do
    with_store_management do |store|
      store.clear
      store.instance_variable_get(:@data).keys("*").flatten.must_be_empty
    end
  end

  it "provides store stats" do
    with_store_management do |store|
      store.stats.wont_be_empty
    end
  end

  it "fetches data" do
    with_store_management do |store|
      store.fetch("rabbit").must_equal(@rabbit)
      store.fetch("rub-a-dub").must_be_nil
      store.fetch("rub-a-dub") { "Flora de Cana" }
      store.fetch("rub-a-dub").must_equal("Flora de Cana")
      store.fetch("rabbit", :force => true) # force cache miss
      store.fetch("rabbit", :force => true, :expires_in => 1.second) { @white_rabbit }
      # store.fetch("rabbit").must_equal(@white_rabbit)
      sleep 2
      store.fetch("rabbit").must_be_nil
    end
  end

  it "reads multiple keys" do
    @store.write "irish whisky", "Jameson"
    result = @store.read_multi "rabbit", "irish whisky"
    result['rabbit'].must_equal(@rabbit)
    result['irish whisky'].must_equal("Jameson")
  end

  it "reads multiple keys and returns only the matched ones" do
    @store.delete 'irish whisky'
    result = @store.read_multi "rabbit", "irish whisky"
    result.wont_include('irish whisky')
    result.must_include('rabbit')
  end

  describe "notifications" do
    it "notifies on #fetch" do
      with_notifications do
        @store.fetch("radiohead") { "House Of Cards" }
      end

      read, generate, write = @events

      read.name.must_equal('cache_read.active_support')
      read.payload.must_equal({ :key => 'radiohead', :super_operation => :fetch })

      generate.name.must_equal('cache_generate.active_support')
      generate.payload.must_equal({ :key => 'radiohead' })

      write.name.must_equal('cache_write.active_support')
      write.payload.must_equal({ :key => 'radiohead' })
    end

    it "notifies on #read" do
      with_notifications do
        @store.read "metallica"
      end

      read = @events.first
      read.name.must_equal('cache_read.active_support')
      read.payload.must_equal({ :key => 'metallica', :hit => false })
    end

    it "notifies on #write" do
      with_notifications do
        @store.write "depeche mode", "Enjoy The Silence"
      end

      write = @events.first
      write.name.must_equal('cache_write.active_support')
      write.payload.must_equal({ :key => 'depeche mode' })
    end

    it "notifies on #delete" do
      with_notifications do
        @store.delete "the new cardigans"
      end

      delete = @events.first
      delete.name.must_equal('cache_delete.active_support')
      delete.payload.must_equal({ :key => 'the new cardigans' })
    end

    it "notifies on #exist?" do
      with_notifications do
        @store.exist? "the smiths"
      end

      exist = @events.first
      exist.name.must_equal('cache_exist?.active_support')
      exist.payload.must_equal({ :key => 'the smiths' })
    end

    it "notifies on #delete_matched" do
      with_notifications do
        @store.delete_matched "afterhours*"
      end

      delete_matched = @events.first
      delete_matched.name.must_equal('cache_delete_matched.active_support')
      delete_matched.payload.must_equal({ :key => %("afterhours*") })
    end

    it "notifies on #increment" do
      with_notifications do
        @store.increment "pearl jam"
      end

      increment = @events.first
      increment.name.must_equal('cache_increment.active_support')
      increment.payload.must_equal({ :key => 'pearl jam', :amount => 1 })
    end

    it "notifies on #decrement" do
      with_notifications do
        @store.decrement "placebo"
      end

      decrement = @events.first
      decrement.name.must_equal('cache_decrement.active_support')
      decrement.payload.must_equal({ :key => 'placebo', :amount => 1 })
    end

    # it "notifies on cleanup" # TODO implement in ActiveSupport::Cache::RedisStore

    it "should notify on clear" do
      with_notifications do
        @store.clear
      end

      clear = @events.first
      clear.name.must_equal('cache_clear.active_support')
      clear.payload.must_equal({ :key => nil })
    end
  end

  private
    def instantiate_store(addresses = nil)
      ActiveSupport::Cache::RedisStore.new(addresses).instance_variable_get(:@data)
    end

    def with_store_management
      yield @store
      yield @dstore
    end

    def with_notifications
      @events = [ ]
      ActiveSupport::Cache::RedisStore.instrument = true
      ActiveSupport::Notifications.subscribe(/^cache_(.*)\.active_support$/) do |*args|
        @events << ActiveSupport::Notifications::Event.new(*args)
      end
      yield
      ActiveSupport::Cache::RedisStore.instrument = false
    end
end


text:
package org.mockito.internal.session;

import org.mockito.plugins.MockitoLogger;
import org.mockito.session.MockitoSessionLogger;

public class MockitoSessionLoggerAdapter implements MockitoSessionLogger {

    private final MockitoLogger logger;

    public MockitoSessionLoggerAdapter(MockitoLogger logger) {
        this.logger = logger;
    }

    @Override
    public void log(String hint) {
        logger.log(hint);
    }
}


text:
package blockservice

import (
	"errors"
	"fmt"

	blocks "github.com/ipfs/go-blocks"
	exchange "github.com/ipfs/go-blocks/blockservice/exchange"
	worker "github.com/ipfs/go-blocks/blockservice/worker"
	blockstore "github.com/ipfs/go-blocks/blockstore"
	key "github.com/ipfs/go-blocks/key"

	context "github.com/ipfs/go-blocks/Godeps/_workspace/src/golang.org/x/net/context"
)

var wc = worker.Config{
	// When running on a single core, NumWorkers has a harsh negative effect on
	// throughput. (-80% when < 25)
	// Running a lot more workers appears to have very little effect on both
	// single and multicore configurations.
	NumWorkers: 25,

	// These have no effect on when running on multiple cores, but harsh
	// negative effect on throughput when running on a single core
	// On multicore configurations these buffers have little effect on
	// throughput.
	// On single core configurations, larger buffers have severe adverse
	// effects on throughput.
	ClientBufferSize: 0,
	WorkerBufferSize: 0,
}

var ErrNotFound = errors.New("blockservice: key not found")

// BlockService is a hybrid block datastore. It stores data in a local
// datastore and may retrieve data from a remote Exchange.
// It uses an internal `datastore.Datastore` instance to store values.
type BlockService struct {
	// TODO don't expose underlying impl details
	Blockstore blockstore.Blockstore
	Exchange   exchange.Interface

	worker *worker.Worker
}

// NewBlockService creates a BlockService with given datastore instance.
func New(bs blockstore.Blockstore, rem exchange.Interface) (*BlockService, error) {
	if bs == nil {
		return nil, fmt.Errorf("BlockService requires valid blockstore")
	}

	return &BlockService{
		Blockstore: bs,
		Exchange:   rem,
		worker:     worker.NewWorker(rem, wc),
	}, nil
}

// AddBlock adds a particular block to the service, Putting it into the datastore.
// TODO pass a context into this if the remote.HasBlock is going to remain here.
func (s *BlockService) AddBlock(b *blocks.Block) (key.Key, error) {
	k := b.Key()
	err := s.Blockstore.Put(b)
	if err != nil {
		return k, err
	}
	if err := s.worker.HasBlock(b); err != nil {
		return "", errors.New("blockservice is closed")
	}
	return k, nil
}

// GetBlock retrieves a particular block from the service,
// Getting it from the datastore using the key (hash).
func (s *BlockService) GetBlock(ctx context.Context, k key.Key) (*blocks.Block, error) {
	block, err := s.Blockstore.Get(k)
	if err == nil {
		return block, nil
		// TODO be careful checking ErrNotFound. If the underlying
		// implementation changes, this will break.
	} else if err == blockstore.ErrNotFound && s.Exchange != nil {
		blk, err := s.Exchange.GetBlock(ctx, k)
		if err != nil {
			return nil, err
		}
		return blk, nil
	} else {
		return nil, ErrNotFound
	}
}

// GetBlocks gets a list of blocks asynchronously and returns through
// the returned channel.
// NB: No guarantees are made about order.
func (s *BlockService) GetBlocks(ctx context.Context, ks []key.Key) <-chan *blocks.Block {
	out := make(chan *blocks.Block, 0)
	go func() {
		defer close(out)
		var misses []key.Key
		for _, k := range ks {
			hit, err := s.Blockstore.Get(k)
			if err != nil {
				misses = append(misses, k)
				continue
			}
			select {
			case out <- hit:
			case <-ctx.Done():
				return
			}
		}

		rblocks, err := s.Exchange.GetBlocks(ctx, misses)
		if err != nil {
			// blocks not found are ignored. this is an optimistic call.
			return
		}

		for b := range rblocks {
			select {
			case out <- b:
			case <-ctx.Done():
				return
			}
		}
	}()
	return out
}

// DeleteBlock deletes a block in the blockservice from the datastore
func (s *BlockService) DeleteBlock(k key.Key) error {
	return s.Blockstore.DeleteBlock(k)
}

func (s *BlockService) Close() error {
	return s.worker.Close()
}


text:
'use strict';

var utils = require('lazy-cache')(require);
var fn = require;
require = utils;

/**
 * Lazily required module dependencies
 */

require('arr-diff', 'diff');
require('arr-union', 'union');
require('define-property', 'define');
require('expand-args');
require('extend-shallow', 'extend');
require = fn;

/**
 * Cast the given `value` to an array.
 *
 * ```js
 * utils.arrayify('foo');
 * //=> ['foo']
 *
 * utils.arrayify(['foo']);
 * //=> ['foo']
 * ```
 * @param {String|Array} `value`
 * @return {Array}
 * @api public
 */

utils.arrayify = function(val) {
  return val ? (Array.isArray(val) ? val : [val]) : [];
};

/**
 * Expose `utils` modules
 */

module.exports = utils;


text:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="@dimen/card_separator_height"
        android:color="@color/lightGray" />
    <corners android:radius="@dimen/card_corner_radius" />
</shape>


text:
<?php
/**
 * Created by PhpStorm.
 * User: tao.huang
 * Date: 15-1-15
 * Time: 下午2:27
 */
namespace Common\View\Helper;

class CheckLang extends \Zend\View\Helper\AbstractHelper
{
    public $langs = array();
    public $template;

    public function __construct($pluginManager)
    {
        $sm= $pluginManager->getServiceLocator();
        $adapter=$sm->get('Zend\Db\Adapter\Adapter');
        $result = $adapter->query('SELECT * from langs where is_enable=1');

        foreach ($result->execute() as $key => $value) {
            $this->langs[] = $value;
        }
        $config=$sm->get('config');
        $langTemplate=$config['view_manager']['template_map'];
        $this->template=$langTemplate['common\lang'];

    }

    public function __invoke()
    {
        $engine=$this->view->getEngine();
         include $this->template;
         return "";
    }

}


text:
<?php

abstract class BaseGgNewsPeer {

	const DATABASE_NAME = 'propel';

	const TABLE_NAME = 'gg_news';

	const CLASS_DEFAULT = 'lib.model.GgNews';

	const NUM_COLUMNS = 7;

	const NUM_LAZY_LOAD_COLUMNS = 0;

	const F_ID = 'gg_news.F_ID';

	const F_TITLE = 'gg_news.F_TITLE';

	const F_TITLE_CN = 'gg_news.F_TITLE_CN';

	const F_CONTENT = 'gg_news.F_CONTENT';

	const F_CONTENT_CN = 'gg_news.F_CONTENT_CN';

	const F_DATE = 'gg_news.F_DATE';

	const F_STATUS = 'gg_news.F_STATUS';

	private static $phpNameMap = null;

	private static $fieldNames = array (
		BasePeer::TYPE_PHPNAME => array ('FId', 'FTitle', 'FTitleCn', 'FContent', 'FContentCn', 'FDate', 'FStatus', ),
		BasePeer::TYPE_COLNAME => array (GgNewsPeer::F_ID, GgNewsPeer::F_TITLE, GgNewsPeer::F_TITLE_CN, GgNewsPeer::F_CONTENT, GgNewsPeer::F_CONTENT_CN, GgNewsPeer::F_DATE, GgNewsPeer::F_STATUS, ),
		BasePeer::TYPE_FIELDNAME => array ('f_id', 'f_title', 'f_title_cn', 'f_content', 'f_content_cn', 'f_date', 'f_status', ),
		BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, )
	);

	private static $fieldKeys = array (
		BasePeer::TYPE_PHPNAME => array ('FId' => 0, 'FTitle' => 1, 'FTitleCn' => 2, 'FContent' => 3, 'FContentCn' => 4, 'FDate' => 5, 'FStatus' => 6, ),
		BasePeer::TYPE_COLNAME => array (GgNewsPeer::F_ID => 0, GgNewsPeer::F_TITLE => 1, GgNewsPeer::F_TITLE_CN => 2, GgNewsPeer::F_CONTENT => 3, GgNewsPeer::F_CONTENT_CN => 4, GgNewsPeer::F_DATE => 5, GgNewsPeer::F_STATUS => 6, ),
		BasePeer::TYPE_FIELDNAME => array ('f_id' => 0, 'f_title' => 1, 'f_title_cn' => 2, 'f_content' => 3, 'f_content_cn' => 4, 'f_date' => 5, 'f_status' => 6, ),
		BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, )
	);

	public static function getMapBuilder()
	{
		include_once 'lib/model/map/GgNewsMapBuilder.php';
		return BasePeer::getMapBuilder('lib.model.map.GgNewsMapBuilder');
	}

	public static function getPhpNameMap()
	{
		if (self::$phpNameMap === null) {
			$map = GgNewsPeer::getTableMap();
			$columns = $map->getColumns();
			$nameMap = array();
			foreach ($columns as $column) {
				$nameMap[$column->getPhpName()] = $column->getColumnName();
			}
			self::$phpNameMap = $nameMap;
		}
		return self::$phpNameMap;
	}

	static public function translateFieldName($name, $fromType, $toType)
	{
		$toNames = self::getFieldNames($toType);
		$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
		if ($key === null) {
			throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
		}
		return $toNames[$key];
	}

	static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
	{
		if (!array_key_exists($type, self::$fieldNames)) {
			throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.');
		}
		return self::$fieldNames[$type];
	}

	public static function alias($alias, $column)
	{
		return str_replace(GgNewsPeer::TABLE_NAME.'.', $alias.'.', $column);
	}

	public static function addSelectColumns(Criteria $criteria)
	{

		$criteria->addSelectColumn(GgNewsPeer::F_ID);

		$criteria->addSelectColumn(GgNewsPeer::F_TITLE);

		$criteria->addSelectColumn(GgNewsPeer::F_TITLE_CN);

		$criteria->addSelectColumn(GgNewsPeer::F_CONTENT);

		$criteria->addSelectColumn(GgNewsPeer::F_CONTENT_CN);

		$criteria->addSelectColumn(GgNewsPeer::F_DATE);

		$criteria->addSelectColumn(GgNewsPeer::F_STATUS);

	}

	const COUNT = 'COUNT(gg_news.F_ID)';
	const COUNT_DISTINCT = 'COUNT(DISTINCT gg_news.F_ID)';

	public static function doCount(Criteria $criteria, $distinct = false, $con = null)
	{
				$criteria = clone $criteria;

				$criteria->clearSelectColumns()->clearOrderByColumns();
		if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
			$criteria->addSelectColumn(GgNewsPeer::COUNT_DISTINCT);
		} else {
			$criteria->addSelectColumn(GgNewsPeer::COUNT);
		}

				foreach($criteria->getGroupByColumns() as $column)
		{
			$criteria->addSelectColumn($column);
		}

		$rs = GgNewsPeer::doSelectRS($criteria, $con);
		if ($rs->next()) {
			return $rs->getInt(1);
		} else {
						return 0;
		}
	}

	public static function doSelectOne(Criteria $criteria, $con = null)
	{
		$critcopy = clone $criteria;
		$critcopy->setLimit(1);
		$objects = GgNewsPeer::doSelect($critcopy, $con);
		if ($objects) {
			return $objects[0];
		}
		return null;
	}

	public static function doSelect(Criteria $criteria, $con = null)
	{
		return GgNewsPeer::populateObjects(GgNewsPeer::doSelectRS($criteria, $con));
	}

	public static function doSelectRS(Criteria $criteria, $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(self::DATABASE_NAME);
		}

		if (!$criteria->getSelectColumns()) {
			$criteria = clone $criteria;
			GgNewsPeer::addSelectColumns($criteria);
		}

				$criteria->setDbName(self::DATABASE_NAME);

						return BasePeer::doSelect($criteria, $con);
	}

	public static function populateObjects(ResultSet $rs)
	{
		$results = array();

				$cls = GgNewsPeer::getOMClass();
		$cls = Propel::import($cls);
				while($rs->next()) {

			$obj = new $cls();
			$obj->hydrate($rs);
			$results[] = $obj;

		}
		return $results;
	}

	public static function getTableMap()
	{
		return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
	}

	public static function getOMClass()
	{
		return GgNewsPeer::CLASS_DEFAULT;
	}

	public static function doInsert($values, $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(self::DATABASE_NAME);
		}

		if ($values instanceof Criteria) {
			$criteria = clone $values; 		} else {
			$criteria = $values->buildCriteria(); 		}

		$criteria->remove(GgNewsPeer::F_ID);

				$criteria->setDbName(self::DATABASE_NAME);

		try {
									$con->begin();
			$pk = BasePeer::doInsert($criteria, $con);
			$con->commit();
		} catch(PropelException $e) {
			$con->rollback();
			throw $e;
		}

		return $pk;
	}

	public static function doUpdate($values, $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(self::DATABASE_NAME);
		}

		$selectCriteria = new Criteria(self::DATABASE_NAME);

		if ($values instanceof Criteria) {
			$criteria = clone $values;
			$comparison = $criteria->getComparison(GgNewsPeer::F_ID);
			$selectCriteria->add(GgNewsPeer::F_ID, $criteria->remove(GgNewsPeer::F_ID), $comparison);

		} else { 			$criteria = $values->buildCriteria(); 			$selectCriteria = $values->buildPkeyCriteria(); 		}

				$criteria->setDbName(self::DATABASE_NAME);

		return BasePeer::doUpdate($selectCriteria, $criteria, $con);
	}

	public static function doDeleteAll($con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(self::DATABASE_NAME);
		}
		$affectedRows = 0; 		try {
									$con->begin();
			$affectedRows += BasePeer::doDeleteAll(GgNewsPeer::TABLE_NAME, $con);
			$con->commit();
			return $affectedRows;
		} catch (PropelException $e) {
			$con->rollback();
			throw $e;
		}
	}

	 public static function doDelete($values, $con = null)
	 {
		if ($con === null) {
			$con = Propel::getConnection(GgNewsPeer::DATABASE_NAME);
		}

		if ($values instanceof Criteria) {
			$criteria = clone $values; 		} elseif ($values instanceof GgNews) {

			$criteria = $values->buildPkeyCriteria();
		} else {
						$criteria = new Criteria(self::DATABASE_NAME);
			$criteria->add(GgNewsPeer::F_ID, (array) $values, Criteria::IN);
		}

				$criteria->setDbName(self::DATABASE_NAME);

		$affectedRows = 0;
		try {
									$con->begin();

			$affectedRows += BasePeer::doDelete($criteria, $con);
			$con->commit();
			return $affectedRows;
		} catch (PropelException $e) {
			$con->rollback();
			throw $e;
		}
	}

	public static function doValidate(GgNews $obj, $cols = null)
	{
		$columns = array();

		if ($cols) {
			$dbMap = Propel::getDatabaseMap(GgNewsPeer::DATABASE_NAME);
			$tableMap = $dbMap->getTable(GgNewsPeer::TABLE_NAME);

			if (! is_array($cols)) {
				$cols = array($cols);
			}

			foreach($cols as $colName) {
				if ($tableMap->containsColumn($colName)) {
					$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
					$columns[$colName] = $obj->$get();
				}
			}
		} else {

		}

		return BasePeer::doValidate(GgNewsPeer::DATABASE_NAME, GgNewsPeer::TABLE_NAME, $columns);
	}

	public static function retrieveByPK($pk, $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(self::DATABASE_NAME);
		}

		$criteria = new Criteria(GgNewsPeer::DATABASE_NAME);

		$criteria->add(GgNewsPeer::F_ID, $pk);

		$v = GgNewsPeer::doSelect($criteria, $con);

		return !empty($v) > 0 ? $v[0] : null;
	}

	public static function retrieveByPKs($pks, $con = null)
	{
		if ($con === null) {
			$con = Propel::getConnection(self::DATABASE_NAME);
		}

		$objs = null;
		if (empty($pks)) {
			$objs = array();
		} else {
			$criteria = new Criteria();
			$criteria->add(GgNewsPeer::F_ID, $pks, Criteria::IN);
			$objs = GgNewsPeer::doSelect($criteria, $con);
		}
		return $objs;
	}

}
if (Propel::isInit()) {
			try {
		BaseGgNewsPeer::getMapBuilder();
	} catch (Exception $e) {
		Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
	}
} else {
			require_once 'lib/model/map/GgNewsMapBuilder.php';
	Propel::registerMapBuilder('lib.model.map.GgNewsMapBuilder');
}


text:
package com.tle.webtests.pageobject.integration.moodle;

import com.tle.webtests.framework.PageContext;
import com.tle.webtests.pageobject.AbstractPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class MoodleTasksBlockPage extends AbstractPage<MoodleTasksBlockPage> {
  @FindBy(xpath = "//div[contains(@class, 'block_equella_tasks')]")
  private WebElement block;

  public MoodleTasksBlockPage(PageContext context) {
    super(context, By.xpath("//div[contains(@class, 'block_equella_tasks')]"));
  }

  public boolean hasTasks() {
    return block.findElements(By.xpath(".//div[text()='You currently have no tasks']")).isEmpty();
  }

  public String getTaskUrl(String type) {
    return block
        .findElement(By.xpath(".//a[contains(text(), " + quoteXPath(type) + ")]"))
        .getAttribute("href");
  }

  public int getTaskCount(String type) {
    String task =
        block.findElement(By.xpath(".//a[contains(text(), " + quoteXPath(type) + ")]")).getText();

    return Integer.parseInt(task.substring(task.lastIndexOf("-") + 2));
  }
}


text:
""" This is a debian copyright file checker.  Put debian/copyright
    file conforming to http://dep.debian.net/deps/dep5/ and
    this program tells you which copyright holders you missed.

    Limitations:

    * for each section, you must put the full set of copyright holders.
      whilst the file lists are "carried over" i.e. later sections
      override earlier ones (see "remove_files()"), the same trick is
      NOT applied to copyright holders.

    * the qgram algorithm is applied to do some fuzzy string matching.
      it's pretty good, but don't rely on it to be perfect.

    * copyright year matching goes against "199" and "200" not
      "198?", "199?", "200?" and certainly not "201?".  if a name
      happens to have "199" or "200" in it, on a line that happens
      to have the word "copyright" in it, it gets assumed to be
      a copyright holder

    * random sentences tacked onto the end of copyrights in files
      are assumed to be part of the copyright holders' name

    * copyrights are assumed to be in the first 80 lines of the file

    * if the file doesn't _have_ a copyright notice, this program can't
      bloody well find it, can it??
"""

import glob
import sys
import os
from string import strip

# qgram: a way to "roughly" match words.  you're supposed to set splitlen
# to half the length of the average word, but 3 is good enough.
def qgram_set(word, splitlen):
    s = set()
    pad = '\0'*(splitlen-1)
    word = pad + word + pad
    for idx in range(len(word)-splitlen):
        s.add(word[idx:idx+splitlen])
    return s

def qgram(word1, word2, splitlen=3):
    s1 = qgram_set(word1, splitlen)
    s2 = qgram_set(word2, splitlen)
    un = len(s1.union(s2))
    ic = len(s1.intersection(s2))
    return float(ic) / float(un)

def truncate_qgram(word1, word2):
    if word1 == word2:
        return 1.0
    qg = 0
    if len(word1) > len(word2):
        tmp = word1
        word1 = word2
        word2 = tmp
    for i in range(len(word1), len(word2)+1):
        qg = max(qgram(word1, word2[:i]), qg)
    return qg

# testing, testing... ok, it works.
#print qgram("Copyright (C) 2009, Luke Kenneth Casson Leighton <lkcl@lkcl.net>",
#             "Copyright (C) 2006, Google, Inc.")
#print qgram("Copyright (C) 2009, Luke Kenneth Casson Leighton <lkcl@lkcl.net>",
#            "Copyright (C) 2009, Luke Kenneth Casson Leighton <lkcl@lkcl.net>")
#print qgram("Copyright (C) 2009, Luke Kenneth Casson Leighton <lkcl@lkcl.net>",
#             "Copyright (c) 2008, Luke Kenneth Casson Leighton")
#print qgram("Copyright (C) 2009, Luke Kenneth Casson Leighton <lkcl@lkcl.net>",
#             "Copyright (c) 2008, 2009, Luke Kenneth Casson Leighton ")
#print qgram("Copyright (C) 2009, Luke Kenneth Casson Leighton",
#             "Copyright (c) 2008, 2009, Luke Kenneth Casson Leighton ")

def check_match(word, word_list):
    matches = set()
    not_matches = set()
    for word2 in word_list:
        match = truncate_qgram(word, word2)
        if match > 0.6:
            matches.add((word, word2))
        else:
            not_matches.add((word, word2))
    return matches, not_matches

def sanitise(copyright):
    if copyright[0] == ':':
        copyright = copyright[1:].strip()
    co = "(c)"
    fco = copyright.lower().find(co)
    if fco >= 0:
        copyright = copyright[:fco] + copyright[fco+len(co):]
    srrs = "some rights reserved"
    srr = copyright.lower().find(srrs)
    if srr >= 0:
        copyright = copyright[:srr] + copyright[srr+len(srrs):]
    arrs = "all rights reserved"
    arr = copyright.lower().find(arrs)
    if arr >= 0:
        copyright = copyright[:arr] + copyright[arr+len(arrs):]
    return copyright
    # hmmm... something not quite right here...
    res = ''
    for c in copyright:
        if c.isalnum():
            res += c
        else:
            res += ' '
    res = res.split(' ')
    res = filter(lambda x:x, res)
    return ' '.join(res)

def find_file_copyright_notices(fname):
    ret = set()
    f = open(fname)
    lines = f.readlines()
    for l in lines[:80]: # hmmm, assume copyright to be in first 80 lines
        idx = l.lower().find("copyright")
        if idx < 0:
            continue
        copyright = l[idx+9:].strip()
        if not copyright:
            continue
        copyright = sanitise(copyright)
        # hmm, do a quick check to see if there's a year,
        # if not, skip it
        if not copyright.find("200") >= 0 and \
           not copyright.find("199") >= 0 :
           continue
        ret.add(copyright)
    return ret

def skip_file(fname):
    if fname.startswith(".svn"):
        return True
    if fname.startswith(".git"):
        return True
    if fname.startswith(".sw"):
        return True
    if fname == "output": # no thanks
        return True
    if fname.find("PureMVC_Python_1_0") >= 0: # no thanks
        return True
    if fname.endswith(".pyc"): # ehmm.. no.
        return True
    if fname.endswith(".java"): # no again
        return True
    return False

def get_files(d):
    res = []
    for p in glob.glob(os.path.join(d, "*")):
        if not p:
            continue
        (pth, fname) = os.path.split(p)
        if skip_file(fname):
            continue
        if os.path.islink(p):
            continue
        if os.path.isdir(p):
            res += get_dir(p)
        else:
            res.append(p)
    return res

def get_dir(match):
    data_files = []
    for d in glob.glob(match):
        if skip_file(d):
            continue
        if os.path.islink(d):
            continue
        if os.path.isdir(d):
            (pth, fname) = os.path.split(d)
            expath = get_files(d)
            data_files += expath
        else:
            data_files.append(d)
    return data_files

class DebSect:
    def __init__(self, pattern, files):
        self.file_pattern = pattern
        self.files = files
        self.copyrights = set()
        self.listed_copyrights = set()
        self.files_by_author = {}

    def read_files_for_copyrights(self):
        for fname in self.files:
            if fname.endswith("copyright_check.py"): # skip this program!
                continue
            if fname == 'copyright': # skip this one duh
                continue
            cops = find_file_copyright_notices(fname)
            self.listed_copyrights.update(cops)
            for c in cops:
                if not self.files_by_author.has_key(c):
                    self.files_by_author[c] = set()
                if fname not in self.files_by_author[c]:
                    self.files_by_author[c].add(fname)
        print "Pattern", self.file_pattern
        for author in self.copyrights:
            print "Copyright:", author
        for author in self.listed_copyrights:
            print "Listed Copyright:", author

    def remove_files(self, to_remove):
        for fname in to_remove:
            if fname in self.files:
                self.files.remove(fname)

    def check_copyright_matches(self):
        self.matches = set()
        self.not_matches = set()

        for author in self.listed_copyrights:
            matches, not_matches = check_match(author, self.listed_copyrights)
            self.matches.update(matches)
            for (word1, word2) in not_matches:
                matches1, not_matches1 = check_match(word2, self.copyrights)
                #print "matches1, not_matches1", word1, word2, matches1, not_matches1
                if len(matches1) > 0:
                    continue
                #print "not matches", repr(word2), self.copyrights
                #print self.files_by_author[word2]
                self.not_matches.add(word2)

        if self.not_matches:
            print
            print"   ** ** ** ** **"
            for m in self.not_matches:
                print "   ** not matches:", m
                for fname in self.files_by_author[m]:
                    print"   ** ** ** ** **:", fname
        print

all_files = get_dir("*")
copyright_sects = []
all_listed_files = []

#print "all files", all_files

# read debian/copyright file and collect all matched files,
# copyrights and licenses
current_debsect = None
current_copyrights = set()
current_licenses = set()

dc = open("copyright")
for l in dc.readlines():
    if l.startswith("License:"):
        current_licenses.add(strip(l[8:]))
        continue
    if l.startswith("Copyright:"):
        current_copyrights.add(sanitise(strip(l[10:])))
        continue
    if not l.startswith("Files:"):
        continue
    if current_debsect:
        current_debsect.licenses = current_licenses
        current_debsect.copyrights = current_copyrights
        current_copyrights = set()
        current_licenses = set()
    l = l.split(" ")
    l = map(strip, l)
    listed_files = []
    for pattern in l[1:]:
        if pattern[-1] == ',':
            pattern = pattern[:-1]
        files = get_dir(pattern)
        listed_files += files
        all_listed_files += files
    current_debsect = DebSect(l[1:], listed_files)
    copyright_sects.append(current_debsect)

if current_debsect:
    current_debsect.copyrights = current_copyrights
    current_debsect.licenses = current_licenses

dc.close()

# remove already-matching: further down takes precedence
for i in range(1, len(copyright_sects)):
    for j in range(i):
        #print i, j, copyright_sects[i].file_pattern, copyright_sects[j].file_pattern
        copyright_sects[j].remove_files(copyright_sects[i].files)

for dc in copyright_sects:
    dc.read_files_for_copyrights()
    dc.check_copyright_matches()
    print

#def check_in(l1, l2):
#    res = []
#    for fname in l1:
#        if fname not in l2:
#            res.append(fname)
#    return res
#
#not_in = check_in(all_files, listed_files)
#for fname in not_in:
#    print fname
#print listed_files
#print check_in(listed_files, all_files)


text:
var chai = require('chai');
var assert = chai.assert;
var fs = require('fs');
var request = require('request');
var path = require('path');

// console.log('--- 1 --- Run Compression Server Tests!');

describe('hooks', function() {
  before(function() {
    // runs before all tests in this block
    // console.log('--- 1.1 --- Before: download test.wav');

    var testWavUrl = 'https://s3-us-west-1.amazonaws.com/jamrecordtest/indextest/testSourceFiles/test1.wav';
    var destinationPath = path.join(__dirname + '/testFiles/test1.wav');
    // console.log(destinationPath);

    request.get(testWavUrl)
      .on('data', function(chunk) {
        // console.log(chunk);
      })
      .pipe( fs.createWriteStream(destinationPath) );
    // console.log('--- 1.2 --- Download completed');

  });

  after(function() {
    // runs after all tests in this block
  });

  beforeEach(function() {
    // runs before each test in this block
  });

  afterEach(function() {
    // runs after each test in this block
  });

  it('it should work', function () {
    assert.equal(1, 1);
  });

  // test cases
});

// describe('Download test.wav', function() {

//   // describe('#indexOf()', function () {
//   //   it('should return -1 when the value is not present', function () {
//   //     assert.equal(1, 1);
//   //   });
//   // });
// });

// https://s3-us-west-1.amazonaws.com/jamrecordtest/indextest/testSourceFiles/test1.wav


text:
<?php

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Conversation extends \Eloquent {
    use SoftDeletingTrait;
	protected $fillable = [];
    protected $table = "conversations";

    public function last_message(){
        return $this->hasOne('Conversation_reply')->orderBy('updated_at','desc');
    }

    public function user_one(){
        return $this->belongsTo('User','user_one_id')->with('profilePicture');
    }

    public function user_two(){
        return $this->belongsTo('User','user_two_id')->with('profilePicture');
    }

}


text:
#pragma once

#include <medCoreExport.h>
#include <dtkCore/dtkAbstractFactory.h>
#include <QtCore>

class medSettingsWidget;
class medSettingsWidgetFactoryPrivate;
struct medSettingDetails;

/**
 * @brief This factory creates Widgets that are pages in the medSettingsEditor widget.
*/
class MEDCORE_EXPORT medSettingsWidgetFactory : public dtkAbstractFactory
{
  Q_OBJECT

public:

  //! This function pointer designates functions allocating memory
  typedef medSettingsWidget*(*medSettingsWidgetCreator)(QWidget *);

  //! Type designating the internal has table containing the creator functions.
  typedef QHash<QString, medSettingDetails*> medSettingsWidgetCreatorHash;

public:

  static medSettingsWidgetFactory * instance();
  /**
   * @brief Registers a new widget type, and its creator function.
   *
   * @param type name of the widget type.
   * @param name Human readable name(Potentially localised).
   * @param description short description, mainly used for tooltips
   * @return bool true if type was not registered already, false if it exists.
  */
  template <typename settingType>
  bool registerSettingsWidget()
  {
      //we must keep the templated part in the .h file for library users
      medSettingsWidgetCreator creator = create<settingType>;
      return registerSettingsWidget(settingType::staticIdentifier(),
                                    settingType::staticName(),
                                    settingType::staticDescription(),
                                    creator);
  }

  QList<QString> settingsWidgets();

  medSettingDetails* settingDetailsFromId (const QString& id ) const;

public slots:

  medSettingsWidget * createSettingsWidget(QString type, QWidget * parent);

protected:

  medSettingsWidgetFactory();
  ~medSettingsWidgetFactory();

private:
  static medSettingsWidgetFactory * s_instance; /**< TODO */
  /**
   * @brief Templated method returning a pointer to an allocated settingsWidget.
   * @see template<class settingType> registerToolBox
   * @warning keep it static if you don't want to freeze your brain (solution in http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.5 for those interested)
   */
  template < typename T >
  static medSettingsWidget* create ( QWidget* parent ) {
  return ( new T(parent) );
  }

  bool registerSettingsWidget (const QString& type,
                               QString name,
                               QString description,
                               medSettingsWidgetCreator);

private:
  medSettingsWidgetFactoryPrivate * d; /**< TODO */
};

/**
 * @brief Stores the details for a particular settingsWidget,
 * and a function to allocate memory.
 *
 */
struct MEDCORE_EXPORT medSettingDetails{
    QString name; /** Readable name*/
    QString description; /** (tooltip) short description */
    medSettingsWidgetFactory::medSettingsWidgetCreator creator; /** function pointer allocating memory for the widget*/
    medSettingDetails(QString name,QString description,
                     medSettingsWidgetFactory::medSettingsWidgetCreator creator):
        name(name),description(description),
        creator(creator){}
};


text:
<?php

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends FOSRestController
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
		$view = new View(null, 200);

		$view->setFormat('html')
			->setHeader('Content-Type', 'html')
			->setTemplate("default/index.html.twig");

		return $this->handleView($view);
    }
}


text:
<?php
$estado=$_GET['estado'];
$codigo_cliente=$_GET['id'];

require_once("manejomysql.php");
conectar_bd();

if($estado == 'Activo')
{
	mysql_query("update usuario set estado='Inactivo' WHERE cod_usuario=".$codigo_cliente );
	header ("Location:dar_baja_vendedor.php");
	exit;

}
else
{
	mysql_query("update usuario set estado='Activo' WHERE cod_usuario=".$codigo_cliente );
	header ("Location:dar_baja_vendedor.php");
	exit;
}
?>