text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Log-Shipping Standby Servers</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.6.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="High Availability, Load Balancing, and Replication"
HREF="high-availability.html"><LINK
REL="PREVIOUS"
TITLE="Comparison of Different Solutions"
HREF="different-replication-solutions.html"><LINK
REL="NEXT"
TITLE="Failover"
HREF="warm-standby-failover.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2017-02-06T21:56:32">

PostgreSQL 9.6.2 Documentation

Prev	Up	Chapter 26. High Availability, Load Balancing, and Replication	Next

26.2. Log-Shipping Standby Servers

   Continuous archiving can be used to create a high
   availability (HA) cluster configuration with one or more
   standby servers ready to take over operations if the
   primary server fails. This capability is widely referred to as
   warm standby or log shipping.

   The primary and standby server work together to provide this capability,
   though the servers are only loosely coupled. The primary server operates
   in continuous archiving mode, while each standby server operates in
   continuous recovery mode, reading the WAL files from the primary. No
   changes to the database tables are required to enable this capability,
   so it offers low administration overhead compared to some other
   replication solutions. This configuration also has relatively low
   performance impact on the primary server.

   Directly moving WAL records from one database server to another
   is typically described as log shipping. PostgreSQL
   implements file-based log shipping by transferring WAL records
   one file (WAL segment) at a time. WAL files (16MB) can be
   shipped easily and cheaply over any distance, whether it be to an
   adjacent system, another system at the same site, or another system on
   the far side of the globe. The bandwidth required for this technique
   varies according to the transaction rate of the primary server.
   Record-based log shipping is more granular and streams WAL changes
   incrementally over a network connection (see Section 26.2.5).

   It should be noted that log shipping is asynchronous, i.e., the WAL
   records are shipped after transaction commit. As a result, there is a
   window for data loss should the primary server suffer a catastrophic
   failure; transactions not yet shipped will be lost.  The size of the
   data loss window in file-based log shipping can be limited by use of the
   <TT
CLASS="VARNAME"
>archive_timeout</TT
> parameter, which can be set as low
   as a few seconds.  However such a low setting will
   substantially increase the bandwidth required for file shipping.
   Streaming replication (see Section 26.2.5)
   allows a much smaller window of data loss.

   Recovery performance is sufficiently good that the standby will
   typically be only moments away from full
   availability once it has been activated. As a result, this is called
   a warm standby configuration which offers high
   availability. Restoring a server from an archived base backup and
   rollforward will take considerably longer, so that technique only
   offers a solution for disaster recovery, not high availability.
   A standby server can also be used for read-only queries, in which case
   it is called a Hot Standby server. See Section 26.5 for
   more information.

26.2.1. Planning

    It is usually wise to create the primary and standby servers
    so that they are as similar as possible, at least from the
    perspective of the database server.  In particular, the path names
    associated with tablespaces will be passed across unmodified, so both
    primary and standby servers must have the same mount paths for
    tablespaces if that feature is used.  Keep in mind that if
    CREATE TABLESPACE
    is executed on the primary, any new mount point needed for it must
    be created on the primary and all standby servers before the command
    is executed. Hardware need not be exactly the same, but experience shows
    that maintaining two identical systems is easier than maintaining two
    dissimilar ones over the lifetime of the application and system.
    In any case the hardware architecture must be the same — shipping
    from, say, a 32-bit to a 64-bit system will not work.

    In general, log shipping between servers running different major
    PostgreSQL release
    levels is not possible. It is the policy of the PostgreSQL Global
    Development Group not to make changes to disk formats during minor release
    upgrades, so it is likely that running different minor release levels
    on primary and standby servers will work successfully. However, no
    formal support for that is offered and you are advised to keep primary
    and standby servers at the same release level as much as possible.
    When updating to a new minor release, the safest policy is to update
    the standby servers first — a new minor release is more likely
    to be able to read WAL files from a previous minor release than vice
    versa.

26.2.2. Standby Server Operation

    In standby mode, the server continuously applies WAL received from the
    master server. The standby server can read WAL from a WAL archive
    (see restore_command) or directly from the master
    over a TCP connection (streaming replication). The standby server will
    also attempt to restore any WAL found in the standby cluster's
    <TT
CLASS="FILENAME"
>pg_xlog</TT
> directory. That typically happens after a server
    restart, when the standby replays again WAL that was streamed from the
    master before the restart, but you can also manually copy files to
    <TT
CLASS="FILENAME"
>pg_xlog</TT
> at any time to have them replayed.

    At startup, the standby begins by restoring all WAL available in the
    archive location, calling <TT
CLASS="VARNAME"
>restore_command</TT
>. Once it
    reaches the end of WAL available there and <TT
CLASS="VARNAME"
>restore_command</TT
>
    fails, it tries to restore any WAL available in the <TT
CLASS="FILENAME"
>pg_xlog</TT
> directory.
    If that fails, and streaming replication has been configured, the
    standby tries to connect to the primary server and start streaming WAL
    from the last valid record found in archive or <TT
CLASS="FILENAME"
>pg_xlog</TT
>. If that fails
    or streaming replication is not configured, or if the connection is
    later disconnected, the standby goes back to step 1 and tries to
    restore the file from the archive again. This loop of retries from the
    archive, <TT
CLASS="FILENAME"
>pg_xlog</TT
>, and via streaming replication goes on until the server
    is stopped or failover is triggered by a trigger file.

    Standby mode is exited and the server switches to normal operation
    when <TT
CLASS="COMMAND"
>pg_ctl promote</TT
> is run or a trigger file is found
    (<TT
CLASS="VARNAME"
>trigger_file</TT
>). Before failover,
    any WAL immediately available in the archive or in <TT
CLASS="FILENAME"
>pg_xlog</TT
> will be
    restored, but no attempt is made to connect to the master.

26.2.3. Preparing the Master for Standby Servers

    Set up continuous archiving on the primary to an archive directory
    accessible from the standby, as described
    in Section 25.3. The archive location should be
    accessible from the standby even when the master is down, i.e. it should
    reside on the standby server itself or another trusted server, not on
    the master server.

    If you want to use streaming replication, set up authentication on the
    primary server to allow replication connections from the standby
    server(s); that is, create a role and provide a suitable entry or
    entries in <TT
CLASS="FILENAME"
>pg_hba.conf</TT
> with the database field set to
    <TT
CLASS="LITERAL"
>replication</TT
>.  Also ensure <TT
CLASS="VARNAME"
>max_wal_senders</TT
> is set
    to a sufficiently large value in the configuration file of the primary
    server. If replication slots will be used,
    ensure that <TT
CLASS="VARNAME"
>max_replication_slots</TT
> is set sufficiently
    high as well.

    Take a base backup as described in Section 25.3.2
    to bootstrap the standby server.

26.2.4. Setting Up a Standby Server

    To set up the standby server, restore the base backup taken from primary
    server (see Section 25.3.4). Create a recovery
    command file <TT
CLASS="FILENAME"
>recovery.conf</TT
> in the standby's cluster data
    directory, and turn on <TT
CLASS="VARNAME"
>standby_mode</TT
>. Set
    <TT
CLASS="VARNAME"
>restore_command</TT
> to a simple command to copy files from
    the WAL archive. If you plan to have multiple standby servers for high
    availability purposes, set <TT
CLASS="VARNAME"
>recovery_target_timeline</TT
> to
    <TT
CLASS="LITERAL"
>latest</TT
>, to make the standby server follow the timeline change
    that occurs at failover to another standby.

Note:      Do not use pg_standby or similar tools with the built-in standby mode
     described here. <TT
CLASS="VARNAME"
>restore_command</TT
> should return immediately
     if the file does not exist; the server will retry the command again if
     necessary. See Section 26.4
     for using tools like pg_standby.

     If you want to use streaming replication, fill in
     <TT
CLASS="VARNAME"
>primary_conninfo</TT
> with a libpq connection string, including
     the host name (or IP address) and any additional details needed to
     connect to the primary server. If the primary needs a password for
     authentication, the password needs to be specified in
     <TT
CLASS="VARNAME"
>primary_conninfo</TT
> as well.

    If you're setting up the standby server for high availability purposes,
    set up WAL archiving, connections and authentication like the primary
    server, because the standby server will work as a primary server after
    failover.

    If you're using a WAL archive, its size can be minimized using the archive_cleanup_command parameter to remove files that are no
    longer required by the standby server.
    The pg_archivecleanup utility is designed specifically to
    be used with <TT
CLASS="VARNAME"
>archive_cleanup_command</TT
> in typical single-standby
    configurations, see pg_archivecleanup.
    Note however, that if you're using the archive for backup purposes, you
    need to retain files needed to recover from at least the latest base
    backup, even if they're no longer needed by the standby.

    A simple example of a <TT
CLASS="FILENAME"
>recovery.conf</TT
> is:

standby_mode = 'on'
primary_conninfo = 'host=192.168.1.50 port=5432 user=foo password=foopass'
restore_command = 'cp /path/to/archive/%f %p'
archive_cleanup_command = 'pg_archivecleanup /path/to/archive %r'

    You can have any number of standby servers, but if you use streaming
    replication, make sure you set <TT
CLASS="VARNAME"
>max_wal_senders</TT
> high enough in
    the primary to allow them to be connected simultaneously.

26.2.5. Streaming Replication

    Streaming replication allows a standby server to stay more up-to-date
    than is possible with file-based log shipping. The standby connects
    to the primary, which streams WAL records to the standby as they're
    generated, without waiting for the WAL file to be filled.

    Streaming replication is asynchronous by default
    (see Section 26.2.8), in which case there is
    a small delay between committing a transaction in the primary and the
    changes becoming visible in the standby. This delay is however much
    smaller than with file-based log shipping, typically under one second
    assuming the standby is powerful enough to keep up with the load. With
    streaming replication, <TT
CLASS="VARNAME"
>archive_timeout</TT
> is not required to
    reduce the data loss window.

    If you use streaming replication without file-based continuous
    archiving, the server might recycle old WAL segments before the standby
    has received them.  If this occurs, the standby will need to be
    reinitialized from a new base backup.  You can avoid this by setting
    <TT
CLASS="VARNAME"
>wal_keep_segments</TT
> to a value large enough to ensure that
    WAL segments are not recycled too early, or by configuring a replication
    slot for the standby.  If you set up a WAL archive that's accessible from
    the standby, these solutions are not required, since the standby can
    always use the archive to catch up provided it retains enough segments.

    To use streaming replication, set up a file-based log-shipping standby
    server as described in Section 26.2. The step that
    turns a file-based log-shipping standby into streaming replication
    standby is setting <TT
CLASS="VARNAME"
>primary_conninfo</TT
> setting in the
    <TT
CLASS="FILENAME"
>recovery.conf</TT
> file to point to the primary server. Set
    listen_addresses and authentication options
    (see <TT
CLASS="FILENAME"
>pg_hba.conf</TT
>) on the primary so that the standby server
    can connect to the <TT
CLASS="LITERAL"
>replication</TT
> pseudo-database on the primary
    server (see Section 26.2.5.1).

    On systems that support the keepalive socket option, setting
    tcp_keepalives_idle,
    tcp_keepalives_interval and
    tcp_keepalives_count helps the primary promptly
    notice a broken connection.

    Set the maximum number of concurrent connections from the standby servers
    (see max_wal_senders for details).

    When the standby is started and <TT
CLASS="VARNAME"
>primary_conninfo</TT
> is set
    correctly, the standby will connect to the primary after replaying all
    WAL files available in the archive. If the connection is established
    successfully, you will see a walreceiver process in the standby, and
    a corresponding walsender process in the primary.

