text:
package jakdbpq

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"reflect"
	"runtime/debug"
	"strconv"
	"strings"
)

// Third-party packages:
import (
	"database/sql"
	_ "github.com/lib/pq"
)

type JakDBPQ struct {
	db *sql.DB
}

type settings struct {
	Username string
	Password string
	Database string
	Host     string
}

type column struct {
	Name        string
	Type        string
	Value       interface{}
	PrimaryKey  bool
	Unique      bool
	NotNull     bool
	StructField int
	// Table      string
}

type Query struct {
	thing   interface{}
	filters []filter
	limit   int
}

type filter struct {
	Column   string
	Operator string
	Value    interface{}
}

var sttngs settings

func init() {

	// PULL DB SETTINGS FROM AN EXTERNAL SOURCE:

	var (
		file   *os.File
		err    error
		err_   error
		buf    *bytes.Buffer
		output []byte
	)

	// Open the file. If it doesn't exist, create it.

	if file, err_ = os.Open("dbsettings.json"); err_ != nil {
		if os.IsNotExist(err_) {
			log.Println("The file, dbsettings.json, does not exist. A new one is being created for you.")

			if file, err = os.Create("dbsettings.json"); err != nil {
				log.Println("Failure creating the new dbsettings.json: " + err.Error())
				file.Close()
			}
			if output, err = json.Marshal(sttngs); err != nil {
				log.Println("Failure to marshall settings into JSON: " + err.Error())
			}
			buf = bytes.NewBuffer(output)
			if _, err = buf.WriteTo(file); err != nil {
				log.Println("Failure to write settings into new dbsettings.json: " + err.Error())
			}
		}
		log.Fatalln("Failure opening dbsettings.json: " + err_.Error())
	}

	defer file.Close()

	// Read the file, unmarshall it into the package settings variable.

	buf = new(bytes.Buffer)
	if _, err = buf.ReadFrom(file); err != nil {
		log.Fatalln("Failure reading dbsettings.json: " + err.Error())
	}

	if err = json.Unmarshal(buf.Bytes(), &sttngs); err != nil {
		log.Fatalln("Failure decoding dbsettings.json: " + err.Error())
	}
}

func NewConnection() *JakDBPQ {
	jdb := new(JakDBPQ)

	setstring := fmt.Sprintf("dbname=%s host=%s user=%s password=%s", sttngs.Database, sttngs.Host, sttngs.Username, sttngs.Password)

	db, err := sql.Open("postgres", setstring)
	if err != nil {
		log.Fatalln("jakdb.OpenDB: Unable to open database:\n" + err.Error())
	}

	jdb.db = db

	return jdb
}

func (jdb *JakDBPQ) Delete(thing interface{}) error {

	pkey := getPrimaryKey(thing)
	table := getTableName(thing)

	stmt, err := jdb.prepare("DELETE FROM " + table + " WHERE " + pkey.Name + "=$1")
	if err != nil {
		return errors.New("jakdb.Delete: Unable to prepare DELETE statement:\n" + err.Error())
	}
	defer stmt.Close()

	_, err = stmt.Exec(pkey.Value)
	if err != nil {
		return errors.New("jakdb.Delete: Unable to execute DELETE statement:\n" + err.Error())
	}

	return nil
}

func Exists(thing interface{}) (bool, error) {

	jdb := NewConnection()

	pkey := getPrimaryKey(thing)
	table := getTableName(thing)

	stmt, err := jdb.prepare("SELECT " + pkey.Name + " FROM " + table + " WHERE " + pkey.Name + "=$1")
	if err != nil {
		return false, errors.New("jakdb.Exists: Unable to prepare SELECT statement\n" + err.Error())
	}
	defer stmt.Close()

	rows, err := stmt.Query(pkey.Value)
	if err != nil {
		return false, errors.New("jakdb.Exists: Unable to execute SELECT statement:\n" + err.Error())
	}
	defer rows.Close()
	return rows.Next(), nil
}

func Index(thing interface{}) ([]string, error) {

	jdb := NewConnection()

	pkey := getPrimaryKey(thing)
	table := getTableName(thing)

	stmt, err := jdb.prepare("SELECT " + pkey.Name + " FROM " + table)
	if err != nil {
		return nil, errors.New("jakdb.Index: Unable to prepare SELECT statement.")
	}
	defer stmt.Close()

	var keys []string
	rows, err := stmt.Query()
	for rows.Next() {
		var key string
		rows.Scan(&key)
		keys = append(keys, key)
	}
	return keys, nil
}

func Insert(thing interface{}) error {

	jdb := NewConnection()

	cols := getColumns(thing)
	vals := make([]interface{}, 0)
	table := getTableName(thing)

	// Third, generate the prepared statement with the column names.
	query := "INSERT INTO " + table + " ("
	for _, col := range cols {
		query += col.Name + ","
		vals = append(vals, col.Value)
	}
	query = query[0 : len(query)-1] // Remove the trailing comma.
	query += ") VALUES ("
	for i := 1; i <= len(cols); i++ {
		query += "$" + strconv.Itoa(i) + ","
	}
	query = query[0 : len(query)-1] // Remove the trailing comma.
	query += ") "

	stmt, err := jdb.db.Prepare(query)
	if err != nil {
		return errors.New("jakdb.Insert: Unable to prepare INSERT statement:\n" + err.Error())
	}
	defer stmt.Close()

	_, err = stmt.Exec(vals...)
	if err != nil {
		return errors.New("jakdb.Insert: Unable to execute INSERT statement:\n" + err.Error())
	}

	return nil
}

func NewSelect(thing interface{}) *Query {

	q := new(Query)
	q.thing = thing

	return q
}

func (q *Query) Filter(column string, operator string, value interface{}) *Query {
	column = strings.ToLower(column)
	q.filters = append(q.filters, filter{column, operator, value})
	return q
}

func (q *Query) Limit(limit int) *Query {
	q.limit = limit
	return q
}

func (q *Query) Execute() ([]interface{}, error) {

	jdb := NewConnection()

	//	pkey := getPrimaryKey(q.Thing)         // Primary key.
	table := getTableName(q.thing) // Table name.
	cols := getColumns(q.thing)    // List of column names.
	args := make([]interface{}, 0) // Query arguments.
	//	vals := make([]interface{}, len(cols))    // Intermediate values.
	vals_pt := make([]interface{}, len(cols)) // Returned value pointers.
	results := make([]interface{}, 0)         // Cumulative results, one per row.

	// Generate the prepared statement with the column names.
	query := "SELECT "
	for _, col := range cols {
		query += col.Name + ","
	}
	query = query[0 : len(query)-1] // Remove the trailing comma.
	query += " FROM " + table

	// Append filters.
	if len(q.filters) > 0 {
		query += " WHERE"

		for idx, filter := range q.filters {
			query += " " + filter.Column + filter.Operator + "$" + strconv.Itoa(idx+1) + " AND "
			args = append(args, filter.Value)
		}
		query = query[0 : len(query)-4] // Remove the trailing AND.

	}

	if q.limit > 0 {
		query += " LIMIT " + fmt.Sprintf("%d", q.limit)
	}

	// Prepare the query.
	stmt, err := jdb.prepare(query)
	if err != nil {
		log.Printf("Query:\n%s\n", query)
		return results, errors.New("jakdb.Execute: Unable to prepare SELECT statement:\n" + err.Error())
	}
	defer stmt.Close()

	// Execute the query.
	rows, err := stmt.Query(args...)
	if err != nil {
		return results, errors.New("jakdb.Execute: Unable to execute SELECT statement:\n" + err.Error())
	}

	//	log.Printf("Executed query:\n%#v\n", query)
	//	log.Printf("Query arguements:\n%#v\n", args)

	// Iterate over the rows and extract the data.
	for rows.Next() {
		thing_type := reflect.TypeOf(q.thing)
		new_thing := reflect.New(thing_type).Interface()
		thing_value := reflect.ValueOf(new_thing)

		// work-around to satisfy rows.Scan().
		for i, _ := range cols {
			vals_pt[i] = thing_value.Elem().Field(cols[i].StructField).Addr().Interface()
		}

		if err := rows.Scan(vals_pt...); err != nil {
			return results, errors.New("jakdb.Execute: Unable to scan data into memory:\n" + err.Error())
		}

		results = append(results, new_thing)
	}

	return results, nil
}

func (jdb *JakDBPQ) Select(thing interface{}) error {

	pkey := getPrimaryKey(thing)
	cols := getColumns(thing)
	vals := make([]interface{}, 0)
	table := getTableName(thing)

	// Third, generate the prepared statement with the column names.
	query := "SELECT "
	for _, col := range cols {
		query += col.Name + ","
		vals = append(vals, col.Value)
	}
	query = query[0 : len(query)-1] // Remove the trailing comma.
	query += " FROM " + table + " WHERE " + pkey.Name + "=$1"

	stmt, err := jdb.prepare(query)
	if err != nil {
		return errors.New("jakdb.Select: Unable to prepare SELECT statement:\n" + err.Error())
	}
	defer stmt.Close()

	rows, err := stmt.Query(pkey.Value)
	if err != nil {
		return errors.New("jakdb.Select: Unable to execute SELECT statement:\n" + err.Error())
	}
	rows.Next()

	err = rows.Scan(vals...)
	if err != nil {
		return errors.New("jakdb.Select: Unable to scan data into memory:\n" + err.Error())
	}

	return nil
}

func Update(thing interface{}) error {

	jdb := NewConnection()

	pkey := getPrimaryKey(thing)
	cols := getColumns(thing)
	vals := make([]interface{}, 0)
	table := getTableName(thing)

	query := "UPDATE " + table + " SET "
	for k, col := range cols {
		query += col.Name + "=$" + strconv.Itoa(k+1) + ","
		vals = append(vals, col.Value)
	}
	query = query[0 : len(query)-1]

	query += " WHERE " + pkey.Name + "=$" + strconv.Itoa(len(cols)+1)

	vals = append(vals, pkey.Value)

	stmt, err := jdb.prepare(query)
	if err != nil {
		return errors.New("jakdb.Update: Unable to prepare UPDATE statement:\n" + err.Error())
	}
	defer stmt.Close()

	// Fourth, execute the statement with the slice of values.
	_, err = stmt.Exec(vals...)
	if err != nil {
		return errors.New("jakdb.Update: Unable to execute UPDATE statement:\n" + err.Error())
	}

	return nil
}

func (jdb *JakDBPQ) prepare(query string) (*sql.Stmt, error) {
	return jdb.db.Prepare(query)
}

func Put(thing interface{}) error {

	if exists, err := Exists(thing); err != nil {
		return err
	} else if !exists {
		return Insert(thing)
	}
	return Update(thing)
}

func getPrimaryKey(thing interface{}) column {

	var col column

	cols := getColumns(thing)
	for _, test := range cols {
		if test.PrimaryKey {
			col = test
		}
	}

	return col
}

