text:
GameWorld::GameWorld()
{
	world_ = NULL;
	sky_ = NULL;
	terrain_ = NULL;
	penguin_ = NULL;
	distance_travelled_ = 0;
	distance_label_ = NULL;
	time_left_ = 0;
	time_label_ = NULL;
	message_label_ = NULL;
	has_game_begun_ = false;
	has_game_ended_ = false;
	is_popup_active_ = false;
#ifdef ENABLE_DEBUG_DRAW
	debug_draw_ = NULL;
#endif
}

GameWorld::~GameWorld()
{
	DestroyWorld();
}

Scene* GameWorld::scene()
{
    Scene *scene = Scene::create();
    GameWorld *layer = GameWorld::create();
    scene->addChild(layer);
    return scene;
}

bool GameWorld::init()
{
    if ( !Layer::init() )
    {
        return false;
    }

    CreateWorld();
	CreateGame();
    return true;
}

void GameWorld::CreateWorld()
{
	// create world
	b2Vec2 gravity;
	gravity.Set(0, -9.8f);
	world_ = new b2World(gravity);
	// tell world we want to listen for collisions
	world_->SetContactListener(this);

#ifdef ENABLE_DEBUG_DRAW
	debug_draw_ = new GLESDebugDraw(PTM_RATIO);
	world_->SetDebugDraw(debug_draw_);
	uint32 flags = 0;
	flags += b2Draw::e_shapeBit;
	debug_draw_->SetFlags(flags);
#endif
}

void GameWorld::DestroyWorld()
{
#ifdef ENABLE_DEBUG_DRAW
	CC_SAFE_DELETE(debug_draw_);
	debug_draw_ = NULL;
#endif
	CC_SAFE_DELETE(world_);
	world_ = NULL;
}

void GameWorld::CreateGame()
{
	// player starts off with 30 seconds
	time_left_ = 30;

	// create & add the first set of hills at 0
	terrain_ = CustomTerrain::create(world_, 0);
	addChild(terrain_, E_LAYER_FOREGROUND);

	// create & add the sky
	sky_ = Sky::create();
	addChild(sky_, E_LAYER_BACKGROUND);

	// create & add the penguin to the hills
	penguin_ = Penguin::create(this, "penguin_1.png");
	terrain_->addChild(penguin_, E_LAYER_FOREGROUND);

	CreateHUD();

	// enable touch and schedule two selectors; the seconds ticker and the update
	// setTouchEnabled(true);

	this->touchListener = EventListenerTouchAllAtOnce::create();
	this->touchListener->onTouchesBegan = CC_CALLBACK_2(GameWorld::onTouchBegan, this);
	this->touchListener->onTouchesEnded = CC_CALLBACK_2(GameWorld::onTouchEnded, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(this->touchListener, this);

	schedule(schedule_selector(GameWorld::Tick), 1.0f);
	scheduleUpdate();
}

void GameWorld::CreateHUD()
{
	// create & add the distance label
	char buf[16] = {0};
	sprintf(buf, "%dm", distance_travelled_);
	distance_label_ = Label::createWithBMFont("wal_font.fnt", buf);
	distance_label_->setPosition(Vec2(SCREEN_SIZE.width*0.1f, SCREEN_SIZE.height*0.925f));
	distance_label_->setAnchorPoint(Vec2(0, 0.5f));
	addChild(distance_label_, E_LAYER_HUD);

	// create & add the time left label
	sprintf(buf, "%ds", time_left_);
	time_label_ = Label::createWithBMFont("wal_font.fnt", buf);
	time_label_->setPosition(Vec2(SCREEN_SIZE.width*0.5f, SCREEN_SIZE.height*0.925f));
	addChild(time_label_, E_LAYER_HUD);

	// create and add a general message label
	message_label_ = Label::createWithBMFont("wal_font.fnt", "");
	message_label_->setVisible(false);
	addChild(message_label_, E_LAYER_HUD);

	// create & add the pause menu containing pause button
	MenuItemSprite* pause_button = MenuItemSprite::create(Sprite::create("pause.png"), Sprite::create("pause.png"), this, menu_selector(GameWorld::OnPauseClicked));
	pause_button->setPosition(Vec2(SCREEN_SIZE.width*0.95f, SCREEN_SIZE.height*0.925f));
	auto menu = Menu::create(pause_button, NULL);
	menu->setAnchorPoint(Point::ZERO);
	menu->setPosition(Point::ZERO);
	addChild(menu, E_LAYER_HUD);
}

bool GameWorld::onTouchBegan(const std::vector<Touch*>& touches, Event* evt)
{
	if(is_popup_active_)
		return false;

	// while leaping, don't allow touch unless the next hill is close enough
	if(terrain_->GetFootKeyPoint().x > penguin_->getPositionX() &&
		terrain_->GetFootKeyPoint().x - penguin_->getPositionX() > 10)
	{
		return false;
	}

	// game begins only after the player touches
	has_game_begun_ = true;
	// tell the penguin to dive
	penguin_->SetIsDiving(true);

	return true;
}

void GameWorld::onTouchEnded(const std::vector<Touch*>& touches, Event* evt)
{
	if(is_popup_active_)
		return;

	// tell the penguin to stop diving
	penguin_->SetIsDiving(false);
}

void GameWorld::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
	// get the world manifold for this contact
	b2WorldManifold world_manifold;
	contact->GetWorldManifold(&world_manifold);
	// get velocity of the penguin
	b2Vec2 velocity = penguin_->GetBody()->GetLinearVelocity();

	// get angles for the velocity & normal vectors
	float velocity_angle = atan2f(velocity.y, velocity.x);
	float normal_angle = atan2f(world_manifold.normal.y, world_manifold.normal.x);

	// it is a bad landing if the difference in angles is above a certain threshold
	if (normal_angle - velocity_angle > BAD_LANDING_ANGLE_DIFF)
	{
		penguin_->OnBadLanding();
	}
}

void GameWorld::update(float dt)
{
	// update penguin physics
	penguin_->UpdatePhysics();

	// update the world
	// slow it down...otherwise the game is too fast to enjoy!
	world_->Step(dt * 0.5f, 8, 3);

	// update penguin node
	penguin_->UpdateNode();

	// update the hills and sky
	terrain_->Update(penguin_->getPosition());
	sky_->Update(penguin_->getPosition(), terrain_->GetOffsetX(), terrain_->getScale());

	// if penguin has gone beyond the second last key point, its time to take a leap
	if(penguin_->getPositionX() > terrain_->GetCliffKeyPoint().x && !penguin_->GetIsLeaping())
	{
		penguin_->StartLeap();
	}
	// check if the penguin is leaping first
	if(penguin_->GetIsLeaping())
	{
		// if the next hill's foot is close enough, its time to stop leaping & time to start falling
		if(terrain_->GetFootKeyPoint().x > penguin_->getPositionX() &&
			terrain_->GetFootKeyPoint().x - penguin_->getPositionX() <= SCREEN_SIZE.width * 1.75f)
		{
			penguin_->FinishLeap();
		}
	}

	// update the distance counter & label
	int new_distance_travelled = penguin_->getPositionX();
	if(new_distance_travelled > distance_travelled_)
	{
		distance_label_->setString(__String::createWithFormat("%dm", (int)(new_distance_travelled / 2))->getCString());
		distance_travelled_ = new_distance_travelled;
	}
}

void GameWorld::Tick(float dt)
{
	// tick only after the game has started till before it ends
	if(!has_game_begun_ || has_game_ended_)
		return;

	// decrement the time counter
	-- time_left_;

	// update the label
	time_label_->setString(__String::createWithFormat("%ds", time_left_)->getCString());

	// no more time...game over
	if(time_left_ <= 0)
	{
		GameOver();
	}

	// when there 5 seconds or less, start animating the label & playing a sound
	if(time_left_ <= 5)
	{
		if(time_label_->getNumberOfRunningActions() <= 0)
		{
			ActionInterval* scale_up_down = Sequence::createWithTwoActions(ScaleTo::create(0.2f, 1.2f), ScaleTo::create(0.2f, 1.0f));
			time_label_->runAction(RepeatForever::create(scale_up_down));

			ActionInterval* shake = Sequence::createWithTwoActions(RotateBy::create(0.05f, 20.0f), RotateBy::create(0.05f, -20.0f));
			time_label_->setRotation(-10.0f);
			time_label_->runAction(RepeatForever::create(shake));
		}
	}
}

void GameWorld::AddTime(int value)
{
	time_left_ += value;
	time_label_->setString(__String::createWithFormat("%ds", time_left_)->getCString());

	// stop any actions that may been running
	time_label_->stopAllActions();
	// reset scale & rotation
	time_label_->setScale(1.0f);
	time_label_->setRotation(0.0f);

	ActionInterval* scale_up_down = Sequence::createWithTwoActions(EaseSineIn::create(ScaleTo::create(0.2f, 1.2f)), EaseSineOut::create(ScaleTo::create(0.2f, 1.0f)));
	time_label_->runAction(scale_up_down);
}

void GameWorld::ShowMessage(const char* message)
{
	// message will be hidden initially so show it
	message_label_->setVisible(true);
	message_label_->setPosition(Vec2(SCREEN_SIZE.width * 0.5f, SCREEN_SIZE.height * 1.2f));
	message_label_->setOpacity(255);
	message_label_->setString(message);

	// animate entry & exit
	ActionInterval* sequence = Sequence::create(EaseBackOut::create(MoveTo::create(0.2f, Vec2(SCREEN_SIZE.width * 0.5f, SCREEN_SIZE.height * 0.8f))),
		DelayTime::create(1.0f),
		FadeOut::create(0.1f),
		Hide::create(), NULL);
	message_label_->runAction(sequence);
}

void GameWorld::OnPauseClicked(Ref* sender)
{
	// this prevents multiple pause popups
	if(is_popup_active_)
		return;

	pause();

	// pause game elements here
	penguin_->Pause();
	time_label_->pause();

	// create & add the pause popup
	PausePopup* pause_popup = PausePopup::create(this);
	addChild(pause_popup, E_LAYER_POPUP);
}

void GameWorld::ResumeGame()
{
	is_popup_active_ = false;

	// resume GameWorld update & Tick functions
	resume();

	// resume game elements here
	penguin_->Resume();
	time_label_->resume();
}