26.2.5.1. Authentication

     It is very important that the access privileges for replication be set up
     so that only trusted users can read the WAL stream, because it is
     easy to extract privileged information from it.  Standby servers must
     authenticate to the primary as a superuser or an account that has the
     <TT
CLASS="LITERAL"
>REPLICATION</TT
> privilege. It is recommended to create a
     dedicated user account with <TT
CLASS="LITERAL"
>REPLICATION</TT
> and <TT
CLASS="LITERAL"
>LOGIN</TT
>
     privileges for replication. While <TT
CLASS="LITERAL"
>REPLICATION</TT
> privilege gives
     very high permissions, it does not allow the user to modify any data on
     the primary system, which the <TT
CLASS="LITERAL"
>SUPERUSER</TT
> privilege does.

     Client authentication for replication is controlled by a
     <TT
CLASS="FILENAME"
>pg_hba.conf</TT
> record specifying <TT
CLASS="LITERAL"
>replication</TT
> in the
     <TT
CLASS="REPLACEABLE"
>database</TT
> field. For example, if the standby is running on
     host IP <TT
CLASS="LITERAL"
>192.168.1.100</TT
> and the account name for replication
     is <TT
CLASS="LITERAL"
>foo</TT
>, the administrator can add the following line to the
     <TT
CLASS="FILENAME"
>pg_hba.conf</TT
> file on the primary:

# Allow the user "foo" from host 192.168.1.100 to connect to the primary
# as a replication standby if the user's password is correctly supplied.
#
# TYPE  DATABASE        USER            ADDRESS                 METHOD
host    replication     foo             192.168.1.100/32        md5

     The host name and port number of the primary, connection user name,
     and password are specified in the <TT
CLASS="FILENAME"
>recovery.conf</TT
> file.
     The password can also be set in the <TT
CLASS="FILENAME"
>~/.pgpass</TT
> file on the
     standby (specify <TT
CLASS="LITERAL"
>replication</TT
> in the <TT
CLASS="REPLACEABLE"
>database</TT
>
     field).
     For example, if the primary is running on host IP <TT
CLASS="LITERAL"
>192.168.1.50</TT
>,
     port <TT
CLASS="LITERAL"
>5432</TT
>, the account name for replication is
     <TT
CLASS="LITERAL"
>foo</TT
>, and the password is <TT
CLASS="LITERAL"
>foopass</TT
>, the administrator
     can add the following line to the <TT
CLASS="FILENAME"
>recovery.conf</TT
> file on the
     standby:

# The standby connects to the primary that is running on host 192.168.1.50
# and port 5432 as the user "foo" whose password is "foopass".
primary_conninfo = 'host=192.168.1.50 port=5432 user=foo password=foopass'

26.2.5.2. Monitoring

     An important health indicator of streaming replication is the amount
     of WAL records generated in the primary, but not yet applied in the
     standby. You can calculate this lag by comparing the current WAL write
     location on the primary with the last WAL location received by the
     standby. They can be retrieved using
     pg_current_xlog_location on the primary and the
     pg_last_xlog_receive_location on the standby,
     respectively (see Table 9-78 and
     Table 9-79 for details).
     The last WAL receive location in the standby is also displayed in the
     process status of the WAL receiver process, displayed using the
     <TT
CLASS="COMMAND"
>ps</TT
> command (see Section 28.1 for details).

     You can retrieve a list of WAL sender processes via the
          <TT
CLASS="LITERAL"
>pg_stat_replication</TT
> view. Large differences between
     pg_current_xlog_location and <TT
CLASS="LITERAL"
>sent_location</TT
> field
     might indicate that the master server is under heavy load, while
     differences between <TT
CLASS="LITERAL"
>sent_location</TT
> and
     pg_last_xlog_receive_location on the standby might indicate
     network delay, or that the standby is under heavy load.

26.2.6. Replication Slots

    Replication slots provide an automated way to ensure that the master does
    not remove WAL segments until they have been received by all standbys,
    and that the master does not remove rows which could cause a
    recovery conflict even when the
    standby is disconnected.

    In lieu of using replication slots, it is possible to prevent the removal
    of old WAL segments using wal_keep_segments, or by
    storing the segments in an archive using
    archive_command.
    However, these methods often result in retaining more WAL segments than
    required, whereas replication slots retain only the number of segments
    known to be needed.  An advantage of these methods is that they bound
    the space requirement for <TT
CLASS="LITERAL"
>pg_xlog</TT
>; there is currently no way
    to do this using replication slots.

    Similarly, hot_standby_feedback
    and vacuum_defer_cleanup_age provide protection against
    relevant rows being removed by vacuum, but the former provides no
    protection during any time period when the standby is not connected,
    and the latter often needs to be set to a high value to provide adequate
    protection.  Replication slots overcome these disadvantages.

26.2.6.1. Querying and manipulating replication slots

     Each replication slot has a name, which can contain lower-case letters,
     numbers, and the underscore character.

     Existing replication slots and their state can be seen in the
     <TT
CLASS="STRUCTNAME"
>pg_replication_slots</TT
>
     view.

     Slots can be created and dropped either via the streaming replication
     protocol (see Section 51.3) or via SQL
     functions (see Section 9.26.6).

26.2.6.2. Configuration Example

     You can create a replication slot like this:

postgres=# SELECT * FROM pg_create_physical_replication_slot('node_a_slot');
  slot_name  | xlog_position
-------------+---------------
 node_a_slot |

postgres=# SELECT * FROM pg_replication_slots;
  slot_name  | slot_type | datoid | database | active | xmin | restart_lsn | confirmed_flush_lsn
-------------+-----------+--------+----------+--------+------+-------------+---------------------
 node_a_slot | physical  |        |          | f      |      |             |
(1 row)

     To configure the standby to use this slot, <TT
CLASS="VARNAME"
>primary_slot_name</TT
>
     should be configured in the standby's <TT
CLASS="FILENAME"
>recovery.conf</TT
>.
     Here is a simple example:

standby_mode = 'on'
primary_conninfo = 'host=192.168.1.50 port=5432 user=foo password=foopass'
primary_slot_name = 'node_a_slot'

26.2.7. Cascading Replication

    The cascading replication feature allows a standby server to accept replication
    connections and stream WAL records to other standbys, acting as a relay.
    This can be used to reduce the number of direct connections to the master
    and also to minimize inter-site bandwidth overheads.

    A standby acting as both a receiver and a sender is known as a cascading
    standby.  Standbys that are more directly connected to the master are known
    as upstream servers, while those standby servers further away are downstream
    servers.  Cascading replication does not place limits on the number or
    arrangement of downstream servers, though each standby connects to only
    one upstream server which eventually links to a single master/primary
    server.

    A cascading standby sends not only WAL records received from the
    master but also those restored from the archive. So even if the replication
    connection in some upstream connection is terminated, streaming replication
    continues downstream for as long as new WAL records are available.

    Cascading replication is currently asynchronous. Synchronous replication
    (see Section 26.2.8) settings have no effect on
    cascading replication at present.

    Hot Standby feedback propagates upstream, whatever the cascaded arrangement.

    If an upstream standby server is promoted to become new master, downstream
    servers will continue to stream from the new master if
    <TT
CLASS="VARNAME"
>recovery_target_timeline</TT
> is set to <TT
CLASS="LITERAL"
>'latest'</TT
>.

    To use cascading replication, set up the cascading standby so that it can
    accept replication connections (that is, set
    max_wal_senders and hot_standby,
    and configure
    host-based authentication).
    You will also need to set <TT
CLASS="VARNAME"
>primary_conninfo</TT
> in the downstream
    standby to point to the cascading standby.

26.2.8. Synchronous Replication

    PostgreSQL streaming replication is asynchronous by
    default. If the primary server
    crashes then some transactions that were committed may not have been
    replicated to the standby server, causing data loss. The amount
    of data loss is proportional to the replication delay at the time of
    failover.

    Synchronous replication offers the ability to confirm that all changes
    made by a transaction have been transferred to one or more synchronous
    standby servers. This extends that standard level of durability
    offered by a transaction commit. This level of protection is referred
    to as 2-safe replication in computer science theory, and group-1-safe
    (group-safe and 1-safe) when <TT
CLASS="VARNAME"
>synchronous_commit</TT
> is set to
    <TT
CLASS="LITERAL"
>remote_write</TT
>.

    When requesting synchronous replication, each commit of a
    write transaction will wait until confirmation is
    received that the commit has been written to the transaction log on disk
    of both the primary and standby server. The only possibility that data
    can be lost is if both the primary and the standby suffer crashes at the
    same time. This can provide a much higher level of durability, though only
    if the sysadmin is cautious about the placement and management of the two
    servers.  Waiting for confirmation increases the user's confidence that the
    changes will not be lost in the event of server crashes but it also
    necessarily increases the response time for the requesting transaction.
    The minimum wait time is the round-trip time between primary to standby.

    Read only transactions and transaction rollbacks need not wait for
    replies from standby servers. Subtransaction commits do not wait for
    responses from standby servers, only top-level commits. Long
    running actions such as data loading or index building do not wait
    until the very final commit message. All two-phase commit actions
    require commit waits, including both prepare and commit.

26.2.8.1. Basic Configuration

    Once streaming replication has been configured, configuring synchronous
    replication requires only one additional configuration step:
    synchronous_standby_names must be set to
    a non-empty value.  <TT
CLASS="VARNAME"
>synchronous_commit</TT
> must also be set to
    <TT
CLASS="LITERAL"
>on</TT
>, but since this is the default value, typically no change is
    required.  (See Section 19.5.1 and
    Section 19.6.2.)
    This configuration will cause each commit to wait for
    confirmation that the standby has written the commit record to durable
    storage.
    <TT
CLASS="VARNAME"
>synchronous_commit</TT
> can be set by individual
    users, so it can be configured in the configuration file, for particular
    users or databases, or dynamically by applications, in order to control
    the durability guarantee on a per-transaction basis.

    After a commit record has been written to disk on the primary, the
    WAL record is then sent to the standby. The standby sends reply
    messages each time a new batch of WAL data is written to disk, unless
    <TT
CLASS="VARNAME"
>wal_receiver_status_interval</TT
> is set to zero on the standby.
    In the case that <TT
CLASS="VARNAME"
>synchronous_commit</TT
> is set to
    <TT
CLASS="LITERAL"
>remote_apply</TT
>, the standby sends reply messages when the commit
    record is replayed, making the transaction visible.
    If the standby is chosen as a synchronous standby, from a priority
    list of <TT
CLASS="VARNAME"
>synchronous_standby_names</TT
> on the primary, the reply
    messages from that standby will be considered along with those from other
    synchronous standbys to decide when to release transactions waiting for
    confirmation that the commit record has been received. These parameters
    allow the administrator to specify which standby servers should be
    synchronous standbys. Note that the configuration of synchronous
    replication is mainly on the master. Named standbys must be directly
    connected to the master; the master knows nothing about downstream
    standby servers using cascaded replication.

    Setting <TT
CLASS="VARNAME"
>synchronous_commit</TT
> to <TT
CLASS="LITERAL"
>remote_write</TT
> will
    cause each commit to wait for confirmation that the standby has received
    the commit record and written it out to its own operating system, but not
    for the data to be flushed to disk on the standby.  This
    setting provides a weaker guarantee of durability than <TT
