text:
#include <babylon/materials/node/blocks/fragment/perturb_normal_block.h>

#include <babylon/core/json_util.h>
#include <babylon/engines/scene.h>
#include <babylon/materials/effect.h>
#include <babylon/materials/node/blocks/input/input_block.h>
#include <babylon/materials/node/node_material.h>
#include <babylon/materials/node/node_material_build_state.h>
#include <babylon/materials/node/node_material_build_state_shared_data.h>
#include <babylon/materials/node/node_material_connection_point.h>
#include <babylon/materials/node/node_material_defines.h>
#include <babylon/misc/string_tools.h>

namespace BABYLON {

PerturbNormalBlock::PerturbNormalBlock(const std::string& iName)
    : NodeMaterialBlock{iName, NodeMaterialBlockTargets::Fragment}
    , invertX{false}
    , invertY{false}
    , worldPosition{this, &PerturbNormalBlock::get_worldPosition}
    , worldNormal{this, &PerturbNormalBlock::get_worldNormal}
    , worldTangent{this, &PerturbNormalBlock::get_worldTangent}
    , uv{this, &PerturbNormalBlock::get_uv}
    , normalMapColor{this, &PerturbNormalBlock::get_normalMapColor}
    , strength{this, &PerturbNormalBlock::get_strength}
    , output{this, &PerturbNormalBlock::get_output}
{
  // Vertex
  registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes::Vector4, false);
  registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes::Vector4, false);
  registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes::Vector4, true);
  registerInput("uv", NodeMaterialBlockConnectionPointTypes::Vector2, false);
  registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes::Color3, false);
  registerInput("strength", NodeMaterialBlockConnectionPointTypes::Float, false);

  // Fragment
  registerOutput("output", NodeMaterialBlockConnectionPointTypes::Vector4);
}

PerturbNormalBlock::~PerturbNormalBlock() = default;

std::string PerturbNormalBlock::getClassName() const
{
  return "PerturbNormalBlock";
}

NodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldPosition()
{
  return _inputs[0];
}

NodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldNormal()
{
  return _inputs[1];
}

NodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldTangent()
{
  return _inputs[2];
}

NodeMaterialConnectionPointPtr& PerturbNormalBlock::get_uv()
{
  return _inputs[3];
}

NodeMaterialConnectionPointPtr& PerturbNormalBlock::get_normalMapColor()
{
  return _inputs[4];
}

NodeMaterialConnectionPointPtr& PerturbNormalBlock::get_strength()
{
  return _inputs[5];
}

NodeMaterialConnectionPointPtr& PerturbNormalBlock::get_output()
{
  return _outputs[0];
}

void PerturbNormalBlock::prepareDefines(AbstractMesh* /*mesh*/,
                                        const NodeMaterialPtr& /*nodeMaterial*/,
                                        NodeMaterialDefines& defines, bool /*useInstances*/,
                                        SubMesh* /*subMesh*/)
{
  defines.setValue("BUMP", true);
}

void PerturbNormalBlock::bind(Effect* effect, const NodeMaterialPtr& nodeMaterial, Mesh* /*mesh*/,
                              SubMesh* /*subMesh*/)
{
  if (nodeMaterial->getScene()->_mirroredCameraPosition) {
    effect->setFloat2(_tangentSpaceParameterName, invertX ? 1.f : -1.f, invertY ? 1.f : -1.f);
  }
  else {
    effect->setFloat2(_tangentSpaceParameterName, invertX ? -1.f : 1.f, invertY ? -1.f : 1.f);
  }
}

void PerturbNormalBlock::autoConfigure(const NodeMaterialPtr& material)
{
  if (!uv()->isConnected()) {
    auto uvInput = material->getInputBlockByPredicate(
      [](const InputBlockPtr& b) -> bool { return b->isAttribute() && b->name() == "uv"; });

    if (!uvInput) {
      uvInput = InputBlock::New("uv");
      uvInput->setAsAttribute();
    }
    uvInput->output()->connectTo(uv);
  }

  if (!strength()->isConnected()) {
    auto strengthInput   = InputBlock::New("strength");
    strengthInput->value = std::make_shared<AnimationValue>(1.f);
    strengthInput->output()->connectTo(strength);
  }
}

PerturbNormalBlock& PerturbNormalBlock::_buildBlock(NodeMaterialBuildState& state)
{
  NodeMaterialBlock::_buildBlock(state);

  const auto iComments       = StringTools::printf("//%s", name().c_str());
  const auto& _uv            = uv();
  const auto& _worldPosition = worldPosition();
  const auto& _worldNormal   = worldNormal();
  const auto& _worldTangent  = worldTangent();

  state.sharedData->blocksWithDefines.emplace_back(shared_from_this());
  state.sharedData->bindableBlocks.emplace_back(shared_from_this());

  _tangentSpaceParameterName = state._getFreeDefineName("tangentSpaceParameter");

  state._emitUniformFromString(_tangentSpaceParameterName, "vec2");

  const auto replaceForBumpInfos
    = strength()->isConnectedToInputBlock() && strength()->connectInputBlock()->isConstant ?
        state._emitFloat(1.f / strength()->connectInputBlock()->value()->get<float>()).c_str() :
        StringTools::printf("1.0 / %s", strength()->associatedVariableName().c_str());

  state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");

  StringsReplacement tangentReplaceString{
    "defined\\(TANGENT\\)",                                               // search
    _worldTangent->isConnected() ? "defined(TANGENT)" : "defined(IGNORE)" // replace
  };

  if (_worldTangent->isConnected()) {
    state.compilationString += StringTools::printf("vec3 tbnNormal = normalize(%s.xyz);\r\n",
                                                   _worldNormal->associatedVariableName().c_str());
    state.compilationString += StringTools::printf("vec3 tbnTangent = normalize(%s.xyz);\r\n",
                                                   _worldTangent->associatedVariableName().c_str());
    state.compilationString += "vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r\n";
    state.compilationString += "mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n";
  }

  {
    EmitFunctionFromIncludeOptions emitFunctionFromIncludeOptions;
    emitFunctionFromIncludeOptions.replaceStrings = {tangentReplaceString};
    state._emitFunctionFromInclude("bumpFragmentMainFunctions", iComments,
                                   emitFunctionFromIncludeOptions);
  }

  {
    EmitFunctionFromIncludeOptions emitFunctionFromIncludeOptions;
    emitFunctionFromIncludeOptions.replaceStrings
      = {{"vBumpInfos.y", replaceForBumpInfos},
         {"vTangentSpaceParams", _tangentSpaceParameterName},
         {"vPositionW", _worldPosition->associatedVariableName() + ".xyz"},
         {"varying vec2 vBumpUV;", ""},
         {R"(uniform sampler2D bumpSampler;[\s\S]*?\})", ""}};
    state._emitFunctionFromInclude("bumpFragmentFunctions", iComments,
                                   emitFunctionFromIncludeOptions);
  }

  state.compilationString += _declareOutput(output, state) + " = vec4(0.);\r\n";
  EmitCodeFromIncludeOptions emitCodeFromIncludeOptions;
  emitCodeFromIncludeOptions.replaceStrings
    = {{"perturbNormal\\(TBN,vBumpUV\\+uvOffset\\)",
        StringTools::printf("perturbNormal(TBN, %s)",
                            normalMapColor()->associatedVariableName().c_str())},
       {"vBumpInfos.y", replaceForBumpInfos},
       {"vBumpUV", _uv->associatedVariableName()},
       {"vPositionW", _worldPosition->associatedVariableName() + ".xyz"},
       {"normalW=", output()->associatedVariableName() + ".xyz = "},
       {R"(mat3\(normalMatrix\)\*normalW)",
        "mat3(normalMatrix) * " + output()->associatedVariableName() + ".xyz"},
       {"normalW", _worldNormal->associatedVariableName() + ".xyz"},
       tangentReplaceString};
  state.compilationString
    += state._emitCodeFromInclude("bumpFragment", iComments, emitCodeFromIncludeOptions);

  return *this;
}

std::string PerturbNormalBlock::_dumpPropertiesCode()
{
  auto codeString = StringTools::printf("%s.invertX = %s;\r\n", _codeVariableName.c_str(),
                                        invertX ? "true" : "false");

  codeString += StringTools::printf("%s.invertY = %s;\r\n", _codeVariableName.c_str(),
                                    invertY ? "true" : "false");

  return codeString;
}

json PerturbNormalBlock::serialize() const
{
  return nullptr;
}

void PerturbNormalBlock::_deserialize(const json& /*serializationObject*/, Scene* /*scene*/,
                                      const std::string& /*rootUrl*/)
{
}

} // end of namespace BABYLON


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

    <servlet>
        <servlet-name>ServerServlet</servlet-name>
        <servlet-class>controller.server.ServerServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ServerServlet</servlet-name>
        <url-pattern>/app</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout> 30 </session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>LibraryApp.jsp</welcome-file>
    </welcome-file-list>

</web-app>

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.scalding

import java.text.SimpleDateFormat

import java.util.Calendar
import java.util.Date
import java.util.TimeZone