func getColumns(thing interface{}) []column {
	columns := make([]column, 0)

	thing_type := reflect.TypeOf(thing)
	//	table_name := tableName(thing)

	for i := 0; i < thing_type.NumField(); i++ {
		field := thing_type.Field(i)
		tag := field.Tag.Get("jackdb")

		var col column

		// Column Name:
		col.Name = strings.ToLower(field.Name)

		// Table Name:
		//		col.Table = table_name

		// Primary Key Status:
		col.PrimaryKey = (tag == "primary_key")

		// Struct Field identifier:
		col.StructField = i

		// Column Type:
		if tag != "-" {
			switch field.Type.Kind() {
			case reflect.Int64:
				col.Type = "bigint"
			case reflect.String:
				col.Type = "text"
			case reflect.Bool:
				col.Type = "boolean"
			case reflect.Int:
				col.Type = "integer"
			case reflect.Slice:
				col.Type = "text" // For JSON storage.
			case reflect.Struct:
				col.Type = "text" // For JSON storage.
			default:
				col.Type = field.Type.Name()
			}
		}

		// Column Value:
		col.Value = reflect.ValueOf(thing).Field(i).Interface()

		columns = append(columns, col)
	}
	//	log.Printf("Columns Map: %#v", columns)

	return columns
}

func getTableName(thing interface{}) string {
	descriptor := reflect.TypeOf(thing).PkgPath() + "." + reflect.TypeOf(thing).Name()

	var table string
	for _, rt := range registeredTypes {
		if reflect.TypeOf(thing) == reflect.TypeOf(rt.thing) {
			table = rt.table
		}
	}
	if table == "" {
		debug.PrintStack()
		log.Fatal("A table name was not found for " + descriptor + ".")
	}
	return table
}

//func tableName(thing interface{}) string {
//	thing_type := reflect.TypeOf(thing)
//	table_name := thing_type.PkgPath() + "_" + thing_type.Name()
//	table_name = strings.ToLower(table_name)
//	table_name = strings.Replace(table_name, "/", "_", -1)
//
//	return table_name
//}


text:
package com.bignerdranchldp.android.runtracker.activity;

import java.io.File;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.bignerdranchldp.android.runtracker.R;
import com.bignerdranchldp.android.runtracker.domain.ServerAPKInfo;
import com.bignerdranchldp.android.runtracker.fragment.FirstUseGuideFragment;
import com.bignerdranchldp.android.runtracker.utils.http.HttpCallbackListener;
import com.bignerdranchldp.android.runtracker.utils.http.HttpConnectionUtil;

public class SplashActivity extends ActionBarActivity{

	private static final String TAG = SplashActivity.class.getSimpleName();

	private static final int NETWORK_ERROR = 1;

	private static final int JSON_ERROR = 2;

	private static final int ENTER_HOME = 3;

	private static final int UPDATE_DIALOG = 4;

	public static final String PREF_FIRST_USE_GUIDE_SHOW = "firstUseGuideShow";

	private static final String DIALOG_SHOW_FIRST_USE_GUIDE = "dialogShowFirstUseGuide";

	private SharedPreferences mPref;

	private ServerAPKInfo serverAPKInfo;

	private ProgressBar pbSplashDownload;

	private Handler handler = new Handler(){

		public void handleMessage(Message msg) {

			switch (msg.what) {

			case NETWORK_ERROR:

				Log.i(TAG, "ÍøÂçÒì³£");
//				Toast.makeText(SplashActivity.this, "ÍøÂçÒì³£", Toast.LENGTH_SHORT).show();
				enterHome();
				break;

			case JSON_ERROR:

				Log.i(TAG, "JSON½âÎöÒì³£");
				Toast.makeText(SplashActivity.this
						, "JSON½âÎöÒì³£", Toast.LENGTH_SHORT).show();
				enterHome();
				break;

			case ENTER_HOME:

				Log.i(TAG, "½øÈëÖ÷½çÃæ");
				enterHome();
				break;

			case UPDATE_DIALOG:

				Log.i(TAG, "µ¯³öÉý¼¶¶Ô»°¿ò");
				showUpdateDialog();
				break;

			default:
				break;
			}
		};
	};

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

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash);

		mPref = PreferenceManager.getDefaultSharedPreferences(this);

        pbSplashDownload = (ProgressBar) findViewById(R.id.pb_splash_download);
		pbSplashDownload.setProgress(0);
        pbSplashDownload.setVisibility(View.INVISIBLE);

        checkVersion();

	}

	private void enterHome(){

		boolean isFirstGuideShow = mPref.getBoolean(PREF_FIRST_USE_GUIDE_SHOW, true);
		if(isFirstGuideShow){

			showFirstGuide();
		}else{

			enterMainPrograme();
		}
	}

	private void enterMainPrograme(){

		Intent intent = new Intent(this,RunListActivity.class);
		startActivity(intent);
		finish();
	}

	private void showFirstGuide() {

		FirstUseGuideFragment firstUseGuideFragment = new FirstUseGuideFragment();

		FragmentManager fragmentManager = getSupportFragmentManager();
		firstUseGuideFragment.show(fragmentManager, DIALOG_SHOW_FIRST_USE_GUIDE);
	}

	/**
	 * È¡µÃ·þÎñÆ÷µÄ°æ±¾Ãû³Æ£¬²¢ºÍ·þÎñÆ÷µÄ°æ±¾Ãû³Æ½øÐбȶÔ
	 */
	private void checkVersion() {

		final long startTime = System.currentTimeMillis();

    	String infoUrl = getString(R.string.serverApkInfoUrl);
    	HttpConnectionUtil.connect(infoUrl,"UTF-8",2000,3000, new HttpCallbackListener() {

			@Override
			public void onFinish(String response) {

				long endTime = System.currentTimeMillis();
				long elapsedTime = endTime - startTime;
				//չʾ2ÃëÖÓµÄlogo
				if(elapsedTime<2000){
					try {
						Thread.sleep(2000-elapsedTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				Log.i(TAG, response);
				try {
					serverAPKInfo = ServerAPKInfo.buildFromJson(response);
				} catch (JSONException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(JSON_ERROR);
					return;
				}

				String currVersionName = getVersionName();
				if(currVersionName.equals(serverAPKInfo.getVersionName())){

					handler.sendEmptyMessage(ENTER_HOME);
				}else{

					handler.sendEmptyMessage(UPDATE_DIALOG);
				}
			}

			@Override
			public void onError(Exception ex) {

				Log.e(TAG, "", ex);

				handler.sendEmptyMessage(NETWORK_ERROR);
			}
		});
	}

	/**
	 * È¡µÃ°æ±¾Ãû³Æ
	 * @return
	 */
	public String getVersionName(){

    	PackageManager pm = getPackageManager();
    	try {
			PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}
    }

    /**
     * µ¯³öÉý¼¶¶Ô»°¿ò
     */
    private void showUpdateDialog() {

    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("·¢ÏÖа汾£¬ÊÇ·ñÉý¼¶");
    	builder.setMessage(serverAPKInfo.getDescription());
    	builder.setCancelable(true);
    	builder.setPositiveButton("Éý¼¶", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				dialog.dismiss();
				updateCurrentProgram();
			}
		});

    	builder.setNegativeButton("Ôݲ»Éý¼¶", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				dialog.dismiss();
				enterHome();
			}
		});

    	//µ±Óû§È¡Ïûʱ½øÈëÖ÷Ò³Ãæ
    	builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {

				Log.i(TAG, "onCancel");
				dialog.dismiss();
				enterHome();
			}
		});

    	builder.show();
	}

    /**
     * Éý¼¶µ±Ç°Ó¦ÓÃ
     */
	private void updateCurrentProgram() {

		//È¡µÃÍâÖÃSD¿¨µÄ״̬
		String externalStorageState = Environment.getExternalStorageState();
		if(externalStorageState.equals(Environment.MEDIA_MOUNTED)){

			String externalStoragePath =
					Environment.getExternalStorageDirectory().getAbsolutePath();
			String newApkPath = externalStoragePath + "/download/runTracker.apk";
			File newApkFile = new File(newApkPath);
			newApkFile.delete();

			pbSplashDownload.setVisibility(View.VISIBLE);

			FinalHttp finalHttp = new FinalHttp();
			finalHttp.download(
					serverAPKInfo.getApkUrl()
					, newApkPath
					, new AjaxCallBack<File>() {

						@Override
						public void onLoading(long count, long current) {

							super.onLoading(count, current);
							int progress = (int) (current*100/count);
							pbSplashDownload.setProgress(progress);
						}

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {

							super.onFailure(t, errorNo, strMsg);
							Log.e(TAG, "", t);
							Toast.makeText(SplashActivity.this, "ÏÂÔØʧ°Ü", Toast.LENGTH_SHORT).show();

							enterHome();
						}

						@Override
						public void onSuccess(File t) {

							super.onSuccess(t);

							Intent intent = new Intent();
							intent.setAction("android.intent.action.VIEW");
							intent.addCategory("android.intent.category.DEFAULT");
							intent.setDataAndType(Uri.fromFile(t)
									, "application/vnd.android.package-archive");
							startActivity(intent);
							SplashActivity.this.finish();
						}

			});

		}else{
			//sd´æ´¢¿¨²»¿ÉÓÃ
			Toast.makeText(this, "SD¿¨ÎÞ·¨Ê¹Óã¬ÎÞ·¨Éý¼¶", Toast.LENGTH_SHORT).show();

			enterHome();
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
describe Picture do
  subject { FactoryGirl.build(:picture) }

  it "auto-creates needed directory" do
    expect(File.directory?(described_class.directory)).to be_truthy
  end

  context "#content" do
    it 'returns expected content' do
      expected = "FOOBAR"
      subject.content = expected.dup
      expect(subject.content).to eq(expected)
    end

    it 'requires content' do
      subject.content = ''
      expect(subject.valid?).to be_falsey
    end
  end

  context "#extension" do
    it 'is required' do
      subject.extension = nil
      expect(subject.valid?).to be_falsey
      expect(subject.errors.messages).to eq(:extension => ["can't be blank", "must be a png, jpg, or svg"])
    end

    it "accepts only png, jpg, or svg" do
      subject.extension = "foo"

      expect(subject.valid?).to be_falsey
      expect(subject.errors.messages).to eq(:extension =>['must be a png, jpg, or svg'])

      subject.extension = "png"
      expect(subject.valid?).to be_truthy

      subject.extension = "jpg"
      expect(subject.valid?).to be_truthy

      subject.extension = "svg"
      expect(subject.valid?).to be_truthy
    end

    it "on new record" do
      ext = "png"
      subject.extension = ext.dup
      expect(subject.extension).to eq(ext)

      subject.save

      p = described_class.first
      expect(p.extension).to eq(ext)

      subject.reload
      expect(subject.extension).to eq(ext)
    end

    it "on existing record" do
      subject.save
      subject.reload

      ext = "jpg"
      subject.extension = ext.dup
      expect(subject.extension).to eq(ext)

      subject.save

      p = described_class.first
      expect(p.extension).to eq(ext)

      subject.reload
      expect(subject.extension).to eq(ext)
    end
  end

  it "#size" do
    expected = "FOOBAR"
    subject.content = expected.dup
    expect(subject.size).to eq(expected.length)
  end

  context "#basename" do
    it "fails when record is new" do
      expect { subject.filename }.to raise_error(RuntimeError, /must have a numeric id/)
    end

    context "works when record is saved" do
      it "with extension" do
        subject.extension = "png"
        subject.save
        expect(subject.basename).to eq("#{subject.id}.#{subject.extension}")
      end
    end
  end

  context '.create_from_base64' do
    let(:attributes) do
      {
        :extension => 'png',
        :content   => 'aW1hZ2U='
      }
    end

    it 'creates a picture' do
      expect do
        Picture.create_from_base64(attributes)
      end.to change(Picture, :count).by(1)
    end

    it 'requires valid base64' do
      attributes[:content] = 'bogus'
      expect do
        Picture.create_from_base64(attributes)
      end.to raise_error(StandardError, 'invalid base64')
    end
  end

  it "#filename" do
    basename = "foo.bar"
    allow(subject).to receive(:basename).and_return(basename)
    expect(subject.filename).to eq(File.join(Picture.directory, basename))
  end

  it "#url_path" do
    basename = "foo.bar"
    allow(subject).to receive(:basename).and_return(basename)
    expect(subject.url_path).to eq("/pictures/#{basename}")
  end
end


text:
package hudson.model;

import hudson.XmlFile;

import java.io.*;
import java.util.concurrent.Future;
import java.util.regex.Pattern;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;

import hudson.security.*;
import hudson.util.StreamTaskListener;
import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;

public class CauseTest {

    @Rule public JenkinsRule j = new JenkinsRule();

    @Issue("JENKINS-14814")
    @Test public void deeplyNestedCauses() throws Exception {
        FreeStyleProject a = j.createFreeStyleProject("a");
        FreeStyleProject b = j.createFreeStyleProject("b");
        Run<?,?> early = null;
        Run<?,?> last = null;
        for (int i = 1; i <= 15; i++) {
            last = b.scheduleBuild2(0, new Cause.UpstreamCause((Run<?,?>) a.scheduleBuild2(0, last == null ? null : new Cause.UpstreamCause(last)).get())).get();
            if (i == 5) {
                early = last;
            }
        }
        String buildXml = new XmlFile(Run.XSTREAM, new File(early.getRootDir(), "build.xml")).asString();
        assertTrue("keeps full history:\n" + buildXml, buildXml.contains("<upstreamBuild>1</upstreamBuild>"));
        buildXml = new XmlFile(Run.XSTREAM, new File(last.getRootDir(), "build.xml")).asString();
        assertFalse("too big:\n" + buildXml, buildXml.contains("<upstreamBuild>1</upstreamBuild>"));
    }

    @Issue("JENKINS-15747")
    @Test public void broadlyNestedCauses() throws Exception {
        FreeStyleProject a = j.createFreeStyleProject("a");
        FreeStyleProject b = j.createFreeStyleProject("b");
        FreeStyleProject c = j.createFreeStyleProject("c");
        Run<?,?> last = null;
        for (int i = 1; i <= 10; i++) {
            Cause cause = last == null ? null : new Cause.UpstreamCause(last);
            Future<? extends Run<?,?>> next1 = a.scheduleBuild2(0, cause);
            a.scheduleBuild2(0, cause);
            cause = new Cause.UpstreamCause(next1.get());
            Future<? extends Run<?,?>> next2 = b.scheduleBuild2(0, cause);
            b.scheduleBuild2(0, cause);
            cause = new Cause.UpstreamCause(next2.get());
            Future<? extends Run<?,?>> next3 = c.scheduleBuild2(0, cause);
            c.scheduleBuild2(0, cause);
            last = next3.get();
        }
        int count = new XmlFile(Run.XSTREAM, new File(last.getRootDir(), "build.xml")).asString().split(Pattern.quote("<hudson.model.Cause_-UpstreamCause")).length;
        assertFalse("too big at " + count, count > 100);
        //j.interactiveBreak();
    }

    @Issue("JENKINS-48467")
    @Test public void userIdCausePrintTest() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        TaskListener listener = new StreamTaskListener(baos);

        //null userId - print unknown or anonymous
        Cause causeA = new Cause.UserIdCause(null);
        causeA.print(listener);

        assertEquals(baos.toString().trim(),"Started by user unknown or anonymous");
        baos.reset();

        //SYSTEM userid  - getDisplayName() should be SYSTEM
        Cause causeB = new Cause.UserIdCause();
        causeB.print(listener);

        assertThat(baos.toString(), containsString("SYSTEM"));
        baos.reset();

        //unknown userid - print unknown or anonymous
        Cause causeC = new Cause.UserIdCause("abc123");
        causeC.print(listener);

        assertEquals(baos.toString().trim(),"Started by user unknown or anonymous");
        baos.reset();

        //More or less standard operation
        //user userid  - getDisplayName() should be foo
        User user = User.getById("foo", true);
        Cause causeD = new Cause.UserIdCause(user.getId());
        causeD.print(listener);

        assertThat(baos.toString(), containsString(user.getDisplayName()));
        baos.reset();
    }
}


text:
package com.google.cloud.functions.v2;

import static com.google.cloud.functions.v2.FunctionServiceClient.ListFunctionsPagedResponse;
import static com.google.cloud.functions.v2.FunctionServiceClient.ListLocationsPagedResponse;

import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientSettings;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.cloud.functions.v2.stub.FunctionServiceStubSettings;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
 * Settings class to configure an instance of {@link FunctionServiceClient}.
 *
 *
The default instance has everything set to sensible defaults:
 *
 *

 *
The default service address (cloudfunctions.googleapis.com) and default port (443) are
 *       used.
 *
Credentials are acquired automatically through Application Default Credentials.
 *
Retries are configured for idempotent methods but not for non-idempotent methods.
 *

 *
 *
The builder of this class is recursive, so contained classes are themselves builders. When
 * build() is called, the tree of builders is called to create the complete settings object.
 *
 *
For example, to set the total timeout of getFunction to 30 seconds:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * FunctionServiceSettings.Builder functionServiceSettingsBuilder =
 *     FunctionServiceSettings.newBuilder();
 * functionServiceSettingsBuilder
 *     .getFunctionSettings()
 *     .setRetrySettings(
 *         functionServiceSettingsBuilder.getFunctionSettings().getRetrySettings().toBuilder()
 *             .setTotalTimeout(Duration.ofSeconds(30))
 *             .build());
 * FunctionServiceSettings functionServiceSettings = functionServiceSettingsBuilder.build();
 * }

 */
