text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>

    Oracle
 —
    SQLAlchemy 1.0 Documentation

        </title>

                <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
                <link rel="stylesheet" href="../_static/changelog.css" type="text/css" />
                <link rel="stylesheet" href="../_static/sphinx_paramlinks.css" type="text/css" />
                <link rel="stylesheet" href="../_static/docs.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
        <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="SQLAlchemy 1.0 Documentation" href="../index.html" />
        <link rel="up" title="Dialects" href="index.html" />
        <link rel="next" title="PostgreSQL" href="postgresql.html" />
        <link rel="prev" title="MySQL" href="mysql.html" />

        Release: 1.0.6 | Release Date: June 25, 2015

SQLAlchemy 1.0 Documentation

SQLAlchemy 1.0 Documentation

                Contents |
                Index

                <form class="search" action="../search.html" method="get">
                  <input type="text" name="q" size="12" /> <input type="submit" value="Search" />
                  <input type="hidden" name="check_keywords" value="yes" />
                  <input type="hidden" name="area" value="default" />
                </form>

            Dialects

Firebird

Microsoft SQL Server

MySQL

Oracle¶

Support for the Oracle database.

Connect Arguments

Auto Increment Behavior

Identifier Casing

LIMIT/OFFSET Support

RETURNING Support

ON UPDATE CASCADE

Oracle 8 Compatibility

Synonym/DBLINK Reflection

DateTime Compatibility

Oracle Table Options

Oracle Specific Index Options

Bitmap Indexes

Index compression

Oracle Data Types

cx_Oracle

DBAPI

Connecting

Additional Connect Arguments

Unicode

RETURNING Support

LOB Objects

Two Phase Transaction Support

Precision Numerics

zxjdbc

DBAPI

Connecting

PostgreSQL

SQLite

Sybase

Oracle¶

Support for the Oracle database.

DBAPI Support¶

The following dialect/DBAPI options are available.  Please refer to individual DBAPI sections for connect information.

cx-Oracle

zxJDBC for Jython

Connect Arguments¶

The dialect supports several create_engine() arguments
which affect the behavior of the dialect regardless of driver in use.

use_ansi - Use ANSI JOIN constructs (see the section on Oracle 8).
Defaults to True.  If False, Oracle-8 compatible constructs are used
for joins.

optimize_limits - defaults to False. see the section on
LIMIT/OFFSET.

use_binds_for_limits - defaults to True.  see the section on
LIMIT/OFFSET.

Auto Increment Behavior¶

SQLAlchemy Table objects which include integer primary keys are usually
assumed to have “autoincrementing” behavior, meaning they can generate their
own primary key values upon INSERT.  Since Oracle has no “autoincrement”
feature, SQLAlchemy relies upon sequences to produce these values.   With the
Oracle dialect, a sequence must always be explicitly specified to enable
autoincrement.  This is divergent with the majority of documentation
examples which assume the usage of an autoincrement-capable database.   To
specify sequences, use the sqlalchemy.schema.Sequence object which is passed
to a Column construct:

t = Table('mytable', metadata,
      Column('id', Integer, Sequence('id_seq'), primary_key=True),
      Column(...), ...
)

This step is also required when using table reflection, i.e. autoload=True:

t = Table('mytable', metadata,
      Column('id', Integer, Sequence('id_seq'), primary_key=True),
      autoload=True
)

Identifier Casing¶

In Oracle, the data dictionary represents all case insensitive identifier
names using UPPERCASE text.   SQLAlchemy on the other hand considers an
all-lower case identifier name to be case insensitive.   The Oracle dialect
converts all case insensitive identifiers to and from those two formats during
schema level communication, such as reflection of tables and indexes.   Using
an UPPERCASE name on the SQLAlchemy side indicates a case sensitive
identifier, and SQLAlchemy will quote the name - this will cause mismatches
against data dictionary data received from Oracle, so unless identifier names
have been truly created as case sensitive (i.e. using quoted names), all
lowercase names should be used on the SQLAlchemy side.

LIMIT/OFFSET Support¶

Oracle has no support for the LIMIT or OFFSET keywords.  SQLAlchemy uses
a wrapped subquery approach in conjunction with ROWNUM.  The exact methodology
is taken from
http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html .

There are two options which affect its behavior:

the “FIRST ROWS()” optimization keyword is not used by default.  To enable
the usage of this optimization directive, specify optimize_limits=True
to create_engine().

the values passed for the limit/offset are sent as bound parameters.   Some
users have observed that Oracle produces a poor query plan when the values
are sent as binds and not rendered literally.   To render the limit/offset
values literally within the SQL statement, specify
use_binds_for_limits=False to create_engine().

Some users have reported better performance when the entirely different
approach of a window query is used, i.e. ROW_NUMBER() OVER (ORDER BY), to
provide LIMIT/OFFSET (note that the majority of users don’t observe this).
To suit this case the method used for LIMIT/OFFSET can be replaced entirely.
See the recipe at
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/WindowFunctionsByDefault
which installs a select compiler that overrides the generation of limit/offset
with a window function.

RETURNING Support¶

The Oracle database supports a limited form of RETURNING, in order to retrieve
result sets of matched rows from INSERT, UPDATE and DELETE statements.
Oracle’s RETURNING..INTO syntax only supports one row being returned, as it
relies upon OUT parameters in order to function.  In addition, supported
DBAPIs have further limitations (see RETURNING Support).

SQLAlchemy’s “implicit returning” feature, which employs RETURNING within an
INSERT and sometimes an UPDATE statement in order to fetch newly generated
primary key values and other SQL defaults and expressions, is normally enabled
on the Oracle backend.  By default, “implicit returning” typically only
fetches the value of a single nextval(some_seq) expression embedded into
an INSERT in order to increment a sequence within an INSERT statement and get
the value back at the same time. To disable this feature across the board,
specify implicit_returning=False to create_engine():

engine = create_engine("oracle://scott:tiger@dsn",
                       implicit_returning=False)

Implicit returning can also be disabled on a table-by-table basis as a table
option:

# Core Table
my_table = Table("my_table", metadata, ..., implicit_returning=False)

# declarative
class MyClass(Base):
    __tablename__ = 'my_table'
    __table_args__ = {"implicit_returning": False}

See also

RETURNING Support - additional cx_oracle-specific restrictions on
implicit returning.

ON UPDATE CASCADE¶

Oracle doesn’t have native ON UPDATE CASCADE functionality.  A trigger based
solution is available at
http://asktom.oracle.com/tkyte/update_cascade/index.html .

When using the SQLAlchemy ORM, the ORM has limited ability to manually issue
cascading updates - specify ForeignKey objects using the
“deferrable=True, initially=’deferred’” keyword arguments,
and specify “passive_updates=False” on each relationship().

Oracle 8 Compatibility¶

When Oracle 8 is detected, the dialect internally configures itself to the
following behaviors:

the use_ansi flag is set to False.  This has the effect of converting all
JOIN phrases into the WHERE clause, and in the case of LEFT OUTER JOIN
makes use of Oracle’s (+) operator.

the NVARCHAR2 and NCLOB datatypes are no longer generated as DDL when
the Unicode is used - VARCHAR2 and CLOB are
issued instead.   This because these types don’t seem to work correctly on
Oracle 8 even though they are available.  The
NVARCHAR and
NCLOB types will always generate
NVARCHAR2 and NCLOB.

the “native unicode” mode is disabled when using cx_oracle, i.e. SQLAlchemy
encodes all Python unicode objects to “string” before passing in as bind
parameters.

Synonym/DBLINK Reflection¶

When using reflection with Table objects, the dialect can optionally search
for tables indicated by synonyms, either in local or remote schemas or
accessed over DBLINK, by passing the flag oracle_resolve_synonyms=True as
a keyword argument to the Table construct:

some_table = Table('some_table', autoload=True,
                            autoload_with=some_engine,
                            oracle_resolve_synonyms=True)

When this flag is set, the given name (such as some_table above) will
be searched not just in the ALL_TABLES view, but also within the
ALL_SYNONYMS view to see if this name is actually a synonym to another
name.  If the synonym is located and refers to a DBLINK, the oracle dialect
knows how to locate the table’s information using DBLINK syntax(e.g.
@dblink).

oracle_resolve_synonyms is accepted wherever reflection arguments are
accepted, including methods such as MetaData.reflect() and
Inspector.get_columns().

If synonyms are not in use, this flag should be left disabled.

DateTime Compatibility¶

Oracle has no datatype known as DATETIME, it instead has only DATE,
which can actually store a date and time value.  For this reason, the Oracle
dialect provides a type oracle.DATE which is a subclass of
DateTime.   This type has no special behavior, and is only
present as a “marker” for this type; additionally, when a database column
is reflected and the type is reported as DATE, the time-supporting
oracle.DATE type is used.

Changed in version 0.9.4: Added oracle.DATE to subclass
DateTime.  This is a change as previous versions
would reflect a DATE column as types.DATE, which subclasses
Date.   The only significance here is for schemes that are
examining the type of column for use in special Python translations or
for migrating schemas to other database backends.

Oracle Table Options¶

The CREATE TABLE phrase supports the following options with Oracle
in conjunction with the Table construct:

ON COMMIT:

Table(
    "some_table", metadata, ...,
    prefixes=['GLOBAL TEMPORARY'], oracle_on_commit='PRESERVE ROWS')

New in version 1.0.0.

COMPRESS:

 Table('mytable', metadata, Column('data', String(32)),
     oracle_compress=True)

 Table('mytable', metadata, Column('data', String(32)),
     oracle_compress=6)

The ``oracle_compress`` parameter accepts either an integer compression
level, or ``True`` to use the default compression level.

New in version 1.0.0.

Oracle Specific Index Options¶

Bitmap Indexes¶

You can specify the oracle_bitmap parameter to create a bitmap index
instead of a B-tree index:

Index('my_index', my_table.c.data, oracle_bitmap=True)

Bitmap indexes cannot be unique and cannot be compressed. SQLAlchemy will not
check for such limitations, only the database will.

New in version 1.0.0.

Index compression¶

Oracle has a more efficient storage mode for indexes containing lots of
repeated values. Use the oracle_compress parameter to turn on key c
ompression:

Index('my_index', my_table.c.data, oracle_compress=True)

Index('my_index', my_table.c.data1, my_table.c.data2, unique=True,
       oracle_compress=1)

The oracle_compress parameter accepts either an integer specifying the
number of prefix columns to compress, or True to use the default (all
columns for non-unique indexes, all but the last column for unique indexes).

New in version 1.0.0.

Oracle Data Types¶

As with all SQLAlchemy dialects, all UPPERCASE types that are known to be
valid with Oracle are importable from the top level dialect, whether
they originate from sqlalchemy.types or from the local dialect:

