text:
import logging

from . import pg_connection
from ._util import closing, table_exists, trigger_exists
from ._adapter import determine_keep_history

logger = logging.getLogger(__name__)

NOTIFY = 'newt_object_state_changed'
PROGRESS_TABLE = 'newt_follow_progress'

def non_empty_generator(gen):
    try:
        first = next(gen)
    except StopIteration:
        return None
    def it():
        yield first
        for v in gen:
            yield v
    return it()

trigger_sql = """
create function newt_notify_object_state_changed() returns trigger
as $$
begin
  perform pg_notify('%s', NEW.tid::text);
  return NEW;
end;
$$ language plpgsql;

create trigger newt_trigger_notify_object_state_changed
  after insert or update on object_state for each row
  execute procedure newt_notify_object_state_changed();
""" % NOTIFY

class Updates:

    _query = """
    select s.tid, s.zoid, state from object_state s
    where s.tid > %s UPPER order by s.tid
    """

    def __init__(self, dsn, start_tid =-1, end_tid=None,
                 batch_limit=100000, internal_batch_size=100,
                 poll_timeout=300, keep_history=None):
        self.dsn = dsn
        self.tid = start_tid
        self.end_tid = end_tid
        self.batch_limit = batch_limit
        self.internal_batch_size = internal_batch_size
        self.poll_timeout = poll_timeout
        self.keep_history = keep_history

    def _batch(self, conn):
        tid = self.tid
        try:
            updates = conn.cursor('object_state_updates')
            updates.itersize = self.internal_batch_size
            updates.execute(self._query, (tid, ))

            n = 0
            for row in updates:
                if row[0] != tid:
                    if n >= self.batch_limit:
                        break
                    tid = self.tid = row[0]
                yield row
                n += 1
        finally:
            try:
                conn.rollback()
                updates.close()
            except Exception:
                pass

    def __iter__(self):
        with closing(pg_connection(self.dsn)) as conn:
            with closing(conn.cursor()) as cursor:
                keep_history = determine_keep_history(cursor, self.keep_history)

                if keep_history:
                    self._query = self._query.replace(
                        'object_state s',
                        'object_state s natural join current_object',
                        )

                self._query = self._query.replace(
                    'UPPER',
                    '' if self.end_tid is None else
                    cursor.mogrify("and s.tid <= %s",
                                   (self.end_tid, )).decode('ascii'),
                    )

                # Catch up:
                while True:
                    batch = non_empty_generator(self._batch(conn))
                    if batch is None:
                        break # caught up
                    else:
                        yield batch

                if self.end_tid is None:
                    for payload in listen(self.dsn, True,
                                          poll_timeout=self.poll_timeout):
                        batch = non_empty_generator(self._batch(conn))
                        if batch is not None:
                            yield batch

def listen(dsn, timeout_on_start=False, poll_timeout=300):
    """Listen for newt database updates.

    Returns an iterator that returns integer transaction ids or None values.

    The purpose of this method is to determine if there are
    updates.  If transactions are committed very quickly, then not
    all of them will be returned by the iterator.

    None values indicate that ``poll_interval`` seconds have
    passed since the last update.

    Parameters:

    dsn
      A Postgres connection string

    timeout_on_start
      Force None to be returned immediately after listening for
      notifications.

      This is useful in some special cases to avoid having to time out
      waiting for changes that happened before the iterator began
      listening.

    poll_timeout
      A timeout after which None is returned if there are no changes.
      (This is a backstop to PostgreSQL's notification system.)
    """
    with closing(pg_connection(dsn)) as conn:
        conn.autocommit = True
        with closing(conn.cursor()) as cursor:
            if not trigger_exists(cursor,
                                  'newt_trigger_notify_object_state_changed'):
                cursor.execute(trigger_sql)

            cursor.execute("LISTEN " + NOTIFY)

            from select import select
            selargs = [conn], (), (), poll_timeout

            if timeout_on_start:
                # avoid a race between catching up and starting to LISTEN
                yield None

            while True:
                if select(*selargs) == ([], [], []):
                    yield None
                else:
                    conn.poll()
                    if conn.notifies:
                        if any(n.payload == 'STOP' for n in conn.notifies):
                            return # for tests
                        # yield the last
                        yield conn.notifies[-1].payload

def updates(conn, start_tid=-1, end_tid=None,
            batch_limit=100000, internal_batch_size=100,
            poll_timeout=300):
    """Create a data-update iterator

    The iterator returns an iterator of batchs, where each batch is an
    iterator of records. Each record is a triple consisting of an
    integer transaction id, integer object id and data.  A sample
    use::

      >>> import newt.db
      >>> import newt.db.follow
      >>> connection = newt.db.pg_connection('')
      >>> for batch in newt.db.follow.updates(connection):
      ...     for tid, zoid, data in batch:
      ...         print(tid, zoid, len(data))

    If no ``end_tid`` is provided, the iterator will iterate until
    interrupted.

    Parameters:

    conn
      A Postgres database connection.

    start_tid
      Start tid, expressed as an integer.  The iterator starts at the
      first transaction **after** this tid.

    end_tid
      End tid, expressed as an integer.  The iterator stops at this, or at
      the end of data, whichever is less.  If the end tid is None, the
      iterator will run indefinately, returning new data as they are
      committed.

    batch_limit
      A soft batch size limit.  When a batch reaches this limit, it will
      end at the next transaction boundary.  The purpose of this limit is to
      limit read-transaction size.

    internal_batch_size
      The size of the internal Postgres iterator.  Data aren't loaded from
      Postgres all at once.  Server-side cursors are used and data are
      loaded from the server in ``internal_batch_size`` batches.

    poll_timeout
      When no ``end_tid`` is specified, this specifies how often to poll
      for changes.  Note that a trigger is created and used to notify the
      iterator of changes, so changes ne detected quickly. The poll
      timeout is just a backstop.
    """

    return Updates(conn, start_tid, end_tid, batch_limit, internal_batch_size,
                   poll_timeout)

def _ex_progress(conn, cursor, sql, *args):
    try:
        cursor.execute(sql, args)
    except Exception:
        # Hm, maybe the table doesn't exist:
        conn.rollback()
        if not table_exists(cursor, PROGRESS_TABLE):
            cursor.execute("create table " + PROGRESS_TABLE +
                           " (id text primary key, tid bigint)")

        # Try again. Note that if we didn't create the table, this
        # will hopefullt fail again, forcing the caller to rollback.
        cursor.execute(sql, args)

def get_progress_tid(connection, id):
    """Get the current progress for a follow client.

    Return the last saved integer transaction id for the client, or
    -1, if one hasn't been saved before.

    A follow client often updates some other data based on the data
    returned from ``updates``.  It may stop and restart later. To do
    this, it will call ``set_progress_tid`` to save its progress and
    later call ``get_progress_tid`` to find where it left off.  It can
    then pass the returned tid as ``start_tid`` to ``updates``.

    The ``connection`` argument must be a PostgreSQL connection string
    or connection.

    The ``id`` parameters is used to identify which progress is
    wanted.  This should uniquely identify the client and generally a
    dotted name (``__name__``) of the client module is used.  This
    allows multiple clients to have their progress tracked.
    """
    if isinstance(connection, str):
        with closing(pg_connection(connection)) as conn:
            return get_progress_tid(conn, id)

    with closing(connection.cursor()) as cursor:
        _ex_progress(
            connection, cursor,
            "select tid from %s where id = %%s" % PROGRESS_TABLE, id)

        tid = list(cursor)
        if tid:
            return tid[0][0]
        else:
            return -1

def set_progress_tid(connection, id, tid):
    """Set the current progress for a follow client.

    See ``get_progress_tid``.

    The ``connection`` argument must be a PostgreSQL connection string
    or connection.

    The ``id`` argument is a string identifying a client. It should
    generally be a dotted name (usually ``__name__``) of the client
    module.  It must uniquely identify the client.

    The ``tid`` argument is the most recently processed transaction id
    as an int.
    """
    if isinstance(connection, str):
        with closing(pg_connection(connection)) as conn:
            set_progress_tid(conn, id, tid)
            conn.commit()
            return

    with closing(connection.cursor()) as cursor:
        _ex_progress(connection, cursor,
                     "delete from %s where id=%%s" % PROGRESS_TABLE, id)
        cursor.execute(
            "insert into %s(id, tid) values(%%s, %%s)" % PROGRESS_TABLE,
            (id, tid))

def stop_updates(conn):
    """Notify all ``updates`` iterators that they should stop.

    This is mainly intended for tests. It only works for iterators
    that are already waiting for for new data.
    """
    with closing(conn.cursor()) as cursor:
        cursor.execute("notify %s, 'STOP'" % NOTIFY)

def garbage(dsn):
    with closing(pg_connection(dsn)) as conn:
        with closing(conn.cursor('find_garbage')) as cursor:
            cursor.execute("select zoid from pack_object where not keep")
            for r in cursor:
                yield r[0]


text:
package org.rockjs.geom;

public class Point3 {
    private double x;
    private double y;
    private double z;

