text:
require 'test_helper'
ActiveValidators.activate(:credit_card)

describe "Credit Card Validation" do
  # Here are some valid credit cards
  VALID_CARDS =
      {
          #American Express
          :amex => '3400 0000 0000 009',
          #Carte Blanche
          :carte_blanche => '3800 0000 0000 06',
          #Discover
          :discover => '6011 0000 0000 0004',
          #Diners Club
          :diners_club => '3852 0000 0232 37',
          #JCB
          :jcb => '3530 1113 3330 0000',
          #MasterCard
          :master_card => '5500 0000 0000 0004',

          :mastercard => '5500 0000 0000 0004',
          #Solo
          :solo => '6334 0000 0000 0004',
          #maestro
          :maestro => '6759 6498 2643 8453',
          #Visa
          :visa => '4111 1111 1111 1111',
          #Laser
          :laser => '6304 1000 0000 0008'
      }

  VALID_CARDS.each_pair do |card, number|
    describe "it accepts #{card} cards" do
      it "using a specific card type" do
        subject = build_card_record({:card => number}, {:type => card})
        assert card_is_valid?(subject)
      end
      it "using :credit_card => { :type => :any }" do
        subject = build_card_record({:card => number}, {:type => :any})
        assert card_is_valid?(subject)
      end
      it "using :credit_card => true" do
        subject = build_card_record({:card => number}, true)
        assert card_is_valid?(subject)
      end
    end
  end

  describe "using multiple card types" do
    it "accepts card if one of type valid" do
      subject = build_card_record({:card => VALID_CARDS[:amex]}, {:type => [:visa, :master_card, :amex]})
      assert card_is_valid?(subject)
    end

    it "rejects card if none of type valid" do
      subject = build_card_record({:card => VALID_CARDS[:solo]}, {:type => [:visa, :master_card, :amex]})
      assert card_is_invalid?(subject)
    end
  end
  describe "for invalid cards" do
    it "rejects invalid cards and generates an error message of type invalid" do
      subject = build_card_record :card => '99999'
      assert card_is_invalid?(subject)
    end
  end

  def build_card_record(attrs = {}, validator = {:type => :any})
    TestRecord.reset_callbacks(:validate)
    TestRecord.validates :card, :credit_card => validator
    TestRecord.new attrs
  end

  def card_is_valid?(subject)
    subject.valid?.must_equal true
    subject.errors.size.must_equal 0
  end

  def card_is_invalid?(subject)
    subject.valid?.must_equal false
    subject.errors.size.must_equal 1
    subject.errors[:card].include?(subject.errors.generate_message(:card, :invalid)).must_equal true
  end

end


text:
require 'stringio'

# The hard part is to not confuse interface with implementation. Tough because
# this relies almost entirely on the interface.
# Possibly reopen STDOUT so that it writes to two, instead of just redefining
# puts/print?
class Replay
  attr_reader :path
  attr_reader :session

  def initialize(path, session)
    @path = path
    @session = session
  end

  def start!
    session.out = MultiIO.new STDOUT, StringIO.new
  end

  def end!
    multi = session.out
    session.out = STDOUT
    stringio = multi.ios[1]
    @text = stringio.read
  end

  def to_s
    @text
  end

end

module Builtins

  def record(path="replay.#{DateTime.now.to_s}")
    @__record__ = Replay.new path, SESSION
    @__record__.start!
  end

  def stop
    @__record__.end!
    @__record__
  end
end

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/sagemaker/SageMaker_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace SageMaker
{
namespace Model
{
  enum class TrafficRoutingConfigType
  {
    NOT_SET,
    ALL_AT_ONCE,
    CANARY,
    LINEAR
  };

namespace TrafficRoutingConfigTypeMapper
{
AWS_SAGEMAKER_API TrafficRoutingConfigType GetTrafficRoutingConfigTypeForName(const Aws::String& name);

AWS_SAGEMAKER_API Aws::String GetNameForTrafficRoutingConfigType(TrafficRoutingConfigType value);
} // namespace TrafficRoutingConfigTypeMapper
} // namespace Model
} // namespace SageMaker
} // namespace Aws


text:
@class MTDURLPreview;

@interface MTDURLPreviewView : UIView

+ (CGFloat)neededHeightForTitle:(NSString *)title
                         domain:(NSString *)domain
                        content:(NSString *)content
                   imageVisible:(BOOL)imageVisible
             constrainedToWidth:(CGFloat)width;

+ (void)setTitleFont:(UIFont *)titleFont;
+ (void)setDomainFont:(UIFont *)domainFont;

@property (nonatomic, readonly) UILabel *titleLabel;
@property (nonatomic, readonly) UILabel *domainLabel;
@property (nonatomic, readonly) UILabel *contentLabel;
@property (nonatomic, readonly) UIImageView *imageView;

@property (nonatomic, strong) UIColor *backgroundColor;
@property (nonatomic, strong) UIColor *textColor;
@property (nonatomic, strong) UIColor *borderColor;

@end

@interface MTDURLPreviewView (MTDModelObject)

+ (CGFloat)neededHeightForURLPreview:(MTDURLPreview *)preview
                  constrainedToWidth:(CGFloat)width;

- (void)setFromURLPreview:(MTDURLPreview *)preview;

@end


text:
package edu.uci.ics.pregelix.example.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import org.apache.asterix.testframework.context.TestCaseContext.OutputFormat;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;

public class RESTRunner {

    @Test
    public void test() throws Exception {
        File directory = new File("queries");
        String[] fileNames = directory.list();
        Arrays.sort(fileNames);
        for (String fileName : fileNames) {
            String statement = readTestFile(new File(directory.getName() + File.separator + fileName));
            long start = System.currentTimeMillis();
            if (!(fileName.startsWith("1") || fileName.startsWith("3"))) {
                continue;
            }
            System.out.println(fileName);
            if (fileName.endsWith("query")) {
                executeQuery(statement, OutputFormat.ADM);
            } else if (fileName.endsWith("update")) {
                executeUpdate(statement);
            } else if (fileName.endsWith("ddl")) {
                executeDDL(statement);
            }
            long end = System.currentTimeMillis();
            System.out.println("Execution Time: " + (end - start) + " milliseconds");
            System.out.println();
        }
    }

    // To execute DDL and Update statements
    // create type statement
    // create dataset statement
    // create index statement
    // create dataverse statement
    // create function statement
    public void executeDDL(String str) throws Exception {
        final String url = "http://sensorium-1.ics.uci.edu:18002/ddl";

        // Create a method instance.
        PostMethod method = new PostMethod(url);
        method.setRequestEntity(new StringRequestEntity(str));
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));

        // Execute the method.
        executeHttpMethod(method);
    }

    // Executes Query and returns results as JSONArray
    public InputStream executeQuery(String str, OutputFormat fmt) throws Exception {
        final String url = "http://sensorium-1.ics.uci.edu:18002/query";

        // Create a method instance.
        GetMethod method = new GetMethod(url);
        method.setQueryString(new NameValuePair[] { new NameValuePair("query", str) });

        //Set accepted output response type
        method.setRequestHeader("Accept", fmt.mimeType());

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        executeHttpMethod(method);
        return method.getResponseBodyAsStream();
    }

    // To execute Update statements
    // Insert and Delete statements are executed here
    public void executeUpdate(String str) throws Exception {
        final String url = "http://sensorium-1.ics.uci.edu:18002/update";

        // Create a method instance.
        PostMethod method = new PostMethod(url);
        method.setRequestEntity(new StringRequestEntity(str));

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));

        // Execute the method.
        executeHttpMethod(method);
    }

    // Executes a HTTP method.
    private static int executeHttpMethod(HttpMethod method) throws Exception {
        HttpClient client = new HttpClient();
        int statusCode;
        try {
            statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                JSONObject result = new JSONObject(
                        new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream())));
                if (result.has("error-code")) {
                    String[] errors = { result.getJSONArray("error-code").getString(0), result.getString("summary"),
                            result.getString("stacktrace") };
                    throw new Exception("HTTP operation failed: " + errors[0] + "\nSTATUS LINE: "
                            + method.getStatusLine() + "\nSUMMARY: " + errors[1] + "\nSTACKTRACE: " + errors[2]);
                }
            }
            return statusCode;
        } catch (Exception e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
    }

    // Method that reads a DDL/Update/Query File
    // and returns the contents as a string
    // This string is later passed to REST API for execution.
    private static String readTestFile(File testFile) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader(testFile));
        String line = null;
        StringBuilder stringBuilder = new StringBuilder();
        String ls = System.getProperty("line.separator");

        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }
        reader.close();
        return stringBuilder.toString();
    }
}


text:
<?php echo validation_errors(); ?>

<?php echo form_open('Flores/pago_P'); ?>

Flores Me Enflorece

1.- Escoge las flores que desees para tu armar tu ramo

<a href="<?php echo site_url('/') ?>">Home

Galeria de Flores

                  <?php foreach ($flores as $flores_item): ?>

                             <img src="<?php echo base_url();?>Img_Flores/Flores/<?php echo $flores_item['id_articulo'];?>.jpg" WIDTH=180 HEIGHT=180 alt="">

<?php echo $flores_item['nombre']; ?>