from sqlalchemy.dialects.oracle import \
            BFILE, BLOB, CHAR, CLOB, DATE, \
            DOUBLE_PRECISION, FLOAT, INTERVAL, LONG, NCLOB, \
            NUMBER, NVARCHAR, NVARCHAR2, RAW, TIMESTAMP, VARCHAR, \
            VARCHAR2

Types which are specific to Oracle, or have Oracle-specific
construction arguments, are as follows:

class sqlalchemy.dialects.oracle.BFILE(length=None)¶

Bases: sqlalchemy.types.LargeBinary

__init__(length=None)¶

Construct a LargeBinary type.

<col class="field-name" />
<col class="field-body" />

Parameters:	length¶ – optional, a length for the column for use in
DDL statements, for those BLOB types that accept a length
(i.e. MySQL).  It does not produce a lengthed BINARY/VARBINARY
type - use the BINARY/VARBINARY types specifically for those.
May be safely omitted if no CREATE
TABLE will be issued.  Certain databases may require a
length for use in DDL, and will raise an exception when
the CREATE TABLE DDL is issued.

class sqlalchemy.dialects.oracle.DATE(timezone=False)¶

Bases: sqlalchemy.types.DateTime

Provide the oracle DATE type.

This type has no special Python behavior, except that it subclasses
types.DateTime; this is to suit the fact that the Oracle
DATE type supports a time value.

New in version 0.9.4.

__init__(timezone=False)¶

Construct a new DateTime.

<col class="field-name" />
<col class="field-body" />

Parameters:	timezone¶ – boolean.  If True, and supported by the
backend, will produce ‘TIMESTAMP WITH TIMEZONE’. For backends
that don’t support timezone aware timestamps, has no
effect.

class sqlalchemy.dialects.oracle.DOUBLE_PRECISION(precision=None, scale=None, asdecimal=None)¶

Bases: sqlalchemy.types.Numeric

class sqlalchemy.dialects.oracle.INTERVAL(day_precision=None, second_precision=None)¶

Bases: sqlalchemy.types.TypeEngine

__init__(day_precision=None, second_precision=None)¶

Construct an INTERVAL.

Note that only DAY TO SECOND intervals are currently supported.
This is due to a lack of support for YEAR TO MONTH intervals
within available DBAPIs (cx_oracle and zxjdbc).

<col class="field-name" />
<col class="field-body" />

Parameters:

day_precision¶ – the day precision value.  this is the number of
digits to store for the day field.  Defaults to “2”

second_precision¶ – the second precision value.  this is the
number of digits to store for the fractional seconds field.
Defaults to “6”.

class sqlalchemy.dialects.oracle.NCLOB(length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False)¶

Bases: sqlalchemy.types.Text

__init__(length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False)¶

Create a string-holding type.

<col class="field-name" />
<col class="field-body" />

Parameters:

length¶ – optional, a length for the column for use in
DDL and CAST expressions.  May be safely omitted if no CREATE
TABLE will be issued.  Certain databases may require a
length for use in DDL, and will raise an exception when
the CREATE TABLE DDL is issued if a VARCHAR
with no length is included.  Whether the value is
interpreted as bytes or characters is database specific.

collation¶ –
Optional, a column-level collation for
use in DDL and CAST expressions.  Renders using the
COLLATE keyword supported by SQLite, MySQL, and Postgresql.
E.g.:

>>> from sqlalchemy import cast, select, String
>>> print select([cast('some string', String(collation='utf8'))])
SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1

New in version 0.8: Added support for COLLATE to all
string types.

convert_unicode¶ –
When set to True, the
String type will assume that
input is to be passed as Python unicode objects,
and results returned as Python unicode objects.
If the DBAPI in use does not support Python unicode
(which is fewer and fewer these days), SQLAlchemy
will encode/decode the value, using the
value of the encoding parameter passed to
create_engine() as the encoding.

When using a DBAPI that natively supports Python
unicode objects, this flag generally does not
need to be set.  For columns that are explicitly
intended to store non-ASCII data, the Unicode
or UnicodeText
types should be used regardless, which feature
the same behavior of convert_unicode but
also indicate an underlying column type that
directly supports unicode, such as NVARCHAR.

For the extremely rare case that Python unicode
is to be encoded/decoded by SQLAlchemy on a backend
that does natively support Python unicode,
the value force can be passed here which will
cause SQLAlchemy’s encode/decode services to be
used unconditionally.

unicode_error¶ – Optional, a method to use to handle Unicode
conversion errors. Behaves like the errors keyword argument to
the standard library’s string.decode() functions.   This flag
requires that convert_unicode is set to force - otherwise,
SQLAlchemy is not guaranteed to handle the task of unicode
conversion.   Note that this flag adds significant performance
overhead to row-fetching operations for backends that already
return unicode objects natively (which most DBAPIs do).  This
flag should only be used as a last resort for reading
strings from a column with varied or corrupted encodings.

class sqlalchemy.dialects.oracle.NUMBER(precision=None, scale=None, asdecimal=None)¶

Bases: sqlalchemy.types.Numeric, sqlalchemy.types.Integer

class sqlalchemy.dialects.oracle.LONG(length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False)¶

Bases: sqlalchemy.types.Text

__init__(length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False)¶

Create a string-holding type.

<col class="field-name" />
<col class="field-body" />

Parameters:

length¶ – optional, a length for the column for use in
DDL and CAST expressions.  May be safely omitted if no CREATE
TABLE will be issued.  Certain databases may require a
length for use in DDL, and will raise an exception when
the CREATE TABLE DDL is issued if a VARCHAR
with no length is included.  Whether the value is
interpreted as bytes or characters is database specific.

collation¶ –
Optional, a column-level collation for
use in DDL and CAST expressions.  Renders using the
COLLATE keyword supported by SQLite, MySQL, and Postgresql.
E.g.:

>>> from sqlalchemy import cast, select, String
>>> print select([cast('some string', String(collation='utf8'))])
SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1

New in version 0.8: Added support for COLLATE to all
string types.

convert_unicode¶ –
When set to True, the
String type will assume that
input is to be passed as Python unicode objects,
and results returned as Python unicode objects.
If the DBAPI in use does not support Python unicode
(which is fewer and fewer these days), SQLAlchemy
will encode/decode the value, using the
value of the encoding parameter passed to
create_engine() as the encoding.

When using a DBAPI that natively supports Python
unicode objects, this flag generally does not
need to be set.  For columns that are explicitly
intended to store non-ASCII data, the Unicode
or UnicodeText
types should be used regardless, which feature
the same behavior of convert_unicode but
also indicate an underlying column type that
directly supports unicode, such as NVARCHAR.

For the extremely rare case that Python unicode
is to be encoded/decoded by SQLAlchemy on a backend
that does natively support Python unicode,
the value force can be passed here which will
cause SQLAlchemy’s encode/decode services to be
used unconditionally.

unicode_error¶ – Optional, a method to use to handle Unicode
conversion errors. Behaves like the errors keyword argument to
the standard library’s string.decode() functions.   This flag
requires that convert_unicode is set to force - otherwise,
SQLAlchemy is not guaranteed to handle the task of unicode
conversion.   Note that this flag adds significant performance
overhead to row-fetching operations for backends that already
return unicode objects natively (which most DBAPIs do).  This
flag should only be used as a last resort for reading
strings from a column with varied or corrupted encodings.

class sqlalchemy.dialects.oracle.RAW(length=None)¶

Bases: sqlalchemy.types._Binary

cx_Oracle¶

Support for the Oracle database via the cx-Oracle driver.

DBAPI¶

Documentation and download information (if applicable) for cx-Oracle is available at:
http://cx-oracle.sourceforge.net/

Connecting¶

Connect String:

oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]

Additional Connect Arguments¶

When connecting with dbname present, the host, port, and dbname tokens are
converted to a TNS name using
the cx_oracle makedsn() function.  Otherwise, the host token is taken
directly as a TNS name.

Additional arguments which may be specified either as query string arguments
on the URL, or as keyword arguments to create_engine() are:

allow_twophase - enable two-phase transactions.  Defaults to True.

arraysize - set the cx_oracle.arraysize value on cursors, defaulted
to 50.  This setting is significant with cx_Oracle as the contents of LOB
objects are only readable within a “live” row (e.g. within a batch of
50 rows).

auto_convert_lobs - defaults to True; See LOB Objects.

auto_setinputsizes - the cx_oracle.setinputsizes() call is issued for
all bind parameters.  This is required for LOB datatypes but can be
disabled to reduce overhead.  Defaults to True.  Specific types
can be excluded from this process using the exclude_setinputsizes
parameter.

coerce_to_unicode - see Unicode for detail.

coerce_to_decimal - see Precision Numerics for detail.

exclude_setinputsizes - a tuple or list of string DBAPI type names to
be excluded from the “auto setinputsizes” feature.  The type names here
must match DBAPI types that are found in the “cx_Oracle” module namespace,
such as cx_Oracle.UNICODE, cx_Oracle.NCLOB, etc.   Defaults to
(STRING, UNICODE).

New in version 0.8: specific DBAPI types can be excluded from the
auto_setinputsizes feature via the exclude_setinputsizes attribute.

mode - This is given the string value of SYSDBA or SYSOPER, or
alternatively an integer value.  This value is only available as a URL query
string argument.

threaded - enable multithreaded access to cx_oracle connections.
Defaults to True.  Note that this is the opposite default of the
cx_Oracle DBAPI itself.

service_name - An option to use connection string (DSN) with
SERVICE_NAME instead of SID. It can’t be passed when a database
part is given.
E.g. oracle+cx_oracle://scott:tiger@host:1521/?service_name=hr
is a valid url. This value is only available as a URL query string argument.

New in version 1.0.0.

Unicode¶

The cx_Oracle DBAPI as of version 5 fully supports unicode, and has the
ability to return string results as Python unicode objects natively.

When used in Python 3, cx_Oracle returns all strings as Python unicode objects
(that is, plain str in Python 3).  In Python 2, it will return as Python
unicode those column values that are of type NVARCHAR or NCLOB.  For
column values that are of type VARCHAR or other non-unicode string types,
it will return values as Python strings (e.g. bytestrings).

The cx_Oracle SQLAlchemy dialect presents two different options for the use
case of returning VARCHAR column values as Python unicode objects under
Python 2:

the cx_Oracle DBAPI has the ability to coerce all string results to Python
unicode objects unconditionally using output type handlers.  This has
the advantage that the unicode conversion is global to all statements
at the cx_Oracle driver level, meaning it works with raw textual SQL
statements that have no typing information associated.  However, this system
has been observed to incur signfiicant performance overhead, not only
because it takes effect for all string values unconditionally, but also
because cx_Oracle under Python 2 seems to use a pure-Python function call in
order to do the decode operation, which under cPython can orders of
magnitude slower than doing it using C functions alone.

