text:
// Copyright 2022 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0

package org.terasology.engine.physics.engine;

import org.joml.Vector3fc;
import org.terasology.engine.entitySystem.entity.EntityRef;
import org.terasology.engine.physics.CollisionGroup;
import org.terasology.engine.physics.Physics;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * The physics engine provides access to physics functionality like ray tracing.
 *

 * TODO: Move physics methods that should only be used by the engine/physics implementing system into another interface that inherits this.
 *
 */
public interface PhysicsEngine extends Physics {
    float GRAVITY = 15f;

    /**
     * Wakes up any rigid bodies that are in a box around the given position.
     *
     * @param pos    The position around which to wake up objects.
     * @param radius the half-length of the sides of the square.
     */
    void awakenArea(Vector3fc pos, float radius);

    /**
     * Combines the flags of the given collision groups into a single flag.
     *
     * @param groups
     * @return A single flag representing all the given groups.
     */
    short combineGroups(CollisionGroup... groups);

    /**
     * Combines the flags of the given collision groups into a single flag.
     *
     * @param groups
     * @return A single flag representing all the given groups.
     */
    short combineGroups(Iterable<CollisionGroup> groups);

    /**
     * Disposes this physics engine. Afterwards this physics engine cannot be
     * used anymore.
     */
    void dispose();

    /**
     * Return a list with all CollisionPairs created since the last call to this
     * method. A collisionPair is created when a Trigger hits an other object.
     * Therefore, one of the entities in the CollisionPair should have a Trigger
     * attached to it.
     *
     * @return A newly allocated list with all pairs of entities that collided.
     */
    List<PhysicsSystem.CollisionPair> getCollisionPairs();

    /**
     * The epsilon value is the value that is considered to be so small that it
     * could just as well be zero. Objects that are closer together than this
     * value are assumes to be colliding.
     *
     * @return The simulation epsilon.
     */
    float getEpsilon();

    /**
     * @return A set with all entities that have a rigidBody that is active in
     *         the physics engine. A new set is created that is not backed by this class.
     */
    Set<EntityRef> getPhysicsEntities();

    /**
     * Get the character collider for the given entity. Will create a new
     * CharacterCollider if non exists and return that one.
     *
     * @param entity
     * @return true if the given entity has a CharacterCollider associated to it.
     */
    CharacterCollider getCharacterCollider(EntityRef entity);

    /**
     * Returns the rigid body associated with the given entity. If no such
     * RigidBody exists, a new one is created and returned.
     *

     * Note that you should not wait with calling this method until using the
     * rigid body. As soon as the rigid body should exist in the physics engine,
     * this method should be called to create the rigid body.
     *
     * @param entity the entity to retrieve the rigid body of.
     * @return A valid RigidBody instance.
     * @throws IllegalArgumentException if there is no RigidBody in this
     *                                  PhysicsEngine for the given entity and one cannot be created because the
     *                                  given entity does not have a LocationComponent, RigidBodyComponent and
     *                                  ShapeComponent.
     */
    RigidBody getRigidBody(EntityRef entity);

    /**
     * @param entity
     * @return Returns true if there is a rigidBody in the physics engine
     *         related to the given entity, false otherwise.
     */
    boolean hasRigidBody(EntityRef entity);

    /**
     * Checks if the given entity has a trigger attached to it.
     *
     * @param entity the entity to check for.
     * @return true if the entity has a trigger, false otherwise.
     */
    boolean hasTrigger(EntityRef entity);

    /**
     * @param entity the entity to check for
     * @return true if the physics engine has a character collider for the given
     *         entity, false otherwise.
     */
    boolean hasCharacterCollider(EntityRef entity);

    /**
     * Warning: Do not remove physics entities while iterating with the returned iterator.

     * You may create a list of entities to remove and remove them afterwards)
     *

     * This method is more efficient than getPhysicsEntities().
     *
     * @return An iterator that iterates over all entities that have a rigidBody
     *         and are active in the physics engine.
     */
    Iterator<EntityRef> physicsEntitiesIterator();

    /**
     * Removes the CharacterCollider associated with the given entity from the
     * physics engine. The collider object of this entity will no longer be
     * valid.
     *

     * If no CharacterCollider was attached to the entity, a warning is logged
     * and this method return false.
     *

     * Make sure not to make another call to getCharacterCollider() if you are
     * destroying the entity, as this will create a new CharacterCollider for
     * the entity.
     *
     * @param entity the entity to remove the rigid body of.
     * @return true if this entity had a character collider attached to it,
     *         false otherwise.
     */
    boolean removeCharacterCollider(EntityRef entity);

    /**
     * Removes the rigid body associated with the given entity from the physics
     * engine. The RigidBody object returned by the newRigidBody(EntityRef) or
     * getRigidBody(EntityRef) method will no longer be valid for this entity un
     * till newRigidBody is called again, so be careful!
     *

     * If no rigid body was attached to the entity, a warning is logged and this
     * method return false.
     *

     * Make sure not to make another call to getRigidBody() if you are
     * destroying the entity, as this will create a new RigidBody for
     * the entity.
     *
     * @param entity the entity to remove the rigid body of.
     * @return true if this entity had a rigid body attached to it, false
     *         otherwise.
     */
    boolean removeRigidBody(EntityRef entity);

    /**
     * Removes the trigger associated with the given entity from the physics
     * engine.
     *

     * If no trigger was attached to the entity, a warning is logged and this
     * method return false.
     *

     * Make sure not to make another call to updateTrigger() if you are
     * destroying the entity, as this will create a new trigger for
     * the entity.
     *
     * @param entity the entity to remove the rigid body of.
     * @return true if this entity had a trigger attached to it, false
     *         otherwise.
     */
    boolean removeTrigger(EntityRef entity);

    /**
     * Advances the physics engine with the given amount of time in seconds. As
     * long as this time does not exceed 8/60 seconds, the game speed will be
     * constant.
     *
     * @param delta amount of time to advance the engine in seconds.
     */
    void update(float delta);

    /**
     * Updates the shape and settings of the rigidBody belonging to the given
     * entity. If the given entity had no rigidBody in the physics engine, it
     * will be created. Updating an entity without RigidBody is seen as bad
     * practise and hence a warning is logged.
     *

     * This method also updates the position of the rigid body in line with
     * the location of the entity. If this method is not called, then the
     * position of the rigid body would be overwritten by the next physics
     * update.
     *
     * @param entity the entity of which the rigidBody needs updating.
     * @return true if there was already a rigidBody registered for the entity
     *         (which is now updated), false otherwise.
     */
    boolean updateRigidBody(EntityRef entity);

    /**
     * Updates or creates the trigger of the given object. The entity must have
     * a TriggerComponent, LocationComponent and ShapeComponent to have a
     * trigger. When updating an existing trigger the location and scale are
     * updated.
     *

     * An entity with a trigger attached to it will generate collision pairs
     * when it collides or intersects with other objects. A good example of its
     * usage is picking up items. By creating a trigger for a player, a
     * collision event will be generated when the shape of the player collides
     * with the shape of a dropped item. This event is not send by the
     * PhysicsEngine class. Instead it is stored and can be retrieved by the
     * getCollisionPairs() method.
     *
     * @param entity the entity of which the trigger may need updating.
     * @return true if there was already a trigger for the given entity, false
     *         otherwise.
     * @throws IllegalArgumentException if a new trigger must be made, but the
     *                                  entity does not have a LocationComponent, TriggerComponent and
     *                                  ShapeComponent.
     */
    boolean updateTrigger(EntityRef entity);