/**
* RichDate adds some nice convenience functions to the Java date/calendar classes
* We commonly do Date/Time work in analysis jobs, so having these operations convenient
* is very helpful.
*/
object RichDate {
  def apply(s : String)(implicit tz : TimeZone) = {
    DateOps.stringToRichDate(s)(tz)
  }
  def apply(l : Long) = {
    DateOps.longToRichDate(l)
  }
  def upperBound(s : String)(implicit tz : TimeZone) = {
    val end = apply(s)(tz)
    (DateOps.getFormat(s) match {
      case Some(DateOps.DATE_WITH_DASH) => end + Days(1)
      case Some(DateOps.DATEHOUR_WITH_DASH) => end + Hours(1)
      case Some(DateOps.DATETIME_WITH_DASH) => end + Minutes(1)
      case Some(DateOps.DATETIME_HMS_WITH_DASH) => end + Seconds(1)
      case Some(DateOps.DATETIME_HMSM_WITH_DASH) => end + Millisecs(2)
      case None => Days(1).floorOf(end + Days(1))
    }) - Millisecs(1)
  }
}

case class RichDate(val value : Date) extends Ordered[RichDate] {
  def +(interval : Duration) = interval.addTo(this)
  def -(interval : Duration) = interval.subtractFrom(this)

  //Inverse of the above, d2 + (d1 - d2) == d1
  def -(that : RichDate) = Duration.fromMillisecs(value.getTime - that.value.getTime)

  override def compare(that : RichDate) : Int = {
    if (value.before(that.value)) {
      -1
    }
    else if (value.after(that.value)) {
      1
    } else {
      0
    }
  }

  //True of the other is a RichDate with equal value, or a Date equal to value
  override def equals(that : Any) = {
    //Due to type erasure (scala 2.9 complains), we need to use a manifest:
    def opInst[T : Manifest](v : Any) = {
      val klass = manifest[T].erasure
      if(null != v && klass.isInstance(v)) Some(v.asInstanceOf[T]) else None
    }
    opInst[RichDate](that)
      .map( _.value)
      .orElse(opInst[Date](that))
      .map( _.equals(value) )
      .getOrElse(false)
  }

  /** Use String.format to format the date, as opposed to toString with uses SimpleDateFormat
   */
  def format(pattern: String)(implicit tz: TimeZone) : String = String.format(pattern, toCalendar(tz))

  override def hashCode = { value.hashCode }

  //milliseconds since the epoch
  def timestamp : Long = value.getTime

  def toCalendar(implicit tz: TimeZone) = {
    val cal = Calendar.getInstance(tz)
    cal.setTime(value)
    cal
  }
  override def toString = {
    value.toString
  }

  /** Use SimpleDateFormat to print the string
   */
  def toString(fmt : String)(implicit tz : TimeZone) : String = {
    val cal = toCalendar(tz)
    val sdfmt = new SimpleDateFormat(fmt)
    sdfmt.setCalendar(cal)
    sdfmt.format(cal.getTime)
  }
}


text:
//
// Novell.Directory.Ldap.Extensions.ListReplicasResponse.cs
//
// Author:
//   Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//

using System;
using Novell.Directory.Ldap;
using Novell.Directory.Ldap.Asn1;
using Novell.Directory.Ldap.Utilclass;
using Novell.Directory.Ldap.Rfc2251;

namespace Novell.Directory.Ldap.Extensions
{

	/// <summary> Retrieves the list of replicas from the specified server.
	///
	/// An object in this class is generated from an ExtendedResponse object
	/// using the ExtendedResponseFactory class.
	///
	/// The listReplicaResponse extension uses the following OID:
	/// 2.16.840.1.113719.1.27.20
	///
	/// </summary>
	public class ListReplicasResponse:LdapExtendedResponse
	{
		/// <summary> Returns a list of distinguished names for the replicas on the server.
		///
		/// </summary>
		/// <returns> String value specifying the identity returned by the server
		/// </returns>
		virtual public System.String[] ReplicaList
		{
			get
			{
				return replicaList;
			}

		}

		// Identity returned by the server
		private System.String[] replicaList;

		/// <summary> Constructs an object from the responseValue which contains the list
		/// of replicas.
		///
		/// The constructor parses the responseValue which has the following
		/// format:
		/// responseValue ::=
		///   replicaList
		/// SEQUENCE OF OCTET STRINGS
		///
		/// </summary>
		/// <exception> IOException  The responseValue could not be decoded.
		/// </exception>
		public ListReplicasResponse(RfcLdapMessage rfcMessage):base(rfcMessage)
		{

			if (ResultCode != LdapException.SUCCESS)
			{
				replicaList = new System.String[0];
			}
			else
			{
				// parse the contents of the reply
				sbyte[] returnedValue = this.Value;
				if (returnedValue == null)
					throw new System.IO.IOException("No returned value");

				// Create a decoder object
				LBERDecoder decoder = new LBERDecoder();
				if (decoder == null)
					throw new System.IO.IOException("Decoding error");

				// We should get back a sequence
				Asn1Sequence returnedSequence = (Asn1Sequence) decoder.decode(returnedValue);
				if (returnedSequence == null)
					throw new System.IO.IOException("Decoding error");

				// How many replicas were returned
				int len = returnedSequence.size();
				replicaList = new System.String[len];

				// Copy each one into our String array
				for (int i = 0; i < len; i++)
				{
					// Get the next Asn1Octet String in the sequence
					Asn1OctetString asn1_nextReplica = (Asn1OctetString) returnedSequence.get_Renamed(i);
					if (asn1_nextReplica == null)
						throw new System.IO.IOException("Decoding error");

					// Convert to a string
					replicaList[i] = asn1_nextReplica.stringValue();
					if ((System.Object) replicaList[i] == null)
						throw new System.IO.IOException("Decoding error");
				}
			}
		}
	}
}


text:
package net.arp7.FsPerfTest;

/**
 * Constants that control the runtime behavior of {@link FsStress}.
 */
class FsStressConstants {
  /**
   * A minimum number of leaves (files/dirs) need to be created per-thread for
   * issuing other requests.
   */
  static final int NUM_LEAVES_LOW_WATERMARK = 3_000;
  static final int NUM_LEAVES_MID_WATERMARK = 6_000;

  /**
   * Above this threshold we will try not to issue create/mkdir requests.
   */

  static final int NUM_LEAVES_HIGH_WATERMARK = 1_000_000;

  /**
   * We use a two-level directory structure to reduce the number of
   * files/dirs per level. Leaf files are dirs are created under the
   * following directory structure e.g. 22/17/000000005291
   * Where 22 is the l1 directory, 17 is the l2 directory and
   * 000000005291 is the leaf-level file/dir name.
   */
  static final int NUM_DIRS_AT_L1_AND_L2 = 32;
}


text:
package com.vladsch.flexmark.ext.gfm.strikethrough;

import com.vladsch.flexmark.util.ast.VisitHandler;

public class SubscriptVisitorExt {
    public static <V extends SubscriptVisitor> VisitHandler<?>[] VISIT_HANDLERS(V visitor) {
        return new VisitHandler<?>[] {
                new VisitHandler<>(Subscript.class, visitor::visit),
        };
    }
}


text:
package eu.agilejava.snoop.client;

import java.util.Optional;
import java.util.logging.Logger;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import javax.ws.rs.core.Response;

/**
 * Client API for calling services registered with Snoop.
 *
 * @author Ivar Grimstad (ivar.grimstad@gmail.com)
 */
public class SnoopServiceClient {

    private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoop");
    private static final String DEFAULT_BASE_URI = "http://localhost:8080/snoop-service/";

    private final String applicationName;
    private final String serviceUrl;

    static final class Builder {

        private final String applicationName;
        private String serviceUrl = DEFAULT_BASE_URI;

        Builder(final String applicationName) {
            this.applicationName = applicationName;
        }

        Builder serviceUrl(final String serviceUrl) {
            this.serviceUrl = serviceUrl;
            return this;
        }

        SnoopServiceClient build() {
            return new SnoopServiceClient(this);
        }
    }

    private SnoopServiceClient(final Builder builder) {
        this.applicationName = builder.applicationName;
        this.serviceUrl = builder.serviceUrl;
        LOGGER.info(() -> "client created for " + applicationName);
    }

    /**
     * Locator to get the service root for the service registered with Snoop.
     *
     * Use this method if the convenience methods simpleXXX are not sufficient or to avoid the extra call to Snoop for
     * every request.
     *
     * @return the serviceRoot
     *
     * @throws SnoopServiceUnavailableException if service is not available
     */
    public WebTarget getServiceRoot() throws SnoopServiceUnavailableException {

        SnoopConfig snoopConfig = getConfigFromSnoop();
        LOGGER.fine(() -> "looking up service for " + applicationName);

        return ClientBuilder.newClient()
                .target(snoopConfig.getServiceHome())
                .path(snoopConfig.getServiceRoot());
    }

    /**
     * Convenience method for making a simple GET request on a resource.
     *
     * Calling this method will result in a call to Snoop to retrieve the current configuration for the service in
     * addition to the actual GET request.
     *
     * @param resourcePath The relative path to the resource
     * @return an optional response that is empty if the service is unavailable.
     */
    public Optional<Response> simpleGet(String resourcePath) {

        Optional<Response> returnValue = Optional.empty();

        try {

            returnValue = Optional.of(getServiceRoot()
                    .path(resourcePath)
                    .request()
                    .get());

        } catch (SnoopServiceUnavailableException e) {
            LOGGER.warning(() -> "Service unavailable for " + applicationName);
        }

        return returnValue;
    }

    /**
     * Convenience method for making a simple DELETE request on a resource.
     *
     * Calling this method will result in a call to Snoop to retrieve the current configuration for the service in
     * addition to the actual DELETE request.
     *
     * @param resourcePath The relative path to the resource
     * @return an optional response that is empty if the service is unavailable.
     */
    public Optional<Response> simpleDelete(String resourcePath) {

        Optional<Response> returnValue = Optional.empty();

        try {

            returnValue = Optional.of(getServiceRoot()
                    .path(resourcePath)
                    .request()
                    .delete());

        } catch (SnoopServiceUnavailableException e) {
            LOGGER.warning(() -> "Service unavailable for " + applicationName);
        }

        return returnValue;
    }