    public Point3(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public double getZ() {
        return z;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical" >

  <fragment
    android:id="@+id/price_chart_fragment"
    android:name="de.dev.eth0.bitcointrader.ui.fragments.PriceChartFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>


text:
#ifndef NMSG_H
#define NMSG_H

/*! \file nmsg.h
 * \brief Base nmsg support header.
 *
 * This header ensures that needed constants, functions, result codes,
 * vendor definitions, and opaque pointer types are defined.
 */

#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <stdbool.h>
#include <stdint.h>

#include <nmsg/res.h>
typedef enum nmsg_res nmsg_res;

typedef struct nmsg_container *	nmsg_container_t;
typedef struct nmsg_input *	nmsg_input_t;
typedef struct nmsg_io *	nmsg_io_t;
typedef struct nmsg_message *	nmsg_message_t;
typedef struct nmsg_msgmod *	nmsg_msgmod_t;
typedef struct nmsg_output *	nmsg_output_t;
typedef struct nmsg_pcap *	nmsg_pcap_t;
typedef struct nmsg_pres *	nmsg_pres_t;
typedef struct nmsg_rate *	nmsg_rate_t;
typedef struct nmsg_random *	nmsg_random_t;
typedef struct nmsg_strbuf *	nmsg_strbuf_t;
typedef struct nmsg_zbuf *	nmsg_zbuf_t;

/**
 * Generic ID to name map.
 */
struct nmsg_idname {
	unsigned	id;	/*%< ID number */
	const char	*name;	/*%< Human readable name */
};

/**
 * Callback function for processing nmsg messages.
 *
 * \param[in] msg Valid nmsg message.
 *
 * \param[in] user User-provided pointer.
 *
 * \see nmsg_input_loop()
 * \see nmsg_output_open_callback()
 */
typedef void (*nmsg_cb_message)(nmsg_message_t msg, void *user);

/**
 * Callback function for generating nmsg messages.
 *
 * \param[out] msg Pointer to where an nmsg_message_t object may be stored.
 *
 * \param[in] user User-provided pointer.
 *
 * \see nmsg_input_open_callback()
 *
 * \return #nmsg_res_success
 * \return #nmsg_res_failure
 * \return #nmsg_res_again
 * \return #nmsg_res_eof
 */
typedef nmsg_res (*nmsg_cb_message_read)(nmsg_message_t *msg, void *user);

#include <nmsg/alias.h>
#include <nmsg/asprintf.h>
#include <nmsg/compat.h>
#include <nmsg/constants.h>
#include <nmsg/container.h>
#include <nmsg/chalias.h>
#include <nmsg/input.h>
#include <nmsg/io.h>
#include <nmsg/ipdg.h>
#include <nmsg/msgmod.h>
#include <nmsg/message.h>
#include <nmsg/output.h>
#include <nmsg/pcap_input.h>
#include <nmsg/rate.h>
#include <nmsg/random.h>
#include <nmsg/sock.h>
#include <nmsg/strbuf.h>
#include <nmsg/timespec.h>
#include <nmsg/vendors.h>
#include <nmsg/zbuf.h>

/**
 * Initialize the libnmsg library. This function MUST be called before
 * using any other libnmsg function. The caller MUST also check that this
 * function returned #nmsg_res_success before using any other libnmsg function.
 * The library should only be initialized once.
 *
 * \return nmsg_res_success On successful library initialization.
 * \return nmsg_res_failure If libnmsg is not usable, or if #nmsg_init() was
 * called more than once.
 */
#if __GNUC__ >= 4
__attribute__ ((warn_unused_result))
#endif
nmsg_res nmsg_init(void);

/**
 * Configure automatic close() behavior of nmsg inputs and outputs. The
 * default behavior is for nmsg_input_close(), nmsg_output_close(), and
 * nmsg_io_destroy() to automatically close the underlying file descriptors
 * for libnmsg inputs and outputs.
 *
 * \param autoclose False to disable automatic close() behavior, true to
 *	re-enable.
 */
void nmsg_set_autoclose(bool autoclose);

/**
 * Set debug level. If the debug level is greater than 0, some libnmsg
 * functions will emit debugging information to stderr. Higher values increase
 * verbosity.
 */
void nmsg_set_debug(int debug);

/**
 * Retrieve the current debug level.
 */
int nmsg_get_debug(void);

#ifdef __cplusplus
}
#endif

/**
\mainpage nmsg documentation

\section intro Introduction

The NMSG format is an efficient encoding of typed, structured data into
payloads which are packed into containers which can be transmitted over the
network or stored to disk. <tt>libnmsg</tt> is the reference implementation of
this format and provides an extensible interface for creating and parsing
messages in NMSG format. The NMSG format relies on Google Protocol Buffers to encode the
payload header. Individual NMSG payloads are distinguished by assigned vendor
ID and message type values and <tt>libnmsg</tt> provides a modular interface
for registering handlers for specific message types. <tt>libnmsg</tt> makes it
easy to build new message types using a Protocol Buffers compiler.

\see http://code.google.com/p/protobuf/
\see http://code.google.com/p/protobuf-c/

\section libnmsg

<tt>libnmsg</tt> provides a reference C implementation of an NMSG parser and
generator. It contains core functions for reading and writing NMSG units and
can be extended at runtime by plugin modules implementing new message types.

\subsection core Core I/O functions

input.h and output.h provide the single-threaded input and output interfaces.
io.h provides a multi-threaded interface for multiplexing data between inputs
and outputs. message.h provides an interface for creating and inspecting
message payloads.

\subsection nmsg_msg nmsg_msg message module interface

The nmsg_msg message module interface is implemented by msgmod.h. Plugins
in external shared objects provide an <tt>nmsg_msgmod_t</tt> structure in order
to implement new message types.

\subsection aux Auxiliary functions

alias.h

asprintf.h

chalias.h

ipdg.h

pcap_input.h

rate.h

strbuf.h

timespec.h

zbuf.h

\section wire_format Wire format

An NMSG unit consists of a small fixed-length header which precedes a variable
length part that may contain one or more payloads or, if a single payload is too
large, the variable length part may contain a single message fragment.

NMSG is designed for transport over UDP sockets or storage in on-disk files.
Individual UDP datagrams may transport only a single NMSG unit, while the file
format is simply a series of NMSG units concatenated together. The variable
length part of an NMSG unit transported over UDP is usually much smaller than
those stored on disk (#NMSG_WBUFSZ_MAX versus #NMSG_WBUFSZ_JUMBO or
#NMSG_WBUFSZ_ETHER). NMSG units stored on disk also do not contain message
fragments.

The fixed-length NMSG header is ten octets long and consists of a magic value, a
bit field of flags, a version number, and the length of the variable length data
part.

The variable length data part is interpreted as a Protocol Buffer message.

Octet 0-3
Octet 4
Octet 5
Octet 6-9
Remainder

Magic
Flags
Version
Length
Data

\subsection magic Magic value

The magic value (#NMSG_MAGIC) is always the four octet sequence 'N', 'M', 'S',
'G'.

\subsection flags Flags

This is a bit field of flags. Currently two values are defined.  #NMSG_FLAG_ZLIB
indicates that the data content has been compressed.  #NMSG_FLAG_FRAGMENT
indicates that the data content starts a special fragmentation header.

\subsubsection zlib NMSG_FLAG_ZLIB

This flag indicates that zlib compression has been applied to the variable
length part. If the #NMSG_FLAG_FRAGMENT flag is not also set, then the entire
variable length part should be deflated with zlib and interpreted as an
NmsgPayload.

\subsubsection frag NMSG_FLAG_FRAGMENT

This flag indicates that the variable length part should be interpreted as an
NmsgFragment. After reassembly, the data should be interpreted as an
NmsgPayload. If the #NMSG_FLAG_ZLIB flag is also set, then the
reassembled data should be deflated and then interpreted as an
NmsgPayload.

Note that when creating a compressed, fragmented NMSG unit, compression should
be applied before fragmentation.

\subsection version Version

This value (#NMSG_VERSION) is currently 2.

\subsection length Length

This value is an unsigned 32 bit integer in network byte order indicating the
length in octets of the variable length data part.

\subsection data Data

The variable length data part is encoded using Google
Protocol Buffers. The file <tt>nmsg/nmsg.proto</tt> in the source
distribution describes the two message types Nmsg and
NmsgFragment that can appear in NMSG units:

\include nmsg.proto

If no flags are set, then the data part is an Nmsg protobuf message. If
only the #NMSG_FLAG_ZLIB flag is set, then the data part is a zlib compressed
Nmsg protobuf message. The Nmsg protobuf message is a container
message for one or more NmsgPayload messages. If only the
#NMSG_FLAG_FRAGMENT flag is set, then the data part is an NmsgFragment
protobuf message.

\subsubsection nmsg Nmsg and NmsgPayload protobuf messages

Nmsg messages contain one or more NmsgPayload messages.

The vid field of NmsgPayload messages is the vendor ID. The
currently defined vendor IDs are listed in vendors.h and assigned by Farsight.
The msgtype field is a vendor-specific value and together the (vid,
msgtype) tuple defines the type of the data contained in the
payload field.

The time that the data encapsulated in the payload field was generated is
stored in the time_sec and time_nsec fields. The number of
nanoseconds since the Unix epoch is split across the two fields, with the
integer number of seconds stored in the time_sec field and the
nanoseconds part stored in the time_nsec field.

The source, operator, and group fields are optional fields
that can be used by cooperating senders and receivers to classify the payload.

\subsubsection nmsgfragment NmsgFragment protobuf messages

NmsgFragment messages are used to encapsulate fragments of an Nmsg
message if the serialized message is too large for the underlying transport.
This enables NMSG payloads to avoid the size restrictions of UDP/IP transport.

If a serialized Nmsg message is too large for the underlying transport,
it is split into fragments which are carried in the fragment field of a
sequence of NmsgFragment messages. A random value is selected for the
id field of these fragments. The 0-indexed current field indicates
the ordering of the fragments, and the last field indicates the total
number of fragments. Once a receiver has received all the fragments for a given
fragment id, the fragmented payload should be extracted from the
payload field of each fragment and concatenated into a buffer.

If the sender performed compression of the Nmsg message before
fragmentation, then all fragments should have the #NMSG_FLAG_ZLIB field set and
the receiver must perform decompression of the reassembled buffer. The result of
decompression should be interpreted as an Nmsg message.

If the sender did not perform compression before fragmentation, then the buffer
should be directly interpreted as an Nmsg message.

*/

#endif /* NMSG_H */


text:
#include "UserAccount.h"
#include "Entry.h"

#include <Wt/WApplication>
#include <Wt/WLogger>

#include <Wt/Dbo/WtSqlTraits>

using namespace Wt;
using namespace Wt::Dbo;

UserAccount::UserAccount()
{ }

UserAccount::UserAccount(const WString& aName)
  : name(aName)
{ }

collection< ptr<Entry> > UserAccount::entriesInRange(const WDate& from,
						     const WDate& until) const
{
  return entries.find()
    .where("start >= ?").bind(WDateTime(from))
    .where("start < ?").bind(WDateTime(until));
}

ptr<UserAccount> UserAccount::login(Session& session,
				    const WString& userName)
{
  Transaction transaction(session);

  ptr<UserAccount> ua =
    session.find<UserAccount>("where name = ?").bind(userName);

  if (!ua) {
    WApplication::instance()
      ->log("notice") << "Creating user: " << userName.toUTF8();

    ua = session.add(new UserAccount(userName));
  }

  transaction.commit();

  return ua;
}


text:
FactoryGirl.define do
  factory :video do
    title { FFaker::HipsterIpsum.words(4).join(' ') }
  end
end


text:
<?php

namespace Watchman\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use Watchman\Scope,
    Watchman\Watchman;

class Watch extends Command {

    protected function configure()
    {
        $this
            ->setName('watch')
            ->setDescription('Watch files as defined in watchlist.json.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $watchman = new Watchman();

        $output->writeln("Initializing watchman...");

        if(is_file("watchlist.json")) {
            $scopes = json_decode(file_get_contents("watchlist.json"), true);
            foreach($scopes as $scope) {
                $watchman->addScope(new Scope($scope['src'], $scope['exclude'], $scope['run']));
            }
            $output->writeln("watchman is watching");
            $watchman->watch();
        } else {
            $output->writeln("Can't find watchlist.json");
        }
    }
}


text:
<?php
include("dbconn.php");

$query = "SELECT*FROM stud WHERE pbrStan=10040";
$result = mysqli_query($db, $query);

echo 'broj pronadjenih zapisa: '.mysqli_affected_rows($db);

$query = "SELECT*FROM stud WHERE pbrStan=10040";
$result = mysqli_query($db, $guery);

 $br_result = mysqli_affected_rows($result);

 if($br_result <= 0){

     echo "Ne postoji niti jedan rezultat";
 } else {

     while ($student = mysqli_fetch_array($db)){

     }
 }
 echo "<br>";

if(mysqli_close($db)){

     echo 'Konekcija zatvorena';
 } else {

     echo 'Doslo je do greske';
 }

$query1 = "INSERT INTO dvorana(oznDvorana,kapacitet)";
$query1 .= " VALUES('M2', 14)";

$result1 = mysqli_query($db, $query1);

     echo "Zadnje pohranjeni ID: ". mysqli_insert_id($result1);

$query2 = "SELECT imeStud, prezStud";
$query2 .= " FROM stud";
$query2 .= " WHERE pbrStan=10040";

     $result2 = mysqli_query($db, $query2);

    echo "Broj polja us zapisu:" . mysqli_num_fields($result2);

$query1 = "SELECT imeStud, prezStud ";
$query1 .= " FROM stud ";
$query1 .= " WHERE pbrStan=10040";
$result1 = mysqli_query($query1);

    echo "broj polja u zapisu: ".mysqli_num_fields($result1);

$query3 = "SELECT imeStud, prezStud";
$query3 .= " FROM stud";
$query3 .= " WHERE pbrStan=10000";

$result3 = mysqli_query($db, $query3);

    echo "Broj zapisa: ". mysqli_num_rows($result3);

    $br_result = mysqli_num_rows($result3);

    if ($br_result <=0){

        echo "Ne postoji niti jedan rezultat";
    }else{

         while ($student = mysqli_fetch_array($result3)){

         }
     }

 ?>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          android:versionCode="6030000"
          android:versionName="6.3.0.Final"
          package="org.drools.examples.android.serialized">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="19"/>

    <application
        android:largeHeap="true"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:label="@string/app_name"
            android:name="org.drools.examples.android.DroolsActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package org.zaproxy.zap.extension.openapi.generators;

import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.parameters.Parameter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpHeaderField;
import org.zaproxy.zap.extension.openapi.converter.swagger.OperationModel;

public class HeadersGenerator {

    private static final String ACCEPT = "Accept";
    private static final String HEADER = "header";
    private static final String COOKIE = "cookie";

    private static final char COOKIE_NAME_VALUE_SEPARATOR = '=';
    private static final String COOKIE_SEPARATOR = "; ";

    private DataGenerator dataGenerator;

    public HeadersGenerator(DataGenerator dataGenerator) {
        this.dataGenerator = dataGenerator;
    }

    public List<HttpHeaderField> generate(OperationModel operationModel, String requestBody) {
        List<HttpHeaderField> headerList = new LinkedList<>();
        generateAcceptHeaders(operationModel.getOperation(), headerList);
        generateContentTypeHeaders(operationModel.getOperation(), headerList, requestBody);
        generateCustomHeader(operationModel.getOperation(), headerList);
        return headerList;
    }

    void generateCustomHeader(Operation operation, List<HttpHeaderField> headers) {
        if (operation.getParameters() != null) {
            List<Parameter> cookies = null;
            for (Parameter parameter : operation.getParameters()) {
                if (parameter == null) {
                    continue;
                }
                if (HEADER.equals(parameter.getIn())) {
                    String name = parameter.getName();
                    String value = dataGenerator.generate(name, parameter);
                    HttpHeaderField header = new HttpHeaderField(name, value);
                    headers.add(header);
                } else if (COOKIE.equals(parameter.getIn())) {
                    if (cookies == null) {
                        cookies = new ArrayList<>();
                    }
                    cookies.add(parameter);
                }
            }

            if (cookies != null) {
                headers.add(generateCookieHeader(cookies));
            }
        }
    }

    HttpHeaderField generateCookieHeader(List<Parameter> cookies) {
        StringBuilder strBuilder = new StringBuilder(cookies.size() * 15);
        cookies.forEach(
                cookie -> {
                    if (strBuilder.length() != 0) {
                        strBuilder.append(COOKIE_SEPARATOR);
                    }
                    strBuilder.append(cookie.getName()).append(COOKIE_NAME_VALUE_SEPARATOR);
                    strBuilder.append(dataGenerator.generate(cookie.getName(), cookie));
                });
        return new HttpHeaderField(HttpHeader.COOKIE, strBuilder.toString());
    }

    void generateContentTypeHeaders(
            Operation operation, List<HttpHeaderField> headers, String requestBody) {
        if (operation.getRequestBody() == null || operation.getRequestBody().getContent() == null) {
            return;
        }

        // Note: the order in which the content types are evaluated should match the order in
        // RequestModelConverter.
        Set<String> contentTypes = operation.getRequestBody().getContent().keySet();
        String contentType =
                getPartialMatch(contentTypes, "json", "x-www-form-urlencoded", "octet-stream");
        if (contentType != null) {
            headers.add(new HttpHeaderField(HttpHeader.CONTENT_TYPE, contentType));
            return;
        }

        contentType = getPartialMatch(contentTypes, "multipart");
        if (contentType != null) {
            if (requestBody.length() > 0) {
                contentType += "; boundary=" + requestBody.substring(2, 38);
            }
            headers.add(new HttpHeaderField(HttpHeader.CONTENT_TYPE, contentType));
        }
    }

    private static String getPartialMatch(Set<String> values, String... wantedMatches) {
        for (String wantedMatch : wantedMatches) {
            Optional<String> match =
                    values.stream()
                            .filter(e -> StringUtils.containsIgnoreCase(e, wantedMatch))
                            .findFirst();
            if (match.isPresent()) {
                return match.get();
            }
        }
        return null;
    }

    void generateAcceptHeaders(Operation operation, List<HttpHeaderField> headers) {

        Set<String> contentSet = new LinkedHashSet<>();
        operation.getResponses().values().stream()
                .map(
                        response -> {
                            if (response.getContent() == null) {
                                return Collections.<String>emptySet();
                            }
                            return response.getContent().keySet();
                        })
                .forEach(contentSet::addAll);
        StringBuilder sb = new StringBuilder();
        for (String type : contentSet) {
            // Claim we accept everything
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append(type);
        }

        String headerValue = sb.toString();
        if (headerValue.isEmpty()) {
            headerValue = "*/*";
        }
        headers.add(new HttpHeaderField(ACCEPT, headerValue));
    }
}


text:
<?php

/**
 * 用户登陆组件
 *
 * the last known user to change this file in the repository  <$LastChangedBy: suqian $>
 * @author Su qian <aoxue.1988.su.qian@163.com>
 * @version $Id: PipiWebUser.php 8317 2013-03-29 01:19:47Z suqian $
 * @package componets
 */
class PipiWebUser extends CWebUser {

	public function afterLogin($fromCookie){
		$returnUrl = Yii::app()->request->getUrlReferrer();
		$returnUrl = $returnUrl ? $returnUrl : Yii::app()->request->getHostInfo();
		$userService = new UserService();
		$records = array();
		$records['uid'] = $this->getId();
		$records['login_page'] = $returnUrl;
		if(Yii::app()->session['open_referer']){
			$records['login_type'] = 1;
		}else{
			$records['login_type'] = 0;
		}
		$userService->saveUserLoginRecords($records);
	}
}


text:
<refentry xmlns="http://docbook.org/ns/docbook"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:xi="http://www.w3.org/2001/XInclude"
          xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          version="5.0" xml:id="refentry.meta.get.quietly">
<refmeta>
<refentrytitle>refentry.meta.get.quietly</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">boolean</refmiscinfo>
</refmeta>
<refnamediv>
<refname>refentry.meta.get.quietly</refname>
<refpurpose>Suppress notes and warnings when gathering refentry metadata?</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment xml:id="refentry.meta.get.quietly.frag">
<xsl:param name="refentry.meta.get.quietly" select="0"/>
</src:fragment>
</refsynopsisdiv>

<refsection><info><title>Description</title></info>

<para>If zero (the default), notes and warnings about "missing" markup
are generated during gathering of refentry metadata. If non-zero, the
metadata is gathered "quietly" -- that is, the notes and warnings are
suppressed.</para>

<tip>
  <para>If you are processing a large amount of <tag>refentry</tag>
  content, you may be able to speed up processing significantly by
  setting a non-zero value for
  <parameter>refentry.meta.get.quietly</parameter>.</para>
</tip>

</refsection>
</refentry>


text:
<?php

namespace FreeDSx\Ldap\Search\Filter;

use FreeDSx\Ldap\Protocol\ProtocolElementInterface;

/**
 * Used to represent filters for search requests.
 *
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
interface FilterInterface extends ProtocolElementInterface
{
    public const PAREN_LEFT = '(';

    public const PAREN_RIGHT = ')';

    public const OPERATOR_AND = '&';

    public const OPERATOR_OR = '|';

    public const OPERATOR_NOT = '!';

    public const FILTER_EQUAL = '=';

    public const FILTER_APPROX = '~=';

    public const FILTER_GTE = '>=';

    public const FILTER_LTE = '<=';

    public const FILTER_EXT = ':=';

    public const OPERATORS = [
        self::OPERATOR_NOT,
        self::OPERATOR_OR,
        self::OPERATOR_AND,
    ];

    public const FILTERS = [
        self::FILTER_EQUAL,
        self::FILTER_APPROX,
        self::FILTER_GTE,
        self::FILTER_LTE,
        self::FILTER_EXT,
    ];

    /**
     * Get the string representation of the filter.
     *
     * @return string
     */
    public function toString(): string;
}


text:
package org.ovirt.engine.core.dal.dbbroker;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
import org.ovirt.engine.core.utils.FileUtil;
import org.ovirt.engine.core.utils.ResourceUtils;
import org.ovirt.engine.core.utils.ejb.ContainerManagedResourceType;
import org.ovirt.engine.core.utils.ejb.EjbUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;

/**
 * A locator singleton for looking up (and initializing) DbFacade instance
 */
public class DbFacadeLocator {

    private static DbFacade dbFacade;
    private static final Log log = LogFactory.getLog(DbFacadeLocator.class);

    static {
        try {
            // ok we need to locate the datasource
            DataSource datasource = EjbUtils
                    .findResource(ContainerManagedResourceType.DATA_SOURCE);
            if (datasource == null)
                throw new RuntimeException("Datasource is not defined ");

            // create the facade and return it
            dbFacade = new DbFacade();
            dbFacade.setDbEngineDialect(loadDbEngineDialect());
            loadDbFacadeConfig();
            JdbcTemplate jdbcTemplate = dbFacade.getDbEngineDialect().createJdbcTemplate(datasource);
            SQLErrorCodeSQLExceptionTranslator tr = new CustomSQLErrorCodeSQLExceptionTranslator(datasource);
            jdbcTemplate.setExceptionTranslator(tr);

            dbFacade.setTemplate(jdbcTemplate);
        } catch (Exception e) {
            log.fatal("Unable to locate DbFacade instance", e);
        }
    }

    public static DbFacade getDbFacade() {
        return dbFacade;
    }

    /**
     * Generate and sets the database engine dialect object according to configuration.
     *
     * @throws Exception
     */
    public static DbEngineDialect loadDbEngineDialect() throws Exception {
        final String ENGINE_DB_ENGINE_PROPERTIES = "engine-db-engine.properties";
        final String DIALECT = "DbEngineDialect";
        Properties props = ResourceUtils.loadProperties(DbFacadeLocator.class, ENGINE_DB_ENGINE_PROPERTIES);
        if (props.getProperty(DIALECT) == null) {
            throw new IllegalStateException("Failed to get property key value");
        }

        return (DbEngineDialect) Class.forName(props.getProperty(DIALECT)).newInstance();
    }

    public static void loadDbFacadeConfig() throws Exception {
        boolean configSucceeded = false;
        final String ENGINE_CONF_FILE = "/etc/ovirt-engine/engine.conf";
        final String ON_START_CONNECTION_TIMEOUT = "OnStartConnectionTimeout";
        final String CONNECTION_CHECK_INTERVAL = "ConnectionCheckInterval";
        final String DEFAULT_TIMEOUT_VALUE = "300000";
        final String DEFAULT_INTERVAL_VALUE = "5000";
        InputStream inputStream = null;
        try {
            String onStartConnectionTimeout = null;
            String connectionCheckInterval = null;
            Properties props = new Properties();
            if (FileUtil.fileExists(ENGINE_CONF_FILE)) {
                // File exists, load /etc/ovirt-engine/engine.conf and set values in DbFacade
                inputStream = new FileInputStream(ENGINE_CONF_FILE);
                props.load(inputStream);
                onStartConnectionTimeout = props.getProperty(ON_START_CONNECTION_TIMEOUT);
                connectionCheckInterval = props.getProperty(CONNECTION_CHECK_INTERVAL);
                if (!validNumber(onStartConnectionTimeout)) {
                    onStartConnectionTimeout = DEFAULT_TIMEOUT_VALUE;
                }
                if (!validNumber(connectionCheckInterval)) {
                    connectionCheckInterval = DEFAULT_INTERVAL_VALUE;
                }
            } else {
                // File does not exist - use defaults
                log.warn(String.format("%1$s file is not found. Please check your engine installation. " +
                        "Default values will be used"
                        , ENGINE_CONF_FILE));
                onStartConnectionTimeout = DEFAULT_TIMEOUT_VALUE;
                connectionCheckInterval = DEFAULT_INTERVAL_VALUE;
            }
            dbFacade.setOnStartConnectionTimeout(Integer.parseInt(onStartConnectionTimeout));
            dbFacade.setConnectionCheckInterval(Integer.parseInt(connectionCheckInterval));
            configSucceeded = true;
        } catch (Exception ex) {
            log.error("Error in configuration of db facade " + ExceptionUtils.getMessage(ex));
        } finally {
            if (!configSucceeded) {
                dbFacade.setOnStartConnectionTimeout(300000);
                dbFacade.setConnectionCheckInterval(1000);
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }

    }

    private static boolean validNumber(String numberStr) {
        return numberStr != null && NumberUtils.isNumber(numberStr);
    }

}


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SrividyaCourseService } from './srividyacourse.service';

@Component({
    templateUrl: './app/srividyacourses/srividyacourselist.component.html'
})
export class SrividyaCourseListComponent implements OnInit {

    public srividyacourse: any;
    errorMessage: string;

    constructor(private route: ActivatedRoute, private router: Router,
        private svcService: SrividyaCourseService) {

    }

    ngOnInit(): void {

        this.svcService.SrividyaCourseList().subscribe(
            data => {
                if (data.length > 0) {
                    this.errorMessage = " ";
                    return this.srividyacourse = data;
                }
                else {
                    this.srividyacourse = null;
                    return this.errorMessage = "There are no SrividyaCourse";
                }

            },
            error => {
                return this.errorMessage = <any>error;
            }
        );
    }
}


text:
layout: relation
title: 'fixed'
redirect_from: "es/dep/mwe.html"
shortdef: 'multi-word expression'
---

This document is a placeholder for the language-specific documentation
for `fixed`.

~~~ sdparse
Tengo que estudiar . \n I have to study .
mwe(Tengo, que)
~~~


text:
<?xml version="1.0"?>
<document url="release-notes.html">
  <properties>
    <author>Craig R. McClanahan</author>
    <author>Robert Leland</author>
    <author>Ted Husted</author>
    <author>Martin Cooper</author>
    <title>Struts Release Notes (since 1.1)</title>
  </properties>

This section contains release notes for changes that have taken place since
        Version 1.1 was released.

The binary distribution of this release includes the following files relevant to Struts:

          INSTALL.txt - Brief installation instructions. For more detail, see the
          Struts User Guide, either through the Struts Documentation application or online at
          http://struts.apache.org/.

          LICENSE.txt - The Apache Software Foundation license that defines the terms under which you can use Struts (and other software licensed by Apache).

          contrib/ - Additional libraries developed by the Struts team which are not yet part of the core distribution.

          lib/ - Directory containing files you will need in your own applications. The individual files of interest are:

            antlr-#.#.jar - ANTLR, ANother Tool for Language Recognition, a public domain library made available by
            antlr.org.

            commons-*-#.#.jar - Various packages from the
            Jakarta Commons Project that Struts relies on. You are welcome to use these classes in your own applications. These JAR files should be copied into the
            /WEB-INF/lib directory of your web application.

            jakarta-oro-#.#.jar - JAR file containing the Jakarta ORO package, utilitied by the Struts Valdiator. You must place this file in the
            /WEB-INF/lib directory of your web application to use the Struts Validator package.

            struts-#.#.jar - JAR file that contains the compiled Java classes of Struts. You must place this file in the
            /WEB-INF/lib directory of your web application.

            struts-*.tld - The tag library descriptor files for the Struts tag libraries (bean, html, logic, and nested). When these taglibs are used, you must place these files in the
            /WEB-INF directory of your web application and reference them with appropriate
            <taglib> directives in your web.xml file.

            struts-config_1_2.dtd - The Document Type Definition (DTD) for the Struts 1.2 configuration file (which is typically named
            /WEB-INF/struts-config.xml). Your configuration file will be validated against an internal copy of this DTD -- this copy is available for reference purposes only.

            struts-config_1_1.dtd - The Document Type Definition (DTD) for the Struts 1.1 configuration file (which is typically named
            /WEB-INF/struts-config.xml). Your configuration file will be validated against an internal copy of this DTD -- this copy is available for reference purposes only.

            struts-config_1_0.dtd - The Document Type Definition (DTD) for the Struts 1.0 configuration file (which is typically named
            /WEB-INF/struts-config.xml. Your configuration file will be validated against an internal copy of this DTD -- this copy is available for reference purposes only.

            web-app_2_2.dtd - The Document Type Definition (DTD) for web.xml files conforming to the Servlet 2.2 specification. This copy is for reference purposes only.

            web-app_2_3.dtd - The Document Type Definition (DTD) for web.xml files conforming to the Servlet 2.3 specification. This copy is for reference purposes only.

          webapps/ - Web Application Archive (WAR) files for the web applications that are included with Struts.

For the version requirements of each library, see the
        Installation chapter.

This section highlights new features added and critical changes made since the last release. Other interesting changes are listed in the
        What Changed? section. Subscribers to the
        struts-dev mailing list, receive reports of all changes as they are made.

        Deprecations - Many constructs were deprecated for the Struts 1.1 release, most of which have now been removed. Before moving to this release, you should clean-compile your application with deprecation warnings enabled. Alternatives should be available for all decprecated constructs.
        You are strongly advised to resolve all Struts 1.1. deprecations before moving to this release. Removed constructs most likely to affect developers are:

          org.apache.struts.Action statics: Use
          org.apache.struts.Global statics instead.

          Action.perform: Use
          Action.execute instead.

Although not removed or deprecated, in many cases
        you should replace the
        ActionErrors with the preferred
        ActionMessages to ensure correct operation.

        TagUtils and ModuleUtils - Many utility methods previously found in
        org.apache.struts.utils.RequestUtils have been moved to
        org.apache.struts.taglibs.TagUtils or
        org.apache.struts.utils.ModuleUtils.

        GenericDataSource / GenericConnection implementations removed - The datasources manager is still supported, but our own datasource
        implementationis not. You are welcome to plug in your own DataSource implementation, but we do not have the resources to maintain one of our own. If your container does not supply a DataSource implementation, the DBCP package from the Jakarta Commons is suggested.

          Validator enhancements

ValidWhen - The Struts Validator now supports a ValidWhen rule, so that one validation can be dependant on another.
          Details ...

IntRange now checks select-one and radio fields. Example: This allows populating combo boxes with valid choices plus one additional choice with a caption something like "Choose one" and a value 0f "-1". Then when the user attempts to submit the form, you can look for the value of "-1" and advise if nothing was selected.

You can now force the clientside Javascript validation to check all constraints, instead of stopping at the first error. By setting a new property,
          stopOnFirstError, on the Validator PlugIn to false.
          Details ...

The "required" validation can now handle checkboxes, radio,select-one, and select-multiple field types. See the updated Validator example application to see these new features in action.

A standard
          validateUrl rule lets you check if a property contains a well-formed URL.

        DigestingPlugIn - A new standard PlugIn that helps you create your own object graph in application scope. This is handy way to create business objects for Actions to call. Check the latest MailReader eaxmple application to see the DigestingPlugin in action.

        ModuleConfigVerifier - While not exactly new, a standard class for verifying module configurations is also available in the PlugIn packages. As it stands, the
        ModuleConfigVerifier mainly confirms that various components of the Struts object graph were loaded. However, ambitious developers could extend this class with additional checks to ensure the Struts configuration is internally consistent.

        Maven project files - While still under development, significant progress has been made toward putting the Struts build process under
        Maven. The core JAR and TLDs can be built using Maven, leveraging the shared Maven repository for our many dependencies. You can find the current maven.xml and project.xml in the root directory of the Struts source distribution. However, at this time, the original Ant build files are still the official mechanism for building Struts.

        New Configuration DTD - The

          struts-config_1_2.dtd
         is preferred to the deprecated Struts Configuration 1.1 DTD. The new DTD adds two new elements <display-name> and <description> to the struts-config element. These elements are for use by struts config file tools and document generation. In the Struts 1.2.x series, existing Struts configuration files can be loaded using either DTD version.

        New Taglib URIs - The URIs for the tag libraries have been changed to reflect the move of Struts from Jakarta to an Apache top level project. For compatibility purposes, TLDs with the old URIs are still available, but users are encouraged to update their usage accordingly.

        New Committers - We are pleased to welcome Steve Raeburn, Don Brown, Joe Germuska and Niall Pemberton to the team of Struts Committers.

        Struts-Chain - Still experimental, this new "contrib" package utilizes the new Chain of Responsibilty package in the Jakarta Sandbox to create a new breed of RequestProcessor. Look for this to become the default implementation in a future release.

        MappingDispatchAction - A new standard Action that dispatches to a method named by the ActionMapping parameter.

        Cancel handlers - DispatchAction, LookupDispatchAction, and MappingDispatchAction - Now provide default cancel handler that can be overridden. It also also possible to specify the default handler name.

        Session-scoped ActionMessages - You can now save ActionMessages in the session and have them cleaned up after the first use. There is now an alternate form of Action.saveMessages() that stores messages in the session. ActionMessages.isAccessed() returns true after the messages have been retrieved one time. RequestProcessor.processCachedMessages() queries isAccessed() to determine if it should remove the messages from the session.

        JA Mailreader - The Struts Mailreader Example application now includes a Japanese resource file.

        Tiles EL - The Tiles tags are now avaiable through the Struts EL taglib, which is based on JSTL.

        Wildcard Mappings - You can now use wildcards in your action-mappings. For details see
        Using Wildcards in ActionMappings as well as the Struts Mailreader Example application.

         Action attributes - An Action attribute has been added to the html img tag, to match what's available on the html link tag now.

       Module attribute - A new "module" attribute is available on the forward element as well as several of the core tags. This attribute allows you to specify another module by name (or "prefix") to create direct links between modules. The new module attribute is preferered to the contextRelative attribute and can often be used in lieu of a "SwitchAction".

This section highlights some of the changes that have taken place since the last release. Subscribers to the
        struts-dev mailing list, receive reports of all changes as they are made.

          General Changes

2004-09-02 - URI for Struts DTD changed to reflect move to an Apache top level project.

2004-08-31 - Code changes to re-enable building with JDK 1.3.

2003-03-14 - Move license on all source code files to ASL 2.0.

2003-12-30 - Add inital STATUS LOG.

          Build Changes

                2004-07-09: struts.xsl: Give each "src" variable a distinct name to follow XSL rules.

                2004-07-08: build.properties.sample.lib: Add a simplified build.properties file for use by developers who are not actively involved in Jakarta development. This template assumes the developer is using JARS from our "lib" distribution.

2004-04-14 - project.properties: Adjust properties to use alternate repo for nightly builds.

2003-08-09 - build.xml: Adjust loading order of properties files to go from most local (current directory) to most global (${user.home}/build.properties).

2003-08-08 - maven.xml,project.xml - Maven build files.

        Configuration Changes [
        /conf/shared]

2003-08-09 - Add two new elements <description-short%gt; and <description-long> for use by struts config file tools and document generation.

2003-07-04 - struts-config_1_2.dtd: Added 1.2 struts-config.dtd. This is a copy of the 1.1 DTD except that the <data-source> "type" attribute is now required because Struts does not supply a default DataSource implementation.

        Project-wide Changes

2004-01-14 - Update License format to please Maven Checkstyle reports.

2004-01-10 - Removed @author javadoc tags from all classes; updated volunteers.xml to list missing people.

        Default Package Changes [
        org.apache.struts]

2003-07-04 - Globals: Removed deprecated APPLICATION_KEY.

2003-07-03 - Globals,ActionServlet,RequestUtils: Moved initialization of module prefix list to the new ActionServlet.initModulePrefixes() method from RequestUtils.getModulePrefixes() because of a potential race condition documented in PR# 21091. This also required a move of the RequestUtils.PREFIXES constant to Globals.MODULE_PREFIXES_KEY.

        Action Package Changes [
        org.apache.struts.action]

2004-09-10 - Corrected Japanese translation of message resources.

2004-09-07 - Action: Use ActionMessages instead of ActionErrors.

2004-09-03 - ActionServlet: Eliminate performance bottleneck in obtaining request processor.

2004-09-03 - ActionForward: New copy constructor that takes module parameter; deprecate copy constructor missing this parameter.

2004-09-02 - Correct javadoc for ActionErrors.

2004-08-10 - DynaActionForm: Change Map's key from String to Object in toString().

2004-07-01 - TestDynaActionFormClass: Correct operation of static method calls.

2004-06-26 - Action: Add getErrors, getMessages, addErrors, and AddMessages methods, to better manage error handling.

2004-04-01 - ActionConfigMatcher: Added support for multiple wildcard replacements.

2004-03-16 - ActionForward: Add "copy constructor".

2004-01-24 - DynaActionForm: Enhance so that it can be initialized using a FormBeanConfig object. Add corresponding method to RequestUtils to create an ActionForm by passing only a FormBeanConfig and an ActionServlet object.

2004-01-19 - ActionMapping, ActionConfig: Push "findException" from ActionMapping up to ActionConfig so that everyone can take advantage of the superclass search logic.

2003-09-29 - RequestProcessor,ActionMappingMatcher,WildcardHelper: Added optional wildcard support for action mappings.

2003-09-11 - Action,ActionMessages,RequestProcessor: Added ability to save ActionMessages in the session and have them cleaned up after the first use.

2003-08-23 - Action: Deprecate saveErrors(HttpServletRequest, ActionErrors) in favor of saveErrors(HttpServletRequest, ActionMessages).

2003-08-23 - RequestProcessor: Replaced ActionErrors reference with ActionMessages.

2003-08-23 - ActionMessages, ActionErrors: Deprecated ActionErrors.GLOBAL_ERROR in favor of ActionMessages.GLOBAL_MESSAGE.

2003-08-16 - ExceptionHandler: Added storeException() method that takes an ActionMessage instead of ActionError.

2003-08-13 - ActionError: Deprecate ActionError in favor of ActionMessage

2003-08-08 - ActionServlet,ActionFormBeans,ActionForwards,ActionMappings.java v 1.13 : Removed references to ActionMappings, ActionFormBeans, and ActionForwards.

2003-07-26 - Action: getLocale() now calls RequestUtils.getUserLocale() to prevent session creation.

2003-07-04 - Action,ActionException: Removed deprecated getResources() method.

2003-07-04 - Action: Removed deprecated perform() methods.

2003-07-03 - ActionServlet: Removed support for some of the deprecated servlet init parameters.

2003-07-03 - Globals,ActionServlet,RequestUtils: Moved initialization of module prefix list to the new ActionServlet.initModulePrefixes() method from RequestUtils.getModulePrefixes() because of a potential race condition documented in PR# 21091. This also required a move of the RequestUtils.PREFIXES constant to Globals.MODULE_PREFIXES_KEY.

2003-07-02 - RequestProcessor: Deprecated log() methods in favor of commons-logging.

2003-07-02 - ActionSerlvet: Removed deprecated method.

2003-07-02 - ActionServlet: Removed references to deprecated ApplicationConfig class.

2003-07-02 - ActionServlet,NoOpAction: Removed deprecated ActionServlet debug level and logging methods.

2003-07-02 - RequestProcessor: Changed processRoles() to send a 403 Forbidden response if the role check fails. Also removed deprecated methods.

2003-07-01 - Action: Removed deprecated constants and toHex() method.

        Actions Package Changes [
        org.apache.struts.actions]

2004-06-24 - RedeployableActionServlet: Provides support for WebLogi hot-deploy.

2003-12-22 - DispatchAction: Add detection of recursive calls.

2003-08-13 - DispatchAction,LookupDispatchAction: Add 'default' and a 'cancel' handlers to DispatchAction and LookupDispatchAction.

2003-08-12 - MappingDispatchAction: Addition of MappingDispatchAction that dispatches to a method named by the ActionMapping parameter.

2003-07-11 - DispatchAction,ForwardAction,IncludeAction,SwitchAction: Throw exceptions from execute() method instead of sending a failure response to the client. This allows the exception handling mechanism to respond to the error gracefully.

2003-07-03 - LookupDispatchAction: Fixed synchronization problem (PR# 21224). Also refactored some code into a new initLookupMap() method.

        Config Package [
        org.apache.struts.config]

              2004-07-31 - Enhance support for "lazy" dynabeans or POJO beans. "Lazy" DynaBeans will hopefully soon be released with Beanutils 1.7.0. These changes will make it easier to plug either a regular JavaBean or a "lazy" DynaBean into struts as an ActionForm. * FormBeanConfig now sets up the properties of DynaBeans which use a MutableDynaClass. * FormBeanConfig now handles POJO beans by wrapping the specified bean using WrapDynaBean and the new BeanValidatorForm. * RequestUtils has been changed so that properties starting with "org.apache.struts" are not attempted to be populated in the ActionForm.

2004-04-14 - ModuleConfig.java: Local, as well as global, ActionForwards now observe pluggable classes.

2004-04-08 - ModuleConfigImpl: Added a list to store ActionConfigs to ensure when enumerated, they are in the order in which they were added.

2004-02-17 - Undeprecate and Restore the functionality for the 'type' attribute on form-beans and global-forwards elements in the config file.

2004-02-13 - Add module property to ForwardConfig to support direct cross-linking between modules.

2004-01-10 - Changed WildcardHelper methods from statics to instance methods to allow subclasses to override and customize behavior. Changed WildcardHelper.match() to accept a generic Map parameter rather than HashMap.

2003-08-08 - ConfigHelper,ConfigHelperInterface: Removed references to ActionMappings, ActionFormBeans, and ActionForwards.

2003-07-27 - ConfigHelper: Deprecate methods() since they return objects that have been deprecated. The ModuleConfig object should be used to lookup these items.

2003-07-16 - ModuleConfigFactory: Catch only relevant exceptions instead of Throwable and made LOG final.

2003-07-04 - struts-config_1_2.dtd, ControllerConfig.java: Removed deprecated debug controller attribute.

2003-07-04 - ActionConfig: Removed deprecated perform() methods.

ApplicationConfig: removed in favor of ModuleConfig.

        Contrib Packages [
        /contrib]

2004-06-29 - struts-chain: Wrap HttpServletRequest to ensure correct handling of URIs.

2004-02-29 - struts-chain: Fix problem with large uploads being deleted if validation failed.

2004-01-15 - struts-chain: Add Tiles support. Add null check for type, to support forward actions; also add commons loggging

2004-01-14 - struts-chain: Add support for 'unknown' actions.

2004-07-07 - struts-faces: correct operation of <s:base> tag and add portlet specific version.

2004-03-08 - struts-faces: updated for JSF 1.0 final release.

2003-12-31 - struts-faces: Initial support for Tiles; partial "Tilesization" of example app; *not* ready for prime time but comments definately welcome.

2003-12-29 - struts-faces: Various updates regarding the JSF Final Draft and to prepare for Tiles support.

2003-12-17 - struts-jericho: Whiteboard directory for Struts-Jericho, a working proposal for Struts 2.x.

2003-09-07 - strutsel.taglib.tiles: Addition of "tiles-el" library

2004-08-10 - TilesUtilImpl: Remove "static" modifier from doInclude() method.

2003-08-11 - struts-chain: Initial check-in of an experimental library that decomposes the Struts 1.1 request procoessor, using the newly checked in Commons Sandbox project called "chain" supporting the Chain of Responsibility pattern.

2003-08-10 - strutsel: Added action attribute added in base class

2003-08-10 - strutsel: Removed deprecated FormTag attributes: name, scope, type.

2003-08-10 - struts-legacy: Removed package (GenericDataSource and GenericConnection).

2003-07-26 - strutsel: Updated tags to match recent attribute changes to tags in base library.

        Plugins Package [
        org.apache.struts.plugins]

2003-08-07 - DigestingPlugIn.java: Added DigestingPlugIn.

        Taglib Package Changes [
        org.apache.struts.taglib]

2004-06-26 - EmptyTag: Add support for arrays.

2004-02-24 - createDynamicJavascript: Move test for null validator form inside "createDynamicJavascript" so that those who use the tag to generate static javascript don't get a JspException.

2003-09-09 - TagUtils: Log error message when keys or bundles are missing.

2003-08-23 - TagUtils: Deprecated getActionErrors() in favor of getActionMessages().

2003-08-16 - TagUtils: Replaced ActionError with ActionMessage.

2003-08-02 - LocalStrings.properties,TagUtils: Move message resources from util package.

2003-07-26 - TagUtils,RequestUtils: Added TagUtils class for taglibs to use instead of RequestUtils. We should migrate any method in RequestUtils that takes a PageContext parameter and/or throws JspException. A clean separation will help keep RequestUtils smaller and allow the taglibs to be easily split off of the core Struts distribution.

        Bean Taglib Package Changes [
        org.apache.struts.taglib.bean]

2004-01-14 - WriteTag: Use client locale when applying date format.

2004-01-01 - WriteTag: Add notes regarding discovering localized notations.

2003-08-28 - IncludeTag: Rename setCookie to addCookie since it isn't a bean setter

2003-07-13 - MessageTag: Simplified args[] creation, deprecated unused defaultLocale variable.

        HTML Taglib Package Changes [
        org.apache.struts.taglib.html]:

2004-08-24 - ImgTag: Correct usage in a module environment.

2004-07-21 - Add accept-charset attribute to the FormTag.

2004-07-01 - JavascriptValidatorTag - Correct naming of JS methods when multiple forms are used.

2004-05-17 - OptionsCollectionTag,OptionsTag: Filter values as well as labels.

2004-03-08 - JavascriptValidatorTag - Allow multiple forms to be on the same page by generating a unique variable name based on form name.

2004-02-14 - Substitute "-" for "/" in JavaScript function name when form is subclass of ValidatorActionForm.

2004-02-07 - Add "module" attribute to IncludeTag, ImgTag, LinkTag, and RewriteTag, as well as to Forward.
              This permits a module to be referenced by name (or "prefix) for direct cross-linking between modules.

2004-02-04 - Run validator messages through a routine to escape quote marks so that the emitted JavaScript is syntactically correct.

2004-02-04 - Throw JspException when no form is found in the ValidatorResources under the specified 'name'.

2004-01-18 - Add "action" attribute to img tag.

2004-01-09 - Add disabled element to TLD.

2004-01-03 - Add 10 new tests that cover "some" of the functionality provided by html:options. More to come.

2004-01-01 - In link-related tags, allow LocalCharacterEncoding to be specified conditionally.

2003-11-28 - JavascriptValidatorTag - Removed getNextVar() and replaceChar() methods and use a simpler javascript identifier naming scheme. All variables with be named a0, a1, etc. to prevent using reserved words as variable names.

2003-08-19 - Remove "request scope" references from messages tag. The messages are searched for in all scopes.

2003-08-10 - struts-html.xml,RewriteTag.java: Added action attribute to rewrite tag.

2003-08-10 - Removed deprecated FormTag attributes: name, scope, type.

2003-07-08 - struts-html.xml,FormTag,JavascriptValidatorTag: Added scriptLanguage property to the form and javascript tags for PR# 17234. This property is ignored in XHTML mode but allows developers to turn off the "language" attribute of <script> tags in HTML.

2003-07-03 - FormTag: Added disabled check to focus JavaScript

2003-07-02 - HtmlTag: Removed deprecated method.

2003-07-02 - BaseHandlerTag: Use RequestUtils.isXhtml() instead of duplicating logic.

2003-07-02 - ErrorsTag: Don't render new lines

        Logic Taglib Package Changes [
        org.apache.struts.taglib.logic]:

2004-01-16 - logic:redirect - Add action attribute.

2003-07-31 - PresentTag,RedirectTag: Replace depricated method calls with non-deprecated ones.

        Nested Taglib Package Changes [
        org.apache.struts.taglib.nested]:

2004-03-22 - Add missing filter attribute to nested:options and nested:optionsCollection.

2004-01-01 - Correct operation of NestedMessage* tags by implementing NestedPropertySupport rather than NestedNameSupport.

2003-08-10 - Removed deprecated FormTag attributes: name, scope, type.

2003-07-03 - struts-nested.xml: Added styleId to nested:hidden

        Tiles Taglib Package Changes [
        org.apache.struts.taglib.tiles]:

2004-05-17 - PutTag: Manage tag body content more carefully to ensure pooled tags do not display old content with empty tiles.

2003-09-07 - ImportAttributeTag,UseAttributeTag: Removing "final" from class declaration, to allow class to be extended in "tiles-el" (or other classes).

2003-07-27 - xmlDefinition/XmlParser: Remove deprecated/non functional digester logging method.

2003-07-10 - TagUtils: Deprecated getProperty() because it provided no value over calling PropertyUtils.getProperty() directly.

2003-07-08 - TilesServlet,ActionComponentServlet: Formatted code, removed deprecated constant.

2003-07-04 - ActionController: Call Action.execute() instead of perform().

        Tiles Package Changes [
        org.apache.struts.tiles]:

2003-09-13 - Controller: Added execute() method to Tiles Controller interface.

2003-08-16 - portal.UserMenuAction: Replaced hardcoded debugging with commons logging.

2003-07-31 - xmlDefinition/I18nFactorySet: Replace deprecated constant reference with it's base interface equal.

2003-07-31 - actions/DefinitionDispatcherAction: Replace deprecated method with current one. Still one method DefinitionUtil.setActionDefinition that doesn't have a replacement. It's a simple method but I don't know where a good place to move it would be.

2003-07-31 - actions/ReloadDefinitionsAction: Use TilesUtil.createDefinitionsFactory(request,context) instead of deprecated method().

2003-07-21 - struts-*config.xml: Remove the use of the deprecated action NoOpAction. Replace by ForwardAction.

2003-07-21 - *Action: Replace the deprecated perform(..) method by the new execute(...) method.

2003-07-12 - DefinitionDispatcherAction: Use commons-logging to record error messages instead of printing them to the response.

2003-07-10 - TilesAction: Removed deprecated perform() method.

2003-07-09 - Removed deprecated TilesUtil.applicationClass() method.

2003-07-08 - DefinitionsUtil.java: Deprecated debug level constants, removed some deprecated methods.

2003-07-08 - ChannelFactorySet: Use commons-logging instead of printing to stdout.

2003-07-07 - InsertTag: Fixed exception handling. Instead of swallowing exceptions or printing the stack trace on the page, the exceptions are logged and rethrown as JspException for the page error handling mechanism to deal with.

2003-07-07 - InsertTag: More code cleanup, removed deprecated method, deprecated ROLE_DELIMITER because it is only used internally to this class

2003-07-04 - ComponentContext: Removed deprecated constructor

2003-07-02 - Changed UntyppedAttribute class name to UntypedAttribute (spelling error).

        Upload Package Changes [
        org.apache.struts.upload]:

2004-04-08 - CommonsMultipartRequestHandler: Made CommonsFormFile serializable since it gets put into the session

2004-03-22 - Allow MultipartPost with latin1 characters over Linux.

2004-01-21 - Add support for an "EncodingFilter" to handle multibyte file names.

2003-11-26 - DiskMultipartRequestHandler: Deprecate DiskMultipartRequestHandler and friends, which is the buggy old upload implementation, no longer used as the default as of Struts 1.1. This will be removed after 1.2 (meaning as of 1.3/2.0).

2003-07-31 - MultipartElement: Remove deprecated methods.

        Utility Package Changes [
        org.apache.struts.util]:

                2004-07-21 - ModuleUtil: Add module support to the bundle attribute.
                2004-07-07 - TokenProcessor: Ensure that tokens returned differ even if called quickly by tracking last value used.

2004-04-08 - RequestUtils: Fixed inappropriate serialization of ModuleConfig when a DynaActionForm was put in the session.

2003-09-22 - LabelValueBean: Implement Comparable interface.

2003-08-16 - ModuleException: Added getActionMessage() to replace the getError() method.

2003-08-02 - LocalStrings.properties: Move message resources to taglib TagUtil package.

2003-08-02 - ModuleUtils.java,RequestUtils.java: Moved module related methods to new ModuleUtils class.

2003-07-26 - TagUtils,RequestUtils: Added TagUtils class for taglibs to use instead of RequestUtils. We should migrate any method in RequestUtils that takes a PageContext parameter and/or throws JspException. A clean separation will help keep RequestUtils smaller and allow the taglibs to be easily split off of the core Struts distribution.

2003-07-25 - RequestUtils: Backwards compatibility fix. Changed ModuleConfig lookups to use getModuleConfig so that default module config is returned if one is not already present in the request

2003-07-16 - RequestUtils: Make retrieveMessageResources() module-aware by adding the module prefix to the bundle name when retrieving from application context.

2003-07-03 - LabelValueBean: Added equals and hashCode() methods.

2003-07-03 - Globals,ActionServlet,RequestUtils: Moved initialization of module prefix list to the new ActionServlet.initModulePrefixes() method from RequestUtils.getModulePrefixes() because of a potential race condition documented in PR# 21091. This also required a move of the RequestUtils.PREFIXES constant to Globals.MODULE_PREFIXES_KEY.

2003-07-02 - RequestUtils,TestRequestUtils: Removed deprecated "application" methods in favor of "module" methods.

2003-07-02 - LabelValueBean: Added default constructor.

        Validator Package Changes [
        org.apache.struts.validator]

2004-09-03 - ValidWhen: Added new test cases.

2004-09-03 - ValidWhen: Correct parsing of integer values.

2004-06-24 - ValidWhen: "allow '_' (underscore) in identifiers.

2004-04-16 - FieldChecks: Add optional variables to configure various aspects of URL validation.

2004-04-03 - ValidatorPlugIn: Modify Validator PlugIn to validate XML file and errros now throw an exception to loudly flag an error. Remove deprecated classes, now in Commons Validator.

2004-04-02 - Add a getValidationKey method to make it eaiser for subclasses to use different rules for finding the Validator form.

2004-02-20 - Changed FieldCheck so that it examines all indexed fields and does not stop on the first failure.

2004-01-17 - Changed initValidator() to accept an ActionMessages object instead of ActionErrors; changed ACTION_ERRORS_PARAM name to ACTION_MESSAGES_PARAM.

2004-01-17 - Add section to Validator User Guide listing standard validations.

2003-12-21 - Add rest of form to fr.CA formset to correct operation; Use action form of html:link;

2003-10-06 - FieldChecks - Add validateUrl. Remove deprecated validateRange.

2003-09-26 - FieldChecks,ValidWhen: Changed validator signatures to use ActionMessages rather than ActionErrors, was breaking validations.

2003-09-26 - validator-rules.xml: Modify JavaScript to honor datePattern option.

2003-09-24 - validator-rules.xml: Add ability of required to handle checkboxes, radio,select-one, and select-multiple field types.

2003-07-30 - validator-rules.xml: Remove deprecated range() method. Use intRange() instead.

2003-07-30 - validator-rules.xml: Allow intRange validation of select-one and radio fields. In some form combo boxes you might have the combo boxes populated with valid choices plus one additional choice with a caption something like "Choose one" and a value 0f "-1". Then when the user attempts to submit the form, you can look for the value of "-1" and yell at them if they failed to pick something.

2003-07-28 - JavascriptValidatorTag.java,ValidatorPlugIn.java: Enhancement to allow checking of all constraints instead of aborting. The default is same as struts 1.1.

2003-07-26 - Resources: Deprecated Resources.getLocale() because it created sessions. Use RequestUtils.getUserLocale() instead.

2003-07-02 - Resources: Rewrote getArgs() method to use arrays and loops, which removes limitation of 4 args.

2003-07-02 - Resources: Remove deprecated methods

2003-07-02 - Validator,ValdiatorUtils: Changed processRoles() to send a 403 Forbidden response if the role check fails. Also removed deprecated methods.

2003-07-01 - Add validwhen validation to package.

        Documentation Application Changes [
        struts-documentation.war]:

2004-08-31 - Added a Struts download page, reflecting the move to an Apache top level project.

2004-08-24 - Fix build script errors on Eclipse HOW-TO page.

2004-07-11 - Add links to development releases.

2004-07-07 - Rename "status.xml" to "roadmap.xml" to avoid confusion with STATUS.txt file.

2004-07-07 - Extend prior draft of bylaws page with additional material from Jakarta site and link to main menu.

2004-03-28 - Added Trifork server to Installing Struts on Various Containers section.

2004-03-24 - Document new exception-throwing behavior in html:javascript when dynamicJavascript is true but no form can be identified.

2003-11-27 - resource: Move resource area to
          Struts SourceForge site.

        MailReader Example Application Changes [
        struts-example.war]:

2004-03-07 - Various refactorings to JSP pages, welcome and login action.

2004-01-08 - Use (new) DigestingPlugIn to create the menu of server types.

2003-12-21 - Change to use typical welcome.do - welcome.jsp approach; Use "name" rather than "attribute" in configuration, per documented and common practice; Use action form of html:link

2003-10-25 - Updated to include the usage of wildcards in action mappings.

2003-08-30 - AlternateApplicationResources_ja.properties,ApplicationResources_ja.properties: Provide Japanese resources.

2003-08-16 - Changed ActionError to ActionMessage.

        Combined Examples Application [
        struts-examples.war]

2004-09-07 - Fix problems with running the application while not connected to the internet.

2004-09-03 - Change Commons Validator DTD to version 1.1.3.

2004-01-17 - Add tests to to hmlt:link page for forwards, actions, and pages.

2004-01-16 - exercises: Add test pages for html:img and logic:forward,redirect. Add test pages for html:img and logic:forward,redirect tags

2004-01-08 - Convert Taglib-Exercises, Upload, and Validator example applications into modules of a combined examples application.

        Exercise module Changes:

2004-01-09 - Enable inputForward.

2004-01-01 - Add several tests to bean:write: localized numbers; date format pattern; localization.

2003-07-23 - html-messages.jsp: Updated to reference Globals constants.

          Upload Example module Changes

2004-01-09 - Enable inputForward; use message tags for validation errors; refine markup on display page.

2004-01-08 - Convert to Upload example application to module under the "examples" application.

2003-08-16 - Changed ActionError to ActionMessage.

          Validator Example module Changes

2004-06-25 - Update arg elements to use new dynamic feature, that does not requiring numbering.

2004-03-25 - Modify example to test proper behaviour is a property is named 'name'.

2004-01-09 - Enable inputForward.

2004-01-08 - Convert to Validator Example application to module under the "examples" application.

2003-12-21 - Add rest of form to fr.CA formset to correct operation.

2003-09-24 - Modify Validator example to show use of 'required' for checkboxes, radio,select-one, and select-multiple field types.

Next:
        Installation

</document>


text:
package dk.simplecontentprovider.demo;

import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import dk.simplecontentprovider.demo.provider.DemoContract;

public class OverviewActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {
    private SimpleCursorAdapter mAdapter;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, OverviewActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        mAdapter = new SimpleCursorAdapter(this, R.layout.item_overview, null,
                new String[]{DemoContract.OwnersAndPetsView.NAME, DemoContract.OwnersAndPetsView.NUMBER_OF_PETS, DemoContract.OwnersAndPetsView.PET_NAMES},
                new int[]{R.id.owner_name, R.id.pet_count, R.id.pet_names}, 0);

        setListAdapter(mAdapter);

        View emptyView = getListView().getEmptyView();
        if (emptyView instanceof TextView) {
            ((TextView) emptyView).setText("No data");
        }

        getLoaderManager().initLoader(0, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(this, DemoContract.OwnersAndPetsView.CONTENT_URI,
                new String[]{DemoContract.OwnersAndPetsView._ID, DemoContract.OwnersAndPetsView.NAME, DemoContract.OwnersAndPetsView.NUMBER_OF_PETS, DemoContract.OwnersAndPetsView.PET_NAMES}, null, null,
                DemoContract.OwnersAndPetsView.NAME);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }
}


text:
def deep_update(a, b):
    """Allow piece-wise overriding of dictionaries"""
    for k, v in b.items():
        if type(v) is dict and type(a) is dict and type(a.get(k)) is dict:
            deep_update(a[k], v)
        else:
            a[k] = v

def import_string(modstr):
    """Resolve a package.module.variable string"""
    module_name, module_var = modstr.rsplit('.', 1)

    module = __import__(module_name)
    for elt in module_name.split('.')[1:]:
        module = getattr(module, elt)

    return getattr(module, module_var)


text:
export default class View {

    /**
     * Retorna uma instancia da classe View
     * Classe base para o template engine
     */
    constructor(element) {
        this._element = document.querySelector(element);
    }

    /**
     * Retorna um erro caso a classe filha nao implemente esse metodo
     * Forca a classe que a extende a ter esse metodo
     */
    template() {
        throw new Error('The template method must be implemented');
    }

    /**
     * Faz o update no DOM de acordo com o template da classe
     * Se a classe filha conter o metodo callback, esse metodo e chamado
     * Serve para acoes apos o html ter sido atualizado
     *
     * @param {Object} model
     * @param {Function} callback
     */
    update(model, callback = null) {
        this._element.innerHTML = this.template(model);

        Object.getOwnPropertyNames(Object.getPrototypeOf(this))
            .forEach(iten => iten == 'callback' ? this.callback() :'');
    }
}


text:
import scala.tools.testkit.async.Async._
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits._

object Test extends App {

  def stackDepth = Thread.currentThread().getStackTrace.length

  val future = async {
    val thread1 = Thread.currentThread
    val stackDepth1 = stackDepth

    val f = await(Future.successful(1))
    val thread2 = Thread.currentThread
    val stackDepth2 = stackDepth
    assert(thread1 == thread2)
    assert(stackDepth1 == stackDepth2)
  }
  Await.result(future, 10.seconds)

}


text:
import { CLEAR_ERROR } from '../actions/Error'
import { REJECT_ACCOUNTS } from '../actions/Accounts'
import { REJECT_TRANSACTIONS } from '../actions/Transactions'

const error = (state = {
  type: null,
  description: null
}, action) => {
  switch (action.type) {
    case REJECT_ACCOUNTS:
    case REJECT_TRANSACTIONS:
      return {
        ...state,
        type: action.error.code,
        description: action.error.message
      }
    case CLEAR_ERROR:
      return {
        ...state,
        type: null,
        description: null
      }
    default:
      return state
  }
}

export default error


text:
package org.fastcatsearch.cli.command.exception;

public class CollectionNotFoundException extends Exception {

}


text:
'use strict'

const test = require('ava').test
const ParseCommand = require('../src/receiver/middleware/parse-command')
const fixtures = require('./fixtures/')

const SIGNATURE = 'mysignature'
const TIMESTAMP = Date.now()

test('ParseCommand()', t => {
  let mw = ParseCommand()
  t.is(mw.length, 2)
})

test.cb('ParseCommand() no payload', t => {
  let mw = ParseCommand().pop()
  let req = { body: {} }

  mw(req, {}, () => {
    let slapp = req.slapp

    t.is(slapp.type, 'command')
    t.deepEqual(slapp.body, req.body)
    t.is(slapp.meta.verify_token, undefined)
    t.is(slapp.meta.user_id, undefined)
    t.is(slapp.meta.channel_id, undefined)
    t.is(slapp.meta.team_id, undefined)
    t.end()
  })
})

test.cb('ParseCommand() with payload', t => {
  let mw = ParseCommand().pop()
  let payload = mockPayload()
  let req = {
    body: payload,
    headers: fixtures.getMockSlackHeaders(SIGNATURE, TIMESTAMP)
  }
  let res = fixtures.getMockRes()

  mw(req, res, () => {
    let slapp = req.slapp

    t.is(slapp.type, 'command')
    t.deepEqual(slapp.body, req.body)
    t.is(slapp.meta.verify_token, payload.token)
    t.is(slapp.meta.user_id, payload.user_id)
    t.is(slapp.meta.channel_id, payload.channel_id)
    t.is(slapp.meta.team_id, payload.team_id)
    t.is(slapp.meta.signature, SIGNATURE)
    t.is(slapp.meta.timestamp, TIMESTAMP)
    t.is(slapp.response, res)
    t.is(slapp.responseTimeout, 2500)
    t.end()
  })
})

function mockPayload () {
  return {
    token: 'token',
    user_id: 'user_id',
    channel_id: 'channel_id',
    team_id: 'team_id'
  }
}


text:
from rapp_DEVICE_api_audio import DeviceAudio
from rapp_DEVICE_api_motion import DeviceMotion
from rapp_DEVICE_api_sensors import DeviceSensors
from rapp_DEVICE_api_humanoid_motion import DeviceHumanoidMotion
from rapp_DEVICE_api_vision import DeviceVision

# The upper class (namespace), containing per-functionality modules
class RappRobot:
    def __init__(self):

        self.parameters = {}

        self.audio = DeviceAudio(self.parameters)
        self.motion = DeviceMotion(self.parameters)
        self.sensors = DeviceSensors(self.parameters)
        self.humanoid_motion = DeviceHumanoidMotion(self.parameters)
        self.vision = DeviceVision(self.parameters)


text:
class Browser;

namespace media_router {

// Dialog that asks the user whether they want to enable cloud services for the
// Cast feature.
class CloudServicesDialogView : public views::BubbleDialogDelegateView,
                                public views::StyledLabelListener {
 public:
  // Instantiates and shows the singleton dialog.
  static void ShowDialog(views::View* anchor_view, Browser* browser);

  // No-op if the dialog is currently not shown.
  static void HideDialog();

  static bool IsShowing();

  // Called by tests. Returns the singleton dialog instance.
  static CloudServicesDialogView* GetDialogForTest();

  // views::WidgetDelegateView:
  bool ShouldShowCloseButton() const override;

  // views::WidgetDelegate:
  base::string16 GetWindowTitle() const override;

  // views::View:
  gfx::Size CalculatePreferredSize() const override;

 private:
  CloudServicesDialogView(views::View* anchor_view, Browser* browser);
  ~CloudServicesDialogView() override;

  void OnDialogAccepted();

  // views::BubbleDialogDelegateView:
  void Init() override;
  void WindowClosing() override;

  // views::StyledLabelListener:
  void StyledLabelLinkClicked(views::StyledLabel* label,
                              const gfx::Range& range,
                              int event_flags) override;

  // The singleton dialog instance. This is a nullptr when a dialog is not
  // shown.
  static CloudServicesDialogView* instance_;

  // Browser window that this dialog is attached to.
  Browser* const browser_;

  DISALLOW_COPY_AND_ASSIGN(CloudServicesDialogView);
};

}  // namespace media_router

#endif  // CHROME_BROWSER_UI_VIEWS_MEDIA_ROUTER_CLOUD_SERVICES_DIALOG_VIEW_H_


text:
package de.kaiserpfalzedv.paladinsinn.commons.api.tenant.model;

import java.util.UUID;

import de.kaiserpfalzedv.paladinsinn.commons.api.persistence.Identifiable;

/**
 * The tenant of a data node in the database.
 *
 * @author rlichti {@literal <rlichti@kaiserpfalz-edv.de>}
 * @since 2016-03-20
 */
public interface Tenant extends Identifiable {
    /**
     * The default tenant id for non-multitenant systems.
     */
    UUID DEFAULT_TENANT = UUID.fromString("4dfb9268-7f29-4442-a458-f00e7e620f18");

    String getKey();
}