CLASS="LITERAL"
>on</TT
>
    does: the standby could lose the data in the event of an operating system
    crash, though not a PostgreSQL crash.
    However, it's a useful setting in practice
    because it can decrease the response time for the transaction.
    Data loss could only occur if both the primary and the standby crash and
    the database of the primary gets corrupted at the same time.

    Setting <TT
CLASS="VARNAME"
>synchronous_commit</TT
> to <TT
CLASS="LITERAL"
>remote_apply</TT
> will
    cause each commit to wait until the current synchronous standbys report
    that they have replayed the transaction, making it visible to user
    queries.  In simple cases, this allows for load balancing with causal
    consistency.

    Users will stop waiting if a fast shutdown is requested.  However, as
    when using asynchronous replication, the server will not fully
    shutdown until all outstanding WAL records are transferred to the currently
    connected standby servers.

26.2.8.2. Multiple Synchronous Standbys

    Synchronous replication supports one or more synchronous standby servers;
    transactions will wait until all the standby servers which are considered
    as synchronous confirm receipt of their data. The number of synchronous
    standbys that transactions must wait for replies from is specified in
    <TT
CLASS="VARNAME"
>synchronous_standby_names</TT
>. This parameter also specifies
    a list of standby names, which determines the priority of each standby
    for being chosen as a synchronous standby. The standbys whose names
    appear earlier in the list are given higher priority and will be considered
    as synchronous. Other standby servers appearing later in this list
    represent potential synchronous standbys. If any of the current
    synchronous standbys disconnects for whatever reason, it will be replaced
    immediately with the next-highest-priority standby.

    An example of <TT
CLASS="VARNAME"
>synchronous_standby_names</TT
> for multiple
    synchronous standbys is:

synchronous_standby_names = '2 (s1, s2, s3)'

    In this example, if four standby servers <TT
CLASS="LITERAL"
>s1</TT
>, <TT
CLASS="LITERAL"
>s2</TT
>,
    <TT
CLASS="LITERAL"
>s3</TT
> and <TT
CLASS="LITERAL"
>s4</TT
> are running, the two standbys
    <TT
CLASS="LITERAL"
>s1</TT
> and <TT
CLASS="LITERAL"
>s2</TT
> will be chosen as synchronous standbys
    because their names appear early in the list of standby names.
    <TT
CLASS="LITERAL"
>s3</TT
> is a potential synchronous standby and will take over
    the role of synchronous standby when either of <TT
CLASS="LITERAL"
>s1</TT
> or
    <TT
CLASS="LITERAL"
>s2</TT
> fails. <TT
CLASS="LITERAL"
>s4</TT
> is an asynchronous standby since
    its name is not in the list.

26.2.8.3. Planning for Performance

    Synchronous replication usually requires carefully planned and placed
    standby servers to ensure applications perform acceptably. Waiting
    doesn't utilize system resources, but transaction locks continue to be
    held until the transfer is confirmed. As a result, incautious use of
    synchronous replication will reduce performance for database
    applications because of increased response times and higher contention.

    PostgreSQL allows the application developer
    to specify the durability level required via replication. This can be
    specified for the system overall, though it can also be specified for
    specific users or connections, or even individual transactions.

    For example, an application workload might consist of:
    10% of changes are important customer details, while
    90% of changes are less important data that the business can more
    easily survive if it is lost, such as chat messages between users.

    With synchronous replication options specified at the application level
    (on the primary) we can offer synchronous replication for the most
    important changes, without slowing down the bulk of the total workload.
    Application level options are an important and practical tool for allowing
    the benefits of synchronous replication for high performance applications.

    You should consider that the network bandwidth must be higher than
    the rate of generation of WAL data.

26.2.8.4. Planning for High Availability

    <TT
CLASS="VARNAME"
>synchronous_standby_names</TT
> specifies the number and
    names of synchronous standbys that transaction commits made when
    <TT
CLASS="VARNAME"
>synchronous_commit</TT
> is set to <TT
CLASS="LITERAL"
>on</TT
>,
    <TT
CLASS="LITERAL"
>remote_apply</TT
> or <TT
CLASS="LITERAL"
>remote_write</TT
> will wait for
    responses from. Such transaction commits may never be completed
    if any one of synchronous standbys should crash.

    The best solution for high availability is to ensure you keep as many
    synchronous standbys as requested. This can be achieved by naming multiple
    potential synchronous standbys using <TT
CLASS="VARNAME"
>synchronous_standby_names</TT
>.
    The standbys whose names appear earlier in the list will be used as
    synchronous standbys. Standbys listed after these will take over
    the role of synchronous standby if one of current ones should fail.

    When a standby first attaches to the primary, it will not yet be properly
    synchronized. This is described as <TT
CLASS="LITERAL"
>catchup</TT
> mode. Once
    the lag between standby and primary reaches zero for the first time
    we move to real-time <TT
CLASS="LITERAL"
>streaming</TT
> state.
    The catch-up duration may be long immediately after the standby has
    been created. If the standby is shut down, then the catch-up period
    will increase according to the length of time the standby has been down.
    The standby is only able to become a synchronous standby
    once it has reached <TT
CLASS="LITERAL"
>streaming</TT
> state.

    If primary restarts while commits are waiting for acknowledgement, those
    waiting transactions will be marked fully committed once the primary
    database recovers.
    There is no way to be certain that all standbys have received all
    outstanding WAL data at time of the crash of the primary. Some
    transactions may not show as committed on the standby, even though
    they show as committed on the primary. The guarantee we offer is that
    the application will not receive explicit acknowledgement of the
    successful commit of a transaction until the WAL data is known to be
    safely received by all the synchronous standbys.

    If you really cannot keep as many synchronous standbys as requested
    then you should decrease the number of synchronous standbys that
    transaction commits must wait for responses from
    in <TT
CLASS="VARNAME"
>synchronous_standby_names</TT
> (or disable it) and
    reload the configuration file on the primary server.

    If the primary is isolated from remaining standby servers you should
    fail over to the best candidate of those other remaining standby servers.

    If you need to re-create a standby server while transactions are
    waiting, make sure that the commands pg_start_backup() and
    pg_stop_backup() are run in a session with
    <TT
CLASS="VARNAME"
>synchronous_commit</TT
> = <TT
CLASS="LITERAL"
>off</TT
>, otherwise those
    requests will wait forever for the standby to appear.

26.2.9. Continuous archiving in standby

     When continuous WAL archiving is used in a standby, there are two
     different scenarios: the WAL archive can be shared between the primary
     and the standby, or the standby can have its own WAL archive. When
     the standby has its own WAL archive, set <TT
CLASS="VARNAME"
>archive_mode</TT
>
     to <TT
CLASS="LITERAL"
>always</TT
>, and the standby will call the archive
     command for every WAL segment it receives, whether it's by restoring
     from the archive or by streaming replication. The shared archive can
     be handled similarly, but the <TT
CLASS="VARNAME"
>archive_command</TT
> must
     test if the file being archived exists already, and if the existing file
     has identical contents. This requires more care in the
     <TT
CLASS="VARNAME"
>archive_command</TT
>, as it must
     be careful to not overwrite an existing file with different contents,
     but return success if the exactly same file is archived twice. And
     all that must be done free of race conditions, if two servers attempt
     to archive the same file at the same time.

     If <TT
CLASS="VARNAME"
>archive_mode</TT
> is set to <TT
CLASS="LITERAL"
>on</TT
>, the
     archiver is not enabled during recovery or standby mode. If the standby
     server is promoted, it will start archiving after the promotion, but
     will not archive any WAL it did not generate itself. To get a complete
     series of WAL files in the archive, you must ensure that all WAL is
     archived, before it reaches the standby. This is inherently true with
     file-based log shipping, as the standby can only restore files that
     are found in the archive, but not if streaming replication is enabled.
     When a server is not in recovery mode, there is no difference between
     <TT
CLASS="LITERAL"
>on</TT
> and <TT
CLASS="LITERAL"
>always</TT
> modes.

Prev	Home	Next

Comparison of Different Solutions	Up	Failover


text:
// g_turret.c

#include "g_local.h"

void AnglesNormalize(vec3_t vec)
{
	while(vec[0] > 360)
		vec[0] -= 360;
	while(vec[0] < 0)
		vec[0] += 360;
	while(vec[1] > 360)
		vec[1] -= 360;
	while(vec[1] < 0)
		vec[1] += 360;
}

float SnapToEights(float x)
{
	x *= 8.0;
	if (x > 0.0)
		x += 0.5;
	else
		x -= 0.5;
	return 0.125 * (int)x;
}

void turret_blocked(edict_t *self, edict_t *other)
{
	edict_t	*attacker;

	if (other->takedamage)
	{
		if (self->teammaster->owner)
			attacker = self->teammaster->owner;
		else
			attacker = self->teammaster;
		T_Damage (other, self, attacker, vec3_origin, other->s.origin, vec3_origin, self->teammaster->dmg, 10, 0, MOD_CRUSH);
	}
}

/*QUAKED turret_breach (0 0 0) ?
This portion of the turret can change both pitch and yaw.
The model  should be made with a flat pitch.
It (and the associated base) need to be oriented towards 0.
Use "angle" to set the starting angle.

"speed"		default 50
"dmg"		default 10
"angle"		point this forward
"target"	point this at an info_notnull at the muzzle tip
"minpitch"	min acceptable pitch angle : default -30
"maxpitch"	max acceptable pitch angle : default 30
"minyaw"	min acceptable yaw angle   : default 0
"maxyaw"	max acceptable yaw angle   : default 360
*/

void turret_breach_fire (edict_t *self)
{
	vec3_t	f, r, u;
	vec3_t	start;
	int		damage;
	int		speed;

	AngleVectors (self->s.angles, f, r, u);
	VectorMA (self->s.origin, self->move_origin[0], f, start);
	VectorMA (start, self->move_origin[1], r, start);
	VectorMA (start, self->move_origin[2], u, start);

	damage = 100 + random() * 50;
	speed = 550 + 50 * skill->value;
	fire_rocket (self->teammaster->owner, start, f, damage, speed, 150, damage);
	gi.positioned_sound (start, self, CHAN_WEAPON, gi.soundindex("weapons/rocklf1a.wav"), 1, ATTN_NORM, 0);
}