void GameWorld::GameOver()
{
	has_game_ended_ = true;

	// stop everything
	time_label_->pause();
	time_label_->setScale(1.0f);
	time_label_->setRotation(0.0f);
	unscheduleAllCallbacks();
	// setTouchEnabled(false);
	_eventDispatcher->removeEventListener(this->touchListener);

	// create & add the game over popup
	GameOverPopup* game_over_popup = GameOverPopup::create(this, distance_travelled_/2, penguin_->GetTotalPerfectSlides());
	addChild(game_over_popup, E_LAYER_POPUP);
}


text:
package com.victormartin.projectcawd.data.datasource;

import com.victormartin.projectcawd.domain.model.ChargeAccount;
import com.victormartin.projectcawd.domain.model.User;

public interface DataSource {

    User loginUser(String identifier, String password)  throws Exception;

    ChargeAccount getProjects()  throws Exception;

}

redpajama_set_name: RedPajamaGithub


text:
data = Chef::EncryptedDataBagItem.load('haibung', 'secrets')

user data['user']['name'] do
  home data['user']['home']
  action :create
end

directory "#{data['user']['home']}/.ssh" do
  owner data['user']['name']
end

file "#{data['user']['home']}/.ssh/authorized_keys" do
  action :create
  owner data['user']['name']
  mode '0600'
  content data['authorized_keys'].join("\n")
end

template '/etc/sudoers' do
  source '/sudo/sudoers.erb'
  owner 'root'
  group 'root'
  mode '440'
  variables(
    'user'     => data['user']['name']
  )
end


text:
package org.springframework.boot.actuate.metrics.export;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.PatternMatchUtils;

/**
 * Configuration properties for metrics export.
 *
 * @author Dave Syer
 * @author Simon Buettner
 * @since 1.3.0
 */
@ConfigurationProperties(prefix = "spring.metrics.export")
public class MetricExportProperties extends TriggerProperties {

	/**
	 * Specific trigger properties per MetricWriter bean name.
	 */
	private Map<String, SpecificTriggerProperties> triggers = new LinkedHashMap<>();

	private Aggregate aggregate = new Aggregate();

	private Redis redis = new Redis();

	private Statsd statsd = new Statsd();

	@PostConstruct
	public void setUpDefaults() {
		TriggerProperties defaults = this;
		for (Entry<String, SpecificTriggerProperties> entry : this.triggers.entrySet()) {
			String key = entry.getKey();
			SpecificTriggerProperties value = entry.getValue();
			if (value.getNames() == null || value.getNames().length == 0) {
				value.setNames(new String[] { key });
			}
		}
		if (defaults.isSendLatest() == null) {
			defaults.setSendLatest(true);
		}
		if (defaults.getDelayMillis() == null) {
			defaults.setDelayMillis(5000);
		}
		for (TriggerProperties value : this.triggers.values()) {
			if (value.isSendLatest() == null) {
				value.setSendLatest(defaults.isSendLatest());
			}
			if (value.getDelayMillis() == null) {
				value.setDelayMillis(defaults.getDelayMillis());
			}
		}
	}

	/**
	 * Configuration for triggers on individual named writers. Each value can individually
	 * specify a name pattern explicitly, or else the map key will be used if the name is
	 * not set.
	 * @return the writers
	 */
	public Map<String, SpecificTriggerProperties> getTriggers() {
		return this.triggers;
	}

	public Aggregate getAggregate() {
		return this.aggregate;
	}

	public void setAggregate(Aggregate aggregate) {
		this.aggregate = aggregate;
	}

	public Redis getRedis() {
		return this.redis;
	}

	public void setRedis(Redis redis) {
		this.redis = redis;
	}

	public Statsd getStatsd() {
		return this.statsd;
	}

	public void setStatsd(Statsd statsd) {
		this.statsd = statsd;
	}

	/**
	 * Find a matching trigger configuration.
	 * @param name the bean name to match
	 * @return a matching configuration if there is one
	 */
	public TriggerProperties findTrigger(String name) {
		for (SpecificTriggerProperties value : this.triggers.values()) {
			if (PatternMatchUtils.simpleMatch(value.getNames(), name)) {
				return value;
			}
		}
		return this;
	}

	/**
	 * Aggregate properties.
	 */
	public static class Aggregate {

		/**
		 * Prefix for global repository if active. Should be unique for this JVM, but most
		 * useful if it also has the form "a.b" where "a" is unique to this logical
		 * process (this application) and "b" is unique to this physical process. If you
		 * set spring.application.name elsewhere, then the default will be in the right
		 * form.
		 */
		private String prefix = "";

		/**
		 * Pattern that tells the aggregator what to do with the keys from the source
		 * repository. The keys in the source repository are assumed to be period
		 * separated, and the pattern is in the same format, e.g. "d.d.k.d". Here "d"
		 * means "discard" and "k" means "keep" the key segment in the corresponding
		 * position in the source.
		 */
		private String keyPattern = "";

		public String getPrefix() {
			return this.prefix;
		}

		public void setPrefix(String prefix) {
			this.prefix = prefix;
		}

		public String getKeyPattern() {
			return this.keyPattern;
		}

		public void setKeyPattern(String keyPattern) {
			this.keyPattern = keyPattern;
		}

	}

	/**
	 * Redis properties.
	 */
	public static class Redis {

		/**
		 * Prefix for redis repository if active. Should be globally unique across all
		 * processes sharing the same repository.
		 */
		private String prefix = "spring.metrics";

		/**
		 * Key for redis repository export (if active). Should be globally unique for a
		 * system sharing a redis repository across multiple processes.
		 */
		private String key = "keys.spring.metrics";

		public String getPrefix() {
			return this.prefix;
		}

		public void setPrefix(String prefix) {
			this.prefix = prefix;
		}

		public String getKey() {
			return this.key;
		}

		public void setKey(String key) {
			this.key = key;
		}

		public String getAggregatePrefix() {
			// The common case including a standalone aggregator would have a prefix that
			// starts with the end of the key, so strip that bit off and call it the
			// aggregate prefix.
			if (this.key.startsWith("keys.")) {
				String candidate = this.key.substring("keys.".length());
				if (this.prefix.startsWith(candidate)) {
					return candidate;
				}
				return candidate;
			}
			// If the user went off piste, choose something that is safe (not empty) but
			// not the whole prefix (on the assumption that it contains dimension keys)
			if (this.prefix.contains(".")
					&& this.prefix.indexOf(".") < this.prefix.length() - 1) {
				return this.prefix.substring(this.prefix.indexOf(".") + 1);
			}
			return this.prefix;
		}

	}

	/**
	 * Statsd properties.
	 */
	public static class Statsd {

		/**
		 * Host of a statsd server to receive exported metrics.
		 */
		private String host;

		/**
		 * Port of a statsd server to receive exported metrics.
		 */
		private int port = 8125;

		/**
		 * Prefix for statsd exported metrics.
		 */
		private String prefix;

		public String getHost() {
			return this.host;
		}

		public void setHost(String host) {
			this.host = host;
		}

		public int getPort() {
			return this.port;
		}

		public void setPort(int port) {
			this.port = port;
		}

		public String getPrefix() {
			return this.prefix;
		}

		public void setPrefix(String prefix) {
			this.prefix = prefix;
		}

	}

}


text:
@implementation PriceCellBuilder

-(void)registerCellInCollectionView:(UICollectionView *)collectionView {
    [PriceCell registerForCollectionView:collectionView];
}

-(UICollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView * _Nonnull)collectionView {

    PriceCell *cell = (PriceCell*)[collectionView dequeueReusableCellWithReuseIdentifier:[PriceCell cellIdentifier] forIndexPath:indexPath];
    return cell;
}
-(CGSize)sizeWithin:(CGRect)bounds{
    return [PriceCell sizeWithin:bounds
                     withPadding:UIEdgeInsetsMake(0, 15, 0, 15)];
}
@end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>orderevents</title>

    <link href="orderevents.css" rel="stylesheet" />

                Date:
                <input id="orderevents-date" class="textinput" type="text" data-win-bind="value: date Binding.Mode.twoway" />

                Comments:
                <input id="orderevents-comments" class="textinput-multiline" type="text" data-win-bind="value: comments Binding.Mode.twoway" />


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>RiggedHand — Leap Motion Java SDK v3.1 documentation</title>

    <link rel="stylesheet" href="../../cpp/_static/bootstrap-3.0.0/css/documentation-bundle.1471552333.css" type="text/css" />

    <link rel="top" title="Leap Motion Java SDK v3.1 documentation" href="../index.html" />

<link rel="stylesheet" href="/assets/standalone-header.css?r9" type="text/css" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

            Developer Portal

      <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

      </button>

What's new

Getting Started

Documentation

 Examples

 Blog

 Community

      JavaScript

      Unity

      C#

      C++

      Java

      Python

      Objective-C

      Unreal

<form class="navbar-form" action="../search.html" method="get" onsubmit="storeThisPage()">

  <input type="search" results="5" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

RiggedHand¶

The RiggedHand script is used with the human-like hand prefabs as well as the image hand prefab. It updates the hand pose by changing the orientations of the bones in a graphics model. The model itself is rotated and positioned based on the palm position.

ImageFullHand

PepperDarkCutHand

SaltLightHand

SaltMediumFullHand

class Leap::Unity::RiggedHand

This version of IHandModel supports a hand respresentation based on a skinned and jointed 3D model asset.

Public Functions

void AutoRigRiggedHand(Transform palm, Transform finger1, Transform finger2)

Sets up the rigged hand if RiggedFinger scripts have already been assigned using Mecanim values.

override void InitHand()

Implement this function to initialise this hand after it is created.

This function is called by the HandController during the Unity Update() phase when a new hand is detected by the Leap Motion device.

void RestoreJointsStartPose()

Restores original joint positions, particularly after model has been placed in Leap‘s editor pose.

void SetupRiggedHand()

Sets up the rigged hand by finding base of each finger by name.

void StoreJointsStartPose()

Stores a snapshot of original joint positions.

override bool SupportsEditorPersistence()

Returns whether or not this hand model supports editor persistence.

This is false by default and must be opt-in by a developer making their own hand model script if they want editor persistence.

override void UpdateHand()

Implement this function to update this hand once every game loop.

For HandModel instances assigned to the HandController graphics hand list, the HandController calls this function during the Unity Update() phase. For HandModel instances in the physics hand list, the HandController calls this function in the FixedUpdate() phase.