    /**
     * Convenience method for making a simple PUT request on a resource.
     *
     * Calling this method will result in a call to Snoop to retrieve the current configuration for the service in
     * addition to the actual PUT request.
     *
     * @param resourcePath The relative path to the resource
     * @param resource The changes made to this resource
     * @return an optional response that is empty if the service is unavailable.
     */
    public Optional<Response> simplePut(String resourcePath, Object resource) {

        Optional<Response> returnValue = Optional.empty();

        try {

            returnValue = Optional.of(getServiceRoot()
                    .path(resourcePath)
                    .request()
                    .put(Entity.entity(resource, APPLICATION_JSON)));

        } catch (SnoopServiceUnavailableException e) {
            LOGGER.warning(() -> "Service unavailable for " + applicationName);
        }

        return returnValue;
    }

    /**
     * Convenience method for making a simple POST request on a resource.
     *
     * Calling this method will result in a call to Snoop to retrieve the current configuration for the service in
     * addition to the actual POST request.
     *
     * @param resourcePath The relative path to the resource
     * @param resource The new resource
     * @return an optional response that is empty if the service is unavailable.
     */
    public Optional<Response> simplePost(String resourcePath, Object resource) {

        Optional<Response> returnValue = Optional.empty();

        try {

            returnValue = Optional.of(getServiceRoot()
                    .path(resourcePath)
                    .request()
                    .post(Entity.entity(resource, APPLICATION_JSON)));

        } catch (SnoopServiceUnavailableException e) {
            LOGGER.warning(() -> "Service unavailable for " + applicationName);
        }

        return returnValue;
    }

    private SnoopConfig getConfigFromSnoop() throws SnoopServiceUnavailableException {

        try {
            Response response = ClientBuilder.newClient()
                    .target(serviceUrl)
                    .path("api")
                    .path("services")
                    .path(applicationName)
                    .request(APPLICATION_JSON)
                    .get();

            if (response.getStatus() == 200) {
                return response.readEntity(SnoopConfig.class);
            } else {
                throw new SnoopServiceUnavailableException("Response from \"" + serviceUrl + "\"=" + response.getStatus());
            }

        } catch (ProcessingException e) {
            throw new SnoopServiceUnavailableException(e);
        }
    }
}


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * The PEAR DB driver for PHP's sqlite extension
 * for interacting with SQLite databases
 *
 * PHP versions 4 and 5
 *
 * LICENSE: This source file is subject to version 3.0 of the PHP license
 * that is available through the world-wide-web at the following URI:
 * http://www.php.net/license/3_0.txt.  If you did not receive a copy of
 * the PHP License and are unable to obtain it through the web, please
 * send a note to license@php.net so we can mail you a copy immediately.
 *
 * @category   Database
 * @package    DB
 * @author     Urs Gehrig <urs@circle.ch>
 * @author     Mika Tuupola <tuupola@appelsiini.net>
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0 3.0
 * @version    CVS: $Id: sqlite.php,v 1.1 2010/05/07 08:33:14 soonchoy Exp $
 * @link       http://pear.php.net/package/DB
 */

/**
 * Obtain the DB_common class so it can be extended from
 */
require_once 'DB/common.php';

/**
 * The methods PEAR DB uses to interact with PHP's sqlite extension
 * for interacting with SQLite databases
 *
 * These methods overload the ones declared in DB_common.
 *
 * NOTICE:  This driver needs PHP's track_errors ini setting to be on.
 * It is automatically turned on when connecting to the database.
 * Make sure your scripts don't turn it off.
 *
 * @category   Database
 * @package    DB
 * @author     Urs Gehrig <urs@circle.ch>
 * @author     Mika Tuupola <tuupola@appelsiini.net>
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  1997-2005 The PHP Group
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0 3.0
 * @version    Release: 1.7.12
 * @link       http://pear.php.net/package/DB
 */
class DB_sqlite extends DB_common
{
    // {{{ properties

    /**
     * The DB driver type (mysql, oci8, odbc, etc.)
     * @var string
     */
    var $phptype = 'sqlite';

    /**
     * The database syntax variant to be used (db2, access, etc.), if any
     * @var string
     */
    var $dbsyntax = 'sqlite';

    /**
     * The capabilities of this DB implementation
     *
     * The 'new_link' element contains the PHP version that first provided
     * new_link support for this DBMS.  Contains false if it's unsupported.
     *
     * Meaning of the 'limit' element:
     *   + 'emulate' = emulate with fetch row by number
     *   + 'alter'   = alter the query
     *   + false     = skip rows
     *
     * @var array
     */
    var $features = array(
        'limit'         => 'alter',
        'new_link'      => false,
        'numrows'       => true,
        'pconnect'      => true,
        'prepare'       => false,
        'ssl'           => false,
        'transactions'  => false,
    );

    /**
     * A mapping of native error codes to DB error codes
     *
     * {@internal  Error codes according to sqlite_exec.  See the online
     * manual at http://sqlite.org/c_interface.html for info.
     * This error handling based on sqlite_exec is not yet implemented.}}
     *
     * @var array
     */
    var $errorcode_map = array(
    );

    /**
     * The raw database connection created by PHP
     * @var resource
     */
    var $connection;

    /**
     * The DSN information for connecting to a database
     * @var array
     */
    var $dsn = array();

    /**
     * SQLite data types
     *
     * @link http://www.sqlite.org/datatypes.html
     *
     * @var array
     */
    var $keywords = array (
        'BLOB'      => '',
        'BOOLEAN'   => '',
        'CHARACTER' => '',
        'CLOB'      => '',
        'FLOAT'     => '',
        'INTEGER'   => '',
        'KEY'       => '',
        'NATIONAL'  => '',
        'NUMERIC'   => '',
        'NVARCHAR'  => '',
        'PRIMARY'   => '',
        'TEXT'      => '',
        'TIMESTAMP' => '',
        'UNIQUE'    => '',
        'VARCHAR'   => '',
        'VARYING'   => '',
    );

    /**
     * The most recent error message from $php_errormsg
     * @var string
     * @access private
     */
    var $_lasterror = '';

    // }}}
    // {{{ constructor

    /**
     * This constructor calls $this->DB_common()
     *
     * @return void
     */
    function DB_sqlite()
    {
        $this->DB_common();
    }

    // }}}
    // {{{ connect()