@Generated("by gapic-generator-java")
public class FunctionServiceSettings extends ClientSettings<FunctionServiceSettings> {

  /** Returns the object with the settings used for calls to getFunction. */
  public UnaryCallSettings<GetFunctionRequest, Function> getFunctionSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).getFunctionSettings();
  }

  /** Returns the object with the settings used for calls to listFunctions. */
  public PagedCallSettings<ListFunctionsRequest, ListFunctionsResponse, ListFunctionsPagedResponse>
      listFunctionsSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).listFunctionsSettings();
  }

  /** Returns the object with the settings used for calls to createFunction. */
  public UnaryCallSettings<CreateFunctionRequest, Operation> createFunctionSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).createFunctionSettings();
  }

  /** Returns the object with the settings used for calls to createFunction. */
  public OperationCallSettings<CreateFunctionRequest, Function, OperationMetadata>
      createFunctionOperationSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).createFunctionOperationSettings();
  }

  /** Returns the object with the settings used for calls to updateFunction. */
  public UnaryCallSettings<UpdateFunctionRequest, Operation> updateFunctionSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).updateFunctionSettings();
  }

  /** Returns the object with the settings used for calls to updateFunction. */
  public OperationCallSettings<UpdateFunctionRequest, Function, OperationMetadata>
      updateFunctionOperationSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).updateFunctionOperationSettings();
  }

  /** Returns the object with the settings used for calls to deleteFunction. */
  public UnaryCallSettings<DeleteFunctionRequest, Operation> deleteFunctionSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).deleteFunctionSettings();
  }

  /** Returns the object with the settings used for calls to deleteFunction. */
  public OperationCallSettings<DeleteFunctionRequest, Empty, OperationMetadata>
      deleteFunctionOperationSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).deleteFunctionOperationSettings();
  }

  /** Returns the object with the settings used for calls to generateUploadUrl. */
  public UnaryCallSettings<GenerateUploadUrlRequest, GenerateUploadUrlResponse>
      generateUploadUrlSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).generateUploadUrlSettings();
  }

  /** Returns the object with the settings used for calls to generateDownloadUrl. */
  public UnaryCallSettings<GenerateDownloadUrlRequest, GenerateDownloadUrlResponse>
      generateDownloadUrlSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).generateDownloadUrlSettings();
  }

  /** Returns the object with the settings used for calls to listRuntimes. */
  public UnaryCallSettings<ListRuntimesRequest, ListRuntimesResponse> listRuntimesSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).listRuntimesSettings();
  }

  /** Returns the object with the settings used for calls to listLocations. */
  public PagedCallSettings<ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
      listLocationsSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).listLocationsSettings();
  }

  /** Returns the object with the settings used for calls to setIamPolicy. */
  public UnaryCallSettings<SetIamPolicyRequest, Policy> setIamPolicySettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).setIamPolicySettings();
  }

  /** Returns the object with the settings used for calls to getIamPolicy. */
  public UnaryCallSettings<GetIamPolicyRequest, Policy> getIamPolicySettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).getIamPolicySettings();
  }

  /** Returns the object with the settings used for calls to testIamPermissions. */
  public UnaryCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse>
      testIamPermissionsSettings() {
    return ((FunctionServiceStubSettings) getStubSettings()).testIamPermissionsSettings();
  }

  public static final FunctionServiceSettings create(FunctionServiceStubSettings stub)
      throws IOException {
    return new FunctionServiceSettings.Builder(stub.toBuilder()).build();
  }

  /** Returns a builder for the default ExecutorProvider for this service. */
  public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
    return FunctionServiceStubSettings.defaultExecutorProviderBuilder();
  }

  /** Returns the default service endpoint. */
  public static String getDefaultEndpoint() {
    return FunctionServiceStubSettings.getDefaultEndpoint();
  }

  /** Returns the default service scopes. */
  public static List<String> getDefaultServiceScopes() {
    return FunctionServiceStubSettings.getDefaultServiceScopes();
  }

  /** Returns a builder for the default credentials for this service. */
  public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
    return FunctionServiceStubSettings.defaultCredentialsProviderBuilder();
  }

  /** Returns a builder for the default gRPC ChannelProvider for this service. */
  public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
    return FunctionServiceStubSettings.defaultGrpcTransportProviderBuilder();
  }

  /** Returns a builder for the default REST ChannelProvider for this service. */
  @BetaApi
  public static InstantiatingHttpJsonChannelProvider.Builder
      defaultHttpJsonTransportProviderBuilder() {
    return FunctionServiceStubSettings.defaultHttpJsonTransportProviderBuilder();
  }

  public static TransportChannelProvider defaultTransportChannelProvider() {
    return FunctionServiceStubSettings.defaultTransportChannelProvider();
  }

  @BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
  public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
    return FunctionServiceStubSettings.defaultApiClientHeaderProviderBuilder();
  }

  /** Returns a new gRPC builder for this class. */
  public static Builder newBuilder() {
    return Builder.createDefault();
  }

  /** Returns a new REST builder for this class. */
  @BetaApi
  public static Builder newHttpJsonBuilder() {
    return Builder.createHttpJsonDefault();
  }

  /** Returns a new builder for this class. */
  public static Builder newBuilder(ClientContext clientContext) {
    return new Builder(clientContext);
  }

  /** Returns a builder containing all the values of this settings class. */
  public Builder toBuilder() {
    return new Builder(this);
  }

  protected FunctionServiceSettings(Builder settingsBuilder) throws IOException {
    super(settingsBuilder);
  }

  /** Builder for FunctionServiceSettings. */
  public static class Builder extends ClientSettings.Builder<FunctionServiceSettings, Builder> {

    protected Builder() throws IOException {
      this(((ClientContext) null));
    }

    protected Builder(ClientContext clientContext) {
      super(FunctionServiceStubSettings.newBuilder(clientContext));
    }

    protected Builder(FunctionServiceSettings settings) {
      super(settings.getStubSettings().toBuilder());
    }

    protected Builder(FunctionServiceStubSettings.Builder stubSettings) {
      super(stubSettings);
    }

    private static Builder createDefault() {
      return new Builder(FunctionServiceStubSettings.newBuilder());
    }

    @BetaApi
    private static Builder createHttpJsonDefault() {
      return new Builder(FunctionServiceStubSettings.newHttpJsonBuilder());
    }

    public FunctionServiceStubSettings.Builder getStubSettingsBuilder() {
      return ((FunctionServiceStubSettings.Builder) getStubSettings());
    }

    /**
     * Applies the given settings updater function to all of the unary API methods in this service.
     *
     *
Note: This method does not support applying settings to streaming methods.
     */
    public Builder applyToAllUnaryMethods(
        ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
      super.applyToAllUnaryMethods(
          getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
      return this;
    }

    /** Returns the builder for the settings used for calls to getFunction. */
    public UnaryCallSettings.Builder<GetFunctionRequest, Function> getFunctionSettings() {
      return getStubSettingsBuilder().getFunctionSettings();
    }

    /** Returns the builder for the settings used for calls to listFunctions. */
    public PagedCallSettings.Builder<
            ListFunctionsRequest, ListFunctionsResponse, ListFunctionsPagedResponse>
        listFunctionsSettings() {
      return getStubSettingsBuilder().listFunctionsSettings();
    }

    /** Returns the builder for the settings used for calls to createFunction. */
    public UnaryCallSettings.Builder<CreateFunctionRequest, Operation> createFunctionSettings() {
      return getStubSettingsBuilder().createFunctionSettings();
    }

    /** Returns the builder for the settings used for calls to createFunction. */
    public OperationCallSettings.Builder<CreateFunctionRequest, Function, OperationMetadata>
        createFunctionOperationSettings() {
      return getStubSettingsBuilder().createFunctionOperationSettings();
    }

    /** Returns the builder for the settings used for calls to updateFunction. */
    public UnaryCallSettings.Builder<UpdateFunctionRequest, Operation> updateFunctionSettings() {
      return getStubSettingsBuilder().updateFunctionSettings();
    }

    /** Returns the builder for the settings used for calls to updateFunction. */
    public OperationCallSettings.Builder<UpdateFunctionRequest, Function, OperationMetadata>
        updateFunctionOperationSettings() {
      return getStubSettingsBuilder().updateFunctionOperationSettings();
    }

    /** Returns the builder for the settings used for calls to deleteFunction. */
    public UnaryCallSettings.Builder<DeleteFunctionRequest, Operation> deleteFunctionSettings() {
      return getStubSettingsBuilder().deleteFunctionSettings();
    }

    /** Returns the builder for the settings used for calls to deleteFunction. */
    public OperationCallSettings.Builder<DeleteFunctionRequest, Empty, OperationMetadata>
        deleteFunctionOperationSettings() {
      return getStubSettingsBuilder().deleteFunctionOperationSettings();
    }

    /** Returns the builder for the settings used for calls to generateUploadUrl. */
    public UnaryCallSettings.Builder<GenerateUploadUrlRequest, GenerateUploadUrlResponse>
        generateUploadUrlSettings() {
      return getStubSettingsBuilder().generateUploadUrlSettings();
    }

    /** Returns the builder for the settings used for calls to generateDownloadUrl. */
    public UnaryCallSettings.Builder<GenerateDownloadUrlRequest, GenerateDownloadUrlResponse>
        generateDownloadUrlSettings() {
      return getStubSettingsBuilder().generateDownloadUrlSettings();
    }

    /** Returns the builder for the settings used for calls to listRuntimes. */
    public UnaryCallSettings.Builder<ListRuntimesRequest, ListRuntimesResponse>
        listRuntimesSettings() {
      return getStubSettingsBuilder().listRuntimesSettings();
    }

    /** Returns the builder for the settings used for calls to listLocations. */
    public PagedCallSettings.Builder<
            ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
        listLocationsSettings() {
      return getStubSettingsBuilder().listLocationsSettings();
    }

    /** Returns the builder for the settings used for calls to setIamPolicy. */
    public UnaryCallSettings.Builder<SetIamPolicyRequest, Policy> setIamPolicySettings() {
      return getStubSettingsBuilder().setIamPolicySettings();
    }

    /** Returns the builder for the settings used for calls to getIamPolicy. */
    public UnaryCallSettings.Builder<GetIamPolicyRequest, Policy> getIamPolicySettings() {
      return getStubSettingsBuilder().getIamPolicySettings();
    }

    /** Returns the builder for the settings used for calls to testIamPermissions. */
    public UnaryCallSettings.Builder<TestIamPermissionsRequest, TestIamPermissionsResponse>
        testIamPermissionsSettings() {
      return getStubSettingsBuilder().testIamPermissionsSettings();
    }

    @Override
    public FunctionServiceSettings build() throws IOException {
      return new FunctionServiceSettings(this);
    }
  }
}