SQLAlchemy has unicode-decoding services built in, and when using
SQLAlchemy’s C extensions, these functions do not use any Python function
calls and are very fast.  The disadvantage to this approach is that the
unicode conversion only takes effect for statements where the
Unicode type or String type with
convert_unicode=True is explicitly associated with the result column.
This is the case for any ORM or Core query or SQL expression as well as for
a text() construct that specifies output column types, so in the vast
majority of cases this is not an issue. However, when sending a completely
raw string to Connection.execute(), this typing information isn’t
present, unless the string is handled within a text() construct that
adds typing information.

As of version 0.9.2 of SQLAlchemy, the default approach is to use SQLAlchemy’s
typing system.  This keeps cx_Oracle’s expensive Python 2 approach
disabled unless the user explicitly wants it.  Under Python 3, SQLAlchemy
detects that cx_Oracle is returning unicode objects natively and cx_Oracle’s
system is used.

To re-enable cx_Oracle’s output type handler under Python 2, the
coerce_to_unicode=True flag (new in 0.9.4) can be passed to
create_engine():

engine = create_engine("oracle+cx_oracle://dsn", coerce_to_unicode=True)

Alternatively, to run a pure string SQL statement and get VARCHAR results
as Python unicode under Python 2 without using cx_Oracle’s native handlers,
the text() feature can be used:

from sqlalchemy import text, Unicode
result = conn.execute(
    text("select username from user").columns(username=Unicode))

Changed in version 0.9.2: cx_Oracle’s outputtypehandlers are no longer used
for unicode results of non-unicode datatypes in Python 2, after they were
identified as a major performance bottleneck.  SQLAlchemy’s own unicode
facilities are used instead.

New in version 0.9.4: Added the coerce_to_unicode flag, to re-enable
cx_Oracle’s outputtypehandler and revert to pre-0.9.2 behavior.

RETURNING Support¶

The cx_oracle DBAPI supports a limited subset of Oracle’s already limited
RETURNING support.  Typically, results can only be guaranteed for at most one
column being returned; this is the typical case when SQLAlchemy uses RETURNING
to get just the value of a primary-key-associated sequence value.
Additional column expressions will cause problems in a non-determinative way,
due to cx_oracle’s lack of support for the OCI_DATA_AT_EXEC API which is
required for more complex RETURNING scenarios.

For this reason, stability may be enhanced by disabling RETURNING support
completely; SQLAlchemy otherwise will use RETURNING to fetch newly
sequence-generated primary keys.  As illustrated in RETURNING Support:

engine = create_engine("oracle://scott:tiger@dsn",
                       implicit_returning=False)

See also

http://docs.oracle.com/cd/B10501_01/appdev.920/a96584/oci05bnd.htm#420693
- OCI documentation for RETURNING

http://sourceforge.net/mailarchive/message.php?msg_id=31338136
- cx_oracle developer commentary

LOB Objects¶

cx_oracle returns oracle LOBs using the cx_oracle.LOB object.  SQLAlchemy
converts these to strings so that the interface of the Binary type is
consistent with that of other backends, and so that the linkage to a live
cursor is not needed in scenarios like result.fetchmany() and
result.fetchall().   This means that by default, LOB objects are fully fetched
unconditionally by SQLAlchemy, and the linkage to a live cursor is broken.

To disable this processing, pass auto_convert_lobs=False to
create_engine().

Two Phase Transaction Support¶

Two Phase transactions are implemented using XA transactions, and are known
to work in a rudimental fashion with recent versions of cx_Oracle
as of SQLAlchemy 0.8.0b2, 0.7.10.   However, the mechanism is not yet
considered to be robust and should still be regarded as experimental.

In particular, the cx_Oracle DBAPI as recently as 5.1.2 has a bug regarding
two phase which prevents
a particular DBAPI connection from being consistently usable in both
prepared transactions as well as traditional DBAPI usage patterns; therefore
once a particular connection is used via Connection.begin_prepared(),
all subsequent usages of the underlying DBAPI connection must be within
the context of prepared transactions.

The default behavior of Engine is to maintain a pool of DBAPI
connections.  Therefore, due to the above glitch, a DBAPI connection that has
been used in a two-phase operation, and is then returned to the pool, will
not be usable in a non-two-phase context.   To avoid this situation,
the application can make one of several choices:

Disable connection pooling using NullPool

Ensure that the particular Engine in use is only used
for two-phase operations.   A Engine bound to an ORM
Session which includes twophase=True will consistently
use the two-phase transaction style.

For ad-hoc two-phase operations without disabling pooling, the DBAPI
connection in use can be evicted from the connection pool using the
Connection.detach() method.

Changed in version 0.8.0b2,0.7.10: Support for cx_oracle prepared transactions has been implemented
and tested.

Precision Numerics¶

The SQLAlchemy dialect goes through a lot of steps to ensure
that decimal numbers are sent and received with full accuracy.
An “outputtypehandler” callable is associated with each
cx_oracle connection object which detects numeric types and
receives them as string values, instead of receiving a Python
float directly, which is then passed to the Python
Decimal constructor.  The Numeric and
Float types under the cx_oracle dialect are aware of
this behavior, and will coerce the Decimal to float if
the asdecimal flag is False (default on Float,
optional on Numeric).

Because the handler coerces to Decimal in all cases first,
the feature can detract significantly from performance.
If precision numerics aren’t required, the decimal handling
can be disabled by passing the flag coerce_to_decimal=False
to create_engine():

engine = create_engine("oracle+cx_oracle://dsn", coerce_to_decimal=False)

New in version 0.7.6: Add the coerce_to_decimal flag.

Another alternative to performance is to use the
cdecimal library;
see Numeric for additional notes.

The handler attempts to use the “precision” and “scale”
attributes of the result set column to best determine if
subsequent incoming values should be received as Decimal as
opposed to int (in which case no processing is added). There are
several scenarios where OCI does not provide unambiguous data
as to the numeric type, including some situations where
individual rows may return a combination of floating point and
integer values. Certain values for “precision” and “scale” have
been observed to determine this scenario.  When it occurs, the
outputtypehandler receives as string and then passes off to a
processing function which detects, for each returned value, if a
decimal point is present, and if so converts to Decimal,
otherwise to int.  The intention is that simple int-based
statements like “SELECT my_seq.nextval() FROM DUAL” continue to
return ints and not Decimal objects, and that any kind of
floating point value is received as a string so that there is no
floating point loss of precision.

The “decimal point is present” logic itself is also sensitive to
locale.  Under OCI, this is controlled by the NLS_LANG
environment variable. Upon first connection, the dialect runs a
test to determine the current “decimal” character, which can be
a comma ”,” for European locales. From that point forward the
outputtypehandler uses that character to represent a decimal
point. Note that cx_oracle 5.0.3 or greater is required
when dealing with numerics with locale settings that don’t use
a period ”.” as the decimal character.

Changed in version 0.6.6: The outputtypehandler supports the case where the locale uses a
comma ”,” character to represent a decimal point.

zxjdbc¶

Support for the Oracle database via the zxJDBC for Jython driver.

Note

Jython is not supported by current versions of SQLAlchemy.  The
zxjdbc dialect should be considered as experimental.

DBAPI¶

Drivers for this database are available at:
http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html.

Connecting¶

Connect String:

oracle+zxjdbc://user:pass@host/dbname

        Previous:
        MySQL
        Next:
        PostgreSQL

        © Copyright 2007-2015, the SQLAlchemy authors and contributors.
        Created using Sphinx 1.3.1.


text:
@implementation BusinessException

@end

redpajama_set_name: RedPajamaGithub


text:
"""Test ClientSession support with asyncio."""

import copy
import sys
import unittest
from test import SkipTest
from test.asyncio_tests import AsyncIOTestCase, asyncio_test
from test.test_environment import env
from test.utils import TestListener, session_ids

from pymongo import IndexModel, InsertOne
from pymongo.errors import InvalidOperation