    /**
     * Connect to the database server, log in and open the database
     *
     * Don't call this method directly.  Use DB::connect() instead.
     *
     * PEAR DB's sqlite driver supports the following extra DSN options:
     *   + mode  The permissions for the database file, in four digit
     *            chmod octal format (eg "0600").
     *
     * Example of connecting to a database in read-only mode:
     *
     * require_once 'DB.php';
     *
     * $dsn = 'sqlite:///path/and/name/of/db/file?mode=0400';
     * $options = array(
     *     'portability' => DB_PORTABILITY_ALL,
     * );
     *
     * $db =& DB::connect($dsn, $options);
     * if (PEAR::isError($db)) {
     *     die($db->getMessage());
     * }
     *
     *
     * @param array $dsn         the data source name
     * @param bool  $persistent  should the connection be persistent?
     *
     * @return int  DB_OK on success. A DB_Error object on failure.
     */
    function connect($dsn, $persistent = false)
    {
        if (!PEAR::loadExtension('sqlite')) {
            return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
        }

        $this->dsn = $dsn;
        if ($dsn['dbsyntax']) {
            $this->dbsyntax = $dsn['dbsyntax'];
        }

        if (!$dsn['database']) {
            return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
        }

        if ($dsn['database'] !== ':memory:') {
            if (!file_exists($dsn['database'])) {
                if (!touch($dsn['database'])) {
                    return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
                }
                if (!isset($dsn['mode']) ||
                    !is_numeric($dsn['mode']))
                {
                    $mode = 0644;
                } else {
                    $mode = octdec($dsn['mode']);
                }
                if (!chmod($dsn['database'], $mode)) {
                    return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
                }
                if (!file_exists($dsn['database'])) {
                    return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND);
                }
            }
            if (!is_file($dsn['database'])) {
                return $this->sqliteRaiseError(DB_ERROR_INVALID);
            }
            if (!is_readable($dsn['database'])) {
                return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION);
            }
        }

        $connect_function = $persistent ? 'sqlite_popen' : 'sqlite_open';

        // track_errors must remain on for simpleQuery()
        @ini_set('track_errors', 1);
        $php_errormsg = '';

        if (!$this->connection = @$connect_function($dsn['database'])) {
            return $this->raiseError(DB_ERROR_NODBSELECTED,
                                     null, null, null,
                                     $php_errormsg);
        }
        return DB_OK;
    }

    // }}}
    // {{{ disconnect()

    /**
     * Disconnects from the database server
     *
     * @return bool  TRUE on success, FALSE on failure
     */
    function disconnect()
    {
        $ret = @sqlite_close($this->connection);
        $this->connection = null;
        return $ret;
    }

    // }}}
    // {{{ simpleQuery()

    /**
     * Sends a query to the database server
     *
     * NOTICE:  This method needs PHP's track_errors ini setting to be on.
     * It is automatically turned on when connecting to the database.
     * Make sure your scripts don't turn it off.
     *
     * @param string  the SQL query string
     *
     * @return mixed  + a PHP result resrouce for successful SELECT queries
     *                + the DB_OK constant for other successful queries
     *                + a DB_Error object on failure
     */
    function simpleQuery($query)
    {
        $ismanip = $this->_checkManip($query);
        $this->last_query = $query;
        $query = $this->modifyQuery($query);

        $php_errormsg = '';

        $result = @sqlite_query($query, $this->connection);
        $this->_lasterror = $php_errormsg ? $php_errormsg : '';

        $this->result = $result;
        if (!$this->result) {
            return $this->sqliteRaiseError(null);
        }

        // sqlite_query() seems to allways return a resource
        // so cant use that. Using $ismanip instead
        if (!$ismanip) {
            $numRows = $this->numRows($result);
            if (is_object($numRows)) {
                // we've got PEAR_Error
                return $numRows;
            }
            return $result;
        }
        return DB_OK;
    }

    // }}}
    // {{{ nextResult()

    /**
     * Move the internal sqlite result pointer to the next available result
     *
     * @param resource $result  the valid sqlite result resource
     *
     * @return bool  true if a result is available otherwise return false
     */
    function nextResult($result)
    {
        return false;
    }

    // }}}
    // {{{ fetchInto()

    /**
     * Places a row from the result set into the given array
     *
     * Formating of the array and the data therein are configurable.
     * See DB_result::fetchInto() for more information.
     *
     * This method is not meant to be called directly.  Use
     * DB_result::fetchInto() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result    the query result resource
     * @param array    $arr       the referenced array to put the data in
     * @param int      $fetchmode how the resulting array should be indexed
     * @param int      $rownum    the row number to fetch (0 = first row)
     *
     * @return mixed  DB_OK on success, NULL when the end of a result set is
     *                 reached or on failure
     *
     * @see DB_result::fetchInto()
     */
    function fetchInto($result, &$arr, $fetchmode, $rownum = null)
    {
        if ($rownum !== null) {
            if (!@sqlite_seek($this->result, $rownum)) {
                return null;
            }
        }
        if ($fetchmode & DB_FETCHMODE_ASSOC) {
            $arr = @sqlite_fetch_array($result, SQLITE_ASSOC);
            if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
                $arr = array_change_key_case($arr, CASE_LOWER);
            }
        } else {
            $arr = @sqlite_fetch_array($result, SQLITE_NUM);
        }
        if (!$arr) {
            return null;
        }
        if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
            /*
             * Even though this DBMS already trims output, we do this because
             * a field might have intentional whitespace at the end that
             * gets removed by DB_PORTABILITY_RTRIM under another driver.
             */
            $this->_rtrimArrayValues($arr);
        }
        if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
            $this->_convertNullArrayValuesToEmpty($arr);
        }
        return DB_OK;
    }

    // }}}
    // {{{ freeResult()

    /**
     * Deletes the result set and frees the memory occupied by the result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::free() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result  PHP's query result resource
     *
     * @return bool  TRUE on success, FALSE if $result is invalid
     *
     * @see DB_result::free()
     */
    function freeResult(&$result)
    {
        // XXX No native free?
        if (!is_resource($result)) {
            return false;
        }
        $result = null;
        return true;
    }

    // }}}
    // {{{ numCols()

    /**
     * Gets the number of columns in a result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::numCols() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result  PHP's query result resource
     *
     * @return int  the number of columns.  A DB_Error object on failure.
     *
     * @see DB_result::numCols()
     */
    function numCols($result)
    {
        $cols = @sqlite_num_fields($result);
        if (!$cols) {
            return $this->sqliteRaiseError();
        }
        return $cols;
    }

    // }}}
    // {{{ numRows()

    /**
     * Gets the number of rows in a result set
     *
     * This method is not meant to be called directly.  Use
     * DB_result::numRows() instead.  It can't be declared "protected"
     * because DB_result is a separate object.
     *
     * @param resource $result  PHP's query result resource
     *
     * @return int  the number of rows.  A DB_Error object on failure.
     *
     * @see DB_result::numRows()
     */
    function numRows($result)
    {
        $rows = @sqlite_num_rows($result);
        if ($rows === null) {
            return $this->sqliteRaiseError();
        }
        return $rows;
    }

    // }}}
    // {{{ affected()

    /**
     * Determines the number of rows affected by a data maniuplation query
     *
     * 0 is returned for queries that don't manipulate data.
     *
     * @return int  the number of rows.  A DB_Error object on failure.
     */
    function affectedRows()
    {
        return @sqlite_changes($this->connection);
    }

    // }}}
    // {{{ dropSequence()

    /**
     * Deletes a sequence
     *
     * @param string $seq_name  name of the sequence to be deleted
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     *
     * @see DB_common::dropSequence(), DB_common::getSequenceName(),
     *      DB_sqlite::nextID(), DB_sqlite::createSequence()
     */
    function dropSequence($seq_name)
    {
        return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
    }

    /**
     * Creates a new sequence
     *
     * @param string $seq_name  name of the new sequence
     *
     * @return int  DB_OK on success.  A DB_Error object on failure.
     *
     * @see DB_common::createSequence(), DB_common::getSequenceName(),
     *      DB_sqlite::nextID(), DB_sqlite::dropSequence()
     */
    function createSequence($seq_name)
    {
        $seqname = $this->getSequenceName($seq_name);
        $query   = 'CREATE TABLE ' . $seqname .
                   ' (id INTEGER UNSIGNED PRIMARY KEY) ';
        $result  = $this->query($query);
        if (DB::isError($result)) {
            return($result);
        }
        $query   = "CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname
                    BEGIN
                        DELETE FROM $seqname WHERE id<LAST_INSERT_ROWID();
                    END ";
        $result  = $this->query($query);
        if (DB::isError($result)) {
            return($result);
        }
    }

    // }}}
    // {{{ nextId()

    /**
     * Returns the next free id in a sequence
     *
     * @param string  $seq_name  name of the sequence
     * @param boolean $ondemand  when true, the seqence is automatically
     *                            created if it does not exist
     *
     * @return int  the next id number in the sequence.
     *               A DB_Error object on failure.
     *
     * @see DB_common::nextID(), DB_common::getSequenceName(),
     *      DB_sqlite::createSequence(), DB_sqlite::dropSequence()
     */
    function nextId($seq_name, $ondemand = true)
    {
        $seqname = $this->getSequenceName($seq_name);

        do {
            $repeat = 0;
            $this->pushErrorHandling(PEAR_ERROR_RETURN);
            $result = $this->query("INSERT INTO $seqname (id) VALUES (NULL)");
            $this->popErrorHandling();
            if ($result === DB_OK) {
                $id = @sqlite_last_insert_rowid($this->connection);
                if ($id != 0) {
                    return $id;
                }
            } elseif ($ondemand && DB::isError($result) &&
                      $result->getCode() == DB_ERROR_NOSUCHTABLE)
            {
                $result = $this->createSequence($seq_name);
                if (DB::isError($result)) {
                    return $this->raiseError($result);
                } else {
                    $repeat = 1;
                }
            }
        } while ($repeat);

        return $this->raiseError($result);
    }

    // }}}
    // {{{ getDbFileStats()

    /**
     * Get the file stats for the current database
     *
     * Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size,
     * atime, mtime, ctime, blksize, blocks or a numeric key between
     * 0 and 12.
     *
     * @param string $arg  the array key for stats()
     *
     * @return mixed  an array on an unspecified key, integer on a passed
     *                arg and false at a stats error
     */
    function getDbFileStats($arg = '')
    {
        $stats = stat($this->dsn['database']);
        if ($stats == false) {
            return false;
        }
        if (is_array($stats)) {
            if (is_numeric($arg)) {
                if (((int)$arg <= 12) & ((int)$arg >= 0)) {
                    return false;
                }
                return $stats[$arg ];
            }
            if (array_key_exists(trim($arg), $stats)) {
                return $stats[$arg ];
            }
        }
        return $stats;
    }

    // }}}
    // {{{ escapeSimple()

    /**
     * Escapes a string according to the current DBMS's standards
     *
     * In SQLite, this makes things safe for inserts/updates, but may
     * cause problems when performing text comparisons against columns
     * containing binary data. See the
     * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
     *
     * @param string $str  the string to be escaped
     *
     * @return string  the escaped string
     *
     * @since Method available since Release 1.6.1
     * @see DB_common::escapeSimple()
     */
    function escapeSimple($str)
    {
        return @sqlite_escape_string($str);
    }

    // }}}
    // {{{ modifyLimitQuery()

    /**
     * Adds LIMIT clauses to a query string according to current DBMS standards
     *
     * @param string $query   the query to modify
     * @param int    $from    the row to start to fetching (0 = the first row)
     * @param int    $count   the numbers of rows to fetch
     * @param mixed  $params  array, string or numeric data to be used in
     *                         execution of the statement.  Quantity of items
     *                         passed must match quantity of placeholders in
     *                         query:  meaning 1 placeholder for non-array
     *                         parameters or 1 placeholder per array element.
     *
     * @return string  the query string with LIMIT clauses added
     *
     * @access protected
     */
    function modifyLimitQuery($query, $from, $count, $params = array())
    {
        return "$query LIMIT $count OFFSET $from";
    }

    // }}}
    // {{{ modifyQuery()

    /**
     * Changes a query string for various DBMS specific reasons
     *
     * This little hack lets you know how many rows were deleted
     * when running a "DELETE FROM table" query.  Only implemented
     * if the DB_PORTABILITY_DELETE_COUNT portability option is on.
     *
     * @param string $query  the query string to modify
     *
     * @return string  the modified query string
     *
     * @access protected
     * @see DB_common::setOption()
     */
    function modifyQuery($query)
    {
        if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
            if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
                $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
                                      'DELETE FROM \1 WHERE 1=1', $query);
            }
        }
        return $query;
    }

    // }}}
    // {{{ sqliteRaiseError()

    /**
     * Produces a DB_Error object regarding the current problem
     *
     * @param int $errno  if the error is being manually raised pass a
     *                     DB_ERROR* constant here.  If this isn't passed
     *                     the error information gathered from the DBMS.
     *
     * @return object  the DB_Error object
     *
     * @see DB_common::raiseError(),
     *      DB_sqlite::errorNative(), DB_sqlite::errorCode()
     */
    function sqliteRaiseError($errno = null)
    {
        $native = $this->errorNative();
        if ($errno === null) {
            $errno = $this->errorCode($native);
        }

        $errorcode = @sqlite_last_error($this->connection);
        $userinfo = "$errorcode ** $this->last_query";

        return $this->raiseError($errno, null, null, $userinfo, $native);
    }

    // }}}
    // {{{ errorNative()

    /**
     * Gets the DBMS' native error message produced by the last query
     *
     * {@internal This is used to retrieve more meaningfull error messages
     * because sqlite_last_error() does not provide adequate info.}}
     *
     * @return string  the DBMS' error message
     */
    function errorNative()
    {
        return $this->_lasterror;
    }

    // }}}
    // {{{ errorCode()

    /**
     * Determines PEAR::DB error code from the database's text error message
     *
     * @param string $errormsg  the error message returned from the database
     *
     * @return integer  the DB error number
     */
    function errorCode($errormsg)
    {
        static $error_regexps;

        // PHP 5.2+ prepends the function name to $php_errormsg, so we need
        // this hack to work around it, per bug #9599.
        $errormsg = preg_replace('/^sqlite[a-z_]+\(\): /', '', $errormsg);

        if (!isset($error_regexps)) {
            $error_regexps = array(
                '/^no such table:/' => DB_ERROR_NOSUCHTABLE,
                '/^no such index:/' => DB_ERROR_NOT_FOUND,
                '/^(table|index) .* already exists$/' => DB_ERROR_ALREADY_EXISTS,
                '/PRIMARY KEY must be unique/i' => DB_ERROR_CONSTRAINT,
                '/is not unique/' => DB_ERROR_CONSTRAINT,
                '/columns .* are not unique/i' => DB_ERROR_CONSTRAINT,
                '/uniqueness constraint failed/' => DB_ERROR_CONSTRAINT,
                '/may not be NULL/' => DB_ERROR_CONSTRAINT_NOT_NULL,
                '/^no such column:/' => DB_ERROR_NOSUCHFIELD,
                '/column not present in both tables/i' => DB_ERROR_NOSUCHFIELD,
                '/^near ".*": syntax error$/' => DB_ERROR_SYNTAX,
                '/[0-9]+ values for [0-9]+ columns/i' => DB_ERROR_VALUE_COUNT_ON_ROW,
            );
        }
        foreach ($error_regexps as $regexp => $code) {
            if (preg_match($regexp, $errormsg)) {
                return $code;
            }
        }
        // Fall back to DB_ERROR if there was no mapping.
        return DB_ERROR;
    }

    // }}}
    // {{{ tableInfo()

    /**
     * Returns information about a table
     *
     * @param string         $result  a string containing the name of a table
     * @param int            $mode    a valid tableInfo mode
     *
     * @return array  an associative array with the information requested.
     *                 A DB_Error object on failure.
     *
     * @see DB_common::tableInfo()
     * @since Method available since Release 1.7.0
     */
    function tableInfo($result, $mode = null)
    {
        if (is_string($result)) {
            /*
             * Probably received a table name.
             * Create a result resource identifier.
             */
            $id = @sqlite_array_query($this->connection,
                                      "PRAGMA table_info('$result');",
                                      SQLITE_ASSOC);
            $got_string = true;
        } else {
            $this->last_query = '';
            return $this->raiseError(DB_ERROR_NOT_CAPABLE, null, null, null,
                                     'This DBMS can not obtain tableInfo' .
                                     ' from result sets');
        }

        if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
            $case_func = 'strtolower';
        } else {
            $case_func = 'strval';
        }

        $count = count($id);
        $res   = array();

        if ($mode) {
            $res['num_fields'] = $count;
        }

        for ($i = 0; $i < $count; $i++) {
            if (strpos($id[$i]['type'], '(') !== false) {
                $bits = explode('(', $id[$i]['type']);
                $type = $bits[0];
                $len  = rtrim($bits[1],')');
            } else {
                $type = $id[$i]['type'];
                $len  = 0;
            }

            $flags = '';
            if ($id[$i]['pk']) {
                $flags .= 'primary_key ';
            }
            if ($id[$i]['notnull']) {
                $flags .= 'not_null ';
            }
            if ($id[$i]['dflt_value'] !== null) {
                $flags .= 'default_' . rawurlencode($id[$i]['dflt_value']);
            }
            $flags = trim($flags);

            $res[$i] = array(
                'table' => $case_func($result),
                'name'  => $case_func($id[$i]['name']),
                'type'  => $type,
                'len'   => $len,
                'flags' => $flags,
            );

            if ($mode & DB_TABLEINFO_ORDER) {
                $res['order'][$res[$i]['name']] = $i;
            }
            if ($mode & DB_TABLEINFO_ORDERTABLE) {
                $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
            }
        }

        return $res;
    }

    // }}}
    // {{{ getSpecialQuery()

    /**
     * Obtains the query string needed for listing a given type of objects
     *
     * @param string $type  the kind of objects you want to retrieve
     * @param array  $args  SQLITE DRIVER ONLY: a private array of arguments
     *                       used by the getSpecialQuery().  Do not use
     *                       this directly.
     *
     * @return string  the SQL query string or null if the driver doesn't
     *                  support the object type requested
     *
     * @access protected
     * @see DB_common::getListOf()
     */
    function getSpecialQuery($type, $args = array())
    {
        if (!is_array($args)) {
            return $this->raiseError('no key specified', null, null, null,
                                     'Argument has to be an array.');
        }

        switch ($type) {
            case 'master':
                return 'SELECT * FROM sqlite_master;';
            case 'tables':
                return "SELECT name FROM sqlite_master WHERE type='table' "
                       . 'UNION ALL SELECT name FROM sqlite_temp_master '
                       . "WHERE type='table' ORDER BY name;";
            case 'schema':
                return 'SELECT sql FROM (SELECT * FROM sqlite_master '
                       . 'UNION ALL SELECT * FROM sqlite_temp_master) '
                       . "WHERE type!='meta' "
                       . 'ORDER BY tbl_name, type DESC, name;';
            case 'schemax':
            case 'schema_x':
                /*
                 * Use like:
                 * $res = $db->query($db->getSpecialQuery('schema_x',
                 *                   array('table' => 'table3')));
                 */
                return 'SELECT sql FROM (SELECT * FROM sqlite_master '
                       . 'UNION ALL SELECT * FROM sqlite_temp_master) '
                       . "WHERE tbl_name LIKE '{$args['table']}' "
                       . "AND type!='meta' "
                       . 'ORDER BY type DESC, name;';
            case 'alter':
                /*
                 * SQLite does not support ALTER TABLE; this is a helper query
                 * to handle this. 'table' represents the table name, 'rows'
                 * the news rows to create, 'save' the row(s) to keep _with_
                 * the data.
                 *
                 * Use like:
                 * $args = array(
                 *     'table' => $table,
                 *     'rows'  => "id INTEGER PRIMARY KEY, firstname TEXT, surname TEXT, datetime TEXT",
                 *     'save'  => "NULL, titel, content, datetime"
                 * );
                 * $res = $db->query( $db->getSpecialQuery('alter', $args));
                 */
                $rows = strtr($args['rows'], $this->keywords);

                $q = array(
                    'BEGIN TRANSACTION',
                    "CREATE TEMPORARY TABLE {$args['table']}_backup ({$args['rows']})",
                    "INSERT INTO {$args['table']}_backup SELECT {$args['save']} FROM {$args['table']}",
                    "DROP TABLE {$args['table']}",
                    "CREATE TABLE {$args['table']} ({$args['rows']})",
                    "INSERT INTO {$args['table']} SELECT {$rows} FROM {$args['table']}_backup",
                    "DROP TABLE {$args['table']}_backup",
                    'COMMIT',
                );

                /*
                 * This is a dirty hack, since the above query will not get
                 * executed with a single query call so here the query method
                 * will be called directly and return a select instead.
                 */
                foreach ($q as $query) {
                    $this->query($query);
                }
                return "SELECT * FROM {$args['table']};";
            default:
                return null;
        }
    }

    // }}}
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 */