text:
if vim.g.neovide then
    require("toggleterm").setup{
     open_mapping = [[<c-z>]],
     direction = 'float',
     float_opts = {
        --     border = 'single' | 'double' | 'shadow' | 'curved' | ... other options supported by win open
        border = 'curved',
     },
    }

    local Terminal  = require('toggleterm.terminal').Terminal
    local lazygit = Terminal:new({ cmd = "lazygit", hidden = true })

    function _lazygit_toggle()
      lazygit:toggle()
    end

    vim.api.nvim_set_keymap("n", "<A-z>", "<cmd>lua _lazygit_toggle()<CR>", {noremap = true, silent = true})
end

-- require("toggleterm").setup{
--  open_mapping = [[<c-z>]],
--  direction = 'float',
--  float_opts = {
--     --     border = 'single' | 'double' | 'shadow' | 'curved' | ... other options supported by win open
--     border = 'curved',
--  },
-- }

-- local Terminal  = require('toggleterm.terminal').Terminal
-- local lazygit = Terminal:new({ cmd = "lazygit", hidden = true })

-- function _lazygit_toggle()
--   lazygit:toggle()
-- end

-- vim.api.nvim_set_keymap("n", "<A-z>", "<cmd>lua _lazygit_toggle()<CR>", {noremap = true, silent = true})

-- WARNING: Please do not copy and paste this configuration! It is here to show what options are available. It is not written be used as is.
-- require("toggleterm").setup{
--   -- size can be a number or function which is passed the current terminal
--   size = 20 | function(term)
--     if term.direction == "horizontal" then
--       return 15
--     elseif term.direction == "vertical" then
--       return vim.o.columns * 0.4
--     end
--   end,
--   open_mapping = [[<c-\>]],
--   on_open = fun(t: Terminal), -- function to run when the terminal opens
--   on_close = fun(t: Terminal), -- function to run when the terminal closes
--   on_stdout = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stdout
--   on_stderr = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stderr
--   on_exit = fun(t: Terminal, job: number, exit_code: number, name: string) -- function to run when terminal process exits
--   hide_numbers = true, -- hide the number column in toggleterm buffers
--   shade_filetypes = {},
--   highlights = {
--     -- highlights which map to a highlight group name and a table of it's values
--     -- NOTE: this is only a subset of values, any group placed here will be set for the terminal window split
--     Normal = {
--       guibg = "<VALUE-HERE>",
--     },
--     NormalFloat = {
--       link = 'Normal'
--     },
--     FloatBorder = {
--       guifg = "<VALUE-HERE>",
--       guibg = "<VALUE-HERE>",
--     },
--   },
--   shade_terminals = true, -- NOTE: this option takes priority over highlights specified so if you specify Normal highlights you should set this to false
--   shading_factor = '<number>', -- the degree by which to darken to terminal colour, default: 1 for dark backgrounds, 3 for light
--   start_in_insert = true,
--   insert_mappings = true, -- whether or not the open mapping applies in insert mode
--   terminal_mappings = true, -- whether or not the open mapping applies in the opened terminals
--   persist_size = true,
--   persist_mode = true, -- if set to true (default) the previous terminal mode will be remembered
--   direction = 'vertical' | 'horizontal' | 'tab' | 'float',
--   close_on_exit = true, -- close the terminal window when the process exits
--   shell = vim.o.shell, -- change the default shell
--   auto_scroll = true, -- automatically scroll to the bottom on terminal output
--   -- This field is only relevant if direction is set to 'float'
--   float_opts = {
--     -- The border key is *almost* the same as 'nvim_open_win'
--     -- see :h nvim_open_win for details on borders however
--     -- the 'curved' border is a custom border type
--     -- not natively supported but implemented in this plugin.
--     border = 'single' | 'double' | 'shadow' | 'curved' | ... other options supported by win open
--     -- like `size`, width and height can be a number or function which is passed the current terminal
--     width = <value>,
--     height = <value>,
--     winblend = 3,
--   },
--   winbar = {
--     enabled = false,
--     name_formatter = function(term) --  term: Terminal
--       return term.name
--     end
--   },
-- }


text:
package pub.devrel.bundler;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation for a class that triggers the generation of an associated {@code Bundler} class.
 */
@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface BundlerClass {}


text:
<!--
Copyright 2016 Goldman Sachs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<MithraObject objectType="transactional">

    <PackageName>com.gs.fw.common.mithra.test.domain</PackageName>
    <ClassName>JudeNutaxejayoFelucayehUlahEtoqag</ClassName>
    <DefaultTable>NAP_TAKALU_KUTOS</DefaultTable>

    <Attribute name="savumIn" javaType="int" primaryKey="true" columnName="KUTOS_LA" nullable="false"/>
</MithraObject>