Public Static Functions

Vector3 CalculateZeroedVector(Vector3 vectorToZero)

Finds nearest cardinal vector to a vector.

Java Docs (v3.1)

API Overview

Guidelines

Application Development

Using the Tracking API

API Reference

Appendices


text:
#ifndef SEAFILE_CLIENT_DAEMON_MANAGER_H
#define SEAFILE_CLIENT_DAEMON_MANAGER_H

#include <QObject>
#include <QProcess>

class QTimer;

/**
 * Start/Monitor seafile daemon
 */
class DaemonManager : public QObject {
    Q_OBJECT

public:
    DaemonManager();
    ~DaemonManager();
    void startSeafileDaemon();

signals:
    void daemonStarted();

    void daemonDead();
    void daemonRestarted();

private slots:
    void onDaemonStarted();
    void onDaemonFinished(int exit_code, QProcess::ExitStatus exit_status);
    void systemShutDown();
    void checkDaemonReady();
    void restartSeafileDaemon();

private:
    Q_DISABLE_COPY(DaemonManager)

    void stopDaemon();
    void scheduleRestartDaemon();
    void transitionState(int new_state);

    QProcess *seaf_daemon_;
    QTimer *conn_daemon_timer_;

    int current_state_;
    // Used to decide whether to emit daemonStarted or daemonRestarted
    bool first_start_;
    int restart_retried_;
};

#endif // SEAFILE_CLIENT_DAEMON_MANAGER_H


text:
from datetime import datetime
from datetime import timedelta

from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone

from craigmine.craigslist import Craigslist
from craigmine.craigslist import querystring_to_dict
from craigmine.models import Item
from craigmine.models import Search

def get_all_search_ids():
    """
    Retrieves all the search IDs.

    :returns: all the search IDs.
    """
    # Retrieve all searches.
    search_ids = Search.objects.values('id')
    if not search_ids:
        return []
    return [d['id'] for d in search_ids]

def run_all_searches():
    """
    Run the indexing process for all the searches.

    :returns: A list of tuples containing the indexing results.
    """
    # Prepare variables.
    results = []

    # Retrieve all the available search ids.
    search_ids = get_all_search_ids()

    # Index each of them.
    for search_id in search_ids:
        indexed_summary = index_search_content(search_id)
        results.append(indexed_summary)

    # Return the results.
    return results

def index_search_content(search_id):
    """
    Returns a tuple containing information about the execution of the date indexed.

    This function ignores the entries that already exist in the databse.

    The returned tuple contains 4 values:
    * the tag describing the query
    * the number of found items
    * the number of indexed items
    * the date of the previous search update

    :param int search_id: ID of the search to index
    :returns: a tuple containing information about the execution of the date indexed.
    """

    # Load the search object.
    search = Search.objects.get(pk=search_id)

    # Load que the parameters.
    queries = search.query
    custom_search_args = search.custom_search_args
    params = {"hasPic": '1' if search.has_pic else '0',
              "min_price": search.min_ask,
              "max_price": search.max_ask,
              "s": 0,
              "sort": "date"}
    cl = Craigslist(search.server, search.category, params=params)

    # Prepare the query parameters.
    cl.params.update(querystring_to_dict(custom_search_args))

    # Retrieve and parse the items.
    requested_items = cl.query_n_parse()

    # Store them in the DB.
    count = 0
    for requested_item in requested_items.values():
        try:
            Item.objects.get(id=requested_item.get("clid"))
        except ObjectDoesNotExist:
            Item.objects.create(search=search,
                                id=requested_item.get("clid"),
                                link=requested_item.get("full_link"),
                                post_date=requested_item.get("post_date"),
                                pnr=requested_item.get("pnr"),
                                price=requested_item.get("price"),
                                title=requested_item.get("title", '?') or '?')
            count += 1

    # Update the search.
    search.save()

    return (search.tag, len(requested_items), count, search.last_update)

def delete_items(days_old):
    """
    Deletes the items older than a certain amount of days.

    If days_old is set to 0, *ALL* the objects will be deleted.

    :param int days_old: the number of days defining the threshold
    :return: the number of deleted items.
    """
    days_ago = datetime.today() - timedelta(days=days_old)
    items = Item.objects.filter(post_date__lt=timezone.make_aware(days_ago))
    item_count = len(items)
    items.delete()

    return item_count


text:
// 20140913nignt.h : main header file for the 20140913nignt application
//
#pragma once

#ifndef __AFXWIN_H__
	#error "include 'stdafx.h' before including this file for PCH"
#endif

#include "resource.h"       // main symbols

// CMy20140913nigntApp:
// See 20140913nignt.cpp for the implementation of this class
//

class CMy20140913nigntApp : public CWinAppEx
{
public:
	CMy20140913nigntApp();

// Overrides
public:
	virtual BOOL InitInstance();
	virtual int ExitInstance();

// Implementation
	UINT  m_nAppLook;
	BOOL  m_bHiColorIcons;

	virtual void PreLoadState();
	virtual void LoadCustomState();
	virtual void SaveCustomState();

	afx_msg void OnAppAbout();
	DECLARE_MESSAGE_MAP()
};

extern CMy20140913nigntApp theApp;


text:
import { put, call, fork } from 'redux-saga/effects';
import { takeLatest } from 'redux-saga';
import * as userActions from './userActions';
import * as actionTypes from '../actionTypes';
import Api from '../../../common/Api';

const api = new Api();

// Workers
export function * login ({ email, password }) {
  try {
    yield call(api.login, email, password);
    yield put(userActions.loginSuccess());
    window.location.href = '/';
  } catch (err) {
    yield put(userActions.loginFail(err));
  }
}

export function * recover ({ email }) {
  try {
    yield call(api.recover, email);
    yield put(userActions.recoverSuccess());
    window.location.href = '/';
  } catch (err) {
    yield put(userActions.recoverFail(err));
  }
}

export function * signup ({name, email, password, confirm}) {
  try {
    yield call(api.signup, name, email, password, confirm);
    yield put(userActions.signupSuccess());
    window.location.href = '/';
  } catch (err) {
    yield put(userActions.signupFail(err));
  }
}

// Watchers
function * watchLogin () {
  yield takeLatest(actionTypes.LOGIN_REQUEST, login);
}

function * watchRecover () {
  yield takeLatest(actionTypes.RECOVER_REQUEST, recover);
}

function * watchSignup () {
  yield takeLatest(actionTypes.SIGNUP_REQUEST, signup);
}

export default function * () {
  yield [
    fork(watchLogin),
    fork(watchRecover),
    fork(watchSignup)
  ];
}


text:
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */

function KeyBuffer() {
	this.buffer = '';

	return (key) => {
		if (this.timeout) {
			clearTimeout(this.timeout);
			this.timeout = undefined;
		}

		this.timeout = setTimeout(() => {
			this.buffer = '';
		}, 400);

		this.buffer = this.buffer + key;
		return this.buffer;
	};
}

export default KeyBuffer;


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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/y174">

        <!--头像-->
        <com.xiaoshangxing.utils.customView.CircleImage
            android:id="@+id/head_image"
            android:layout_width="@dimen/x108"
            android:layout_height="@dimen/x108"
            android:layout_centerVertical="true"
            android:src="@mipmap/greyblock" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/x26"
            android:layout_marginTop="@dimen/y30"
            android:layout_toRightOf="@+id/head_image"
            android:textColor="@color/b0"
            android:textSize="@dimen/x48" />

        <!--性别-->
        <ImageView
            android:id="@+id/sex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/x12"
            android:layout_marginTop="@dimen/y40"
            android:layout_toRightOf="@+id/name" />

        <!--学院-->
        <TextView
            android:id="@+id/college"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/name"
            android:layout_marginStart="@dimen/x26"
            android:layout_toRightOf="@+id/head_image"
            android:textColor="@color/g0"
            android:textSize="@dimen/x39" />

        <FrameLayout
            android:id="@+id/more"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:layout_marginEnd="@dimen/x28">

            <!--留心-->
            <LinearLayout
                android:id="@+id/love_lay"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:src="@mipmap/icon_dazhaohu" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:text="打个招呼"
                    android:textColor="@color/gray_login"
                    android:textSize="@dimen/x28" />

            </LinearLayout>

            <!--留心-->
            <LinearLayout
                android:id="@+id/star_lay"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingEnd="@dimen/x16">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:src="@mipmap/icon_liuxin_g2" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:text="留心"
                    android:textColor="@color/gray_login"
                    android:textSize="@dimen/x28" />

            </LinearLayout>

        </FrameLayout>
    </RelativeLayout>

</LinearLayout>


text:
package com.googlecode.gwt.crypto.gwtx.io;

/**
 * This IO exception is thrown when a program encounters some sort I/O error. Details may be
 * specified in the constructor or by one of the subclasses.
 *
 */
@SuppressWarnings("serial")
public class IOException extends Exception {

  /**
   * Constructs a new instance of this class with its walkback filled in.
   */
  public IOException() {
    super();
  }

  /**
   * Constructs a new instance of this class with its walkback and message filled in.
   *
   * @param detailMessage
   *          The detail message for the exception.
   */
  public IOException(String detailMessage) {
    super(detailMessage);
  }

}


text:
package javay.test.expr;

import javay.regex.expr.RExprParser;

public class TestRTestExpr {

    public static void main(String[] args) throws Exception {
        String pattern = "\\.(\\d*?)(9|0)\\2{5,}(\\d{1,5})$";
        RExprParser.parse(pattern);
    }

}


text:
This code provide a self-contained MNIST example of influence / memorization
estimation based on training with subsets of data.
Note that MNIST is a very simple dataset, and as we noted in the paper,
there are not many examples that are memorized or have very strong
influence on test examples. We chose this dataset as demo mainly
because it is extremely cheap to train a model on it. So we can
demonstrate the entire computing pipeline that trains 2,000 models
in a simple script, which can finish in a few hours by
running sequentially on a single GPU.

The code has the following dependencies:

* Python 3
* [JAX](https://github.com/google/jax)
* [tensorflow-datasets](https://www.tensorflow.org/datasets)
* [tqdm](https://github.com/tqdm/tqdm)
* Numpy, Matplotlib

After running, it will save the computed estimation in `infl_mem.npz`,
which will be ~2.3GB as the influence estimate is a 10,000 x 60,000
matrix. It will also output a plot in `mnist-examples.pdf`, which will
look like the figure shown below: in each row, the first digit is a test
example; the next 4 digits are the training examples ranked by their
influence on this test example; the last 5 digits show 5 random training
examples belonging to the same class as the test example.

![MNIST Examples](mnist-examples.png)


text:
package scaleway

import (
	"errors"
	"net/http"

	"github.com/scaleway/scaleway-sdk-go/scw"
)

// isHTTPCodeError returns true if err is an http error with code statusCode
func isHTTPCodeError(err error, statusCode int) bool {
	if err == nil {
		return false
	}

	responseError := &scw.ResponseError{}
	if errors.As(err, &responseError) && responseError.StatusCode == statusCode {
		return true
	}
	return false
}

// is404Error returns true if err is an HTTP 404 error
func is404Error(err error) bool {
	notFoundError := &scw.ResourceNotFoundError{}
	return isHTTPCodeError(err, http.StatusNotFound) || errors.As(err, &notFoundError)
}


text:
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :nombres, null: false
      t.string :email
      t.string :imagen_url
      t.boolean :admin, default: false
      t.boolean :banned, default: false
      t.timestamps
    end
  end
end


text:
package br.com.dlp.jazz.omr.model;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import br.com.dlp.jazzomr.question.QuestionVO;

public class TestDomainValidations {

	public static void main(String[] args) {

		Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

		QuestionVO questionVO = new QuestionVO();

		questionVO.setDescription("zubalele");

		Set<ConstraintViolation<QuestionVO>> a = validator.validate(questionVO);

		for (ConstraintViolation<QuestionVO> constraintViolation : a) {
			System.out.println(constraintViolation);
		}

	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/umeng_fb_send_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <View
        android:id="@+id/umeng_fb_reply_item_view_tag"
        android:layout_width="6dp"
        android:layout_height="match_parent"
        android:background="@color/umeng_fb_gray" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <View
            android:id="@+id/umeng_fb_reply_item_view_line"
            android:layout_width="match_parent"
            android:layout_height="@dimen/umeng_fb_item_line_height"
            android:background="@color/umeng_fb_line" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="6dp">

            <Button
                android:id="@+id/umeng_fb_send_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:background="@null"
                android:gravity="center"
                android:text="@string/umeng_fb_send"
                android:textColor="@color/umeng_fb_secondary_text_light"
                android:textSize="@dimen/umeng_fb_item_content_size" />

            <EditText
                android:id="@+id/umeng_fb_send_content"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerVertical="true"
                android:layout_marginEnd="10dp"
                android:layout_marginRight="10dp"
                android:layout_toLeftOf="@id/umeng_fb_send_btn"
                android:layout_toStartOf="@id/umeng_fb_send_btn"
                android:background="@null"
                android:focusable="true"
                android:hint="@string/umeng_fb_feedback"
                android:inputType="textCapSentences|textMultiLine"
                android:textSize="@dimen/umeng_fb_item_content_size" />
        </RelativeLayout>
    </LinearLayout>
</LinearLayout>


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.uccollaborationlib;
import com.wilutions.com.*;

/**
 * ModalityProperty.
 * Enumerates the modality properties.
 */
@SuppressWarnings("all")
@CoInterface(guid="{00000000-0000-0000-0000-000000000000}")
public class ModalityProperty {
  static boolean __typelib__loaded = __TypeLib.load();

  // Typed constants
  public final static ModalityProperty ucInstantMessageModalitySharedCapabilities = new ModalityProperty(537591808);
  public final static ModalityProperty ucInstantMessageModalityInviteMessage = new ModalityProperty(720897);
  public final static ModalityProperty ucInstantMessageModalityNoAutoAccept = new ModalityProperty(269156354);
  public final static ModalityProperty ucInstantMessageModalityInviteForked = new ModalityProperty(269156355);
  public final static ModalityProperty ucAVModalityAudioRenderVolume = new ModalityProperty(537591812);
  public final static ModalityProperty ucAVModalityAudioRenderMute = new ModalityProperty(269156357);
  public final static ModalityProperty ucAVModalityAudioRenderIntensity = new ModalityProperty(537591814);
  public final static ModalityProperty ucAVModalityAudioRenderIntensityMin = new ModalityProperty(537591815);
  public final static ModalityProperty ucAVModalityAudioRenderIntensityMax = new ModalityProperty(537591816);
  public final static ModalityProperty ucAVModalityAudioCaptureVolume = new ModalityProperty(537591817);
  public final static ModalityProperty ucAVModalityAudioCaptureMute = new ModalityProperty(269156362);
  public final static ModalityProperty ucAVModalityAudioCaptureIntensity = new ModalityProperty(537591819);
  public final static ModalityProperty ucAVModalityAudioCaptureIntensityMin = new ModalityProperty(537591820);
  public final static ModalityProperty ucAVModalityAudioCaptureIntensityMax = new ModalityProperty(537591821);
  public final static ModalityProperty ucAVModalityAudioCanCallComputer = new ModalityProperty(269156366);
  public final static ModalityProperty ucAVModalityAudioCanCallTelephone = new ModalityProperty(269156367);
  public final static ModalityProperty ucAVModalityAudioRenderDevice = new ModalityProperty(720912);
  public final static ModalityProperty ucAVModalityAudioCaptureDevice = new ModalityProperty(720913);
  public final static ModalityProperty ucAVModalityAudioSpeakerMode = new ModalityProperty(806027282);
  public final static ModalityProperty ucAVModalityAudioHistoryInfo = new ModalityProperty(1074462739);
  public final static ModalityProperty ucAVModalityAudioOriginalTargetUri = new ModalityProperty(720916);
  public final static ModalityProperty ucAVModalityAudioReferredByUri = new ModalityProperty(720917);
  public final static ModalityProperty ucAVModalityAudioSupportsAdvancedTransfer = new ModalityProperty(269156374);
  public final static ModalityProperty ucAVModalityAudioQuality = new ModalityProperty(806027287);
  public final static ModalityProperty ucAVModalityAudioOnHoldSource = new ModalityProperty(720920);
  public final static ModalityProperty ucAVModalityAudioOnHoldRepeated = new ModalityProperty(269156377);
  public final static ModalityProperty ucAVModalityAudioRemoteHoldFeature = new ModalityProperty(806027290);
  public final static ModalityProperty ucAVModalityIsAutoAccepted = new ModalityProperty(269156379);
  public final static ModalityProperty ucAVModalityAudioSupportsSafeTransfer = new ModalityProperty(269156380);
  public final static ModalityProperty ucAVModalityAudioNetworkQuality = new ModalityProperty(806027293);
  public final static ModalityProperty ucAVModalityAudioBandwidthQuality = new ModalityProperty(806027294);
  public final static ModalityProperty ucAVModalityAudioDeviceQuality = new ModalityProperty(806027295);
  public final static ModalityProperty ucAVModalityVoicemailItemId = new ModalityProperty(720928);
  public final static ModalityProperty ucAVModalityVideoNetworkQuality = new ModalityProperty(806027297);
  public final static ModalityProperty ucAVModalityVideoBandwidthQuality = new ModalityProperty(806027298);
  public final static ModalityProperty ucAVModalityVideoDeviceQuality = new ModalityProperty(806027299);
  public final static ModalityProperty ucAVModalityAudioIsEmergencyCall = new ModalityProperty(806027300);
  public final static ModalityProperty ucAVModalityUsbOffHookLedStatus = new ModalityProperty(269156389);
  public final static ModalityProperty ucAVModalityUsbDisplayName = new ModalityProperty(720934);
  public final static ModalityProperty ucApplicationSharingModalityCanShareMonitor = new ModalityProperty(806027303);
  public final static ModalityProperty ucApplicationSharingModalityCanShareApplications = new ModalityProperty(806027304);
  public final static ModalityProperty ucAVModalityAudioLocationSent = new ModalityProperty(1074495488);
  public final static ModalityProperty ucAVModalityAudioPrivateCall = new ModalityProperty(269189121);
  public final static ModalityProperty ucAVModalityAudioIsPersistentSession = new ModalityProperty(269189122);
  public final static ModalityProperty ucAVModalityAudioCannotDisconnectSession = new ModalityProperty(269189123);
  public final static ModalityProperty ucAVModalityAudioIsAudioMCUModeAllowed = new ModalityProperty(269189124);
  public final static ModalityProperty ucAVModalityAudioMCUSession = new ModalityProperty(269189125);
  public final static ModalityProperty ucAVModalityAudioRemoteSupportsReferExtensions = new ModalityProperty(269189126);
  public final static ModalityProperty ucAVModalityAudioRemoteSupportsSafeTransfer = new ModalityProperty(269189127);
  public final static ModalityProperty ucAVModalityAudioStartTime = new ModalityProperty(537624584);
  public final static ModalityProperty ucAVModalityAudioSupportsReplaces = new ModalityProperty(269189129);
  public final static ModalityProperty ucAVModalityExtendedAudioQuality = new ModalityProperty(1074495498);
  public final static ModalityProperty ucAVModalityVideoCapturePaused = new ModalityProperty(269189131);
  public final static ModalityProperty ucAVModalityVideoRenderPaused = new ModalityProperty(269189132);
  public final static ModalityProperty ucAVModalityVideoIsAVMCUModeAllowed = new ModalityProperty(269189133);
  public final static ModalityProperty ucAVModalityVideoStartTime = new ModalityProperty(537624590);
  public final static ModalityProperty ucAVModalityExtendedVideoQuality = new ModalityProperty(1074495503);
  public final static ModalityProperty ucAVModalityDTMFDigits = new ModalityProperty(753680);
  public final static ModalityProperty ucAVModalityUsbConvId = new ModalityProperty(753681);
  public final static ModalityProperty ucContentModalityPresentedContentIdAtDisconnect = new ModalityProperty(537624594);

  // Integer constants for bitsets and switch statements
  public final static int _ucInstantMessageModalitySharedCapabilities = 537591808;
  public final static int _ucInstantMessageModalityInviteMessage = 720897;
  public final static int _ucInstantMessageModalityNoAutoAccept = 269156354;
  public final static int _ucInstantMessageModalityInviteForked = 269156355;
  public final static int _ucAVModalityAudioRenderVolume = 537591812;
  public final static int _ucAVModalityAudioRenderMute = 269156357;
  public final static int _ucAVModalityAudioRenderIntensity = 537591814;
  public final static int _ucAVModalityAudioRenderIntensityMin = 537591815;
  public final static int _ucAVModalityAudioRenderIntensityMax = 537591816;
  public final static int _ucAVModalityAudioCaptureVolume = 537591817;
  public final static int _ucAVModalityAudioCaptureMute = 269156362;
  public final static int _ucAVModalityAudioCaptureIntensity = 537591819;
  public final static int _ucAVModalityAudioCaptureIntensityMin = 537591820;
  public final static int _ucAVModalityAudioCaptureIntensityMax = 537591821;
  public final static int _ucAVModalityAudioCanCallComputer = 269156366;
  public final static int _ucAVModalityAudioCanCallTelephone = 269156367;
  public final static int _ucAVModalityAudioRenderDevice = 720912;
  public final static int _ucAVModalityAudioCaptureDevice = 720913;
  public final static int _ucAVModalityAudioSpeakerMode = 806027282;
  public final static int _ucAVModalityAudioHistoryInfo = 1074462739;
  public final static int _ucAVModalityAudioOriginalTargetUri = 720916;
  public final static int _ucAVModalityAudioReferredByUri = 720917;
  public final static int _ucAVModalityAudioSupportsAdvancedTransfer = 269156374;
  public final static int _ucAVModalityAudioQuality = 806027287;
  public final static int _ucAVModalityAudioOnHoldSource = 720920;
  public final static int _ucAVModalityAudioOnHoldRepeated = 269156377;
  public final static int _ucAVModalityAudioRemoteHoldFeature = 806027290;
  public final static int _ucAVModalityIsAutoAccepted = 269156379;
  public final static int _ucAVModalityAudioSupportsSafeTransfer = 269156380;
  public final static int _ucAVModalityAudioNetworkQuality = 806027293;
  public final static int _ucAVModalityAudioBandwidthQuality = 806027294;
  public final static int _ucAVModalityAudioDeviceQuality = 806027295;
  public final static int _ucAVModalityVoicemailItemId = 720928;
  public final static int _ucAVModalityVideoNetworkQuality = 806027297;
  public final static int _ucAVModalityVideoBandwidthQuality = 806027298;
  public final static int _ucAVModalityVideoDeviceQuality = 806027299;
  public final static int _ucAVModalityAudioIsEmergencyCall = 806027300;
  public final static int _ucAVModalityUsbOffHookLedStatus = 269156389;
  public final static int _ucAVModalityUsbDisplayName = 720934;
  public final static int _ucApplicationSharingModalityCanShareMonitor = 806027303;
  public final static int _ucApplicationSharingModalityCanShareApplications = 806027304;
  public final static int _ucAVModalityAudioLocationSent = 1074495488;
  public final static int _ucAVModalityAudioPrivateCall = 269189121;
  public final static int _ucAVModalityAudioIsPersistentSession = 269189122;
  public final static int _ucAVModalityAudioCannotDisconnectSession = 269189123;
  public final static int _ucAVModalityAudioIsAudioMCUModeAllowed = 269189124;
  public final static int _ucAVModalityAudioMCUSession = 269189125;
  public final static int _ucAVModalityAudioRemoteSupportsReferExtensions = 269189126;
  public final static int _ucAVModalityAudioRemoteSupportsSafeTransfer = 269189127;
  public final static int _ucAVModalityAudioStartTime = 537624584;
  public final static int _ucAVModalityAudioSupportsReplaces = 269189129;
  public final static int _ucAVModalityExtendedAudioQuality = 1074495498;
  public final static int _ucAVModalityVideoCapturePaused = 269189131;
  public final static int _ucAVModalityVideoRenderPaused = 269189132;
  public final static int _ucAVModalityVideoIsAVMCUModeAllowed = 269189133;
  public final static int _ucAVModalityVideoStartTime = 537624590;
  public final static int _ucAVModalityExtendedVideoQuality = 1074495503;
  public final static int _ucAVModalityDTMFDigits = 753680;
  public final static int _ucAVModalityUsbConvId = 753681;
  public final static int _ucContentModalityPresentedContentIdAtDisconnect = 537624594;

  // Value, readonly field.
  public final int value;

  // Private constructor, use valueOf to create an instance.
  private ModalityProperty(int value) { this.value = value; }

  // Return one of the predefined typed constants for the given value or create a new object.
  public static  ModalityProperty valueOf(int value) {
    switch(value) {
    case 537591808: return ucInstantMessageModalitySharedCapabilities;
    case 720897: return ucInstantMessageModalityInviteMessage;
    case 269156354: return ucInstantMessageModalityNoAutoAccept;
    case 269156355: return ucInstantMessageModalityInviteForked;
    case 537591812: return ucAVModalityAudioRenderVolume;
    case 269156357: return ucAVModalityAudioRenderMute;
    case 537591814: return ucAVModalityAudioRenderIntensity;
    case 537591815: return ucAVModalityAudioRenderIntensityMin;
    case 537591816: return ucAVModalityAudioRenderIntensityMax;
    case 537591817: return ucAVModalityAudioCaptureVolume;
    case 269156362: return ucAVModalityAudioCaptureMute;
    case 537591819: return ucAVModalityAudioCaptureIntensity;
    case 537591820: return ucAVModalityAudioCaptureIntensityMin;
    case 537591821: return ucAVModalityAudioCaptureIntensityMax;
    case 269156366: return ucAVModalityAudioCanCallComputer;
    case 269156367: return ucAVModalityAudioCanCallTelephone;
    case 720912: return ucAVModalityAudioRenderDevice;
    case 720913: return ucAVModalityAudioCaptureDevice;
    case 806027282: return ucAVModalityAudioSpeakerMode;
    case 1074462739: return ucAVModalityAudioHistoryInfo;
    case 720916: return ucAVModalityAudioOriginalTargetUri;
    case 720917: return ucAVModalityAudioReferredByUri;
    case 269156374: return ucAVModalityAudioSupportsAdvancedTransfer;
    case 806027287: return ucAVModalityAudioQuality;
    case 720920: return ucAVModalityAudioOnHoldSource;
    case 269156377: return ucAVModalityAudioOnHoldRepeated;
    case 806027290: return ucAVModalityAudioRemoteHoldFeature;
    case 269156379: return ucAVModalityIsAutoAccepted;
    case 269156380: return ucAVModalityAudioSupportsSafeTransfer;
    case 806027293: return ucAVModalityAudioNetworkQuality;
    case 806027294: return ucAVModalityAudioBandwidthQuality;
    case 806027295: return ucAVModalityAudioDeviceQuality;
    case 720928: return ucAVModalityVoicemailItemId;
    case 806027297: return ucAVModalityVideoNetworkQuality;
    case 806027298: return ucAVModalityVideoBandwidthQuality;
    case 806027299: return ucAVModalityVideoDeviceQuality;
    case 806027300: return ucAVModalityAudioIsEmergencyCall;
    case 269156389: return ucAVModalityUsbOffHookLedStatus;
    case 720934: return ucAVModalityUsbDisplayName;
    case 806027303: return ucApplicationSharingModalityCanShareMonitor;
    case 806027304: return ucApplicationSharingModalityCanShareApplications;
    case 1074495488: return ucAVModalityAudioLocationSent;
    case 269189121: return ucAVModalityAudioPrivateCall;
    case 269189122: return ucAVModalityAudioIsPersistentSession;
    case 269189123: return ucAVModalityAudioCannotDisconnectSession;
    case 269189124: return ucAVModalityAudioIsAudioMCUModeAllowed;
    case 269189125: return ucAVModalityAudioMCUSession;
    case 269189126: return ucAVModalityAudioRemoteSupportsReferExtensions;
    case 269189127: return ucAVModalityAudioRemoteSupportsSafeTransfer;
    case 537624584: return ucAVModalityAudioStartTime;
    case 269189129: return ucAVModalityAudioSupportsReplaces;
    case 1074495498: return ucAVModalityExtendedAudioQuality;
    case 269189131: return ucAVModalityVideoCapturePaused;
    case 269189132: return ucAVModalityVideoRenderPaused;
    case 269189133: return ucAVModalityVideoIsAVMCUModeAllowed;
    case 537624590: return ucAVModalityVideoStartTime;
    case 1074495503: return ucAVModalityExtendedVideoQuality;
    case 753680: return ucAVModalityDTMFDigits;
    case 753681: return ucAVModalityUsbConvId;
    case 537624594: return ucContentModalityPresentedContentIdAtDisconnect;
    default: return new ModalityProperty(value);
    }
  }
}


text:
<html>
<body>
No match found. Try again later.
</body>
</html>


text:
/**
 * Test the global selector
 */

import globalSelector from '../globalSelector';
import { fromJS } from 'immutable';
import expect from 'expect';

describe('globalSelector', () => {
    it('should select the global state', () => {
        const globalState = fromJS({});
        const mockedState = fromJS({
            global: globalState,
        });
        expect(globalSelector(mockedState)).toEqual(globalState);
    });
});


text:
namespace boost
{
namespace lexer
{
// IMPORTANT! This won't work if you don't enable RTTI!
template<typename CharT, class Archive>
void serialise (basic_state_machine<CharT> &sm_, Archive &ar_, unsigned int version_ = 1)
{
    ar_ & version_;
    ar_ & *sm_._lookup;
    ar_ & sm_._dfa_alphabet;
    ar_ & *sm_._dfa;
    ar_ & sm_._seen_BOL_assertion;
    ar_ & sm_._seen_EOL_assertion;
}
}
}

#endif


text:
import { createActionSet } from 'utils';

export const GET_REPOSITORY_CONTENTS = createActionSet(
  'GET_REPOSITORY_CONTENTS'
);
export const GET_COMMIT = createActionSet('GET_COMMIT');
export const GET_COMMIT_DIFF = createActionSet('GET_COMMIT_DIFF');
export const GET_REPOSITORY_FILE = createActionSet('GET_REPOSITORY_FILE');
export const GET_REPOSITORY_COMMITS = createActionSet('GET_REPOSITORY_COMMITS');
export const GET_REPOSITORY_README = createActionSet('GET_REPOSITORY_README');
export const GET_REPOSITORY_LABELS = createActionSet('GET_REPOSITORY_LABELS');


text:
TimeSliderView
================

### Description
UIView which works like UISlider to let the user to select time. Features:
- Ability to change time between 12 hours (AM/PM) and 24 hours modes.
- Horizontal and vertical layouts.
- Ability to change color schemes.
- Allows to click above and below slider handle to increase/decrease time by specified step.
- Ability to change minutes/hours step.


text:
using GRA.SRP.DAL;
using GRA.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GRA.SRP.Controls {
    public partial class BooksRead : System.Web.UI.UserControl {
        protected void Page_Load(object sender, EventArgs e) {
            if(!IsPostBack) {
                var currentPatron = (Patron)Session["Patron"];

                if(currentPatron.IsMasterAccount) {
                    familyMemberSelector.Visible = true;

                    var ds = Patron.GetSubAccountList(currentPatron.PID);
                    PID.Items.Add(new ListItem(DisplayHelper.FormatName(currentPatron.FirstName,
                                                                        currentPatron.LastName,
                                                                        currentPatron.Username),
                                               currentPatron.PID.ToString()));
                    for(int i = 0; i < ds.Tables[0].Rows.Count; i++) {
                        PID.Items.Add(new ListItem(DisplayHelper.FormatName(ds.Tables[0].Rows[i]["FirstName"].ToString(),
                                                                            ds.Tables[0].Rows[i]["LastName"].ToString(),
                                                                            ds.Tables[0].Rows[i]["Username"].ToString()),
                                                   ds.Tables[0].Rows[i]["PID"].ToString()));
                    }
                    PID.SelectedValue = currentPatron.PID.ToString();
                }
                PopulateList(currentPatron.PID.ToString());
            }
        }

        protected void Ddl_SelectedIndexChanged(object sender, EventArgs e) {
            PopulateList(PID.SelectedValue);
        }

        protected void PopulateList(string patronId) {
            int patronIdNumeric = int.Parse(patronId);
            var patron = Patron.FetchObject(patronIdNumeric);
            whoRead.Text = DisplayHelper.FormatName(patron.FirstName, patron.LastName, patron.Username);
            var ds = Patron.GetReadingList(patronIdNumeric);
            rptr.DataSource = ds;
            rptr.DataBind();
            noBooksLabel.Visible = ds.Tables[0].Rows.Count == 0;
            booksPanel.Visible = !noBooksLabel.Visible;
        }
    }
}


text:
#ifndef BOOST_SPIRIT_FUNCTOR_PARSER_HPP
#define BOOST_SPIRIT_FUNCTOR_PARSER_HPP

///////////////////////////////////////////////////////////////////////////////
#include "boost/spirit/core/parser.hpp"

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit {

    ///////////////////////////////////////////////////////////////////////////
    //
    //  functor_parser class
    //
    //      Once a functor parser has been defined, you can build a real
    //      parser from it by passing it to this class as the template
    //      parameter.
    //
    ///////////////////////////////////////////////////////////////////////////
    template < class FunctorT >
    struct functor_parser : public parser<functor_parser<FunctorT> >
    {
        FunctorT functor;

        functor_parser(): functor() {}
        functor_parser(FunctorT const& functor_): functor(functor_) {}

        typedef typename FunctorT::result_t functor_result_t;
        typedef functor_parser<FunctorT> self_t;

        template <typename ScannerT>
        struct result
        {
            typedef typename match_result<ScannerT, functor_result_t>::type
            type;
        };

        template <typename ScannerT>
        typename parser_result<self_t, ScannerT>::type
        parse(ScannerT const& scan) const
        {
            typedef typename parser_result<self_t, ScannerT>::type result_t;
            typedef typename ScannerT::value_t      value_t;
            typedef typename ScannerT::iterator_t   iterator_t;

            iterator_t const s(scan.first);
            functor_result_t result;
            int const len = functor(scan, result);

            if (len < 0)
                return scan.no_match();
            else
                return scan.create_match(len, result, s, scan.first);
        }
    };

}} // namespace boost::spirit

#endif


text:
@interface PodsDummy_Pods_alwaysawakeUITests : NSObject
@end
@implementation PodsDummy_Pods_alwaysawakeUITests
@end


text:
<?php

namespace Martin\core\exceptions;

class RuntimeError extends \Exception
{

}


text:
from warnings import warn

CHUNK_SIZE = 1024 * 10

def http_key(key):
    """content-type --> Content-Type"""
    return key.replace('_', '-').title()

class Header(object):
    """Store response header, Also be used in request._form and request._file.
    Header class support three ways to initialize:
    1. Supply a dict object
    2. DO NOT Supply a dict or list object, but gives key-value pairs
    3. Supply a list object

    Data-structure:
    self._list = [(key1, value1), (key2, value2), ...]
    """
    def __init__(self, _dict_list=None, base=True, *args, **kwargs):
        # self._list = [(key, value), (key, value), ...]
        self._list = []

        # Flag for judge whether this class is used to be a instance of HTTP Header.
        # Currently, it is useful when Header class is used in request._form and request._file
        self.base = base

        if not _dict_list:
            for key, value in dict(*args, **kwargs).iteritems():
                self._list.append((key, value))
        elif isinstance(_dict_list, dict):
            for key, value in _dict_list.iteritems():
                self._list.append((key, value))
        elif isinstance(_dict_list, list):
            self._list.extend(_dict_list)
        else:
            warn(
                'The response head is initialized to None, '
                'because the param is not dict or list.', UserWarning
            )

    def __setitem__(self, key, value):
        if isinstance(key, int):
            self._list[key] = value
        else:
            key = http_key(key) if self.base else key
            for _id, (_key, _value) in enumerate(self._list):
                if _key == key:
                    self._list[_id] = (_key, str(_value))
                    break
            else:
                self.add(key, str(value))

    def __getitem__(self, item):
        if isinstance(item, int):
            return self._list[item]
        item = http_key(item) if self.base else item
        for key, value in self._list:
            if key == item:
                return value

    def __delitem__(self, key):
        if isinstance(key, int):
            del self._list[key]
        else:
            key = http_key(key) if self.base else key
            for _id, _key, _value in enumerate(self._list):
                if key == _key:
                    del self._list[_id]

    def __iter__(self):
        return iter(self._list)

    def add(self, key, value):
        self._list.append((key, value))

    def get(self, key):
        key = http_key(key) if self.base else key
        for _key, _value in self._list:
            if _key == key:
                return _value
        return None

    def head_to_list(self, charset='utf-8'):
        result = []
        for key, value in self:
            if isinstance(value, unicode):
                value = value.encode(charset)
            else:
                value = str(value)
            result.append((key, value))
        return result

    def __str__(self):
        string = ''
        for key, value in self.head_to_list():
            string += '%s: %s\r\n' % (key, value)
        return string

class EnvironHeader(object):
    """A data structure for request.environ.
    It will convert the input key to a standard key when users want to
    get the value of key
    """

    def __init__(self, environ):
        self.environ = environ

    def __len__(self):
        return len(dict(iter(self)))

    def __getitem__(self, item):
        item = self.handle_http_key(item)
        if item in ('CONTENT_LENGTH', 'CONTENT_TYPE'):
            return self.environ[item]
        return self.environ['HTTP_' + item]

    def __iter__(self):
        for key, value in self.environ.iteritems():
            if key.startswith('HTTP_') and \
                            key not in ('HTTP_CONTENT_LENGTH', 'HTTP_CONTENT_TYPE'):
                yield http_key(key[5:]), value
            elif key in ('CONTENT_LENGTH', 'CONTENT_TYPE'):
                yield http_key(key), value

    def handle_http_key(self, key):
        """content-type --> CONTENT_TYPE"""
        return key.upper().replace('-', '_')

class IterStream(object):
    """
    Make an instance of the object, which can get the data which size is limited.
    """
    def __init__(self, stream, end):
        """Init the IterStream.

        :param stream: the data stream
        :param end: the size of the data
        """
        self._pos = 0
        self.end = end
        self._read = stream.read
        self._readline = stream.readline

    def __iter__(self):
        return self

    def next(self):
        line = self.readline()
        if not line:
            raise StopIteration()
        # if line[-2:] == '\r\n':
        #     return line[:-2]
        return line

    def read(self, size=CHUNK_SIZE):
        """Read the stream, if the size is given, read the constant size data."""
        if self._pos >= self.end:
            return ''
        read = self._read(min(self.end-self._pos, size))
        self._pos += len(read)
        return read

    def readline(self, size=None):
        if self._pos >= self.end:
            return ''
        if size is None:
            size = self.end - self._pos
        else:
            size = min(self.end-self._pos, size)
        line = self._readline(size)

        self._pos += len(line)
        return line

    @property
    def is_exhausted(self):
        return self._pos >= self.end

class File(object):

    def __init__(self, stream, file_name, content_type='application/octet-stream'):
        self.file_name = file_name
        self.stream = stream
        self.content_type = content_type

    def read_data_from_stream(self, stream, chunk_size=CHUNK_SIZE):
        """Get the constant size data from the stream. It is a generater."""
        stream.seek(0)
        while True:
            data = stream.read(chunk_size)
            if not data:
                break
            yield data

    def create(self, destination):
        """Create a new file, and set data of the stream into the file."""
        with open(destination, 'w+b') as f:
            for data in self.read_data_from_stream(self.stream):
                f.write(data)
        self.close()

    def close(self):
        """Close the underlying file if possible."""
        try:
            self.stream.close()
        except:
            pass

    def __repr__(self):
        return '<%s: %r (%r)>' % (
            self.__class__.__name__,
            self.file_name,
            self.content_type
        )


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>pentaho</groupId>
    <artifactId>pentaho-osgi-bundles</artifactId>
    <version>7.1-SNAPSHOT</version>
  </parent>
  <artifactId>pentaho-i18n-bundle</artifactId>
  <version>7.1-SNAPSHOT</version>
  <packaging>bundle</packaging>
  <name>Pentaho Community Edition Project: ${project.artifactId}</name>
  <description>a Pentaho open source project</description>
  <url>http://www.pentaho.com</url>
  <dependencies>
    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.apache.felix.framework</artifactId>
      <version>${felix.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.apache.felix.fileinstall</artifactId>
      <version>${felix-fileinstall.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.karaf</groupId>
      <artifactId>org.apache.karaf.util</artifactId>
      <version>${karaf.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j-api.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava.version}</version>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>${json-simple.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
      <version>${cxf.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxws</artifactId>
      <version>${cxf.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-transports-http</artifactId>
      <version>${cxf.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-transports-http-jetty</artifactId>
      <version>${cxf.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>${mockito.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <resources>
      <resource>
        <filtering>false</filtering>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*</include>
        </includes>
        <excludes>
          <exclude>OSGI-INF/blueprint/*</exclude>
        </excludes>
      </resource>
      <resource>
        <filtering>true</filtering>
        <directory>src/main/resources</directory>
        <includes>
          <include>OSGI-INF/blueprint/*</include>
        </includes>
      </resource>
    </resources>
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>2.3.7</version>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
            <Bundle-Version>${project.version}</Bundle-Version>
            <Export-Package>org.pentaho.osgi.i18n</Export-Package>
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
import flask
import uuid
import os
from werkzeug import utils as werkzeug_utils

from infosystem.common.subsystem import manager
from infosystem.common.subsystem import operation

# TODO(samueldmq): put this in the app config
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = ['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'csv']

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

class Create(operation.Create):

    def pre(self, session, **kwargs):
        # TODO(samueldmq): replace with proper domain_id
        self.domain_id = self.manager.api.domains.list(name='default')[0].id

        self.file = flask.request.files.get('file', None)
        if self.file and allowed_file(self.file.filename):
            filename = werkzeug_utils.secure_filename(self.file.filename)
            self.entity = self.driver.instantiate(
                id=uuid.uuid4().hex, domain_id=self.domain_id, name=filename)
        else:
            # NOTE(samueldmq): this will force a 400 since the name is not
            # provided, raise specific exception here about the file
            self.entity = self.driver.instantiate(
                id=uuid.uuid4().hex, domain_id=self.domain_id)

        return self.entity.is_stable()

    def do(self, session, **kwargs):
        folder = os.path.join(UPLOAD_FOLDER, self.domain_id)
        if not os.path.exists(folder):
            os.makedirs(folder)
        self.file.save(os.path.join(folder, self.entity.name))
        super().do(session)

class Get(operation.Get):

    def do(self, session, **kwargs):
        file = super().do(session, **kwargs)

        folder = os.path.join(UPLOAD_FOLDER, file.domain_id)
        return flask.send_from_directory(folder, file.name)

class Manager(manager.Manager):

    def __init__(self, driver):
        super().__init__(driver)
        self.create = Create(self)
        self.get = Get(self)


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

<title>ParameterParser.Recognizer (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.hibernate.engine.query.spi

Interface ParameterParser.Recognizer

All Known Implementing Classes:

ParamLocationRecognizer, SQLQueryParser.ParameterSubstitutionRecognizer

Enclosing class:

ParameterParser

public static interface ParameterParser.Recognizer

Maybe better named a Journaler.  Essentially provides a callback contract for things that recognize parameters

Method Summary

Methods

Modifier and Type
Method and Description

void
jpaPositionalParameter(String name,
                      int position)

void
namedParameter(String name,
              int position)

void
ordinalParameter(int position)

void
other(char character)

void
outParameter(int position)

Method Detail

outParameter

void outParameter(int position)

Called when an output parameter is recognized

Parameters:

position - The position within the query

ordinalParameter

void ordinalParameter(int position)

Called when an ordinal parameter is recognized

Parameters:

position - The position within the query

namedParameter

void namedParameter(String name,
                  int position)

Called when a named parameter is recognized

Parameters:

name - The recognized parameter name

position - The position within the query

jpaPositionalParameter

void jpaPositionalParameter(String name,
                          int position)

Called when a JPA-style named parameter is recognized

Parameters:

name - The name of the JPA-style parameter

position - The position within the query

other

void other(char character)

Called when a character that is not a parameter (or part of a parameter dfinition) is recognized.

Parameters:

character - The recognized character

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
/**
 * This file is automatically generated by wheat-build.
 * Do not modify this file -- YOUR CHANGES WILL BE ERASED!
 */

package x7c1.linen.glue.res.layout;

import android.view.View;

public class SourceSearchRowFooter extends SourceSearchRow {

    public SourceSearchRowFooter(
        View itemView
    ){
        super(itemView);

    }
}


text:
namespace peloton {
namespace test {

class InsertSQLTests : public PelotonTest {};

void CreateAndLoadTable() {
  // Create a table first
  TestingSQLUtil::ExecuteSQLQuery(
      "CREATE TABLE test(a INT PRIMARY KEY, b INT, c INT);");

  // Insert tuples into table
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test VALUES (1, 22, 333);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test VALUES (2, 11, 000);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test VALUES (3, 33, 444);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test VALUES (4, 00, 555);");
}

void CreateAndLoadTable2() {
  // Create a table first
  TestingSQLUtil::ExecuteSQLQuery(
      "CREATE TABLE test2(a INT PRIMARY KEY, b INT, c INT);");

  // Insert tuples into table
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test2 VALUES (5, 99, 888);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test2 VALUES (6, 88, 777);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test2 VALUES (7, 77, 666);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test2 VALUES (8, 55, 999);");
}

void CreateAndLoadTable3() {
  // Create a table first
  TestingSQLUtil::ExecuteSQLQuery(
      "CREATE TABLE test3(a INT, b CHAR(4), c VARCHAR(10));");
}

void CreateAndLoadTable4() {
  // Create a table first
  TestingSQLUtil::ExecuteSQLQuery(
      "CREATE TABLE test4(a INT PRIMARY KEY, b TINYINT, c SMALLINT, "
      "d BIGINT, e DECIMAL, f DOUBLE, g TIMESTAMP, "
      "i CHAR, j VARCHAR, k VARBINARY, l BOOLEAN);");

  // Insert tuples into table
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test4 VALUES "
      "(1, 2, 3, 4, 5.1, 6.1, '2017-10-10 00:00:00-00', "
      "'A', 'a', '1', 'true');");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test4 VALUES "
      "(11, 12, 13, 14, 15.1, 16.1, '2017-10-11 00:00:00-00', "
      "'B', 'b', '2', 'false');");
}

void CreateAndLoadTable5() {
  // Create a table first
  TestingSQLUtil::ExecuteSQLQuery(
      "CREATE TABLE test5(a INT PRIMARY KEY, b TINYINT, c SMALLINT, "
      "d BIGINT, e DECIMAL, f DOUBLE, g TIMESTAMP, "
      "i CHAR, j VARCHAR, k VARBINARY, l BOOLEAN);");
}

void CreateAndLoadTable6() {
  // Create a table first
  TestingSQLUtil::ExecuteSQLQuery(
      "CREATE TABLE test6(a INT, b INT, c INT);");

  // Insert tuples into table
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test6 VALUES (1, 22, 333);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test6 VALUES (2, 11, 000);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test6 VALUES (3, 33, 444);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test6 VALUES (4, 00, 555);");
}

void CreateAndLoadTable7() {
  // Create a table first
  TestingSQLUtil::ExecuteSQLQuery(
      "CREATE TABLE test7(a INT, b INT, c INT);");

  // Insert tuples into table
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test7 VALUES (99, 5, 888);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test7 VALUES (88, 6, 777);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test7 VALUES (77, 7, 666);");
  TestingSQLUtil::ExecuteSQLQuery("INSERT INTO test7 VALUES (55, 8, 999);");
}

TEST_F(InsertSQLTests, InsertOneValue) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);

  CreateAndLoadTable();

  std::vector<ResultValue> result;
  std::vector<FieldInfo> tuple_descriptor;
  std::string error_message;
  int rows_changed;
  std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
      new optimizer::Optimizer());

  // INSERT a tuple
  std::string query("INSERT INTO test VALUES (5, 55, 555);");

  txn = txn_manager.BeginTransaction();
  auto plan = TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query, txn);
  txn_manager.CommitTransaction(txn);
  EXPECT_EQ(plan->GetPlanNodeType(), PlanNodeType::INSERT);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, query, result, tuple_descriptor, rows_changed, error_message);

  EXPECT_EQ(1, rows_changed);

  // SELECT to find out if the data is correctly inserted
  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test WHERE a=5", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("5", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("55", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("555", TestingSQLUtil::GetResultValueAsString(result, 2));

  // free the database just created
  txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);
}

TEST_F(InsertSQLTests, InsertMultipleValues) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);

  CreateAndLoadTable();

  std::vector<ResultValue> result;
  std::vector<FieldInfo> tuple_descriptor;
  std::string error_message;
  int rows_changed;
  std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
      new optimizer::Optimizer());

  // INSERT multiple tuples
  std::string query("INSERT INTO test VALUES (6, 11, 888), (7, 77, 999);");

  txn = txn_manager.BeginTransaction();
  auto plan = TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query, txn);
  EXPECT_EQ(plan->GetPlanNodeType(), PlanNodeType::INSERT);
  txn_manager.CommitTransaction(txn);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, query, result, tuple_descriptor, rows_changed, error_message);

  EXPECT_EQ(2, rows_changed);

  // SELECT to find out if the tuples are correctly inserted
  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test WHERE a=6", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("6", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("11", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("888", TestingSQLUtil::GetResultValueAsString(result, 2));

  // SELECT to find out if the tuples are correctly inserted
  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test WHERE a=7", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("7", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("77", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("999", TestingSQLUtil::GetResultValueAsString(result, 2));

  // free the database just created
  txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);
}