void turret_breach_think (edict_t *self)
{
	edict_t	*ent;
	vec3_t	current_angles;
	vec3_t	delta;

	VectorCopy (self->s.angles, current_angles);
	AnglesNormalize(current_angles);

	AnglesNormalize(self->move_angles);
	if (self->move_angles[PITCH] > 180)
		self->move_angles[PITCH] -= 360;

	// clamp angles to mins & maxs
	if (self->move_angles[PITCH] > self->pos1[PITCH])
		self->move_angles[PITCH] = self->pos1[PITCH];
	else if (self->move_angles[PITCH] < self->pos2[PITCH])
		self->move_angles[PITCH] = self->pos2[PITCH];

	if ((self->move_angles[YAW] < self->pos1[YAW]) || (self->move_angles[YAW] > self->pos2[YAW]))
	{
		float	dmin, dmax;

		dmin = fabs(self->pos1[YAW] - self->move_angles[YAW]);
		if (dmin < -180)
			dmin += 360;
		else if (dmin > 180)
			dmin -= 360;
		dmax = fabs(self->pos2[YAW] - self->move_angles[YAW]);
		if (dmax < -180)
			dmax += 360;
		else if (dmax > 180)
			dmax -= 360;
		if (fabs(dmin) < fabs(dmax))
			self->move_angles[YAW] = self->pos1[YAW];
		else
			self->move_angles[YAW] = self->pos2[YAW];
	}

	VectorSubtract (self->move_angles, current_angles, delta);
	if (delta[0] < -180)
		delta[0] += 360;
	else if (delta[0] > 180)
		delta[0] -= 360;
	if (delta[1] < -180)
		delta[1] += 360;
	else if (delta[1] > 180)
		delta[1] -= 360;
	delta[2] = 0;

	if (delta[0] > self->speed * FRAMETIME)
		delta[0] = self->speed * FRAMETIME;
	if (delta[0] < -1 * self->speed * FRAMETIME)
		delta[0] = -1 * self->speed * FRAMETIME;
	if (delta[1] > self->speed * FRAMETIME)
		delta[1] = self->speed * FRAMETIME;
	if (delta[1] < -1 * self->speed * FRAMETIME)
		delta[1] = -1 * self->speed * FRAMETIME;

	VectorScale (delta, 1.0/FRAMETIME, self->avelocity);

	self->nextthink = level.time + FRAMETIME;

	for (ent = self->teammaster; ent; ent = ent->teamchain)
		ent->avelocity[1] = self->avelocity[1];

	// if we have adriver, adjust his velocities
	if (self->owner)
	{
		float	angle;
		float	target_z;
		float	diff;
		vec3_t	target;
		vec3_t	dir;

		// angular is easy, just copy ours
		self->owner->avelocity[0] = self->avelocity[0];
		self->owner->avelocity[1] = self->avelocity[1];

		// x & y
		angle = self->s.angles[1] + self->owner->move_origin[1];
		angle *= (M_PI*2 / 360);
		target[0] = SnapToEights(self->s.origin[0] + cos(angle) * self->owner->move_origin[0]);
		target[1] = SnapToEights(self->s.origin[1] + sin(angle) * self->owner->move_origin[0]);
		target[2] = self->owner->s.origin[2];

		VectorSubtract (target, self->owner->s.origin, dir);
		self->owner->velocity[0] = dir[0] * 1.0 / FRAMETIME;
		self->owner->velocity[1] = dir[1] * 1.0 / FRAMETIME;

		// z
		angle = self->s.angles[PITCH] * (M_PI*2 / 360);
		target_z = SnapToEights(self->s.origin[2] + self->owner->move_origin[0] * tan(angle) + self->owner->move_origin[2]);

		diff = target_z - self->owner->s.origin[2];
		self->owner->velocity[2] = diff * 1.0 / FRAMETIME;

		if (self->spawnflags & 65536)
		{
			turret_breach_fire (self);
			self->spawnflags &= ~65536;
		}
	}
}

void turret_breach_finish_init (edict_t *self)
{
	// get and save info for muzzle location
	if (!self->target)
	{
		gi.dprintf("%s at %s needs a target\n", self->classname, vtos(self->s.origin));
	}
	else
	{
		self->target_ent = G_PickTarget (self->target);
		VectorSubtract (self->target_ent->s.origin, self->s.origin, self->move_origin);
		G_FreeEdict(self->target_ent);
	}

	self->teammaster->dmg = self->dmg;
	self->think = turret_breach_think;
	self->think (self);
}

void SP_turret_breach (edict_t *self)
{
	self->solid = SOLID_BSP;
	self->movetype = MOVETYPE_PUSH;
	gi.setmodel (self, self->model);

	if (!self->speed)
		self->speed = 50;
	if (!self->dmg)
		self->dmg = 10;

	if (!st.minpitch)
		st.minpitch = -30;
	if (!st.maxpitch)
		st.maxpitch = 30;
	if (!st.maxyaw)
		st.maxyaw = 360;

	self->pos1[PITCH] = -1 * st.minpitch;
	self->pos1[YAW]   = st.minyaw;
	self->pos2[PITCH] = -1 * st.maxpitch;
	self->pos2[YAW]   = st.maxyaw;

	self->ideal_yaw = self->s.angles[YAW];
	self->move_angles[YAW] = self->ideal_yaw;

	self->blocked = turret_blocked;

	self->think = turret_breach_finish_init;
	self->nextthink = level.time + FRAMETIME;
	gi.linkentity (self);
}

/*QUAKED turret_base (0 0 0) ?
This portion of the turret changes yaw only.
MUST be teamed with a turret_breach.
*/

void SP_turret_base (edict_t *self)
{
	self->solid = SOLID_BSP;
	self->movetype = MOVETYPE_PUSH;
	gi.setmodel (self, self->model);
	self->blocked = turret_blocked;
	gi.linkentity (self);
}

/*QUAKED turret_driver (1 .5 0) (-16 -16 -24) (16 16 32)
Must NOT be on the team with the rest of the turret parts.
Instead it must target the turret_breach.
*/

void infantry_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage);
void infantry_stand (edict_t *self);
void monster_use (edict_t *self, edict_t *other, edict_t *activator);

void turret_driver_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
{
	edict_t	*ent;

	// level the gun
	self->target_ent->move_angles[0] = 0;

	// remove the driver from the end of them team chain
	for (ent = self->target_ent->teammaster; ent->teamchain != self; ent = ent->teamchain)
		;
	ent->teamchain = NULL;
	self->teammaster = NULL;
	self->flags &= ~FL_TEAMSLAVE;

	self->target_ent->owner = NULL;
	self->target_ent->teammaster->owner = NULL;

	infantry_die (self, inflictor, attacker, damage);
}

qboolean FindTarget (edict_t *self);

void turret_driver_think (edict_t *self)
{
	vec3_t	target;
	vec3_t	dir;
	float	reaction_time;

	self->nextthink = level.time + FRAMETIME;

	if (self->enemy && (!self->enemy->inuse || self->enemy->health <= 0))
		self->enemy = NULL;

	if (!self->enemy)
	{
		if (!FindTarget (self))
			return;
		self->monsterinfo.trail_time = level.time;
		self->monsterinfo.aiflags &= ~AI_LOST_SIGHT;
	}
	else
	{
		if (visible (self, self->enemy))
		{
			if (self->monsterinfo.aiflags & AI_LOST_SIGHT)
			{
				self->monsterinfo.trail_time = level.time;
				self->monsterinfo.aiflags &= ~AI_LOST_SIGHT;
			}
		}
		else
		{
			self->monsterinfo.aiflags |= AI_LOST_SIGHT;
			return;
		}
	}

	// let the turret know where we want it to aim
	VectorCopy (self->enemy->s.origin, target);
	target[2] += self->enemy->viewheight;
	VectorSubtract (target, self->target_ent->s.origin, dir);
	vectoangles (dir, self->target_ent->move_angles);

	// decide if we should shoot
	if (level.time < self->monsterinfo.attack_finished)
		return;

	reaction_time = (3 - skill->value) * 1.0;
	if ((level.time - self->monsterinfo.trail_time) < reaction_time)
		return;

	self->monsterinfo.attack_finished = level.time + reaction_time + 1.0;
	//FIXME how do we really want to pass this along?
	self->target_ent->spawnflags |= 65536;
}

void turret_driver_link (edict_t *self)
{
	vec3_t	vec;
	edict_t	*ent;

	self->think = turret_driver_think;
	self->nextthink = level.time + FRAMETIME;

	self->target_ent = G_PickTarget (self->target);
	self->target_ent->owner = self;
	self->target_ent->teammaster->owner = self;
	VectorCopy (self->target_ent->s.angles, self->s.angles);

	vec[0] = self->target_ent->s.origin[0] - self->s.origin[0];
	vec[1] = self->target_ent->s.origin[1] - self->s.origin[1];
	vec[2] = 0;
	self->move_origin[0] = VectorLength(vec);

	VectorSubtract (self->s.origin, self->target_ent->s.origin, vec);
	vectoangles (vec, vec);
	AnglesNormalize(vec);
	self->move_origin[1] = vec[1];

	self->move_origin[2] = self->s.origin[2] - self->target_ent->s.origin[2];

	// add the driver to the end of them team chain
	for (ent = self->target_ent->teammaster; ent->teamchain; ent = ent->teamchain)
		;
	ent->teamchain = self;
	self->teammaster = self->target_ent->teammaster;
	self->flags |= FL_TEAMSLAVE;
}

void SP_turret_driver (edict_t *self)
{
	if (deathmatch->value)
	{
		G_FreeEdict (self);
		return;
	}

	self->movetype = MOVETYPE_PUSH;
	self->solid = SOLID_BBOX;
	self->s.modelindex = gi.modelindex("models/monsters/infantry/tris.md2");
	VectorSet (self->mins, -16, -16, -24);
	VectorSet (self->maxs, 16, 16, 32);

	self->health = 100;
	self->gib_health = 0;
	self->mass = 200;
	self->viewheight = 24;

	self->die = turret_driver_die;
	self->monsterinfo.stand = infantry_stand;

	self->flags |= FL_NO_KNOCKBACK;

	level.total_monsters++;

	self->svflags |= SVF_MONSTER;
	self->s.renderfx |= RF_FRAMELERP;
	self->takedamage = DAMAGE_AIM;
	self->use = monster_use;
	self->clipmask = MASK_MONSTERSOLID;
	VectorCopy (self->s.origin, self->s.old_origin);
	self->monsterinfo.aiflags |= AI_STAND_GROUND|AI_DUCKED;

	if (st.item)
	{
		self->item = FindItemByClassname (st.item);
		if (!self->item)
			gi.dprintf("%s at %s has bad item: %s\n", self->classname, vtos(self->s.origin), st.item);
	}

	self->think = turret_driver_link;
	self->nextthink = level.time + FRAMETIME;

	gi.linkentity (self);
}

redpajama_set_name: RedPajamaGithub


text:
package edu.berkeley.nlp.PCFGLA;

import java.io.Serializable;
import java.util.List;
import java.util.Random;

import edu.berkeley.nlp.PCFGLA.SimpleLexicon.IntegerIndexer;
import edu.berkeley.nlp.PCFGLA.smoothing.Smoother;
import edu.berkeley.nlp.math.CachingDifferentiableFunction;
import edu.berkeley.nlp.math.DifferentiableFunction;
import edu.berkeley.nlp.math.DoubleArrays;
import edu.berkeley.nlp.math.LBFGSMinimizer;
import edu.berkeley.nlp.math.SloppyMath;
import edu.berkeley.nlp.syntax.StateSet;
import edu.berkeley.nlp.syntax.Tree;
import edu.berkeley.nlp.util.ArrayUtil;
import edu.berkeley.nlp.util.Counter;
import edu.berkeley.nlp.util.Indexer;
import edu.berkeley.nlp.util.Pair;
import edu.berkeley.nlp.util.ScalingTools;

/**
 *
 * @author dlwh
 */
public class FeaturizedLexicon implements Lexicon, Serializable {

	private double[][][] expectedCounts; // indexed by tag, substate, word
	private double[][][] scores; // indexed by tag, substate, word
	private double[][] normalizers; // indexed by tag, substate
	public int[] wordCounter; // how many times each word occured (global
								// indexed)
	private int[][] tagWordCounts; // indexed by tag, word (global indexed)
	private int[][] tagWordsWithFeatures; // indexed by tag, index: which
											// tag/word pairs have
											// any features at all. (i.e., which
											// ones are allowed?)
	/**
	 * A trick to allow loading of saved Lexicons even if the version has
	 * changed.
	 */
	private static final long serialVersionUID = 3L;
	/** The number of substates for each state */
	public short[] numSubStates;
	int numStates;
	int nWords;
	double threshold;
	boolean isLogarithmMode;
	boolean useVarDP = false;
	private Indexer<String> wordIndexer = new Indexer<String>();
	public int[][][][] indexedFeatures; // tag, substate, word, substate list of
										// features
	Smoother smoother;
	private Featurizer featurizer;
	private Indexer<String> featureIndex = new Indexer<String>();
	private double[] featureWeights;
	private double regularizationConstant = 1.0;