$<?php echo $flores_item['precio'];?>

                                    <a onclick="document.getElementById('qty-<?php echo $flores_item['id_articulo'];?>').value = parseInt(document.getElementById('qty-<?php echo $flores_item['id_articulo'];?>').value) - 1" title=""><button  type="button" class="btn btn-danger" ></button>

                                <input name="qty" id="qty-<?php echo $flores_item['id_articulo'];?>" type="text" class="form-control text-center" value="0" min="0" max="10" disabled>

                                    <a onclick="document.getElementById('qty-<?php echo $flores_item['id_articulo'];?>').value = parseInt(document.getElementById('qty-<?php echo $flores_item['id_articulo'];?>').value) + 1" title=""><button  type="button" class="btn btn-success" ></button>

                        <button class="btn btn-default add-to-cart" id="btn_carrito"  onclick="agregar(<?php echo $flores_item['id_articulo']?>,document.getElementById('qty-<?php echo $flores_item['id_articulo'];?>').value )">  Comprar</button>

<?php endforeach; ?>

Total:

  <form  method="post" action="#">

Configura tu ramo

Campos obligatorios *

* PONLE UN NOMBRE A TU RAMO:

                    <input type="text" name="nombrePer" class="input-text required-entry validate-no-html-tags form-control" placeholder="Nombre Ramo"  maxlength="50" required />

* Día de entrega

                            <input type="date" class="form-control" name="fechaP" id="fechaP" style="font-size: 11px" onblur="validarFecha()" required/>

* Horario de entrega

                        <input type="radio" name="radioP" id="mañana" value="mañana"  />
                        Por la mañana

                        <input type="radio" name="radioP" id="tarde" value="tarde"  />
                        Por la tarde

                        <input type="radio" name="radioP" id="noche" value="noche"  />
                        Por la noche

* ¿Para quién es?

                       *  <input type="text" name="nombreEnvioP" class="input-text required-entry validate-no-html-tags form-control" placeholder="Nombre" value="" maxlength="20" required onkeypress="return soloLetras(event)"/>

                    *

                        <input type="text" name="apellidoEnvioP" class="input-text required-entry validate-no-html-tags form-control" placeholder="Apellidos" value="" maxlength="20" required onkeypress="return soloLetras(event)" />

                   *

                        <input type="text" name="telefonoEnvioP" class="input-text required-entry custom-validate-phone form-control" placeholder="Teléfono" value="" maxlength="10" required onkeypress="return solonumero(event)"/>

                   *

                        <select name="comboboxP" class="form-control" required>
                            <option value="Quito">Quito</option>
                            <option value="Guayaquil">Guayaquil</option>
                            <option value="Cuenca">Cuenca</option>
                        </select>

                   *

                        <input type="text" name="direccionEnvioP" class="input-text required-entry validate-no-html-tags form-control" placeholder="Direccion de envio" value="" required/>

                        <input type="text" name="codpostalEnvioP" class="input-text validate-no-html-tags form-control" placeholder="Codigo Postal" value="" maxlength="6" onkeypress="return solonumero(event)"/>

Incluye tu dedicatoria

                    <textarea class="form-control textarea validate-no-html-tags" id="dedicatoriaP" name="dedicatoriaP" placeholder="Dedicatoria" maxlength="250" ></textarea>

Máximo de 250 caracteres

                    <button type="submit" class="form-control btn btn-primary boton-margen text-center" onclick="crear()"; send();>COMPRAR</button>

            </form>


text:
#include "private/qdeclarativefocuspanel_p.h"

#include "private/qdeclarativeitem_p.h"

#include <QtGui/qgraphicsscene.h>
#include <QEvent>

QT_BEGIN_NAMESPACE

/*!
   \qmlclass FocusPanel QDeclarativeFocusPanel
    \since 4.7
    \ingroup qml-basic-interaction-elements

   \brief The FocusPanel item explicitly creates a focus panel.
   \inherits Item

    Focus panels assist in keyboard focus handling when building QML
    applications.  All the details are covered in the
    \l {qmlfocus}{keyboard focus documentation}.
*/

QDeclarativeFocusPanel::QDeclarativeFocusPanel(QDeclarativeItem *parent) :
    QDeclarativeItem(parent)
{
    Q_D(QDeclarativeItem);
    d->flags |= QGraphicsItem::ItemIsPanel;
}

QDeclarativeFocusPanel::~QDeclarativeFocusPanel()
{
}

/*!
    \qmlproperty bool FocusPanel::active

    Sets whether the item is the active focus panel.
*/

bool QDeclarativeFocusPanel::sceneEvent(QEvent *event)
{
    if (event->type() == QEvent::WindowActivate ||
        event->type() == QEvent::WindowDeactivate)
        emit activeChanged();
    return QDeclarativeItem::sceneEvent(event);
}

QT_END_NAMESPACE


text:
alter table tab1 add `status` char(1) DEFAULT NULL;
alter table tab1 add `operatTime` datetime DEFAULT NULL;
alter table tab1 add `creatTime` datetime DEFAULT NULL;
alter table tab1 add `version` int(11) DEFAULT NULL;
alter table tab1 add `creatIp` char(16) DEFAULT NULL;
alter table tab1 add `operatIp` char(16) DEFAULT NULL;
alter table tab1 add `creator` bigint(20) DEFAULT NULL;
alter table tab1 add `operator` bigint(20) DEFAULT NULL;


text:
FROM alpine:latest
LABEL maintainer="Teddysun <i@teddysun.com>"

WORKDIR /root
COPY xray.sh /root/xray.sh
COPY config.json /etc/xray/config.json
RUN set -ex \
	&& apk add --no-cache tzdata ca-certificates \
	&& mkdir -p /var/log/xray /usr/share/xray \
	&& chmod +x /root/xray.sh \
	&& /root/xray.sh \
	&& rm -fv /root/xray.sh \
	&& wget -O /usr/share/xray/geosite.dat https://github.com/v2fly/domain-list-community/releases/latest/download/dlc.dat \
	&& wget -O /usr/share/xray/geoip.dat https://github.com/v2fly/geoip/releases/latest/download/geoip.dat

VOLUME /etc/xray
ENV TZ=Asia/Shanghai
CMD [ "/usr/bin/xray", "-config", "/etc/xray/config.json" ]


text:
from .content_add_form import *
from .content_edit_form import *
from .content_delete_form import *


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_bg_dark" android:state_pressed="true"></item>
    <item android:drawable="@drawable/btn_bg"></item>

</selector>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Matchday_model extends CI_Model
{
	public function find_by_weekid($weeknumber)
	{
		$sql = "SELECT * FROM  matchday WHERE  week_id = $weeknumber ORDER BY DATE ASC , TIME ASC";
		$result =  $this->db->query($sql);
		return $result->result_array();
	}
}


text:
import os

from kubeflow.kubeflow.crud_backend import config, logging

from ..common import create_app as create_default_app
from .routes import bp as routes_bp

log = logging.getLogger(__name__)

def create_app(name=__name__, cfg: config.Config = None):
    cfg = config.Config() if cfg is None else cfg

    # Properly set the static serving directory
    static_dir = os.path.join(
        os.path.abspath(os.path.dirname(__file__)), "static"
    )

    app = create_default_app(name, static_dir, cfg)

    log.info("Setting STATIC_DIR to: " + static_dir)
    app.config["STATIC_DIR"] = static_dir

    # Register the app's blueprints
    app.register_blueprint(routes_bp)

    return app


text:
package com.yangyu.myslidingmenudemo06;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.MenuItem;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