    /**
     * Recompute the character collider for the given entity.
     *
     * The entity must have a {@link org.terasology.engine.logic.location.LocationComponent LocationComponent}
     * and a {@link org.terasology.engine.logic.characters.CharacterMovementComponent CharacterMovementComponent}.
     *
     * @param entity the entity to recompute the character collider for.
     * @return the updated character collider of the entity
     */
    default CharacterCollider recomputeCharacterCollider(EntityRef entity) {
        removeCharacterCollider(entity);
        return getCharacterCollider(entity);
    }
}


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

namespace UnityEditor.VFX.Operator
{
    [VFXInfo(category = "Math/Arithmetic")]
    class Step : VFXOperatorNumericUnified, IVFXOperatorNumericUnifiedConstrained
    {
        protected override sealed string operatorName { get { return "Step"; } }

        public class InputProperties
        {
            [Tooltip("The value to compare")]
            public float Value = 0.0f;
            [Tooltip("The threshold from which the function will return one")]
            public float Threshold = 0.5f;
        }

        public IEnumerable<int> slotIndicesThatMustHaveSameType
        {
            get
            {
                return Enumerable.Range(0, 2);
            }
        }

        public IEnumerable<int> slotIndicesThatCanBeScalar
        {
            get
            {
                yield return 1;
            }
        }

        protected override sealed ValidTypeRule typeFilter { get { return ValidTypeRule.allowEverythingExceptInteger; } }

        protected override sealed VFXExpression[] BuildExpression(VFXExpression[] inputExpression)
        {
            return new[]
            {
                VFXOperatorUtility.Saturate(VFXOperatorUtility.Ceil(inputExpression[0] - inputExpression[1])),

                // TODO : It would be nice to have inverted step output (1 if below threshold), but we need to be able to define multiple output slots.
                //VFXOperatorUtility.Clamp( new VFXExpressionFloor(inputExpression[0])-inputExpression[1], VFXValue.Constant(0.0f), VFXValue.Constant(1.0f)),
            };
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace chromecast {
namespace metrics {

namespace {

class CastMetricsHelperStub : public CastMetricsHelper {
 public:
  CastMetricsHelperStub();
  ~CastMetricsHelperStub() override;

  void TagAppStart(const std::string& arg_app_name) override;
  void LogMediaPlay() override;
  void LogMediaPause() override;
  void LogTimeToDisplayVideo() override;
  void LogTimeToBufferAv(BufferingType buffering_type,
                         base::TimeDelta time) override;
  void ResetVideoFrameSampling() override;
  void LogFramesPer5Seconds(
      int displayed_frames, int dropped_frames,
      int delayed_frames, int error_frames) override;
  std::string GetMetricsNameWithAppName(
      const std::string& prefix, const std::string& suffix) const override;
  void SetMetricsSink(MetricsSink* delegate) override;

 private:
  DISALLOW_COPY_AND_ASSIGN(CastMetricsHelperStub);
};

bool stub_instance_exists = false;

CastMetricsHelperStub::CastMetricsHelperStub()
    : CastMetricsHelper() {
  DCHECK(!stub_instance_exists);
  stub_instance_exists = true;
}

CastMetricsHelperStub::~CastMetricsHelperStub() {
  DCHECK(stub_instance_exists);
  stub_instance_exists = false;
}

void CastMetricsHelperStub::TagAppStart(const std::string& arg_app_name) {
}

void CastMetricsHelperStub::LogMediaPlay() {
}

void CastMetricsHelperStub::LogMediaPause() {
}

void CastMetricsHelperStub::LogTimeToDisplayVideo() {
}

void CastMetricsHelperStub::LogTimeToBufferAv(BufferingType buffering_type,
                                              base::TimeDelta time) {
}

void CastMetricsHelperStub::ResetVideoFrameSampling() {
}

void CastMetricsHelperStub::LogFramesPer5Seconds(int displayed_frames,
                                                 int dropped_frames,
                                                 int delayed_frames,
                                                 int error_frames) {
}

std::string CastMetricsHelperStub::GetMetricsNameWithAppName(
    const std::string& prefix,
    const std::string& suffix) const {
  return "";
}

void CastMetricsHelperStub::SetMetricsSink(MetricsSink* delegate) {
}

}  // namespace

void InitializeMetricsHelperForTesting() {
  if (!stub_instance_exists) {
    new CastMetricsHelperStub();
  }
}

}  // namespace metrics
}  // namespace chromecast


text:
import pandas
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import label_binarize

import os
import sys
config_path = "utilities/"
sys.path.append(os.path.abspath(config_path))

from MyAPI import MyAPI
api = MyAPI()
X, Y = api.get_dataset(0, start_index=0,end_index=20000, nr=20000)

# prepare models
models = []
models.append(('KNN', KNeighborsClassifier()))
models.append(('Decision Tree', DecisionTreeClassifier()))
models.append(('Gaussian', GaussianNB()))
models.append(('SVM', SVC()))

classes=list(set(Y))

# prepare configuration for cross validation test harness
seed = 7

# evaluate each model in turn
results = []
names = []
scoring = 'accuracy'
for name, model in models:
    kfold = model_selection.KFold(n_splits=10, random_state=seed)
    cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring)
    results.append(cv_results)
    names.append(name)
    msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
    print(msg)
# boxplot algorithm comparison
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
plt.savefig('compare.png')


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.junit;

import com.intellij.psi.PsiElementFactory;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;

public class JUnitTagValidationTest extends LightJavaCodeInsightFixtureTestCase {
  /**
   * {@link TestTags#parseAsJavaExpression(java.lang.String[])}
   */
  public void testValidTags() {
    PsiElementFactory factory = myFixture.getJavaFacade().getElementFactory();
    factory.createExpressionFromText("1+2", null);
    factory.createExpressionFromText("!1+2", null);
    factory.createExpressionFromText("!1+ 2", null);
  }
}


text:
package eu.scidipes.toolkits.palibrary.exceptions;

/**
 * Generic PA RuntimeException extension
 *
 * @author Tom Bunting
 *
 */
public class PARuntimeException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public PARuntimeException(final String message, final Throwable cause) {
		super(message, cause);
	}

	public PARuntimeException(final String message) {
		super(message);
	}

}


text:
@interface CartViewController : RootViewController

@end


text:
<?php
namespace LSI\SystemBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * SalesRecord
 *
 ** @ORM\Table(name="sales_record")
 ** @ORM\Entity
 */
class SalesRecord
{
    /**
     *** @var integer
     *
     ** @ORM\Column(name="sales_record_id", type="integer", nullable=false)
     ** @ORM\Id
     ** @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $salesRecordId;

    /**
     *** @var integer
     *
     ** @ORM\Column(name="record_year", type="integer", nullable=false)
     */
    private $recordYear;

    /**
     *** @var string
     *
     ** @ORM\Column(name="record_holder_name", type="string", length=100, nullable=false)
     */
    private $recordHolderName;

    /**
     *** @var float
     *
     ** @ORM\Column(name="record_value", type="decimal", precision=10, scale=4, nullable=false)
     */
    private $recordValue;

    /**
     *** @var string
     *
     ** @ORM\Column(name="active_status", type="string", length=1, nullable=false)
     */
    private $activeStatus;

    /**
     *** @var \DateTime
     *
     ** @ORM\Column(name="create_date", type="date", nullable=false)
     */
    private $createDate;