TEST_F(InsertSQLTests, InsertSpecifyColumns) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);

  CreateAndLoadTable();

  std::vector<ResultValue> result;
  std::vector<FieldInfo> tuple_descriptor;
  std::string error_message;
  int rows_changed;
  std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
      new optimizer::Optimizer());

  // INSERT a tuple with columns specified
  std::string query("INSERT INTO test (b, a, c) VALUES (99, 8, 111);");

  txn = txn_manager.BeginTransaction();
  auto plan = TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query, txn);
  EXPECT_EQ(plan->GetPlanNodeType(), PlanNodeType::INSERT);
  txn_manager.CommitTransaction(txn);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, query, result, tuple_descriptor, rows_changed, error_message);

  EXPECT_EQ(1, rows_changed);

  // SELECT to find out if the tuple is correctly inserted
  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test WHERE a=8", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("8", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("99", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("111", TestingSQLUtil::GetResultValueAsString(result, 2));

  // free the database just created
  txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);
}

TEST_F(InsertSQLTests, InsertTooLargeVarchar) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);

  CreateAndLoadTable3();

  std::vector<ResultValue> result;
  std::vector<FieldInfo> tuple_descriptor;
  std::string error_message;
  int rows_changed;
  std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
      new optimizer::Optimizer());

  std::string query("INSERT INTO test3 VALUES(1, 'abcd', 'abcdefghij');");
  //std::string query("INSERT INTO test3 VALUES(1, 'abcd', 'abcdefghijk');");

  txn = txn_manager.BeginTransaction();
  // This should be re-enabled when the check is properly done in catalog
  // It used to be done at the insert query level
  //EXPECT_THROW(TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query,
  //             txn, peloton::Exception);
  auto plan = TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query, txn);
  EXPECT_EQ(plan->GetPlanNodeType(), PlanNodeType::INSERT);
  txn_manager.CommitTransaction(txn);

  rows_changed = 0;
  TestingSQLUtil::ExecuteSQLQuery(query, result, tuple_descriptor, rows_changed,
                                  error_message);
  EXPECT_EQ(1, rows_changed);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test3;", result, tuple_descriptor, rows_changed,
      error_message);
  EXPECT_EQ(3, result.size());

  // free the database just created
  txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);
}