public class MainActivity extends SlidingFragmentActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setTitle("ViewPager");

		initSlidingMenu();

		initView();
	}

	/**
	 * ³õ'»¯»¬¶¯²Ëµ¥
	 */
	/**
	 *
	 */
	private void initSlidingMenu(){
		// ÉèÖû¬¶¯²Ëµ¥´ò¿ªºóµÄÊÓͼ½çÃæ
		setBehindContentView(R.layout.menu_frame);
		getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, new SampleListFragment()).commit();

		// ÉèÖû¬¶¯²Ëµ¥µÄÊôÐÔÖµ
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setFadeDegree(0.35f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	/**
	 * ³õ'»¯×é¼þ
	 */
	private void initView(){
		ViewPager vp = new ViewPager(this);
		vp.setId("VP".hashCode());
		vp.setAdapter(new ColorPagerAdapter(getSupportFragmentManager()));
		setContentView(vp);

		vp.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageScrollStateChanged(int arg0) { }

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) { }

			@Override
			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
					break;
				default:
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
					break;
				}
			}

		});

		vp.setCurrentItem(0);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
	}

	public class ColorPagerAdapter extends FragmentPagerAdapter {
		private ArrayList<Fragment> mFragments;

		private final int[] COLORS = new int[] {
			R.color.red,
			R.color.green,
			R.color.blue,
			R.color.white,
			R.color.black
		};

		public ColorPagerAdapter(FragmentManager fm) {
			super(fm);
			mFragments = new ArrayList<Fragment>();
			for (int color : COLORS)
				mFragments.add(new ColorFragment(color));
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

		@Override
		public Fragment getItem(int position) {
			return mFragments.get(position);
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}


text:
package mysql

import (
	"bytes"
	"context"
	crypto_rand "crypto/rand"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"math/rand"
	"net"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"vitess.io/vitess/go/sqltypes"
	"vitess.io/vitess/go/test/utils"
	querypb "vitess.io/vitess/go/vt/proto/query"
	"vitess.io/vitess/go/vt/sqlparser"
)

func createSocketPair(t *testing.T) (net.Listener, *Conn, *Conn) {
	// Create a listener.
	listener, err := net.Listen("tcp", ":0")
	if err != nil {
		t.Fatalf("Listen failed: %v", err)
	}
	addr := listener.Addr().String()
	listener.(*net.TCPListener).SetDeadline(time.Now().Add(10 * time.Second))

	// Dial a client, Accept a server.
	wg := sync.WaitGroup{}

	var clientConn net.Conn
	var clientErr error
	wg.Add(1)
	go func() {
		defer wg.Done()
		clientConn, clientErr = net.DialTimeout("tcp", addr, 10*time.Second)
	}()

	var serverConn net.Conn
	var serverErr error
	wg.Add(1)
	go func() {
		defer wg.Done()
		serverConn, serverErr = listener.Accept()
	}()

	wg.Wait()

	if clientErr != nil {
		t.Fatalf("Dial failed: %v", clientErr)
	}
	if serverErr != nil {
		t.Fatalf("Accept failed: %v", serverErr)
	}

	// Create a Conn on both sides.
	cConn := newConn(clientConn)
	sConn := newConn(serverConn)
	sConn.PrepareData = map[uint32]*PrepareData{}

	return listener, sConn, cConn
}

func useWritePacket(t *testing.T, cConn *Conn, data []byte) {
	defer func() {
		if x := recover(); x != nil {
			t.Fatalf("%v", x)
		}
	}()

	dataLen := len(data)
	dataWithHeader := make([]byte, packetHeaderSize+dataLen)
	copy(dataWithHeader[packetHeaderSize:], data)

	if err := cConn.writePacket(dataWithHeader); err != nil {
		t.Fatalf("writePacket failed: %v", err)
	}
}

func useWriteEphemeralPacketBuffered(t *testing.T, cConn *Conn, data []byte) {
	defer func() {
		if x := recover(); x != nil {
			t.Fatalf("%v", x)
		}
	}()
	cConn.startWriterBuffering()
	defer cConn.endWriterBuffering()

	buf, pos := cConn.startEphemeralPacketWithHeader(len(data))
	copy(buf[pos:], data)
	if err := cConn.writeEphemeralPacket(); err != nil {
		t.Fatalf("writeEphemeralPacket(false) failed: %v", err)
	}
}

func useWriteEphemeralPacketDirect(t *testing.T, cConn *Conn, data []byte) {
	defer func() {
		if x := recover(); x != nil {
			t.Fatalf("%v", x)
		}
	}()

	buf, pos := cConn.startEphemeralPacketWithHeader(len(data))
	copy(buf[pos:], data)
	if err := cConn.writeEphemeralPacket(); err != nil {
		t.Fatalf("writeEphemeralPacket(true) failed: %v", err)
	}
}

func verifyPacketCommsSpecific(t *testing.T, cConn *Conn, data []byte,
	write func(t *testing.T, cConn *Conn, data []byte),
	read func() ([]byte, error)) {
	// Have to do it in the background if it cannot be buffered.
	// Note we have to wait for it to finish at the end of the
	// test, as the write may write all the data to the socket,
	// and the flush may not be done after we're done with the read.
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		write(t, cConn, data)
		wg.Done()
	}()

	received, err := read()
	if err != nil || !bytes.Equal(data, received) {
		t.Fatalf("ReadPacket failed: %v %v", received, err)
	}
	wg.Wait()
}

// Write a packet on one side, read it on the other, check it's
// correct.  We use all possible read and write methods.
func verifyPacketComms(t *testing.T, cConn, sConn *Conn, data []byte) {
	// All three writes, with ReadPacket.
	verifyPacketCommsSpecific(t, cConn, data, useWritePacket, sConn.ReadPacket)
	verifyPacketCommsSpecific(t, cConn, data, useWriteEphemeralPacketBuffered, sConn.ReadPacket)
	verifyPacketCommsSpecific(t, cConn, data, useWriteEphemeralPacketDirect, sConn.ReadPacket)

	// All three writes, with readEphemeralPacket.
	verifyPacketCommsSpecific(t, cConn, data, useWritePacket, sConn.readEphemeralPacket)
	sConn.recycleReadPacket()
	verifyPacketCommsSpecific(t, cConn, data, useWriteEphemeralPacketBuffered, sConn.readEphemeralPacket)
	sConn.recycleReadPacket()
	verifyPacketCommsSpecific(t, cConn, data, useWriteEphemeralPacketDirect, sConn.readEphemeralPacket)
	sConn.recycleReadPacket()

	// All three writes, with readEphemeralPacketDirect, if size allows it.
	if len(data) < MaxPacketSize {
		verifyPacketCommsSpecific(t, cConn, data, useWritePacket, sConn.readEphemeralPacketDirect)
		sConn.recycleReadPacket()
		verifyPacketCommsSpecific(t, cConn, data, useWriteEphemeralPacketBuffered, sConn.readEphemeralPacketDirect)
		sConn.recycleReadPacket()
		verifyPacketCommsSpecific(t, cConn, data, useWriteEphemeralPacketDirect, sConn.readEphemeralPacketDirect)
		sConn.recycleReadPacket()
	}
}

func TestRawConnection(t *testing.T) {
	listener, sConn, cConn := createSocketPair(t)
	defer func() {
		listener.Close()
		sConn.Close()
		cConn.Close()
	}()
	assert.IsType(t, &net.TCPConn{}, sConn.GetRawConn())
	assert.IsType(t, &net.TCPConn{}, cConn.GetRawConn())
}

func TestPackets(t *testing.T) {
	listener, sConn, cConn := createSocketPair(t)
	defer func() {
		listener.Close()
		sConn.Close()
		cConn.Close()
	}()

	// Verify all packets go through correctly.
	// Small one.
	data := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	verifyPacketComms(t, cConn, sConn, data)

	// 0 length packet
	data = []byte{}
	verifyPacketComms(t, cConn, sConn, data)

	// Under the limit, still one packet.
	data = make([]byte, MaxPacketSize-1)
	data[0] = 0xab
	data[MaxPacketSize-2] = 0xef
	verifyPacketComms(t, cConn, sConn, data)

	// Exactly the limit, two packets.
	data = make([]byte, MaxPacketSize)
	data[0] = 0xab
	data[MaxPacketSize-1] = 0xef
	verifyPacketComms(t, cConn, sConn, data)

	// Over the limit, two packets.
	data = make([]byte, MaxPacketSize+1000)
	data[0] = 0xab
	data[MaxPacketSize+999] = 0xef
	verifyPacketComms(t, cConn, sConn, data)
}

func TestBasicPackets(t *testing.T) {
	require := require.New(t)
	assert := assert.New(t)
	listener, sConn, cConn := createSocketPair(t)
	defer func() {
		listener.Close()
		sConn.Close()
		cConn.Close()
	}()

	// Write OK packet, read it, compare.
	err := sConn.writeOKPacket(&PacketOK{
		affectedRows: 12,
		lastInsertID: 34,
		statusFlags:  56,
		warnings:     78,
	})
	require.NoError(err)

	data, err := cConn.ReadPacket()
	require.NoError(err)
	require.NotEmpty(data)
	assert.EqualValues(data[0], OKPacket, "OKPacket")

	packetOk, err := cConn.parseOKPacket(data)
	require.NoError(err)
	assert.EqualValues(12, packetOk.affectedRows)
	assert.EqualValues(34, packetOk.lastInsertID)
	assert.EqualValues(56, packetOk.statusFlags)
	assert.EqualValues(78, packetOk.warnings)

	// Write OK packet with affected GTIDs, read it, compare.
	sConn.Capabilities |= CapabilityClientSessionTrack
	cConn.Capabilities |= CapabilityClientSessionTrack
	ok := PacketOK{
		affectedRows:     23,
		lastInsertID:     45,
		statusFlags:      67 | ServerSessionStateChanged,
		warnings:         89,
		info:             "",
		sessionStateData: "foo-bar",
	}
	err = sConn.writeOKPacket(&ok)
	require.NoError(err)

	data, err = cConn.ReadPacket()
	require.NoError(err)
	require.NotEmpty(data)
	assert.EqualValues(data[0], OKPacket, "OKPacket")

	packetOk, err = cConn.parseOKPacket(data)
	require.NoError(err)
	assert.EqualValues(23, packetOk.affectedRows)
	assert.EqualValues(45, packetOk.lastInsertID)
	assert.EqualValues(ServerSessionStateChanged, packetOk.statusFlags&ServerSessionStateChanged)
	assert.EqualValues(89, packetOk.warnings)
	assert.EqualValues("foo-bar", packetOk.sessionStateData)

	// Write OK packet with EOF header, read it, compare.
	ok = PacketOK{
		affectedRows: 12,
		lastInsertID: 34,
		statusFlags:  56,
		warnings:     78,
	}
	err = sConn.writeOKPacketWithEOFHeader(&ok)
	require.NoError(err)

	data, err = cConn.ReadPacket()
	require.NoError(err)
	require.NotEmpty(data)
	assert.True(isEOFPacket(data), "expected EOF")

	packetOk, err = cConn.parseOKPacket(data)
	require.NoError(err)
	assert.EqualValues(12, packetOk.affectedRows)
	assert.EqualValues(34, packetOk.lastInsertID)
	assert.EqualValues(56, packetOk.statusFlags)
	assert.EqualValues(78, packetOk.warnings)

	// Write error packet, read it, compare.
	err = sConn.writeErrorPacket(ERAccessDeniedError, SSAccessDeniedError, "access denied: %v", "reason")
	require.NoError(err)
	data, err = cConn.ReadPacket()
	require.NoError(err)
	require.NotEmpty(data)
	assert.EqualValues(data[0], ErrPacket, "ErrPacket")

	err = ParseErrorPacket(data)
	utils.MustMatch(t, err, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "access denied: reason"), "")

	// Write error packet from error, read it, compare.
	err = sConn.writeErrorPacketFromError(NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "access denied"))
	require.NoError(err)

	data, err = cConn.ReadPacket()
	require.NoError(err)
	require.NotEmpty(data)
	assert.EqualValues(data[0], ErrPacket, "ErrPacket")

	err = ParseErrorPacket(data)
	utils.MustMatch(t, err, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "access denied"), "")

	// Write EOF packet, read it, compare first byte. Payload is always ignored.
	err = sConn.writeEOFPacket(0x8912, 0xabba)
	require.NoError(err)

	data, err = cConn.ReadPacket()
	require.NoError(err)
	require.NotEmpty(data)
	assert.True(isEOFPacket(data), "expected EOF")
}