class TestAsyncIOSession(AsyncIOTestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        if not env.sessions_enabled:
            raise SkipTest("Sessions not supported")

    async def _test_ops(self, client, *ops):
        listener = client.options.event_listeners[0]

        for f, args, kw in ops:
            s = await client.start_session()
            # Simulate "async with" on Python 3.4.
            try:
                listener.results.clear()
                # In case "f" modifies its inputs.
                args2 = copy.copy(args)
                kw2 = copy.copy(kw)
                kw2["session"] = s
                await f(*args2, **kw2)
                for event in listener.results["started"]:
                    self.assertTrue(
                        "lsid" in event.command,
                        "%s sent no lsid with %s" % (f.__name__, event.command_name),
                    )

                    self.assertEqual(
                        s.session_id,
                        event.command["lsid"],
                        "%s sent wrong lsid with %s" % (f.__name__, event.command_name),
                    )

                self.assertFalse(s.has_ended)
            finally:
                await s.end_session()

            with self.assertRaisesRegex(InvalidOperation, "ended session"):
                await f(*args2, **kw2)

        # No explicit session.
        for f, args, kw in ops:
            listener.results.clear()
            await f(*args, **kw)
            self.assertGreaterEqual(len(listener.results["started"]), 1)
            lsids = []
            for event in listener.results["started"]:
                self.assertTrue(
                    "lsid" in event.command,
                    "%s sent no lsid with %s" % (f.__name__, event.command_name),
                )

                lsids.append(event.command["lsid"])

            if "PyPy" not in sys.version:
                # Server session was returned to pool. Ignore interpreters with
                # non-deterministic GC.
                for lsid in lsids:
                    self.assertIn(
                        lsid,
                        session_ids(client),
                        "%s did not return implicit session to pool" % (f.__name__,),
                    )

    @asyncio_test
    async def test_database(self):
        listener = TestListener()
        client = self.asyncio_client(event_listeners=[listener])

        db = client.pymongo_test
        ops = [
            (db.command, ["ping"], {}),
            (db.drop_collection, ["collection"], {}),
            (db.create_collection, ["collection"], {}),
            (db.list_collection_names, [], {}),
        ]

        await self._test_ops(client, *ops)

    @asyncio_test(timeout=60)
    async def test_collection(self):
        listener = TestListener()
        client = self.asyncio_client(event_listeners=[listener])
        await client.drop_database("motor_test")

        coll = client.motor_test.test_collection

        async def list_indexes(session=None):
            await coll.list_indexes(session=session).to_list(length=None)

        async def aggregate(session=None):
            await coll.aggregate([], session=session).to_list(length=None)

        # Test some collection methods - the rest are in test_cursor.
        await self._test_ops(
            client,
            (coll.drop, [], {}),
            (coll.bulk_write, [[InsertOne({})]], {}),
            (coll.insert_one, [{}], {}),
            (coll.insert_many, [[{}, {}]], {}),
            (coll.replace_one, [{}, {}], {}),
            (coll.update_one, [{}, {"$set": {"a": 1}}], {}),
            (coll.update_many, [{}, {"$set": {"a": 1}}], {}),
            (coll.delete_one, [{}], {}),
            (coll.delete_many, [{}], {}),
            (coll.find_one_and_replace, [{}, {}], {}),
            (coll.find_one_and_update, [{}, {"$set": {"a": 1}}], {}),
            (coll.find_one_and_delete, [{}, {}], {}),
            (coll.rename, ["collection2"], {}),
            # Drop collection2 between tests of "rename", above.
            (client.motor_test.drop_collection, ["collection2"], {}),
            (coll.distinct, ["a"], {}),
            (coll.find_one, [], {}),
            (coll.count_documents, [{}], {}),
            (coll.create_indexes, [[IndexModel("a")]], {}),
            (coll.create_index, ["a"], {}),
            (coll.drop_index, ["a_1"], {}),
            (coll.drop_indexes, [], {}),
            (list_indexes, [], {}),
            (coll.index_information, [], {}),
            (coll.options, [], {}),
            (aggregate, [], {}),
        )

    @asyncio_test
    async def test_cursor(self):
        listener = TestListener()
        client = self.asyncio_client(event_listeners=[listener])
        await self.make_test_data()

        coll = client.motor_test.test_collection

        s = await client.start_session()
        # Simulate "async with" on Python 3.4.
        try:
            listener.results.clear()
            cursor = coll.find(session=s)
            await cursor.to_list(length=None)
            self.assertEqual(len(listener.results["started"]), 2)
            for event in listener.results["started"]:
                self.assertTrue(
                    "lsid" in event.command, "find sent no lsid with %s" % (event.command_name,)
                )

                self.assertEqual(
                    s.session_id,
                    event.command["lsid"],
                    "find sent wrong lsid with %s" % (event.command_name,),
                )
        finally:
            await s.end_session()

        with self.assertRaisesRegex(InvalidOperation, "ended session"):
            await coll.find(session=s).to_list(length=None)

        # No explicit session.
        listener.results.clear()
        cursor = coll.find()
        await cursor.to_list(length=None)
        self.assertEqual(len(listener.results["started"]), 2)
        event0 = listener.first_command_started()
        self.assertTrue(
            "lsid" in event0.command, "find sent no lsid with %s" % (event0.command_name,)
        )

        lsid = event0.command["lsid"]

        for event in listener.results["started"][1:]:
            self.assertTrue(
                "lsid" in event.command, "find sent no lsid with %s" % (event.command_name,)
            )

            self.assertEqual(
                lsid, event.command["lsid"], "find sent wrong lsid with %s" % (event.command_name,)
            )

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


text:
module Trailblazer::Rails::Controller::Cell
  module Render
    def render(cell = nil, options = {}, *, &block)
      return super unless cell.kind_of?(::Cell::ViewModel)

      render_cell(cell, options)
    end

    def render_cell(cell, options)
      options = options.reverse_merge(layout: true)

      # render the cell.
      content = cell.()

      render({html: content}.merge(options))
    end

    def cell(constant, model=nil, options={})
      cell_options = options.reverse_merge(options_for_cell(model, options))

      super(constant, model, cell_options) # From cells-rails gem.
    end

    # Override this to customize what options are passed into the cell constructor.
    # E.g. `{layout: Song::Cell::Layout}`
    def options_for_cell(_model, _options)
      {}
    end
  end

  include Render unless method_defined?(:render_cell) # FIXME: this will be removed soon.
end


text:
                        {{'come_conferire'|translate}}

                        {{comeConferire}}

                        {{'presta_attenzione'|translate}}

                        {{prestaAttenzione}}


text: define("dojox/atom/widget/nls/ar/FeedViewerEntry",({deleteButton:"[حذف]"}));


text:
describe('AutoColumnSize', () => {
  const id = 'testContainer';

  beforeEach(function() {
    this.$container = $(`<div id="${id}"></div>`).appendTo('body');
  });

  afterEach(function() {
    if (this.$container) {
      destroy();
      this.$container.remove();
    }
  });

  const arrayOfObjects = function() {
    return [
      { id: 'Short', name: 'Somewhat long', lastName: 'The very very very longest one', nestedData: [{ id: 1000 }] }
    ];
  };

  it('should apply auto size by default', () => {
    handsontable({
      data: arrayOfObjects()
    });

    const width0 = colWidth(spec().$container, 0);
    const width1 = colWidth(spec().$container, 1);
    const width2 = colWidth(spec().$container, 2);

    expect(width0).toBeLessThan(width1);
    expect(width1).toBeLessThan(width2);
  });

  it('should update column width after update value in cell (array of objects)', async() => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      columns: [
        { data: 'id' },
        { data: 'name' },
        { data: 'lastName' },
      ]
    });

    expect(colWidth(spec().$container, 0)).toBeAroundValue(50, 3);
    expect([117, 120, 121, 129, 135]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 1)]));
    expect([216, 229, 247, 260, 261]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 2)]));

    setDataAtRowProp(0, 'id', 'foo bar foo bar foo bar');
    setDataAtRowProp(0, 'name', 'foo');

    await sleep(50);

    expect([165, 168, 169, 189, 191]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
    expect(colWidth(spec().$container, 1)).toBeAroundValue(50, 3);
    expect([216, 229, 247, 260, 261]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 2)]));
  });

  it('should correctly detect column widths with colHeaders', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      colHeaders: ['Identifier Longer text'],
      columns: [
        { data: 'id' },
        { data: 'name' },
      ]
    });

    expect([149, 155, 174, 178]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
  });

  it('should correctly detect column widths after update colHeaders when headers were passed as an array', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      colHeaders: true,
      columns: [
        { data: 'id' },
        { data: 'name' },
      ]
    });

    expect([50, 51, 53]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));

    updateSettings({ colHeaders: ['Identifier Longer text', 'Identifier Longer and longer text'] });

    expect([149, 155, 174, 178]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
    expect([226, 235, 263, 270]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 1)]));
  });

  it('should correctly detect column widths after update colHeaders when headers were passed as a string', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      colHeaders: true,
      columns: [
        { data: 'id' },
        { data: 'name' },
      ]
    });

    expect([50, 51, 53]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));

    updateSettings({ colHeaders: 'Identifier Longer text' });

    expect([149, 155, 174, 178]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
    expect([149, 155, 174, 178]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 1)]));
  });

  it('should correctly detect column widths after update colHeaders when headers were passed as a function', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      colHeaders: true,
      columns: [
        { data: 'id' },
        { data: 'name' },
      ]
    });

    expect([50, 51, 53]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));

    updateSettings({
      colHeaders(index) {
        return index === 0 ? 'Identifier Longer text' : 'Identifier Longer and longer text';
      },
    });

    expect([149, 155, 174, 178]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
    expect([226, 235, 263, 270]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 1)]));
  });

  it('should correctly detect column width with colHeaders and the useHeaders option set to false (not taking the header widths into calculation)', () => {
    handsontable({
      data: [
        { id: 'ab' }
      ],
      autoColumnSize: {
        useHeaders: false
      },
      colHeaders: ['Identifier'],
      columns: [
        { data: 'id' }
      ]
    });

    expect(colWidth(spec().$container, 0)).toBe(50);
  });

  it('should correctly detect column width with columns.title', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      columns: [
        { data: 'id', title: 'Identifier' }
      ]
    });

    expect([68, 70, 71, 80, 82]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
  });

  it('should correctly detect column widths after update columns.title', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      columns: [
        { data: 'id', title: 'Identifier' }
      ]
    });

    updateSettings({
      columns: [
        { data: 'id', title: 'Identifier with longer text' },
      ],
    });

    expect([174, 182, 183, 208, 213]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
  });

  // https://github.com/handsontable/handsontable/issues/2684
  it('should correctly detect column width when table is hidden on init (display: none)', async() => {
    spec().$container.css('display', 'none');
    const hot = handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      colHeaders: ['Identifier', 'First Name']
    });

    await sleep(200);

    spec().$container.css('display', 'block');
    hot.render();

    expect([68, 70, 71, 80, 82]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
  });

  it('should not wrap the cell values when the whole column has values with the same length', () => {
    handsontable({
      data: [
        {
          units: 'EUR / USD'
        },
        {
          units: 'JPY / USD'
        },
        {
          units: 'GBP / USD'
        },
        {
          units: 'MXN / USD'
        },
        {
          units: 'ARS / USD'
        }
      ],
      autoColumnSize: {
        samplingRatio: 5,
      },
      columns: [
        { data: 'units' },
      ]
    });

    expect([93]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
    expect(rowHeight(spec().$container, 0)).toBe(24);
    expect(rowHeight(spec().$container, 1)).toBe(23);
    expect(rowHeight(spec().$container, 2)).toBe(23);
    expect(rowHeight(spec().$container, 3)).toBe(23);
    expect(rowHeight(spec().$container, 4)).toBe(23);
  });

  it('should keep last columns width unchanged if all rows was removed', async() => {
    const hot = handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      columns: [
        { data: 'id', title: 'Identifier' },
        { data: 'name', title: 'Name' },
        { data: 'lastName', title: 'Last Name' },
      ]
    });

    expect([68, 70, 71, 80, 82]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
    expect([117, 120, 121, 129, 135]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 1)]));
    expect([216, 229, 247, 260, 261]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 2)]));

    hot.alter('remove_row', 0);
    await sleep(50);

    expect([68, 70, 71, 80, 82]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 0)]));
    expect([117, 120, 121, 129, 135]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 1)]));
    expect([216, 229, 247, 260, 261]).toEqual(jasmine.arrayContaining([colWidth(spec().$container, 2)]));
  });

  it('should be possible to disable plugin using updateSettings', () => {
    handsontable({
      data: arrayOfObjects()
    });

    let width0 = colWidth(spec().$container, 0);
    let width1 = colWidth(spec().$container, 1);
    let width2 = colWidth(spec().$container, 2);

    expect(width0).toBeLessThan(width1);
    expect(width1).toBeLessThan(width2);

    updateSettings({
      autoColumnSize: false
    });

    width0 = colWidth(spec().$container, 0);
    width1 = colWidth(spec().$container, 1);
    width2 = colWidth(spec().$container, 2);

    expect(width0).toEqual(width1);
    expect(width0).toEqual(width2);
    expect(width1).toEqual(width2);
  });

  it('should apply disabling/enabling plugin using updateSettings, only to a particular HOT instance', () => {
    spec().$container2 = $(`<div id="${id}-2"></div>`).appendTo('body');

    handsontable({
      data: arrayOfObjects()
    });

    spec().$container2.handsontable({
      data: arrayOfObjects()
    });

    const widths = {
      1: [],
      2: []
    };

    widths[1][0] = colWidth(spec().$container, 0);
    widths[1][1] = colWidth(spec().$container, 1);
    widths[1][2] = colWidth(spec().$container, 2);

    widths[2][0] = colWidth(spec().$container2, 0);
    widths[2][1] = colWidth(spec().$container2, 1);
    widths[2][2] = colWidth(spec().$container2, 2);

    expect(widths[1][0]).toBeLessThan(widths[1][1]);
    expect(widths[1][1]).toBeLessThan(widths[1][2]);

    expect(widths[2][0]).toBeLessThan(widths[2][1]);
    expect(widths[2][1]).toBeLessThan(widths[2][2]);

    updateSettings({
      autoColumnSize: false
    });

    widths[1][0] = colWidth(spec().$container, 0);
    widths[1][1] = colWidth(spec().$container, 1);
    widths[1][2] = colWidth(spec().$container, 2);

    widths[2][0] = colWidth(spec().$container2, 0);
    widths[2][1] = colWidth(spec().$container2, 1);
    widths[2][2] = colWidth(spec().$container2, 2);

    expect(widths[1][0]).toEqual(widths[1][1]);
    expect(widths[1][0]).toEqual(widths[1][2]);
    expect(widths[1][1]).toEqual(widths[1][2]);

    expect(widths[2][0]).toBeLessThan(widths[2][1]);
    expect(widths[2][1]).toBeLessThan(widths[2][2]);

    spec().$container2.handsontable('destroy');
    spec().$container2.remove();
  });

  it('should be possible to enable plugin using updateSettings', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: false
    });

    let width0 = colWidth(spec().$container, 0);
    let width1 = colWidth(spec().$container, 1);
    let width2 = colWidth(spec().$container, 2);

    expect(width0).toEqual(width1);
    expect(width0).toEqual(width2);
    expect(width1).toEqual(width2);

    updateSettings({
      autoColumnSize: true
    });

    width0 = colWidth(spec().$container, 0);
    width1 = colWidth(spec().$container, 1);
    width2 = colWidth(spec().$container, 2);

    expect(width0).toBeLessThan(width1);
    expect(width1).toBeLessThan(width2);
  });

  it('should consider CSS style of each instance separately', () => {
    const $style = $('').appendTo('head');
    const $container1 = $('

').appendTo('body').handsontable({
      data: arrayOfObjects()
    });
    const $container2 = $('

').appendTo('body').handsontable({
      data: arrayOfObjects()
    });
    const hot1 = $container1.handsontable('getInstance');
    const hot2 = $container2.handsontable('getInstance');

    expect(colWidth($container1, 0)).toEqual(colWidth($container2, 0));

    $container1.addClass('big');
    hot1.render();
    hot2.render();
    expect(colWidth($container1, 0)).toBeGreaterThan(colWidth($container2, 0));

    $container1.removeClass('big').handsontable('render');
    $container2.addClass('big').handsontable('render');
    expect(colWidth($container1, 0)).toBeLessThan(colWidth($container2, 0));

    $style.remove();
    $container1.handsontable('destroy');
    $container1.remove();
    $container2.handsontable('destroy');
    $container2.remove();
  });

  it('should consider CSS class of the
 element (e.g. when used with Bootstrap)', () => {
    const $style = $('').appendTo('head');

    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true
    });

    const width = colWidth(spec().$container, 0);

    spec().$container.find('table').addClass('big-table');
    render();
    expect(colWidth(spec().$container, 0)).toBeGreaterThan(width);

    $style.remove();
  });

  it('should destroy temporary element', () => {
    handsontable({
      autoColumnSize: true
    });

    expect(document.querySelector('.htAutoSize')).toBe(null);
  });

  it('should not trigger autoColumnSize when column width is defined (through colWidths)', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      colWidths: [70, 70, 70],
      width: 500,
      height: 100,
      rowHeaders: true
    });

    setDataAtCell(0, 0, 'LongLongLongLong');

    expect(colWidth(spec().$container, 0)).toBe(70);
  });

  it('should not trigger autoColumnSize when column width is defined (through columns.width)', () => {
    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      colWidth: 77,
      columns: [
        { width: 70 },
        { width: 70 },
        { width: 70 }
      ],
      width: 500,
      height: 100,
      rowHeaders: true
    });

    setDataAtCell(0, 0, 'LongLongLongLong');

    expect(colWidth(spec().$container, 0)).toBe(70);
  });

  it('should consider renderer that uses conditional formatting for specific row & column index', () => {
    const data = arrayOfObjects();
    data.push({ id: '2', name: 'Rocket Man', lastName: 'In a tin can' });
    handsontable({
      data,
      columns: [
        { data: 'id' },
        { data: 'name' }
      ],
      autoColumnSize: true,
      renderer(instance, td, row, col, ...args) {
        // taken from demo/renderers.html
        Handsontable.renderers.TextRenderer.apply(this, [instance, td, row, col, ...args]);
        if (row === 1 && col === 0) {
          td.style.padding = '100px';
        }
      }
    });

    expect(colWidth(spec().$container, 0)).toBeGreaterThan(colWidth(spec().$container, 1));
  });

  it('should\'t serialize value if it is array (nested data sources)', () => {
    const spy = jasmine.createSpy('renderer');

    handsontable({
      data: arrayOfObjects(),
      autoColumnSize: true,
      columns: [
        { data: 'nestedData' }
      ],
      renderer: spy
    });

    expect(spy.calls.mostRecent().args[5]).toEqual([{ id: 1000 }]);
  });

  it('should not change width after select/click cell', async() => {
    handsontable({
      data: [
        ['Canceled'],
        ['Processing'],
        ['Processing'],
        ['Created'],
        ['Processing'],
        ['Completed']
      ],
      colHeaders: true,
      rowHeaders: true,
    });

    await sleep(300);

    const cloneTopHider = spec().$container.find('.ht_clone_top .wtHider');

    expect(cloneTopHider.width()).toEqual(140);

    selectCell(0, 0);

    await sleep(300);

    expect(cloneTopHider.width()).toEqual(140);
  });

  it('should not calculate any column widths, if there are no columns in the dataset', () => {
    handsontable({
      data: [[1, 2]],
      colHeaders: true,
    });

    spyOn(getPlugin('autoColumnSize'), 'calculateColumnsWidth').and.callThrough();
    const calculateColumnsWidth = getPlugin('autoColumnSize').calculateColumnsWidth;

    loadData([[]]);

    expect(calculateColumnsWidth).not.toHaveBeenCalled();
  });
});