TEST_F(InsertSQLTests, InsertIntoSelectSimple) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);

  CreateAndLoadTable();
  CreateAndLoadTable2();

  std::vector<ResultValue> result;
  std::vector<FieldInfo> tuple_descriptor;
  std::string error_message;
  int rows_changed;
  std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
      new optimizer::Optimizer());

  // TEST CASE 1
  std::string query_1("INSERT INTO test SELECT * FROM test2;");

  txn = txn_manager.BeginTransaction();
  auto plan =
      TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query_1, txn);
  txn_manager.CommitTransaction(txn);
  EXPECT_EQ(plan->GetPlanNodeType(), PlanNodeType::INSERT);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query_1, result,
                                               tuple_descriptor, rows_changed,
                                               error_message);

  EXPECT_EQ(4, rows_changed);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test WHERE a=8", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("8", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("55", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("999", TestingSQLUtil::GetResultValueAsString(result, 2));

  // TEST CASE 2
  std::string query_2("INSERT INTO test2 SELECT * FROM test WHERE a=1;");
  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query_2, result,
                                               tuple_descriptor, rows_changed,
                                               error_message);
  EXPECT_EQ(1, rows_changed);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test2 WHERE a=1", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("22", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("333", TestingSQLUtil::GetResultValueAsString(result, 2));

  // TEST CASE 3
  std::string query_3("INSERT INTO test2 SELECT b,a,c FROM test WHERE a=2;");
  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query_3, result,
                                               tuple_descriptor, rows_changed,
                                               error_message);
  EXPECT_EQ(1, rows_changed);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test2 WHERE a=11", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("11", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("0", TestingSQLUtil::GetResultValueAsString(result, 2));

  // free the database just created
  txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);
}

