text:
Data Retrieval And Manipulation
===============================

Data Retrieval
--------------

Using a database implies retrieval of data. It is the primary use-case of a database.
For this purpose each database vendor exposes a Client API that can be integrated into
programming languages. PHP has a generic abstraction layer for this
kind of API called PDO (PHP Data Objects). However because of disagreements
between the PHP community there are often native extensions for each database
vendor that are much more maintained (OCI8 for example).

Doctrine DBAL API integrates native extensions. If you already have an open connection
through the ``Doctrine\DBAL\DriverManager::getConnection()`` method you
can start using this API for data retrieval easily.

Start writing an SQL query and pass it to the ``query()`` method of your
connection:

.. code-block:: php

    <?php
    use Doctrine\DBAL\DriverManager;

    $conn = DriverManager::getConnection($params, $config);

    $sql = "SELECT * FROM articles";
    $stmt = $conn->query($sql); // Simple, but has several drawbacks

The query method executes the SQL and returns a database statement object.
A database statement object can be iterated to retrieve all the rows that matched
the query until there are no more rows:

.. code-block:: php

    <?php

    while (($row = $stmt->fetchAssociative()) !== false) {
        echo $row['headline'];
    }

The query method is the most simple one for fetching data, but it also has
several drawbacks:

-   There is no way to add dynamic parameters to the SQL query without modifying
    ``$sql`` itself. This can easily lead to a category of security
    holes called **SQL injection**, where a third party can modify the SQL executed
    and even execute their own queries through clever exploiting of the security hole.
-   **Quoting** dynamic parameters for an SQL query is tedious work and requires lots
    of use of the ``Doctrine\DBAL\Connection#quote()`` method, which makes the
    original SQL query hard to read/understand.
-   Databases optimize SQL queries before they are executed. Using the query method
    you will trigger the optimization process over and over again, although
    it could re-use this information easily using a technique called **prepared statements**.

These three arguments and some more technical details hopefully convinced you to investigate
prepared statements for accessing your database.

Dynamic Parameters and Prepared Statements
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Consider the previous query, now parameterized to fetch only a single article by id.
Using **ext/mysql** (still the primary choice of MySQL access for many developers) you had to escape
every value passed into the query using ``mysql_real_escape_string()`` to avoid SQL injection:

.. code-block:: php

    <?php
    $sql = "SELECT * FROM articles WHERE id = '" . mysql_real_escape_string($id, $link) . "'";
    $rs = mysql_query($sql);

If you start adding more and more parameters to a query (for example in UPDATE or INSERT statements)
this approach might lead to complex to maintain SQL queries. The reason is simple, the actual
SQL query is not clearly separated from the input parameters. Prepared statements separate
these two concepts by requiring the developer to add **placeholders** to the SQL query (prepare) which
are then replaced by their actual values in a second step (execute).

.. code-block:: php

    <?php
    // $conn instanceof Doctrine\DBAL\Connection

    $sql = "SELECT * FROM articles WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1, $id);
    $resultSet = $stmt->executeQuery();

Placeholders in prepared statements are either simple positional question marks (``?``) or named labels starting with
a colon (e.g. ``:name1``). You cannot mix the positional and the named approach. You have to bind a parameter
to each placeholder.

The approach using question marks is called positional, because the values are bound in order from left to right
to any question mark found in the previously prepared SQL query. That is why you specify the
position of the variable to bind into the ``bindValue()`` method:

.. code-block:: php

    <?php
    // $conn instanceof Doctrine\DBAL\Connection

    $sql = "SELECT * FROM articles WHERE id = ? AND status = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1, $id);
    $stmt->bindValue(2, $status);
    $resultSet = $stmt->executeQuery();

Named parameters have the advantage that their labels can be re-used and only need to be bound once:

.. code-block:: php

    <?php
    // $conn instanceof Doctrine\DBAL\Connection

    $sql = "SELECT * FROM users WHERE name = :name OR username = :name";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue("name", $name);
    $resultSet = $stmt->executeQuery();

The following section describes the API of Doctrine DBAL with regard to prepared statements.

.. note::

    Support for positional and named prepared statements varies between the different
    database extensions. PDO implements its own client side parser so that both approaches
    are feasible for all PDO drivers. OCI8/Oracle only supports named parameters, but
    Doctrine implements a client side parser to allow positional parameters also.

Using Prepared Statements
~~~~~~~~~~~~~~~~~~~~~~~~~

There are three low-level methods on ``Doctrine\DBAL\Connection`` that allow you to
use prepared statements:

-   ``prepare($sql)`` - Create a prepared statement of the type ``Doctrine\DBAL\Statement``.
    Using this method is preferred if you want to re-use the statement to execute several
    queries with the same SQL statement only with different parameters.
-   ``executeQuery($sql, $params, $types)`` - Create a prepared statement for the passed
    SQL query, bind the given params with their binding types and execute the query.
    This method returns the executed prepared statement for iteration and is useful
    for SELECT statements.
-   ``executeStatement($sql, $params, $types)`` - Create a prepared statement for the passed
    SQL query, bind the given params with their binding types and execute the query.
    This method returns the number of affected rows by the executed query and is useful
    for UPDATE, DELETE and INSERT statements.

A simple usage of prepare was shown in the previous section, however it is useful to
dig into the features of a ``Doctrine\DBAL\Statement`` a little bit more. There are essentially
two different types of methods available on a statement. Methods for binding parameters and types
and methods to retrieve data from a statement.

-   ``bindValue($pos, $value, $type)`` - Bind a given value to the positional or named parameter
    in the prepared statement.
-   ``bindParam($pos, &$param, $type)`` - Bind a given reference to the positional or
    named parameter in the prepared statement.

If you are finished with binding parameters you have to call ``executeQuery()`` on the statement,
which will trigger a query to the database. After the query is finished, a ``Doctrine\DBAL\Result``
instance is returned and you can access the results of this query using the fetch API of the result:

-   ``fetchNumeric()`` - Retrieves the next row from the statement or false if there are none.
    The row is fetched as an array with numeric keys where the columns appear in the same order as
    they were specified in the executed ``SELECT`` query.
    Moves the pointer forward one row, so that consecutive calls will always return the next row.
-   ``fetchAssociative()`` - Retrieves the next row from the statement or false if there are none.
    The row is fetched as an associative array where the keys represent the column names as
    specified in the executed ``SELECT`` query.
    Moves the pointer forward one row, so that consecutive calls will always return the next row.
-   ``fetchOne()`` - Retrieves the value of the first column of the next row from the statement
    or false if there are none.
    Moves the pointer forward one row, so that consecutive calls will always return the next row.
-   ``fetchAllNumeric()`` - Retrieves all rows from the statement as arrays with numeric keys.
-   ``fetchAllAssociative()`` - Retrieves all rows from the statement as associative arrays.
-   ``fetchFirstColumn()`` - Retrieves the value of the first column of all rows.

The fetch API of a prepared statement obviously works only for ``SELECT`` queries. If you want to
execute a statement that does not yield a result set, like ``INSERT``, ``UPDATE`` or ``DELETE``
for instance, you might want to call ``executeStatement()`` instead of ``executeQuery()``.

If you find it tedious to write all the prepared statement code you can alternatively use
the ``Doctrine\DBAL\Connection#executeQuery()`` and ``Doctrine\DBAL\Connection#executeStatement()``
methods. See the API section below on details how to use them.

Additionally there are lots of convenience methods for data-retrieval and manipulation
on the Connection, which are all described in the API section below.

Binding Types
-------------

Besides ``Doctrine\DBAL\ParameterType`` constants, you
can make use of two very powerful additional features.

Doctrine\DBAL\Types Conversion
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you don't specify an integer (through one of ``Doctrine\DBAL\ParameterType`` constants) to
any of the parameter binding methods but a string, Doctrine DBAL will
ask the type abstraction layer to convert the passed value from
its PHP to a database representation. This way you can pass ``\DateTime``
instances to a prepared statement and have Doctrine convert them
to the appropriate vendors database format:

.. code-block:: php

    <?php
    $date = new \DateTime("2011-03-05 14:00:21");
    $stmt = $conn->prepare("SELECT * FROM articles WHERE publish_date > ?");
    $stmt->bindValue(1, $date, "datetime");
    $resultSet = $stmt->executeQuery();

If you take a look at ``Doctrine\DBAL\Types\DateTimeType`` you will see that
parts of the conversion are delegated to a method on the current database platform,
which means this code works independent of the database you are using.

.. note::

    Be aware this type conversion only works with ``Statement#bindValue()``,
    ``Connection#executeQuery()`` and ``Connection#executeStatement()``. It
    is not supported to pass a doctrine type name to ``Statement#bindParam()``,
    because this would not work with binding by reference.

List of Parameters Conversion
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

One rather annoying bit of missing functionality in SQL is the support for lists of parameters.
You cannot bind an array of values into a single prepared statement parameter. Consider
the following very common SQL statement:

.. code-block:: sql

    SELECT * FROM articles WHERE id IN (?)