    /**
     *** @var integer
     *
     ** @ORM\Column(name="create_userid", type="integer", nullable=false)
     */
    private $createUserid;

    /**
     *** @var \DateTime
     *
     ** @ORM\Column(name="update_date", type="date", nullable=false)
     */
    private $updateDate;

    /**
     *** @var integer
     *
     ** @ORM\Column(name="update_userid", type="integer", nullable=false)
     */
    private $updateUserid;

    /**
     *** @var \SalesRecordType
     *
     ** @ORM\ManyToOne(targetEntity="SalesRecordType")
     ** @ORM\JoinColumns({
     *  * @ORM\JoinColumn(name="sales_record_type", referencedColumnName="sales_record_type")
     * })
     */
    private $salesRecordType;

    /**
     *** @var \UserRole
     *
     ** @ORM\ManyToOne(targetEntity="UserRole")
     ** @ORM\JoinColumns({
     *  * @ORM\JoinColumn(name="record_holder_user_role", referencedColumnName="user_role")
     * })
     */
    private $recordHolderUserRole;

    /**
     *** @var \SalesProgramType
     *
     ** @ORM\ManyToOne(targetEntity="SalesProgramType")
     ** @ORM\JoinColumns({
     *  * @ORM\JoinColumn(name="sales_program_type", referencedColumnName="sales_program_type")
     * })
     */
    private $salesProgramType;

    /**
     * Get salesRecordId
     *
     ** @return integer
     */
    public function getSalesRecordId()
    {
        return $this->salesRecordId;
    }

    /**
     * Set recordYear
     *
     ** @param integer $recordYear
     ** @return SalesRecord
     */
    public function setRecordYear($recordYear)
    {
        $this->recordYear = $recordYear;

        return $this;
    }

    /**
     * Get recordYear
     *
     ** @return integer
     */
    public function getRecordYear()
    {
        return $this->recordYear;
    }

    /**
     * Set recordHolderName
     *
     ** @param string $recordHolderName
     ** @return SalesRecord
     */
    public function setRecordHolderName($recordHolderName)
    {
        $this->recordHolderName = $recordHolderName;

        return $this;
    }

    /**
     * Get recordHolderName
     *
     ** @return string
     */
    public function getRecordHolderName()
    {
        return $this->recordHolderName;
    }

    /**
     * Set recordValue
     *
     ** @param float $recordValue
     ** @return SalesRecord
     */
    public function setRecordValue($recordValue)
    {
        $this->recordValue = $recordValue;

        return $this;
    }

    /**
     * Get recordValue
     *
     ** @return float
     */
    public function getRecordValue()
    {
        return $this->recordValue;
    }

    /**
     * Set activeStatus
     *
     ** @param string $activeStatus
     ** @return SalesRecord
     */
    public function setActiveStatus($activeStatus)
    {
        $this->activeStatus = $activeStatus;

        return $this;
    }

    /**
     * Get activeStatus
     *
     ** @return string
     */
    public function getActiveStatus()
    {
        return $this->activeStatus;
    }

    /**
     * Set createDate
     *
     ** @param \DateTime $createDate
     ** @return SalesRecord
     */
    public function setCreateDate($createDate)
    {
        $this->createDate = $createDate;

        return $this;
    }

    /**
     * Get createDate
     *
     ** @return \DateTime
     */
    public function getCreateDate()
    {
        return $this->createDate;
    }

    /**
     * Set createUserid
     *
     ** @param integer $createUserid
     ** @return SalesRecord
     */
    public function setCreateUserid($createUserid)
    {
        $this->createUserid = $createUserid;

        return $this;
    }

    /**
     * Get createUserid
     *
     ** @return integer
     */
    public function getCreateUserid()
    {
        return $this->createUserid;
    }

    /**
     * Set updateDate
     *
     ** @param \DateTime $updateDate
     ** @return SalesRecord
     */
    public function setUpdateDate($updateDate)
    {
        $this->updateDate = $updateDate;

        return $this;
    }

    /**
     * Get updateDate
     *
     ** @return \DateTime
     */
    public function getUpdateDate()
    {
        return $this->updateDate;
    }

    /**
     * Set updateUserid
     *
     ** @param integer $updateUserid
     ** @return SalesRecord
     */
    public function setUpdateUserid($updateUserid)
    {
        $this->updateUserid = $updateUserid;

        return $this;
    }

    /**
     * Get updateUserid
     *
     ** @return integer
     */
    public function getUpdateUserid()
    {
        return $this->updateUserid;
    }

    /**
     * Set salesRecordType
     *
     ** @param \SalesRecordType $salesRecordType
     ** @return SalesRecord
     */
    public function setSalesRecordType(\LSI\SystemBundle\Entity\SalesRecordType $salesRecordType = null)
    {
        $this->salesRecordType = $salesRecordType;

        return $this;
    }

    /**
     * Get salesRecordType
     *
     ** @return \SalesRecordType
     */
    public function getSalesRecordType()
    {
        return $this->salesRecordType;
    }

    /**
     * Set recordHolderUserRole
     *
     ** @param \UserRole $recordHolderUserRole
     ** @return SalesRecord
     */
    public function setRecordHolderUserRole(\LSI\SystemBundle\Entity\UserRole $recordHolderUserRole = null)
    {
        $this->recordHolderUserRole = $recordHolderUserRole;

        return $this;
    }

    /**
     * Get recordHolderUserRole
     *
     ** @return \UserRole
     */
    public function getRecordHolderUserRole()
    {
        return $this->recordHolderUserRole;
    }

    /**
     * Set salesProgramType
     *
     ** @param \SalesProgramType $salesProgramType
     ** @return SalesRecord
     */
    public function setSalesProgramType(\LSI\SystemBundle\Entity\SalesProgramType $salesProgramType = null)
    {
        $this->salesProgramType = $salesProgramType;

        return $this;
    }

    /**
     * Get salesProgramType
     *
     ** @return \SalesProgramType
     */
    public function getSalesProgramType()
    {
        return $this->salesProgramType;
    }
}


text:
package ru.skrser.ctci3dot1;

/**
 * Multiple stack realisation using single array
 */
public class Solution {

    private final int STACKS_NUMBER = 3;
    private final int STACK_MAXSIZE = 5;

    private int[] stackIndex = new int[STACKS_NUMBER];
    private Integer[] array = new Integer[STACKS_NUMBER * STACK_MAXSIZE];

    /**
     * Pushes value to stack
     *
     * @param stackNum stack number to be used. Acceptable values: 0..2
     * @param data     to be pushed in stack
     * @throws IndexOutOfBoundsException if stack overflow (more than STACK_MAXSIZE = 5 values)
     * @throws IllegalArgumentException  if stackNum < 0 or > 2
     */
    public void push(int stackNum, int data) {
        checkStackNum(stackNum);
        array[stackIndex[stackNum]++ * STACKS_NUMBER + stackNum] = data;
    }

    private void checkStackNum(int stackNum) {
        if (stackNum < 0 || stackNum > STACKS_NUMBER - 1)
            throw new IllegalArgumentException("Illegal value for stackNum: " + stackNum + ". Should be 0.." + (STACKS_NUMBER - 1));
    }

    /**
     * Pops value from stack
     *
     * @param stackNum stack number to be used. Acceptable values: 0..2
     * @return value from corresponding stack; null if nothing was previously pushed in stack
     * @throws IllegalArgumentException if stackNum < 0 or > 2
     */
    public Integer pop(int stackNum) {
        checkStackNum(stackNum);
        int dataIndex = --stackIndex[stackNum] * STACKS_NUMBER + stackNum;
        if (dataIndex >= 0) {
            int data = array[dataIndex];
            array[dataIndex] = null;
            return data;
        } else {
            stackIndex[stackNum] = 0;
            return null;
        }
    }