func TestOkPackets(t *testing.T) {
	listener, sConn, cConn := createSocketPair(t)
	defer func() {
		listener.Close()
		sConn.Close()
		cConn.Close()
	}()

	testCases := []struct {
		data        string
		cc          uint32
		expectedErr string
	}{{
		data: `
00000000  00 00 00 02 00 00 00                              |.......|`,
		cc: CapabilityClientProtocol41,
	}, {
		data: `
00000000  00 00 00 02 00                                    |.....|`,
		cc:          CapabilityClientTransactions,
		expectedErr: "invalid OK packet warnings: &{[0 0 0 2 0] 0}",
	}, {
		data: `
00000000  00 00 00 02 40 00 00 00  2a 03 28 00 26 66 32 37  |....@...*.(.&f27|
00000010  66 36 39 37 31 2d 30 33  65 37 2d 31 31 65 62 2d  |f6971-03e7-11eb-|
00000020  38 35 63 35 2d 39 38 61  66 36 35 61 36 64 63 34  |85c5-98af65a6dc4|
00000030  61 3a 32                                          |a:2|`,
		cc: CapabilityClientProtocol41 | CapabilityClientTransactions | CapabilityClientSessionTrack,
	}, {
		data:        `00000000  00 00 00 02 40 00 00 00  07 01 05 04 74 65 73 74  |....@.......test|`,
		cc:          CapabilityClientProtocol41 | CapabilityClientTransactions | CapabilityClientSessionTrack,
		expectedErr: "invalid OK packet session state change type: 1",
	}, {
		data: `
00000000  00 00 00 00 40 00 00 00  14 00 0f 0a 61 75 74 6f  |....@.......auto|
00000010  63 6f 6d 6d 69 74 03 4f  46 46 02 01 31           |commit.OFF..1|`,
		cc:          CapabilityClientProtocol41 | CapabilityClientTransactions | CapabilityClientSessionTrack,
		expectedErr: "invalid OK packet session state change type: 0",
	}, {
		data: `
00000000  00 00 00 00 40 00 00 00  0a 01 05 04 74 65 73 74  |....@.......test|
00000010  02 01 31                                          |..1|`,
		cc:          CapabilityClientProtocol41 | CapabilityClientTransactions | CapabilityClientSessionTrack,
		expectedErr: "invalid OK packet session state change type: 1",
	}}

	for i, testCase := range testCases {
		t.Run("data packet:"+strconv.Itoa(i), func(t *testing.T) {
			data := ReadHexDump(testCase.data)

			cConn.Capabilities = testCase.cc
			sConn.Capabilities = testCase.cc
			// parse the packet
			packetOk, err := cConn.parseOKPacket(data)
			if testCase.expectedErr != "" {
				require.Error(t, err)
				require.Equal(t, testCase.expectedErr, err.Error())
				return
			}
			require.NoError(t, err, "failed to parse OK packet")

			// write the ok packet from server
			err = sConn.writeOKPacket(packetOk)
			require.NoError(t, err, "failed to write OK packet")

			// receive the ok packer on client
			readData, err := cConn.ReadPacket()
			require.NoError(t, err, "failed to read packet that was written")
			assert.Equal(t, data, readData, "data read and written does not match")
		})
	}
}

func ReadHexDump(value string) []byte {
	lines := strings.Split(value, "\n")
	var data []byte
	for _, line := range lines {
		if len(line) == 0 {
			continue
		}
		indexOfPipe := strings.Index(line, "|")
		s := line[8:indexOfPipe]
		hexValues := strings.Split(s, " ")
		for _, val := range hexValues {
			if val != "" {
				i, _ := hex.DecodeString(val)
				data = append(data, i...)
			}
		}
	}

	return data
}

// Mostly a sanity check.
func TestEOFOrLengthEncodedIntFuzz(t *testing.T) {
	for i := 0; i < 100; i++ {
		bytes := make([]byte, rand.Intn(16)+1)
		_, err := crypto_rand.Read(bytes)
		if err != nil {
			t.Fatalf("error doing rand.Read")
		}
		bytes[0] = 0xfe

		_, _, isInt := readLenEncInt(bytes, 0)
		isEOF := isEOFPacket(bytes)
		if (isInt && isEOF) || (!isInt && !isEOF) {
			t.Fatalf("0xfe bytestring is EOF xor Int. Bytes %v", bytes)
		}
	}
}

func TestMultiStatementStopsOnError(t *testing.T) {
	listener, sConn, cConn := createSocketPair(t)
	sConn.Capabilities |= CapabilityClientMultiStatements
	defer func() {
		listener.Close()
		sConn.Close()
		cConn.Close()
	}()

	err := cConn.WriteComQuery("error;select 2")
	require.NoError(t, err)

	// this handler will return results according to the query. In case the query contains "error" it will return an error
	// panic if the query contains "panic" and it will return selectRowsResult in case of any other query
	handler := &testRun{t: t, err: fmt.Errorf("execution failed")}
	res := sConn.handleNextCommand(handler)
	// Execution error will occur in this case because the query sent is error and testRun will throw an error.
	// We should send an error packet but not close the connection.
	require.True(t, res, "we should not break the connection because of execution errors")

	data, err := cConn.ReadPacket()
	require.NoError(t, err)
	require.NotEmpty(t, data)
	require.EqualValues(t, data[0], ErrPacket) // we should see the error here
}

func TestMultiStatement(t *testing.T) {
	listener, sConn, cConn := createSocketPair(t)
	sConn.Capabilities |= CapabilityClientMultiStatements
	defer func() {
		listener.Close()
		sConn.Close()
		cConn.Close()
	}()

	err := cConn.WriteComQuery("select 1;select 2")
	require.NoError(t, err)

	// this handler will return results according to the query. In case the query contains "error" it will return an error
	// panic if the query contains "panic" and it will return selectRowsResult in case of any other query
	handler := &testRun{t: t, err: NewSQLError(CRMalformedPacket, SSUnknownSQLState, "cannot get column number")}
	res := sConn.handleNextCommand(handler)
	//The queries run will be select 1; and select 2; These queries do not return any errors, so the connection should still be open
	require.True(t, res, "we should not break the connection in case of no errors")
	// Read the result of the query and assert that it is indeed what we want. This will contain the result of the first query.
	data, more, _, err := cConn.ReadQueryResult(100, true)
	require.NoError(t, err)
	// Since we executed 2 queries, there should be more results to be read
	require.True(t, more)
	require.True(t, data.Equal(selectRowsResult))

	// Read the results for the second query and verify the correctness
	data, more, _, err = cConn.ReadQueryResult(100, true)
	require.NoError(t, err)
	// This was the final query run, so we expect that more should be false as there are no more queries.
	require.False(t, more)
	require.True(t, data.Equal(selectRowsResult))

	// This time we run two queries fist of which will return an error
	err = cConn.WriteComQuery("error;select 2")
	require.NoError(t, err)

	res = sConn.handleNextCommand(handler)
	// Even if the query returns an error we should not close the connection as it is an execution error
	require.True(t, res, "we should not break the connection because of execution errors")

	// Read the result and assert that we indeed see the error that testRun throws.
	data, more, _, err = cConn.ReadQueryResult(100, true)
	require.EqualError(t, err, "cannot get column number (errno 2027) (sqlstate HY000)")
	// In case of errors in a multi-statement, the following statements are not executed, therefore we want that more should be false
	require.False(t, more)
	require.Nil(t, data)
}