TEST_F(InsertSQLTests, InsertIntoSelectSimpleAllType) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);

  CreateAndLoadTable4();
  CreateAndLoadTable5();

  std::vector<ResultValue> result;
  std::vector<FieldInfo> tuple_descriptor;
  std::string error_message;
  int rows_changed;
  std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
      new optimizer::Optimizer());

  // TEST CASE 1
  std::string query_1("INSERT INTO test5 SELECT * FROM test4;");

  txn = txn_manager.BeginTransaction();
  auto plan =
      TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query_1, txn);
  txn_manager.CommitTransaction(txn);
  EXPECT_EQ(plan->GetPlanNodeType(), PlanNodeType::INSERT);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query_1, result,
                                               tuple_descriptor, rows_changed,
                                               error_message);

  EXPECT_EQ(2, rows_changed);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test4 WHERE a=1", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(11, result.size());
  EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("3", TestingSQLUtil::GetResultValueAsString(result, 2));
  EXPECT_EQ("4", TestingSQLUtil::GetResultValueAsString(result, 3));
  EXPECT_EQ("5.1", TestingSQLUtil::GetResultValueAsString(result, 4));
  EXPECT_EQ("6.1", TestingSQLUtil::GetResultValueAsString(result, 5));
  EXPECT_EQ("2017-10-10 00:00:00.000000+00",
             TestingSQLUtil::GetResultValueAsString(result, 6));
  EXPECT_EQ("A", TestingSQLUtil::GetResultValueAsString(result, 7));
  EXPECT_EQ("a", TestingSQLUtil::GetResultValueAsString(result, 8));
  EXPECT_EQ('1', TestingSQLUtil::GetResultValueAsString(result, 9).at(0));
  EXPECT_EQ("true", TestingSQLUtil::GetResultValueAsString(result, 10));

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test5 WHERE a=1", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(11, result.size());
  EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("3", TestingSQLUtil::GetResultValueAsString(result, 2));
  EXPECT_EQ("4", TestingSQLUtil::GetResultValueAsString(result, 3));
  EXPECT_EQ("5.1", TestingSQLUtil::GetResultValueAsString(result, 4));
  EXPECT_EQ("6.1", TestingSQLUtil::GetResultValueAsString(result, 5));
  EXPECT_EQ("2017-10-10 00:00:00.000000+00",
             TestingSQLUtil::GetResultValueAsString(result, 6));
  EXPECT_EQ("A", TestingSQLUtil::GetResultValueAsString(result, 7));
  EXPECT_EQ("a", TestingSQLUtil::GetResultValueAsString(result, 8));
  EXPECT_EQ('1', TestingSQLUtil::GetResultValueAsString(result, 9).at(0));
  EXPECT_EQ("true", TestingSQLUtil::GetResultValueAsString(result, 10));

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test5 WHERE a=11", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(11, result.size());
  EXPECT_EQ("11", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("12", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("13", TestingSQLUtil::GetResultValueAsString(result, 2));
  EXPECT_EQ("14", TestingSQLUtil::GetResultValueAsString(result, 3));
  EXPECT_EQ("15.1", TestingSQLUtil::GetResultValueAsString(result, 4));
  EXPECT_EQ("16.1", TestingSQLUtil::GetResultValueAsString(result, 5));
  EXPECT_EQ("2017-10-11 00:00:00.000000+00",
             TestingSQLUtil::GetResultValueAsString(result, 6));
  EXPECT_EQ("B", TestingSQLUtil::GetResultValueAsString(result, 7));
  EXPECT_EQ("b", TestingSQLUtil::GetResultValueAsString(result, 8));
  EXPECT_EQ('2', TestingSQLUtil::GetResultValueAsString(result, 9).at(0));
  EXPECT_EQ("false", TestingSQLUtil::GetResultValueAsString(result, 10));

  // free the database just created
  txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);
}