text:
using VisualRecognition.ViewModels;
using WatsonServices.Models.VisualRecognition;

namespace VisualRecognition.Mappers
{
    internal static class ImageFaceAgeMapper
    {
        internal static ImageFaceAgeViewModel Map(ImageFaceAge fromModel)
        {
            if (fromModel == null)
                return null;

            var toModel = new ImageFaceAgeViewModel();
            toModel.MaximumAge = fromModel.MaximumAge;
            toModel.MinimumAge = fromModel.MinimumAge;
            toModel.Score = fromModel.Score;
            return toModel;
        }
    }
}


text:
namespace MassTransit.Topology
{
    using GreenPipes;

    public interface ISendTopologyConfigurator :
        ISendTopology,
        ISpecification
    {
        /// <summary>
        /// Adds a convention to the topology, which will be applied to every message type
        /// requested, to determine if a convention for the message type is available.
        /// </summary>
        /// <param name="convention">The send topology convention</param>
        void AddConvention(ISendTopologyConvention convention);

        /// <summary>
        /// Add a send topology for a specific message type
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="topology">The topology</param>
        void AddMessageSendTopology<T>(IMessageSendTopology<T> topology)
            where T : class;
    }
}


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Common\FileToolkit;
use AppBundle\Common\ArrayToolkit;
use Biz\User\Service\TokenService;
use Biz\CloudPlatform\CloudAPIFactory;
use Biz\File\Service\UploadFileService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Biz\MaterialLib\Service\MaterialLibService;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class PlayerController extends BaseController
{
    public function showAction(Request $request, $id, $context = array())
    {
        $ssl = $request->isSecure() ? true : false;

        $file = $this->getUploadFileService()->getFullFile($id);
        if (empty($file)) {
            throw $this->createNotFoundException('file not found');
        }
        if (!in_array($file['type'], array('audio', 'video'))) {
            throw $this->createAccessDeniedException("player does not support  file type: {$file['type']}");
        }

        $player = $this->getPlayer($file);

        $agentInWhiteList = $this->agentInWhiteList($request->headers->get('user-agent'));

        $isEncryptionPlus = false;
        if ($file['type'] == 'video' && $file['storage'] == 'cloud') {
            $storageSetting = $this->getSettingService()->get('storage');

            $isEncryptionPlus = isset($storageSetting['enable_hls_encryption_plus']) && (bool) $storageSetting['enable_hls_encryption_plus'];

            if (!$this->isHiddenVideoHeader()) {
                // 加入片头信息
                $videoHeaderFile = $this->getUploadFileService()->getFileByTargetType('headLeader');
                if (!empty($videoHeaderFile) && $videoHeaderFile['convertStatus'] == 'success') {
                    $context['videoHeaderLength'] = $videoHeaderFile['length'];
                }
            }

            if (!empty($file['convertParams']['hasVideoWatermark'])) {
                $file['videoWatermarkEmbedded'] = 1;
            }

            $result = $this->getMaterialLibService()->player($file['globalId'], $ssl);

            if (isset($result['subtitles'])) {
                $this->filterSubtitles($result['subtitles']);
                $context['subtitles'] = $result['subtitles'];
            }

            // 临时修复手机浏览器端视频不能播放的问题
            if ($agentInWhiteList) {
                //手机浏览器不弹题
                $context['hideQuestion'] = 1;
                if (isset($file['mcStatus']) && $file['mcStatus'] == 'yes') {
                    $player = 'local-video-player';
                    $mp4Url = isset($result['mp4url']) ? $result['mp4url'] : '';
                    $isEncryptionPlus = false;
                }
            }
        }
        $url = isset($mp4Url) ? $mp4Url : $this->getPlayUrl($file, $context, $ssl);

        return $this->render('player/show.html.twig', array(
            'file' => $file,
            'url' => isset($url) ? $url : null,
            'context' => $context,
            'player' => $player,
            'agentInWhiteList' => $agentInWhiteList,
            'isEncryptionPlus' => $isEncryptionPlus,
        ));
    }

    public function localMediaAction(Request $request, $id, $token)
    {
        $file = $this->getUploadFileService()->getFile($id);

        if (empty($file)) {
            throw $this->createNotFoundException();
        }

        if (!in_array($file['type'], array('audio', 'video'))) {
            throw $this->createAccessDeniedException();
        }

        $token = $this->getTokenService()->verifyToken('local.media', $token);
        if (!$token || $token['userId'] != $this->getCurrentUser()->getId()) {
            throw $this->createAccessDeniedException();
        }

        $response = BinaryFileResponse::create($file['fullpath'], 200, array(), false);
        $response::trustXSendfileTypeHeader();

        $mimeType = FileToolkit::getMimeTypeByExtension($file['ext']);

        if ($mimeType) {
            $response->headers->set('Content-Type', $mimeType);
        }

        return $response;
    }

    public function streamAction(Request $request, $globalId, $level, $token)
    {
        $token = $this->getTokenService()->verifyToken('hls.stream', $token);

        if (empty($token)) {
            throw $this->createNotFoundException();
        }

        $dataId = is_array($token['data']) ? $token['data']['globalId'] : $token['data'];

        if ($dataId != ($globalId.$level)) {
            throw $this->createNotFoundException();
        }

        $file = $this->getMaterialLibService()->get($globalId);

        if (empty($file)) {
            throw $this->createNotFoundException();
        }

        if (empty($file['metas']['levels'][$level]['key'])) {
            throw $this->createNotFoundException();
        }

        $tokenFields = array(
            'data' => array(
                'globalId' => $file['no'],
                'level' => $level,
                'keyencryption' => 0,
            ),
            'times' => 1,
            'duration' => 3600,
        );

        if (!empty($token['userId'])) {
            $tokenFields['userId'] = $token['userId'];
        }

        $token = $this->getTokenService()->makeToken('hls.clef', $tokenFields);

        $params = array();
        $params['keyUrl'] = $this->generateUrl('global_file_hls_clef', array(
            'globalId' => $file['no'],
            'token' => $token['token'],
        ), true);
        $params['key'] = $file['metas']['levels'][$level]['key'];
        $params['fileId'] = $file['id'];

        $api = CloudAPIFactory::create('leaf');

        $stream = $api->get('/hls/stream', $params);

        if (empty($stream['stream'])) {
            return $this->createMessageResponse('error', '生成视频播放地址失败!');
        }

        return new Response($stream['stream'], 200, array(
            'Content-Type' => 'application/vnd.apple.mpegurl',
            'Content-Disposition' => 'inline; filename="stream.m3u8"',
        ));
    }

    public function playlistAction(Request $request, $globalId, $token)
    {
        $token = $this->getTokenService()->verifyToken('hls.playlist', $token);

        if (empty($token)) {
            throw $this->createNotFoundException();
        }

        $dataId = is_array($token['data']) ? $token['data']['globalId'] : $token['data'];

        if ($dataId != $globalId) {
            throw $this->createNotFoundException();
        }

        $file = $this->getMaterialLibService()->get($globalId);

        if (empty($file)) {
            throw $this->createNotFoundException();
        }

        $streams = array();

        foreach (array('sd', 'hd', 'shd') as $level) {
            if (empty($file['metas']['levels'][$level])) {
                continue;
            }

            $tokenFields = array(
                'data' => array(
                    'globalId' => $file['no'].$level,
                ),
                'times' => $this->agentInWhiteList($request->headers->get('user-agent')) ? 0 : 1,
                'duration' => 3600,
            );

            if (!empty($token['userId'])) {
                $tokenFields['userId'] = $token['userId'];
            }

            $token = $this->getTokenService()->makeToken('hls.stream', $tokenFields);

            $params = array(
                'globalId' => $file['no'],
                'level' => $level,
                'token' => $token['token'],
            );

            $streams[$level] = $this->generateUrl('global_file_hls_stream', $params, true);
        }

        $api = CloudAPIFactory::create('leaf');

        $qualities = array(
            'video' => $file['directives']['videoQuality'],
            'audio' => $file['directives']['audioQuality'],
        );

        $playlist = $api->get('/hls/playlist/json', array('streams' => $streams, 'qualities' => $qualities));

        return $this->createJsonResponse($playlist);
    }

    protected function getPlayUrl($file, $context, $ssl)
    {
        if ($file['storage'] == 'cloud') {
            if (!empty($file['metas2']) && !empty($file['metas2']['sd']['key'])) {
                if (isset($file['convertParams']['convertor']) && ($file['convertParams']['convertor'] == 'HLSEncryptedVideo')) {
                    $hideBeginning = isset($context['hideBeginning']) ? $context['hideBeginning'] : false;
                    $context['hideBeginning'] = $this->isHiddenVideoHeader($hideBeginning);
                    $token = $this->makeToken('hls.playlist', $file['id'], $context);
                    $params = array(
                        'id' => $file['id'],
                        'token' => $token['token'],
                    );

                    return $this->generateUrl('hls_playlist', $params, true);
                } else {
                    throw new \RuntimeException('当前视频格式不能被播放!');
                }
            } else {
                if (!empty($file['metas']) && !empty($file['metas']['hd']['key'])) {
                    $key = $file['metas']['hd']['key'];
                } else {
                    $key = $file['hashId'];
                }

                if ($key) {
                    $result = $this->getMaterialLibService()->player($file['globalId'], $ssl);
                }
            }

            return isset($result['url']) ? $result['url'] : '';
        } else {
            $token = $this->makeToken('local.media', $file['id']);

            return $this->generateUrl('player_local_media', array(
                'id' => $file['id'],
                'token' => $token['token'],
            ));
        }
    }

    protected function makeToken($type, $fileId, $context = array())
    {
        $fields = array(
            'data' => array(
                'id' => $fileId,
            ),
            'times' => 3,
            'duration' => 3600,
            'userId' => $this->getUser()->getId(),
        );

        if (isset($context['watchTimeLimit'])) {
            $fields['data']['watchTimeLimit'] = $context['watchTimeLimit'];
        }

        if (isset($context['hideBeginning'])) {
            $fields['data']['hideBeginning'] = $context['hideBeginning'];
        }

        $token = $this->getTokenService()->makeToken($type, $fields);

        return $token;
    }

    protected function getPlayer($file)
    {
        switch ($file['type']) {
            case 'audio':
                return 'audio-player';
            case 'video':
                return $file['storage'] == 'local' ? 'local-video-player' : 'balloon-cloud-video-player';
            default:
                return null;
        }
    }

    protected function isHiddenVideoHeader($isHidden = false)
    {
        $storage = $this->setting('storage');
        if (!empty($storage) && array_key_exists('video_header', $storage) && $storage['video_header'] && !$isHidden) {
            return false;
        } else {
            return true;
        }
    }

    protected function agentInWhiteList($userAgent)
    {
        $whiteList = array('iPhone', 'iPad', 'Android', 'HTC');

        return ArrayToolkit::some($whiteList, function ($agent) use ($userAgent) {
            return strpos($userAgent, $agent) > -1;
        });
    }

    private function filterSubtitles(&$subtitles)
    {
        foreach ($subtitles as &$subtitle) {
            $subtitle['name'] = rtrim($subtitle['name'], '.srt');
        }
    }

    /**
     * @return UploadFileService
     */
    protected function getUploadFileService()
    {
        return $this->getBiz()->service('File:UploadFileService');
    }

    /**
     * @return MaterialLibService
     */
    protected function getMaterialLibService()
    {
        return $this->getBiz()->service('MaterialLib:MaterialLibService');
    }

    /**
     * @return \Biz\System\Service\SettingService
     */
    protected function getSettingService()
    {
        return $this->getBiz()->service('System:SettingService');
    }

    /**
     * @return TokenService
     */
    protected function getTokenService()
    {
        return $this->getBiz()->service('User:TokenService');
    }
}


