text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>CREATE FUNCTION</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.2.8 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="SQL Commands"
HREF="sql-commands.html"><LINK
REL="PREVIOUS"
TITLE="CREATE FOREIGN TABLE"
HREF="sql-createforeigntable.html"><LINK
REL="NEXT"
TITLE="CREATE GROUP"
HREF="sql-creategroup.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2014-03-17T19:46:29">

PostgreSQL 9.2.8 Documentation

Prev	Up		Next

CREATE FUNCTION

Name
CREATE FUNCTION -- define a new function

Synopsis

CREATE [ OR REPLACE ] FUNCTION
    <TT
CLASS="REPLACEABLE"
>name</TT
> ( [ [ <TT
CLASS="REPLACEABLE"
>argmode</TT
> ] [ <TT
CLASS="REPLACEABLE"
>argname</TT
> ] <TT
CLASS="REPLACEABLE"
>argtype</TT
> [ { DEFAULT | = } <TT
CLASS="REPLACEABLE"
>default_expr</TT
> ] [, ...] ] )
    [ RETURNS <TT
CLASS="REPLACEABLE"
>rettype</TT
>
      | RETURNS TABLE ( <TT
CLASS="REPLACEABLE"
>column_name</TT
> <TT
CLASS="REPLACEABLE"
>column_type</TT
> [, ...] ) ]
  { LANGUAGE <TT
CLASS="REPLACEABLE"
>lang_name</TT
>
    | WINDOW
    | IMMUTABLE | STABLE | VOLATILE | [ NOT ] LEAKPROOF
    | CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
    | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
    | COST <TT
CLASS="REPLACEABLE"
>execution_cost</TT
>
    | ROWS <TT
CLASS="REPLACEABLE"
>result_rows</TT
>
    | SET <TT
CLASS="REPLACEABLE"
>configuration_parameter</TT
> { TO <TT
CLASS="REPLACEABLE"
>value</TT
> | = <TT
CLASS="REPLACEABLE"
>value</TT
> | FROM CURRENT }
    | AS '<TT
CLASS="REPLACEABLE"
>definition</TT
>'
    | AS '<TT
CLASS="REPLACEABLE"
>obj_file</TT
>', '<TT
CLASS="REPLACEABLE"
>link_symbol</TT
>'
  } ...
    [ WITH ( <TT
CLASS="REPLACEABLE"
>attribute</TT
> [, ...] ) ]

Description

   <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
> defines a new function.
   <TT
CLASS="COMMAND"
>CREATE OR REPLACE FUNCTION</TT
> will either create a
   new function, or replace an existing definition.
   To be able to define a function, the user must have the
   <TT
CLASS="LITERAL"
>USAGE</TT
> privilege on the language.

   If a schema name is included, then the function is created in the
   specified schema.  Otherwise it is created in the current schema.
   The name of the new function must not match any existing function
   with the same input argument types in the same schema.  However,
   functions of different argument types can share a name (this is
   called overloading).

   To replace the current definition of an existing function, use
   <TT
CLASS="COMMAND"
>CREATE OR REPLACE FUNCTION</TT
>.  It is not possible
   to change the name or argument types of a function this way (if you
   tried, you would actually be creating a new, distinct function).
   Also, <TT
CLASS="COMMAND"
>CREATE OR REPLACE FUNCTION</TT
> will not let
   you change the return type of an existing function.  To do that,
   you must drop and recreate the function.  (When using <TT
CLASS="LITERAL"
>OUT</TT
>
   parameters, that means you cannot change the types of any
   <TT
CLASS="LITERAL"
>OUT</TT
> parameters except by dropping the function.)

   When <TT
CLASS="COMMAND"
>CREATE OR REPLACE FUNCTION</TT
> is used to replace an
   existing function, the ownership and permissions of the function
   do not change.  All other function properties are assigned the
   values specified or implied in the command.  You must own the function
   to replace it (this includes being a member of the owning role).

   If you drop and then recreate a function, the new function is not
   the same entity as the old; you will have to drop existing rules, views,
   triggers, etc. that refer to the old function.  Use
   <TT
CLASS="COMMAND"
>CREATE OR REPLACE FUNCTION</TT
> to change a function
   definition without breaking objects that refer to the function.
   Also, <TT
CLASS="COMMAND"
>ALTER FUNCTION</TT
> can be used to change most of the
   auxiliary properties of an existing function.

   The user that creates the function becomes the owner of the function.

   To be able to create a function, you must have <TT
CLASS="LITERAL"
>USAGE</TT
>
   privilege on the argument types and the return type.

Parameters

<TT
CLASS="REPLACEABLE"
>name</TT
>

       The name (optionally schema-qualified) of the function to create.

<TT
CLASS="REPLACEABLE"
>argmode</TT
>

       The mode of an argument: <TT
CLASS="LITERAL"
>IN</TT
>, <TT
CLASS="LITERAL"
>OUT</TT
>,
       <TT
CLASS="LITERAL"
>INOUT</TT
>, or <TT
CLASS="LITERAL"
>VARIADIC</TT
>.
       If omitted, the default is <TT
CLASS="LITERAL"
>IN</TT
>.
       Only <TT
CLASS="LITERAL"
>OUT</TT
> arguments can follow a <TT
CLASS="LITERAL"
>VARIADIC</TT
> one.
       Also, <TT
CLASS="LITERAL"
>OUT</TT
> and <TT
CLASS="LITERAL"
>INOUT</TT
> arguments cannot be used
       together with the <TT
CLASS="LITERAL"
>RETURNS TABLE</TT
> notation.

<TT
CLASS="REPLACEABLE"
>argname</TT
>

       The name of an argument. Some languages (including SQL and PL/pgSQL)
       let you use the name in the function body.  For other languages the
       name of an input argument is just extra documentation, so far as
       the function itself is concerned; but you can use input argument names
       when calling a function to improve readability (see Section 4.3).  In any case, the name
       of an output argument is significant, because it defines the column
       name in the result row type.  (If you omit the name for an output
       argument, the system will choose a default column name.)

<TT
CLASS="REPLACEABLE"
>argtype</TT
>

       The data type(s) of the function's arguments (optionally
       schema-qualified), if any. The argument types can be base, composite,
       or domain types, or can reference the type of a table column.

       Depending on the implementation language it might also be allowed
       to specify "pseudotypes" such as <TT
CLASS="TYPE"
>cstring</TT
>.
       Pseudotypes indicate that the actual argument type is either
       incompletely specified, or outside the set of ordinary SQL data types.

       The type of a column is referenced by writing
       <TT
CLASS="LITERAL"
><TT
CLASS="REPLACEABLE"
>table_name</TT
>.<TT
CLASS="REPLACEABLE"
>column_name</TT
>%TYPE</TT
>.
       Using this feature can sometimes help make a function independent of
       changes to the definition of a table.

<TT
CLASS="REPLACEABLE"
>default_expr</TT
>

       An expression to be used as default value if the parameter is
       not specified.  The expression has to be coercible to the
       argument type of the parameter.
       Only input (including <TT
CLASS="LITERAL"
>INOUT</TT
>) parameters can have a default
        value.  All input parameters following a
       parameter with a default value must have default values as well.

<TT
CLASS="REPLACEABLE"
>rettype</TT
>

       The return data type (optionally schema-qualified). The return type
       can be a base, composite, or domain type,
       or can reference the type of a table column.
       Depending on the implementation language it might also be allowed
       to specify "pseudotypes" such as <TT
CLASS="TYPE"
>cstring</TT
>.
       If the function is not supposed to return a value, specify
       <TT
CLASS="TYPE"
>void</TT
> as the return type.

       When there are <TT
CLASS="LITERAL"
>OUT</TT
> or <TT
CLASS="LITERAL"
>INOUT</TT
> parameters,
       the <TT
CLASS="LITERAL"
>RETURNS</TT
> clause can be omitted.  If present, it
       must agree with the result type implied by the output parameters:
       <TT
CLASS="LITERAL"
>RECORD</TT
> if there are multiple output parameters, or
       the same type as the single output parameter.

       The <TT
CLASS="LITERAL"
>SETOF</TT
>
       modifier indicates that the function will return a set of
       items, rather than a single item.

       The type of a column is referenced by writing
       <TT
CLASS="LITERAL"
><TT
CLASS="REPLACEABLE"
>table_name</TT
>.<TT
CLASS="REPLACEABLE"
>column_name</TT
>%TYPE</TT
>.

<TT
CLASS="REPLACEABLE"
>column_name</TT
>

       The name of an output column in the <TT
CLASS="LITERAL"
>RETURNS TABLE</TT
>
       syntax.  This is effectively another way of declaring a named
       <TT
CLASS="LITERAL"
>OUT</TT
> parameter, except that <TT
CLASS="LITERAL"
>RETURNS TABLE</TT
>
       also implies <TT
CLASS="LITERAL"
>RETURNS SETOF</TT
>.

<TT
CLASS="REPLACEABLE"
>column_type</TT
>

       The data type of an output column in the <TT
CLASS="LITERAL"
>RETURNS TABLE</TT
>
       syntax.

<TT
CLASS="REPLACEABLE"
>lang_name</TT
>

       The name of the language that the function is implemented in.
       Can be <TT
CLASS="LITERAL"
>SQL</TT
>, <TT
CLASS="LITERAL"
>C</TT
>,
       <TT
CLASS="LITERAL"
>internal</TT
>, or the name of a user-defined
       procedural language.  For backward compatibility,
       the name can be enclosed by single quotes.

<TT
CLASS="LITERAL"
>WINDOW</TT
>

<TT
CLASS="LITERAL"
>WINDOW</TT
> indicates that the function is a
       window function rather than a plain function.
       This is currently only useful for functions written in C.
       The <TT
CLASS="LITERAL"
>WINDOW</TT
> attribute cannot be changed when
       replacing an existing function definition.