text:
(function() {

  var hideShow = function () {
    var inputs = document.querySelectorAll('.hide-show');

    for(var i=0; i < inputs.length; i++) {
      if (inputs[i].checked) {
        if(inputs[i].value === 'No-dob') {
          document.querySelector('#dob-reveal').className = 'panel-indent js-hidden';
          document.querySelector('#approx-age').className = 'panel-indent';
        }
        else if (inputs[i].value === 'Yes-dob') {
          document.querySelector('#approx-age').className = 'panel-indent js-hidden';
          document.querySelector('#dob-reveal').className = 'panel-indent';
        }
        else if (inputs[i].value === 'Yes') {
          inputs[i].parentElement.parentElement.nextElementSibling.className = 'panel-indent';
        }
        else {
          inputs[i].parentElement.parentElement.nextElementSibling.className = 'panel-indent js-hidden';
        }
      }
    }
  };

  var atLeastOneChecked = function (inputs) {
    var fraudTypes        = inputs,
        atleastOneChecked = false;
    for (var i=0; i <= fraudTypes.length; i++) {
      if(fraudTypes[i] && fraudTypes[i].checked) {
        atleastOneChecked = true;
      }
    }
    return atleastOneChecked;
  }

  var atLeastOneFieldEntered =  function (inputs) {
    var atLeastOneFieldEntered = false;
    for (i = 0; i < inputs.length; i++) {
      if (inputs[i].value) {
        atLeastOneFieldEntered = true;
      }
    }
    return atLeastOneFieldEntered;
  }

  var fraudTypeValidation = function () {
    var form           = document.querySelector('#form-fraud-type'),
        fieldset       = document.querySelector('.fieldset-fraud-type'),
        msgBox         = document.createElement('div'),
        msgText        = document.createTextNode('Please select at least one type of fraud.'),
        inputs         = document.querySelectorAll('.input-fraud-type'),
        continueButton = document.querySelector('.button');

    form.addEventListener('submit', function (e) {
      if(atLeastOneChecked(inputs) === false) {
        fieldset.className += ' invalid';
        msgBox.className += ' validation-message';
        msgBox.appendChild(msgText);
        form.insertBefore(msgBox,continueButton.previousSibling);
        e.preventDefault();
      }
    });
  };

  var errorMsg = function (action,input,msgText) {
    var msgBox         = document.createElement('div'),
        msgText        = document.createTextNode(msgText),
        form           = document.querySelector('.form'),
        continueButton = document.querySelector('.button');

    if (action === 'add') {
      input.className += ' invalid';

      input.parentNode.className += ' invalid';
      msgBox.className += ' validation-message';
      msgBox.appendChild(msgText);
      form.insertBefore(msgBox,continueButton.previousSibling);
    }
    else {
      input.className.replace('invalid','');
      input.parentNode.className.replace('invalid','');
      document.querySelector('#form-nino').removeChild(document.querySelector('.validation-message'));
    }
  }

  var basicInfoValidation = function () {
    var form           = document.querySelector('#form-suspect-info'),
        firstName      = document.querySelector('#first-name-2'),
        lastName       = document.querySelector('#last-name-2'),
        age            = document.getElementsByName('radio-indent-group-1'),
        button         = document.querySelector('#button-step3a'),
        continueButton = document.querySelector('.button');

      form.addEventListener('submit', function (e) {
        var validationMessages = document.querySelectorAll('.validation-message'),
            sendForm           = true;

      for (i=0;i  < validationMessages.length; i++) {
        validationMessages[i].parentNode.removeChild(validationMessages[i])
      }

      if(firstName.value === '') {
        errorMsg('add',firstName,'Please enter a first name(s)');
        sendForm = false;
      }
      if (lastName.value === '') {
        errorMsg('add',lastName ,'Please enter a last name');
        sendForm = false;
      }
      if(atLeastOneChecked(age) === false) {
        var form     = document.querySelector('#form-suspect-info'),
            fieldset = document.querySelector('.fieldset-dob'),
            msgBox   = document.createElement('div'),
            msgText  = document.createTextNode('Please enter a date of birth or an approximate age.');

        fieldset.className += ' invalid';
        msgBox.className += ' validation-message';
        msgBox.appendChild(msgText);
        form.insertBefore(msgBox,continueButton.previousSibling);

        sendForm = false;
        //errorMsg('add',lastName ,'Please enter a last name');
      }

      if(document.querySelector('#radio-indent-dob-1').checked) {
        var form    = document.querySelector('#form-suspect-info'),
            day     = document.querySelector('#dob-day'),
            month   = document.querySelector('#dob-month'),
            year    = document.querySelector('#dob-year'),
            dobFull = true,
            msgBox  = document.createElement('div'),
            msgText = document.createTextNode('Please enter a full date of birth.');

        if(day.value === '') {
          day.className += ' invalid'
          dobFull = false;
        }
        if(month.value === ''){
          month.className += ' invalid'
          dobFull = false;
        }
        if(year.value === ''){
          year.className += ' invalid'
          dobFull = false;
        }

        if (dobFull === false) {
          sendForm = false;
          day.parentNode.parentNode.parentNode.className += ' invalid'
          msgBox.className += ' validation-message';
          msgBox.appendChild(msgText);
          form.insertBefore(msgBox,continueButton.previousSibling);
        }
      }

      if(document.querySelector('#radio-indent-dob-2').checked) {
        var form      = document.querySelector('#form-suspect-info'),
            approxAge = document.querySelector('#dob-approx'),
            msgBox    = document.createElement('div'),
            msgText   = document.createTextNode('Please enter an approximate age.');

        if(approxAge.value === '') {
          approxAge.className += ' invalid';
          approxAge.parentNode.parentNode.className += ' invalid';
          msgBox.className += ' validation-message';
          msgBox.appendChild(msgText);
          form.insertBefore(msgBox,continueButton.previousSibling)
        }
      }

      if(document.querySelector('#radio-indent-address-yes').checked) {
        var postcode  = document.querySelector('#postcode'),
            address   = document.querySelector('#address'),
            town      = document.querySelector('#town'),
            msgBox    = document.createElement('div'),
            addressOk = false;

        if (postcode.value) {
          addressOk = true;
        }

        if (address.value && town.value) {
          addressOk = true;
        }

        if(addressOk !== true) {
          var msgText = document.createTextNode('Please enter either a building and street name and town or just a postcode.');
          sendForm = false;
          if (address.value === '') {
            address.className += ' invalid';
          }
          if (town.value === '') {
            town.className += ' invalid';
          }
          if (postcode.value === '') {
            postcode.className += ' invalid';
          }
          if (address.value === '' && town.value) {
            var msgText = document.createTextNode('Please enter either a building and street name or postcode.');
          }
          if (address.value && town.value === '') {
            var msgText = document.createTextNode('Please enter either a town or postcode.');
          }
          postcode.parentNode.parentNode.className += ' invalid';
          msgBox.className += ' validation-message';
          msgBox.appendChild(msgText);
          form.insertBefore(msgBox,continueButton.previousSibling)
        }
      }

      if (document.querySelector('#radio-indent-contact-yes').checked) {
        var inputs = document.querySelectorAll('.step3-contact');
        if (! atLeastOneFieldEntered(inputs)) {

          var msgText    = document.createTextNode('Please enter at least one contact detail.'),
              msgBox     = document.createElement('div'),
              homeNumber = document.querySelector('#home-number');

          homeNumber.parentNode.parentNode.className += ' invalid';
          msgBox.className += ' validation-message';
          msgBox.appendChild(msgText);
          form.insertBefore(msgBox,continueButton.previousSibling)
        }
      }

      if (sendForm === false) {
        e.preventDefault();
      }
    })
  };

  var isTherePartner = function () {
    var form           = document.querySelector('#form-additonal-suspect-details'),
        inputs         = document.querySelectorAll('.hasPartner'),
        msgBox         = document.createElement('div'),
        msgText        = document.createTextNode('Please select one of the options above.'),
        continueButton = document.querySelector('.button');

    form.addEventListener ('submit', function (e) {
      if (atLeastOneChecked(inputs) === false) {
        document.querySelector('.hasPartner').parentNode.parentNode.parentNode.className += ' invalid'
        msgBox.className += ' validation-message';
        msgBox.appendChild(msgText);
        form.insertBefore(msgBox,continueButton.previousSibling);
        e.preventDefault();
      }
    })
  };

  var partnerInfo = function () {
    var form           = document.querySelector('#form-partner-details'),
        firstName      = document.querySelector('#first-name-2'),
        lastName       = document.querySelector('#last-name-2'),
        additonalInfo  = document.querySelector('#additonalInfo'),
        msgBox         = document.createElement('div'),
        msgText        = document.createTextNode('Please provide any information you have on the parnter.'),
        continueButton = document.querySelector('.button');

    continueButton.addEventListener ('click', function (e) {
      var sendForm = true,
          secondAttempt = false;

      if(document.querySelector('.validation-message')) {
        secondAttempt = true;
      }

      if (firstName.value === '' && lastName.value === '' && additonalInfo.value === '') {
        errorMsg('add',firstName,'Please enter a first name(s) if you know it.');
        errorMsg('add',lastName ,'Please enter a last name if you know it.');
        errorMsg('add',additonalInfo,'Please enter any additional information if you can.');
        sendForm = false;
      }

      if (firstName.value !== '' || lastName.value !== '' || additonalInfo.value !== '') {
        sendForm = true;
      }

      if (sendForm === false && secondAttempt === false) {
        e.preventDefault();
      }

    })
  };

  var suspectWork = function () {
    var form           = document.querySelector('#form-suspect-work'),
        whereWorking   = document.querySelector('#where-working'),
        selfEmployed   = document.querySelector('#radio-indent-self-employed-yes'),
        workType       = document.querySelector('#work-type'),
        msgBox         = document.createElement('div'),
        msgText        = document.createTextNode('Please provide any information you have on the parnter.'),
        continueButton = document.querySelector('.button');

    continueButton.addEventListener ('click', function (e) {
      var sendForm = true;

      if (whereWorking.value === '') {
        errorMsg('add',whereWorking,'Please provide some information about where you believe they are working.');
        sendForm = false;
      }

      if (selfEmployed.checked && workType.value === '') {
        errorMsg('add',workType,'Please enter the type of work they do.');
        workType.parentNode.parentNode.parentNode.className += ' invalid';
        sendForm = false;
      }

      if (sendForm === false) {
        e.preventDefault();
      }
    });

  }

  var vehicleDetails = function () {
    var form           = document.querySelector('#form-vehicle-information'),
        vehicleType    = document.querySelector('#vehicle-type');
        form.addEventListener('submit', function (e) {
          if(vehicleType.value === '') {
            errorMsg('add',vehicleType,'Please enter the type of transport.');
            e.preventDefault();
          }
        })
  }

  var businessRules = function () {
    var form             = document.querySelector('#form-suspect-info');

    form.addEventListener('submit', function (e) {
      var firstname        = document.querySelector('#first-name-2'),
          lastname         = document.querySelector('#last-name-2'),
          othernameChecked = document.querySelector('#radio-indent-other-yes').checked,
          otherFirstname   = document.querySelector('#first-name-2a'),
          otherLastname    = document.querySelector('#last-name-2a'),
          ninoChecked      = document.querySelector('#radio-indent-nino-yes').checked,
          nino             = document.querySelector('#nino'),
          addressChecked   = document.querySelector('#radio-indent-address-yes').checked,
          contactsChecked  = document.querySelector('#radio-indent-contact-yes').checked,
          ageDob           = atLeastOneChecked(document.querySelectorAll('.dob-age')),
          submitForm       = true;

      function nameProvided () {
        var nameProvided = false;
        if (firstname.value !== '' || lastname.value !== '') {
          nameProvided = true;
        }

        if (othernameChecked && (otherFirstname.value !== '' || otherLastname.value !== '')) {
          nameProvided = true;
        }
        return nameProvided;
      }

      function ageOrDobProvided () {
        var ageProvided = false;
        if (atLeastOneChecked(document.querySelectorAll('.dob-age'))) {
          ageProvided = true;
        }
        return ageProvided;
      }

      function addressProvided () {
        var addressProvided = false;
        if (addressChecked) {
          addressProvided = true;
        }
        return addressProvided;
      }

      function ninoProvided () {
        var ninoProvided = false;
        if (ninoChecked) {
          ninoProvided = true;
        }
        return ninoProvided;
      }

      function contactDetailsProvided () {
        var contactDetailsProvided = false;
        if (contactsChecked) {
          contactDetailsProvided = true;
        }
        return contactDetailsProvided;
      }

      function addressOrContactProvided () {
        var addressOrContactProvided = false;
        if (addressProvided() || contactDetailsProvided()) {
          addressOrContactProvided = true;
        }
        return addressOrContactProvided;
      }

      console.log('name -----' + nameProvided())
      console.log('age -----' + ageOrDobProvided())
      console.log('address -----' + addressProvided())
      console.log('nino    -----' + ninoProvided())
      console.log('contact -----' + contactDetailsProvided())
      console.log('contact/address -----' + addressOrContactProvided())
      console.log('----------------------------------------------------')

      if ((ninoProvided() && nameProvided()) || (ninoProvided() && addressOrContactProvided())  ) {
        console.log('submit form nino and name or address')
        console.log('----------------------------------------------------')
      }

      if (ninoProvided() && ageOrDobProvided()) {
        console.log('submit form nino and age')
        console.log('----------------------------------------------------')
      }

      if ((nameProvided() && ageOrDobProvided()) && addressOrContactProvided()) {
        console.log('submit form name and/or dob')
        console.log('----------------------------------------------------')
      }

      e.preventDefault();
    })
  }

  bindEvents = function () {
    var inputs    = document.querySelectorAll('.hide-show');

    for (var i = 0; i < inputs.length; i++) {
      inputs[i].addEventListener("click", hideShow, true );
    };

    if(document.querySelector('#form-fraud-type')) {
      fraudTypeValidation();
    }

    if(document.querySelector('#form-suspect-info')) {
      //basicInfoValidation();
      businessRules();
    }

    if(document.querySelector('#form-additonal-suspect-details')) {
      isTherePartner();
    }

    if(document.querySelector('#button-step4b')) {
      partnerInfo();
    }
    if(document.querySelector('#button-step6')) {
      suspectWork();
    }

    if(document.querySelector('#form-vehicle-information')) {
      vehicleDetails();
    }

  };

  return {
    bindEvents : bindEvents()
  };

})();