    /**
     * Picks value from stack
     *
     * @param stackNum stack number to be used. Acceptable values: 0..2
     * @return value from corresponding stack; null if nothing was previously pushed in stack
     * @throws IllegalArgumentException if stackNum < 0 or > 2
     */
    public Integer pick(int stackNum) {
        checkStackNum(stackNum);
        int dataIndex = (stackIndex[stackNum] - 1) * STACKS_NUMBER + stackNum;
        if (dataIndex >= 0) {
            return array[dataIndex];
        } else {
            return null;
        }
    }

}


text:
.. _deploy-cgi-chapter:

============================
Deploying Pyblosxom with CGI
============================

Summary
=======

You can run Pyblosxom as a CGI script with many web servers.  This
document covers setting Pyblosxom up as a CGI script.

Dependencies
============

You need an account on a web server configured to run CGI scripts.  It
helps to know how to run CGI scripts on that server, too.

Deployment
==========

1. Copy the ``pyblosxom.cgi`` file from the blog directory (the
   directory which you created with ``pyblosxom-cmd create ./blog/``)
   into your CGI directory.

2. Edit the ``pyblosxom.cgi`` file.

   The top of the file looks something like this

   .. code-block:: python
      :emphasize-lines: 1,5,11
      :linenos:

      #!/usr/bin/env python

      # -u turns off character translation to allow transmission
      # of gzip compressed content on Windows and OS/2
      #!/path/to/python -u

      import os, sys

      # Uncomment this line to add the directory your config.py file is
      # in to the python path:
      #sys.path.append("/path/to/directory/")

   Make sure the first line points to a valid python interpreter.  If
   you're using virtualenv, then make sure it points to the python
   interpreter in the virtual environment.

   Uncomment the ``sys.path.append("/path/to/directory/")`` line and
   make sure the path being appended is the directory that your
   ``config.py`` file is in.

4. Make sure the ``pyblosxom.cgi`` file has the correct permissions
   and ownership for running a CGI script in this directory for the
   server that you're using.

5. Make sure your blog directory has the correct permissions for being
   read by the process executing your CGI script.

6. Run your ``pyblosxom.cgi`` script by doing::

       % ./pyblosxom.cgi test

   If that doesn't work, double-check to make sure you've completed
   the above steps, then check the trouble-shooting section below,
   then ask for help on IRC or the users mailing list.  More details
   in :ref:`project-details-and-contact`.

If that does work, then try to run the CGI script from your
web browser.  The url is dependent on where you put the
``pyblosxom.cgi`` script and how CGI works on your web server.

Trouble-shooting
================

We're going to try to break this down a bit into categories. Bear with
us and keep trying things.

If you have problems and have gone through this section to no avail,
ask a question on the pyblosxom-users mailing list or ask us on IRC.
Details for both of these are on the `website`_.

.. _website: http://pyblosxom.github.com/

Running ./pyblosxom.cgi doesn't work
------------------------------------

First, you should check to see if you have the minimum requirements
for Pyblosxom on your system.  They're listed in the
:ref:`Requirements section of the Install chapter <requirements>`.  If
not, then please install them.

If Python is installed on your system, make sure the first line in
``pyblosxom.cgi`` points to the correct Python interpreter.  By
default, ``pyblosxom.cgi`` uses ``env`` to execute the Python
interpreter.  In some rare systems, ``/usr/bin/env`` doesn't exist or
the system may have odd environment settings.  In those cases, you may
edit the first line to point to the Python interpreter directly.  For
example::

    #!/usr/bin/python

Then try running ``./pyblosxom.cgi`` again.

If Python is installed on your system and the first line of
``pyblosxom.cgi`` is correct, check for permissions issues.
``pyblosxom.cgi`` is a script, so it needs execute permission in order
to function.  If those aren't set, then fix that and try running
``./pyblosxom.cgi`` again.

Check the error logs for your web server.

I see a HTTP 404 error when I try to bring up my blog
-----------------------------------------------------

When you try to look at your blog and you get a HTTP 404 error, then
you're using the wrong URL.  Here are some questions to ask yourself:

* Are you using an ``.htaccess`` file?
* Does your server allow you to run CGI scripts?
* Do other CGI scripts in this directory work?
* Does the URL you're trying to use to access Pyblosxom look like
  other URLs that work on your system?

I see a HTTP 500 error when I try to bring up my blog
-----------------------------------------------------

At this point, running ``./pyblosxom.cgi`` at the command prompt
should work fine.  If you haven't done that and you're busy
trouble-shooting, go back and review the deployment instructions.

If the problem is with Pyblosxom and not your web server, then you
should see a pretty traceback that will help you figure out what the
specific problem is.

If the traceback and information doesn't make any sense to you, ask a
question on the pyblosxom-users mailing list or ask us on IRC.
Details for both of these are on the `website
<http://pyblosxom.github.com/>`_.

If you don't see a traceback, then you either have a configuration
problem with your web server or a configuration problem with Python.
The first thing you should do is check your web server's error logs.
For Apache, look for the ``error.log`` file in a place like
``/var/logs/apache/`` or ``/var/logs/httpd/``.  If you don't know
where your web server's error logs are, ask your system administrator.

Does the account your web server runs as have execute access to your
``pyblosxom.cgi`` script?  If your web server does not have the
permissions to read and execute your ``pyblosxom.cgi`` script, then
your blog will not work.

Do you have plugins loaded?  If you do, comment out the
``load_plugins`` setting in your ``config.py`` file so that Pyblosxom
isn't loading any plugins.

For example::

    py["load_plugins"] = ['plugina', 'pluginb', ...]

would get changed to::

    # commenting this out to see if it's a plugin problem
    # py["load_plugins"] = ['plugina', 'pluginb', ...]

Check to see if the problem persists.  Sometimes there are issues with
plugins that only show up in certain situations.

I have other issues
-------------------

Try changing the renderer for your blog to the debug renderer.  You
can do this by setting the ``renderer`` property in your ``config.py``
file to ``debug``.  For example::

    py["renderer"] = "debug"

That will show a lot more detail about your configuration, what the
web server passes Pyblosxom in environment variables, and other data
about your blog that might help you figure out what your problem is.

If that doesn't help, ask a question on the pyblosxom-users mailing
list or ask us on IRC.  Details for both of these are on the `website
<http://pyblosxom.github.com/>`_.

UGH! My blog looks UGLY!
------------------------

.. only:: text

   Read the documentation regarding Flavours and Templates to help you
   out.

.. only:: html or latex

   Check out :ref:`flavours-and-templates`.

I hate writing in HTML!
-----------------------

That's ok.  Pyblosxom supports formatters and entry parsers which
allow you to use a variety of markups for writing blog entries.  See
the documentation on Writing Entries for more information.

.. only:: text

   See the chapter on Writing Entries.

.. only:: html or latex

   Check out :ref:`writing-entries`.

Advanced installation
=====================

We encourage you not to try any of this until you've gotten a blog up
and running.

This section covers additional advanced things you can do to your blog
that will make it nicer.  However, they're not necessary and they're
advanced and we consider these things to be very much a "you're on
your own" kind of issue.

If you ever have problems with Pyblosxom and you ask us questions on
the pyblosxom-users or pyblosxom-devel mailing lists, make sure you
explicitly state what things you've done from this chapter.  It'll go
a long way in helping us to help you.

Renaming the pyblosxom.cgi script
=================================

In the default installation, the Pyblosxom script is named
``pyblosxom.cgi``.

For a typical user on an Apache installation with user folders turned
on, Pyblosxom URLs could look like this::