text:
import React from 'react'
import PT from 'prop-types'
import * as THREE from 'three'
import Promise from 'bluebird'
import droidSans from '-/assets/fonts/helvetiker_bold.typeface.json'

import Example from '-/components/example'

import notes from './readme.md'
import stationsData from './stations.json'
import threeOrbitControls from 'three-orbit-controls'

const globals = {
  stations: [],
  particles: {
    vertices: [],
  },
  fontLoader: new THREE.FontLoader(),
  font: null,
  colors: {
    stations: 0x4466ff,
    stationLabels: 0xffffff,
  },
}

/**
 * Create a station mesh object
 */
const createStation = (station) => {
  const stationGeom = new THREE.IcosahedronBufferGeometry(0.35, 0)
  const stationMat = new THREE.MeshPhongMaterial({
    color: globals.colors.stations,
  })
  const polyhedron = new THREE.Mesh(stationGeom, stationMat)
  const pos = calcPosFromLatLonRad(station.latitude, station.longitude, 30)
  polyhedron.position.set(...pos)
  return polyhedron
}

/**
 * Create a station mesh label
 */
const createStationLabel = (station) => {
  const textMat = new THREE.MeshPhongMaterial({
    color: globals.colors.stationLabels,
  })
  const defaultTextBufferGeomOpts = {
    size: 0.25,
    height: 0.25,
    curveSegments: 3,
    bevelEnabled: false,
  }
  const textGeom = new THREE.TextBufferGeometry(
    station.stationName,
    Object.assign({}, defaultTextBufferGeomOpts, {
      font: globals.font,
    })
  )
  const text = new THREE.Mesh(textGeom, textMat)
  const pos = calcPosFromLatLonRad(station.latitude, station.longitude, 30)
  text.position.set(...pos)
  return text
}

/**
 * Load the stations data into the given scene
 */
const loadStations = async (scene) => {
  const font = globals.fontLoader.parse(droidSans)
  globals.font = font

  const loadStations = stationsData.stations.map((s) => async () => {
    const station = createStation(s)
    const label = createStationLabel(s)
    scene.add(station)
    scene.add(label)
    globals.stations.push(station)
  })
  Promise.map(loadStations, (x) => Promise.resolve(x()).delay(100), {
    concurrency: 25,
  })
}

const loadParticles = async (scene) => {
  const particleCount = 1800
  const particleGeom = new THREE.Geometry()
  const particleMat = new THREE.PointsMaterial({
    color: 0xffffff,
    size: 0.5,
  })

  Array.from(new Array(particleCount).keys()).forEach(() => {
    const x = Math.random() * 150 - 75
    const y = Math.random() * 100 - 50
    const particle = new THREE.Vector3(x, y, 0)
    particleGeom.vertices.push(particle)
  })
  globals.particles = particleGeom

  const particles = new THREE.Points(particleGeom, particleMat)

  scene.add(particles)
}