/*
if (ninoChecked && nino.value === '') {
  console.log('enter nino')
}

if (ninoChecked && nino.value !== '') {
  if ((firstname.value === '' && lastname.value === '' && ageDob === false) && (addressChecked === false) && (contactsChecked === false) ) {
  console.log('nino entered but nothing else')
  }
}

if (firstname.value && (lastname.value === '' && ageDob === false && addressChecked === false && contactsChecked === false)) {
  console.log('first name but nothing else')
}

if (lastname.value && (firstname.value === '' && ageDob === false && addressChecked === false && contactsChecked === false)) {
  console.log('last name but nothing else')
}

if (ageDob === true && (firstname.value === '' && lastname.value === '') && (addressChecked === false && contactsChecked === false)) {
  console.log('age but nothing else')
}

*/


text:
CURL *hnd = curl_easy_init();

curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har");

struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "content-type: multipart/form-data; boundary=---011000010111000001101001");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);

curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--");

CURLcode ret = curl_easy_perform(hnd);


text:
/*
 * ScratchBot.cpp
 *
 * Created: 10/27/2014 4:36:24 PM
 *  Author: N
 */

#include <avr32/io.h>
#include "utils/MotorDriver.h"
#include "sensors/Button.h"
#include "sensors/ProximitySensor.h"
#include "sensors/IR.h"
#include "sensors/MotionSensor.h"
#include "sensors/SensorsArray.h"
#include "strategies/Strategy.h"
#include "strategies/RandomMovement.h"
#include "strategies/Sniper.h"

#include <chrono>       /* time_t, struct tm, difftime, time, mktime */
using namespace std;
using std::chrono::milliseconds;
int main(void)
{

    while(1) {
		int TICK = 10; //MS
        SensorsArray sensors = SensorsArray();
		MotorDriver motors = MotorDriver();
		//Refresh sensor data

		int mills = chrono::system_clock::now().time_since_epoch().count();
		//Every tick
		while(mills - sensors.getTick() >= TICK) {
			Sniper sniper = Sniper(sensors, motors);
			sensors.setTick(mills);
			//Go through strategies in most->least priority order

			sniper.tapIn();
		}
    }
	return 0;
}