    http://example.com/~joe/cgi-bin/pyblosxom.cgi
    http://example.com/~joe/cgi-bin/pyblosxom.cgi/an_entry.html
    http://example.com/~joe/cgi-bin/pyblosxom.cgi/dev/another_entry.html

That gets pretty long and it's not very good looking.  For example,
telling the URL to your mother or best friend over the phone would be
challenging.  It would be nice if we could shorten and simplify it.

So, we have some options:

* Change the name of the ``pyblosxom.cgi`` script.

* And if that's not good enough for you, use the Apache mod_rewrite
  module to get URLs internally redirected to the ``pyblosxom.cgi``
  script.

Both methods are described here in more detail.

Change the name of the pyblosxom.cgi script
-------------------------------------------

There's no reason that ``pyblosxom.cgi`` has to be named
``pyblosxom.cgi``.  Let's try changing it ``blog``.  Now our example
URLs look like this::

    http://example.com/~joe/cgi-bin/blog
    http://example.com/~joe/cgi-bin/blog/an_entry.html
    http://example.com/~joe/cgi-bin/blog/category1/another_entry.html

That's better looking in the example.  In your specific circumstances,
that may be all you need.

You might have to change the ``base_url`` property in your
``config.py`` file to match the new URL.

.. Note::

    The ``base_url`` value should NOT have a trailing slash.

If you're running on Apache, you might have to tell Apache that this
is a CGI script even if it doesn't have a ``.cgi`` at the end of it.
If you can use ``.htaccess`` files to override Apache settings, you
might be able to do something like this::

    # this allows execution of CGI scripts in this directory
    Options ExecCGI

    # if the user doesn't specify a file, then instead of doing the
    # regular directory listing, we look at "blog" (which is our
    # pyblosxom.cgi script renamed)
    DirectoryIndex blog

    # this tells Apache that even though "blog" doesn't end in .cgi,
    # it is in fact a CGI script and should be treated as such
    <Files blog>
    ForceType application/cgi-script
    SetHandler cgi-script
    </Files>

You may need to stop and restart Apache for your Apache changes to
take effect.

Hiding the .cgi with RewriteRule
--------------------------------

Apache has a module for URL rewriting which allows you to convert
incoming URLs to other URLs that can be handled internally.  You can
do URL rewriting based on all sorts of things.  See the Apache manual
for more details.

In our case, we want all incoming URLs pointing to ``blog`` to get
rewritten to ``cgi-bin/pyblosxom.cgi`` so they can be handled by
Pyblosxom.  Then all our URLs will look like this::

    http://example.com/~joe/blog
    http://example.com/~joe/blog/an_entry.html
    http://example.com/~joe/blog/category1/another_entry.html

To do this, we create an .htaccess file (it has to be named exactly
that) in our ``public_html`` directory (or wherever it is that
``/~joe/`` points to).  In that file we have the following code::

    RewriteEngine on
    RewriteRule   ^blog?(.*)$   /~joe/cgi-bin/pyblosxom.cgi$1   [last]

The first line turns on the Apache mod_rewrite engine so that it will
rewrite URLs.

The second line has four parts.  The first part denotes the line as a
RewriteRule.  The second part states the regular expression that
matches the part of the URL that we want to rewrite.  The third part
denotes what we're rewriting the URL to.  The fourth part states that
after this rule is applied, no future rewrite rules should be applied.

If you do URL rewriting, you may have to set the base_url property in
your ``config.py`` accordingly.  In the above example, the
``base_url`` would be ``http://example.com/~joe/blog`` with no
trailing slash.

For more information on URL re-writing, see the mode_rewrite chapter
in the Apache documentation for the version that you're using.


text:
'use strict';

const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();

const Helper = require('../helper.js');

// To make lab look like BDD:
const describe = lab.describe;
const it = lab.it;
const before = lab.before;
const after = lab.after;
const expect = Code.expect;

const DBPath = './test.sqlite3';
const SQLiteDBConfig = {
    name: 'sqlite',
    client: 'sqlite3',
    connection: {
        filename: DBPath
    },
    useNullAsDefault: true
};
const PGDBConfig = {
    name: 'pg',
    client: 'pg',
    connection: {
        database: 'hapi_db_manager_testing',
        user: 'postgres',
        password: ''
    },
    pool: {
        min: 2,
        max: 10
    }
};

describe('Data', () => {

    before((done) => {

        // Create table for testing
        const payload = {
            columnList: [
                { name: 'col1', type: 'integer' },
                { name: 'col2', type: 'string' }
            ]
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig, PGDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'POST', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);

                // Create table for pg
                server.inject({ method: 'POST', url: '/dbadmin/api/' + PGDBConfig.name + '/data_table', payload }, (response2) => {

                    expect(response2.statusCode).to.equal(200);
                    expect(response2.result.code).to.equal(200);
                    expect(response2.result.data).to.be.instanceof(Array);
                    done();

                });

            });

        });

    });

    it('sqlite list all data with non-existing database test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/null/data_table/data' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(404);
                done();

            });

        });

    });

    it('sqlite list all data with non-existing table test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/null/data' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(400);
                done();

            });

        });

    });

    it('sqlite list all data test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite list all data with page test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data?page=1' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite list all data with rows test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data?rows=10' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite list all data with page and rows test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data?page=1&rows=10' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite list all data with minus page and rows test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data?page=-1&rows=-10' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite list all data with non-number page and rows test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data?page=aaa&rows=bbb' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite list total count with non-existing database test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/null/data_table/data/count' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(404);
                done();

            });

        });

    });

    it('sqlite list total count with non-existing table test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/null/data/count' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(400);
                done();

            });

        });

    });

    it('sqlite list total count test', (done) => {

        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'GET', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data/count' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.equal(0);
                done();

            });

        });

    });

    it('sqlite add new data with non-existing database test', (done) => {

        const payload = {
            col1: 111,
            col2: 'bbb'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'POST', url: '/dbadmin/api/null/data_table/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(404);
                done();

            });

        });

    });

    it('sqlite add new data with non-existing table test', (done) => {

        const payload = {
            col1: 111,
            col2: 'bbb'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'POST', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/null/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(400);
                done();

            });

        });

    });

    it('sqlite add new data with non-existing column test', (done) => {

        const payload = {
            zzz: 'aaa'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'POST', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(400);
                done();

            });

        });

    });

    it('sqlite add new data test', (done) => {

        const payload = {
            col1: 111,
            col2: 'bbb'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'POST', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite add new data with page and rows test', (done) => {

        const payload = {
            col1: 111,
            col2: 'bbb'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'POST', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data?page=1&rows=10', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite edit data with non-existing database test', (done) => {

        const payload = {
            col1: 222,
            col2: 'yyy'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'PUT', url: '/dbadmin/api/null/data_table/data/1', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(404);
                done();

            });

        });

    });

    it('sqlite edit data with non-existing table test', (done) => {

        const payload = {
            col1: 222,
            col2: 'yyy'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'PUT', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/null/data/1', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(400);
                done();

            });

        });

    });

    it('sqlite edit data with non-existing column test', (done) => {

        const payload = {
            zzz: 'zzz'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'PUT', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data/1', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(400);
                done();

            });

        });

    });

    it('sqlite edit data test', (done) => {

        const payload = {
            col1: 222,
            col2: 'yyy'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'PUT', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data/1', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite edit data with page and rows test', (done) => {

        const payload = {
            col1: 222,
            col2: 'yyy'
        };
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'PUT', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data/2?page=1&rows=10', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite delete data with non-existing database test', (done) => {

        const payload = [1];
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'DELETE', url: '/dbadmin/api/null/data_table/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(404);
                done();

            });

        });

    });

    it('sqlite delete data with non-existing table test', (done) => {

        const payload = [1];
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'DELETE', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/null/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(400);
                done();

            });

        });

    });

    it('sqlite delete data test', (done) => {

        const payload = [1];
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'DELETE', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite delete data with page and rows test', (done) => {

        const payload = [2];
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'DELETE', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data?page=1&rows=10', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('sqlite delete data with non-exisint id test', (done) => {

        const payload = [999];
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'DELETE', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('pg add new data with wrong data type test', (done) => {

        const payload = {
            col1: 'aaa',
            col2: 'bbb'
        };
        Helper.createServer({
            databaseConfigList: [PGDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'POST', url: '/dbadmin/api/' + PGDBConfig.name + '/data_table/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(500);
                done();

            });

        });

    });

    it('pg add new data test', (done) => {

        const payload = {
            col1: 111,
            col2: 'bbb'
        };
        Helper.createServer({
            databaseConfigList: [PGDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'POST', url: '/dbadmin/api/' + PGDBConfig.name + '/data_table/data', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                done();

            });

        });

    });

    it('pg edit data with wrong data type test', (done) => {

        const payload = {
            col1: 'zzz',
            col2: 'yyy'
        };
        Helper.createServer({
            databaseConfigList: [PGDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'PUT', url: '/dbadmin/api/' + PGDBConfig.name + '/data_table/data/1', payload }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(500);
                done();

            });

        });

    });

    after((done) => {

        // Drop another testing table
        Helper.createServer({
            databaseConfigList: [SQLiteDBConfig, PGDBConfig]
        }, (err, server) => {

            expect(err).to.equal(null);
            server.inject({ method: 'DELETE', url: '/dbadmin/api/' + SQLiteDBConfig.name + '/data_table' }, (response) => {

                expect(response.statusCode).to.equal(200);
                expect(response.result.code).to.equal(200);
                expect(response.result.data).to.be.instanceof(Array);
                server.inject({ method: 'DELETE', url: '/dbadmin/api/' + PGDBConfig.name + '/data_table' }, (response2) => {

                    expect(response2.statusCode).to.equal(200);
                    expect(response2.result.code).to.equal(200);
                    expect(response2.result.data).to.be.instanceof(Array);
                    done();

                });

            });

        });

    });

});


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Marten.Events;
using Marten.Events.Projections;
using Marten.Events.Projections.Async;
using Marten.Storage;
using Marten.Testing.CodeTracker;
using NSubstitute;
using Shouldly;
using Xunit;