/**
 * didMount()
 */
const init = ({ canvas }) => {
  console.log(canvas)
  // Create the scene and renderer
  const scene = new THREE.Scene()
  const renderer = new THREE.WebGLRenderer({ canvas })
  renderer.setSize(canvas.clientWidth, canvas.clientHeight)

  // Add the camera
  const camera = new THREE.PerspectiveCamera(
    75,
    canvas.clientWidth / canvas.clientHeight,
    1,
    100000
  )
  camera.position.z = 50

  const OrbitControls = threeOrbitControls(THREE)
  const controls = new OrbitControls(camera)
  controls.update()

  // Add the main light source
  const light = new THREE.PointLight(0xffffff, 2, 200)
  light.position.set(0, 40, 40)
  scene.add(light)

  let frame = 0
  const animate = () => {
    requestAnimationFrame(animate)

    globals.stations.forEach((p, i) => {
      p.rotation.x += 0.01
    })
    controls.update()

    globals.particles.vertices.forEach((p, i) => {
      const newPos = updateParticlePosition(p, frame)
      p.x = newPos.x
      p.y = newPos.y
    })
    globals.particles.verticesNeedUpdate = true

    renderer.render(scene, camera)
    frame += 0.1
  }
  animate()

  loadStations(scene)
  loadParticles(scene)

  return () => {
    scene.dispose()
    renderer.dispose()
  }
}

const updateParticlePosition = (pos, frame) => {
  const [x, y, z] = [
    pos.x + (Math.random() - 0.5) * 0.2,
    pos.y + (Math.random() - 0.5) * 0.2,
    pos.z,
  ]
  return new THREE.Vector3(x, y, z)
}

/**
 * Calculate a 3D position from a lat,lng pair and radius.
 */
// const calc3dPosFromLatLonRad = (lat, lon, radius) => {
//   const phi = (90 - lat) * (Math.PI / 180)
//   const theta = (lon + 180) * (Math.PI / 180)
//
//   const x = -(radius * Math.sin(phi) * Math.cos(theta))
//   const z = radius * Math.sin(phi) * Math.sin(theta)
//   const y = radius * Math.cos(phi)
//
//   return [x, y, z]
// }

/**
 * Calculate a 3D position from a lat,lng pair and radius
 */
const calcPosFromLatLonRad = (lat, lon, radius) => {
  const shift = Math.PI * radius
  const x = (lon * shift) / 180
  let y = Math.log(Math.tan(((90 + lat) * Math.PI) / 360)) / (Math.PI / 180)
  y = (y * shift) / 180

  return [x, y, 0]
}

const Winds = ({ color, id }) => {
  const canvas = React.useRef(null)
  console.log('effect')
  React.useEffect(() => {
    return init({ canvas: canvas.current })
  })
  return <canvas ref={canvas} />
}
Winds.propTypes = {
  color: PT.string,
  id: PT.string,
}

const E = () => (
  <div id="container">
    <Example notes={notes} components={{ Winds }} init={() => () => {}} />
  </div>
)

export default E


text:
set -o errexit

filename=datasets/StructureDemo/nomosalpha.wav

echo ./pymir3-cl.py tool wav2spectrogram $filename /tmp/$$.spec
./pymir3-cl.py tool wav2spectrogram $filename /tmp/$$.spec

echo ./pymir3-cl.py info any /tmp/$$.spec
./pymir3-cl.py info any /tmp/$$.spec -m

feature_files=""
for feature in energy mfcc centroid flatness flux rolloff
do
echo "Computing $feature"
echo ./pymir3-cl.py features $feature /tmp/$$.spec /tmp/$$.$feature
./pymir3-cl.py features $feature /tmp/$$.spec /tmp/$$.$feature
featurefiles=$featurefiles" /tmp/$$.$feature"
done

echo "Joining features"
./pymir3-cl.py features join $featurefiles /tmp/$$.features.join

echo "Calculating textural similarities"
./pymir3-cl.py structure naivebayes /tmp/$$.features.join -s 5 -s 15 -e 9 -e 18 > test.dat


text:
<?php

namespace Orchestra\OrchestraBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class SocialNetworkUserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('url')
            ->add('socialNetwork')
            ->add('user')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Orchestra\OrchestraBundle\Entity\SocialNetworkUser'
        ));
    }

    public function getName()
    {
        return 'orchestra_orchestrabundle_socialnetworkusertype';
    }
}


text:
<?php
/** @package    HELLO WORLD::Controller */

/** import supporting libraries */
require_once("verysimple/Phreeze/Controller.php");

/**
 *
 * @package HELLO WORLD::Controller
 * @author ClassBuilder
 * @version 1.0
 */
class TestController extends Controller
{

	/**
	 * Not used but necessary to implement Controller
	 * @see Controller::Init()
	 */
	protected function Init()
	{
	}

	/**
	 * Test route that outputs a simple JSON object
	 */
	public function JSON()
	{
		$arr = array(
		    "message" => "Hello, World!"
		);

		$this->RenderJSON($arr);
	}

	/**
	 * Test route that connects to the database and outputs
	 * the number of rows specified in the querystring argument "queries"
	 */
	public function DB()
	{
		require_once("Model/World.php");

		// Read number of queries to run from URL parameter
		$query_count = RequestUtil::Get('queries',1);

		$arr = array();

		for ($i = 0; $i < $query_count; $i++) {

			$id = mt_rand(1, 10000);

			$world = $this->Phreezer->Get("World",$id);

			// convert the Phreezable object into a simple structure for output
			$arr[] = array('id'=>$world->Id,'randomNumber'=>$world->Randomnumber);
		}

		$this->RenderJSON($arr);

	}

	/**
	 * Output the Fortunes test template
	 */
	public function Fortunes()
	{
		require_once("Model/Fortune.php");
		require_once("verysimple/Phreeze/PHPRenderEngine.php");

		// charset must be set to UTF8 to support multi-byte chars
		$this->Phreezer->DataAdapter->ConnectionSetting->Charset = "utf8";

		// obtain fortunes without using 'order by'
		$fortunes = $this->Phreezer->Query('Fortune')->ToObjectArray();

		// dynamically add a new, non-persisted Fortune object
		$newFortune = new Fortune($this->Phreezer);
		$newFortune->Id = 0;
		$newFortune->Message = 'Additional fortune added at request time.';
		$fortunes[] = $newFortune;

		// sort (will use Fortune->ToString)
		Phreezer::Sort($fortunes);

		// Render using a template
		$this->RenderEngine = new PHPRenderEngine('templates');
		$this->Assign('fortunes',$fortunes);
		$this->Render('TestFortunes.php');
	}

	/**
	 * Test for performing updates
	 */
	public function Updates()
	{
		require_once("Model/World.php");

		// Read number of queries to run from URL parameter
		$query_count = RequestUtil::Get('queries',1);

		$arr = array();

		for ($i = 0; $i < $query_count; $i++) {

			$id = mt_rand(1, 10000);

			$world = $this->Phreezer->Get("World",$id);

			// update the random number and persist the record
			$world->Randomnumber = mt_rand(1, 10000);
			$world->Save();

			// convert the Phreezable object into a simple structure for output
			$arr[] = array('id'=>$world->Id,'randomNumber'=>$world->Randomnumber);
		}

		$this->RenderJSON($arr);
	}

	/**
	 * Test for outputting plaintext
	 */
	public function PlainText()
	{
		header('Content-type: text/plain');
		echo 'Hello, World!';
	}

}


text:
//
//  AZCountdownManager.h
//  AZTime
//
//  Created by Alfred Zhang on 2017/4/10.
//  Copyright © 2017年 com.alfred.AZTime. All rights reserved.
//

#import <UIKit/UIKit.h>

@class AZCountdownModel;

typedef void(^AZLeftTimeChangedBlock)(NSTimeInterval leftTime, UIView * _Nullable view, NSString * _Nonnull key);

@interface AZCountdownManager : NSObject

/**
 已经添加的倒计时key
 */
@property (strong, nonatomic, readonly) NSArray<NSString *> * _Nullable keys;

/**
 本地时间和服务器时间的偏差量 default 0

 ex: 服务器时间 2017-08-15 12:00:00 , 本地时间 2017-08-15 12:00:10 则 serverOffset = 10
 */
@property (nonatomic, assign) NSTimeInterval serverOffset;

/**
 基于serverOffset计算得到的服务器时间
 */
@property (nonatomic, strong, readonly) NSDate * _Nonnull serverDate;

+ (instancetype _Nonnull )sharedInstance;

- (BOOL)isExistKey:(nonnull NSString *)key;
- (BOOL)isExistView:(nonnull UIView *)view;
- (NSString *_Nullable)keyFromView:(nonnull UIView *)view;

/**
获取相对服务器的deadline

 @param duration 倒计时持续时间
 @return 相对服务器的deadlin
 */
- (NSDate *_Nonnull)serverDeadlieDateWithDuration:(NSTimeInterval)duration;

/**
 添加一个根据view自动生成key的倒计时,倒计时生命周期和view一样

 */
- (void)addCountdownWithView:(UIView *_Nonnull)view
                deadlineDate:(NSDate *_Nonnull)deadline
                    interval:(NSTimeInterval)interval
                    autoStop:(BOOL)autoStop
        leftTimeChangedBlock:(AZLeftTimeChangedBlock _Nullable )leftTimeChangedBlock;

/**
 添加一个自定义key的倒计时

 当autoStop = YES 时,倒计时到 0 后会自动停止
 当autoStop = NO 需要手动停止 ,否则倒计时会一直运行
 */
- (void)addCountdownWithKey:(NSString *_Nonnull)key
                deadlineDate:(NSDate *_Nonnull)deadline
                    interval:(NSTimeInterval)interval
                    autoStop:(BOOL)autoStop
        leftTimeChangedBlock:(AZLeftTimeChangedBlock _Nullable )leftTimeChangedBlock;

/**
 添加一个自定义key且倒计时生命周期和view一样的倒计时 (key和view不能同时为nil)

 @param key 自定义倒计时key
 @param view 倒计时绑定的view
 @param deadline 倒计时终点时间
 @param interval 倒计时刷新间隔
 @param autoStop 倒计时到0后是否自动停止倒计时
 @param leftTimeChangedBlock 倒计时刷新回调block
 */