?>


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace PSWinCom.Gateway.Client
{
    public static partial class Gateway
    {
        public static string DefaultAddress
        {
            get { return Factory.DefaultAddress; }
            set { Factory.DefaultAddress = value; }
        }

        public static string DefaultUsername
        {
            get { return Factory.DefaultUsername; }
            set { Factory.DefaultUsername = value; }
        }

        public static string DefaultPassword
        {
            get { return Factory.DefaultPassword; }
            set { Factory.DefaultPassword = value; }
        }

        public static IAsyncGatewayClient Client()
        {
            return (IAsyncGatewayClient)Factory.Client();
        }

        public static IAsyncGatewayClient Client(string username, string password)
        {
            return (IAsyncGatewayClient)Factory.Client(username, password);
        }

        public static IAsyncGatewayClient Client(string uri)
        {
            return (IAsyncGatewayClient)Factory.Client(uri);
        }

        public static IAsyncGatewayClient Client(string uri, string username, string password)
        {
            return (IAsyncGatewayClient)Factory.Client(uri, username, password);
        }

        public static IAsyncGatewayClient Client(Uri uri, string username, string password)
        {
            return (IAsyncGatewayClient)Factory.Client(uri, username, password);
        }

        public static IAsyncGatewayClient Client(Uri uri)
        {
            return (IAsyncGatewayClient)Factory.Client(uri);
        }
    }
}