TEST_F(InsertSQLTests, InsertIntoSelectColumn) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);

  CreateAndLoadTable6();
  CreateAndLoadTable7();

  std::vector<ResultValue> result;
  std::vector<FieldInfo> tuple_descriptor;
  std::string error_message;
  int rows_changed;
  std::unique_ptr<optimizer::AbstractOptimizer> optimizer(
      new optimizer::Optimizer());

  // TEST CASE 1
  std::string query_1("INSERT INTO test6 SELECT b,a,c FROM test7;");

  txn = txn_manager.BeginTransaction();
  auto plan =
      TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query_1, txn);
  txn_manager.CommitTransaction(txn);
  EXPECT_EQ(plan->GetPlanNodeType(), PlanNodeType::INSERT);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query_1, result,
                                               tuple_descriptor, rows_changed,
                                               error_message);

  EXPECT_EQ(4, rows_changed);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test6 WHERE a=8", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("8", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("55", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("999", TestingSQLUtil::GetResultValueAsString(result, 2));

  // TEST CASE 2
  std::string query_2("INSERT INTO test7 SELECT * FROM test6 WHERE a=1;");
  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query_2, result,
                                               tuple_descriptor, rows_changed,
                                               error_message);
  EXPECT_EQ(1, rows_changed);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test7 WHERE a=1", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("1", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("22", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("333", TestingSQLUtil::GetResultValueAsString(result, 2));

  // TEST CASE 3
  std::string query_3("INSERT INTO test7 SELECT b,a,c FROM test6 WHERE a=2;");
  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(optimizer, query_3, result,
                                               tuple_descriptor, rows_changed,
                                               error_message);
  EXPECT_EQ(1, rows_changed);

  TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
      optimizer, "SELECT * FROM test7 WHERE a=11", result, tuple_descriptor,
      rows_changed, error_message);
  EXPECT_EQ(3, result.size());
  EXPECT_EQ("11", TestingSQLUtil::GetResultValueAsString(result, 0));
  EXPECT_EQ("2", TestingSQLUtil::GetResultValueAsString(result, 1));
  EXPECT_EQ("0", TestingSQLUtil::GetResultValueAsString(result, 2));

  // free the database just created
  txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);
}

TEST_F(InsertSQLTests, UniqueColumn) {
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);

  std::string create_table("CREATE TABLE t (id INTEGER NOT NULL PRIMARY KEY,"
                                        "st VARCHAR(15) NOT NULL UNIQUE);");
  TestingSQLUtil::ExecuteSQLQuery(create_table);

  ResultType result;
  std::vector<std::string> ref_result;
  std::string result_query = "select st from t;";

  // Single row, should succeed
  std::string ins_query_1("INSERT INTO t VALUES (1, 'abc');");
  result = TestingSQLUtil::ExecuteSQLQuery(ins_query_1);
  EXPECT_EQ(result, ResultType::SUCCESS);
  ref_result.push_back("abc");
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(result_query,
                                                ref_result,
                                                false);

  // Second row, distinct from first, should succeed
  std::string ins_query_2("INSERT INTO t VALUES (2, 'def');");
  result = TestingSQLUtil::ExecuteSQLQuery(ins_query_2);
  EXPECT_EQ(result, ResultType::SUCCESS);
  ref_result.push_back("def");
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(result_query,
                                                ref_result,
                                                false);

  // Third row, non-unique value for string, should fail
  std::string ins_query_3("INSERT INTO t VALUES (3, 'abc');");
  result = TestingSQLUtil::ExecuteSQLQuery(ins_query_3);
  EXPECT_EQ(result, ResultType::ABORTED);
  // and the results returned should not include failed insert
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(result_query,
                                                ref_result,
                                                false);

  // free the database just created
  txn = txn_manager.BeginTransaction();
  catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
  txn_manager.CommitTransaction(txn);
}

}  // namespace test
}  // namespace peloton