	/**
	 * Create a blank Lexicon object. Fill it by calling tallyStateSetTree for
	 * each training tree, then calling optimize().
	 *
	 * @param numSubStates
	 */
	@SuppressWarnings("unchecked")
	public FeaturizedLexicon(short[] numSubStates, Featurizer featurizer,
			StateSetTreeList trainTrees) {
		this(numSubStates, featurizer);
		;
		init(trainTrees);
	}

	public FeaturizedLexicon(short[] numSubStates, Featurizer featurizer) {
		this.numSubStates = numSubStates;
		this.wordIndexer = new Indexer<String>();
		this.numStates = numSubStates.length;
		this.isLogarithmMode = false;
		this.featurizer = featurizer;
		minimizer.setMaxIterations(20);
	}

	transient private LBFGSMinimizer minimizer = new LBFGSMinimizer();

	public LBFGSMinimizer getMinimizer() {
		if (minimizer == null) {
			minimizer = new LBFGSMinimizer();
		}
		return minimizer;
	}

	private double[][][] projectWeightsToScores(double[] weights) {
		final double[][][] thetas = new double[numStates][][];
		for (int tag = 0; tag < numStates; tag++) {
			thetas[tag] = new double[numSubStates[tag]][];
			normalizers[tag] = new double[numSubStates[tag]];
			final int expLength = expectedCounts[tag].length;
			for (int substate = 0; substate < expLength; ++substate) {
				thetas[tag][substate] = new double[wordIndexer.size()];
				double[] importantThetas = new double[tagWordsWithFeatures[tag].length];
				int j = 0;
				for (int word : tagWordsWithFeatures[tag]) {
					double score = 0.0;
					if (indexedFeatures[tag][substate][word].length == 0) {
						throw new RuntimeException("Shouldn't be here!");
					} else {
						for (int f : indexedFeatures[tag][substate][word]) {
							score += weights[f];
						}
					}
					thetas[tag][substate][word] = score;
					importantThetas[j++] = score;
				}
				// TODO: updating normalizers here is ugly ugly ugly, but safe
				// enough.
				normalizers[tag][substate] = SloppyMath.logAdd(importantThetas);
				// the rest are pre-inited to 0.0
				for (int word : tagWordsWithFeatures[tag]) {
					thetas[tag][substate][word] = Math
							.exp(thetas[tag][substate][word]
									- normalizers[tag][substate]);
				}
			}
		}
		isLogarithmMode = false;

		return thetas;
	}

	// the m-step objective
	private DifferentiableFunction objective(final double[][][] expectedCounts) { // tag,
																					// substate
		final double[][] eTotals = new double[expectedCounts.length][];
		for (int tag = 0; tag < numStates; tag++) {
			eTotals[tag] = new double[numSubStates[tag]];
			for (int substate = 0; substate < numSubStates[tag]; ++substate) {
				for (int word : tagWordsWithFeatures[tag]) {
					eTotals[tag][substate] += expectedCounts[tag][substate][word];
				}
				eTotals[tag][substate] = Math.log(eTotals[tag][substate]);
			}
		}

		return new CachingDifferentiableFunction() {

			@Override
			public int dimension() {
				return featureWeights.length;
			}

			@Override
			public double valueAt(double[] x) {
				if (isCached(x))
					return super.valueAt(x);
				double[][][] thetas = projectWeightsToScores(x);
				double logProb = 0.0;
				for (int tag = 0; tag < numStates; tag++) {
					final int expLength = expectedCounts[tag].length;
					for (int substate = 0; substate < expLength; ++substate) {
						for (int word : tagWordsWithFeatures[tag]) {
							if (expectedCounts[tag][substate][word] > 0)
								logProb += expectedCounts[tag][substate][word]
										* Math.log(thetas[tag][substate][word]);
						}
					}
				}
				return -logProb + regularizationValue(x);
			}

			@Override
			protected Pair<Double, double[]> calculate(double[] x) {
				double[] gradient = new double[x.length];
				double[][][] thetas = projectWeightsToScores(x);
				double logProb = 0.0;
				for (int tag = 0; tag < numStates; tag++) {
					final int expLength = expectedCounts[tag].length;
					for (int substate = 0; substate < expLength; ++substate) {
						double logTotal = eTotals[tag][substate];
						for (int word : tagWordsWithFeatures[tag]) {
							double e = expectedCounts[tag][substate][word];
							double lT = Math.log(thetas[tag][substate][word]);
							double margin = e - Math.exp(logTotal + lT);

							if (e > 0)
								logProb += expectedCounts[tag][substate][word]
										* Math.log(thetas[tag][substate][word]);

							for (int f : indexedFeatures[tag][substate][word]) {
								// we're doing negative gradient because we're
								// maximizing.
								gradient[f] -= margin;
							}
						}
					}
				}
				double[] finalGrad = DoubleArrays.add(gradient,
						regularizationGradient(x));
				double finalLP = -logProb + regularizationValue(x);
				return Pair.makePair(finalLP, finalGrad);
			}
		};
	}

	private static final double PRIOR_MEAN = -3.0;

	private double[] regularizationGradient(double[] x) {
		double[] centered = DoubleArrays.add(x, -PRIOR_MEAN);
		return DoubleArrays.multiply(centered, regularizationConstant);
	}

	private double regularizationValue(double[] weights) {
		double[] centered = DoubleArrays.add(weights, -PRIOR_MEAN);
		return DoubleArrays.innerProduct(centered, centered) * 0.5
				* regularizationConstant;
	}

	// Should be called whenever the number of features or substates changes.
	private void refeaturize() {
		indexedFeatures = new int[numStates][][][];
		featureIndex = new Indexer<String>();
		tagWordsWithFeatures = new int[numStates][];

		for (int tag = 0; tag < numStates; tag++) {
			IntegerIndexer tagIndexer = new IntegerIndexer(wordIndexer.size());
			indexedFeatures[tag] = new int[numSubStates[tag]][wordIndexer
					.size()][];
			// index all the features for each word seen with this tag.
			for (int globalWordIndex = 0; globalWordIndex < wordIndexer.size(); ++globalWordIndex) {
				String word = wordIndexer.getObject(globalWordIndex);
				List<String>[] features = featurizer.featurize(word, tag,
						numSubStates[tag], wordCounter[globalWordIndex],
						tagWordCounts[tag][globalWordIndex]);
				for (int state = 0; state < numSubStates[tag]; ++state) {
					int[] indices = new int[features[state].size()];
					for (int i = 0; i < indices.length; ++i) {
						indices[i] = featureIndex.getIndex(features[state]
								.get(i));
					}
					indexedFeatures[tag][state][globalWordIndex] = indices;

					if (features[state].size() > 0)
						tagIndexer.add(globalWordIndex);
				}
			}

			tagWordsWithFeatures[tag] = new int[tagIndexer.size()];
			for (int j = 0; j < tagIndexer.size(); ++j) {
				tagWordsWithFeatures[tag][j] = tagIndexer.get(j);
			}

		}

		if (featureWeights == null
				|| featureWeights.length != featureIndex.size()) {
			featureWeights = new double[featureIndex.size()];
		}
	}

	public void optimize() {
		refeaturize();
		LBFGSMinimizer minimizer = getMinimizer();
		DifferentiableFunction objective = objective(expectedCounts);
		minimizer.dumpHistory();
		// System.out.println("pre norm:" +
		// DoubleArrays.innerProduct(featureWeights, featureWeights));
		featureWeights = minimizer.minimize(objective, featureWeights, 1E-5,
				true);
		// System.out.println("post norm1:" +
		// DoubleArrays.innerProduct(featureWeights, featureWeights));
		scores = projectWeightsToScores(featureWeights);
	}

	public double[] score(String word, short tag, int pos, boolean noSmoothing,
			boolean isSignature) {
		StateSet stateSet = new StateSet(tag, (short) 1, word, (short) pos,
				(short) (pos + 1));
		stateSet.wordIndex = -2;
		stateSet.sigIndex = -2;
		return score(stateSet, tag, noSmoothing, isSignature);
	}

	public double[] score(StateSet stateSet, short tag, boolean noSmoothing,
			boolean isSignature) {
		double[] res = new double[numSubStates[tag]];
		int globalWordIndex = stateSet.wordIndex;
		if (globalWordIndex < 1) {
			globalWordIndex = stateSet.wordIndex = wordIndexer.indexOf(stateSet
					.getWord());
		}

		if (globalWordIndex < 0) { // not rare, so it can't be this tag.
			List<String>[] features = featurizer.featurize(stateSet.getWord(),
					tag, numSubStates[tag], 0, 0);
			for (int state = 0; state < numSubStates[tag]; ++state) {
				double score = 0.0;
				for (String feature : features[state]) {
					int index = featureIndex.indexOf(feature);
					if (index >= 0) {
						score += featureWeights[index];
					} else {
						score += 100 * PRIOR_MEAN;
					}
				}
				if (isLogarithmMode()) {
					res[state] = score - normalizers[tag][state];
				} else {
					res[state] = Math.exp(score - normalizers[tag][state]);
				}
			}
		} else { // we've scored this word:
			for (int i = 0; i < numSubStates[tag]; i++) {
				res[i] = scores[tag][i][globalWordIndex];
			}
		}
		return res;
	}

	// no signatures
	public String getSignature(String word, int sentencePosition) {
		return word;
	}

	public boolean isLogarithmMode() {
		return isLogarithmMode;
	}

	public void logarithmMode() {
		if (isLogarithmMode) {
			return;
		}
		for (int tag = 0; tag < scores.length; tag++) {
			for (int word = 0; word < scores[tag].length; word++) {
				for (int substate = 0; substate < scores[tag][word].length; substate++) {
					scores[tag][word][substate] = Math
							.log(scores[tag][word][substate]);
				}
			}
		}
		isLogarithmMode = true;
	}

	/*
	 * assume that rare words have been replaced by their signature
	 */
	public void init(StateSetTreeList trainTrees) {
		for (Tree<StateSet> tree : trainTrees) {
			List<StateSet> words = tree.getYield();
			for (StateSet word : words) {
				String sig = word.getWord();
				wordIndexer.add(sig);
			}
		}

		wordCounter = new int[wordIndexer.size()];
		tagWordCounts = new int[numStates][wordIndexer.size()];

		for (Tree<StateSet> tree : trainTrees) {
			List<StateSet> tags = tree.getPreTerminalYield();
			List<StateSet> words = tree.getYield();
			int ind = 0;
			for (StateSet word : words) {
				String sig = word.getWord();
				wordCounter[wordIndexer.indexOf(sig)]++;
				tagWordCounts[tags.get(ind).getState()][wordIndexer
						.indexOf(sig)]++;
				ind++;
			}
		}

		resetCounts();

		nWords = wordIndexer.size();
		labelTrees(trainTrees);
	}

	public void resetCounts() {
		expectedCounts = new double[numStates][][];
		scores = new double[numStates][][];
		normalizers = new double[numStates][];
		for (int tag = 0; tag < numStates; tag++) {
			expectedCounts[tag] = new double[numSubStates[tag]][wordIndexer
					.size()];
			normalizers[tag] = new double[numSubStates[tag]];
			scores[tag] = new double[numSubStates[tag]][wordIndexer.size()];
		}
	}