<TT
CLASS="LITERAL"
>IMMUTABLE</TT
>
<TT
CLASS="LITERAL"
>STABLE</TT
>
<TT
CLASS="LITERAL"
>VOLATILE</TT
>

       These attributes inform the query optimizer about the behavior
       of the function.  At most one choice
       can be specified.  If none of these appear,
       <TT
CLASS="LITERAL"
>VOLATILE</TT
> is the default assumption.

<TT
CLASS="LITERAL"
>IMMUTABLE</TT
> indicates that the function
       cannot modify the database and always
       returns the same result when given the same argument values; that
       is, it does not do database lookups or otherwise use information not
       directly present in its argument list.  If this option is given,
       any call of the function with all-constant arguments can be
       immediately replaced with the function value.

<TT
CLASS="LITERAL"
>STABLE</TT
> indicates that the function
       cannot modify the database,
       and that within a single table scan it will consistently
       return the same result for the same argument values, but that its
       result could change across SQL statements.  This is the appropriate
       selection for functions whose results depend on database lookups,
       parameter variables (such as the current time zone), etc.  (It is
       inappropriate for <TT
CLASS="LITERAL"
>AFTER</TT
> triggers that wish to
       query rows modified by the current command.)  Also note
       that the current_timestamp family of functions qualify
       as stable, since their values do not change within a transaction.

<TT
CLASS="LITERAL"
>VOLATILE</TT
> indicates that the function value can
       change even within a single table scan, so no optimizations can be
       made.  Relatively few database functions are volatile in this sense;
       some examples are <TT
CLASS="LITERAL"
>random()</TT
>, <TT
CLASS="LITERAL"
>currval()</TT
>,
       <TT
CLASS="LITERAL"
>timeofday()</TT
>.  But note that any function that has
       side-effects must be classified volatile, even if its result is quite
       predictable, to prevent calls from being optimized away; an example is
       <TT
CLASS="LITERAL"
>setval()</TT
>.

       For additional details see Section 35.6.

<TT
CLASS="LITERAL"
>LEAKPROOF</TT
>

       <TT
CLASS="LITERAL"
>LEAKPROOF</TT
> indicates that the function has no side
       effects.  It reveals no information about its arguments other than by
       its return value.  For example, a function which throws an error message
       for some argument values but not others, or which includes the argument
       values in any error message, is not leakproof.   The query planner may
       push leakproof functions (but not others) into views created with the
       <TT
CLASS="LITERAL"
>security_barrier</TT
> option.  See
       CREATE VIEW and Section 37.4.
       This option can only be set by the superuser.

<TT
CLASS="LITERAL"
>CALLED ON NULL INPUT</TT
>
<TT
CLASS="LITERAL"
>RETURNS NULL ON NULL INPUT</TT
>
<TT
CLASS="LITERAL"
>STRICT</TT
>

<TT
CLASS="LITERAL"
>CALLED ON NULL INPUT</TT
> (the default) indicates
       that the function will be called normally when some of its
       arguments are null.  It is then the function author's
       responsibility to check for null values if necessary and respond
       appropriately.

<TT
CLASS="LITERAL"
>RETURNS NULL ON NULL INPUT</TT
> or
       <TT
CLASS="LITERAL"
>STRICT</TT
> indicates that the function always
       returns null whenever any of its arguments are null.  If this
       parameter is specified, the function is not executed when there
       are null arguments; instead a null result is assumed
       automatically.

<TT
CLASS="LITERAL"
>[EXTERNAL] SECURITY INVOKER</TT
>
<TT
CLASS="LITERAL"
>[EXTERNAL] SECURITY DEFINER</TT
>

<TT
CLASS="LITERAL"
>SECURITY INVOKER</TT
> indicates that the function
      is to be executed with the privileges of the user that calls it.
      That is the default.  <TT
CLASS="LITERAL"
>SECURITY DEFINER</TT
>
      specifies that the function is to be executed with the
      privileges of the user that created it.

      The key word <TT
CLASS="LITERAL"
>EXTERNAL</TT
> is allowed for SQL
      conformance, but it is optional since, unlike in SQL, this feature
      applies to all functions not only external ones.

<TT
CLASS="REPLACEABLE"
>execution_cost</TT
>

       A positive number giving the estimated execution cost for the function,
       in units of cpu_operator_cost.  If the function
       returns a set, this is the cost per returned row.  If the cost is
       not specified, 1 unit is assumed for C-language and internal functions,
       and 100 units for functions in all other languages.  Larger values
       cause the planner to try to avoid evaluating the function more often
       than necessary.

<TT
CLASS="REPLACEABLE"
>result_rows</TT
>

       A positive number giving the estimated number of rows that the planner
       should expect the function to return.  This is only allowed when the
       function is declared to return a set.  The default assumption is
       1000 rows.

<TT
CLASS="REPLACEABLE"
>configuration_parameter</TT
>
<TT
CLASS="REPLACEABLE"
>value</TT
>

       The <TT
CLASS="LITERAL"
>SET</TT
> clause causes the specified configuration
       parameter to be set to the specified value when the function is
       entered, and then restored to its prior value when the function exits.
       <TT
CLASS="LITERAL"
>SET FROM CURRENT</TT
> saves the session's current value of
       the parameter as the value to be applied when the function is entered.

       If a <TT
CLASS="LITERAL"
>SET</TT
> clause is attached to a function, then
       the effects of a <TT
CLASS="COMMAND"
>SET LOCAL</TT
> command executed inside the
       function for the same variable are restricted to the function: the
       configuration parameter's prior value is still restored at function exit.
       However, an ordinary
       <TT
CLASS="COMMAND"
>SET</TT
> command (without <TT
CLASS="LITERAL"
>LOCAL</TT
>) overrides the
       <TT
CLASS="LITERAL"
>SET</TT
> clause, much as it would do for a previous <TT
CLASS="COMMAND"
>SET
       LOCAL</TT
> command: the effects of such a command will persist after
       function exit, unless the current transaction is rolled back.

       See SET and
       Chapter 18
       for more information about allowed parameter names and values.

<TT
CLASS="REPLACEABLE"
>definition</TT
>

       A string constant defining the function; the meaning depends on the
       language.  It can be an internal function name, the path to an
       object file, an SQL command, or text in a procedural language.

       It is often helpful to use dollar quoting (see Section 4.1.2.4) to write the function definition
       string, rather than the normal single quote syntax.  Without dollar
       quoting, any single quotes or backslashes in the function definition must
       be escaped by doubling them.

<TT
CLASS="LITERAL"
><TT
CLASS="REPLACEABLE"
>obj_file</TT
>, <TT
CLASS="REPLACEABLE"
>link_symbol</TT
></TT
>

       This form of the <TT
CLASS="LITERAL"
>AS</TT
> clause is used for
       dynamically loadable C language functions when the function name
       in the C language source code is not the same as the name of
       the SQL function. The string <TT
CLASS="REPLACEABLE"
>obj_file</TT
> is the name of the
       file containing the dynamically loadable object, and
       <TT
CLASS="REPLACEABLE"
>link_symbol</TT
> is the
       function's link symbol, that is, the name of the function in the C
       language source code.  If the link symbol is omitted, it is assumed
       to be the same as the name of the SQL function being defined.

       When repeated <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
> calls refer to
       the same object file, the file is only loaded once per session.
       To unload and
       reload the file (perhaps during development), start a new session.

<TT
CLASS="REPLACEABLE"
>attribute</TT
>

       The historical way to specify optional pieces of information
       about the function.  The following attributes can appear here:

<TT
CLASS="LITERAL"
>isStrict</TT
>

          Equivalent to <TT
CLASS="LITERAL"
>STRICT</TT
> or <TT
CLASS="LITERAL"
>RETURNS NULL ON NULL INPUT</TT
>.

<TT
CLASS="LITERAL"
>isCachable</TT
>

<TT
CLASS="LITERAL"
>isCachable</TT
> is an obsolete equivalent of
          <TT
CLASS="LITERAL"
>IMMUTABLE</TT
>; it's still accepted for
          backwards-compatibility reasons.

      Attribute names are not case-sensitive.

    Refer to Section 35.3 for further information on writing
    functions.

Overloading

    PostgreSQL allows function
    overloading; that is, the same name can be
    used for several different functions so long as they have distinct
    input argument types.  However, the C names of all functions must be
    different, so you must give overloaded C functions different C
    names (for example, use the argument types as part of the C
    names).

    Two functions are considered the same if they have the same names and
    input argument types, ignoring any <TT
CLASS="LITERAL"
>OUT</TT
>
    parameters.  Thus for example these declarations conflict:

CREATE FUNCTION foo(int) ...
CREATE FUNCTION foo(int, out text) ...

    Functions that have different argument type lists will not be considered
    to conflict at creation time, but if defaults are provided they might
    conflict in use.  For example, consider

CREATE FUNCTION foo(int) ...
CREATE FUNCTION foo(int, int default 42) ...

    A call <TT
CLASS="LITERAL"
>foo(10)</TT
> will fail due to the ambiguity about which
    function should be called.

Notes

    The full <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> type syntax is allowed for
    declaring a function's arguments and return value.  However,
    parenthesized type modifiers (e.g., the precision field for
    type <TT
CLASS="TYPE"
>numeric</TT
>) are discarded by <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
>.
    Thus for example
    <TT
CLASS="LITERAL"
>CREATE FUNCTION foo (varchar(10)) ...</TT
>
    is exactly the same as
    <TT
CLASS="LITERAL"
>CREATE FUNCTION foo (varchar) ...</TT
>.

    When replacing an existing function with <TT
CLASS="COMMAND"
>CREATE OR REPLACE
    FUNCTION</TT
>, there are restrictions on changing parameter names.
    You cannot change the name already assigned to any input parameter
    (although you can add names to parameters that had none before).
    If there is more than one output parameter, you cannot change the
    names of the output parameters, because that would change the
    column names of the anonymous composite type that describes the
    function's result.  These restrictions are made to ensure that
    existing calls of the function do not stop working when it is replaced.

    If a function is declared <TT