Since you are using an ``IN`` expression you would really like to use it in the following way
(and I guess everybody has tried to do this once in his life, before realizing it doesn't work):

.. code-block:: php

    <?php
    $stmt = $conn->prepare('SELECT * FROM articles WHERE id IN (?)');
    // THIS WILL NOT WORK:
    $stmt->bindValue(1, [1, 2, 3, 4, 5, 6]);
    $resultSet = $stmt->executeQuery();

Implementing a generic way to handle this kind of query is tedious work. This is why most
developers fallback to inserting the parameters directly into the query, which can open
SQL injection possibilities if not handled carefully.

Doctrine DBAL implements a very powerful parsing process that will make this kind of prepared
statement possible natively in the binding type system.
The parsing necessarily comes with a performance overhead, but only if you really use a list of parameters.
There are two special binding types that describe a list of integers or strings:

-   ``\Doctrine\DBAL\Connection::PARAM_INT_ARRAY``
-   ``\Doctrine\DBAL\Connection::PARAM_STR_ARRAY``

Using one of these constants as a type you can activate the SQLParser inside Doctrine that rewrites
the SQL and flattens the specified values into the set of parameters. Consider our previous example:

.. code-block:: php

    <?php
    $stmt = $conn->executeQuery('SELECT * FROM articles WHERE id IN (?)',
        [[1, 2, 3, 4, 5, 6]],
        [\Doctrine\DBAL\Connection::PARAM_INT_ARRAY]
    );

The SQL statement passed to ``Connection#executeQuery`` is not the one actually passed to the
database. It is internally rewritten to look like the following explicit code that could
be specified as well:

.. code-block:: php

    <?php
    // Same SQL WITHOUT usage of Doctrine\DBAL\Connection::PARAM_INT_ARRAY
    $stmt = $conn->executeQuery('SELECT * FROM articles WHERE id IN (?, ?, ?, ?, ?, ?)',
        [1, 2, 3, 4, 5, 6],
        [
            ParameterType::INTEGER,
            ParameterType::INTEGER,
            ParameterType::INTEGER,
            ParameterType::INTEGER,
            ParameterType::INTEGER,
            ParameterType::INTEGER,
        ]
    );

This is much more complicated and is ugly to write generically.

.. note::

    The parameter list support only works with ``Doctrine\DBAL\Connection::executeQuery()``
    and ``Doctrine\DBAL\Connection::executeStatement()``, NOT with the binding methods of
    a prepared statement.

API
---

The DBAL contains several methods for executing queries against
your configured database for data retrieval and manipulation.

These DBAL methods retrieve data from the database using the underlying database driver and do not perform any type conversion.
So the result php type for a database column can vary between database drivers and php versions.

Below we'll introduce these methods and provide some examples for each of
them.

prepare()
~~~~~~~~~

Prepare a given SQL statement and return the
``\Doctrine\DBAL\Statement`` instance:

.. code-block:: php

    <?php
    $statement = $conn->prepare('SELECT * FROM user');
    $resultSet = $statement->executeQuery();
    $users = $resultSet->fetchAllAssociative();

    /*
    array(
      0 => array(
        'username' => 'jwage',
        'email' => 'j.wage@example.com'
      )
    )
    */

executeStatement()
~~~~~~~~~~~~~~~

Executes a prepared statement with the given SQL and parameters and
returns the affected rows count:

.. code-block:: php

    <?php
    $count = $conn->executeStatement('UPDATE user SET username = ? WHERE id = ?', ['jwage', 1]);
    echo $count; // 1

The ``$types`` variable contains the PDO or Doctrine Type constants
to perform necessary type conversions between actual input
parameters and expected database values. See the
:ref:`Types <mappingMatrix>` section for more information.

executeQuery()
~~~~~~~~~~~~~~

Creates a prepared statement for the given SQL and passes the
parameters to the executeQuery method, then returning the result set:

.. code-block:: php

    <?php
    $resultSet = $conn->executeQuery('SELECT * FROM user WHERE username = ?', ['jwage']);
    $user = $resultSet->fetchAssociative();

    /*
    array(
      0 => 'jwage',
      1 => 'j.wage@example.com'
    )
    */

The ``$types`` variable contains the PDO or Doctrine Type constants
to perform necessary type conversions between actual input
parameters and expected database values. See the
:ref:`Types <mappingMatrix>` section for more information.

fetchAllAssociative()
~~~~~~~~~~~~~~~~~~~~~

Execute the query and fetch all results into an array:

.. code-block:: php

    <?php
    $users = $conn->fetchAllAssociative('SELECT * FROM user');

    /*
    array(
      0 => array(
        'username' => 'jwage',
        'email' => 'j.wage@example.com'
      )
    )
    */

fetchAllKeyValue()
~~~~~~~~~~~~~~~~~~

Execute the query and fetch the first two columns into an associative array as keys and values respectively:

.. code-block:: php

    <?php
    $users = $conn->fetchAllKeyValue('SELECT username, email FROM user');

    /*
    array(
      'jwage' => 'j.wage@example.com',
    )
    */

.. note::
   All additional columns will be ignored and are only allowed to be selected by DBAL for its internal purposes.

fetchAllAssociativeIndexed()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Execute the query and fetch the data as an associative array where the key represents the first column and the value is
an associative array of the rest of the columns and their values:

.. code-block:: php

    <?php
    $users = $conn->fetchAllAssociativeIndexed('SELECT id, username, email FROM user');

    /*
    array(
        1 => array(
          'username' => 'jwage',
          'email' => 'j.wage@example.com'
        )
    )
    */

fetchNumeric()
~~~~~~~~~~~~~~

Numeric index retrieval of first result row of the given query:

.. code-block:: php

    <?php
    $user = $conn->fetchNumeric('SELECT * FROM user WHERE username = ?', ['jwage']);

    /*
    array(
      0 => 'jwage',
      1 => 'j.wage@example.com'
    )
    */

fetchOne()
~~~~~~~~~~

Retrieve only the value of the first column of the first result row.

.. code-block:: php

    <?php
    $username = $conn->fetchOne('SELECT username FROM user WHERE id = ?', [1], 0);
    echo $username; // jwage

fetchAssociative()
~~~~~~~~~~~~~~~~~~

Retrieve associative array of the first result row.

.. code-block:: php

    <?php
    $user = $conn->fetchAssociative('SELECT * FROM user WHERE username = ?', ['jwage']);
    /*
    array(
      'username' => 'jwage',
      'email' => 'j.wage@example.com'
    )
    */

There are also convenience methods for data manipulation queries:

iterateKeyValue()
~~~~~~~~~~~~~~~~~

Execute the query and iterate over the first two columns as keys and values respectively:

.. code-block:: php

    <?php
    foreach ($conn->iterateKeyValue('SELECT username, email FROM user') as $username => $email) {
        // ...
    }

.. note::
   All additional columns will be ignored and are only allowed to be selected by DBAL for its internal purposes.

iterateAssociativeIndexed()
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Execute the query and iterate over the result with the key representing the first column and the value being
an associative array of the rest of the columns and their values:

.. code-block:: php

    <?php
    foreach ($conn->iterateAssociativeIndexed('SELECT id, username, email FROM user') as $id => $data) {
        // ...
    }

delete()
~~~~~~~~~

Delete all rows of a table matching the given identifier, where
keys are column names.

.. code-block:: php

    <?php
    $conn->delete('user', ['id' => 1]);
    // DELETE FROM user WHERE id = ? (1)

insert()
~~~~~~~~~

Insert a row into the given table name using the key value pairs of
data.

.. code-block:: php

    <?php
    $conn->insert('user', ['username' => 'jwage']);
    // INSERT INTO user (username) VALUES (?) (jwage)

update()
~~~~~~~~~

Update all rows for the matching key value identifiers with the
given data.

.. code-block:: php

    <?php
    $conn->update('user', ['username' => 'jwage'], ['id' => 1]);
    // UPDATE user (username) VALUES (?) WHERE id = ? (jwage, 1)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Stopsopa\UtilsBundle\Lib;

class AlphaId {
// pochodzi : [http://stackoverflow.com/questions/4514168/unique-alpha-numeric-generator]
  protected $key = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; // youtube używa np : http://www.youtube.com/watch?v=BF1B1dlHEow&list=RD02sdHx_0s-_mQ
//  private $key = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-';  // tylko te znaki są bezpiecznie jeśli chodzi o użycie w php urlencode()
//  private $key = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_)(.-*!~';  // te dodatkowe znaki nie są przetwarzane przez encodeURIComponent js więc na upartego też można ich użyć
  protected $div = 0;
  public function __construct( $key = false) {
    $this->setKey($key);
  }
  public function setKey($key) {
    if ($key && is_string($key) && strlen($key)) {
      $this->key = $key;
    }
    $this->count = strlen($this->key);
  }
  public function encode($num) {
    $encoded = '';
    $count   = $this->count; // optymalizacja - nie wiem czemu ale jest minimalnie szybciej, jeśli kilka takich zmiennych pomocniczych się zastosuje zamiast wywoływać składowe to daje efekt
    $c       = $this->key; // optymalizacja
    while ($num >= $count) {
      $div     = intval($num/$count);
      $encoded.= $c[$num-($count*$div)];
      $num     = $div;
    }
    if ($num) {
      $encoded .= $c[$num];
    }

    return strrev($encoded);
  }
  public function decode($alpha) {

    $alpha = strrev($alpha);

    $decoded = 0;
    $multi   = 1;
    $c       = $this->key; // optymalizacja
    $count   = $this->count; // optymalizacja
    $len     = strlen($alpha);
    for ( $i=0 ; $i<$len ; $i++ ) {
      $decoded += $multi * strpos($c, $alpha[$i]);
      $multi   *= $count;
    }
    return $decoded;
  }
  public static function encodeStatic($num, $key = false) {
    $ins = new static($key);
    return $ins->encode($num);
  }
  public static function decodeStatic($alpha, $key = false) {
    $ins = new static($key);
    return $ins->decode($alpha);
  }
}


text:
package no.nordicsemi.puckcentral.services;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import no.nordicsemi.puckcentral.triggers.Trigger;
import no.nordicsemi.puckcentral.utils.UUIDUtils;

public abstract class GattServices {
    public static final UUID CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID
            = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");

    public static final UUID LOCATION_SERVICE_UUID = UUIDUtils.stringToUUID("bftj location   ");
    public static final UUID IR_SERVICE_UUID =  UUIDUtils.stringToUUID("bftj ir         ");
    public static final UUID CUBE_SERVICE_UUID = UUIDUtils.stringToUUID("bftj cube       ");
    public static final UUID DISPLAY_SERVICE_UUID = UUIDUtils.stringToUUID("bftj display    ");

    public static final UUID CUBE_CHARACTERISTIC_DIRECTION_UUID
            = UUIDUtils.stringToUUID("bftj cube dirctn");

    public static final String[] LOCATION_TRIGGERS = new String[] {
            Trigger.TRIGGER_ENTER_ZONE,
            Trigger.TRIGGER_LEAVE_ZONE
    };

    public static final String[] CUBE_TRIGGERS = new String[] {
            Trigger.TRIGGER_ROTATE_CUBE_UP,
            Trigger.TRIGGER_ROTATE_CUBE_DOWN,
            Trigger.TRIGGER_ROTATE_CUBE_LEFT,
            Trigger.TRIGGER_ROTATE_CUBE_RIGHT,
            Trigger.TRIGGER_ROTATE_CUBE_FRONT,
            Trigger.TRIGGER_ROTATE_CUBE_BACK
    };

    public static Map<UUID, String[]> mServicesToTriggers;

    static {
        mServicesToTriggers = new HashMap<>();
        mServicesToTriggers.put(LOCATION_SERVICE_UUID, LOCATION_TRIGGERS);
        mServicesToTriggers.put(IR_SERVICE_UUID, LOCATION_TRIGGERS);
        mServicesToTriggers.put(CUBE_SERVICE_UUID, CUBE_TRIGGERS);
    }

    public static String[] getTriggersForServiceUUID(UUID serviceUUID) {
        if (mServicesToTriggers.containsKey(serviceUUID)) {
            return mServicesToTriggers.get(serviceUUID);
        }
        return new String[0];
    }

    public static String[] getTriggersForServiceUUIDs(ArrayList<UUID> serviceUUIDs) {
        Set<String> triggers = new HashSet<>();
        for (UUID serviceUUID : serviceUUIDs) {
            triggers.addAll(Arrays.asList(getTriggersForServiceUUID(serviceUUID)));
        }
        return triggers.toArray(new String[triggers.size()]);
    }
}


text:
class Notification < ActiveRecord::Base

  attr_accessible :from, :notify

  belongs_to :user
  belongs_to :from, :class_name => 'User', :foreign_key => 'from_id'

  attr_accessible :user, :notify

  acts_as_api

  api_accessible :angular do |t|
    t.add :id
    t.add :notify
    t.add :created_at
    t.add :from, :template => :user
  end
end


text:
% | ————————————————————————————————————————————————————————————————————————————
% | # 1 - xreverse
% |
% | ## References
% | http://learnprolognow.org/lpnpage.php?pagetype=html&pageid=lpn-htmlse25
% |
% | ## Notes
% | Common pattern used in solution, detailed comments included to
% | demonstrate thorough understanding as per academic integrity.
% | ————————————————————————————————————————————————————————————————————————————

% Use accumulator pattern, acummulating the solution's elements into empty list.
xreverse(L,R):- xreverseAcc(L,[],R).

% Deconstruct the given list into head and tail, then recursively take the head
% of each successive tail as the head of the provided accumulator list.
xreverseAcc([H|T],A,R):- xreverseAcc(T,[H|A],R).

% Base case is true if accumulated solution list (A) matches reversed list (R).
% If R is not provided, this will set the value of R to A so as to return R = A.
xreverseAcc([],A,A).


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Lorem ipsum dolor
sit amet, consectetur
adipiscing elit, sed
do eiusmod tempor
 incididunt ut
 labore et dolore
 magna aliqua.

Ut enim ad minim
veniam, quis nostrud
exercitation
ullamco laboris

        nisi ut aliquip ex ea
commodo consequat.
Duis aute irure
dolor in reprehenderit
in voluptate velit
 esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

</no-start-tag>


text:
package netdb.software.benchmark.remote.vanilladb;

import netdb.software.benchmark.remote.SutResultSet;

import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;
import org.vanilladb.core.sql.Schema;

public class VanillaDbResultSet implements SutResultSet {
	private Record[] recs;
	private Schema sch;

	public VanillaDbResultSet(SpResultSet result) {
		recs = result.getRecords();
		sch = result.getSchema();
	}

	public boolean isCommitted() {
		if (!sch.hasField("status"))
			throw new RuntimeException("result set not completed");
		String status = (String) recs[0].getVal("status").asJavaVal();
		return status.equals("committed");
	}

	public String outputMsg() {
		return recs[0].toString();
	}
}


text:
package net.ripe.db.whois.query;

import net.ripe.db.whois.common.IntegrationTest;
import net.ripe.db.whois.common.domain.IpRanges;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.common.support.TelnetWhoisClient;
import net.ripe.db.whois.query.support.AbstractQueryIntegrationTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;

// TODO: [AH] this should be in whois-query; however, crowdserverdummy is tied to whois-api because of jetty references
@Category(IntegrationTest.class)
@ContextConfiguration(locations = {"classpath:applicationContext-api-test.xml"})
public class InverseQueryTestIntegration extends AbstractQueryIntegrationTest {

    private static final RpslObject PAULETH_PALTHEN = RpslObject.parse("" +
            "person:    Pauleth Palthen\n" +
            "address:   Singel 258\n" +
            "phone:     +31-1234567890\n" +
            "e-mail:    noreply@ripe.net\n" +
            "mnt-by:    OWNER-MNT\n" +
            "nic-hdl:   PP1-TEST\n" +
            "remarks:   remark\n" +
            "source:    TEST\n");

    private static final RpslObject OWNER_MNT = RpslObject.parse("" +
            "mntner:      OWNER-MNT\n" +
            "descr:       Owner Maintainer\n" +
            "admin-c:     PP1-TEST\n" +
            "upd-to:      noreply@ripe.net\n" +
            "auth:        MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" +
            "auth:        SSO person@net.net\n" +
            "auth:        PGPKEY-A8D16B70\n" +
            "mnt-by:      OWNER-MNT\n" +
            "source:      TEST");

    private static final RpslObject KEYCERT = RpslObject.parse(
            "key-cert:       PGPKEY-A8D16B70\n" +
            "method:         PGP\n" +
            "owner:          Test Person5 <noreply5@ripe.net>\n" +
            "fingerpr:       D079 99F1 92D5 41B6 E7BC  6578 9175 DB8D A8D1 6B70\n" +
            "certif:         -----BEGIN PGP PUBLIC KEY BLOCK-----\n" +
            "certif:         Version: GnuPG/MacGPG2 v2.0.18 (Darwin)\n" +
            "certif:         Comment: GPGTools - http://gpgtools.org\n" +
            "certif:\n" +
            "certif:         mI0EUXD+mAEEAKbIL2qj82+7FXCFJntqY50bdNI4NrhrMfGiBMpwmuuFscvI+iT7\n" +
            "certif:         /9AcLaAefKrKCqrM/MYLOx6b6UnIyBFqu/JVdl4aAtUpEUc4YV6jjvKa/29lAwi4\n" +
            "certif:         /gepCwBFL1b5hV7pxnM13ZOODrf10FMjq4Y0EXP4CFVf0wi0ryqIftatABEBAAG0\n" +
            "certif:         IFRlc3QgUGVyc29uNSA8bm9yZXBseTVAcmlwZS5uZXQ+iLkEEwECACMFAlFw/pgC\n" +
            "certif:         GwMHCwkIBwMCAQYVCAIJCgsEFgIDAQIeAQIXgAAKCRCRdduNqNFrcDArBACPPxu+\n" +
            "certif:         mdBqhEysSeQR1DrL02X4mwR3kkCElva4Yx91/TaZf0NC/Xa3Zr4mUKQgNW+Bp3j8\n" +
            "certif:         QN05jY4nqVYjkiFW6U9TMnGyFcwVzQdEJzgvjeZsuANd1RxdL8E4N0l4J+lYf5WN\n" +
            "certif:         5wfDgHE1aRm1QC5h1bOqThZ4/hFmddffL3TI77iNBFFw/pgBBACsA5ZBIZ7Ax2oA\n" +
            "certif:         XGPHooWP6K5d9Q5MDDyoyI6eyhVGhRFY0W40/9EdCCnzv3NNC5rnkXNrUpct3WVl\n" +
            "certif:         NpZybSVUqMkuOyAwgxqfe8k/EPpi6IfRUZeft/Hfpby7ycVUSWPxb4AmzNvR4lUp\n" +
            "certif:         wLfAJSETsrffOCo1hhGgT7Qg2SMLswARAQABiJ8EGAECAAkFAlFw/pgCGwwACgkQ\n" +
            "certif:         kXXbjajRa3AecwP7BbunGw89R2u8C+sw+chO3gyWr+klccxZ2g2RiGOMKWEVQXUM\n" +
            "certif:         Ru0OLzbKfGajl1RO4oo6aTLQAKwi7RoQO31mf699Nadt8nLnI3anVT3tcdI/HXNM\n" +
            "certif:         0qCy3r2tct/P63LCn+uIT4WvBjCp3gxPok3FdJf6iRon/J5lMNe3M3VjJoM=\n" +
            "certif:         =DgsR\n" +
            "certif:         -----END PGP PUBLIC KEY BLOCK-----\n" +
            "mnt-by:         OWNER-MNT\n" +
            "source:         TEST");

    @Autowired IpRanges ipRanges;

    @Before
    public void startupWhoisServer() throws Exception {
        databaseHelper.addObjects(PAULETH_PALTHEN, KEYCERT, OWNER_MNT);

        queryServer.start();
    }

    @After
    public void shutdownWhoisServer() {
        queryServer.stop(true);
    }

    @Test
    public void inverse_auth_pgpkey_case_sensitive() throws Exception {
        assertThat(query("-B -i auth PgPKeY-A8D16B70"), containsString("OWNER-MNT"));
    }

    @Test
    public void inverse_upd_to_case_sensitive() throws Exception {
        assertThat(query("-B -i upd-to noreply@riPe.net"), containsString("OWNER-MNT"));
    }

    @Test
    public void inverse_auth_pgpkey() throws Exception {
        assertThat(query("-B -i auth PGPKEY-A8D16B70"), containsString("OWNER-MNT"));
    }

    @Test
    public void inverse_auth_nonexistant_pgpkey() {
        assertThat(query("-B -i auth PGPKEY-12345678"),
                containsString("%ERROR:101: no entries found"));
    }

    @Test
    public void inverse_auth_sso_with_email() {
        assertThat(query("-B -i auth SSO person@net.net"),
                containsString("% Inverse search on 'auth' attribute is limited to 'key-cert' objects only"));
    }

    @Test
    public void inverse_auth_sso_with_uuid_untrusted() {
        ipRanges.setTrusted("::0");

        assertThat(query("-B -i auth SSO 906635c2-0405-429a-800b-0602bd716124"),
                containsString("% Inverse search on 'auth' attribute is limited to 'key-cert' objects only"));
    }

    @Test
    public void inverse_auth_sso_with_uuid_trusted() {
        ipRanges.setTrusted("127/8", "::1");

        final String response = query("-B -i auth SSO 906635c2-0405-429a-800b-0602bd716124");

        assertThat(response, containsString("mntner:         OWNER-MNT"));
        assertThat(response, containsString("auth:           SSO # Filtered"));
    }

    @Test
    public void inverse_auth_md5() {
        assertThat(query("-B -i auth MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/"),
                containsString("% Inverse search on 'auth' attribute is limited to 'key-cert' objects only"));
    }

    @Test
    public void inverse_auth_unknown_md5() {
        assertThat(query("-B -i auth MD5-PW $1$deadbeef$Si7YudNf4rUGmR71n/cqk/"),
                containsString("% Inverse search on 'auth' attribute is limited to 'key-cert' objects only"));
    }

    @Test
    public void inverse_invalid_nic_hdl() {
        databaseHelper.addObject(
                "person:    Henry Mitchell\n" +
                "nic-hdl:   TEST-HM3\n" +
                "source:    TEST");
        databaseHelper.addObject(
                "mntner:    Another Maintainer\n" +
                "tech-c:    TEST-HM3\n" +
                "source:    TEST");

        assertThat(query("-i tech-c TEST-HM3"), containsString("Another Maintainer"));
    }

    @Test
    public void inverse_referral_by_is_invalid() {
        assertThat(query("-i referral-by TEST"), containsString("\"referral-by\" is not a known attribute."));
    }

    private String query(final String query) {
        return TelnetWhoisClient.queryLocalhost(QueryServer.port, query);
    }
}


text:
find_path(LIBFMT_INCLUDE_DIR fmt/core.h)
mark_as_advanced(LIBFMT_INCLUDE_DIR)

find_library(LIBFMT_LIBRARY NAMES fmt fmtd)
mark_as_advanced(LIBFMT_LIBRARY)

include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(
    LIBFMT
    DEFAULT_MSG
    LIBFMT_LIBRARY LIBFMT_INCLUDE_DIR)

if(LIBFMT_FOUND)
    set(LIBFMT_LIBRARIES ${LIBFMT_LIBRARY})
    set(LIBFMT_INCLUDE_DIRS ${LIBFMT_INCLUDE_DIR})
    message(STATUS "Found {fmt}: ${LIBFMT_LIBRARY}")
    add_library(fmt::fmt UNKNOWN IMPORTED)
    set_target_properties(
      fmt::fmt PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${LIBFMT_INCLUDE_DIR}"
    )
    set_target_properties(
      fmt::fmt PROPERTIES
      IMPORTED_LINK_INTERFACE_LANGUAGES "C"
      IMPORTED_LOCATION "${LIBFMT_LIBRARY}"
    )
endif()


text:
package com.sdsxer.mmdiary.tasks.domain.filter;

import com.sdsxer.mmdiary.tasks.domain.model.Task;
import java.util.List;

public interface TaskFilter {
    List<Task> filter(List<Task> tasks);
}


text:
app.directive('accountView', function () {
    return{
        restrict: 'E',
        templateUrl: 'app/components/account/accountView.html'
    }
});


text:
QByteArray fingerprint();

PwStore::PwStore() {
    m_key = fingerprint().left(KEY_SIZE);
}

QByteArray PwStore::encrypt(QString s) {
    std::string ciphertext;

    // Random IV
    QByteArray iv;
    iv.resize(IV_SIZE);
    CryptoPP::OS_GenerateRandomBlock(false, (byte*)iv.data(), IV_SIZE);

    CryptoPP::GCM<CryptoPP::AES>::Encryption enc;
    enc.SetKeyWithIV((byte*)m_key.data(), m_key.length(), (byte*)iv.data(), iv.length());

    CryptoPP::AuthenticatedEncryptionFilter aef( enc,
        new CryptoPP::StringSink( ciphertext )
    );

    QByteArray sBytes(s.toUtf8());

    aef.Put((byte*)sBytes.data(), sBytes.size());
    aef.MessageEnd();

    return iv + QByteArray(ciphertext.data(), ciphertext.length());
}

QString PwStore::decrypt(QByteArray s) {
    QByteArray ciphertext, iv;
    iv = s.left(IV_SIZE);
    ciphertext = s.mid(IV_SIZE);

    std::string plaintext;

    CryptoPP::GCM<CryptoPP::AES>::Decryption dec;
    dec.SetKeyWithIV((byte*)m_key.data(), m_key.length(), (byte*)iv.data(), iv.length());

    try {
        CryptoPP::AuthenticatedDecryptionFilter adf( dec,
            new CryptoPP::StringSink( plaintext )
        );

        adf.Put((byte*)ciphertext.data(), ciphertext.size());
        adf.MessageEnd();
    }
    catch (CryptoPP::HashVerificationFilter::HashVerificationFailed) {
        return QString();
    }

    QByteArray plaintextBytes(QByteArray::fromStdString(plaintext));

    return QString::fromUtf8(plaintextBytes);
}

void secureStringClear(QString &s) {
    int l = s.length();
    for (int i=0; i<l; i++) {
        s[i] = '\0';
    }
    s.clear();
}

QByteArray getMacs() {
    foreach(QNetworkInterface netInterface, QNetworkInterface::allInterfaces()) {
        if (netInterface.flags() & QNetworkInterface::IsLoopBack) {
            continue;
        }
        return netInterface.hardwareAddress().toLatin1();
    }
    return QByteArray();
}

QByteArray getMachineName() {
   static wchar_t computerName[1024];
   DWORD size = 1024;
   GetComputerName( computerName, &size );
   return QString::fromWCharArray(computerName).toLatin1();
}

QByteArray getMachineGUID() {
    QSettings settings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography", QSettings::NativeFormat);
    return settings.value("MachineGuid", "0").toByteArray();
}

QByteArray getVolumeHash() {
   DWORD serialNum = 0;

   GetVolumeInformation( L"c:\\", nullptr, 0, &serialNum, nullptr, nullptr, nullptr, 0 );

   return QByteArray((char*)&serialNum, 4);
}

QByteArray fingerprint() {
    const int rounds = 1000;

    QByteArray buffer;
    buffer += getVolumeHash();
    buffer += getMachineGUID();
    buffer += getMachineName();
    buffer += getMacs();

    for (int i=0; i<rounds; i++) {
        buffer = QCryptographicHash::hash(buffer, QCryptographicHash::Sha1);
    }

    return buffer;
}

#endif


text:
package com.dangdang.ddframe.job.util.config;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import lombok.Getter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 分片项工具类.
 *
 * @author zhangliang
 */
@Getter
public final class ShardingItems {

    private static final String DELIMITER = ",";

    /**
     * 根据分片项字符串获取分片项列表.
     *
     * @param itemsString 分片项字符串
     * @return 分片项列表
     */
    public static List<Integer> toItemList(final String itemsString) {
        if (Strings.isNullOrEmpty(itemsString)) {
            return Collections.emptyList();
        }
        String[] items = itemsString.split(DELIMITER);
        List<Integer> result = new ArrayList<>(items.length);
        for (String each : items) {
            int item = Integer.parseInt(each);
            if (!result.contains(item)) {
                result.add(item);
            }
        }
        return result;
    }

    /**
     * 根据分片项列表获取分片项字符串.
     *
     * @param items 分片项列表
     * @return 分片项字符串
     */
    public static String toItemsString(final List<Integer> items) {
        return items.isEmpty() ? "" : Joiner.on(DELIMITER).join(items);
    }
}


text:
local tabs = {
  module = "index",
  view = "show_tab"
}

local selector = Area:new_selector()
  :reset_fields()
  :add_field("area.id", nil, { "grouped" })
  :add_field("area.name", nil, { "grouped" })
  :add_field("membership.member_id NOTNULL", "is_member", { "grouped" })
  :add_field("count(issue.id)", "issues_to_vote_count")
  :add_field("count(interest.member_id)", "interested_issues_to_vote_count")
  :add_field("count(interest.member_id NOTNULL OR interest.member_id NOTNULL)", "issues_to_vote_count_sum")
  :join("issue", nil, "issue.area_id = area.id AND issue.fully_frozen NOTNULL AND issue.closed ISNULL")
  :left_join("direct_voter", nil, { "direct_voter.issue_id = issue.id AND direct_voter.member_id = ?", app.session.member.id })
  :add_where{ "direct_voter.member_id ISNULL" }
  :left_join("interest", nil, { "interest.issue_id = issue.id AND interest.member_id = ?", app.session.member.id })
  :left_join("membership", nil, { "membership.area_id = area.id AND membership.member_id = ? ", app.session.member.id })

local not_voted_areas = {}
local issues_to_vote_count = 0
for i, area in ipairs(selector:exec()) do
  if area.is_member or area.interested_issues_to_vote_count > 0 then
    not_voted_areas[#not_voted_areas+1] = area
  end
  issues_to_vote_count = issues_to_vote_count + area.issues_to_vote_count_sum
end

tabs[#tabs+1] = {
  name = "not_voted_issues",
  label = _"Not voted issues" .. " (" .. tostring(issues_to_vote_count) .. ")",
  icon = { static = "icons/16/email_open.png" },
  module = "index",
  view = "_not_voted_issues",
  params = {
    areas = not_voted_areas
  }
}

local initiator_invites_selector = Initiative:new_selector()
  :join("issue", "_issue_state", "_issue_state.id = initiative.issue_id")
  :join("initiator", nil, { "initiator.initiative_id = initiative.id AND initiator.member_id = ? AND initiator.accepted ISNULL", app.session.member.id })
  :add_where("_issue_state.closed ISNULL AND _issue_state.half_frozen ISNULL")

tabs[#tabs+1] = {
  name = "initiator_invites",
  label = _"Initiator invites" .. " (" .. tostring(initiator_invites_selector:count()) .. ")",
  icon = { static = "icons/16/email_open.png" },
  module = "index",
  view = "_initiator_invites",
  params = {
    initiatives_selector = initiator_invites_selector
  }
}

local updated_drafts_selector = Initiative:new_selector()
  :join("issue", "_issue_state", "_issue_state.id = initiative.issue_id AND _issue_state.closed ISNULL AND _issue_state.fully_frozen ISNULL")
  :join("current_draft", "_current_draft", "_current_draft.initiative_id = initiative.id")
  :join("supporter", "supporter", { "supporter.member_id = ? AND supporter.initiative_id = initiative.id AND supporter.draft_id < _current_draft.id", app.session.member_id })

tabs[#tabs+1] = {
  name = "updated_drafts",
  label = _"Updated drafts" .. " (" .. tostring(updated_drafts_selector:count()) .. ")",
  icon = { static = "icons/16/email_open.png" },
  module = "index",
  view = "_updated_drafts",
  params = {
    initiatives_selector = updated_drafts_selector
  }
}

ui.tabs(tabs)


text:
package com.redheap.selenium.pages;

import com.redheap.selenium.component.AdfInputNumberSpinbox;
import com.redheap.selenium.component.AdfTextEditor;
import com.redheap.selenium.page.Page;

import org.openqa.selenium.WebDriver;

public class TextEditorDemoPage extends Page {

    private static final String TEXTEDITOR = "dmoTpl:idRichTextEditor";

    public TextEditorDemoPage(WebDriver webDriver) {
        super(webDriver);
    }

    @Override
    protected String getExpectedTitle() {
        return "richTextEditor Demo";
    }

    public AdfTextEditor findTextEditor() {
        return findAdfComponent(TEXTEDITOR);
    }

}


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

    <TextView
            android:id="@+id/title"
            android:textSize="@dimen/text_size_medium"
            android:textStyle="bold"
            android:textColor="@color/darkblue"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:paddingBottom="10dip"
            android:paddingTop="10dip"
            android:text="Titre"
            android:textAppearance="?android:attr/textAppearanceLarge"/>

    <include layout="@layout/colorstrip"/>

    <ListView
            android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:cacheColorHint="#00000000"/>

    <WebView
            android:id="@android:id/empty"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_gravity="center"
            android:gravity="center"
            android:layout_weight="1"
            android:padding="5dip"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/darkblue"/>

</LinearLayout>


text:
var Q = require('q'),
    redis = require('redis'),
    _ = require('lodash'),
    moment = require('moment');

module.exports = function(request) {
    var _this = this;

    this.log.debug("Handling heartbeat for agent %s.payload=%s", request.id, typeof request.payload !== 'undefined');
    this.log.trace("heartbeat payload is ",request);
    var defer = Q.defer();

    Q.nextTick(_.bind(function() {
        this.db.hset(request.id, "lastHeartbeatTs", moment().utc().unix());
        this.db.hget(request.id, "status", function(err, state) {
            if(err) defer.reject(err);
            else {
                _this.log.trace(arguments, "Agent  %s state", request.id);

                if(state !== 'CONNECTED') {
                    _this.log.info("Agent %s has been detected has connected", request.id);
                    _this.db.hset(request.id, 'status', 'CONNECTED');

                    _this.emit('agent-connected', {
                        id: request.id,
                        ts: moment().utc().unix(),
                        agent: request,
                        meta: request.meta
                    });

                }
                else {
                    _this.log.debug("Agent %s was already connected.", request.id);

                    // Check if we have a watchdog... we may not have one if we were the one being down
                    _this.db.hget(request.id, 'heartbeat-interval', function(err, interval) {
                        _this.log.trace("Detected heartbeat interval: %s", interval);

                        if(!_this.hasWatchDog(request.id)) {

                            _this.ensureWatchDog({
                                id:request.id,
                                interval:interval || 30
                            });

                            // Force the execution of a configure command on the agent
                            _this.executeOnAgent(request.id, 'configure', {restart: true});
                        }

                    });
                }

                // Do we have a payload, ask for advise on how to handle this extra infos
                if(request.payload) {
                    _this.log.debug("A payload was supplied by agent %s, asking for help from our host", request.id);
                    _this.emit('heartbeat-payload', request, request.payload);
                }

                // Update our status report data
                _this.statusReportData.agents[request.id] = {
                    id: request.id,
                    ts: moment().format("LLL")
                };

                defer.resolve();
            }

        });

    }, this));

    return defer.promise;
};


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">
        <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
		<META HTTP-EQUIV="Expires" CONTENT="-0">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link href="css/smoothness/jquery-ui-1.10.2.custom.css" rel="stylesheet">

                  <map name="Map2">
                    <area shape="rect" coords="171,72,198,103" href="javascript:search('search', false);" alt="Search for tips...">
                  </map>
				<input id="search-box-txt" type="input" value="Search for tips..."/>

Filter by:
                	Plants
                    Vegetables
                    Lawn
                    Trees
                    Garden Furniture

          <map name="Map">
            <area shape="rect" coords="345,0,430,30" href="#" onClick="closeX()">
          </map>

                  <map name="Map3">
                    <area shape="rect" coords="200,9,278,46" href="http://www.homebase.co.uk/webapp/wcs/stores/servlet/HomebaseStaticPageSecondLevel?langId=110&storeId=10151&includeName=HBCustomerServiceArticles/privacypolicy.htm" target="_blank" alt="Privacy Policy">
                    <area shape="rect" coords="289,9,359,47" href="javascript:showTerms();" target="_self" alt="Terms of Use">
                    <area shape="rect" coords="619,9,704,49" href="http://www.alzheimers.co.uk" target="_blank" alt="Alzheimers.co.uk">
                    <area shape="rect" coords="716,11,797,50" href="http://www.homebase.co.uk" target="_blank" alt="Homebase.co.uk">
                  </map>

            x
            Terms and Conditions

(Consumer Prize share your gardening tips and memories)

Entrants to the competition are bound by these terms and conditions.

No purchase necessary.

The competition is operated by Homebase Limited, 489-499 Avebury Boulevard, Saxon Gate West, Milton Keynes MK9 2NW.

Entrants to the competition must be resident in the UK or Ireland.

1st Prize consists of £4,000 Homebase voucher plus the first 1000 entries  received a free packet of seeds – selected at random from the grow your own range.

Plus every entry we will donate £1 to the Alzheimer's society* (capped at £3000)

There is no cash alternative for the prize.

To enter the competition register/log in to http://www.facebook.com/homebase/app_310179562389446 and upload a picture with your favourite gardening memory or gardening top tip.

The winner will be notified via email 28 working days of the closing date. If we do not hear from you within five working days of sending out the Notification, your prize will be forfeited and another winner will be selected and contacted until the prize has been issued.

The following persons are not eligible to enter the competition: (i) employees of any business involved or associated with the competition (including Home Retail Group) and any other agent representative of Home Retail Group) and (ii) any such person's family or household members.

By entering the competition, you hereby warrant and confirm that you are sole owner of the copyright in the Entry and that you have not infringed copyright or intellectual property rights in creating and submitting the Entry to this competition. You also warrant and confirm that Home Retail Group are authorised to use the entry for the purposes stated in the terms and conditions.

Any information submitted by you must be personal to and relate specifically to you. You warrant and confirm that the information which you submit and/ or distribute will not infringe the intellectual property, privacy, proprietary or any other rights of any third party, and will not contain anything which is libellous, defamatory, obscene, indecent, harassing or threatening. To the fullest extent permitted by the law, Home Retail Group Ltd. does not accept any responsibility for any claims by any third party that arise as a result of submission of information or the Entry for the purposes of this competition.

By entering the competition, you grant Home Retail Group Ltd. the right to publish and exhibit your Entry. You will retain the copyright in your Entry, however in consideration of their providing the competition, you grant a worldwide, irrevocable, perpetual licence to Home Retail Group Ltd. (including publishers authorised by Home Retail Group) to use the Entry for marketing and advertising purposes including publishing and exhibiting your Entry, on websites or in any other on or offline media. No fees will be payable for any of the above uses. You also agree to take part in post-competition publicity.

The closing date for this competition is 26th April 2013

No responsibility is accepted by Home Retail Group Ltd. or its agent for entries incompletely or incorrectly completed or not received for whatever reason. Neither Home Retail Group Ltd. nor any appointed agent will accept responsibility for any technical or other error that might arise whilst submitting an entry, nor for the failure to store any image.

Any personal data relating to entrants will be used solely in accordance with current UK data protection legislation and will not be disclosed to a third party outside of Home Retail Group Ltd. without the individual's prior consent.

Home Retail Group Ltd. reserves the right to verify the eligibility of all entrants.

In the event of any dispute regarding the competition, the decision of Home Retail Group Ltd.is final and no correspondence or discussion shall be entered into. Home Retail Group Ltd. reserves the right to disqualify any entrant if it has reasonable grounds to believe the entrant has breached any of these terms and conditions.

Home Retail Group Ltd. may withdraw this competition where necessary if circumstances arise that are beyond its control at any time without notice.

English law governs these terms and conditions and the English courts will have exclusive jurisdiction over any dispute arising from or in relation to these terms and conditions.

The promoter is Homebase Limited, 489-499 Avebury Boulevard, Saxon Gate West, Milton Keynes MK9 2NW


text:
'use strict';
/*global $: false, angular: false */

var app = angular.module('RoutesDemo', ['ngRoute']);

app.config(function ($routeProvider) {
  $routeProvider.
    when('/baseball', {
      controller: 'BaseballCtrl',
      templateUrl: 'partials/baseball.html',
      view: 'center'
    }).
    when('/hockey/:conference?', {
      controller: 'HockeyCtrl',
      templateUrl: 'partials/hockey.html',
      view: 'center'
    }).
    otherwise({
      redirectTo: '/baseball'
    });
});

app.controller('DemoCtrl', function ($scope, $location) {
  $scope.showBaseball = function () {
    $location.path('/baseball');
  };

  $scope.showHockey = function () {
    $location.path('/hockey');
  };
});


text:
import { takeEvery } from 'redux-saga';
import { put } from 'redux-saga/effects';
import zip from 'array-zip';
import { ADD_GUESS } from '../reducers/restore.js';
import { setScore } from '../reducers/score.js';

const calculateScoreHelper = (cards, guesses) => {
    return zip(guesses, cards)
        .reduce((collector, item) => {
            const [correctValue, guess] = item;
            if (correctValue === guess) {
                return [...collector, collector[collector.length - 1] + 1];
            } else {
                return [...collector, 0];
            }
        }, [0])
        .reduce((sum, i) => sum + i, 0);    // 0 is added to make reduce work with empty initial array
};

function* calculateScore(getState) {
    const cards = getState().remember.list;
    const guesses = getState().restore.list;

    yield put(setScore(calculateScoreHelper(cards, guesses)));
}

function *watchAddGuessToCalculateScore(getState) {
    yield* takeEvery(ADD_GUESS, calculateScore, getState);
}

export default watchAddGuessToCalculateScore;


text:
This is a simple 2-page application that demonstrates the basic usage of [React Native Router Flux](https://github.com/aksonov/react-native-router-flux) as a navigation tool. It is extremely easy to understand. This step-by-step tutorial will take you through the basic concepts. We are using [NativeBase](https://nativebase.io/) as the UI library to design our pages.

# Find full code [here](https://github.com/GeekyAnts/native-base-example-rnrf)

![RNRF Gif](https://docs.nativebase.io/docs/assets/RNRFGif.gif)

## Aim
We are creating a 2-page application with a button on each page that takes us to the other page onPress.

## Installation

**Note:** If you encounter an issue with [React Native Router Flux](https://github.com/aksonov/react-native-router-flux) during building your project, it might be due to issue with latest versions of [React Native](https://github.com/facebook/react-native). Check out [this issue](https://github.com/aksonov/react-native-router-flux/issues/1761). You might have to bump down the versions of [React Native](https://github.com/facebook/react-native) and React

1. **SetUp React Native Project**
 SetUp a React Native project. Refer [this](https://facebook.github.io/react-native/docs/getting-started.html) for more information about setting up a React Native project.
2. **Installing Libraries**
With a React Native project SetUp, We can now install all required Libraries as follows.

a. **React Native Router Flux**

npm install react-native-router-flux --save

b. **NativeBase**

npm install native-base@2 --save

c. **Configure dependencies**

react-native link

By the end of Installation, your package.json file should look something like this.

![RNRFExample PackageJson](https://docs.nativebase.io/docs/assets/RNRFPackage.png)

## Lets Play

With our basic project setup we can now start building our App.

Make a folder at the project root by the name of src. Inside this folder we make 3 files.

### App.js

This file is where our app lives. This is where we setup our navigation library [React Native Router Flux](https://github.com/aksonov/react-native-router-flux).

Some components from [React Native Router Flux](https://github.com/aksonov/react-native-router-flux) are worth understanding.
1. Router Component : This component is the parent component inside which we pass all other Page components that are part of our Navigation objective.

2. Scene Component : We pass our Page components to Scene through component prop as shown below.

The key prop is used to reference our component when we wish to switch a Scene.

3. We are going to be optimistic and assume that our Page components are made. Hence we import out page components and pass them to Scene.

**Code**

import React, { Component } from 'react';
import { Router, Scene } from 'react-native-router-flux';
import PageOne from './pageOne';
import PageTwo from './pageTwo';
export default class App extends Component {
  render() {
    return (
      <Router hideNavBar= "true">
        <Scene key="root">
          <Scene key="pageOne" component={PageOne} title="PageOne" initial={true} />
          <Scene key="pageTwo" component={PageTwo} title="PageTwo" />
        </Scene>
      </Router>
    )
  }
}

### PageOne.js

This page will simply have one Button to take us to next page.

We will fire an Action onPress of this Button.

**Note:** We will use [RNRF](https://github.com/aksonov/react-native-router-flux) to navigate between screens, hence in the code below, we import Actions from [RNRF](https://github.com/aksonov/react-native-router-flux) and we have added Actions.pageTwo() as an onPress event on the button which will take us to the PageTwo Screen.

The general syntax to navigate between screens in [RNRF](https://github.com/aksonov/react-native-router-flux) goes like :-

Actions.ACTION_NAME(PARAMS)

We have already declared ACTION_NAME in the key prop of Scene component back in out App.js file

**Code**

import React, { Component } from 'react';
import { Container, Content, Text, Card, Header, Body, Button, Title, CardItem } from 'native-base';
import { Actions } from 'react-native-router-flux';
export default class pageOne extends Component {
  render(){
    return(
      <Container>
        <Header>
          <Body>
            <Title>PageOne</Title>
          </Body>
        </Header>
        <Content padder>
          <Card>
            <CardItem>
              <Body>
                <Text>
                  This is Page One, Press button to goto page two
                </Text>
              </Body>
            </CardItem>
          </Card>
          <Button dark bordered style = {{alignSelf: 'center', margin: 30}}
            onPress= {() => {Actions.pageTwo(); }}>
            <Text>Goto Page 2</Text>
          </Button>
         </Content>
      </Container>
    );
  }
}

### PageTwo.js
This page will simply have one Button to take us to the previous page.

We will fire an Action onPress of this Button.

We will use Actions.pop() to return to previous page.

**Code**

import React, { Component } from 'react';
import { Container, Content, Text, Card, Header, Body, Button, Title, CardItem } from 'native-base';
import { Actions } from 'react-native-router-flux';
export default class pageTwo extends Component {
  render(){
    return(
      <Container>
        <Header>
          <Body>
            <Title>PageTwo</Title>
          </Body>
        </Header>
        <Content padder>
          <Card>
            <CardItem>
              <Body>
                <Text>
                  This is Page One, Press button to goto page two
                </Text>
              </Body>
            </CardItem>
          </Card>
          <Button dark bordered
            onPress= {() => {Actions.pop(); }}>
            <Text>Goto Page 1</Text>
         </Button>
        </Content>
      </Container>
    );
  }
}

### What Next?
Well, we are pretty much done. Next we simply import our App component in our index.js file. The file and folder structure will look something like this.

**Code**

import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import App from './src/App.js';
export default class RnrfExample extends Component {
  render() {
    return (
      <App />
    );
  }
}
AppRegistry.registerComponent('RnrfExample', () => RnrfExample);

![RNRFExample Overall](https://docs.nativebase.io/docs/assets/RNRFOverall.png)


text:
include ../compilerSettings_clang3.5.mk

SOURCES=IgnoreForLambdaChecks.cpp
EXECUTABLE=IgnoreForLambdaChecks

include ../makeCommon.mk


text:
```
irb(main):001:0> 24*365
=> 8760

irb(main):003:0> 60*24*365*10
=> 5256000

```

[simple-string](https://github.com/Kevin-Fowle/phase-0/blob/master/week-4/simple-string.rb)

[defining-variables](https://github.com/Kevin-Fowle/phase-0/blob/master/week-4/defining-variables.rb)

[basic-math](https://github.com/Kevin-Fowle/phase-0/blob/master/week-4/basic-math.rb)

puts is a ruby command that when used will print the text on the next line. Print will put the text on the same line. Puts moves it the next line down.

An integer is simply just a number. A float is a more precise number when dealing with decimal places.

Integer devision is dividing two whole numbers like 4/2. Which will output 2. 4.0/2 will equal 2.0. The second example is float devision. It gives a more precise number on your devision. It often will come into play when dealing with decimals.

Strings are pieces of text in ruby. You might need to push some information to the user after they interact with your program. If you were to make a string like "thank you" and then puts that string to the console, the user would be able to read "thank-you".

Local variables allow programmers to save integers or strings to a value. When you need to use the integer or string later on, you can recall the string/integer by calling the variable.

It was a great review of the basics. To be honest, I haven't touched Ruby since the application. It was nice to have a little refresher.


text:
PRG="${0}"

while [ -h "${PRG}" ]; do
  ls=`ls -ld "${PRG}"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "${PRG}"`/"$link"
  fi
done

BASEDIR=`dirname ${PRG}`
BASEDIR=`cd ${BASEDIR}/..;pwd`

source ${BASEDIR}/bin/oozie-sys.sh

# The Java System property 'oozie.http.port' it is not used by Oozie,
# it is used in Tomcat's server.xml configuration file
#
echo "Using   CATALINA_OPTS:       ${CATALINA_OPTS}"

catalina_opts="-Doozie.home.dir=${OOZIE_HOME}";
catalina_opts="${catalina_opts} -Doozie.config.dir=${OOZIE_CONFIG}";
catalina_opts="${catalina_opts} -Doozie.log.dir=${OOZIE_LOG}";
catalina_opts="${catalina_opts} -Doozie.data.dir=${OOZIE_DATA}";

catalina_opts="${catalina_opts} -Doozie.config.file=${OOZIE_CONFIG_FILE}";

catalina_opts="${catalina_opts} -Doozie.log4j.file=${OOZIE_LOG4J_FILE}";
catalina_opts="${catalina_opts} -Doozie.log4j.reload=${OOZIE_LOG4J_RELOAD}";

catalina_opts="${catalina_opts} -Doozie.http.hostname=${OOZIE_HTTP_HOSTNAME}";
catalina_opts="${catalina_opts} -Doozie.http.port=${OOZIE_HTTP_PORT}";
catalina_opts="${catalina_opts} -Doozie.base.url=${OOZIE_BASE_URL}";

echo "Adding to CATALINA_OPTS:     ${catalina_opts}"

export CATALINA_OPTS="${CATALINA_OPTS} ${catalina_opts}"

if [ ! -e "${CATALINA_BASE}/webapps/oozie.war" ]; then
  echo "WARN: Oozie WAR has not been set up at ''${CATALINA_BASE}/webapps'', doing default set up"
  ${BASEDIR}/bin/oozie-setup.sh
  if [ "$?" != "0" ]; then
    exit -1
  fi
fi
echo

${BASEDIR}/oozie-server/bin/catalina.sh run


text:
    <form action="<?php echo base_url("master-biro-jasa-save"); ?>" method="post" enctype="multipart/form-data" parsley-validate novalidate>

Master Birojasa Add

                        Nama Birojasa
                        <input type="text" name="nama_birojasa" parsley-trigger="change" required placeholder="Isi Nama Birojasa" class="form-control">

                        Telepon Birojasa
                        <input type="tel" name="telepon_birojasa" parsley-trigger="change" parsley-type="digits" required placeholder="Isi Telepon Birojasa" class="form-control">

                        Handphone Birojasa
                        <input type="tel" name="handphone_birojasa" parsley-trigger="change" parsley-type="digits" required placeholder="Isi Handphone Birojasa" class="form-control">

                        Alamat Birojasa
                        <textarea name="alamat_birojasa" parsley-trigger="change" required placeholder="Isi Alamat Birojasa" class="form-control"></textarea>

                        PIC Birojasa
                        <input type="text" name="pic_birojasa" parsley-trigger="change" required placeholder="Isi Nama PIC Birojasa" class="form-control">

                        Kontak PIC Birojasa
                        <input type="text" name="pic_kontak_birojasa" parsley-trigger="change"parsley-type="digits" required placeholder="Isi Kontak PIC Birojasa" class="form-control">

                        Emal Birojasa
                        <input type="text" name="email_birojasa" parsley-trigger="change" required placeholder="Isi Kontak PIC Birojasa" class="form-control">

                        Status
                        <select name="status_birojasa" placeholder="Pilih Status" required class="form-control">
                            <option value="1">Aktif</option>
                            <option value="2">Non Aktif</option>
                        </select>

                    <button class="btn btn-primary" type="submit">Submit</button>
                    <a href="<?php echo base_url('master-biro-jasa'); ?>" class="btn btn-default">Cancel

    </form>


text:
package org.cloudfoundry.client.v2.applications;

import org.junit.Test;

public final class ListApplicationsRequestTest {

    @Test
    public void valid() {
        ListApplicationsRequest.builder()
            .build();
    }

}


text:
package org.waveprotocol.wave.client.editor.content.misc;

import org.waveprotocol.wave.model.document.operation.Nindo;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Manages the annotations that are to be applied to content
 * inserted at the user's caret, which may override annotations that cover
 * a range containing the current caret.
 *
 * @author patcoleman@google.com (Pat Coleman)
 */
public class CaretAnnotations {
  // TODO(patcoleman) - optimise to StringMap when testable

  /** Stores the annotations as an optimised mapping of strings to strings. */
  Map<String, String> annotations = new HashMap<String, String>();

  /**
   * Stores something which can assist in finding current styles to be
   * applied on the caret.
   */
  AnnotationResolver resolver = null;

  /** Defines the contract for an annotation resolution strategy. */
  public interface AnnotationResolver {
    /** Retrieves the annotation for a particular key. */
    String getAnnotation(String key);
  }

  /** Retrieves all the annotations for the current caret. */
  public Set<String> getAnnotationKeys() {
    return annotations.keySet();
  }

  /** Retrieves the annotation for a particular key. */
  public String getAnnotation(String key) {
    if (hasAnnotation(key)) {
      return annotations.get(key);
    } else if (resolver != null) {
      return resolver.getAnnotation(key); // delegate to try to work it out
    } else {
      return null; // unknown, so set as unstyled
    }
  }

  /** Annotates the caret with a particular key/value pair. */
  public void setAnnotation(String key, String value) {
    annotations.put(key, value);
  }

  /** Check whether the caret has a particular annotation */
  public boolean hasAnnotation(String key) {
    return annotations.containsKey(key);
  }

  /** Removes an annotation from the caret (note that this is not the same as setting it to null) */
  public void removeAnnotation(String key) {
    annotations.remove(key);
  }

  /** Clears all annotations on the caret. */
  public void clear() {
    annotations.clear();
  }

  /** Attaches a strategy to resolve unknown annotation styles. */
  public void setAnnotationResolver(AnnotationResolver newResolver) {
    resolver = newResolver;
  }

  /**
   * Generate the mutation arguments for the annotations to be applied.
   * @param b The object building the mutation.
   */
  public void buildAnnotationStarts(Nindo.Builder b) {
    // add the annotations to the builder
    for (Entry<String, String> entry : annotations.entrySet()) {
      b.startAnnotation(entry.getKey(), entry.getValue());
    }
  }

  /**
   * Close off the mutation arguments for the annotations to be applied.
   * @param b The object building the mutation.
   * @param clear True iff the annotations are to be cleared afterwards.
   */
  public void buildAnnotationEnds(Nindo.Builder b, boolean clear) {
    // finish all we applied earlier, and possibly clear
    for (String key : annotations.keySet()) {
      b.endAnnotation(key);
    }
    if (clear) {
      clear();
    }
  }

  /**
   * Convenience check to see whether a given key/value annotation has
   * been applied to the caret.
   * @param key Key of the annotation.
   * @param value Value to check if the key has been set to.
   * @return True iff the annotation is set to the value for the current caret.
   */
  public boolean isAnnotated(String key, String value) {
    // compare the two, handling nulls:
    String current = getAnnotation(key);
    return current == null ? value == null : current.equals(value);
  }
}


text:
**NOTE: This module is depreciated since SecurePay has moved from their SOAP XML API to REST**
**Please see the [SecurePay API](https://auspost.com.au/payments/docs/securepay/?javascript#securepay-api-card-payments-rest-api) to communicate with SecurePay**

**The below documentation is provided for backwards compatibility for existing SOAP XML requests which use the old username / password system**

---

Very simple [SecurePay.com.au](http://www.securepay.com.au) API for PHP.

The secure pay service is a reasonably reliable and well documented credit card gateway.

You will require an existing username and password (or a test account) to use this module.

Installation
============
Download this GIT repository and copy into your application directory.

Alternatively, install with [Composer](http://getcomposer.org).

Examples
========

Full Example
------------
	<?php
	include('securepay.php');

	$sp = new SecurePay('username','password');
	$sp->TestMode(); // Remove this line to actually preform a transaction

	$sp->TestConnection();
	print_r($sp->ResponseXml);

	$sp->NameOnCard = 'John Citizen'; // optional
	$sp->Cc = 462834666666;
	$sp->ExpiryDate = '07/09';
	$sp->ChargeAmount = 123;
	$sp->ChargeCurrency = 'USD';
	$sp->Cvv = 321;
	$sp->OrderId = 'ORD34234';
	if ($sp->Valid()) { // Is the above data valid?
		$response = $sp->Process();
		if ($response == SECUREPAY_STATUS_APPROVED) {
			echo "Transaction was a success\n";
		} else {
			echo "Transaction failed with the error code: $response\n";
			echo "XML Dump: " . print_r($sp->ResponseXml,1) . "\n";
		}
	} else {
		die("Your data is invalid\n");
	}
	?>

Global
------
The following examples all the basic PHP setup to kick things off.
Obviously we need to load the library first:

	<?php
	include('securepay.php');

Create a new SecurePay object
-------------------------------------------
	$sp = new SecurePay('username','password');

OR

	$sp = new SecurePay();
	$sp->Login('username','password');

Test the connection to the server
--------------------------------------
	if ($sp->TestConnection()) {
		echo "Server is working\n";
	} else {
		echo "Server is Down\n";
	}

Enable Test Mode (Optional)
----------------------------------
	$sp->TestMode();

OR

	$sp->TestMode(TRUE);

Check if all provided Data is valid (Quick Method)
--------------------------------------------------
	if ($sp->Valid()) {
		echo "Everything is valid\n";
	} else {
		echo "Something is wrong\n";
	}

OR you can break each validity test down individually

	if (!$sp->ValidCc()) {
		echo "Credit Card Number is invalid\n";
	} elseif (!$sp->ValidExpiryDate()) {
		echo "Expiry Date is invalid\n";
	} elseif (!$sp->ValidCvv()) {
		echo "CVV is invalid\n";
	} elseif (!$sp->ValidChargeAmount()) {
		echo "Charge Amount is invalid\n";
	} elseif (!$sp->ValidChargeCurrency()) {
		echo "Charge Currency is invalid\n";
	} elseif (!$sp->ValidOrderId()) {
		echo "Order ID is invalid\n";
	} else {
		echo "All data is valid\n";
	}

Process a payment
-----------------
	// Charge the credit card '462834666666' '$123' US dollars. The card expires on '07/09', has the CVV code '32' and the local order ID is 'ORD34234'.
	$sp->Process(123, 'USD', '462834666666', '07/09', '321', 'ORD34234');

OR

	// Charge the credit card '462834666666' '$123' US dollars. The card expires on '07/09', has the CVV code '32' and the local order ID is 'ORD34234'.
	$sp->Cc = 462834666666;
	$sp->ExpiryDate = '07/09';
	$sp->ChargeAmount = 123;
	$sp->ChargeCurrency = 'USD';
	$sp->Cvv = 321;
	$sp->OrderId = 'ORD34234';
	$sp->Process();

Pre-authorize a payment
-----------------------
	// This is the same process as passing a regular payment but the last parameter indicates that it should be treated as a PreAuth transaction
	$sp->Process(123, 'USD', '462834666666', '07/09', '321', 'ORD34234', TRUE);

OR

	// Exactly the same as a regular charge but with PreAuth = 1
	$sp->PreAuth = 1;
	$sp->Cc = 462834666666;
	$sp->ExpiryDate = '07/09';
	$sp->ChargeAmount = 123;
	$sp->ChargeCurrency = 'USD';
	$sp->Cvv = 321;
	$sp->OrderId = 'ORD34234';
	$sp->Process();
	$preauthid = $sp->PreAuthId; // $preauthid contains the ID used by SecurePay (use this when finalizing a PreAuth)

Charge a PreAuth payment
------------------------
	$sp->PreAuth = 1;
	$sp->PreAuthID = $preauthid; // The ID we got in the above process
	$sp->ChargeAmount = 123;
	$sp->ChargeCurrency = 'USD';
	$sp->OrderId = 'ORD34234'; // NOTE this must match the OrderID used in the above process
	$sp->Process();

Setup a repeating payment
-------------------------
	// Charge the credit card '462834666666' '$123' US dollars every month for 6 months.
	$sp->Cc = 462834666666;
	$sp->ExpiryDate = '07/09';
	$sp->ChargeAmount = 123;
	$sp->ChargeCurrency = 'USD';
	$sp->Cvv = 321;
	$sp->OrderId = 'ORD34234';
	$sp->SetupRepeat('monthly', 6); // Second arg is the interval between months
	$sp->Process();

OR

	// Charge the credit card '462834666666' '$123' US dollars every week for 6 weeks starting on 01/01/10
	$sp->Cc = 462834666666;
	$sp->ExpiryDate = '07/09';
	$sp->ChargeAmount = 123;
	$sp->ChargeCurrency = 'USD';
	$sp->Cvv = 321;
	$sp->OrderId = 'ORD34234';
	$sp->SetupRepeat(SECUREPAY_REPEAT_WEEKLY, 6);
	$sp->RepeatStart = strtotime('01/01/10');
	$sp->Process();

OR

	// Charge the credit card '462834666666' '$123' US dollars every two days for 60 days starting on 01/01/10
	$sp->Cc = 462834666666;
	$sp->ExpiryDate = '07/09';
	$sp->ChargeAmount = 123;
	$sp->ChargeCurrency = 'USD';
	$sp->Cvv = 321;
	$sp->OrderId = 'ORD34234';
	$sp->Repeat = SECUREPAY_REPEAT_DAILY;
	$sp->RepeatInterval = 2;
	$sp->RepeatCount = 60;
	$sp->RepeatStart = strtotime('01/01/10');
	$sp->Process();

Setup a repeating payment with a manual trigger
-----------------------------------------------
	// Charge the credit card '462834666666' '$123' US dollars every week for 6 weeks starting on 01/01/10
	// Then manually trigger the response
	$sp->Cc = 462834666666;
	$sp->ExpiryDate = '07/09';
	$sp->ChargeAmount = 123;
	$sp->ChargeCurrency = 'USD';
	$sp->Cvv = 321;
	$sp->OrderId = 'ORD34234';
	$sp->SetupRepeat(SECUREPAY_REPEAT_WEEKLY, 6);
	$sp->RepeatStart = strtotime('01/01/10');
	$sp->RepeatTrigger = FALSE;
	$sp->Process();
	// ... The repeat payment is now setup
	$sp->Trigger(); // Now start it

Refund a Transaction
--------------------
	//We are assuming that we have previously charged a credit card with the OrderId `ABC123` and the TransactionId was `123456`
	$sp->TransactionId = 123456;
	$sp->ChargeAmount = 123; //Must be less or equal to the transaction amount
	$sp->OrderId = 'ABC123'; //Must be the same as the original transaction

	$sp->Refund(); //Refund it!

Retrieve all client information
-------------------------------
	$sp->WebLogin('username','admin','password'); // Web login details
	$details = $sp->GetClientInfo();

Retrieve a specific clients information
---------------------------------------
	$sp->WebLogin('username','admin','password'); // Web login details
	$details = $sp->GetClientInfo('a_client_id');

Retrieve a list of transactions (today)
---------------------------------------
	$sp->WebLogin('username','admin','password');
	print_r($sp->GetTransactions());

OR for yesterday:

	print_r($sp->GetTransactions('yesterday'));

OR for any date range:

	$sp->WebLogin('username','admin','password');
	print_r($sp->GetTransactions(strtotime('1/1/2008'), strtotime('30/1/2008'))); // Retrieves all transactions between 1/1/2008 and 30/1/2008

Thanks
======
Thanks to Chris Bosdriesz for pointing out that CVV is optional with some cards.


text:
angular.module('app').controller('vendorsCtrl', ['$http', '$scope','locals','NgTableParams', function($http, $scope,locals,NgTableParams){
  var userInfo=locals.getObject('userInfo'),
      sid=userInfo.sid,
      uid=window.localStorage.getItem('uid');
      var agination_index = 0;

    // 调用获取用户列表接口 **********
    $http({
        method:"post",
        url:"../../db/user.php",
        data:{
            sid:sid,
            cmd:"vendor_list"
        },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        transformRequest: function (data) {return $.param(data);}
    }).success(function(data){
        console.log(data);
        $scope.user = data.vendors;
        $scope.users = [];

        $scope.vendorTable=new NgTableParams({},{
          dataset:$scope.user
        })

        // 页数
        $scope.paginationsnum = [];
        var num =  Math.ceil($scope.user.length/18);
        for(var j=0;j<num;j++){
            var dom = {
                name:j+1
            };
            $scope.paginationsnum.push(dom);
        }
        // 默认显示第一页的内容
        for(var i=0;i<$scope.user.length;i++){
            if(i<18){
                $scope.users.push($scope.user[i]);
            }
        }
    });

    //分页
    $scope.pagination_page = function(index){
        agination_index = index;
        getPagination(agination_index);
    };
    //上一页
    $scope.toPreviouspage = function(){
        if(agination_index>0){
            agination_index--;
            getPagination(agination_index);
        }
    };
    //下一页
    $scope.toNextpage_user = function(){
        if(agination_index<$scope.paginationsnum.length-1){
            agination_index++;
            getPagination(agination_index);
        }
    };
    //分页函数
    function getPagination(agination_index){
        $http({
            method:"POST",
            url:"../../db/user.php",
            data:{
                sid:sid,
                cmd:"vendor_list"
            },
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            transformRequest: function (data) {return $.param(data);}
        }).success(function(data){
            $scope.user = data.vendors;
            $scope.users = [];
            var	min = agination_index,
                max = agination_index+1,
                s_num = min*18,
                e_num = max*18;
            for(var i=1;i<=$scope.user.length;i++){
                if(i>s_num && i<=e_num){
                    $scope.users.push($scope.user[i-1]);
                }
            }
            $($('.pagination li.Pagination')[agination_index]).addClass('active').siblings().removeClass('active');
        });
    }
    //修改****
    $scope.change = function(index){
        $scope.userItem = $scope.users[index];
        var s_company=$scope.userItem.company,
            s_level=$scope.userItem.level,
            s_status=$scope.userItem.status;
        $scope.change_sure=function () {
            $http({
                method:"post",
                url:"../../db/user.php",
                data:{
                    sid:sid,
                    cmd:"edit_vendor",
                    id:$scope.userItem.id,
                    company:$scope.userItem.company,
                    level:$scope.userItem.level,
                    status:$scope.userItem.status
                },
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function (data) {return $.param(data);}
            }).success(function(data){
                console.log(data);
                //分页   判断删除时,地区条数是否正好是18的倍数,如果是则agination_index要减一
                var big = Math.floor(($scope.user.length - 1) / 18);
                var flag = ($scope.user.length - 1) - big * 18;
                if (flag == 0) {
                    if(agination_index == ($scope.paginationsnum.length-1)){
                        agination_index--;
                    }
                    $scope.paginationsnum.length--;
                }
                getPagination(agination_index);
            });
            $('#changeModal').modal('hide');
        };
        $scope.change_cancel=function () {
            $('#changeModal').modal('hide');
        };
    };
    //添加代理商**********
    $scope.addVendor = function() {
        $scope.add_sure = function () {
            // 调用新增管理员用户
            $http({
                method: "post",
                url: "../../db/user.php",
                data: {
                    sid: sid,
                    cmd: "add_vendor",
                    company: $scope.addItem.company
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                transformRequest: function (data) {return $.param(data);}
            }).success(function (data) {
                console.log(data);
                // 页数
                $scope.paginationsnum = [];
                var num = Math.ceil(($scope.user.length + 1) / 18);
                for (var j = 0; j < num; j++) {
                    var dom = {
                        name: j + 1
                    };
                    $scope.paginationsnum.push(dom);
                }
                getPagination(agination_index);
                $('#addVendor').modal('hide').find('input').val('');
            });
        };
        //点击取消
        $scope.add_cancel = function () {
            $('#addVendor').modal('hide');
        }
    };
}]);


text:
if [ -d "/Applications/Postgres.app" ]; then
  export PATH="$PATH:/Applications/Postgres.app/Contents/Versions/latest/bin"
fi


text:
/*

g++ -c flatpermissions.cpp
g++ -shared flatpermissions.o -o flatpermissions.so

*/
/*
  Copyright (c) 2010, The Mineserver Project
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  * Neither the name of the The Mineserver Project nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <cstdlib>
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>

#define MINESERVER_C_API
#include "plugin_api.h"

#define PLUGIN_VERSION 1.0
mineserver_pointer_struct* mineserver;
std::string pluginName = "flatpermissions";

std::string dtos(double n)
{
  std::stringstream result;
  result << n;
  return result.str();
}

void loginPost(const char* userIn){
  std::ifstream file;
  file.open("permissions.txt", std::ios::in);
  std::string line;
  if(file.is_open()){
    while(file.good()){
      std::string msg;
      std::getline(file, msg);
      if(msg.size()>1){
        std::string name, rank;
        std::istringstream line(msg);
        std::getline(line,name,':');
        std::getline(line,rank);
        if(name.compare(std::string(userIn))==0){
          std::transform(rank.begin(), rank.end(), rank.begin(), ::tolower);
          if(rank.compare("admin")==0 || rank.compare("admins")==0){
            mineserver->permissions.setAdmin(name.c_str());
          }else if(rank.compare("op")==0 || rank.compare("ops")==0){
            mineserver->permissions.setOp(name.c_str());
          }else if(rank.compare("member")==0 || rank.compare("members")==0){
            mineserver->permissions.setMember(name.c_str());
          }else{
            mineserver->permissions.setGuest(name.c_str());
          }
          break;
        }
      }
    }
    file.close();
  }
}

PLUGIN_API_EXPORT void CALLCONVERSION flatpermissions_shutdown(void)
{
  if (mineserver->plugin.getPluginVersion(pluginName.c_str()) <= 0)
  {
    mineserver->logger.log(6, "plugin.flatpermissions", "flatpermission is not loaded!");
    return;
  }
}

PLUGIN_API_EXPORT void CALLCONVERSION flatpermissions_init(mineserver_pointer_struct* mineserver_temp)
{
  mineserver = mineserver_temp;
  if(mineserver->plugin.getPluginVersion(pluginName.c_str())>0){
    std::string msg = "flatpermission is already loaded, v. "+dtos(mineserver->plugin.getPluginVersion(pluginName.c_str()));
    mineserver->logger.log(6, "plugin.flatpermissions", msg.c_str());
    return;
  }
  std::string msg = "Loaded "+pluginName+"!";
  mineserver->logger.log(6, "plugin.flatpermissions", msg.c_str());

  mineserver->plugin.setPluginVersion(pluginName.c_str(), PLUGIN_VERSION);
  mineserver->plugin.addCallback("PlayerLoginPost", reinterpret_cast<voidF>(loginPost));
}


text:
/*!
 * Module dependencies
 */

var fs = require('fs');
var link = require('../helpers/linktype');
var hl = require('highlight.js')
var md = require('markdown')

module.exports = {
    docs: []
  , github: 'https://github.com/LearnBoost/mongoose/tree/'
  , title: 'API docs'
}

var out = module.exports.docs;

var docs = fs.readFileSync(__dirname + '/_docs', 'utf8');
parse(docs);
order(out);

function parse (docs) {
  docs.split(/^### /gm).forEach(function (chunk) {
    if (!(chunk = chunk.trim())) return;

    chunk = chunk.split(/^([^\n]+)\n/);

    var title = chunk[1];

    if (!title || !(title = title.trim()))
      throw new Error('missing title');

    title = title.replace(/^lib\//, '');

    var json = JSON.parse(chunk[2]);

    var props = [];
    var methods = [];
    var statics = [];
    var constructor = null;

    json.forEach(function (comment) {
      if (comment.description)
        highlight(comment.description);

      var prop = false;
      comment.params = [];
      comment.see = [];

      var i = comment.tags.length;
      while (i--) {
        var tag = comment.tags[i];
        switch (tag.type) {
        case 'property':
          prop = true;
          comment.ctx || (comment.ctx = {});
          comment.ctx.name = tag.string;
          props.unshift(comment);
          break;
        case 'method':
          prop = false;
          comment.ctx || (comment.ctx = {});
          comment.ctx.name || (comment.ctx.name = tag.string);
          comment.ctx.type = 'method';
          comment.code = '';
          break;
        case 'memberOf':
          prop = false;
          comment.ctx || (comment.ctx = {});
          comment.ctx.constructor = tag.parent;
          break;
        case 'static':
          prop = false;
          comment.ctx || (comment.ctx = {});
          comment.ctx.name = tag.string;
          comment.ctx.type = 'method';
          break;
        case 'receiver':
          prop = false;
          comment.ctx || (comment.ctx = {});
          comment.ctx.receiver = tag.string;
          break;
        case 'constructor':
          prop = false;
          comment.ctx || (comment.ctx = {});
          comment.ctx.name || (comment.ctx.name = tag.string);
          comment.ctx.type = 'function';
          comment.code = '';
          break;
        case 'inherits':
          if (/http/.test(tag.string)) {
            var result = tag.string.split(' ');
            var href = result.pop();
            var title = result.join(' ');
            comment.inherits = '' + title + '';
          } else {
            comment.inherits = link(tag.string);
          }
          comment.tags.splice(i, 1);
          break;
        case 'param':
          comment.params.unshift(tag);
          comment.tags.splice(i, 1);
          break;
        case 'return':
          comment.return = tag;
          comment.tags.splice(i, 1);
          break;
        case 'see':
          if (tag.local) {
            var parts = tag.local.split(' ');
            if (1 === parts.length) {
              tag.url = link.type(parts[0]);
              tag.title = parts[0];
            } else {
              tag.url = parts.pop();
              tag.title = parts.join(' ');
            }
          }
          comment.see.unshift(tag);
          comment.tags.splice(i, 1);
          break;
        case 'event':
          var str = tag.string.replace(/\\n/g, '\n');
          tag.string = md.parse(str).replace(/\n/g, '\\n').replace(/'/g, ''');
          comment.events || (comment.events = []);
          comment.events.unshift(tag);
          comment.tags.splice(i, 1);
        }
      }

      if (!prop) {
        methods.push(comment);
      }
    });

    methods = methods.filter(ignored);
    props = props.filter(ignored);

    function ignored (method) {
      if (method.ignore) return false;
      return true;
    }

    if (0 === methods.length + props.length) return;

    // add constructor to properties too
    methods.some(function (method) {
      if (method.ctx && 'method' == method.ctx.type && method.ctx.hasOwnProperty('constructor')) {
        props.forEach(function (prop) {
          prop.ctx.constructor = method.ctx.constructor;
        });
        return true;
      }
      return false;
    });

    var len = methods.length;
    while (len--) {
      method = methods[len];
      if (method.ctx && method.ctx.receiver) {
        var stat = methods.splice(len, 1)[0];
        statics.unshift(stat);
      }
    }

    out.push({
        title: title
      , methods: methods
      , props: props
      , statics: statics
      , hasPublic: hasPublic(methods, props, statics)
    });
  });
}

function hasPublic () {
  for (var i = 0; i < arguments.length; ++i) {
    var arr = arguments[i];
    for (var j = 0; j < arr.length; ++j) {
      var item = arr[j];
      if (!item.ignore && !item.isPrivate) return true;
    }
  }
  return false;
}

// add "class='language'" to our
 elements
function highlight (o) {
  o.full = fix(o.full);
  o.summary = fix(o.summary);
  o.body = fix(o.body);
}

function fix (str) {
  return str.replace(/(
)([^<]+)(<\/code)/gm, function (_, $1, $2, $3) {

    // parse out the ```language
    var code = /^(?:`{3}([^\n]+)\n)?([\s\S]*)/gm.exec($2);

    if ('js' == code[1] || !code[1]) {
      code[1] = 'javascript';
    }

    return $1
          + hl.highlight(code[1], code[2]).value.trim()
          + $3;
  });
}

function order (docs) {
  // want index first
  for (var i = 0; i < docs.length; ++i) {
    if ('index.js' == docs[i].title) {
      docs.unshift(docs.splice(i, 1)[0]);
    }
  }
}


text:
define(['./../../module', 'underscore'], function (module, _) {

    module.controller('BlogModuleSidePostsFormController', ['$scope', '$routeParams', '$location', 'Rest', 'Spinner', function ($scope, $routeParams, $location, Rest, Spinner) {
        /* opened modules */
        $scope.module_id = $routeParams.module_id || null;

        /* scope vars */
        $scope.module_type = 'blog_side_posts';
        $scope.default_language = Journal2Config.languages.default;
        $scope.posts = [];

        $scope.module_data = {
            general_is_open: true,
            close_others: false,
            module_name: 'New Module',
            module_type: 'newest',
            posts: [],
            limit: 5
        };

        Rest.getBlog('posts').then(function (response) {
            $scope.posts = response.posts;
        }, function (error) {
            alert(error);
        });

        /* get data */
        if ($scope.module_id) {
            Rest.getModule($scope.module_id).then(function (response) {
                $scope.module_data = _.extend($scope.module_data, response.module_data);
                Spinner.hide();
            }, function (error) {
                $scope.module_data.general_is_open = true;
                Spinner.hide();
                alert(error);
            });
        } else {
            Spinner.hide();
        }

        /* save data */
        $scope.save = function ($event) {
            var $src = $($event.target || $event.srcElement);
            Spinner.show($src);
            if ($scope.module_id) {
                Rest.editModule($scope.module_id, $scope.module_data).then(function () {
                    Spinner.hide($src);
                }, function (error) {
                    alert(error);
                    Spinner.hide($src);
                });
            } else {
                Rest.addModule($scope.module_type, $scope.module_data).then(function (response) {
                    $location.path('/module/' + $scope.module_type + '/form/' + response.module_id);
                    Spinner.hide($src);
                }, function (error) {
                    alert(error);
                    Spinner.hide($src);
                });
            }
        };

        $scope.delete = function ($event) {
            var $src = $($event.target || $event.srcElement);
            Spinner.show($src);
            if (!confirm('Delete module "' + $scope.module_data.module_name + '"?')) {
                Spinner.hide($src);
                return;
            }
            Rest.deleteModule($scope.module_id).then(function () {
                $location.path('/module/' + $scope.module_type + '/all');
                Spinner.hide($src);
            }, function (error) {
                Spinner.hide($src);
                alert(error);
            });
        };

        $scope.toggleAccordion = function (value) {
            $scope.module_data.general_is_open = value;
            if (value) {
                $scope.module_data.close_others = false;
            }
        };

        $scope.addPost = function () {
            $scope.module_data.posts.push({});
        };

        $scope.removePost = function ($index) {
            $scope.module_data.posts.splice($index, 1);
        };

    }]);

});


text:
var browserSync = require("../../../../");

var connect = require("connect");
var serveStatic = require("serve-static");
var request = require("supertest");
var assert = require("chai").assert;

describe("E2E proxy test with snippet options: Whitelist", function() {
    var instance, server, options;

    before(function(done) {
        browserSync.reset();

        var app = connect();
        app.use(serveStatic("./test/fixtures"));
        server = app.listen();
        var proxytarget = "http://localhost:" + server.address().port;

        var config = {
            proxy: proxytarget,
            logLevel: "silent",
            open: false,
            snippetOptions: {
                whitelist: ["/index-large.html"]
            }
        };

        instance = browserSync.init([], config, function(err, bs) {
            options = bs.options;
            done();
        }).instance;
    });

    after(function() {
        instance.cleanup();
        server.close();
    });

    it("can init proxy & serve a page with whitelist option (injects snippet even without html headers)", function(done) {
        assert.isDefined(instance.server);

        request(instance.server)
            .get("/index-large.html")
            .expect(200)
            .end(function(err, res) {
                assert.include(res.text, options.get("snippet"));
                done();
            });
    });
});

describe("E2E proxy test with snippet options: blacklist", function() {
    var instance, server, options;

    before(function(done) {
        browserSync.reset();

        var app = connect();
        app.use(serveStatic("./test/fixtures"));
        server = app.listen();
        var proxytarget = "http://localhost:" + server.address().port;

        var config = {
            proxy: proxytarget,
            logLevel: "silent",
            open: false,
            snippetOptions: {
                blacklist: ["/index-large.html"]
            }
        };

        instance = browserSync.init([], config, function(err, bs) {
            options = bs.options;
            done();
        }).instance;
    });

    after(function() {
        instance.cleanup();
        server.close();
    });

    it("can init proxy & serve a page with whitelist option", function(done) {
        assert.isDefined(instance.server);

        request(instance.server)
            .get("/index-large.html")
            .set("accept", "text/html")
            .expect(200)
            .end(function(err, res) {
                assert.notInclude(res.text, options.get("snippet"));
                done();
            });
    });
});