func TestMultiStatementOnSplitError(t *testing.T) {
	listener, sConn, cConn := createSocketPair(t)
	// Set the splitStatementFunction to return an error.
	splitStatementFunction = func(blob string) (pieces []string, err error) {
		return nil, fmt.Errorf("Error in split statements")
	}
	defer func() {
		// Set the splitStatementFunction to the correct function back
		splitStatementFunction = sqlparser.SplitStatementToPieces
	}()
	sConn.Capabilities |= CapabilityClientMultiStatements
	defer func() {
		listener.Close()
		sConn.Close()
		cConn.Close()
	}()

	err := cConn.WriteComQuery("select 1;select 2")
	require.NoError(t, err)

	// this handler will return results according to the query. In case the query contains "error" it will return an error
	// panic if the query contains "panic" and it will return selectRowsResult in case of any other query
	handler := &testRun{t: t, err: fmt.Errorf("execution failed")}

	// We will encounter an error in split statement when this multi statement is processed.
	res := sConn.handleNextCommand(handler)
	// Since this is an execution error, we should not be closing the connection.
	require.True(t, res, "we should not break the connection because of execution errors")
	// Assert that the returned packet is an error packet.
	data, err := cConn.ReadPacket()
	require.NoError(t, err)
	require.NotEmpty(t, data)
	require.EqualValues(t, data[0], ErrPacket) // we should see the error here
}

func TestInitDbAgainstWrongDbDoesNotDropConnection(t *testing.T) {
	listener, sConn, cConn := createSocketPair(t)
	sConn.Capabilities |= CapabilityClientMultiStatements
	defer func() {
		listener.Close()
		sConn.Close()
		cConn.Close()
	}()

	err := cConn.writeComInitDB("error")
	require.NoError(t, err)

	// this handler will return results according to the query. In case the query contains "error" it will return an error
	// panic if the query contains "panic" and it will return selectRowsResult in case of any other query
	handler := &testRun{t: t, err: fmt.Errorf("execution failed")}
	res := sConn.handleNextCommand(handler)
	require.True(t, res, "we should not break the connection because of execution errors")

	data, err := cConn.ReadPacket()
	require.NoError(t, err)
	require.NotEmpty(t, data)
	require.EqualValues(t, data[0], ErrPacket) // we should see the error here
}

func TestConnectionErrorWhileWritingComQuery(t *testing.T) {
	// Set the conn for the server connection to the simulated connection which always returns an error on writing
	sConn := newConn(testConn{
		writeToPass: []bool{false, true},
		pos:         -1,
		queryPacket: []byte{0x21, 0x00, 0x00, 0x00, ComQuery, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x20, 0x40, 0x40, 0x76, 0x65, 0x72, 0x73,
			0x69, 0x6f, 0x6e, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x20, 0x31},
	})

	// this handler will return an error on the first run, and fail the test if it's run more times
	errorString := make([]byte, 17000)
	handler := &testRun{t: t, err: fmt.Errorf(string(errorString))}
	res := sConn.handleNextCommand(handler)
	require.False(t, res, "we should beak the connection in case of error writing error packet")
}

func TestConnectionErrorWhileWritingComStmtSendLongData(t *testing.T) {
	// Set the conn for the server connection to the simulated connection which always returns an error on writing
	sConn := newConn(testConn{
		writeToPass: []bool{false, true},
		pos:         -1,
		queryPacket: []byte{0x21, 0x00, 0x00, 0x00, ComStmtSendLongData, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x20, 0x40, 0x40, 0x76, 0x65, 0x72, 0x73,
			0x69, 0x6f, 0x6e, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x20, 0x31},
	})

	// this handler will return an error on the first run, and fail the test if it's run more times
	handler := &testRun{t: t, err: fmt.Errorf("not used")}
	res := sConn.handleNextCommand(handler)
	require.False(t, res, "we should beak the connection in case of error writing error packet")
}

func TestConnectionErrorWhileWritingComPrepare(t *testing.T) {
	// Set the conn for the server connection to the simulated connection which always returns an error on writing
	sConn := newConn(testConn{
		writeToPass: []bool{false},
		pos:         -1,
		queryPacket: []byte{0x01, 0x00, 0x00, 0x00, ComPrepare},
	})
	sConn.Capabilities = sConn.Capabilities | CapabilityClientMultiStatements
	// this handler will return an error on the first run, and fail the test if it's run more times
	handler := &testRun{t: t, err: fmt.Errorf("not used")}
	res := sConn.handleNextCommand(handler)
	require.False(t, res, "we should beak the connection in case of error writing error packet")
}

func TestConnectionErrorWhileWritingComStmtExecute(t *testing.T) {
	// Set the conn for the server connection to the simulated connection which always returns an error on writing
	sConn := newConn(testConn{
		writeToPass: []bool{false},
		pos:         -1,
		queryPacket: []byte{0x21, 0x00, 0x00, 0x00, ComStmtExecute, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x20, 0x40, 0x40, 0x76, 0x65, 0x72, 0x73,
			0x69, 0x6f, 0x6e, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x20, 0x31},
	})
	// this handler will return an error on the first run, and fail the test if it's run more times
	handler := &testRun{t: t, err: fmt.Errorf("not used")}
	res := sConn.handleNextCommand(handler)
	require.False(t, res, "we should beak the connection in case of error writing error packet")
}

var _ Handler = (*testRun)(nil)

type testConn struct {
	writeToPass []bool
	pos         int
	queryPacket []byte
}

func (t testConn) Read(b []byte) (n int, err error) {
	for j, i := range t.queryPacket {
		b[j] = i
	}
	return len(b), nil
}

func (t testConn) Write(b []byte) (n int, err error) {
	t.pos = t.pos + 1
	if t.writeToPass[t.pos] {
		return 0, nil
	}
	return 0, fmt.Errorf("error in writing to connection")
}

func (t testConn) Close() error {
	panic("implement me")
}

func (t testConn) LocalAddr() net.Addr {
	panic("implement me")
}

func (t testConn) RemoteAddr() net.Addr {
	return mockAddress{s: "a"}
}

func (t testConn) SetDeadline(t1 time.Time) error {
	panic("implement me")
}

func (t testConn) SetReadDeadline(t1 time.Time) error {
	panic("implement me")
}

func (t testConn) SetWriteDeadline(t1 time.Time) error {
	panic("implement me")
}

var _ net.Conn = (*testConn)(nil)

type mockAddress struct {
	s string
}

func (m mockAddress) Network() string {
	return m.s
}

func (m mockAddress) String() string {
	return m.s
}

var _ net.Addr = (*mockAddress)(nil)

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func randSeq(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}

func TestPrepareAndExecute(t *testing.T) {
	// this test starts a lot of clients that all send prepared statement parameter values
	// and check that the handler received the correct input
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	for i := 0; i < 1000; i++ {
		startGoRoutine(ctx, t, randSeq(i))
	}

	for {
		select {
		case <-ctx.Done():
			return
		default:
			if t.Failed() {
				return
			}
		}
	}
}

func startGoRoutine(ctx context.Context, t *testing.T, s string) {
	go func(longData string) {
		listener, sConn, cConn := createSocketPair(t)
		defer func() {
			listener.Close()
			sConn.Close()
			cConn.Close()
		}()

		sql := "SELECT * FROM test WHERE id = ?"
		mockData := preparePacket(t, sql)

		err := cConn.writePacket(mockData)
		require.NoError(t, err)

		handler := &testRun{
			t:              t,
			expParamCounts: 1,
			expQuery:       sql,
			expStmtID:      1,
		}

		ok := sConn.handleNextCommand(handler)
		require.True(t, ok, "oh noes")

		resp, err := cConn.ReadPacket()
		require.NoError(t, err)
		require.EqualValues(t, 0, resp[0])

		for count := 0; ; count++ {
			select {
			case <-ctx.Done():
				return
			default:
			}
			cConn.sequence = 0
			longDataPacket := createSendLongDataPacket(sConn.StatementID, 0, []byte(longData))
			err = cConn.writePacket(longDataPacket)
			assert.NoError(t, err)

			assert.True(t, sConn.handleNextCommand(handler))
			data := sConn.PrepareData[sConn.StatementID]
			assert.NotNil(t, data)
			variable := data.BindVars["v1"]
			assert.NotNil(t, variable, fmt.Sprintf("%#v", data.BindVars))
			assert.Equalf(t, []byte(longData), variable.Value[len(longData)*count:], "failed at: %d", count)
		}
	}(s)
}

func createSendLongDataPacket(stmtID uint32, paramID uint16, data []byte) []byte {
	stmtIDBinary := make([]byte, 4)
	binary.LittleEndian.PutUint32(stmtIDBinary, stmtID)

	paramIDBinary := make([]byte, 2)
	binary.LittleEndian.PutUint16(paramIDBinary, paramID)

	packet := []byte{0, 0, 0, 0, ComStmtSendLongData}
	packet = append(packet, stmtIDBinary...)  // append stmt ID
	packet = append(packet, paramIDBinary...) // append param ID
	packet = append(packet, data...)          // append data
	return packet
}

type testRun struct {
	t              *testing.T
	err            error
	expParamCounts int
	expQuery       string
	expStmtID      int
}