	public void labelTrees(StateSetTreeList trainTrees) {
		for (Tree<StateSet> tree : trainTrees) {
			List<StateSet> words = tree.getYield();
			for (StateSet word : words) {
				word.wordIndex = wordIndexer.indexOf(word.getWord());
				word.sigIndex = -1;
			}
		}

	}

	public double[] scoreWord(StateSet stateSet, int tag) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	public double[] scoreSignature(StateSet stateSet, int tag) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	public void trainTree(Tree<StateSet> trainTree, double randomness,
			Lexicon oldLexicon, boolean secondHalf, boolean noSmoothing,
			int unkThreshold) {
		// scan data
		// for all substates that the word's preterminal tag has
		double sentenceScore = 0;
		if (randomness == -1) {
			sentenceScore = trainTree.getLabel().getIScore(0);
			if (sentenceScore == 0) {
				System.out
						.println("Something is wrong with this tree. I will skip it.");
				return;
			}
		}
		int sentenceScale = trainTree.getLabel().getIScale();

		List<StateSet> words = trainTree.getYield();
		List<StateSet> tags = trainTree.getPreTerminalYield();
		// for all words in sentence
		for (int position = 0; position < words.size(); position++) {

			int nSubStates = tags.get(position).numSubStates();
			short tag = tags.get(position).getState();

			String word = words.get(position).getWord();
			int globalWordIndex = wordIndexer.indexOf(word);

			double[] oldLexiconScores = null;
			if (randomness == -1) {
				oldLexiconScores = oldLexicon.score(word, tag, position,
						noSmoothing, false);
			}

			StateSet currentState = tags.get(position);
			double scale = ScalingTools.calcScaleFactor(currentState
					.getOScale() - sentenceScale)
					/ sentenceScore;

			for (short substate = 0; substate < nSubStates; substate++) {
				double weight = 1;
				if (randomness == -1) {
					// weight by the probability of seeing the tag and word
					// together, given the sentence
					if (!Double.isInfinite(scale)) {
						weight = currentState.getOScore(substate)
								* oldLexiconScores[substate] * scale;
					} else {
						weight = Math.exp(Math.log(ScalingTools.SCALE)
								* (currentState.getOScale() - sentenceScale)
								- Math.log(sentenceScore)
								+ Math.log(currentState.getOScore(substate))
								+ Math.log(oldLexiconScores[substate]));
					}
				} else if (randomness == 0) {
					// for the baseline
					weight = 1;
				} else {
					// add a bit of randomness
					weight = GrammarTrainer.RANDOM.nextDouble() * randomness
							/ 100.0 + 1.0;
				}
				if (weight == 0) {
					continue;
				}
				// tally in the tag with the given weight

				expectedCounts[tag][substate][globalWordIndex] += weight;
			}
		}
	}

	public void setSmoother(Smoother smoother) {
		this.smoother = smoother;
	}

	public FeaturizedLexicon splitAllStates(int[] counts,
			boolean moreSubstatesThanCounts, int mode) {
		FeaturizedLexicon splitLex = this.copyLexicon();

		short[] newNumSubStates = new short[numSubStates.length];
		newNumSubStates[0] = 1; // never split ROOT
		for (short i = 1; i < numSubStates.length; i++) {
			newNumSubStates[i] = (short) (numSubStates[i] * 2);
		}
		newNumSubStates[0] = 1; // never split ROOT
		Random random = GrammarTrainer.RANDOM;
		splitLex.numSubStates = newNumSubStates;
		double[][][] newScores = new double[scores.length][][];
		double[][][] newExpCounts = new double[scores.length][][];
		for (int tag = 1; tag < expectedCounts.length; tag++) {
			newScores[tag] = new double[newNumSubStates[tag]][wordIndexer
					.size()];
			newExpCounts[tag] = new double[newNumSubStates[tag]][wordIndexer
					.size()];
			for (int substate = 0; substate < numSubStates[tag]; substate++) {
				for (int word = 0; word < scores[tag][substate].length; word++) {
					newScores[tag][2 * substate][word] = newScores[tag][2 * substate + 1][word] = scores[tag][substate][word];
					if (mode == 2) {
						newScores[tag][2 * substate][word] = newScores[tag][2 * substate + 1][word] = 1.0 + random
								.nextDouble() / 100.0;
					}
				}
			}
		}
		splitLex.scores = newScores;
		splitLex.expectedCounts = newExpCounts;
		return splitLex;
	}

	/**
	 * @param mergeThesePairs
	 * @param mergeWeights
	 */
	public void mergeStates(boolean[][][] mergeThesePairs,
			double[][] mergeWeights) {
		short[] newNumSubStates = new short[numSubStates.length];
		short[][] mapping = new short[numSubStates.length][];
		// invariant: if partners[state][substate][0] == substate, it's the 1st
		// one
		short[][][] partners = new short[numSubStates.length][][];
		Grammar.calculateMergeArrays(mergeThesePairs, newNumSubStates, mapping,
				partners, numSubStates);

		double[][][] newScores = new double[scores.length][][];
		for (int tag = 1; tag < expectedCounts.length; tag++) {
			newScores[tag] = new double[newNumSubStates[tag]][wordIndexer
					.size()];
			if (numSubStates[tag] == 1)
				continue;
			for (int word = 0; word < expectedCounts[tag][0].length; word++) {
				for (int i = 0; i < numSubStates[tag]; i = i + 2) {
					int nSplit = partners[tag][i].length;
					if (nSplit == 2) {
						double mergeWeightSum = mergeWeights[tag][partners[tag][i][0]]
								+ mergeWeights[tag][partners[tag][i][1]];
						if (mergeWeightSum == 0)
							mergeWeightSum = 1;
						newScores[tag][mapping[tag][i]][word] = ((mergeWeights[tag][partners[tag][i][0]] * scores[tag][partners[tag][i][0]][word]) + (mergeWeights[tag][partners[tag][i][1]] * scores[tag][partners[tag][i][1]][word]))
								/ mergeWeightSum;
					} else {
						newScores[tag][mapping[tag][i]][word] = scores[tag][i][word];
						newScores[tag][mapping[tag][i + 1]][word] = scores[tag][i + 1][word];
					}
				}
			}
		}
		this.numSubStates = newNumSubStates;
		this.scores = newScores;
		for (int tag = 0; tag < numStates; tag++) {
			this.expectedCounts[tag] = new double[newNumSubStates[tag]][wordIndexer
					.size()];
		}
	}