text:
<!DOCTYPE html>

		<title>three.js webgl - raycast - sprite</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

three.js - webgl raycast sprite


text:
package molecule
package channel

import java.util.{ concurrent => juc }

/**
 * Trait for non-blocking system-level input channels.
 *
 * @tparam A The type of messages.
 */
trait IChan[+A] {

  /**
   * Read a segment from this channel.
   *
   * @param k the continuation taking the last segment read as parameter
   *          and the seed on which to read subsequent segments.
   * @return Unit
   */
  def read(k: (Seg[A], IChan[A]) => Unit): Unit

  /**
   * Poison this channel and any segment it may have buffered.
   *
   * @param signal the poison signal.
   * @return Unit
   */
  def poison(signal: Signal): Unit

}

object IChan {

  private[this] val IChanIsPoisonable = new Message[IChan[Any]] {
    def poison(message: IChan[Any], signal: Signal): Unit = {
      message.poison(signal)
    }
  }

  implicit def ichanIsMessage[A]: Message[IChan[A]] = IChanIsPoisonable

  case class Nil(val signal: Signal) extends IChan[Nothing] {

    def read(k: (Seg[Nothing], IChan[Nothing]) => Unit): Unit =
      throw new Error("Cannot read on NilChan:" + signal)

    def poison(signal: Signal): Unit = {}

  }

  def unapply(ichan: IChan[_]): Option[Signal] =
    if (ichan.isInstanceOf[Nil])
      Some(ichan.asInstanceOf[Nil].signal)
    else
      None

  private[this] final val eos = new Nil(EOS)

  /**
   * Construct a input channel that terminates immediately with a signal
   *
   *  @param signal the termination signal.
   *  @tparam       A the type of the messages carried by the input channel.
   *  @return An input channel that terminates immediately.
   */
  def empty[A](signal: Signal): IChan[A] = signal match {
    case EOS => eos
    case _ => new Nil(signal)
  }

  /**
   * Construct a input channel that terminates immediately with EOS
   *
   *  @param signal the termination signal.
   *  @tparam       A the type of the messages carried by the input channel.
   *  @return An input channel that terminates immediately.
   */
  def empty[A]: IChan[A] = empty(EOS)

  /**
   * Create an input channel that generates data lazily out of
   * main memory.
   *
   * @param  a    the first message read on the channel.
   * @param  tail the remainder of the channel.
   * @tparam A    the type of the messages carried by the input channel.
   * @return an input channel with a segment prepended.
   *
   */
  def apply[A: Message](a: A, tail: => IChan[A]): IChan[A] =
    IChan.cons(Seg(a), tail)

  /**
   * Create a channel that returns a single segment.
   *
   * @param  seg    the segment read on the channel.
   * @param  signal the termination signal.
   * @tparam A    the type of the messages carried by the input channel.
   * @return an input channel that contains a single segment.
   */
  def apply[A: Message](seg: Seg[A], signal: Signal): IChan[A] =
    IChan.cons_!(seg, IChan.empty(signal))

  /**
   * Create a, input channel that generates data lazily out of
   * main memory.
   *
   * @param  seg the segment to prepend to the channel.
   * @param  tail the original input channel.
   * @tparam A the type of the messages carried by the input channel.
   * @return an input channel with a segment prepended.
   */
  def cons[A: Message](seg: Seg[A], tail: => IChan[A]): IChan[A] = new IChan[A] {

    def read(k: (Seg[A], IChan[A]) => Unit): Unit =
      k(seg, tail)

    def poison(signal: Signal): Unit =
      seg.poison(signal)
    // No need to poison the tail since it has not been evaluated.

  }

  /**
   * Prepend a segment in front of an existing input channel.
   *
   * @param  seg the segment to prepend to the channel.
   * @param  tail the original input channel.
   * @tparam A the type of the messages carried by the input channel.
   * @return an input channel with a segment prepended.
   */
  def cons_![A: Message](seg: Seg[A], tail: IChan[A]): IChan[A] = new IChan[A] {

    def read(k: (Seg[A], IChan[A]) => Unit): Unit =
      k(seg, tail)

    def poison(signal: Signal): Unit = {
      seg.poison(signal)
      tail.poison(signal)
    }
  }

  def bind[A: Message](first: IChan[A], next: (A, Signal) => IChan[A]): IChan[A] = {
    def _bind(last: A, ichan: IChan[A]): IChan[A] = new IChan[A] {
      def read(k: (Seg[A], IChan[A]) => Unit): Unit =
        first.read((seg, ichan) => ichan match {
          case IChan(signal) =>
            if (seg.isEmpty) k(Seg(last), next(last, signal))
            else k(seg, next(seg.last, signal))
          case _ =>
            if (seg.isEmpty) k(Seg(), _bind(last, ichan))
            else k(last +: seg.init, _bind(seg.last, ichan))
        })

      def poison(signal: Signal): Unit = {
        Message.poison(last, signal)
        ichan.poison(signal)
      }
    }

    new IChan[A] {
      def read(k: (Seg[A], IChan[A]) => Unit): Unit =
        first.read((seg, ichan) => ichan match {
          case IChan(signal) =>
            if (seg.isEmpty) k(Seg(), ichan)
            else k(seg, next(seg.last, signal))
          case _ =>
            if (seg.isEmpty) k(Seg(), bind(ichan, next))
            else k(seg.init, _bind(seg.last, ichan))
        })

      def poison(signal: Signal): Unit =
        first.poison(signal)
    }
  }

  @inline
  private[this] final def SST = platform.Platform.segmentSizeThreshold

  /**
   * Create an infinite stream starting at start
   * and incrementing by step step
   *
   * @param start the start value of the stream
   * @param step the increment value of the stream
   * @return the stream starting at value start.
   */
  def from(start: Int, step: Int): IChan[Int] = {
    // note: end limit of range is exclusive
    val end = start + SST * step
    IChan.cons(Seg.wrap(Range(start, end, step)), from(end, step))
  }

  /**
   * Create an infinite stream starting at start
   * and incrementing by 1.
   *
   * @param start the start value of the stream
   * @return the stream starting at value start.
   */
  def from(start: Int): IChan[Int] = {
    val end = start + SST
    IChan.cons(Seg.wrap(Range(start, end)), from(end))
  }

  /**
   * An infinite stream that repeatedly applies a given function to a start value.
   *
   *  @param start the start value of the stream
   *  @param f     the function that's repeatedly applied
   *  @return      the stream returning the infinite sequence of values `start, f(start), f(f(start)), ...`
   */
  def iterate[A: Message](start: A)(f: A => A): IChan[A] = {

    def loop(n: Int, start: A, batch: Seg[A]): (Seg[A], A) = {
      if (n == 0) {
        (batch, start)
      } else {
        val next = f(start)
        loop(n - 1, next, batch :+ next)
      }
    }
    val (seg, next) = loop(SST, start, Seg.empty[A])

    IChan.cons(seg, iterate(next)(f))
  }

  /**
   * Create an infinite stream containing the given element expression (which is computed for each
   * occurrence)
   *
   * @param elem the element composing the resulting stream
   * @return the stream containing an infinite number of elem
   * // TODO add iterator seg
   */
  def continually[A: Message](elem: => A): IChan[A] =
    IChan.cons(Seg.wrap(Vector.fill(SST)(elem)), continually(elem))

  /**
   * Create an infinite stream containing the given element expression
   * which is computed at the time the channel is read. Contrarily
   * to `continually`, this channels emits one message at a time.
   *
   * @param elem the element composing the resulting stream
   * @return the stream containing an infinite number of elem
   */
  def lazily[A](elem: => A): IChan[A] = new IChan[A] {
    def read(k: (Seg[A], IChan[A]) => Unit): Unit =
      k(Seg(elem), this)
    def poison(signal: Signal): Unit = {}
  }

  /**
   * Create an stream of fixed size containing the given element expression
   * which is computed at the time the channel is read
   *
   * @param elem the element composing the resulting stream
   * @return the stream containing an infinite number of elem
   */
  def fill[A: Message](n: Int)(elem: => A): IChan[A] =
    if (n == 0)
      IChan.empty(EOS)
    else if (n <= SST)
      IChan(Seg.wrap(Vector.fill(n)(elem)), EOS)
    else
      IChan.cons(Seg.wrap(Vector.fill(SST)(elem)), fill(n - SST)(elem))

  /**
   * Produces a stream containing values of a given function over a range of integer values starting from 0.
   * @param n The number of elements to generate.
   * @param f The function computing element values
   * @return A new stream consisting of elements `f(0), ..., f(n -1)`
   */
  def tabulate[A: Message](n: Int)(f: Int => A): IChan[A] = {
    if (n == 0)
      IChan.empty(EOS)
    else if (n <= SST)
      IChan(Seg.wrap(Vector.tabulate(n)(f)), EOS)
    else
      IChan.cons(Seg.wrap(Vector.tabulate(SST)(f)), tabulate(n - SST)(f))
  }

  import java.util.concurrent.TimeUnit