namespace Marten.Testing.Events.Projections.Async
{

    public class when_caching_pages : ProjectionTrackContext
    {
        [Fact]
        public async Task stores_the_first_page()
        {
            var thePage = new EventPage(0, 100, new IEvent[0]) { Count = 100 };

            await theProjectionTrack.CachePage(thePage).ConfigureAwait(false);

            theProjectionTrack.Accumulator.AllPages().Single()
                .ShouldBe(thePage);
        }

        [Fact]
        public async Task should_queue_the_page_on_each_projection_on_the_first_one()
        {
            var thePage = new EventPage(0, 100, new IEvent[0]) { Count = 100 };

            await theProjectionTrack.CachePage(thePage).ConfigureAwait(false);
        }

        [Fact]
        public async Task should_not_pause_the_fetcher_if_under_the_threshold()
        {
            var thePage = new EventPage(0, 100, new IEvent[0]) { Count = 100 };

            await theProjectionTrack.CachePage(thePage).ConfigureAwait(false);

            await theFetcher.DidNotReceive().Pause().ConfigureAwait(false);
        }

        [Fact]
        public async Task pauses_the_fetcher_if_the_queue_number_is_greater_than_the_options_threshold()
        {
            // The default for MaximumStagedEventCount is 1000
            await theProjectionTrack.CachePage(new EventPage(0, 100, new IEvent[0]) {Count = 100}).ConfigureAwait(false);
            await theProjectionTrack.CachePage(new EventPage(101, 200, new IEvent[0]) {Count = 100}).ConfigureAwait(false);
            await theProjectionTrack.CachePage(new EventPage(201, 1100, new IEvent[0]) {Count = 1100 - 201}).ConfigureAwait(false);

            await theFetcher.Received().Pause().ConfigureAwait(false);
        }
    }

    public class when_stopping_a_projection_track : ProjectionTrackContext
    {
        [Fact]
        public async Task should_stop_the_fetcher_and_projections()
        {
            theFetcher.Stop().Returns(Task.CompletedTask);

            await theProjectionTrack.Stop().ConfigureAwait(false);

            await theFetcher.Received().Stop();

        }

    }

    public class when_storing_progress : ProjectionTrackContext
    {
        [Fact]
        public async Task store_progress_removes_obsolete_page()
        {
            var thePage = new EventPage(0, 100, new IEvent[0]) { Count = 100 };
            var thePage2 = new EventPage(101, 200, new IEvent[0]) { Count = 100 };
            await theProjectionTrack.CachePage(thePage).ConfigureAwait(false);
            await theProjectionTrack.CachePage(thePage2).ConfigureAwait(false);

            await theProjectionTrack.StoreProgress(typeof(ActiveProject), thePage).ConfigureAwait(false);

            theProjectionTrack.Accumulator.AllPages().Single()
                .ShouldBe(thePage2);
        }

        [Fact]
        public async Task should_restart_the_fetcher_if_it_was_paused_and_below_the_threshold()
        {
            theFetcher.State.Returns(FetcherState.Paused);

            var thePage = new EventPage(0, 100, new IEvent[0]) { Count = 100 };
            await theProjectionTrack.CachePage(thePage).ConfigureAwait(false);

            await theProjectionTrack.StoreProgress(typeof(ActiveProject), thePage).ConfigureAwait(false);

            theFetcher.Received().Start(theProjectionTrack, theProjectionTrack.Lifecycle);
        }
    }

    public abstract class ProjectionTrackContext
    {
        protected readonly IFetcher theFetcher = Substitute.For<IFetcher>();
        protected ProjectionTrack theProjectionTrack;
        protected IProjection projection;

        public ProjectionTrackContext()
        {
            projection = Substitute.For<IProjection>();

            projection.AsyncOptions.Returns(new AsyncOptions());

            theProjectionTrack = new ProjectionTrack(theFetcher, TestingDocumentStore.Basic(), projection, Substitute.For<IDaemonLogger>(), new StubErrorHandler(), Substitute.For<ITenant>());

        }

    }
}


text:
<?php
namespace Concrete\Core\Console\Command;