CLASS="LITERAL"
>STRICT</TT
> with a <TT
CLASS="LITERAL"
>VARIADIC</TT
>
    argument, the strictness check tests that the variadic array as
    a whole is non-null.  The function will still be called if the
    array has null elements.

Examples

   Here are some trivial examples to help you get started.  For more
   information and examples, see Section 35.3.

CREATE FUNCTION add(integer, integer) RETURNS integer
    AS 'select $1 + $2;'
    LANGUAGE SQL
    IMMUTABLE
    RETURNS NULL ON NULL INPUT;

   Increment an integer, making use of an argument name, in
   PL/pgSQL:

CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
        BEGIN
                RETURN i + 1;
        END;
$$ LANGUAGE plpgsql;

   Return a record containing multiple output parameters:

CREATE FUNCTION dup(in int, out f1 int, out f2 text)
    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
    LANGUAGE SQL;

SELECT * FROM dup(42);

   You can do the same thing more verbosely with an explicitly named
   composite type:

CREATE TYPE dup_result AS (f1 int, f2 text);

CREATE FUNCTION dup(int) RETURNS dup_result
    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
    LANGUAGE SQL;

SELECT * FROM dup(42);

   Another way to return multiple columns is to use a <TT
CLASS="LITERAL"
>TABLE</TT
>
   function:

CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
    LANGUAGE SQL;

SELECT * FROM dup(42);

   However, a <TT
CLASS="LITERAL"
>TABLE</TT
> function is different from the
   preceding examples, because it actually returns a set
   of records, not just one record.

Writing <TT
CLASS="LITERAL"
>SECURITY DEFINER</TT
> Functions Safely

    Because a <TT
CLASS="LITERAL"
>SECURITY DEFINER</TT
> function is executed
    with the privileges of the user that created it, care is needed to
    ensure that the function cannot be misused.  For security,
    search_path should be set to exclude any schemas
    writable by untrusted users.  This prevents
    malicious users from creating objects that mask objects used by the
    function.  Particularly important in this regard is the
    temporary-table schema, which is searched first by default, and
    is normally writable by anyone.  A secure arrangement can be had
    by forcing the temporary schema to be searched last.  To do this,
    write <TT
CLASS="LITERAL"
>pg_temp</TT
> as the last entry in <TT
CLASS="VARNAME"
>search_path</TT
>.
    This function illustrates safe usage:

CREATE FUNCTION check_password(uname TEXT, pass TEXT)
RETURNS BOOLEAN AS $$
DECLARE passed BOOLEAN;
BEGIN
        SELECT  (pwd = $2) INTO passed
        FROM    pwds
        WHERE   username = $1;

        RETURN passed;
END;
$$  LANGUAGE plpgsql
    SECURITY DEFINER
    -- Set a secure search_path: trusted schema(s), then 'pg_temp'.
    SET search_path = admin, pg_temp;

    Before PostgreSQL version 8.3, the
    <TT
CLASS="LITERAL"
>SET</TT
> option was not available, and so older functions may
    contain rather complicated logic to save, set, and restore
    <TT
CLASS="VARNAME"
>search_path</TT
>.  The <TT
CLASS="LITERAL"
>SET</TT
> option is far easier
    to use for this purpose.

    Another point to keep in mind is that by default, execute privilege
    is granted to <TT
CLASS="LITERAL"
>PUBLIC</TT
> for newly created functions
    (see GRANT for more
    information).  Frequently you will wish to restrict use of a security
    definer function to only some users.  To do that, you must revoke
    the default <TT
CLASS="LITERAL"
>PUBLIC</TT
> privileges and then grant execute
    privilege selectively.  To avoid having a window where the new function
    is accessible to all, create it and set the privileges within a single
    transaction.  For example:

BEGIN;
CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER;
REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
COMMIT;

Compatibility

   A <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
> command is defined in SQL:1999 and later.
   The PostgreSQL version is similar but
   not fully compatible.  The attributes are not portable, neither are the
   different available languages.

   For compatibility with some other database systems,
   <TT
CLASS="REPLACEABLE"
>argmode</TT
> can be written
   either before or after <TT
CLASS="REPLACEABLE"
>argname</TT
>.
   But only the first way is standard-compliant.

   The SQL standard does not specify parameter defaults.  The syntax
   with the <TT
CLASS="LITERAL"
>DEFAULT</TT
> key word is from Oracle, and it
   is somewhat in the spirit of the standard: SQL/PSM uses it for
   variable default values.  The syntax with <TT
CLASS="LITERAL"
>=</TT
> is
   used in T-SQL and Firebird.

See Also
ALTER FUNCTION, DROP FUNCTION, GRANT, LOAD, REVOKE, createlang

Prev	Home	Next

CREATE FOREIGN TABLE	Up	CREATE GROUP


text:
package metrics

import "github.com/czerwonk/bird_exporter/protocol"