func (t testRun) ComStmtExecute(c *Conn, prepare *PrepareData, callback func(*sqltypes.Result) error) error {
	panic("implement me")
}

func (t testRun) NewConnection(c *Conn) {
	panic("implement me")
}

func (t testRun) ConnectionClosed(c *Conn) {
	panic("implement me")
}

func (t testRun) ComQuery(c *Conn, query string, callback func(*sqltypes.Result) error) error {
	if strings.Contains(query, "error") {
		return t.err
	}
	if strings.Contains(query, "panic") {
		panic("test panic attack!")
	}
	if strings.Contains(query, "twice") {
		callback(selectRowsResult)
	}
	callback(selectRowsResult)
	return nil
}

func (t testRun) ComPrepare(c *Conn, query string, bv map[string]*querypb.BindVariable) ([]*querypb.Field, error) {
	assert.Equal(t.t, t.expQuery, query)
	assert.EqualValues(t.t, t.expStmtID, c.StatementID)
	assert.NotNil(t.t, c.PrepareData[c.StatementID])
	assert.EqualValues(t.t, t.expParamCounts, c.PrepareData[c.StatementID].ParamsCount)
	assert.Len(t.t, c.PrepareData, int(c.PrepareData[c.StatementID].ParamsCount))
	return nil, nil
}

func (t testRun) WarningCount(c *Conn) uint16 {
	return 0
}

func (t testRun) ComResetConnection(c *Conn) {
	panic("implement me")
}

var _ Handler = (*testRun)(nil)


text:
<!-- add dse CSS -->
<link href="/css/dse.css" rel="stylesheet">


text:
@interface fanweiTableViewController ()<dataHttpDelegate>

@end

@implementation fanweiTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if(!([dataHttpManager getInstance].rangeDic && [dataHttpManager getInstance].rangeDic.count > 0)){
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [[dataHttpManager getInstance] letGetRange];
        });
    }
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [dataHttpManager getInstance].delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [dataHttpManager getInstance].delegate =  nil;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0){
        return 1;
    }
    return [dataHttpManager getInstance].rangeDic.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *FirstLevelCell = @"cengji";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             FirstLevelCell];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleSubtitle
                reuseIdentifier: FirstLevelCell];
    }

    if(indexPath.section == 0){
        cell.textLabel.text = @"当前可视范围";
    }else{
        cell.textLabel.text = [[dataHttpManager getInstance].rangeDic.allKeys objectAtIndex:indexPath.row];
    }

    if([cell.textLabel.text isEqualToString:[dataHttpManager getInstance].cache.range]){
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.textLabel.adjustsFontSizeToFitWidth = YES;
    cell.textLabel.minimumScaleFactor = 0.7;
    return cell;
}

- (void)didGetFailed{
    ALERT(@"获取行政区划失败");
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        [dataHttpManager getInstance].cache.range = @"当前可视范围";
        [dataHttpManager getInstance].cache.rangeBox = nil;
    }else{
        [dataHttpManager getInstance].cache.range = [[dataHttpManager getInstance].rangeDic.allKeys objectAtIndex:indexPath.row];
        [dataHttpManager getInstance].cache.rangeBox = [[dataHttpManager getInstance].rangeDic objectForKey:[dataHttpManager getInstance].cache.range];
    }
    [tableView reloadData];
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}

- (void)didGetRange:(NSMutableDictionary *)rangeDic{
    [SVProgressHUD dismiss];
    [dataHttpManager getInstance].rangeDic = [NSDictionary dictionaryWithDictionary:rangeDic];
    [self.tableView reloadData];
}

@end


text:
const expect = require('chai').expect;
const dbUtils = require('../../db/lib/utils.js');
const Stats = require('../../db/models/cityinfo.js');

describe('city info model tests', function () {
  beforeEach(function (done) {
    dbUtils.rollbackMigrate(done);
  });

  afterEach(function (done) {
    dbUtils.rollback(done);
  });

  it('Should be able to retrieve data', function (done) {
    Stats.forge({
      city: 'san francisco',
      city_stats: 'string of info',
      city_details: 'another string'
    }).save()
    .then(() => {
      return Stats.fetchAll();
    })
      .then(function (results) {
        expect(results.length).to.equal(1);
        expect(results.at(0).get('id')).to.equal(1);
        done();
      })
      .catch(function (err) {
        done(err);
      });
  });
});


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

<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>Pittsburgh 2014
 -  Proposal</title>
<meta name="author" content="Brandon Burton" >

<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >

<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">

      Home

      Contact

      Events

      Presentations

      Blog

Pittsburgh 2014
 -  Proposal

Steel sponsors

welcome
propose
program
location
register
sponsor
contact
conduct

Back to proposals overview - program

Going whole hog on PaaS?

Abstract:

The last few years have seen the rise of Platform as a Service (PaaS) as part of the computing landscape, through the success and growth of numerous public and private offerings, both commercial and open source.

The promise of a unified platform that abstracts away language/application runtimes, data services, and systems management into a single platform that has automation, logging, metrics, auto-scaling, and self-service all baked in, is extremely appealing and implementing some kind of PaaS strategy is often a topic when discuss how to "do DevOps", as the ideas that PaaS encompasses include many core DevOps principles and the idea of a turn-key solution is hard to resist.

Unfortunately, in many ways the landscape is still young and the solutions available take many different approaches, from hosted offerings like Heroku, DotCloud, or Nodejitsu, to large scale, one-size fits all in-house offerings like CloudFoundry, OpenShift, or Stackato, to newer and more targeted (often Docker based) offerings, such as Deis, Dokku, or Flynn. So it's difficult to know where to begin and what's truly turn-key, and how far these solutions will get you in a reasonable amount of time and effort.

Drawing on my years of experience in the web hosting industry and my experience over the last two years in implementing a production in-house PaaS offering at Mozilla, I will attempt to

Provide a concise overview of the PaaS landscape

Lend some insight into what PaaS might be good for you, based on some attributes of your organization, culture, technology stack, and technical debt