	public Smoother getSmoother() {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	public double[] getSmoothingParams() {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	public FeaturizedLexicon projectLexicon(double[] condProbs,
			int[][] mapping, int[][] toSubstateMapping) {
		short[] newNumSubStates = new short[numSubStates.length];
		for (int state = 0; state < numSubStates.length; state++) {
			newNumSubStates[state] = (short) toSubstateMapping[state][0];
		}
		FeaturizedLexicon newLexicon = this.copyLexicon();

		double[][][] newScores = new double[scores.length][][];

		for (short tag = 0; tag < scores.length; tag++) {
			newScores[tag] = new double[newNumSubStates[tag]][wordIndexer
					.size()];
			for (int word = 0; word < scores[tag][0].length; word++) {
				for (int substate = 0; substate < numSubStates[tag]; substate++) {
					newScores[tag][toSubstateMapping[tag][substate + 1]][word] += condProbs[mapping[tag][substate]]
							* scores[tag][substate][word];

				}
			}
		}

		newLexicon.numStates = newScores.length;
		newLexicon.numSubStates = newNumSubStates;
		newLexicon.scores = newScores;

		newLexicon.expectedCounts = new double[numStates][][];
		for (short tag = 0; tag < numStates; tag++) {
			newLexicon.expectedCounts[tag] = new double[newNumSubStates[tag]][wordIndexer
					.size()];
			for (int substate = 0; substate < newNumSubStates[tag]; substate++) {
				for (int word = 0; word < wordIndexer.size(); ++word) {
					newLexicon.expectedCounts[tag][substate][word] = isLogarithmMode ? Math
							.exp(newScores[tag][substate][word])
							: newScores[tag][substate][word];
				}
			}
		}

		newLexicon.optimize();
		return newLexicon;
	}

	public FeaturizedLexicon copyLexicon() {
		FeaturizedLexicon copy = new FeaturizedLexicon(numSubStates, featurizer);
		copy.expectedCounts = new double[numStates][][];
		copy.scores = ArrayUtil.clone(scores);// new double[numStates][][];
		copy.wordIndexer = this.wordIndexer;
		for (int tag = 0; tag < numStates; tag++) {
			copy.expectedCounts[tag] = new double[numSubStates[tag]][wordIndexer
					.size()];
		}
		copy.nWords = this.nWords;
		copy.smoother = this.smoother;
		copy.numStates = this.numStates;
		copy.numSubStates = this.numSubStates;
		copy.wordCounter = this.wordCounter.clone();
		copy.tagWordCounts = ArrayUtil.clone(tagWordCounts);
		copy.tagWordsWithFeatures = ArrayUtil.clone(tagWordsWithFeatures);
		copy.featureWeights = ArrayUtil.clone(featureWeights);
		copy.normalizers = ArrayUtil.clone(normalizers);
		copy.featureIndex = this.featureIndex;
		copy.indexedFeatures = indexedFeatures;
		return copy;
	}

	public void removeUnlikelyTags(double threshold, double exponent) {
		// throw new UnsupportedOperationException("Not supported yet.");
	}

	public double getPruningThreshold() {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	public void tieRareWordStats(int threshold) {
		return;
	}

	public Counter<String> getWordCounter() {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	public void explicitlyComputeScores(int finalLevel) {
		throw new UnsupportedOperationException("Not supported yet.");
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>integration-service</artifactId>
  <packaging>jar</packaging>

  <parent>
  	<groupId>com.jimmy.integration</groupId>
  	<artifactId>integration-root</artifactId>
  	<version>1.0-SNAPSHOT</version>
  	<relativePath>../integration-root/pom.xml</relativePath>
  </parent>

  <name>integration-service</name>
  <url>http://maven.apache.org</url>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
import src.settings as var
from src.utilities import *
from src import debuglog, errlog, plog
from src.decorators import cmd, event_listener
from src.messages import messages
from src.events import Event

# handles villager and cultist

@event_listener("transition_night_end", priority=2)
def on_transition_night_end(evt, cli, var):
    if var.FIRST_NIGHT or var.ALWAYS_PM_ROLE:
        villroles = var.HIDDEN_VILLAGERS | {"villager"}
        if var.DEFAULT_ROLE == "villager":
            villroles |= var.HIDDEN_ROLES
        villagers = list_players(villroles)
        for villager in villagers:
            if villager in var.PLAYERS and not is_user_simple(villager):
                pm(cli, villager, messages["villager_notify"])
            else:
                pm(cli, villager, messages["villager_simple"])

        cultroles = {"cultist"}
        if var.DEFAULT_ROLE == "cultist":
            cultroles |= var.HIDDEN_ROLES
        cultists = list_players(cultroles)
        for cultist in cultists:
            if cultist in var.PLAYERS and not is_user_simple(cultist):
                pm(cli, cultist, messages["cultist_notify"])
            else:
                pm(cli, cultist, messages["cultist_simple"])

# No listeners should register before this one
# This sets up the initial state, based on village/wolfteam/neutral affiliation
@event_listener("player_win", priority=0)
def on_player_win(evt, cli, var, nick, role, winner, survived):
    # init won/iwon to False
    evt.data["won"] = False
    evt.data["iwon"] = False

    if role in var.WOLFTEAM_ROLES or (var.DEFAULT_ROLE == "cultist" and role in var.HIDDEN_ROLES):
        if winner == "wolves":
            evt.data["won"] = True
            evt.data["iwon"] = survived
    elif role in var.TRUE_NEUTRAL_ROLES:
        # handled in their individual files
        pass
    elif winner == "villagers":
        evt.data["won"] = True
        evt.data["iwon"] = survived

# vim: set sw=4 expandtab:


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

<TITLE>
VertexSetListener (JGraphT : a free Java graph library)
</TITLE>

<META NAME="date" CONTENT="2010-11-27">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.jgrapht.event

Interface VertexSetListener<V>

All Superinterfaces:
java.util.EventListener

All Known Subinterfaces:
GraphListener<V,E>

All Known Implementing Classes:
ConnectivityInspector, DirectedNeighborIndex, NeighborIndex

public interface VertexSetListener<V>
extends java.util.EventListener

A listener that is notified when the graph's vertex set changes. It should be
 used when only notifications on vertex-set changes are of interest. If
 all graph notifications are of interest better use
 GraphListener.

Since:

Jul 18, 2003

Author:

Barak Naveh

See Also:
GraphListener

Method Summary

 void
vertexAdded(GraphVertexChangeEvent<V> e)

          Notifies that a vertex has been added to the graph.

 void
vertexRemoved(GraphVertexChangeEvent<V> e)

          Notifies that a vertex has been removed from the graph.

Method Detail

vertexAdded

void vertexAdded(GraphVertexChangeEvent<V> e)

Notifies that a vertex has been added to the graph.

Parameters:
e - the vertex event.

vertexRemoved

void vertexRemoved(GraphVertexChangeEvent<V> e)

Notifies that a vertex has been removed from the graph.

Parameters:
e - the vertex event.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
Washington Metropolitan Area Transit Authority API Node.JS Wrapper
============================================

[![Tests](https://travis-ci.org/anderMatt/wmata-api-node.svg?branch=master)](https://travis-ci.org/anderMatt/wmata-api-node)
[![Coverage Status](https://coveralls.io/repos/anderMatt/wmata-api-node/badge.svg)](https://coveralls.io/r/anderMatt/wmata-api-node)

This is a wrapper for the [WMATA Web API](https://developer.wmata.com) that
runs on Node.JS.

It includes helper functions to do the following:

#### Bus Information
- Bus positions
- Bus arrival time predictions

#### Train Information
- Train positions
- Train arrival time predictions

##### Dependencies

This project deponds on [request](https://github.com/request/request) to make HTTP requests.

## Installation

    $ npm install wmata-api-node --save

## Usage

First, instantiate the wrapper.
```javascript
var WmataApi = require('wmata-api-node');

// Instantiate the api with your api key
var wmataApi = new WmataApi('mysupersecretkey123');
```

Use the wrapper's methods to make requests to WMATA's web API. Methods use promises, so be sure to provide success and error handlers.
```javascript
// Get bus positions for the D2 line
wmataApi.getBusPositions('D2')
    .then(data => {
        console.log('Bus positions', data.BusPositions);
    })
    .catch(err => {
        console.error(err);
    });
```

### Authorization
You must provide an API key to the wrapper at instantiation. See [WMATA's API documentation](https://developer.wmata.com) for steps on obtaining your free API key.

## Development

Discover a bug, or have improvements? [Open an issue](https://github.com/anderMatt/wmata-api-node/issues/new) or clone the project and send a pull request with your changes!

### Running tests
You can run unit tests by executing `mocha`.


text:
package com.hazelcast.partition;

import java.util.EventListener;

/**
 * MigrationListener provides the ability to listen to
 * partition migration process and events.
 *
 * @see Partition
 * @see PartitionService
 * @see MigrationState
 * @see ReplicaMigrationEvent
 */
public interface MigrationListener extends EventListener {

    /**
     * Called when the migration process starts.
     * A migration process consists of a group of partition
     * replica migrations which are planned together.
     *

     * When migration process is completed, {@link #migrationFinished(MigrationState)}
     * is called.
     *
     * @param state Plan of the migration process
     */
    void migrationStarted(MigrationState state);

    /**
     * Called when the migration process finishes.
     * This event denotes ending of migration process which is
     * started by {@link #migrationStarted(MigrationState)}.
     *

     * Not all of the planned migrations have to be completed.
     * Some of them can be skipped because of a newly created migration plan.
     *

     * If migration process coordinator member (generally the oldest member in cluster)
     * crashes before migration process ends, then this method may not be called at all.
     *
     * @param state Result of the migration process
     */
    void migrationFinished(MigrationState state);

    /**
     * Called when a partition replica migration is completed successfully.
     *
     * @param event the event for the partition replica migration
     */
    void replicaMigrationCompleted(ReplicaMigrationEvent event);

    /**
     * Called when a partition replica migration is failed.
     *
     * @param event the event for the partition replica migration
     */
    void replicaMigrationFailed(ReplicaMigrationEvent event);

}


text:
HTML Attribute Content takes a string and preps it for use inside HTML tag attributes. You might find this handy when using content inside attributes of certain tags, like `<meta>` tags used by [Twitter Cards](https://dev.twitter.com/docs/cards).

**NOTE: This add-on is largely not needed in ExpressionEngine 4. Most variables can use the `:attr_safe` modifier. This plugin can still be useful on arbitrary text in a template, from non-standard sources.**

## Requirements

- ExpressionEngine 4

## Usage

### `{exp:html_attribute_content}`

*Note:* If your tagdata contains an ExpressionEngine typography code-syntax highlighted codeblock, it will be stripped in its entirety, since it cannot be summarized.

#### Example Usage

It strips tags, turns single and double quotes into entities, then optionally limits to a fixed number of characters (retaining whole words), and appends a terminating character.

```
{exp:html_attribute_content limit='200' end_char='…'}
    content to make safe for use in a tag parameter
{/exp:html_attribute_content}
```

#### Parameters

##### limit (optional)

`limit='200'`

The number of characters to limit the output to (keeps whole words).

##### double_encode (optional, default='no')

`double_encode='yes'`

yes/no. Whether or not to double-encode character entities.

##### end_char (optional, default='…')

`end_char='…'`

A terminating character (or characters) to append to the string. The limit parameter takes this into consideration, so your final string will still
be within the bounds of your specified limit.

##### unicode_punctuation (optional, default='yes')

`unicode_punctuation='yes'`

Whether or not to use unicode punctuation characters instead of entities. Handy for things like meta tags, where HTML entities may not be parsed.

## Change Log

### 3.0.0

- Modified for ExpressionEngine 4
- Switched to ExpressionEngine's `attributeSafe()` formatter for application consistency.
    - **NOTE:** this may flip your `double_encode=` parameter setting, as the new default is to _not_ double encode.
    - This also adds the `unicode_punctuation=` parameter

### 2.1.4

- standardizing MIT license

### 2.1.3

- Updating build system for GitHub download generation.

### 2.1.2

- Cleaned up GitHub release download package

### 2.1.1

- Fixed a typo in the README

### 2.1

- added `double_encode=` parameter to optionally disable double-encoding of character entities

### 2.0

- Updated plugin to be 3.0 compatible

### 1.0

- Released

## License

Copyright (c) 2015 EllisLab, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

### Exclusions

Except as contained in this notice, the name of EllisLab, Inc. shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from EllisLab, Inc.


text:
package org.javaswift.joss.command.impl.object;

import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.javaswift.joss.command.impl.core.httpstatus.HttpStatusChecker;
import org.javaswift.joss.command.impl.core.httpstatus.HttpStatusFailCondition;
import org.javaswift.joss.command.impl.core.httpstatus.HttpStatusMatch;
import org.javaswift.joss.command.impl.core.httpstatus.HttpStatusSuccessCondition;
import org.javaswift.joss.command.shared.object.CopyObjectCommand;
import org.javaswift.joss.headers.object.CopyFrom;
import org.javaswift.joss.model.Access;
import org.javaswift.joss.model.Account;
import org.javaswift.joss.model.StoredObject;

public class CopyObjectCommandImpl extends AbstractObjectCommand<HttpPut, Object> implements CopyObjectCommand {

    public CopyObjectCommandImpl(Account account, HttpClient httpClient, Access access,
                                 StoredObject sourceObject, StoredObject targetObject) {
        super(account, httpClient, access, targetObject);
        setHeader(new CopyFrom(sourceObject.getPath()));
    }

    @Override
    protected HttpPut createRequest(String url) {
        return new HttpPut(url);
    }

    @Override
    public HttpStatusChecker[] getStatusCheckers() {
        return new HttpStatusChecker[] {
            new HttpStatusSuccessCondition(new HttpStatusMatch(HttpStatus.SC_CREATED)),
            new HttpStatusFailCondition(new HttpStatusMatch(HttpStatus.SC_NOT_FOUND))
        };
    }

}


text:
 # Learn Reactive Extensions for JavaScript

- Tutorials
    - [The introduction to Reactive Programming you've been missing](https://gist.github.com/staltz/868e7e9bc2a7b8c1f754)
    - [2 minute introduction to Rx](https://medium.com/@andrestaltz/2-minute-introduction-to-rx-24c8ca793877)
    - [Learn RxJS - @jhusain](https://github.com/jhusain/learnrx)
    - [RxJS Koans](https://github.com/Reactive-Extensions/RxJSKoans)
    - [RxJS Workshop from BuildStuff 2014](https://github.com/Reactive-Extensions/BuildStuffWorkshop)
    - [Rx Workshop](http://rxworkshop.codeplex.com/)
    - [Reactive Programming and MVC](http://aaronstacy.com/writings/reactive-programming-and-mvc/)
    - [RxJS lessons - egghead.io](https://egghead.io/technologies/rx)
    - [RxJS Training - @andrestaltz](https://github.com/staltz/rxjs-training)

- Reference Material
    - [Rx Marbles](http://rxmarbles.com/)
    - [RxJS GitBook](http://xgrommx.github.io/rx-book/)
    - [Intro to Rx](http://introtorx.com/)
    - [101 Rx Samples Wiki](http://rxwiki.wikidot.com/101samples)
    - [RxJS Design Guidelines](https://github.com/Reactive-Extensions/RxJS/tree/master/doc/designguidelines)
    - [Visualizing Reactive Streams](http://jaredforsyth.com/2015/03/06/visualizing-reactive-streams-hot-and-cold/)
    - [Your Mouse is a Database](http://queue.acm.org/detail.cfm?id=2169076)

- Essential tools
    - [RxVision](http://jaredforsyth.com/rxvision/)
    - [Percussion](https://github.com/grisendo/Percussion)

- Books
    - [RxJS in Action](https://www.manning.com/books/rxjs-in-action)
    - [RxJS](http://xgrommx.github.io/rx-book/)
    - [Intro to Rx](http://www.amazon.com/Introduction-to-Rx-ebook/dp/B008GM3YPM/)
    - [Programming Reactive Extensions and LINQ](http://www.amazon.com/Programming-Reactive-Extensions-Jesse-Liberty/dp/1430237473/)
    - [Reactive Programming with RxJS](https://pragprog.com/book/smreactjs/reactive-programming-with-rxjs)

- [Community Examples](examples/community.md)
- [Presentations](examples/presentations.md)
- [Videos and Podcasts](examples/videos.md)


text:
<?php

/**
 * @namespace
 */
namespace PopTest\Pdf;

use Pop\Loader\Autoloader;
use Pop\Pdf\Object\Object;

// Require the library's autoloader.
require_once __DIR__ . '/../../../src/Pop/Loader/Autoloader.php';

// Call the autoloader's bootstrap function.
Autoloader::factory()->splAutoloadRegister();

class ObjectTest extends \PHPUnit_Framework_TestCase
{

    public function testConstructor()
    {
        $this->assertInstanceOf('Pop\Pdf\Object\Object', new Object(1));
    }

    public function testSetAndGetDef()
    {
        $o = new Object(5);
        $o->define('some def /Xobject something');
        $this->assertEquals('some def /Xobject something', $o->getDef());
        $this->assertTrue($o->isXObject());
        $this->assertEquals(40, $o->getByteLength());
    }

    public function testGetStream()
    {
        $o = new Object("<<5 0 obj\nstream\nBlah Blah\nendstreamendobj\n>>");
        $this->assertEquals('Blah Blah', trim($o->getStream()));
    }

    public function testCompress()
    {
        $o = new Object("<<5 0 obj\nstream\nBlah Blah\nendstreamendobj\n>>");
        $o->compress();
        $this->assertContains('<</Length 16 /Filter /FlateDecode>>', (string)$o);
        $this->assertTrue($o->isCompressed());
    }

    public function testSetAndGetPalette()
    {
        $o = new Object("<<5 0 obj\nstream\nBlah Blah\nendstreamendobj\n>>");
        $o->setPalette(true);
        $this->assertTrue($o->isPalette());
    }

}


text:
package edu.uci.python.nodes.function;

import com.oracle.truffle.api.*;
import com.oracle.truffle.api.frame.*;

import edu.uci.python.nodes.*;
import edu.uci.python.runtime.*;
import edu.uci.python.runtime.function.*;

public class GeneratorFunctionDefinitionNode extends FunctionDefinitionNode {

    protected final int numOfActiveFlags;
    protected final int numOfGeneratorBlockNode;
    protected final int numOfGeneratorForNode;

    public GeneratorFunctionDefinitionNode(String name, String enclosingClassName, PythonContext context, Arity arity, PNode defaults, RootCallTarget callTarget, FrameDescriptor frameDescriptor,
                    boolean needsDeclarationFrame, int numOfActiveFlags, int numOfGeneratorBlockNode, int numOfGeneratorForNode) {
        super(name, enclosingClassName, context, arity, defaults, callTarget, frameDescriptor, needsDeclarationFrame);
        this.numOfActiveFlags = numOfActiveFlags;
        this.numOfGeneratorBlockNode = numOfGeneratorBlockNode;
        this.numOfGeneratorForNode = numOfGeneratorForNode;
    }

    public static GeneratorFunctionDefinitionNode create(String name, String enclosingClassName, PythonContext context, Arity arity, PNode defaults, RootCallTarget callTarget,
                    FrameDescriptor frameDescriptor, boolean needsDeclarationFrame, int numOfActiveFlags, int numOfGeneratorBlockNode, int numOfGeneratorForNode) {
        if (needsDeclarationFrame || !EmptyNode.isEmpty(defaults)) {
            return new GeneratorFunctionDefinitionNode(name, enclosingClassName, context, arity, defaults, callTarget, frameDescriptor, needsDeclarationFrame, numOfActiveFlags,
                            numOfGeneratorBlockNode, numOfGeneratorForNode);
        }

        return new StatelessGeneratorFunctionDefinitionNode(name, enclosingClassName, context, arity, callTarget, frameDescriptor, numOfActiveFlags, numOfGeneratorBlockNode, numOfGeneratorForNode);
    }

    @Override
    public Object execute(VirtualFrame frame) {
        defaults.executeVoid(frame);
        MaterializedFrame declarationFrame = needsDeclarationFrame ? frame.materialize() : null;
        return new PGeneratorFunction(name, enclosingClassName, arity, callTarget, frameDescriptor, declarationFrame, numOfActiveFlags, numOfGeneratorBlockNode, numOfGeneratorForNode);
    }

    /**
     * Creates a generator function that does not capture any state. Therefore, it can always return
     * the same generator function instance.
     */
    public static final class StatelessGeneratorFunctionDefinitionNode extends GeneratorFunctionDefinitionNode {

        private final PGeneratorFunction cached;

        public StatelessGeneratorFunctionDefinitionNode(String name, String enclosingClassName, PythonContext context, Arity arity, RootCallTarget callTarget, FrameDescriptor frameDescriptor,
                        int numOfActiveFlags, int numOfGeneratorBlockNode, int numOfGeneratorForNode) {
            super(name, enclosingClassName, context, arity, EmptyNode.create(), callTarget, frameDescriptor, false, numOfActiveFlags, numOfGeneratorBlockNode, numOfGeneratorForNode);
            cached = new PGeneratorFunction(name, enclosingClassName, arity, callTarget, frameDescriptor, null, numOfActiveFlags, numOfGeneratorBlockNode, numOfGeneratorForNode);
        }

        public StatelessGeneratorFunctionDefinitionNode(GeneratorExpressionNode prev) {
            super(prev.getName(), null, prev.context, Arity.DUMMY, EmptyNode.create(), prev.getCallTarget(), prev.getFrameDescriptor(), false, prev.getNumOfActiveFlags(),
                            prev.getNumOfGeneratorBlockNode(), prev.getNumOfGeneratorForNode());
            cached = new PGeneratorFunction(name, enclosingClassName, arity, callTarget, frameDescriptor, null, numOfActiveFlags, numOfGeneratorBlockNode, numOfGeneratorForNode);
        }

        @Override
        public Object execute(VirtualFrame frame) {
            return cached;
        }
    }

}


text:
This template deploys the Nylas Sync Engine on a Debian VM in Azure. This allows you to sync your email with the Nylas N1 email client on a Linux OS like Ubuntu.

For more information on the Nylas sync engine, see https://github.com/nylas/sync-engine


text:
package com.worizon.junit.jsonresponse;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.util.List;

import org.junit.Test;

import com.worizon.jsonrpc.JsonRpcResponse;

public class JsonRpcDoubleListResponseTest {

	@Test
	public void testResult() throws Exception{

		String message = "{\"jsonrpc\": \"2.0\", \"result\": [-19.8,10.2,54.9,67.1], \"id\": 2}";
		JsonRpcResponse<List> res = new JsonRpcResponse<List>(message, List.class);

		assertThat( new Double[]{-19.8d,10.2d,54.9d,67.1d}, is(equalTo(res.getResult().toArray())));
		assertThat( res.getId(), is(2L) );
		assertThat(res.getVersion(), is(equalTo("2.0")));
		assertThat(res.getError(), is(nullValue()));

	}

	@Test
	public void testNull() throws Exception{

		String message = "{\"jsonrpc\": \"2.0\", \"result\": null, \"id\": 2}";
		JsonRpcResponse<float[]> res = new JsonRpcResponse<float[]>(message, float[].class);

		assertThat(res.getResult(), is(nullValue()));

	}

}


text:
- [Notepad++][Notepad++] (or some other decent text editor)
- Windows 8 or later
- [Create Discord Bot application](http://nadekobot.readthedocs.io/en/latest/JSON%20Explanations/#creating-discord-bot-application) and [Invite the bot to your server](http://nadekobot.readthedocs.io/en/latest/JSON%20Explanations/#inviting-your-bot-to-your-server).

#### Guide
- Download and run the [NadekoBot Updater.][Updater]
- Press **`Install ffmpeg`** and **`Install youtube-dl`** if you want music features.
***NOTE:** RESTART YOUR PC IF YOU DO.*
- Press **`Update`** and go through the installation wizard.
***NOTE:** If you're upgrading from 1.3, DO NOT select your old nadekobot folder. Install it in a separate directory and read the [upgrading guide](http://nadekobot.readthedocs.io/en/latest/guides/Upgrading%20Guide/).*
- When installation is finished, make sure **`Open credentials.json`** is checked.
***NOTE:** Make sure to open it with Notepad++ or some other decent text editor.*
- [Set up credentials.json](http://nadekobot.readthedocs.io/en/latest/JSON%20Explanations/#setting-up-credentialsjson-file) file.

#### Starting the bot
- Either press **`Start`** Button in the updater, or run the bot via it's desktop shortcut.

#### Updating NadekoBot
- Make sure the bot is closed and is not running
(Run `.die` in a connected server to ensure it's not running).
- Open NadekoBot Updater
- If updates are available, you will be able to click on the Update button
- Start the bot
- You've updated and are running again, easy as that!

[Updater]: https://download.nadekobot.me/
[DiscordApp]: https://discordapp.com/developers/applications/me
[Notepad++]: https://notepad-plus-plus.org/
[Invite Guide]: http://discord.kongslien.net/guide.html
[Google Console]: https://console.developers.google.com
[.NET Core SDK]: https://www.microsoft.com/net/core#windowscmd


text:
<!DOCTYPE html>

	<title>Lode Runner - Playful Pasts</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
 	<link rel="shortcut icon" type="image/x-icon" href="../favicon.ico" />
  	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>

  <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

	<link rel="stylesheet" type="text/css" href="../css/game.css">
	<link rel="stylesheet" type="text/css" href="../css/navbar.css">
	<link rel="stylesheet" type="text/css" href="../css/waves.css">

				Issue 10 - July 1983
				Lode Runner

				
				

An Apple ][ Emulator in JavaScript written by Will Scullin

							<canvas id="screen" width="560" height="384"></canvas>

0KHz

						No Disk Inserted

							<button id="diskload1" class="diskload" value="Load"	onclick="document.getElementById('local_file').click(); return false;">
							Load Disk
							</button>

						<button id="resetGame" onclick="resetCheck();">
							Reset
						</button>
						<form id="uploaddsk" action="#">
							<input type="file" id="local_file" accept=".dsk, .do, .po, nib, 2mg" onchange="doLoadLocal();" style="visibility: hidden;"/>
						</form>

							Green Screen
  						<input type="checkbox" id="green_screen" accept=".dsk, .do, .po, .nib, .2mg" onclick="updateScreen()" checked="checked">

Lode Runner

					In Lode Runner, you are an intergalactic commando charged with recovering gold stashed away in 150 different treasure chambers put there by the deranged leadership of the Bungeling Empire. The leadership of the Empire got the gold by swindling their people out of it via fast-food taxes. You have tools allowing you to dig and drill through bricks for the gold. Once all the gold on a level has been collected, a ladder allowing you to move onto the next screen is added.

					Quick Start

					The default keys for playing are printed on the first screen you'll see when the disk loads. You can change them before you begin if you want.

					If you ever can't control the game with your keyboard, try clicking on the screen.

					Impact

					Lode Runner was one of the earliest games to include a level editor, allowing the creation of new level designs with no programming skill. There are ten types of building blocks to use in creating the screens including trap doors and monkey bars. Softline's July 1983 issue describes Lode Runner as addicting and a ton of fun.

Production History

					Lode Runner was created by Doug Smith in 1983. It was published by Brøderbund Software. Brøderbund, headed by Doug Carlston - who was one a member of the "brotherhood" of game makers in the early 1980s - was purchased by The Learning Company in 1998. However, the brand can still be seen on some original Brøderbund products.

Help

				The Game page contains game play information, a link to a manual (if available), and the impact and history of the game. This is where you will upload and play the game you downloaded on the Magazine page.

			Playing a Game

Select Load Disk on the Apple II emulator (Your File/Finder window will appear)

Select the game .dsk file in the Download folder in your File/Finder window

Click Open in the File/Finder window after selecting the game .dsk file

Play the game in the Apple II emulator

      CLOSE