use Concrete\Core\Command\Process\Command\ProcessMessageInterface;
use Concrete\Core\Command\Process\ProcessUpdater;
use Concrete\Core\Command\Task\Command\ExecuteConsoleTaskCommand;
use Concrete\Core\Command\Task\Input\InputFactory;
use Concrete\Core\Command\Task\Runner\ProcessTaskRunnerInterface;
use Concrete\Core\Messenger\MessageBusAwareInterface;
use Concrete\Core\Command\Task\Input\Input;
use Concrete\Core\Command\Task\Output\OutputFactory;
use Concrete\Core\Command\Task\TaskInterface;
use Concrete\Core\Messenger\MessageBusManager;
use Concrete\Core\Support\Facade\Facade;
use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class TaskCommand extends SymfonyCommand
{

    /**
     * @var TaskInterface
     */
    protected $task;

    public function __construct(TaskInterface $task)
    {
        $this->task = $task;
        parent::__construct();
    }

    public function configure()
    {
        $controller = $this->task->getController();
        $this->setName(sprintf('task:%s', $controller->getConsoleCommandName()));
        $this->setDescription($controller->getDescription());

        $definition = $controller->getInputDefinition();
        if ($definition) {
            $definition->addToCommand($this);
        }
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $app = Facade::getFacadeApplication();
        $inputFactory = $app->make(InputFactory::class);

        $taskInput = $inputFactory->createFromConsoleInput($input, $this->task->getController()->getInputDefinition());
        $command = new ExecuteConsoleTaskCommand($this->task, $taskInput, $output);
        $app->executeCommand($command);

        return static::SUCCESS;
    }
}


text:
#include "tensorflow/compiler/xla/service/gpu/instruction_fusion.h"

#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_fusible.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_query.h"
#include "tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.h"
#include "tensorflow/compiler/xla/service/pattern_matcher.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"

namespace xla {
namespace gpu {

/*static*/ bool GpuInstructionFusion::IsExpensive(
    const HloInstruction& instruction) {
  // We say that floating-point division is cheap on the GPU.
  if (instruction.opcode() == HloOpcode::kDivide &&
      ShapeUtil::ElementIsFloating(instruction.shape())) {
    return false;
  }
  return InstructionFusion::IsExpensive(instruction);
}

bool GpuInstructionFusion::ShouldFuseInexpensiveChecks(HloInstruction* consumer,
                                                       int64 operand_index) {
  HloInstruction* producer = consumer->mutable_operand(operand_index);

  // Output fusions are not currently supported on GPUs.
  if (producer->opcode() == HloOpcode::kFusion) {
    return false;
  }
  // Cost condition: not fuse (simple, expensive producers) and (consumers who
  // reuse operand elements).
  if (producer->opcode() != HloOpcode::kFusion &&
      consumer->ReusesOperandElements(operand_index) &&
      is_expensive(*producer)) {
    return false;
  }

  if (!IsProducerConsumerFusible(*producer, *consumer) ||
      !InstructionFusion::ShouldFuse(consumer, operand_index)) {
    return false;
  }
  return true;
}

bool GpuInstructionFusion::ShouldFuse(HloInstruction* consumer,
                                      int64 operand_index) {
  if (!ShouldFuseInexpensiveChecks(consumer, operand_index)) {
    return false;
  }
  auto producer = consumer->operand(operand_index);

  // The following checks are potentially expensive.
  if (FusionWouldBeTooLarge(*consumer, *producer)) {
    return false;
  }
  // Also check that our emitter can handle the fusion node. We currently can
  // have exponential time/memory requirements for emitting certain fusion
  // kernels, in which case we don't want to fuse.
  // TODO(b/119692968): Remove this once we have fixed our fusion emitter.
  return !FusedIrEmitter::IsFusedIrEmitterInefficient(consumer, producer);
}

bool GpuInstructionFusion::ShouldFuseIntoMultiOutput(HloInstruction* consumer,
                                                     int64 operand_index) {
  return false;
}

HloInstruction::FusionKind GpuInstructionFusion::ChooseKind(
    const HloInstruction* producer, const HloInstruction* consumer) {
  return ChooseFusionKind(*producer, *consumer);
}

}  // namespace gpu
}  // namespace xla


text:
import base64
import codecs
import json
import os
import string
import subprocess
import sys

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

def Run(*args):
  with open(os.devnull, 'w') as null:
    subprocess.check_call(args, stdout=null, stderr=null)

def FindNode(node, component):
  for child in node['children']:
    if child['name'] == component:
      return child
  return None

def InsertIntoTree(tree, source_name, size):
  components = source_name[3:].split('\\')
  node = tree
  for index, component in enumerate(components):
    data = FindNode(node, component)
    if not data:
      data = { 'name': source_name, 'name': component }
      if index == len(components) - 1:
        data['size'] = size
      else:
        data['children'] = []
      node['children'].append(data)
    node = data

def FlattenTree(tree):
  result = [['Path', 'Parent', 'Size', 'Value']]
  def Flatten(node, parent):
    name = node['name']
    if parent and parent != '/':
      name = parent + '/' + name
    if 'children' in node:
      result.append([name, parent, -1, -1])
      for c in node['children']:
        Flatten(c, name)
    else:
      result.append([name, parent, node['size'], node['size']])
  Flatten(tree, '')
  return result

def GetAsset(filename):
  with open(os.path.join(BASE_DIR, filename), 'rb') as f:
    return f.read()

def AppendAsScriptBlock(f, value, var=None):
  f.write('<script type="text/javascript">\n')
  if var:
    f.write('var ' + var + ' = ')
  f.write(value)
  if var:
    f.write(';\n')
  f.write('</script>\n')