Share some lessons learned in implementing a production PaaS at Mozilla, including cultural challenges, shifts in thinking required to adopting a PaaS ( the http://12factor.net/ mindset), and technical challenges, such as managed shared secrets, removing reliance on shared filesystems (NFS), etc

Provide guidance on why you may not want to adopt any PaaS solution, but instead determine how to apply your existing infrastructure automation (Configuration Management, IaaS, CI pipeline, etc) with some custom automation, APIs, self-service tools, to achieve the promise of PaaS and apply "PaaS patterns" to your existing tools and workflows.

In the end, you'll leave this talk with more insight into what PaaS means, how you can apply the patterns it embodies to improve your automation, your workflows, and ultimately your culture, and you'll know if you should go whole hog on PaaS or not.

Speaker:
Brandon Burton

Please enable JavaScript to view the comments powered by Disqus.
blog comments powered by Disqus

Aluminum sponsors

Glass sponsors

Media sponsors

Host sponsor


text:
Registrate con tu email

		<form name="userForm" data-ng-submit="signup()" class="signin form-horizontal" novalidate autocomplete="off">
			<fieldset>

					Nombre
					<input type="text" required id="firstName" name="firstName" class="form-control" data-ng-model="credentials.firstName" placeholder="Nombre">

					Apellido
					<input type="text" id="lastName" name="lastName" class="form-control" data-ng-model="credentials.lastName" placeholder="Nombre">

					Email
					<input type="email" id="email" name="email" class="form-control" data-ng-model="credentials.email" placeholder="Email">

					Usuario
					<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Usuario">

					Contraseña
					<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Contraseña">

					<button type="submit" class="btn btn-large btn-primary">Registrate</button>  o tienes cuenta?
					Ingresa

			</fieldset>
		</form>


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">

    <ImageView
        android:id="@+id/img_one"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/guide1" />

</LinearLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fungal Diversity 8: 51 (2001)

#### Original name
Cercospora jatrophigena U. Braun

### Remarks
null


text:
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Framework.Configuration;
using osu.Game.Users;

namespace osu.Game.Online.API
{
    public class DummyAPIAccess : IAPIProvider
    {
        public Bindable<User> LocalUser { get; } = new Bindable<User>(new User
        {
            Username = @"Dummy",
            Id = 1,
        });

        public bool IsLoggedIn => true;

        public void Update()
        {
        }

        public virtual void Queue(APIRequest request)
        {
        }

        public void Register(IOnlineComponent component)
        {
        }
    }
}


text:
package arboralexplorer.io;

import arboralexplorer.algo.upperbound.GreedyASS;
import arboralexplorer.data.GridSet;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Sander Verdonschot <sander.verdonschot at gmail.com>
 */
public class GridSetWriterTest {

    public GridSetWriterTest() {
    }

    @Test
    public void testExportGrid() throws Exception {
        int[] permutation = new int[]{5, 12, 4, 3, 16, 6, 14, 8, 0, 9, 17, 19, 18, 15, 2, 11, 13, 10, 1, 7};
        boolean[][] points = new boolean[permutation.length][permutation.length];

        for (int i = 0; i < permutation.length; i++) {
            points[i][permutation[i]] = true;
        }

        GridSet grid = GreedyASS.solve(new GridSet(points));

        Path temp = Paths.get("textExportGrid.tmp");
        GridSetWriter.exportGrid(grid, temp);
        GridSet grid2 = GridSetReader.importGrid(temp);
        Files.delete(temp);

        assertGridsEquals(grid, grid2);
    }

    private void assertGridsEquals(GridSet expectedGrid, GridSet actualGrid) {
        if (expectedGrid == null) {
            assertNull(actualGrid);
            return;
        }

        assertNotNull(actualGrid);

        assertEquals(expectedGrid.getWidth(), actualGrid.getWidth());
        assertEquals(expectedGrid.getHeight(), actualGrid.getHeight());

        for (int i = 0; i < expectedGrid.getWidth(); i++) {
            for (int j = 0; j < expectedGrid.getHeight(); j++) {
                assertEquals(expectedGrid.hasPoint(i, j), actualGrid.hasPoint(i, j));
                assertEquals(expectedGrid.isGroundSet(i, j), actualGrid.isGroundSet(i, j));
            }
        }
    }

}


text:
package course;

import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import freemarker.template.Configuration;
import freemarker.template.SimpleHash;
import freemarker.template.Template;
import org.apache.commons.lang3.StringEscapeUtils;
import spark.Request;
import javax.servlet.http.Cookie;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.setPort;

/**
 * This class encapsulates the controllers for the blog web application.  It delegates all interaction with MongoDB
 * to three Data Access Objects (DAOs).
 * <p/>
 * It is also the entry point into the web application.
 */
public class BlogController {

    private final Configuration cfg;
    private final BlogPostDAO blogPostDAO;
    private final UserDAO userDAO;
    private final SessionDAO sessionDAO;

    public static void main(String[] args) throws IOException {
        if (args.length == 0) {
            new BlogController("mongodb://localhost");
        } else {
            new BlogController(args[0]);
        }
    }

    public BlogController(String mongoURIString) throws IOException {
        final MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURIString));
        final DB blogDatabase = mongoClient.getDB("blog");

        blogPostDAO = new BlogPostDAO(blogDatabase);
        userDAO = new UserDAO(blogDatabase);
        sessionDAO = new SessionDAO(blogDatabase);

        cfg = createFreemarkerConfiguration();
        setPort(8082);
        initializeRoutes();
    }

    private void initializeRoutes() throws IOException {
        // this is the blog home page
        get("/", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("blog_template.ftl");
                String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

                List<DBObject> posts = blogPostDAO.findByDateDescending(10);
                SimpleHash root = new SimpleHash();

                root.put("myposts", posts);
                if (username != null) {
                    root.put("username", username);
                }

                template.process(root, writer);
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // used to display actual blog post detail page
        get("/post/:permalink", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("entry_template.ftl");
                String permalink = request.params(":permalink");

                System.out.println("/post: get " + permalink);

                DBObject post = blogPostDAO.findByPermalink(permalink);
                if (post == null) {
                    response.redirect("/post_not_found");
                } else {
                    // empty comment to hold new comment in form at bottom of blog entry detail page
                    SimpleHash newComment = new SimpleHash();
                    newComment.put("name", "");
                    newComment.put("email", "");
                    newComment.put("body", "");

                    SimpleHash root = new SimpleHash();

                    root.put("post", post);
                    root.put("comment", newComment);

                    template.process(root, writer);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // handle the signup post
        post("/signup", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("signup.ftl");
                String email = request.queryParams("email");
                String username = request.queryParams("username");
                String password = request.queryParams("password");
                String verify = request.queryParams("verify");

                HashMap<String, String> root = new HashMap<String, String>();
                root.put("username", StringEscapeUtils.escapeHtml4(username));
                root.put("email", StringEscapeUtils.escapeHtml4(email));

                if (validateSignup(username, password, verify, email, root)) { // good user
                    System.out.println("Signup: Creating user with: " + username + " " + password);
                    if (!userDAO.addUser(username, password, email)) { // duplicate user
                        root.put("username_error", "Username already in use, Please choose another");
                        template.process(root, writer);
                    } else { // good user, let's start a session
                        String sessionID = sessionDAO.startSession(username);
                        System.out.println("Session ID is" + sessionID);

                        response.raw().addCookie(new Cookie("session", sessionID));
                        response.redirect("/welcome");
                    }
                } else { // bad signup
                    System.out.println("User Registration did not validate");
                    template.process(root, writer);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // present signup form for blog
        get("/signup", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("signup.ftl");
                SimpleHash root = new SimpleHash();

                // initialize values for the form.
                root.put("username", "");
                root.put("password", "");
                root.put("email", "");
                root.put("password_error", "");
                root.put("username_error", "");
                root.put("email_error", "");
                root.put("verify_error", "");

                template.process(root, writer);
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // will present the form used to process new blog posts
        get("/newpost", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("newpost_template.ftl");
                // get cookie
                String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

                if (username == null) { // looks like a bad request. user is not logged in
                    response.redirect("/login");
                } else {
                    SimpleHash root = new SimpleHash();
                    root.put("username", username);

                    template.process(root, writer);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // handle the new post submission
        post("/newpost", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("newpost_template.ftl");
                String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject"));
                String post = StringEscapeUtils.escapeHtml4(request.queryParams("body"));
                String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags"));

                String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

                if (username == null) { // only logged in users can post to blog
                    response.redirect("/login");
                } else if (title.equals("") || post.equals("")) { // redisplay page with errors
                    HashMap<String, String> root = new HashMap<String, String>();
                    root.put("errors", "post must contain a title and blog entry.");
                    root.put("subject", title);
                    root.put("username", username);
                    root.put("tags", tags);
                    root.put("body", post);
                    template.process(root, writer);
                } else { // extract tags
                    ArrayList<String> tagsArray = extractTags(tags);

                    // substitute some <p> for the paragraph breaks
                    post = post.replaceAll("\\r?\\n", "<p>");

                    String permalink = blogPostDAO.addPost(title, post, tagsArray, username);

                    // now redirect to the blog permalink
                    response.redirect("/post/" + permalink);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        get("/welcome", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("welcome.ftl");
                String cookie = getSessionCookie(request);
                String username = sessionDAO.findUserNameBySessionId(cookie);

                if (username == null) {
                    System.out.println("welcome() can't identify the user, redirecting to signup");
                    response.redirect("/signup");
                } else {
                    SimpleHash root = new SimpleHash();

                    root.put("username", username);

                    template.process(root, writer);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // process a new comment
        post("/newcomment", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("entry_template.ftl");
                String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName"));
                String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail"));
                String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody"));
                String permalink = request.queryParams("permalink");

                DBObject post = blogPostDAO.findByPermalink(permalink);
                if (post == null) {
                    response.redirect("/post_not_found");
                } else if (name.equals("") || body.equals("")) { // check that comment is good
                    // bounce this back to the user for correction
                    SimpleHash root = new SimpleHash();
                    SimpleHash comment = new SimpleHash();

                    comment.put("name", name);
                    comment.put("email", email);
                    comment.put("body", body);
                    root.put("comment", comment);
                    root.put("post", post);
                    root.put("errors", "Post must contain your name and an actual comment");

                    template.process(root, writer);
                } else {
                    blogPostDAO.addPostComment(name, email, body, permalink);
                    response.redirect("/post/" + permalink);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // present the login page
        get("/login", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("login.ftl");
                SimpleHash root = new SimpleHash();

                root.put("username", "");
                root.put("login_error", "");

                template.process(root, writer);
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // process output coming from login form. On success redirect folks to the welcome page
        // on failure, just return an error and let them try again.
        post("/login", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("login.ftl");
                String username = request.queryParams("username");
                String password = request.queryParams("password");

                System.out.println("Login: User submitted: " + username + "  " + password);

                DBObject user = userDAO.validateLogin(username, password);

                if (user != null) { // valid user, let's log them in
                    String sessionID = sessionDAO.startSession(user.get("_id").toString());

                    if (sessionID == null) {
                        response.redirect("/internal_error");
                    } else {
                        // set the cookie for the user's browser
                        response.raw().addCookie(new Cookie("session", sessionID));
                        response.redirect("/welcome");
                    }
                } else {
                    SimpleHash root = new SimpleHash();

                    root.put("username", StringEscapeUtils.escapeHtml4(username));
                    root.put("password", "");
                    root.put("login_error", "Invalid Login");
                    template.process(root, writer);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // Show the posts filed under a certain tag
        get("/tag/:thetag", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("blog_template.ftl");

                String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
                SimpleHash root = new SimpleHash();

                String tag = StringEscapeUtils.escapeHtml4(request.params(":thetag"));
                List<DBObject> posts = blogPostDAO.findByTagDateDescending(tag);

                root.put("myposts", posts);
                if (username != null) {
                    root.put("username", username);
                }

                template.process(root, writer);
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // will allow a user to click Like on a post
        post("/like", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("entry_template.ftl");

                String permalink = request.queryParams("permalink");
                String commentOrdinalStr = request.queryParams("comment_ordinal");

                // look up the post in question
                int ordinal = Integer.parseInt(commentOrdinalStr);

                // TODO: check return or have checkSession throw
                String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
                DBObject post = blogPostDAO.findByPermalink(permalink);

                //  if post not found, redirect to post not found error
                if (post == null) {
                    response.redirect("/post_not_found");
                } else {
                    blogPostDAO.likePost(permalink, ordinal);
                    response.redirect("/post/" + permalink);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // tells the user that the URL is dead
        get("/post_not_found", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("post_not_found.ftl");
                SimpleHash root = new SimpleHash();
                template.process(root, writer);
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // allows the user to logout of the blog
        get("/logout", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("signup.ftl");
                String sessionID = getSessionCookie(request);

                if (sessionID == null) { // no session to end
                    response.redirect("/login");
                } else {
                    // deletes from session table
                    sessionDAO.endSession(sessionID);

                    // this should delete the cookie
                    Cookie c = getSessionCookieActual(request);
                    c.setMaxAge(0);

                    response.raw().addCookie(c);

                    response.redirect("/login");
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });

        // used to process internal errors
        get("/internal_error", (request, response) -> {
            StringWriter writer = new StringWriter();
            try {
                Template template = cfg.getTemplate("error_template.ftl");
                SimpleHash root = new SimpleHash();

                root.put("error", "System has encountered an error.");
                template.process(root, writer);
            } catch (Exception e) {
                e.printStackTrace();
                response.redirect("/internal_error");
            }
            return writer;
        });
    }

    // helper function to get session cookie as string
    private String getSessionCookie(final Request request) {
        if (request.raw().getCookies() == null) {
            return null;
        }
        for (Cookie cookie : request.raw().getCookies()) {
            if (cookie.getName().equals("session")) {
                return cookie.getValue();
            }
        }
        return null;
    }

    // helper function to get session cookie as string
    private Cookie getSessionCookieActual(final Request request) {
        if (request.raw().getCookies() == null) {
            return null;
        }
        for (Cookie cookie : request.raw().getCookies()) {
            if (cookie.getName().equals("session")) {
                return cookie;
            }
        }
        return null;
    }

    // tags the tags string and put it into an array
    private ArrayList<String> extractTags(String tags) {
        // probably more efficient ways to do this.
        //
        // whitespace = re.compile('\s')

        tags = tags.replaceAll("\\s", "");
        String tagArray[] = tags.split(",");

        // let's clean it up, removing the empty string and removing dups
        ArrayList<String> cleaned = new ArrayList<String>();
        for (String tag : tagArray) {
            if (!tag.equals("") && !cleaned.contains(tag)) {
                cleaned.add(tag);
            }
        }

        return cleaned;
    }

    // validates that the registration form has been filled out right and username conforms
    public boolean validateSignup(String username, String password, String verify, String email, HashMap<String, String> errors) {
        String USER_RE = "^[a-zA-Z0-9_-]{3,20}$";
        String PASS_RE = "^.{3,20}$";
        String EMAIL_RE = "^[\\S]+@[\\S]+\\.[\\S]+$";

        errors.put("username_error", "");
        errors.put("password_error", "");
        errors.put("verify_error", "");
        errors.put("email_error", "");

        if (!username.matches(USER_RE)) {
            errors.put("username_error", "invalid username. try just letters and numbers");
            return false;
        }

        if (!password.matches(PASS_RE)) {
            errors.put("password_error", "invalid password.");
            return false;
        }

        if (!password.equals(verify)) {
            errors.put("verify_error", "password must match");
            return false;
        }

        if (!email.equals("")) {
            if (!email.matches(EMAIL_RE)) {
                errors.put("email_error", "Invalid Email Address");
                return false;
            }
        }

        return true;
    }

    private Configuration createFreemarkerConfiguration() {
        Configuration retVal = new Configuration();
        retVal.setClassForTemplateLoading(BlogController.class, "/freemarker");
        return retVal;
    }

}


text:
import { isMatch } from 'lodash';

// NOTE: this method will duplicate the matching items
// currently cookies-tests use incorrect behavior of this method
// the method and cookies-tests should be rewritten
export default function matchCollection (items: object[], filters: object[]): object[] {
    if (!filters.length)
        return items;

    const result = [];

    for (const item of items) {
        for (const filter of filters) {
            if (isMatch(item, filter))
                result.push(item);
        }
    }

    return result;
}


text:
using UnityEngine;
using System.Collections;

/*objects don't necessarily need rigidbodies or mesh colliders
* it can be useful for travel aesthetics
*/
[RequireComponent(typeof(Rigidbody))]//), typeof(MeshCollider))]
public class Returnable : MonoBehaviour {

	#region vars
	private Vector3 origin;
	private Quaternion rot;
	private Transform thisTransform;
	private Rigidbody thisRigidbody;
	private Collider thisCollider;
	private float physicsToLerpThresh = 7;

	private delegate void CurrentAction();
	private CurrentAction Action;
	#endregion

	#region Unity methods
	void Start()
	{
		Action = DoNothing;
	}

	void Update()
	{
		Action();
	}
	#endregion

	#region movement
	private void LerpTravel()
	{
		float returnSpeed = (1/(thisTransform.position - origin).sqrMagnitude < .5f ) ? .5f : 1/(thisTransform.position - origin).magnitude;

		thisTransform.position = Vector3.Lerp(thisTransform.position, origin, Time.fixedDeltaTime * returnSpeed * 10);
		thisTransform.rotation = Quaternion.Lerp(thisTransform.rotation, rot, Time.fixedDeltaTime * returnSpeed * 10);

		//if object is close enough to origin, stop travelling
		if((thisTransform.position - origin).sqrMagnitude < .001f)
		{
			thisTransform.position = origin;
			thisTransform.rotation = rot;

            thisRigidbody.isKinematic = false;
            thisCollider.enabled = true;
            thisRigidbody.velocity = Vector3.zero;
            thisRigidbody.angularVelocity = Vector3.zero;
            thisCollider.isTrigger = false;

			//rigidbody actions and collider actions go here
			Action = DoNothing;
		}
	}

	//method for returning objects via their rigidbody/physics
	//the difference between lerp and physics movement is mostly aesthetic
	private void RigidBodyTravel()
	{
		thisRigidbody.AddForce((origin - thisTransform.position).normalized, ForceMode.Impulse);
		//if object is close enough to origin, switch to LerpTravel() to ensure arrival at destination
		if(Vector3.Distance(thisTransform.position, origin) < physicsToLerpThresh)
		{
            thisRigidbody.isKinematic = true;
            thisCollider.enabled = false;
			Action = LerpTravel;
		}
	}

	private void DoNothing()
	{
	}
	#endregion

	#region triggers
	public void Activated(Vector3 position)
	{
		//this portion used to control exploding
		//put enabling / disabling / on pickup actions here
		thisRigidbody.isKinematic = true;
		thisCollider.enabled = false;
		thisRigidbody.AddExplosionForce(500, position, 150);

	}

	public void Initialize()
	{
		thisTransform = transform;
		origin = thisTransform.position;
		rot = thisTransform.rotation;
		thisRigidbody = rigidbody;
		thisRigidbody.isKinematic = false;
		thisRigidbody.useGravity = true;
		thisCollider = collider;
		thisCollider.enabled = true;
        thisRigidbody.velocity = Vector3.zero;
		thisRigidbody.angularVelocity = Vector3.zero;
	}

	public void Reset()
	{
		Action = RigidBodyTravel;
		Invoke("GoHome", .2f);
	}

	private void GoHome()
	{
		Action = LerpTravel;

		thisRigidbody.isKinematic = true;
		thisCollider.enabled = false;
        thisCollider.isTrigger = true;
	}

	private void GoHomeImmediate()
	{
		Action = LerpTravel;
		thisRigidbody.isKinematic = true;
		thisCollider.enabled = false;
        thisRigidbody.useGravity = false;
        thisCollider.isTrigger = true;
	}
	#endregion

}


text:
layout: page
subheadline: 50° festival di Nuova Consonanza
title:  "Assoli per Paolo Renosto"
teaser: "In duo con il flautista Gianni Trovalusci per la serata dedicata alle musiche di Paolo Renosto."
meta_teaser: "dove va a finire il meta_teaser?"

permalink: "/music/Renosto"
breadcrumb: true
categories:
    - flute
tags:
    - concert
    - duet
    - contemporary music
    - Maderna
    - Renosto

header:
    title: ''
    image_fullwidth: "/Renosto/Renosto2.png"
image:
    thumb: /Renosto/Renosto2.png

---

6 dicembre 2013, ore 21 - Sala Casella, Filarmonica Romana

* ##### Dialodia (1971) - *Bruno Maderna*
per due flauti

* ##### Discanto (1980) - *Paolo Renosto*
per due flauti

con Gianni Trovalusci, Sala Casella (Filarmonica Romana)

  Programmi

manifesto del concerto

  locandina del festival ›


text:
namespace TotaMoviesRental.Migrations
{
    using System.Data.Entity.Migrations;

    public partial class PopulateGenres : DbMigration
    {
        public override void Up()
        {
            Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Comedy')");
            Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Action')");
            Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
            Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
        }

        public override void Down()
        {
        }
    }
}


text:
module Mogli
  class Work < Model

    define_properties :start_date, :end_date

    hash_populating_accessor :employer, "Page"
    hash_populating_accessor :location, "Page"
    hash_populating_accessor :position, "Page"
  end
end