  /**
   * Creates a stream with the specified elements.
   * @tparam A the type of the stream's elements
   * @param a the first elements of the created stream
   * @param as the remaining elements of the created stream
   * @return a new stream with the elements passed as parameters
   */
  def apply[A: Message](a: A, as: A*): IChan[A] =
    IChan.source(a +: as.toSeq)

  def apply(r: Range): IChan[Int] =
    IChan.source(r)

  def source[A: Message](as: Traversable[A], sst: Int = SST): IChan[A] = {
    require(sst > 0, "batch size must be greater than 0")
    _source(as, sst min SST)
  }

  private[this] def _source[A: Message](as: Traversable[A], mss: Int): IChan[A] = {
    val (a, b) = as.splitAt(mss)
    if (b.isEmpty)
      IChan(Seg.wrap(a), EOS)
    else
      IChan.cons(Seg.wrap(a), _source(b, mss))
  }

}


text:
package net.sleworks.morp.repository.exceptions;

public class NotValidRepositoryObject extends MoRPRepositoryRuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = -1126117599952816564L;

}


text:
using Microsoft.Win32;
using System;
using System.IO;

namespace LauncherWPF.Management
{

    /// <summary>
    ///     Assists with locating Roller Coaster Tycoon 2's installation folder.
    /// </summary>
    public static class RctLocator
    {

        /// <summary>
        ///     Attempts to find the RCT2 installation directory.
        /// </summary>
        /// <returns><see cref="string"/> that points to the exact location where RCT2 is installed.</returns>
        public static string DiscoverRct2InstallationDirectory()
        {
            const string SteamDisplayName = @"Steam";
            const string Rct2DisplayName = @"RollerCoaster Tycoon 2";
            const string NonWowRegistryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            const string WowRegistryKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";

            // We'll check WOW path first; it's the most likely suspect.
            // If we don't find it there, we'll check the Non-WOW path. I highly doubt
            // that we'd see it there. However, I'd rather be thorough than not check well enough.
            var explorer = new RegistryExplorer();

            // Here's where magic begins.
            string rctPath, steamPath;

            // Search the WOW key area.
            rctPath = explorer.SearchForInstallPath(NonWowRegistryKey, Rct2DisplayName);
            if (!string.IsNullOrWhiteSpace(rctPath)) return rctPath;

            // Search the non-WOW key area.
            rctPath = explorer.SearchForInstallPath(WowRegistryKey, Rct2DisplayName);
            if (!string.IsNullOrWhiteSpace(rctPath)) return rctPath;

            // Well... okay. Maybe it's a Steam game?
            // Let's try searching for Steam.
            steamPath = explorer.SearchForInstallPath(NonWowRegistryKey, SteamDisplayName);
            if (!string.IsNullOrWhiteSpace(steamPath))
            {
                rctPath = TryToFindRct2PathViaSteam(steamPath);
                if (!string.IsNullOrWhiteSpace(rctPath)) return rctPath;
            }
            steamPath = explorer.SearchForInstallPath(WowRegistryKey, SteamDisplayName);
            if (!string.IsNullOrWhiteSpace(steamPath))
            {
                rctPath = TryToFindRct2PathViaSteam(steamPath);
                if (!string.IsNullOrWhiteSpace(rctPath)) return rctPath;
            }
            return null;
        }

        private static string TryToFindRct2PathViaSteam(string steamDirectory)
        {
            // steamdirectory should be the root of Steam where Steam.exe lives.
            // So, we need to go into the config directory and find config.vdf!
            // config.vdf contains a few lines we shall need:
            // "BaseInstallFolder_1" "J:\\Steam Games"
            // "BaseInstallFolder_2" "Blah"
            // ...
            // We need each one of those BaseInstallFolder values.
            // Fuck writing a proper parser. I'm just gonna go ham and do this
            // line-by-line.
            var configVdf = Path.Combine(steamDirectory, "config", "config.vdf");
            if (!File.Exists(configVdf)) return null; // fuck this shit I'm out.

            // Before we go reading the config.vdf for additional installation folders, let's check the current one!
            string rct2Path;
            rct2Path = CheckSteamInstallFolderForRct2(Path.Combine(steamDirectory, "SteamApps"));
            if (!string.IsNullOrWhiteSpace(rct2Path)) return rct2Path;

            string currentLine;
            using (var sr = new StreamReader(configVdf))
            {
                while ((currentLine = sr.ReadLine()) != null)
                {
                    if (currentLine.IndexOf("BaseInstallFolder") == -1) continue;
                    currentLine = currentLine.Trim();

                    // split on tabs. It appears to be tab indented currently.
                    // This might be a bad idea instead of manually processing the line.
                    // We can always resort to that in later patches.
                    var lineArray = currentLine.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    var installFolder = Path.Combine(lineArray[1].Trim('\"').Replace(@"\\", "\\"), "SteamApps");
                    rct2Path = CheckSteamInstallFolderForRct2(installFolder);
                    if (!string.IsNullOrWhiteSpace(rct2Path)) return rct2Path;

                }
            }
            return null;
        }

        private static string CheckSteamInstallFolderForRct2(string installFolder)
        {
            // The SteamApps folder contains .acf files. These .acf files
            // contain the metadata that we need about the games installed
            // in the passed in folder. We need the "installdir" key.
            // This "installdir" key, when combined iwth installFolder
            // is the exact directory where the game is installed.
            foreach (var acfFile in Directory.GetFiles(installFolder, "*.acf"))
            {
                var needInstallDir = false;
                string currentLine;
                using (var sr = new StreamReader(acfFile))
                {
                    while ((currentLine = sr.ReadLine()) != null)
                    {
                        if (needInstallDir && currentLine.IndexOf("installdir", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            var lineArray = currentLine.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                            return Path.Combine(installFolder, lineArray[1].Trim('\"'));
                        }
                        if (currentLine.IndexOf("name") > -1 && (currentLine.IndexOf("rollercoaster tycoon 2", StringComparison.OrdinalIgnoreCase) > -1 || currentLine.IndexOf("roller coaster tycoon 2", StringComparison.OrdinalIgnoreCase) > -1))
                        {
                            needInstallDir = true;
                        }
                    }
                }
            }
            return null;
        }

        /// <summary>
        ///     Navigates a registry key.
        /// </summary>
        internal sealed class RegistryExplorer
        {

            /// <summary>
            ///     Searches the subkey collection for <paramref name="displayName"/>
            /// </summary>
            /// <param name="displayName">The display name of the item to search for.</param>
            /// <param name="comparison">The <see cref="StringComparison"/> type to use when doing checking</param>
            /// <returns></returns>
            public string SearchForInstallPath(string key, string displayName, StringComparison comparison = StringComparison.OrdinalIgnoreCase)
            {
                using (var regKey = Registry.LocalMachine.OpenSubKey(key))
                {
                    foreach (var subKeyName in regKey.GetSubKeyNames())
                    {
                        using (var subKey = regKey.OpenSubKey(subKeyName))
                        {
                            var keyNameObj = subKey.GetValue("DisplayName");
                            if (keyNameObj == null) continue; // null check in case this key doesn't have "DisplayName".
                            var keyName = keyNameObj.ToString();
                            if (keyName.IndexOf(displayName, comparison) == -1) continue; // skip this key if we don't find displayName.

                            // We've got a couple different keys that this could work.
                            var installedPathObj = subKey.GetValue("InstalledPath");
                            if (installedPathObj != null) return installedPathObj.ToString();
                            installedPathObj = subKey.GetValue("InstallLocation");
                            if (installedPathObj != null) return installedPathObj.ToString();
                            installedPathObj = subKey.GetValue("UninstallString");
                            if (installedPathObj != null)
                            {
                                var uninstallPath = installedPathObj.ToString();

                                // ToDo: Make this more optimized. In theory, this could potentially
                                // cause a ton of string allocations if the foreach loop must be run
                                // and there are a lot of invalid charaters. Let's actively consider
                                // how to make this better in the future. For a prototype/version 1
                                // this will "work".
                                if (uninstallPath.IndexOfAny(Path.GetInvalidPathChars()) > -1)
                                    foreach (var invalidChar in Path.GetInvalidPathChars())
                                        uninstallPath = uninstallPath.Replace(invalidChar.ToString(), string.Empty);

                                return Path.GetDirectoryName(uninstallPath);
                            }
                        }
                    }
                }
                return null;
            }

        }

    }
}


text:
using System;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Collections.ObjectModel;
using System.Web.Http.Filters;
using Bmz.Framework.Collections.Extensions;

namespace Bmz.Framework.WebApi.Controllers.Dynamic.Selectors
{
    /// <summary>
    /// This class is used to extend the default controller descriptor to add the action filters dynamically.
    /// </summary>
    public class DynamicHttpControllerDescriptor : HttpControllerDescriptor
    {
        /// <summary>
        /// The Dynamic Controller Action filters.
        /// </summary>
        private readonly IFilter[] _filters;

        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicHttpControllerDescriptor"/> class. Add the argument for action filters to the controller.
        /// </summary>
        /// <param name="configuration">The Http Configuration.</param>
        /// <param name="controllerName"> The controller name.</param>
        /// <param name="controllerType">The controller type.</param>
        /// <param name="filters">The Dynamic Controller action filters.</param>
        public DynamicHttpControllerDescriptor(HttpConfiguration configuration, string controllerName, Type controllerType, IFilter[] filters = null)
            : base(configuration, controllerName, controllerType)
        {
            _filters = filters;
        }