- (void)addCountdownWithKey:(NSString *_Nullable)key
                       view:(UIView *_Nullable)view
               deadlineDate:(NSDate *_Nonnull)deadline
                   interval:(NSTimeInterval)interval
                   autoStop:(BOOL)autoStop
       leftTimeChangedBlock:(AZLeftTimeChangedBlock _Nullable )leftTimeChangedBlock;

/**
 停止倒计时
 */
- (void)stopCountdownWithKey:(NSString *_Nonnull)key;
- (void)stopCountdownWithView:(UIView *_Nonnull)view;

@end


text:
<cd-property-group>
  <cd-select-grid
    [data]="menuData | MarkSelection: variant"
    (selectItem)="onVariantSelect($event)"
  ></cd-select-grid>
</cd-property-group>

<ng-container [ngSwitch]="variant">
  <ng-container *ngSwitchCase="EmbedVariant.Figma" [ngTemplateOutlet]="figmaRef"></ng-container>
  <ng-container *ngSwitchCase="EmbedVariant.YouTube" [ngTemplateOutlet]="youtubeRef"></ng-container>
  <ng-container *ngSwitchCase="EmbedVariant.GoogleMaps" [ngTemplateOutlet]="mapsRef"></ng-container>
  <ng-container *ngSwitchCase="EmbedVariant.GoogleDocs" [ngTemplateOutlet]="docsRef"></ng-container>
  <ng-container *ngSwitchCase="EmbedVariant.GoogleSheets" [ngTemplateOutlet]="sheetsRef"></ng-container>
  <ng-container *ngSwitchCase="EmbedVariant.GoogleSlides" [ngTemplateOutlet]="slidesRef"></ng-container>
  <ng-container *ngSwitchDefault [ngTemplateOutlet]="websiteRef"></ng-container>
</ng-container>

<ng-template #websiteRef>
  <cd-property-group removePadding>
    <cd-input-group label="Source">
      <cd-input [value]="src" placeholder="https://" (change)="onSourceChange($event)"></cd-input>
    </cd-input-group>
    * Some websites won't work inside an iframe.
  </cd-property-group>
</ng-template>

<ng-template #youtubeRef>
  <app-youtube-props [src]="src" (srcChange)="onSourceChange($event)"></app-youtube-props>
</ng-template>

<ng-template #mapsRef>
  <app-map-props [src]="src" (srcChange)="onSourceChange($event)"></app-map-props>
</ng-template>

<ng-template #figmaRef>
  <app-figma-props [src]="src" (srcChange)="onSourceChange($event)"></app-figma-props>
</ng-template>

<ng-template #docsRef>
  <app-docs-embed-props [src]="src" (srcChange)="onSourceChange($event)"></app-docs-embed-props>
</ng-template>

<ng-template #slidesRef>
  <app-slides-embed-props [src]="src" (srcChange)="onSourceChange($event)"></app-slides-embed-props>
</ng-template>

<ng-template #sheetsRef>
  <app-sheets-embed-props [src]="src" (srcChange)="onSourceChange($event)"></app-sheets-embed-props>
</ng-template>


text:
struct avg_descriptor {
    uint32_t ma_total;
    uint16_t nsamps;
    uint16_t init;
};

void avg_init(struct avg_descriptor *, uint16_t);
void avg_moving(struct avg_descriptor *, uint16_t);
uint16_t avg_get(struct avg_descriptor *);

#endif


text:
class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :hour

  validates :tag, presence: true
  validates :hour, presence: true
end


text:
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//     * Neither the name of Ayende Rahien nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Xunit;
using Rhino.Mocks.Constraints;
using Rhino.Mocks.Exceptions;
using Rhino.Mocks.Expectations;
using Rhino.Mocks.Impl;
using Rhino.Mocks.Interfaces;
using Rhino.Mocks.Tests.Expectations;
using Rhino.Mocks.Utilities;

namespace Rhino.Mocks.Tests
{
	/// <summary>
	/// Tests needed to get full coverage
	/// They won't test meaningful stuff neccesarily
	/// </summary>

	public class Coverage
	{

		[Fact]
		public void CanSerializeObjectNotMockObjectFromThisRepostiory()
		{
			ObjectNotMockFromThisRepositoryException e = new ObjectNotMockFromThisRepositoryException("ff");
			ObjectNotMockFromThisRepositoryException other = (ObjectNotMockFromThisRepositoryException)SerializeAndDeserialize(e);
			Assert.Equal("ff", other.Message );
		}

		[Fact]
		public void CanTestConstaintForTruth()
		{
			if (Is.Null())
				return;
		}

		[Fact]
		public void TryingToGetEventRaiserFromNonEvenTrhows()
		{
			MockRepository mocks = new MockRepository();
			IDemo demo = mocks.StrictMock<IDemo>();
			demo.EnumNoArgs();
			Assert.Throws<InvalidOperationException>(
				"The last method call EnumNoArgs was not an event add / remove method",
				() => LastCall.GetEventRaiser());
		}

		[Fact]
		public void UsingCallOriginalWithSetter()
		{
			MockRepository mocks = new MockRepository();
			WithParameters withParameters = mocks.StrictMock<WithParameters>(1);
			withParameters.Int = 5;
			LastCall.PropertyBehavior();
			mocks.ReplayAll();
			withParameters.Int = 12;
			withParameters.Int = 15;
			Assert.Equal(15, withParameters.Int);
			mocks.VerifyAll();
		}

		[Fact]
		public void MockObjCanHandleGetEventSubscribersCallsWithoutEventsRegistered()
		{
			MockRepository mocks = new MockRepository();
			WithParameters withParameters = mocks.StrictMock<WithParameters>(1);
			IMockedObject mocked = (IMockedObject) withParameters;
			Delegate eventSubscribers = mocked.GetEventSubscribers("ff");
			Assert.Null(eventSubscribers);
		}

		[Fact]
		public void MockObjEqualityCanHandleNonMockObjects()
		{
			int i = MockedObjectsEquality.Instance.GetHashCode("");
			Assert.NotEqual(0, i);
		}

		[Fact]
		public void WillDisplayMethodUsingArraysCorrectly()
		{
			string result = MethodCallUtil.StringPresentation(null, GetType().GetMethod("MethodUsingArray"), new object[] { 1, new string[] { "a", "b" } });
			Assert.Equal("Coverage.MethodUsingArray(1, [\"a\", \"b\"]);",result );
		}

		public void MethodUsingArray(int i, string[] foo)
		{
		}

		private delegate string ToStringDelegate();

		[Fact]
		public void TryingToPassNullToReturnOrThrowWithActionWillThrow()
		{
			AnyArgsExpectation expectation = new AnyArgsExpectation(new FakeInvocation(typeof(object).GetMethod("ToString")), new Range(1, 1));
			expectation.ActionToExecute = (ToStringDelegate)delegate { return "fpp"; };
			Assert.Throws<InvalidOperationException>(
				"Trying to run a Do() delegate when no arguments were matched to the expectation.",
				() => expectation.ReturnOrThrow(null, null));
		}

		[Fact]
		public void CanCallSetExceptionToThrowOnVerifyOnVerifiedMockState()
		{
			new VerifiedMockState(null).SetExceptionToThrowOnVerify(null);
		}

		[Fact]
		public void WillGetPartialRecordFromPartialRecord()
		{
			MockRepository mocks = new MockRepository();
			IDemo demo = mocks.StrictMock<IDemo>();
			IMockState mockState = new RecordPartialMockState((IMockedObject)demo, mocks).BackToRecord();
			Assert.Equal(typeof(RecordPartialMockState), mockState.GetType());
		}

		[Fact]
		public void WillGetPartialRecordFromPartialReplay()
		{
			MockRepository mocks = new MockRepository();
			IDemo demo = mocks.StrictMock<IDemo>();
			IMockState mockState = new ReplayPartialMockState(new RecordPartialMockState((IMockedObject)demo, mocks)).BackToRecord();
			Assert.Equal(typeof(RecordPartialMockState), mockState.GetType());
		}

		[Fact]
		public void WillGetDynamicRecordFromDynamicReplay()
		{
			MockRepository mocks = new MockRepository();
			IDemo demo = mocks.StrictMock<IDemo>();
			IMockState mockState = new ReplayDynamicMockState(new RecordDynamicMockState((IMockedObject)demo, mocks)).BackToRecord();
			Assert.Equal(typeof(RecordDynamicMockState), mockState.GetType());
		}

		public static object SerializeAndDeserialize(object proxy)
		{
			MemoryStream stream = new MemoryStream();
			BinaryFormatter formatter = new BinaryFormatter();
			formatter.Serialize(stream, proxy);
			stream.Position = 0;
			return formatter.Deserialize(stream);
		}

	}
}


text:
package org.yardstickframework.spark;

import akka.actor.*;
import org.apache.spark.*;
import org.apache.spark.deploy.worker.*;
import scala.*;

/**
 * Spark worker node.
 */
public class SparkWorker {
    /** Worker. */
    Tuple2<ActorSystem, Object> worker;

    /**
     * Start worker node.
     *
     * @param masterUrl Url to master. <i>spark://HOST:PORT</i>
     */
    public void start(String masterUrl) {
        SparkConf conf = new SparkConf();

        conf.set("spark.executor.memory", "10G");
        conf.set("spark.shuffle.memoryFraction", "0.6");
        conf.set("spark.eventLog.enabled", "true");

        WorkerArguments args = new WorkerArguments(new String[]{masterUrl}, conf);

        worker = Worker.startSystemAndActor(
            args.host(),
            args.port(),
            args.webUiPort(),
            args.cores(),
            args.memory(),
            args.masters(),
            args.workDir(),
            Option.apply((Object) 1),
                conf
        );
    }

    /**
     * Wait termination worker.
     */
    public void waitTerminate() {
        worker._1().awaitTermination();
    }

    /**
     * Stop node.
     */
    public void stop() {
        if (worker != null)
            worker._1().shutdown();
    }
}


text:
layout: study
title: Hit and Miss
include_sidebar: true
sidebar_type: newsletter-index
---

Hit and Miss

		I publish a small weekly newsletter titled Hit and Miss. In it, I write about whatever
		I've been reading each week, usually with some tilt toward the interaction of technology and
		society. Check out the archive below—if it interests you, please consider subscribing.

	{% assign sorted_newsletters = site.newsletters | sort: 'date' | reverse %}
	{% for newsletter in sorted_newsletters %}

#{{ newsletter.number }}: {{ newsletter.title | markdownify | remove: '
' | remove: '
' }}

{{ newsletter.date | date: '%B ~%dth, %Y' | replace: '~0', '' | replace: '~', '' | replace: '1th', '1st' | replace: '2th', '2nd' | replace: '3th', '3rd' | replace: '11st', '11th' | replace: '12nd', '12th' | replace: '13rd', '13th' }}

	{% endfor %}