// LabelStrategy abstracts the label generation for protocol metrics
type LabelStrategy interface {
	// LabelNames is the list of label names
	LabelNames(p *protocol.Protocol) []string

	// Label values is the list of values for the labels specified in `LabelNames()`
	LabelValues(p *protocol.Protocol) []string
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

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

#### Published in
null

#### Original name
Poa asthenes Roem. & Schult.

### Remarks
null


text:
"""Tests for `tf.data.Dataset.from_tensors()."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from absl.testing import parameterized
import numpy as np

from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.data.kernel_tests import checkpoint_test_base
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.util import nest
from tensorflow.python.framework import combinations
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops.ragged import ragged_factory_ops
from tensorflow.python.platform import test

class FromTensorsTest(test_base.DatasetTestBase, parameterized.TestCase):

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensors(self):
    """Test a dataset that represents a single tuple of tensors."""
    components = (np.array(1), np.array([1, 2, 3]), np.array(37.0))

    dataset = dataset_ops.Dataset.from_tensors(components)

    self.assertEqual(
        [c.shape for c in components],
        nest.flatten(dataset_ops.get_legacy_output_shapes(dataset)))

    self.assertDatasetProduces(dataset, expected_output=[components])

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsDataset(self):
    """Test a dataset that represents a dataset."""
    dataset = dataset_ops.Dataset.from_tensors(dataset_ops.Dataset.range(10))
    dataset = dataset.flat_map(lambda x: x)
    self.assertDatasetProduces(dataset, expected_output=range(10))

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsTensorArray(self):
    """Test a dataset that represents a TensorArray."""
    components = (
        tensor_array_ops.TensorArray(dtypes.float32, element_shape=(), size=2)
        .unstack([1.0, 2.0]))

    dataset = dataset_ops.Dataset.from_tensors(components)

    self.assertDatasetProduces(
        dataset, expected_output=[[1.0, 2.0]], requires_initialization=True)

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsSparse(self):
    """Test a dataset that represents a single tuple of tensors."""
    components = (sparse_tensor.SparseTensorValue(
        indices=np.array([[0]]),
        values=np.array([0]),
        dense_shape=np.array([1])),
                  sparse_tensor.SparseTensorValue(
                      indices=np.array([[0, 0], [1, 1]]),
                      values=np.array([-1, 1]),
                      dense_shape=np.array([2, 2])))

    dataset = dataset_ops.Dataset.from_tensors(components)

    self.assertEqual(
        [tensor_shape.TensorShape(c.dense_shape) for c in components],
        [shape for shape in dataset_ops.get_legacy_output_shapes(dataset)])
    self.assertDatasetProduces(dataset, expected_output=[components])

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsMixed(self):
    """Test an dataset that represents a single tuple of tensors."""
    components = (np.array(1), np.array([1, 2, 3]), np.array(37.0),
                  sparse_tensor.SparseTensorValue(
                      indices=np.array([[0]]),
                      values=np.array([0]),
                      dense_shape=np.array([1])),
                  sparse_tensor.SparseTensorValue(
                      indices=np.array([[0, 0], [1, 1]]),
                      values=np.array([-1, 1]),
                      dense_shape=np.array([2, 2])))

    dataset = dataset_ops.Dataset.from_tensors(components)
    self.assertEqual([
        tensor_shape.TensorShape(c.dense_shape)
        if sparse_tensor.is_sparse(c) else c.shape for c in components
    ], [shape for shape in dataset_ops.get_legacy_output_shapes(dataset)])

    self.assertDatasetProduces(dataset, expected_output=[components])

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsRagged(self):
    components = (
        ragged_factory_ops.constant_value([[[0]], [[1]], [[2]]]),
        ragged_factory_ops.constant_value([[[3]], [[4]], [[5]]]),
    )

    dataset = dataset_ops.Dataset.from_tensors(components)

    self.assertDatasetProduces(dataset, expected_output=[components])

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsMixedRagged(self):
    components = (np.array(1), np.array([1, 2, 3]), np.array(37.0),
                  sparse_tensor.SparseTensorValue(
                      indices=np.array([[0]]),
                      values=np.array([0]),
                      dense_shape=np.array([1])),
                  sparse_tensor.SparseTensorValue(
                      indices=np.array([[0, 0], [1, 1]]),
                      values=np.array([-1, 1]),
                      dense_shape=np.array([2, 2])),
                  ragged_factory_ops.constant_value([[[0]], [[1]], [[2]]]))

    dataset = dataset_ops.Dataset.from_tensors(components)

    self.assertDatasetProduces(dataset, expected_output=[components])

  @combinations.generate(
      combinations.combine(
          tf_api_version=[1],
          mode=["graph"],
          components=(np.array([1, 2, 3], dtype=np.int64),
                      (np.array([4., 5.]), np.array(
                          [6., 7.])), np.array([8, 9, 10], dtype=np.int64)),
          expected_shapes=[[[None, 3], [None, 3], [None, 2], [None, 2]]]) +
      combinations.combine(
          tf_api_version=[1],
          mode=["eager"],
          components=(np.array([1, 2, 3], dtype=np.int64),
                      (np.array([4., 5.]), np.array(
                          [6., 7.])), np.array([8, 9, 10], dtype=np.int64)),
          expected_shapes=[[[1, 3], [1, 3], [1, 2], [1, 2]]]))
  def testNestedStructure(self, components, expected_shapes):
    dataset = dataset_ops.Dataset.from_tensors(components)
    dataset = dataset.map(lambda x, y, z: ((x, z), (y[0], y[1])))

    dataset = dataset.flat_map(
        lambda x, y: dataset_ops.Dataset.from_tensors(
            ((x[0], x[1]), (y[0], y[1])))).batch(32)

    get_next = self.getNext(dataset)
    (w, x), (y, z) = get_next()
    self.assertEqual(dtypes.int64, w.dtype)
    self.assertEqual(dtypes.int64, x.dtype)
    self.assertEqual(dtypes.float64, y.dtype)
    self.assertEqual(dtypes.float64, z.dtype)
    self.assertEqual(expected_shapes, [
        w.shape.as_list(),
        x.shape.as_list(),
        y.shape.as_list(),
        z.shape.as_list()
    ])

    get_next = self.getNext(dataset)
    (w, x), (y, z) = get_next()
    self.assertEqual(dtypes.int64, w.dtype)
    self.assertEqual(dtypes.int64, x.dtype)
    self.assertEqual(dtypes.float64, y.dtype)
    self.assertEqual(dtypes.float64, z.dtype)
    self.assertEqual(expected_shapes, [
        w.shape.as_list(),
        x.shape.as_list(),
        y.shape.as_list(),
        z.shape.as_list()
    ])

  @combinations.generate(test_base.default_test_combinations())
  def testNestedDict(self):
    components = {"a": {"aa": 1, "ab": [2.0, 2.0]}, "b": [3, 3, 3]}
    dataset = dataset_ops.Dataset.from_tensors(components)
    self.assertEqual(dtypes.int32,
                     dataset_ops.get_legacy_output_types(dataset)["a"]["aa"])
    self.assertEqual(dtypes.float32,
                     dataset_ops.get_legacy_output_types(dataset)["a"]["ab"])
    self.assertEqual(dtypes.int32,
                     dataset_ops.get_legacy_output_types(dataset)["b"])
    self.assertEqual([],
                     dataset_ops.get_legacy_output_shapes(dataset)["a"]["aa"])
    self.assertEqual([2],
                     dataset_ops.get_legacy_output_shapes(dataset)["a"]["ab"])
    self.assertEqual([3],
                     dataset_ops.get_legacy_output_shapes(dataset)["b"])

  @combinations.generate(test_base.default_test_combinations())
  def testNonSequenceNestedStructure(self):
    components = np.array([1, 2, 3], dtype=np.int64)

    dataset = dataset_ops.Dataset.from_tensors(components)
    self.assertEqual(dtypes.int64,
                     dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual([3], dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.filter(
        lambda x: math_ops.reduce_all(math_ops.equal(x, components)))
    self.assertEqual(dtypes.int64,
                     dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual([3], dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.map(lambda x: array_ops.stack([x, x]))
    self.assertEqual(dtypes.int64,
                     dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual([2, 3], dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.flat_map(
        lambda x: dataset_ops.Dataset.from_tensor_slices(x))
    self.assertEqual(dtypes.int64,
                     dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual([3], dataset_ops.get_legacy_output_shapes(dataset))

    get_next = self.getNext(dataset)
    self.assertEqual(dtypes.int64, get_next().dtype)
    self.assertEqual([3], get_next().shape)

  # TODO(b/121264236): needs mechanism for multiple device in eager mode.
  @combinations.generate(test_base.graph_only_combinations())
  def testSplitPipeline(self):
    with session.Session(
        target="",
        config=config_pb2.ConfigProto(device_count={"CPU": 2})) as sess:

      dataset = dataset_ops.Dataset.from_tensors(0)

      # Define a pipeline that attempts to use variables on two
      # different devices.
      #
      # Initialize the variables before creating to iterator, to avoid the
      # placement algorithm overriding the DT_RESOURCE colocation constraints.
      with ops.device("/cpu:0"):
        var_0 = resource_variable_ops.ResourceVariable(initial_value=1)
      dataset = dataset.map(lambda x: x + var_0.read_value())
      sess.run(var_0.initializer)

      with ops.device("/cpu:1"):
        var_1 = resource_variable_ops.ResourceVariable(initial_value=1)
      dataset = dataset.map(lambda x: x + var_1.read_value())
      sess.run(var_1.initializer)

      iterator = dataset_ops.make_initializable_iterator(dataset)
      sess.run(iterator.initializer)

      self.assertEqual(sess.run(iterator.get_next()), 2)

class FromTensorsCheckpointTest(checkpoint_test_base.CheckpointTestBase,
                                parameterized.TestCase):

  def _build_tensor_dataset(self, variable_array):
    components = (variable_array, np.array([1, 2, 3]), np.array(37.0))

    return dataset_ops.Dataset.from_tensors(components)

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsCore(self):
    # Equal length components
    arr = np.array(1)
    num_outputs = 1
    self.run_core_tests(lambda: self._build_tensor_dataset(arr), num_outputs)

if __name__ == "__main__":
  test.main()


text:
package com.haulmont.cuba.gui.config;

import com.haulmont.cuba.gui.screen.FrameOwner;

/**
 * Interface for runnable classes of a menu item in menu config.
 */
public interface MenuItemRunnable {
    /**
     * Runs action of menu item. Called by the menu UI component when menu item triggered by a user.
     *
     * @param origin   origin screen
     * @param menuItem menu item
     */
    void run(FrameOwner origin, MenuItem menuItem);
}


text:
layout:         post
category:       podcast
title:          "FKI0055 Switching Protocols"
date:           2019-05-22 23:30:00+02:00
recording_date: 2019-05-22 21:00:00+02:00
file_url:       "https://s3.eu-central-1.amazonaws.com/feinkost-intenet/fki0055.mp3"
file_duration:  "01:10:09"
file_size:      50703271
permalink:      /:title
team:
- josa
- robert
- thomas
---

Hauchdünne Kompetenz gedünstet über einem schwall heißer Luft bildet auch in dieser Folge den sämigen Spiegel auf dem serviert wird, was weg muss.

### Themen

- Game Of Thrones Richtigstellung
- Challenge Nachbesprechung
- Thomas hatte Spaß mit UnityMedia
- Österreich
  - http://dotheyknowitseurope.eu
- Huawei wird boycotiert
- Wahl-O-Mat is offline
- [Rezo ja lol ey: Die Zerstörung der CDU](https://youtu.be/4Y1lZQsyuSQ)
- Thomas nimmt jetzt Klavierunterricht
- Thomas sagt: "Kunst is too damm teuer"
  - [James Jean](http://www.jamesjean.com/)

### Picks

- Thomas:
  - [Strange Planet By @nathanwpyle ](https://www.instagram.com/nathanwpylestrangeplanet/)
  - URL shortener: [FCK AFDe](https://fckaf.de/)


text:
import React, {PropTypes, Component} from 'react';
import moment from 'moment';
import classNames from 'classnames';

export default class MeetingItem extends Component {
  static propTypes = {
    location: PropTypes.string,
    summary: PropTypes.string,
    start: PropTypes.object,
    end: PropTypes.object,
    attendees: PropTypes.array,
    id: PropTypes.string
  }
  constructor(props) {
    super(props);
    this.state = {expanded: false};
  }
  toggleCard() {
    this.setState({expanded: !this.state.expanded});
  }
  renderAttendees(attendees) {
    return attendees.map( person => {
      if (person.displayName) {
        if (person.displayName.split(' ').length > 1) {
      // let headshot = 'http://www.brooklynunited.com/images/brooklyn-united-header-gear.gif';
      // fbUtils.getUserImage(person, res => {
      //   headshot = res;
      // });
          return (

{person.displayName}

            //
          );
        }
      }
    });
  }
  render() {
    const {location, summary, start, end, attendees} = this.props;
    let meetingLoc = '';
    if (location) meetingLoc = location.toLowerCase();
    return (

{summary}

          {(start && start.dateTime) &&

              {moment(start.dateTime).format('MMM D, YYYY h:mm a') + ' - '}
              {moment(end.dateTime).format('h:mm a')}

          }
          {(start && start.date) &&

              {moment(start.date).format('MMM D, YYYY')}

              All day

          }
          {attendees &&

{this.renderAttendees(attendees)}

          }
          {location &&

{location}

          }

        {/*

{summary}

          {start &&

              {moment(start.dateTime).format('MMM D, YYYY h:mm a') + ' - '}
              {moment(end.dateTime).format('h:mm a')}

          }
          {attendees &&

{this.renderAttendees(attendees)}

          }

{location}

 */}

    );
  }
}


text:
<?php
namespace Concrete\Core\Page\Controller;

use PageController as CorePageController;

class PageTypeController extends CorePageController
{
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('polls', '0047_auto_20160717_1541'),
    ]

    operations = [
        migrations.CreateModel(
            name='ConditionalItem',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ],
        ),
        migrations.RemoveField(
            model_name='combination',
            name='dependencies',
        ),
        migrations.RemoveField(
            model_name='combination',
            name='response',
        ),
        migrations.AddField(
            model_name='conditionalitem',
            name='combination',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Combination'),
        ),
        migrations.AddField(
            model_name='conditionalitem',
            name='items',
            field=models.ManyToManyField(to='polls.Item'),
        ),
        migrations.AddField(
            model_name='conditionalitem',
            name='response',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='polls.Response'),
        ),
    ]


text:
package org.redisson;

import io.netty.util.concurrent.Future;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ExecutionException;

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.redisson.core.RSet;
import org.redisson.core.RSortedSet;

public class RedissonSetTest extends BaseTest {

    public static class SimpleBean implements Serializable {

        private Long lng;

        public Long getLng() {
            return lng;
        }

        public void setLng(Long lng) {
            this.lng = lng;
        }

    }

    @Test
    public void testAddBean() throws InterruptedException, ExecutionException {
        SimpleBean sb = new SimpleBean();
        sb.setLng(1L);
        RSet<SimpleBean> set = redisson.getSet("simple");
        set.add(sb);
        Assert.assertEquals(sb.getLng(), set.iterator().next().getLng());
    }

    @Test
    public void testAddLong() throws InterruptedException, ExecutionException {
        Long sb = 1l;

        RSet<Long> set = redisson.getSet("simple_longs");
        set.add(sb);

        for (Long l : set) {
            Assert.assertEquals(sb.getClass(), l.getClass());
        }

        Object[] arr = set.toArray();

        for (Object o : arr) {
            Assert.assertEquals(sb.getClass(), o.getClass());
        }
    }

    @Test
    public void testAddAsync() throws InterruptedException, ExecutionException {
        RSet<Integer> set = redisson.getSet("simple");
        Future<Boolean> future = set.addAsync(2);
        Assert.assertTrue(future.get());

        Assert.assertTrue(set.contains(2));
    }

    @Test
    public void testRemoveAsync() throws InterruptedException, ExecutionException {
        RSet<Integer> set = redisson.getSet("simple");
        set.add(1);
        set.add(3);
        set.add(7);

        Assert.assertTrue(set.removeAsync(1).get());
        Assert.assertFalse(set.contains(1));
        Assert.assertThat(set, Matchers.containsInAnyOrder(3, 7));

        Assert.assertFalse(set.removeAsync(1).get());
        Assert.assertThat(set, Matchers.containsInAnyOrder(3, 7));

        set.removeAsync(3).get();
        Assert.assertFalse(set.contains(3));
        Assert.assertThat(set, Matchers.contains(7));
    }

    @Test
    public void testIteratorRemove() {
        Set<String> list = redisson.getSet("list");
        list.add("1");
        list.add("4");
        list.add("2");
        list.add("5");
        list.add("3");

        for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
            String value = iterator.next();
            if (value.equals("2")) {
                iterator.remove();
            }
        }

        Assert.assertThat(list, Matchers.containsInAnyOrder("1", "4", "5", "3"));

        int iteration = 0;
        for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
            iterator.next();
            iterator.remove();
            iteration++;
        }

        Assert.assertEquals(4, iteration);

        Assert.assertEquals(0, list.size());
        Assert.assertTrue(list.isEmpty());
    }

    @Test
    public void testIteratorSequence() {
        Set<Long> set = redisson.getSet("set");
        for (int i = 0; i < 1000; i++) {
            set.add(Long.valueOf(i));
        }

        Set<Long> setCopy = new HashSet<Long>();
        for (int i = 0; i < 1000; i++) {
            setCopy.add(Long.valueOf(i));
        }

        checkIterator(set, setCopy);
    }

    private void checkIterator(Set<Long> set, Set<Long> setCopy) {
        for (Iterator<Long> iterator = set.iterator(); iterator.hasNext();) {
            Long value = iterator.next();
            if (!setCopy.remove(value)) {
                Assert.fail();
            }
        }

        Assert.assertEquals(0, setCopy.size());
    }

    @Test
    public void testLong() {
        Set<Long> set = redisson.getSet("set");
        set.add(1L);
        set.add(2L);

        Assert.assertThat(set, Matchers.containsInAnyOrder(1L, 2L));
    }

    @Test
    public void testRetainAll() {
        Set<Integer> set = redisson.getSet("set");
        for (int i = 0; i < 20000; i++) {
            set.add(i);
        }

        Assert.assertTrue(set.retainAll(Arrays.asList(1, 2)));
        Assert.assertThat(set, Matchers.containsInAnyOrder(1, 2));
        Assert.assertEquals(2, set.size());
    }

//    @Test
//    public void testIteratorRemoveHighVolume() {
//        Set<Integer> set = redisson.getSet("set") /*new HashSet<Integer>()*/;
//        for (int i = 0; i < 120000; i++) {
//            set.add(i);
//        }
//        int cnt = 0;
//        Iterator<Integer> iterator = set.iterator();
//        while (iterator.hasNext()) {
//            Integer integer = iterator.next();
//            if (integer > -1) { // always
//                iterator.remove();
//            }
//            cnt++;
//        }
//        System.out.println("-----------");
//        for (Integer integer : set) {
//            System.out.println(integer);
//        }
//        Assert.assertEquals(20000, cnt);
//    }

    @Test
    public void testContainsAll() {
        Set<Integer> set = redisson.getSet("set");
        for (int i = 0; i < 200; i++) {
            set.add(i);
        }

        Assert.assertTrue(set.containsAll(Arrays.asList(30, 11)));
        Assert.assertFalse(set.containsAll(Arrays.asList(30, 711, 11)));
    }

    @Test
    public void testToArray() {
        Set<String> set = redisson.getSet("set");
        set.add("1");
        set.add("4");
        set.add("2");
        set.add("5");
        set.add("3");

        MatcherAssert.assertThat(Arrays.asList(set.toArray()), Matchers.<Object>containsInAnyOrder("1", "2", "4", "5", "3"));

        String[] strs = set.toArray(new String[0]);
        MatcherAssert.assertThat(Arrays.asList(strs), Matchers.containsInAnyOrder("1", "4", "2", "5", "3"));
    }

    @Test
    public void testContains() {
        Set<TestObject> set = redisson.getSet("set");

        set.add(new TestObject("1", "2"));
        set.add(new TestObject("1", "2"));
        set.add(new TestObject("2", "3"));
        set.add(new TestObject("3", "4"));
        set.add(new TestObject("5", "6"));

        Assert.assertTrue(set.contains(new TestObject("2", "3")));
        Assert.assertTrue(set.contains(new TestObject("1", "2")));
        Assert.assertFalse(set.contains(new TestObject("1", "9")));
    }

    @Test
    public void testDuplicates() {
        Set<TestObject> set = redisson.getSet("set");

        set.add(new TestObject("1", "2"));
        set.add(new TestObject("1", "2"));
        set.add(new TestObject("2", "3"));
        set.add(new TestObject("3", "4"));
        set.add(new TestObject("5", "6"));

        Assert.assertEquals(4, set.size());
    }

    @Test
    public void testSize() {
        Set<Integer> set = redisson.getSet("set");
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(3);
        set.add(4);
        set.add(5);
        set.add(5);

        Assert.assertEquals(5, set.size());
    }

    @Test
    public void testRetainAllEmpty() {
        Set<Integer> set = redisson.getSet("set");
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(4);
        set.add(5);

        Assert.assertTrue(set.retainAll(Collections.<Integer>emptyList()));
        Assert.assertEquals(0, set.size());
    }

    @Test
    public void testRetainAllNoModify() {
        Set<Integer> set = redisson.getSet("set");
        set.add(1);
        set.add(2);

        Assert.assertFalse(set.retainAll(Arrays.asList(1, 2))); // nothing changed
        Assert.assertThat(set, Matchers.containsInAnyOrder(1, 2));
    }
}


text:
namespace Mordor {

size_t
Stream::read(void *buffer, size_t length)
{
    MORDOR_ASSERT(supportsRead());
    Buffer internalBuffer;
    internalBuffer.adopt(buffer, length);
    size_t result = read(internalBuffer, length);
    MORDOR_ASSERT(result <= length);
    MORDOR_ASSERT(internalBuffer.readAvailable() == result);
    if (result == 0u)
        return 0;
    std::vector<iovec> iovs = internalBuffer.readBuffers(result);
    MORDOR_ASSERT(!iovs.empty());
    // It wrote directly into our buffer
    if (iovs.front().iov_base == buffer && iovs.front().iov_len == result)
        return result;
    bool overlapping = false;
    for (std::vector<iovec>::iterator it = iovs.begin();
        it != iovs.end();
        ++it) {
        if (it->iov_base >= buffer || it->iov_base <=
            (unsigned char *)buffer + length) {
            overlapping = true;
            break;
        }
    }
    // It didn't touch our buffer at all; it's safe to just copyOut
    if (!overlapping) {
        internalBuffer.copyOut(buffer, result);
        return result;
    }
    // We have to allocate *another* buffer so we don't destroy any data while
    // copying to our buffer
    boost::scoped_array<unsigned char> extraBuffer(new unsigned char[result]);
    internalBuffer.copyOut(extraBuffer.get(), result);
    memcpy(buffer, extraBuffer.get(), result);
    return result;
}

size_t
Stream::read(Buffer &buffer, size_t length)
{
    return read(buffer, length, false);
}

size_t
Stream::read(Buffer &buffer, size_t length, bool coalesce)
{
    MORDOR_ASSERT(supportsRead());
    iovec iov = buffer.writeBuffer(length, coalesce);
    size_t result = read(iov.iov_base, iov.iov_len);
    buffer.produce(result);
    return result;
}

size_t
Stream::write(const char *string)
{
    return write(string, strlen(string));
}

size_t
Stream::write(const void *buffer, size_t length)
{
    MORDOR_ASSERT(supportsWrite());
    Buffer internalBuffer;
    internalBuffer.copyIn(buffer, length);
    return write(internalBuffer, length);
}

size_t
Stream::write(const Buffer &buffer, size_t length)
{
    return write(buffer, length, false);
}

size_t
Stream::write(const Buffer &buffer, size_t length, bool coalesce)
{
    MORDOR_ASSERT(supportsWrite());
    const iovec iov = buffer.readBuffer(length, coalesce);
    return write(iov.iov_base, iov.iov_len);
}

long long
Stream::seek(long long offset, Anchor anchor)
{
    MORDOR_NOTREACHED();
}

long long
Stream::size()
{
    MORDOR_NOTREACHED();
}

void
Stream::truncate(long long size)
{
    MORDOR_NOTREACHED();
}

ptrdiff_t
Stream::find(char delimiter, size_t sanitySize, bool throwIfNotFound)
{
    MORDOR_NOTREACHED();
}

ptrdiff_t
Stream::find(const std::string &delimiter, size_t sanitySize,
    bool throwIfNotFound)
{
    MORDOR_NOTREACHED();
}

std::string
Stream::getDelimited(char delim, bool eofIsDelimiter, bool includeDelimiter)
{
    ptrdiff_t offset = find(delim, ~0, !eofIsDelimiter);
    eofIsDelimiter = offset < 0;
    if (offset < 0)
        offset = -offset - 1;
    std::string result;
    result.resize(offset + (eofIsDelimiter ? 0 : 1));
    MORDOR_VERIFY(read((char *)result.c_str(), result.size())
        == result.size());
    if (!eofIsDelimiter && !includeDelimiter)
        result.resize(result.size() - 1);
    return result;
}

std::string
Stream::getDelimited(const std::string &delim, bool eofIsDelimiter,
    bool includeDelimiter)
{
    ptrdiff_t offset = find(delim, ~0, !eofIsDelimiter);
    eofIsDelimiter = offset < 0;
    if (offset < 0)
        offset = -offset - delim.size();
    std::string result;
    result.resize(offset + (eofIsDelimiter ? 0 : delim.size()));
    MORDOR_VERIFY(read((char *)result.c_str(), result.size())
        == result.size());
    if (!eofIsDelimiter && !includeDelimiter)
        result.resize(result.size() - delim.size());
    return result;
}

void
Stream::unread(const Buffer &buffer, size_t length)
{
    MORDOR_NOTREACHED();
}

}


text:
/**
 Created by Michal Bluma for WCMTL2015
 */

(function ($) {

	if (typeof DIAGRAMMAR === 'undefined') {
		DIAGRAMMAR = {};
	}

	DIAGRAMMAR.showCss = {
		init                : function () {
			var _this = DIAGRAMMAR.showCss;

			_this.$mainContainer = $('.diagrammar-container');

			if (_this.$mainContainer.length > 0) {

				_this.$allItems = _this.$mainContainer.find('.diag-item');
				_this.createDebugBox();
				_this.gatherCssInformation();
				_this.refreshDebugBox();
				_this.makeMoveable();
				_this.makeSelectable();

				_this.addAlignButton();
				_this.bindEvents();
			}
		},
		bindEvents          : function () {
			var _this = DIAGRAMMAR.showCss;

			_this.$alignButton.on('click', function () {
				_this.alignVertical();
			});

		},
		gatherCssInformation: function () {
			var _this = DIAGRAMMAR.showCss;

			_this.arrCssInfo = [];

			_this.$allItems.each(function () {
				var $this = $(this),
					positionLeft = Math.floor($this.position().left),
					positionTop = Math.floor($this.position().top),
					itemInfo = {
						'id'  : $this.attr('id'),
						'left': positionLeft,
						'top' : positionTop,
						'item': $this
					};

				$this.data('pos-left', positionLeft).data('pos-top', positionTop);
				_this.arrCssInfo.push(itemInfo);

			});

			console.table(_this.arrCssInfo);

		},
		makeMoveable        : function () {
			var _this = DIAGRAMMAR.showCss;

			_this.$allItems.each(function () {
				var $this = $(this);

				$this.css({
					'position': 'absolute',
					'left'    : $this.data('pos-left'),
					'top'     : $this.data('pos-top')
				});
			});

			_this.$allItems.draggable({
				stop: function (event, ui) {
					_this.gatherCssInformation();
					_this.updateContainer();
					_this.refreshDebugBox();
				}
			});

		},
		createDebugBox      : function () {
			var _this = DIAGRAMMAR.showCss;

			_this.$debugBox = $('
').appendTo('body');

		},
		refreshDebugBox     : function () {
			var _this = DIAGRAMMAR.showCss;

			var htmlOutput = '';

			htmlOutput += '
'
			htmlOutput += '
'
			htmlOutput += '
#' + _this.$mainContainer.attr('id') + ' {
';
			htmlOutput += '
height: ' + _this.$mainContainer.css('height') + '
';
			htmlOutput += '
width: ' + _this.$mainContainer.css('width') + '
';
			htmlOutput += '}
'; // debug-item-info
			htmlOutput += '
'; // debug-section

			for (var i = 0; i < _this.arrCssInfo.length; i++) {
				var itemInfo = _this.arrCssInfo[i];

				htmlOutput += '
'
				htmlOutput += '
'
				htmlOutput += '
#' + itemInfo['id'] + ' {
';
				htmlOutput += '
top: ' + itemInfo['top'] + 'px
';
				htmlOutput += '
left: ' + itemInfo['left'] + 'px
';
				htmlOutput += '}
'; // debug-item-info
				htmlOutput += '
'; // debug-section

			}

			_this.$debugBox.html(htmlOutput);
		},
		updateContainer     : function () {
			var _this = DIAGRAMMAR.showCss;

			var maxTop = 0,
				maxLeft = 0,
				$mostTop,
				$mostLeft;

			for (var i = 0; i < _this.arrCssInfo.length; i++) {
				var obj = _this.arrCssInfo[i],
					itemTop = obj['top'],
					itemHeight = obj['item'].outerHeight(),
					itemTopmost = itemTop + itemHeight,
					itemLeft = obj['left'],
					itemWidth = obj['item'].outerWidth(),
					itemLeftmost = itemLeft + itemWidth;

				if (itemTopmost > maxTop) {
					maxTop = itemTopmost;
				}

				if (itemLeftmost > maxLeft) {
					maxLeft = itemLeftmost;
				}

			}

			_this.$mainContainer.css({
				'width' : maxLeft,
				'height': maxTop
			});

		},
		makeSelectable      : function () {
			var _this = DIAGRAMMAR.showCss;

			_this.$mainContainer.selectable({
				appendTo: _this.$mainContainer
			});
		},
		addAlignButton      : function () {
			var _this = DIAGRAMMAR.showCss;

			_this.$alignButton = $('<button class="diagrammar-align-button">Align</button>').appendTo('body');
		},
		alignVertical       : function () {
			var _this = DIAGRAMMAR.showCss;

			var $selectedItems = _this.$allItems.filter('.ui-selected'),
				minTop = 99999999;

			if ($selectedItems.length > 0) {

				$selectedItems.each(function () {
					var $this = $(this),
						itemTop = $this.position().top;

					console.log('minTop: ', minTop, '   itemTop: ', itemTop);
					minTop = itemTop < minTop ? itemTop : minTop;
				});

				$selectedItems.css({
					top: minTop
				});

				_this.gatherCssInformation();
				_this.updateContainer();
				_this.refreshDebugBox();
			}
		}
	}

	$(document).ready(function () {
		DIAGRAMMAR.showCss.init();
	});
})(jQuery);


text:
package sun.awt.X11;

import java.awt.*;
import java.util.logging.*;

/**
 * This class represent focus holder window implementation. When toplevel requests or receives focus
 * it instead sets focus to this proxy. This proxy is mapped but invisible(it is kept at (-1,-1))
 * and therefore X doesn't control focus after we have set it to proxy.
 */
public class XFocusProxyWindow extends XBaseWindow {
    XWindowPeer owner;

    public XFocusProxyWindow(XWindowPeer owner) {
        super(new XCreateWindowParams(new Object[] {
            BOUNDS, new Rectangle(-1, -1, 1, 1),
            PARENT_WINDOW, new Long(owner.getWindow()),
            EVENT_MASK, new Long(FocusChangeMask | KeyPressMask | KeyReleaseMask)
        }));
        this.owner = owner;
    }

    public void postInit(XCreateWindowParams params){
        super.postInit(params);
        setWMClass(getWMClass());
        xSetVisible(true);
    }

    protected String getWMName() {
        return "FocusProxy";
    }
    protected String[] getWMClass() {
        return new String[] {"Focus-Proxy-Window", "FocusProxy"};
    }

    public XWindowPeer getOwner() {
        return owner;
    }

    public void dispatchEvent(XEvent ev) {
        int type = ev.get_type();
        switch (type)
        {
          case XlibWrapper.FocusIn:
          case XlibWrapper.FocusOut:
              handleFocusEvent(ev);
              break;
        }
        super.dispatchEvent(ev);
    }

    public void handleFocusEvent(XEvent xev) {
        owner.handleFocusEvent(xev);
    }

    public void handleKeyPress(XEvent xev) {
        owner.handleKeyPress(xev);
    }

    public void handleKeyRelease(XEvent xev) {
        owner.handleKeyRelease(xev);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.belive.weather</groupId>
        <artifactId>weather-api</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>weather-api-owm</artifactId>
    <packaging>jar</packaging>
    <name>Weather Api Open Weather Map</name>

    <dependencies>
        <dependency>
            <groupId>com.belive.weather</groupId>
            <artifactId>weather-api-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>${compile.encoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
package net.techreadiness.persistence.datagrid;

import net.techreadiness.service.common.DataGridItemProvider;
import net.techreadiness.service.object.Org;

public interface OrgByUserItemProvider extends DataGridItemProvider<Org> {
	abstract void setUserId(Long userId);

	void setScopeId(Long scopeId);

}


text:
jSmart is a port of the Smarty Template Engine to Javascript, a JavaScript template library that supports the template [syntax](https://github.com/miroshnikov/jsmart/blob/wiki/syntax.md) and all the features (functions, variable modifiers, etc.) of the well-known PHP template engine [Smarty] (http://www.smarty.net).

jSmart is written entirely in JavaScript, does not have any DOM/DHTML/browser or third-party JavaScript library dependencies and can be run in a web browser as well as Node.js.

jSmart supports plugin architecture, you can [extend it with custom plugins](https://github.com/miroshnikov/jsmart/blob/wiki/CreatePlugin.md): functions, blocks and variable modifiers, [templates inclusion](https://github.com/miroshnikov/jsmart/blob/wiki/IncludeTemplates.md), [templates inheritance and overriding](https://github.com/miroshnikov/jsmart/blob/wiki/Template_inheritance.md), [caching](https://github.com/miroshnikov/jsmart/blob/wiki/caching.md), [escape HTML](https://github.com/miroshnikov/jsmart/blob/wiki/escape_html.md).

jSmart has some limited support of the PHP syntax and allows you to [use the same Smarty templates on both server and client side](https://github.com/miroshnikov/jsmart/blob/wiki/Smarty_template_in_javascript.md), for both PHP and Javascript.

See the overview of the basic syntax of jSmart templates [here](https://github.com/miroshnikov/jsmart/blob/wiki/syntax.md)

[**Demo page**](https://jsfiddle.net/miroshnikov/6tfz9p3z/1/) play with it at JsFiddle

[**Discussion board**](http://groups.google.com/group/jsmartdiscussion) feel free to ask questions, share your ideas, etc.

##Usage

* **Browser**
```html
<script type="text/javascript" src="smart.min.js"></script>
```
```javascript
<script id="tpl" type="text/x-smarty-tmpl">
   Hello {$who}!
</script>

<script>
   var tplText = document.getElementById('tpl').innerHTML;
   var compiled = new jSmart( tplText );
   var res = compiled.fetch( { who:'world' } );  //res = Hello world!
</script>
```

* **Node.js**
```
npm install smarty.js
```
```javascript
var Smarty = require('smarty.js');
var fs = require('fs');

Smarty.prototype.getTemplate = function(name) {
   return fs.readFileSync('./templates/'+name, {encoding: 'utf-8'});
}

var tplText = fs.readFileSync('./templates/main.tpl', {encoding: 'utf-8'});
var compiled = new Smarty(tplText);
var res = compiled.fetch({...});
```

* **Require.js**
```javascript
require(['smart'], function(Smarty){
   var compiled = new Smarty("Hello {$who}!");
   var res = compiled.fetch({who:'world'});
});
```

* **Bower**
```
bower install smarty
```

**Note**: The template's text is compiled in the constructor, so it's fast to call ```fetch()``` with different assigned variables many times.
```javascript
var compiled = new jSmart( '{$greeting}, {$name}!' );
compiled.fetch( {greeting:'Hello', name:'John'} ); //Hello, John!
compiled.fetch( {greeting:'Hi', name:'Jane'} );    //Hi, Jane!
```


text:
configuration RebootRequired
{
    Import-DscResource -ModuleName PSDesiredStateConfiguration

    Script reboot
    {
        GetScript = {@{}}
        SetScript = {$global:DSCMachineStatus = 1}
        TestScript = {$false}
    }
}


text:
import {LitElement, html} from "lit";
import Utils from "./../../../core/utils.js";
import UtilsNew from "../../../core/utils-new.js";

/**
 * Consequence type filter as list of checkboxes. This has been deprecated in favor of consequence-type-select-filter
 * @deprecated
 */
export default class ConsequenceTypeFilter extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            consequenceTypes: {
                type: Object
            },
            ct: {
                type: String
            }
        };
    }

    _init() {
        this._prefix = "ctf-" + UtilsNew.randomString(6) + "_";
        this.selectedCt = [];
        $("select.selectpicker", this).selectpicker("render");
        $('.select.selectpicker', this).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
            console.log(e,clickedIndex,isSelected,previousValue)
        });

    }

    updated(_changedProperties) {
        if (_changedProperties.has("ct")) {
            if (this.ct) {
                this.selectedCt = this.ct.split(",");
            } else {
                $("input[type=checkbox]", this).prop("checked", false);
            }
            this.requestUpdate();
        }
    }

    filterChange(e) {
        const ct = this.ct ? this.ct : null;
        console.log("filterChange", ct);
        const event = new CustomEvent("filterChange", {
            detail: {
                value: ct
            }
        });
        this.dispatchEvent(event);
    }

    clearSelection() {
        $("input[type=checkbox]", this).prop("checked", false);
        this.ct = "";
        this.filterChange();
    }

    onChange(e) {
        // TODO refactor!
        const lofCheckBox = this.querySelector("#" + this._prefix + "LossOfFunctionCheckBox");
        console.log("e.currentTarget", e.currentTarget.id)
        if (e.currentTarget.id === this._prefix + "LossOfFunctionCheckBox") {
            for (const ct of this.consequenceTypes.lof) {
                const checkbox = this.querySelector("#" + this._prefix + ct + "Checkbox");
                if (checkbox) {
                    checkbox.checked = e.currentTarget.checked;
                }
            }
        }

        console.log("currentTarget.dataset.category",e.currentTarget.dataset.category)
        // Select/Unselect the items from one category
        if (e.currentTarget.dataset.category) {
            $("#" + e.currentTarget.dataset.category + " ul li input").each(function() {
                $(this).prop("checked", e.target.checked);
            });
        }
        const soTerms = [];
        const selected = this.querySelector("#" + this._prefix + "consequenceTypeFilter").querySelectorAll("li input");
        selected.forEach(sel => {
            if (sel.checked && typeof sel.dataset !== "undefined" && typeof sel.dataset.id !== "undefined") {
                soTerms.push(sel.dataset.id);
            } else {
                // If one term from LoF array is not selected we remove LoF check
                const dataId = sel.getAttribute("data-id");
                if (lofCheckBox.checked && UtilsNew.isNotUndefinedOrNull(dataId) && this.consequenceTypes.lof.includes(dataId)) {
                    lofCheckBox.checked = false;
                }
            }
        });

        this.ct = soTerms.join(",");
        this.selectedCt = soTerms;
        this.filterChange();

        // TODO onSelect an item, this refers to the whole category and to the the title of the category
        // this will be useful to automatially select the category checkbox when all the items in it are selected (useful with saved filters as well)
        // console.log("checked: ", $("input[type=checkbox]", e.target.parentNode.parentNode.parentNode).length)
        // console.log("total: ", $("input[type=checkbox]:checked", e.target.parentNode.parentNode.parentNode).length)
        // console.log("title", e.target.parentNode.parentNode.parentNode.parentNode.id)
    }

    render() {
        return html`

            <button class="btn btn-sm" @click="${this.clearSelection}">clear</button>

Loss-of-Function (LoF) terms:

                    <input id="${this._prefix}LossOfFunctionCheckBox" type="checkbox" class="${this._prefix}FilterCheckBox"
                               style="cursor: pointer" @change="${this.onChange}"/>
                    LoF terms

Consequence Type terms:

                    ${this.consequenceTypes.categories && this.consequenceTypes.categories.length && this.consequenceTypes.categories.map(category => html`

                            ${category.terms && category.terms.length ? html`
                                <input id="${this._prefix}${category.title}Input" type="checkbox" class="${this._prefix}FilterCheckBox" data-category="${category.title}" @change="${this.onChange}">
                                ${category.title}

                                    ${category.terms.map(item => html`

                                        <input id="${this._prefix}${item.name}Checkbox" type="checkbox" data-id="${item.name}"
                                                   class="soTermCheckBox ${this._prefix}FilterCheckBox" @change="${this.onChange}" ?checked="${~this.selectedCt.indexOf(item.name)}">

                                                ${item.name}

                                        (${item.id})

                                    `)}

                                ` : html`
                                    <input id="${this._prefix}${category.name}Checkbox" type="checkbox"
                                        data-id="${category.name}" class="soTermCheckBox ${this._prefix}FilterCheckBox" @change="${this.onChange}" ?checked="${~this.selectedCt.indexOf(category.name)}">

                                            ${category.name}

                                    (${category.id})
                                `}

                    `)}

        `;
    }

}

customElements.define("consequence-type-filter", ConsequenceTypeFilter);


text:
/* {#
       Core materialization implementation. BigQuery and Snowflake are similar
       because both can use `create or replace view` where the resulting view schema
       is not necessarily the same as the existing view. On Redshift, this would
       result in: ERROR:  cannot change number of columns in view

       This implementation is superior to the create_temp, swap_with_existing, drop_old
       paradigm because transactions don't run DDL queries atomically on Snowflake. By using
       `create or replace view`, the materialization becomes atomic in nature.
#} */

{% macro create_or_replace_view() %}
  {%- set identifier = model['alias'] -%}

  {%- set old_relation = adapter.get_relation(database=database, schema=schema, identifier=identifier) -%}

  {%- set exists_as_view = (old_relation is not none and old_relation.is_view) -%}

  {%- set target_relation = api.Relation.create(
      identifier=identifier, schema=schema, database=database,
      type='view') -%}

  {{ run_hooks(pre_hooks) }}

  -- If there's a table with the same name and we weren't told to full refresh,
  -- that's an error. If we were told to full refresh, drop it. This behavior differs
  -- for Snowflake and BigQuery, so multiple dispatch is used.
  {%- if old_relation is not none and old_relation.is_table -%}
    {{ handle_existing_table(should_full_refresh(), old_relation) }}
  {%- endif -%}

  -- build model
  {% call statement('main') -%}
    {{ get_create_view_as_sql(target_relation, sql) }}
  {%- endcall %}

  {{ run_hooks(post_hooks) }}

  {{ return({'relations': [target_relation]}) }}

{% endmacro %}


text:
package money.machine

import Akka._

import java.time.LocalTime
import java.time.temporal.ChronoUnit

import scala.collection.Map
import scala.concurrent.duration.DurationDouble
import scala.util.{Failure, Success}

/**
  * provides balances of registered exchanges (see #withExchanges)
  */
object ExchangeBalances {

  type Balances = Map[Token, BigDecimal]

  val intervalInSec = 8 seconds
  val maxAgeInSec = 25

  private val balances = scala.collection.mutable.Map[Exchange[_], (LocalTime, Balances)]()

  def sufficientBalance[C <: Coin, CC <: Currency](buyOrder: BuyOrder[_, C, CC]): Boolean = {
    val balance = get(buyOrder.exchange, buyOrder.currency)
    if (!balance.isDefined) {
      println(s"warn: balances not defined for ${buyOrder.exchange}")
      true
    } else if (balance.get < buyOrder.volume.price.amount) {
      println(s"warn: insufficient balances for order $buyOrder")
      false
    } else true
  }

  def sufficientBalance[C <: Coin, CC <: Currency](newOrder: NewOrder[_, C, CC]): Boolean = newOrder match {
    case bo@BuyOrder(_,_) => sufficientBalance(bo)
    case so@SellOrder(_,_) => sufficientBalance(so)
  }

  def sufficientBalance[C <: Coin, CC <: Currency](sellOrder: SellOrder[_, C, CC]): Boolean = {
    val balance = get(sellOrder.exchange, sellOrder.coin)
    if (!balance.isDefined) {
      println(s"warn: balances not defined for ${sellOrder.exchange}")
      true
    } else if (balance.get < sellOrder.volume.coinVolume) {
      println(s"warn: insufficient balances for order $sellOrder")
      false
    } else true
  }

  def get(exchange: Exchange[_], token: Token): Option[BigDecimal] = {
    balances synchronized {
      for {
        bs <- balances.get(exchange)
        ageInSec = bs._1.until(LocalTime.now(), ChronoUnit.SECONDS)
        if (ageInSec < maxAgeInSec)
        b <- bs._2.get(token)
      } yield b
    }
  }

  // total coin volume
  def sum(coin: Coin): BigDecimal = {
    balances.keys
      .map(e => get(e, coin).get)
      .fold(BigDecimal(0))((x,y) => x + y)
  }

  // total available sum
  def sum[CC<:Currency](cc: CC): Price[CC] = {
    balances.keys
      .map(e => get(e, cc).get)
      .foldLeft(Price(0, cc))((acc,amount) => Price(acc.amount + amount, cc))
  }

  // available coin + available currency in coin volume
  def sum(coin: Coin, currency: Currency): BigDecimal = {
    sum(coin) + MoneyMachine.averagePriceRate(coin, currency)(balances.keys.toList).coinVolume(sum(currency)).coinVolume
  }

  private def remove(exchange: Exchange[_]) = {
    balances synchronized {
      balances.remove(exchange)
    }
  }

  private def update(exchange: Exchange[_], exchangeBalances: Balances) = {
    balances synchronized {
      balances.put(exchange, (LocalTime.now(), exchangeBalances))
    }
  }

  def withAllExchanges(): Unit = {
    withExchanges(Exchange.exchanges:_*)
  }

  def withExchanges(exchanges: Exchange[_]*): Unit = {
    exchanges.filter(e => balances.get(e).isEmpty).foreach(e => fetch(e))
  }

  private def fetch(exchanges: Exchange[_]*): Unit = {

    def delayed(f: => Unit) = {
      Akka.actorSystem.scheduler.scheduleOnce(delay = intervalInSec)(f)
    }

    exchanges.foreach { e =>
      e.balances.onComplete {
        case Success(b) => update(e, b); delayed(fetch(e))
        case Failure(t) => println(s"exception (balances): ${t.getMessage}"); remove(e); delayed(fetch(e))
      }
    }
  }
}


text:
#pragma once

#ifndef _INPUT_MANAGER_H
#define _INPUT_MANAGER_H

/**********************
*   System Includes   *
***********************/

/*************************
*   3rd Party Includes   *
**************************/

/***************************
*   Game Engine Includes   *
****************************/
#include "InputDefs.h"

/********************
*   Forward Decls   *
*********************/
class Keyboard;
class XBoxGamepadManager;

/*****************
*   Class Decl   *
******************/

class InputManager sealed : public AEObject
{
    private:

    /************************
    *   Private Variables   *
    *************************/
#pragma region Private Variables

        /// <summary>
        /// Handles the Keyboard Input.
        /// </summary>
        Keyboard* m_Keyboard = nullptr;

        /// <summary>
        /// Handles the XBox Gamepad Input.
        /// </summary>
        XBoxGamepadManager* m_XBoxGamepadManager = nullptr;

        /// <summary>
        /// Defines if the class has been initialize and is ready to run.
        /// </summary>
        bool m_IsReady = false;

#pragma endregion

        /**********************
        *   Private Methods   *
        ***********************/
#pragma region Private Methods

        /// <summary>
        /// Cleans up the memory use by the manager.
        /// </summary>
        void CleanUp();

#pragma endregion

    public:

    /***************************************
    *   Constructor & Destructor Methods   *
    ****************************************/
#pragma region Constructor & Destructor Methods

        /// <summary>
        /// Default InputManager Constructor
        /// </summary>
        InputManager();

        /// <summary>
        /// Default InputManager Destructor
        /// </summary>
        virtual ~InputManager();

        //Delete copy constructor/operator
        InputManager(const InputManager&) = delete;
        InputManager& operator=(const InputManager&) = delete;

#pragma endregion

    /******************
    *   Get Methods   *
    *******************/
#pragma region Get Methods

        /// <summary>
        /// Get the Keyboard Input Handler
        /// </summary>
        inline Keyboard* GetKeyboard() const
        {
            return m_Keyboard;
        }

        /// <summary>
        /// Gets the XBox Gamepad Input Handler.
        /// </summary>
        inline XBoxGamepadManager* GetXBoxGamepadManager() const
        {
            return m_XBoxGamepadManager;
        }

#pragma endregion

    /******************
    *   Set Methods   *
    *******************/
#pragma region Set Methods

#pragma endregion

    /************************
    *   Framework Methods   *
    *************************/
#pragma region Framework Methods

        AEResult Initialize(const GameConfigInput& configInput);

        void ProcessKeyboardWindows(TCHAR keyCode, bool isExtended, bool isDown);

        void ReloadKeyboardLaylout();

        void LoseFocus();

        bool IsKeyboardActive() const;

        bool IsXBoxGamepadManagerActive() const;

#pragma endregion

};

#endif


text:
/**
  Mail utility module.

  @module utils
*/

"use strict";

var buffer = require("buffer");
var encodingUtils = require("encoding");

var quotedPrintableRegex = /=[0-9a-fA-F][0-9a-fA-F]/g;

/**
  This class is is just a container for some class methods. It seems yuidocjs
  doesn't support documentation of functions that are outside of classes.

  @class Utils
*/
var Utils = function() {
};

/**
  Decode all quoted-printable characters in the text.

  @method decodeQuotedPrintable
  @static
  @param text {String} The string containing quoted-printable character
    sequences.
  @return {String} Returns the decoded text. If the input text is null or
    undefined, null is returned.
*/
Utils.decodeQuotedPrintable = function(text) {
  if(text == null) {
    return null;
  }
  return text.replace(quotedPrintableRegex, function(part) {
    var code = parseInt(part.substring(1), 16);
    return String.fromCharCode(code);
  });
};

/**
  Convert an input text from a given input encoding.

  @method convert
  @static
  @param text {string} The text to be converted.
  @param encoding {string} The encoding (either an encoding supported
    directly by the nodejs buffer module or the 8bit or quoted-printable
    encoding).
  @return Returns either a Buffer (for encodings natively supported by the
    buffer module) or a string for other encodings. You need to test for the
    result type yourself and convert the result to what you need.
*/
Utils.convert = function(text, encoding) {
  encoding = encoding.toLowerCase();
  if(buffer.Buffer.isEncoding(encoding)) {
    return new buffer.Buffer(text, encoding);
  } else {
    if(encoding === "quoted-printable") {
      return Utils.decodeQuotedPrintable(text);
    }
    // a transfer encoding of 7bit or 8bit has no effect on the input
    // text. in this case, no transformations are applied and the actual
    // encoding is determined by the content type.
    return text;
  }
};

var mimeWordRegex = /=\?([^?]*)\?([^?]*)\?([^?]*)\?=/g;

/**
  Decodes the given text using the charset and encoding.

  @method decodeMimeWord
  @static
  @param charset {String} The name of the (input) charset.
  @param encoding {String} A single character specifying the encoding
    of the text. This can be either "Q" for quoted printable or "B" for
    base64.
  @param text {String} The encoded text.
  @return Returns the decoded text as a string. If text is null or undefined,
    the function returns null. Otherwise, a string is returned.
*/
Utils.decodeMimeWord = function(charset, encoding, text) {
  if(text == null) {
    return null;
  }
  charset = charset.toLowerCase();
  encoding = encoding.toLowerCase();
  text = Utils.convert(text, (encoding === "b" ? "base64" : "quoted-printable"));
  text = typeof(text) === "string" ? text : text.toString("binary");
  return encodingUtils.convert(text, "utf8", charset);
};

/**
  Decodes the header value of an e-mail or MIME part header by decoding the
  =?charset?encoding?text?= parts. The result is a utf8 string.

  @method decodeMimeHeaderValue
  @static
  @param text {String} The text (aka the value of the header field) to be
    decoded.
  @return {String} Returns a utf8 string with all MIME words being decoded.
*/
Utils.decodeMimeHeaderValue = function(text) {
  var match;
  var result = "";
  var start = 0;
  while((match = mimeWordRegex.exec(text)) != null) {
    result += text.substring(start, match.index);
    var charset = match[1], encoding = match[2], encodedText = match[3];
    result += Utils.decodeMimeWord(charset, encoding, encodedText);
    start += encodedText.length;
  }
  if(start < text.length) {
    result += text.substring(start);
  }
  return result;
};

module.exports = Utils;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Discom. Bohem. (Prague) 357 (1934)

#### Original name
Ascophanus carneus var. sublividus Velen.

### Remarks
null