def main():
  out_dir = os.path.join(BASE_DIR, '..', '..', '..', 'out', 'Release')
  jsons = []
  for dll in ('chrome.dll', 'chrome_child.dll'):
    dll_path = os.path.normpath(os.path.join(out_dir, dll))
    if os.path.exists(dll_path):
      print 'Tallying %s...' % dll_path
      json_path = dll_path + '.json'
      Run(os.path.join(BASE_DIR, '..', '..', '..', 'third_party', 'syzygy',
                       'binaries', 'exe', 'experimental', 'code_tally.exe'),
          '--input-image=' + dll_path,
          '--input-pdb=' + dll_path + '.pdb',
          '--output-file=' + json_path)
      jsons.append(json_path)
  if not jsons:
    print 'Couldn\'t find binaries, looking in', out_dir
    return 1

  # Munge the code_tally json format into an easier-to-view format.
  for json_name in jsons:
    with open(json_name, 'r') as jsonf:
      all_data = json.load(jsonf)
    html_path = os.path.splitext(json_name)[0] + '.html'
    print 'Generating %s... (standlone)' % html_path
    by_source = {}
    symbols_index = {}
    symbols = []
    for obj_name, obj_data in all_data['objects'].iteritems():
      for symbol, symbol_data in obj_data.iteritems():
        size = int(symbol_data['size'])
        # Sometimes there's symbols with no source file, we just ignore those.
        if 'contribs' in symbol_data:
          i = 0
          while i < len(symbol_data['contribs']):
            src_index = symbol_data['contribs'][i]
            i += 1
            per_line = symbol_data['contribs'][i]
            i += 1
            source = all_data['sources'][int(src_index)]
            if source not in by_source:
              by_source[source] = {'lines': {}, 'total_size': 0}
            size = 0
            # per_line is [line, size, line, size, line, size, ...]
            for j in range(0, len(per_line), 2):
              line_number = per_line[j]
              size += per_line[j + 1]
              # Save some time/space in JS by using an array here. 0 == size,
              # 1 == symbol list.
              by_source[source]['lines'].setdefault(line_number, [0, []])
              by_source[source]['lines'][line_number][0] += per_line[j + 1]
              if symbol in symbols_index:
                symindex = symbols_index[symbol]
              else:
                symbols.append(symbol)
                symbols_index[symbol] = symindex = len(symbols) - 1
              by_source[source]['lines'][line_number][1].append(
                  symindex)
            by_source[source]['total_size'] += size
    binary_name = all_data['executable']['name']
    data = {}
    data['name'] = '/'
    data['children'] = []
    file_contents = {}
    line_data = {}
    for source, file_data in by_source.iteritems():
      InsertIntoTree(data, source, file_data['total_size'])

      store_as = source[3:].replace('\\', '/')
      try:
        with codecs.open(source, 'rb', encoding='latin1') as f:
          file_contents[store_as] = f.read()
      except IOError:
        file_contents[store_as] = '// Unable to load source.'

      line_data[store_as] = file_data['lines']
      # code_tally attempts to assign fractional bytes when code is shared
      # across multiple symbols. Round off here for display after summing above.
      for per_line in line_data[store_as].values():
        per_line[0] = round(per_line[0])

    flattened = FlattenTree(data)
    maxval = 0
    for i in flattened[1:]:
      maxval = max(i[2], maxval)
    flattened_str = json.dumps(flattened)

    to_write = GetAsset('template.html')
    # Save all data and what would normally be external resources into the
    # one html so that it's a standalone report.
    with open(html_path, 'w') as f:
      f.write(to_write)
      # These aren't subbed in as a silly workaround for 32-bit python.
      # The end result is only ~100M, but while substituting these into a
      # template, it otherwise raises a MemoryError, I guess due to
      # fragmentation. So instead, we just append them as variables to the file
      # and then refer to the variables in the main script.
      filedata_str = json.dumps(file_contents).replace(
          '</script>', '</scr"+"ipt>')
      AppendAsScriptBlock(f, filedata_str, var='g_file_contents')
      AppendAsScriptBlock(f, json.dumps(line_data), var='g_line_data')
      AppendAsScriptBlock(f, json.dumps(symbols), var='g_symbol_list')
      favicon_str = json.dumps(base64.b64encode(GetAsset('favicon.png')))
      AppendAsScriptBlock(f, favicon_str, var='g_favicon')
      AppendAsScriptBlock(f, flattened_str, var='g_raw_data')
      AppendAsScriptBlock(f, str(maxval), var='g_maxval')
      dllname_str = binary_name + ' ' + all_data['executable']['version']
      AppendAsScriptBlock(f, json.dumps(dllname_str), var='g_dllname')
      AppendAsScriptBlock(f, GetAsset('codemirror.js'))
      AppendAsScriptBlock(f, GetAsset('clike.js'))
      AppendAsScriptBlock(f, GetAsset('main.js'))
      f.write('</html>')

  return 0

if __name__ == '__main__':
  sys.exit(main())


text:
<?php

namespace common\models;

use Yii;
use common\models\base\BaseModel;;
use common\models\CatModel;

/**
 * This is the model class for table "posts".
 *
 * @property integer $id
 * @property string $title
 * @property string $summary
 * @property string $content
 * @property string $label_img
 * @property integer $cat_id
 * @property integer $user_id
 * @property string $user_name
 * @property integer $is_valid
 * @property integer $created_at
 * @property integer $updated_at
 */
class PostModel extends BaseModel
{
    const IS_VALID = 1;//已发布
    const NO_VALID = 0;//未发布
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'posts';
    }

    public function getRelate()
    {
        return $this->hasMany(RelationPostTagModel::className(), ['post_id' => 'id']);
    }

    public function getExtend()
    {
        return $this->hasOne(PostExtendModel::className(), ['post_id' => 'id']);
    }

    public function getCat()
    {
        return $this->hasOne(CatModel::className(), ['id' => 'cat_id']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['content'], 'string'],
            [['cat_id', 'user_id', 'is_valid', 'created_at', 'updated_at'], 'integer'],
            [['title', 'summary', 'label_img', 'user_name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'summary' => '摘要',
            'content' => '内容',
            'label_img' => '标签图',
            'cat_id' => '分类',
            'user_id' => '用户ID',
            'user_name' => '用户名',
            'is_valid' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '修改时间',
        ];
    }

}


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DriveHiderTool")]
[assembly: AssemblyDescription("tool to hide the partition in the system Windows Explorer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GrakovNe")]
[assembly: AssemblyProduct("DriveHiderTool")]
[assembly: AssemblyCopyright("GrakovNe ©  2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6b99992d-bc21-4050-ba91-5b928c90bd11")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
window.LiveReloadOptions = { host: 'localhost' };
require('../../../src/startup.js');

window.hellow = function hellow () {
  return 42;
};


text:
class UpdateUserSeenImages < ActiveRecord::Migration
  def change
    create_table :user_seen_images do |t|
      t.references :user, index: true, null: false
      t.string :media_url, null: false
      t.timestamps null: false
    end
  end
end


text:
namespace metaSMT {

  struct VertexDecorator
  {
    typedef void result_type;
    typedef boost::graph_traits<SMT_Graph>::vertex_descriptor VertexT;

    VertexDecorator( const SMT_Graph & g, VertexT const & v , std::ostream & out)
      : _g(g), _v(v), out(out) {}

    void operator()(logic::QF_BV::tag::bvbin_tag const &) {
      using namespace boost;
      out << "[ label=\"";
      out << "bvbin(" << any_cast<std::string>(get(vertex_arg, _g, _v)) << ")";
      out << "\"]";
    }

    void operator()(logic::QF_BV::tag::bvhex_tag const &) {
      using namespace boost;
      out << "[ label=\"";
      out << "bvhex(" << any_cast<std::string>(get(vertex_arg, _g, _v)) << ")";
      out << "\"]";
    }

    void operator()(logic::QF_BV::tag::bvuint_tag const &) {
      using namespace boost;
      out << "[ label=\"";
      out << "bvuint" << any_cast<tuple< unsigned long, unsigned long> >(get(vertex_arg, _g, _v));
      out << "\"]";
    }

    void operator()(logic::QF_BV::tag::bvsint_tag const &) {
      using namespace boost;
      out << "[ label=\"";
      out << "bvsint" << any_cast<tuple< long, unsigned long> >(get(vertex_arg, _g, _v));
      out << "\"]";
    }

    template <typename Tag>
    void operator()(Tag const & t ){
      using namespace boost;
      out << "[ label=\"" << out << "\"]";
    }

    private:
      const SMT_Graph & _g;
      const VertexT & _v;
      std::ostream & out;
  };

  struct DotDecorator {
    DotDecorator(const SMT_Graph & g)
      : _g(g) { }

    typedef boost::graph_traits<SMT_Graph>::vertex_descriptor VertexT;
    typedef boost::graph_traits<SMT_Graph>::edge_descriptor   EdgeT;

    void operator()(std::ostream & out, VertexT n ) {
      VertexDecorator vd(_g, n, out);
      boost::apply_visitor(vd, boost::get(boost::vertex_tag, _g, n) );
    }

    void operator()(std::ostream & out, EdgeT e){
      using namespace boost;
      out << "[ label=\"";
      out << "IN: " << get(edge_input, _g, e);
      out << "\"]";
    }

    template <typename T2>
    void operator()(std::ostream & out, T2) const{
    }

    private:
    SMT_Graph const & _g;
  };

  inline void write_dot(std::ostream & out, SMT_Graph & g) {
    DotDecorator dotDecorator(g);
    write_graphviz(out, g, dotDecorator, dotDecorator);
  }

} // namespace metaSMT
//  vim: ft=cpp:ts=2:sw=2:expandtab