text:
(function() {
 'use strict';

var dependencies, name_resolver, require, sources, _this = this;

name_resolver = function(parent, name) {
  if (dependencies[parent] == null) {
    throw Error("no dependencies list for parent |" + parent + "|");
  }
  if (dependencies[parent][name] == null) {
    throw Error("no one module resolved, name - |" + name + "|, parent - |" + parent + "|");
  }
  return dependencies[parent][name];
};
require = function(name, parent) {
  var exports, module, module_source, resolved_name, _ref;
  if (!(module_source = sources[name])) {
    resolved_name = name_resolver(parent, name);
    if (!(module_source = sources[resolved_name])) {
      throw Error("can`t find module source code: original_name - |" + name + "|, resolved_name - |" + resolved_name + "|");
    }
  }
  module_source.call(_this,exports = {}, module = {}, function(mod_name) {
    return require(mod_name, resolved_name != null ? resolved_name : name);
  });
  return (_ref = module.exports) != null ? _ref : exports;
};
    dependencies = {"2282979379":{"lodash":1154215551},"3137057011":{"../src/lib/regexp_dot_forger":2282979379,"lodash":1154215551}};
    sources = {
"1154215551": function(exports, module, require) {
// /Users/meettya/github/TinyData/web_modules/lodash.coffee
/*
This is lodash shim
*/

module.exports = this._;
},
"2282979379": function(exports, module, require) {
// /Users/meettya/github/TinyData/src/lib/regexp_dot_forger.coffee
/*
This is RegExp helper for TinyData

Its convert users RegExp with escaped dot \.
 or dot as a part of character set [.] - like this,
 by replace all of that to something else

Raison d'être - inside TinyData for entity devision used dot_replacer,
  but for the simplicity we are MAY (and I believe MUST) cloak this fact.
*/

/*
Logging method decorator
*/

var RegExpDotForger, logOnDemand, _,
  __slice = [].slice;

logOnDemand = function(methodBody) {
  return function() {
    var args, __rval__;
    args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    __rval__ = methodBody.apply(this, args);
    if (this._do_logging_) {
      console.log("" + args[0] + " -> " + __rval__);
    }
    return __rval__;
  };
};

_ = require('lodash');

RegExpDotForger = (function() {

  function RegExpDotForger(_dot_substitute_, _options_) {
    this._dot_substitute_ = _dot_substitute_;
    this._options_ = _options_ != null ? _options_ : {};
    if (!((this._dot_substitute_ != null) && _.isString(this._dot_substitute_))) {
      throw Error("constructor must be called with string as dot substitute, but got:\n|dot_substitute| = |" + this._dot_substitute_ + "|");
    }
    this._do_logging_ = (this._options_.log != null) && this._options_.log === true && ((typeof console !== "undefined" && console !== null ? console.log : void 0) != null) ? true : false;
  }

  /*
    This method return pattern RegExp by name or throw exception
    why it public? for tests
  */

  RegExpDotForger.prototype.getPatternByName = function(pattern_name) {
    switch (pattern_name.toUpperCase()) {
      case 'CHARACTER_SET':
        return /((?:^|(?:(?:^|[^\\])\\(?:\\{2})*\\)|[^\\]+))(\[(?:]|(?:[^\\]+])|(?:.*?[^\\]+])|(?:.*?[^\\]+\\(?:\\{2})*\\])))/;
      case 'ESCAPED_DOT':
        return /((?:^|[^\\])(?:\\{2})*)(\\\.)/;
      default:
        throw Error("so far don`t know pattern, named |" + pattern_name + "|, mistype?");
    }
  };

  /*
    This method forge dots in incoming regexp and return 'corrected' one
  */

  RegExpDotForger.prototype.doForgeDots = logOnDemand(function(in_regexp) {
    if (!((in_regexp != null) && _.isRegExp(in_regexp))) {
      throw Error("must be called with RegExp, but got:\n|in_regexp| = |" + in_regexp + "|");
    }
    return new RegExp(this._forgeEscapedDots(this._forgeCharacterSet(in_regexp.source)));
  });

  /*
    This method change dots to substitute in character sets
  */

  RegExpDotForger.prototype._forgeCharacterSet = function(in_regexp_as_string) {
    var dot_replacer, global_char_set_pattern,
      _this = this;
    global_char_set_pattern = new RegExp(this.getPatternByName('character_set').source, 'g');
    dot_replacer = function(match, captured_1, captured_2) {
      var forged_set;
      forged_set = captured_2.replace(/\./g, _this._dot_substitute_);
      return captured_1 + forged_set;
    };
    return in_regexp_as_string.replace(global_char_set_pattern, dot_replacer);
  };

  /*
    This method change escaped dots to substitute
  */

  RegExpDotForger.prototype._forgeEscapedDots = function(in_regexp_as_string) {
    var escaped_dot_replacer, global_escaped_dot_pattern,
      _this = this;
    global_escaped_dot_pattern = new RegExp(this.getPatternByName('escaped_dot').source, 'g');
    escaped_dot_replacer = function(match, captured_1, captured_2) {
      var forged_set;
      forged_set = captured_2.replace(/\\\./, _this._dot_substitute_);
      return captured_1 + forged_set;
    };
    return in_regexp_as_string.replace(global_escaped_dot_pattern, escaped_dot_replacer);
  };

  return RegExpDotForger;

})();

module.exports = RegExpDotForger;
},
"3137057011": function(exports, module, require) {
// /Users/meettya/github/TinyData/test/regexp_dot_forger-test.coffee
/*
Test suite for node AND browser in one file
*/

var RegExpDotForger, character_set_pattern, character_set_pattern_suite, dot_substitutor, escaped_dot_pattern, escaped_dot_pattern_suite, forger_obj, substitution_test_suite, _;

_ = require('lodash');

RegExpDotForger = require("../src/lib/regexp_dot_forger");

forger_obj = character_set_pattern = escaped_dot_pattern = null;

dot_substitutor = "\uFE45";

character_set_pattern_suite = {
  example_true: [/[]/, /[.]/, /[[.]/, /[.[]/, /[\]\.\[]/, /\\[\.]/, /\\\\[.\\\\]\\/, /[.\\]/, /dtt[.]/, /3434\\[\\.]\/\//, /^\.rtt([^.]+)\./, /^[^.]+\.comment\.([^.]+)\./],
  example_false: [/\[.]/, /\\\[.\.]/, /ddsds\[.]/]
};

escaped_dot_pattern_suite = {
  example_true: [/\./, /\\\./, /^\d+[.\]]ft\./, /\\\\\.\\\.\./],
  example_false: [/\\./, /sd\b\\\\./, /\(.\)/]
};

substitution_test_suite = {
  example_true: [[/\./, /\uFE45/], [/[.]/, /[\uFE45]/], [/[\.]/, /[\\uFE45]/], [/[...]/, /[\uFE45\uFE45\uFE45]/], [/^[^.]+\.comment\.([^.]+)\./, /^[^﹅]+﹅comment﹅([^﹅]+)﹅/]],
  example_false: [[/\\./, /\\./], [/\[.]/, /\[.]/]]
};

describe('RegExpDotForger:', function() {
  beforeEach(function() {
    return forger_obj = new RegExpDotForger(dot_substitutor);
  });
  describe('new()', function() {
    it('should return RegExpDotForger object on call with data', function() {
      forger_obj = new RegExpDotForger(dot_substitutor);
      return forger_obj.should.be.an["instanceof"](RegExpDotForger);
    });
    return it('should throw Error on void call', function() {
      return (function() {
        return new RegExpDotForger();
      }).should.to["throw"](/constructor must be called with/);
    });
  });
  describe('#getPatternByName()', function() {
    it('should return existance pattern', function() {
      character_set_pattern = forger_obj.getPatternByName('character_set');
      return character_set_pattern.should.to.be["instanceof"](RegExp);
    });
    return it('should throw Error on unknown name', function() {
      return (function() {
        return forger_obj.getPatternByName('foo_bar');
      }).should.to["throw"](/don`t know pattern/);
    });
  });
  describe('#doForgeDots()', function() {
    it('should change escaped dots (\\.) and dots in character set ([.]) to substitutor', function() {
      return _.each(substitution_test_suite.example_true, function(test_suite) {
        return forger_obj.doForgeDots(test_suite[0]).should.be.eql(test_suite[1]);
      });
    });
    return it('should NOT change dots itself as "one symbol" (.) to substitutor', function() {
      return _.each(substitution_test_suite.example_false, function(test_suite) {
        return forger_obj.doForgeDots(test_suite[0]).should.be.eql(test_suite[1]);
      });
    });
  });
  return describe('patterns ITSELF for searching in regexp patterns:', function() {
    describe('\'character set\' search pattern:', function() {
      beforeEach(function() {
        return character_set_pattern = forger_obj.getPatternByName('character_set');
      });
      it('should match righ things', function() {
        return _.each(character_set_pattern_suite.example_true, function(pattern) {
          return character_set_pattern.test(pattern.source).should.to.be["true"];
        });
      });
      return it('should NOT match wrong things', function() {
        return _.each(character_set_pattern_suite.example_false, function(pattern) {
          return character_set_pattern.test(pattern.source).should.to.be["false"];
        });
      });
    });
    return describe('\'escaped dot\' search pattern:', function() {
      beforeEach(function() {
        return escaped_dot_pattern = forger_obj.getPatternByName('escaped_dot');
      });
      it('should match righ things', function() {
        return _.each(escaped_dot_pattern_suite.example_true, function(pattern) {
          return escaped_dot_pattern.test(pattern.source).should.to.be["true"];
        });
      });
      return it('should NOT match wrong things', function() {
        return _.each(escaped_dot_pattern_suite.example_false, function(pattern) {
          return escaped_dot_pattern.test(pattern.source).should.to.be["false"];
        });
      });
    });
  });
});
}};

/* bundle export */
this.tinydata_package = {
"TinyData": require(3137057011)};
}).call(this);


text:
<?php

final class PhabricatorProjectBoardManageController
  extends PhabricatorProjectBoardController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();
    $board_id = $request->getURIData('projectID');

    $board = id(new PhabricatorProjectQuery())
      ->setViewer($viewer)
      ->withIDs(array($board_id))
      ->needImages(true)
      ->executeOne();
    if (!$board) {
      return new Aphront404Response();
    }
    $this->setProject($board);

    // Perform layout of no tasks to load and populate the columns in the
    // correct order.
    $layout_engine = id(new PhabricatorBoardLayoutEngine())
      ->setViewer($viewer)
      ->setBoardPHIDs(array($board->getPHID()))
      ->setObjectPHIDs(array())
      ->setFetchAllBoards(true)
      ->executeLayout();

    $columns = $layout_engine->getColumns($board->getPHID());

    $board_id = $board->getID();

    $header = $this->buildHeaderView($board);
    $actions = $this->buildActionView($board);
    $properties = $this->buildPropertyView($board);

    $properties->setActionList($actions);

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->addTextCrumb(pht('Workboard'), "/project/board/{$board_id}/");
    $crumbs->addTextCrumb(pht('Manage'));

    $box = id(new PHUIObjectBoxView())
      ->setHeader($header)
      ->addPropertyList($properties);

    $nav = $this->getProfileMenu();

    $title = array(
      pht('Manage Workboard'),
      $board->getDisplayName(),
    );

    $columns_list = $this->buildColumnsList($board, $columns);

    return $this->newPage()
      ->setTitle($title)
      ->setNavigation($nav)
      ->setCrumbs($crumbs)
      ->appendChild(
        array(
          $box,
          $columns_list,
        ));
  }

  private function buildHeaderView(PhabricatorProject $board) {
    $viewer = $this->getRequest()->getUser();

    $header = id(new PHUIHeaderView())
      ->setUser($viewer)
      ->setHeader(pht('Workboard: %s', $board->getDisplayName()));

    return $header;
  }

  private function buildActionView(PhabricatorProject $board) {
    $viewer = $this->getRequest()->getUser();
    $id = $board->getID();

    $actions = id(new PhabricatorActionListView())
      ->setUser($viewer);

    $can_edit = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      $board,
      PhabricatorPolicyCapability::CAN_EDIT);

    $reorder_uri = $this->getApplicationURI("board/{$id}/reorder/");

    $actions->addAction(
      id(new PhabricatorActionView())
        ->setIcon('fa-exchange')
        ->setName(pht('Reorder Columns'))
        ->setHref($reorder_uri)
        ->setDisabled(!$can_edit)
        ->setWorkflow(true));

    $background_uri = $this->getApplicationURI("board/{$id}/background/");

    $actions->addAction(
      id(new PhabricatorActionView())
        ->setIcon('fa-paint-brush')
        ->setName(pht('Change Background Color'))
        ->setHref($background_uri)
        ->setDisabled(!$can_edit)
        ->setWorkflow(!$can_edit));

    $disable_uri = $this->getApplicationURI("board/{$id}/disable/");

    $actions->addAction(
      id(new PhabricatorActionView())
        ->setIcon('fa-ban')
        ->setName(pht('Disable Board'))
        ->setHref($disable_uri)
        ->setDisabled(!$can_edit)
        ->setWorkflow(true));

    return $actions;
  }

  private function buildPropertyView(
    PhabricatorProject $board) {
    $viewer = $this->getRequest()->getUser();

    $properties = id(new PHUIPropertyListView())
      ->setUser($viewer)
      ->setObject($board);

    $background = $board->getDisplayWorkboardBackgroundColor();
    if ($background !== null) {
      $map = PhabricatorProjectWorkboardBackgroundColor::getOptions();
      $map = ipull($map, 'name');

      $name = idx($map, $background, $background);
      $properties->addProperty(pht('Background Color'), $name);
    }

    return $properties;
  }

  private function buildColumnsList(
    PhabricatorProject $board,
    array $columns) {
    assert_instances_of($columns, 'PhabricatorProjectColumn');

    $board_id = $board->getID();

    $view = id(new PHUIObjectItemListView())
      ->setNoDataString(pht('This board has no columns.'));

    foreach ($columns as $column) {
      $column_id = $column->getID();

      $proxy = $column->getProxy();
      if ($proxy && !$proxy->isMilestone()) {
        continue;
      }

      $detail_uri = "/project/board/{$board_id}/column/{$column_id}/";

      $item = id(new PHUIObjectItemView())
        ->setHeader($column->getDisplayName())
        ->setHref($detail_uri);

      if ($column->isHidden()) {
        $item->setDisabled(true);
      }

      $view->addItem($item);
    }

    return id(new PHUIObjectBoxView())
      ->setHeaderText(pht('Columns'))
      ->setObjectList($view);
  }

}


text:
/* Meta.js
KC3改 Meta Data

Provides access to data on built-in JSON files
*/
(function(){
	"use strict";

	window.KC3Meta = {
		_cache:{},
		_icons:{},
		_exp:{},
		_gauges:{},
		_ship:{},
		_defeq:{},
		_slotitem:{},
		_quests:{},
		_ranks:{},
		_stype:{},
		_servers:{},
		_battle:{},
		_terms:{
			troll:{},
			lang:{},
		},
		_edges:{},
		_defaultIcon:"",

		/* Initialization
		-------------------------------------------------------*/
		init :function( repo ){
			/* to remove deprecated warning
				http://stackoverflow.com/questions/22090764/alternative-to-async-false-ajax
			*/
			// Load Common Meta
			this._icons		= JSON.parse( $.ajax(repo+'icons.json', { async: false }).responseText );
			this._exp		= JSON.parse( $.ajax(repo+'experience.json', { async: false }).responseText );
			this._gauges	= JSON.parse( $.ajax(repo+'gauges.json', { async: false }).responseText );
			this._defeq		= JSON.parse( $.ajax(repo+'defeq.json', { async: false }).responseText );
			this._edges		= JSON.parse( $.ajax(repo+'edges.json', { async: false }).responseText );

			// Load Translations
			this._ship 		= KC3Translation.getJSON(repo, 'ships', true);
			this._slotitem	= KC3Translation.getJSON(repo, 'items', true);
			this._quests	= KC3Translation.getJSON(repo, 'quests', true);
			this._ranks		= KC3Translation.getJSON(repo, 'ranks', true);
			this._stype		= KC3Translation.getJSON(repo, 'stype', true);
			this._servers	= KC3Translation.getJSON(repo, 'servers', true);
			this._battle	= KC3Translation.getJSON(repo, 'battle', true);
			// troll language always loaded
			this._terms.troll		= JSON.parse( $.ajax(repo+'lang/data/troll/terms.json', { async: false }).responseText );
			// other language loaded here
			this._terms.lang		= KC3Translation.getJSON(repo, 'terms');
		},

		/* Data Access
		-------------------------------------------------------*/
		defaultIcon :function(iconSrc){
			this._defaultIcon = iconSrc;
		},

		shipIcon :function(id, empty){
			if(typeof this._icons[id] !== "undefined"){
				return "http://i708.photobucket.com/albums/ww87/dragonjet25/KC3%20Ship%20Icons/"+this._icons[id];
			}
			if(typeof empty == "undefined"){
				return this._defaultIcon;
			}
			return empty;
		},

		abyssIcon :function(id, empty){
			if(typeof this._icons[id] !== "undefined"){
				return "http://i708.photobucket.com/albums/ww87/dragonjet25/KC3%20Abyss%20Icons/"+this._icons[id];
			}
			if(typeof empty == "undefined"){
				return this._defaultIcon;
			}
			return empty;
		},

		formationIcon :function(formationId){
			return "../../../../assets/img/formation2/" + formationId + ".png";
		},

		formationText :function(formationId){
			return [
				"",
				"Line Ahead",
				"Double Line",
				"Diamond",
				"Echelon",
				"Line Abreast",
				"","","","","",
				"Cruising Formation 1 (anti-sub)",
				"Cruising Formation 2 (forward)",
				"Cruising Formation 1 (anti-sub)",
				"Cruising Formation 1 (anti-sub)",
				"","","","","","",
				"Cruising Formation 1 (anti-sub)",
				"Cruising Formation 2 (forward)",
				"Cruising Formation 1 (anti-sub)",
				"Cruising Formation 1 (anti-sub)"
			][formationId];
		},

		shipName :function( jp_name ){
			if(typeof this._cache[jp_name] !== "undefined"){ return this._cache[jp_name]; }
			if(typeof this._ship[jp_name] !== "undefined"){
				this._cache[jp_name] = this._ship[jp_name];
				return this._cache[jp_name];
			}
			var
				bare = jp_name,
				combin = [],
				repTab = {
					"甲"   : '_A',
					"改二" : '_KaiNi',
					"改"   : '_Kai',
				},
				repRes = null,
				replaced = false;
			// in here, the regular expression will read which one comes first (which mean, to be in the end of the name
			// and then, the bare string will be chopped by how long the pattern match...
			// the matched one, added to the combination stack (FILO)
			// removing from the replacement table in order to prevent infinite loop ^^;
			// if there's no match, it'll instantly stop and return the actual value
			while( !!(repRes = (new RegExp(".+("+(Object.keys(repTab).join("|"))+")$",'gi')).exec(bare)) ){
				bare = bare.substr(0, bare.length-repRes[1].length);
				combin.unshift(this._ship[repTab[repRes[1]]]);
				delete repTab[repRes[1]];
				replaced = true;
			}
			console.log("Remaining",bare,"with combination",combin.join(" "));
			if(replaced) {
				combin.unshift("");
				if(typeof this._ship[bare] !== "undefined"){
					this._cache[jp_name] = this._ship[bare] + (combin.length > 0 ? combin.join(" ") : "");
				}
				return this._cache[jp_name];
			}
			return jp_name;
		},

		gearName :function( jp_name ){
			if(typeof this._slotitem[ jp_name ] !== "undefined"){
				return this._slotitem[ jp_name ];
			}
			return jp_name;
		},

		exp :function(level){
			return this._exp[level] || [0,0];
		},

		quest :function(id){
			return this._quests[id] || false;
		},

		rank :function(id){
			return this._ranks[id] || "Unknown Rank";
		},

		stype :function(id){
			return this._stype[id] || "??";
		},

		server :function(ip){
			return this._servers[ip] || {name:"Unknown Server", num:0, ip:ip };
		},

		serverByNum :function(num){
			var ctr;
			for(ctr in this._servers){
				if(this._servers[ctr].num==num){
					return this._servers[ctr];
				}
			}
			return {name:"Unknown Server", num:num, ip:"0.0.0.0" };
		},

		gauge :function(map_id){
			return this._gauges["m"+map_id] || false;
		},

		defaultEquip :function(id){
			if (typeof this._defeq["s" + id] == "undefined") {
				console.log("No ship has master id " + id + " in defeq.json");
			}
			return this._defeq["s" + id] || 0;
		},

		detection :function(index){
			return this._battle.detection[index] || ["",""];
		},

		airbattle :function(index){
			return this._battle.airbattle[index] || ["",""];
		},

		engagement :function(index){
			return this._battle.engagement[index] || ["",""];
		},

		term: function(key) {
			return (ConfigManager.info_troll && this._terms.troll[key]) || this._terms.lang[key] || key;
		},

		nodeLetter : function(worldId, mapId, edgeId) {
			var map = this._edges["World " + worldId + "-" + mapId];
			if (typeof map !== "undefined") {
				var edge = map[edgeId];
				if (typeof edge !== "undefined") {
					return edge[1];	// return destination
				}
			}
			return edgeId;
		}
	};

})();


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"encoding/json"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/validate"
)

// ErrorType Error Types
// swagger:model ErrorType
type ErrorType string

const (
	ErrorTypeUnknownError           ErrorType = "UnknownError"
	ErrorTypeInvalidDomain          ErrorType = "InvalidDomain"
	ErrorTypeUnkownVersion          ErrorType = "UnkownVersion"
	ErrorTypeInvalidRecord          ErrorType = "InvalidRecord"
	ErrorTypeInvalidRequest         ErrorType = "InvalidRequest"
	ErrorTypeInvalidResponse        ErrorType = "InvalidResponse"
	ErrorTypeInvalidProtobufMessage ErrorType = "InvalidProtobufMessage"
	ErrorTypeInvalidJSON            ErrorType = "InvalidJSON"
	ErrorTypeFailedToOpenEnvelope   ErrorType = "FailedToOpenEnvelope"
	ErrorTypeInvalidStateTransition ErrorType = "InvalidStateTransition"
	ErrorTypeUnauthorized           ErrorType = "Unauthorized"
	ErrorTypeResourceConflict       ErrorType = "ResourceConflict"
	ErrorTypeResourceExist          ErrorType = "ResourceExist"
	ErrorTypeResourceNotFound       ErrorType = "ResourceNotFound"
	ErrorTypeRouterError            ErrorType = "RouterError"
	ErrorTypeSoftLayerAPIError      ErrorType = "SoftLayerAPIError"
	ErrorTypeGUIDGeneration         ErrorType = "GUIDGeneration"
	ErrorTypeDeserialize            ErrorType = "Deserialize"
	ErrorTypeDeadlock               ErrorType = "Deadlock"
	ErrorTypeUnrecoverable          ErrorType = "Unrecoverable"
)

// for schema
var errorTypeEnum []interface{}

func init() {
	var res []ErrorType
	if err := json.Unmarshal([]byte(`["UnknownError","InvalidDomain","UnkownVersion","InvalidRecord","InvalidRequest","InvalidResponse","InvalidProtobufMessage","InvalidJSON","FailedToOpenEnvelope","InvalidStateTransition","Unauthorized","ResourceConflict","ResourceExist","ResourceNotFound","RouterError","SoftLayerAPIError","GUIDGeneration","Deserialize","Deadlock","Unrecoverable"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		errorTypeEnum = append(errorTypeEnum, v)
	}
}

func (m ErrorType) validateErrorTypeEnum(path, location string, value ErrorType) error {
	if err := validate.Enum(path, location, value, errorTypeEnum); err != nil {
		return err
	}
	return nil
}

// Validate validates this error type
func (m ErrorType) Validate(formats strfmt.Registry) error {
	var res []error

	// value enum
	if err := m.validateErrorTypeEnum("", "body", m); err != nil {
		return err
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
/*

smoothScroll - framework JS folosita pentru a realiza o scrolare automata usoara pentru link-urile interne

Obs: Daca pagina necesita request-uri AJAX pentru preluarea continutului, se va folosi functia smoothScroll(), ce va fi chemata in sectiunea "success" a request-ului.

Utilizare:
1. Includere JS

2. Exemplu cod HTML
View content

Content here

*/

function smoothScroll(){
    $('a[href*="#"]:not([href="#"])').click(function(){
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname){
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length){
                var scrollAmount = target.offset().top + 3;
                $('html, body').animate({
                    scrollTop: scrollAmount
                }, 1000);
             return false;
            }
        }
    });
}
$(document).ready(function(){
   smoothScroll();
})


text:
title: Whoops!
layout: default
permalink: /404.html
---

Looks like you've wandered into a bad link. Sorry about that! If the
link has a `/blog` in it you might want to remove that and try again.
Otherwise, try the search bar to the left, or take a trip [to the home
page](http://cwinters.com/) and see if anything there helps out.


text:
// Copyright © 2015 ~ 2017 Sunsoft Studio, All rights reserved.
// Umizoo is a framework can help you develop DDD and CQRS style applications.
//
// Created by young.han with Visual Studio 2017 on 2017-08-08.

using System.Runtime.Serialization;
using Umizoo.Configurations;

namespace Umizoo.Messaging
{
    [DataContract]
    public abstract class HandleResult
    {
        /// <summary>
        ///     Default constructor.
        /// </summary>
        public HandleResult()
            : this(HandleStatus.Success)
        {
        }

        /// <summary>
        ///     Parameterized Constructor.
        /// </summary>
        public HandleResult(HandleStatus status, string errorMessage = null)
        {
            Status = status;
            ErrorMessage = errorMessage;

            ReplyServer = string.Concat(ConfigurationSettings.InnerAddress,
                "@", ConfigurationSettings.ServiceName);
        }

        [DataMember]
        public string ReplyServer { get; set; }

        /// <summary>
        ///     失败的消息
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string ErrorMessage { get; set; }

        /// <summary>
        ///     返回处理状态。
        /// </summary>
        [DataMember]
        public HandleStatus Status { get; set; }
    }
}


text:
package info.json_graph_format.jgfapp.api;

import info.json_graph_format.jgfapp.api.model.Edge;
import info.json_graph_format.jgfapp.api.model.Evidence;
import info.json_graph_format.jgfapp.api.model.Graph;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyTable;

/**
 * {@link BELEvidenceMapper} handles {@link Evidence} conversions.
 */
public interface BELEvidenceMapper {

    /**
     * Maps an {@link Edge edge} to an array of {@link Evidence} objects.
     *
     * @param graph the {@link Graph}; cannot be {@code null}
     * @param edge the {@link Edge}; cannot be {@code null}
     * @return the {@link Evidence} array; will not be {@code null} but may be empty
     * @throws java.lang.NullPointerException if {@code graph} or {@code edge} is
     * {@code null}
     */
    public Evidence[] mapEdgeToEvidence(Graph graph, Edge edge);

    /**
     * Map an {@link Evidence} object to a {@link CyTable table}.
     *

     * The {@link Graph graph} should provide the cytoscape network information
     * (see {@link Graph#cyNetwork}). This can provide access to the network SUID.
     *

     * The {@link Edge edge} should provide the cytoscape edge information
     * (see {@link Edge#cyEdge}). This can provide access to the edge SUID.
     *
     * @param graph the {@link Graph} containg the evidence; cannot be {@code null}
     * and {@link Graph#cyNetwork} cannot be {@code null}
     * @param edge the {@link Edge} containing the evidence; cannot be {@code null}
     * and {@link Edge#cyEdge} cannot be {@code null}
     * @param evidence the {@link Evidence} to map; cannot be {@code null}
     * @param table the {@link CyTable} to map to; cannot be {@code null}
     * @throws NullPointerException when {@code graph}, {@code edge},
     * {@code evidence}, or {@code table} is {@code null}
     * @throws IllegalArgumentException when the {@code graph}'s
     * {@link Graph#cyNetwork} is {@code null} or the {@code edge}'s
     * {@link Edge#cyEdge} is {@code null}
     */
    public void mapToTable(Graph graph, Edge edge, Evidence evidence, CyTable table);

    /**
     * Maps an {@link Edge edge} of the {@link CyTable table} to an array of
     * {@link Evidence} objects.
     *
     * @param edge the {@link CyEdge}; cannot be {@code null}
     * @param table the {@link CyTable}; cannot be {@code null}
     * @return the {@link Evidence} array; will not be {@code null} but may be empty
     */
    public Evidence[] mapFromTable(CyEdge edge, CyTable table);
}