        /// <summary>
        /// The overrides the GetFilters for the controller and adds the Dynamic Controller filters.
        /// </summary>
        /// <returns> The Collection of filters.</returns>
        public override Collection<IFilter> GetFilters()
        {
            if (_filters.IsNullOrEmpty())
            {
                return base.GetFilters();
            }

            var actionFilters = new Collection<IFilter>();

            foreach (var filter in _filters)
            {
                actionFilters.Add(filter);
            }

            foreach (var baseFilter in base.GetFilters())
            {
                actionFilters.Add(baseFilter);
            }

            return actionFilters;
        }
    }
}


text:
package org.apache.servicemix.jbi.runtime.impl.utils;

import java.io.ByteArrayInputStream;

import javax.xml.namespace.QName;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import junit.framework.TestCase;

public class DOMUtilTest extends TestCase {

    public void testNewDoc() throws Exception  {
        Document doc = DOMUtil.newDocument();
        assertNotNull(doc);
    }

    public void testDoc() throws Exception {
        String xml = "<root><hello>world</hello></root>";
        Document doc = DOMUtil.parseDocument(new ByteArrayInputStream(xml.getBytes()));
        assertNotNull(doc);
        assertNotNull(doc.getDocumentElement().getFirstChild());
        Element e = DOMUtil.getFirstChildElement(doc.getDocumentElement());
        assertEquals("world", DOMUtil.getElementText(e));
        assertEquals(new QName("hello"), DOMUtil.getQName(e));
    }

}


text:
<?php

namespace Addy\PageBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * LivePage
 * @Orm\MappedSuperclass
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Addy\PageBundle\Entity\LivePageRepository")
 */
class LivePage extends Page
{

    /**
     * @ORM\OneToMany(targetEntity="Addy\PageBundle\Entity\Content", mappedBy="page", cascade="persist")
     */
    private $contents;

     public function __construct()
    {
        $this->contents = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Remove contents
     *
     * @param \Homepan\PageBundle\Entity\Content $contents
     */
    public function removeContent(\Addy\PageBundle\Entity\Content $contents)
    {
        $this->contents->removeElement($contents);
    }

    /**
     * Get contents
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getContents()
    {
        return $this->contents;
    }
}


text:
require "faraday"
require "faraday_middleware"
require "rack/utils"

class ThetvdbApi::Base
  def initialize(options = {})
    @options = options
    @connection = build_connection
  end

  private

  attr_reader :connection, :options

  def build_connection
    connection = Faraday.new(url: base_url)
    connection.response :xml, content_type: /\bxml$/
    setup_adapter(connection)
    connection
  end

  def setup_adapter(connection)
    connection.adapter(options[:adapter] || :net_http)
  end

  def get(uri, query = {})
    connection.get(uri, query)
  end

  def build_query(**params)
    query = Rack::Utils.build_query(params.select{ |_, value| !value.nil? })
    return if query.size == 0
    "?#{query}"
  end

  def base_url
    "http://thetvdb.com/api/"
  end
end


text:
title: Week 26
layout: post
author: tom.vicary
permalink: /week-26/
source-id: 1DtbxRLZ3zOLBMwVVeuTqSBfiz5yeA_KZllMki_M7grY
published: true
---

    Title
    Monday 6th March 2017
    Date
    6/3/17

    Starting point:
    23% of codecademy

    Target for this lesson?
    To finish Conditionals & Control flow lesson

    Did I reach my target?
(add details to "Lesson Review")
     Yes. I finished the lesson and started pyglatin

    Lesson Review

    How did I learn? What strategies were effective?

    As usual I read the instructions and description thoroughly to add to my understanding of the subject

    What limited my learning? Which habits do I need to work on?

    I need to stop worrying about how far other people are through their course and concentrating more on completing exercises.

    What will I change for next time? How will I improve my learning?

    I will try to work quicker. For the last two lessons I have been stuck on the same lesson and now I understand that I can ask other people for help and to give me hints


text:
package uk.gov.phe.erdst.sc.awag.service.export;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import com.opencsv.CSVWriter;

import uk.gov.phe.erdst.sc.awag.businesslogic.ActivityLogController;
import uk.gov.phe.erdst.sc.awag.datamodel.ActivityLog;
import uk.gov.phe.erdst.sc.awag.exceptions.AWInputValidationException;
import uk.gov.phe.erdst.sc.awag.service.activitylogging.LoggedActions;
import uk.gov.phe.erdst.sc.awag.service.activitylogging.LoggedActivity;
import uk.gov.phe.erdst.sc.awag.service.activitylogging.LoggedUser;
import uk.gov.phe.erdst.sc.awag.service.validation.utils.ValidatorUtils;
import uk.gov.phe.erdst.sc.awag.utils.Constants;
import uk.gov.phe.erdst.sc.awag.utils.WebApiUtils;
import uk.gov.phe.erdst.sc.awag.webapi.request.PagingQueryParams;

@RequestScoped
public class ActivityLogExporter
{
    private static final String DOWNLOAD_STATUS_COOKIE_NAME = "activityLogDownloadStatus";
    private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(Constants.OUTPUT_DATE_FORMAT);

    @Inject
    private ActivityLogController mActivityLogController;

    @Inject
    private Validator mValidator;

    @LoggedActivity(actionName = LoggedActions.EXPORT_ACTIVITY_LOGS)
    public void exportData(String dateFrom, String dateTo, PagingQueryParams pagingParams,
        HttpServletResponse response, LoggedUser loggedUser) throws IOException, AWInputValidationException
    {
        ValidatorUtils.validateOptionalDateParameters(dateFrom, dateTo);

        Set<ConstraintViolation<PagingQueryParams>> pagingParamsViolations = new HashSet<>(0);
        boolean isPagingParamsSet = pagingParams.isParamsSet();

        if (isPagingParamsSet)
        {
            pagingParamsViolations = mValidator.validate(pagingParams);
        }

        if (pagingParamsViolations.isEmpty())
        {
            Integer offset = isPagingParamsSet ? pagingParams.offset : null;
            Integer limit = isPagingParamsSet ? pagingParams.limit : null;

            List<ActivityLog> logs = mActivityLogController.getActivityLogsBetween(dateFrom, dateTo, offset, limit);

            String fileName = getCsvFileName();

            WebApiUtils.setContentTypeToCsv(response);
            WebApiUtils.setContentDispositionHeader(response, fileName);

            writeCsv(logs, fileName, response.getOutputStream());
        }

    }

    public String getDownloadStatusCookieName()
    {
        return DOWNLOAD_STATUS_COOKIE_NAME;
    }

    public String getDownloadStatusCookieValue()
    {
        return Constants.WebApi.DEFAULT_DOWNLOAD_STATUS_COOKIE_VALUE;
    }

    public int getDownloadStatusCookieExpirationTimeSeconds()
    {
        return Constants.WebApi.DEFAULT_DOWNLOAD_STATUS_COOKIE_EXPIRATION_TIME_SEC;
    }

    private String getCsvFileName()
    {
        String date = DATE_FORMATTER.format(new Date(System.currentTimeMillis()));
        return String.format("%s-%s-%s.csv", Constants.OUTPUT_FILES_PREFIX, "activity-logs", date);
    }

    private void writeCsv(List<ActivityLog> logs, String fileName, OutputStream output) throws IOException
    {
        BufferedWriter buffWriter = new BufferedWriter(new OutputStreamWriter(output, Constants.OUTPUT_ENCODING_UTF_8));
        CSVWriter csvWriter = new CSVWriter(buffWriter);

        // Column headers
        csvWriter.writeNext(new String[] {"Date and time", "Action", "Username"});

        for (ActivityLog log : logs)
        {
            String[] entries = new String[] {log.getDateTime(), log.getAction(), log.getUsername()};
            csvWriter.writeNext(entries);
        }

        csvWriter.close();
    }
}


text:
class TrainHookCollection:
    def __init__(self, gan):
        self.gan = gan

    def augment_latent(self, latent):
        for hook in self.gan.hooks:
            latent = hook.augment_latent(latent)
        return latent

    def augment_x(self, x):
        for hook in self.gan.hooks:
            x = hook.augment_x(x)
        return x

    def augment_g(self, g):
        for hook in self.gan.hooks:
            g = hook.augment_g(g)
        return g


text:
<?php

/**
 *
 * @author Janis Heller (janis@heller.pw)
 *
 */

class CoiniPw
{
    private $api_key;

    public function __construct($api_key)
    {
        $this->api_key = $api_key;
        if(strlen($this->api_key) != 64)
            throw new Exception("API key invalid!");
    }

    public function getNewAddress(){
        try{
            $json = json_decode(file_get_contents('https://coini.pw/api/v2/get_new_address?api_key=' . $this->api_key));
        }
        catch(Exception $e){
            throw new Exception("Cannot establish connection!");
        }

        if (!isset($json->errors))
            return $json;
        else
            throw new Exception($json->errors->message);
    }
}
?>


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct output_fun</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../utilities.html#header.boost.log.utility.functional.bind_output_hpp" title="Header <boost/log/utility/functional/bind_output.hpp>">
<link rel="prev" href="bind_assign.html" title="Function template bind_assign">
<link rel="next" href="bind_output.html" title="Function template bind_output">

Struct output_fun

boost::log::output_fun — The function object that outputs its second operand to the first one.

Synopsis

// In header: <boost/log/utility/functional/bind_output.hpp>

struct output_fun {
  // types
  typedef void result_type;

  // public member functions
  template<typename StreamT, typename T>
    void operator()(StreamT &, T const &) const;
};

Description

output_fun public member functions

template<typename StreamT, typename T>
  void operator()(StreamT & strm, T const & val) const;

Copyright © 2007-2016 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).