text:
var ajaxFuncs = {};

function setupLinks(ajaxCallbacks, listId)
{
	var list = $(listId);
	var links = list.children("li");

	list.disableSelection();
	list.sortable(
	{
		placeholder : 'ui-state-highlight',
		stop : stopCallback,
		containment : '#col',

		// If the page is scrolled down in FF, the dragged object is
		// offset from the pointer by that much. Hax to fix it
		start : function(event, ui)
		{
			if ($.browser.mozilla && ui.helper !== undefined)
			{
				ui.helper.css('position', 'absolute').css('margin-top',
						$(window).scrollTop());
			}
		},
		beforeStop : function(event, ui)
		{
			if ($.browser.mozilla && ui.offset !== undefined)
			{
				ui.helper.css('margin-top', 0);
			}
		}
	});

	links.mousedown(function( )
	{
		links.removeClass("highlight");
		$(this).addClass("highlight");
	});
	ajaxFuncs.movedCallback = ajaxCallbacks.movedCallback;
}

function stopCallback(event, ui)
{
	var url = ui.item;
	var uuid = url.children("input").val();
	var position = url.prevAll().length;

	if (ajaxFuncs.movedCallback)
	{
		ajaxFuncs.movedCallback(null, uuid, position);
	}
}


text:
package com.zuowei.utils.chat;

import android.text.TextUtils;

import com.avos.avoscloud.AVCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCreatedCallback;
import com.vivifram.second.hitalk.manager.chat.ClientManager;
import com.vivifram.second.hitalk.model.ConversationType;
import com.zuowei.dao.greendao.User;
import com.zuowei.utils.common.NLog;
import com.zuowei.utils.common.TagUtil;
import com.zuowei.utils.helper.HiTalkHelper;
import com.zuowei.utils.helper.UserBeanCacheHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 项目名称:Hitalk
 * 类描述:
 * 创建人:zuowei
 * 创建时间:16-10-25 下午7:35
 * 修改人:zuowei
 * 修改时间:16-10-25 下午7:35
 * 修改备注:
 */
public class ConversationUtils {
    public static void getConversationName(AVIMConversation conversation, final AVCallback<String> callback) {
        if(null != callback) {
            if(null == conversation) {
                callback.internalDone(null,new AVException(new Throwable("conversation can not be null!")));
            } else {
                if(conversation.isTransient()) {
                    NLog.i(TagUtil.makeTag(ConversationUtils.class),"conversation.isTransient");
                    callback.internalDone(conversation.getName(), null);
                } else if(2 == conversation.getMembers().size()) {
                    NLog.i(TagUtil.makeTag(ConversationUtils.class),"conversation.getMembers = 2");
                    String peerId = getConversationPeerId(conversation);
                    UserBeanCacheHelper.getInstance().getUserName(peerId, callback);
                } else if(!TextUtils.isEmpty(conversation.getName())) {
                    NLog.i(TagUtil.makeTag(ConversationUtils.class),"conversation.getName not null");
                    callback.internalDone(conversation.getName(), null);
                } else {
                    UserBeanCacheHelper.getInstance().getCachedUsers(conversation.getMembers(), new AVCallback<List<User>>() {
                        protected void internalDone0(List<User> users, AVException e) {
                            ArrayList nameList = new ArrayList();
                            if(null != users) {
                                Iterator<User> i$ = users.iterator();

                                while(i$.hasNext()) {
                                    User user = i$.next();
                                    nameList.add(user.getUserName());
                                }
                            }
                            callback.internalDone(TextUtils.join(",", nameList), e);
                        }
                    });
                }

            }
        }
    }

    public static void createGroupConversation(final List<String> memberIds, String name, final AVIMConversationCreatedCallback callback) {
        Map<String, Object> attrs = new HashMap<>();
        attrs.put(ConversationType.TYPE_KEY, ConversationType.Group.getValue());
        attrs.put("name", name);
        ClientManager.getInstance().getClient().createConversation(memberIds, "", attrs, false, true, callback);
    }

    public static void createSingleConversation(String memberId, AVIMConversationCreatedCallback callback) {
        Map<String, Object> attrs = new HashMap<>();
        attrs.put(ConversationType.TYPE_KEY, ConversationType.Single.getValue());
        ClientManager.getInstance().getClient().createConversation(Arrays.asList(memberId), "", attrs, false, true, callback);
    }

    public static void getConversationPeerIcon(AVIMConversation conversation, AVCallback<String> callback) {
        if(null != conversation && !conversation.isTransient() && !conversation.getMembers().isEmpty()) {
            String peerId = getConversationPeerId(conversation);
            if(1 == conversation.getMembers().size()) {
                peerId = conversation.getMembers().get(0);
            }
            UserBeanCacheHelper.getInstance().getUserAvatar(peerId, callback);
        } else {
            callback.internalDone(null, new AVException(new Throwable("cannot find icon!")));
        }

    }

    private static String getConversationPeerId(AVIMConversation conversation) {
        if(null != conversation && 2 == conversation.getMembers().size()) {
            String currentUserId = HiTalkHelper.getInstance().getCurrentUserId();
            String firstMemeberId = conversation.getMembers().get(0);
            return conversation.getMembers().get(firstMemeberId.equals(currentUserId)?1:0);
        } else {
            return "";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace JustOrderIt.Web.Infrastructure.Mapping.Profiles
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using AutoMapper;

    internal class StandardMappingsProfile : Profile
    {
        public StandardMappingsProfile(List<Type> types, IMapperConfigurationExpression mapperConfiguration)
        {
            this.LoadStandardMappings(types, mapperConfiguration);
        }

        private void LoadStandardMappings(IEnumerable<Type> types, IMapperConfigurationExpression mapperConfiguration)
        {
            var maps = from t in types
                       from i in t.GetInterfaces()
                       where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
                             !t.IsAbstract &&
                             !t.IsInterface
                       select new
                       {
                           Source = i.GetGenericArguments()[0],
                           Destination = t
                       };

            foreach (var map in maps)
            {
                mapperConfiguration.CreateMap(map.Source, map.Destination);
            }
        }
    }
}


text:
namespace verilog {

using verible::IdentifierObfuscator;

std::string RandomEqualLengthSymbolIdentifier(absl::string_view in) {
  verilog::VerilogLexer lexer("");  // Oracle to check identifier-ness.
  // In rare case we accidentally generate a keyword, try again.
  for (;;) {
    std::string candidate = verible::RandomEqualLengthIdentifier(in);
    lexer.Restart(candidate);
    if (lexer.DoNextToken().token_enum() == verilog_tokentype::SymbolIdentifier)
      return candidate;
  }
}

// TODO(fangism): single-char identifiers don't need to be obfuscated.
// or use a shuffle/permutation to guarantee collision-free reversibility.

static void ObfuscateVerilogCodeInternal(absl::string_view content,
                                         std::ostream* output,
                                         IdentifierObfuscator* subst) {
  VLOG(1) << __FUNCTION__;
  verilog::VerilogLexer lexer(content);
  while (true) {
    const verible::TokenInfo& token(lexer.DoNextToken());
    if (token.isEOF()) break;
    switch (token.token_enum()) {
      case verilog_tokentype::SymbolIdentifier:
      case verilog_tokentype::PP_Identifier:
        *output << (*subst)(token.text());
        break;
        // Preserve all $ID calls, including system task/function calls, and VPI
        // calls
      case verilog_tokentype::SystemTFIdentifier:
        *output << token.text();
        break;
        // The following identifier types start with a special character that
        // needs to be preserved.
      case verilog_tokentype::MacroIdentifier:
      case verilog_tokentype::MacroCallId:
        // TODO(fangism): verilog_tokentype::EscapedIdentifier
        *output << token.text()[0] << (*subst)(token.text().substr(1));
        break;
      // The following tokens are un-lexed, so they need to be lexed
      // recursively.
      case verilog_tokentype::MacroArg:
      case verilog_tokentype::PP_define_body:
        ObfuscateVerilogCodeInternal(token.text(), output, subst);
        break;
      default:
        // This also covers lexical error tokens.
        *output << token.text();
    }
  }
  VLOG(1) << "end of " << __FUNCTION__;
}

static absl::Status ObfuscationError(absl::string_view message,
                                     absl::string_view original,
                                     absl::string_view encoded) {
  return absl::InternalError(absl::StrCat(message, "\nORIGINAL:\n", original,
                                          "\nENCODED:\n", encoded,
                                          "\n*** Please file a bug. ***\n"));
}

static absl::Status ReversibilityError(absl::string_view original,
                                       absl::string_view encoded,
                                       absl::string_view decoded) {
  return absl::InternalError(absl::StrCat(
      "Internal error: decode(encode) != original\nORIGINAL:\n", original,
      "\nENCODED:\n", encoded, "\nDECODED:\n", decoded,
      // FIXME(fangism): use a diff library to highlight the differences
      "\n*** Please file a bug. ***\n"));
}

// Internal consistency check that decoding restores original text.
static absl::Status VerifyDecoding(absl::string_view original,
                                   absl::string_view encoded,
                                   const verible::Obfuscator& subst) {
  VLOG(1) << __FUNCTION__;
  // Skip if original transformation was already decoding.
  if (subst.is_decoding()) return absl::OkStatus();

  IdentifierObfuscator reverse_subst(RandomEqualLengthSymbolIdentifier);
  reverse_subst.set_decode_mode(true);

  // Copy over mappings.  Verify map reconstruction.
  const auto saved_map = subst.save();
  if (auto status = reverse_subst.load(saved_map); !status.ok()) {
    return status;
  }

  // Decode and compare.
  std::ostringstream decoded_output;
  ObfuscateVerilogCodeInternal(encoded, &decoded_output, &reverse_subst);
  if (original != decoded_output.str()) {
    return ReversibilityError(original, encoded, decoded_output.str());
  }
  return absl::OkStatus();
}

// Verify that obfuscated output is lexically equivalent to original.
static absl::Status VerifyEquivalence(absl::string_view original,
                                      absl::string_view encoded) {
  VLOG(1) << __FUNCTION__;
  std::ostringstream errstream;
  const auto diff_status =
      verilog::ObfuscationEquivalent(original, encoded, &errstream);
  switch (diff_status) {
    case verilog::DiffStatus::kEquivalent:
      break;
    case verilog::DiffStatus::kDifferent:
      return ObfuscationError(
          absl::StrCat("output is not equivalent: ", errstream.str()), original,
          encoded);
    case verilog::DiffStatus::kLeftError:
      return absl::InvalidArgumentError(
          absl::StrCat("Input contains lexical errors:\n", errstream.str()));
    case verilog::DiffStatus::kRightError:
      return ObfuscationError(
          absl::StrCat("output contains lexical errors: ", errstream.str()),
          original, encoded);
  }
  return absl::OkStatus();
}

absl::Status ObfuscateVerilogCode(absl::string_view content,
                                  std::ostream* output,
                                  IdentifierObfuscator* subst) {
  VLOG(1) << __FUNCTION__;
  std::ostringstream buffer;
  ObfuscateVerilogCodeInternal(content, &buffer, subst);

  // Always verify equivalence.
  if (auto status = VerifyEquivalence(content, buffer.str()); !status.ok()) {
    return status;
  }

  // Always verify decoding.
  if (auto status = VerifyDecoding(content, buffer.str(), *subst);
      !status.ok()) {
    return status;
  }

  *output << buffer.str();
  return absl::OkStatus();
}

}  // namespace verilog


text:
function createPin(pin) {
    var data = pin.getJSONData();
    var connection = new _haitoRequest(
        "create",
        "POST",
        data,
        function (response) {
            var parsed = JSON.parse(response);
            if (parsed.success) {
                pin.BSONId = parsed._id
            }
        }, function (response) {
            alert(response)
        }
    );
    console.log(connection + "connection");

    ajaxAPI(connection)
}

function syncPins() {
    currentPins = [];
    var connection = new _haitoRequest(
        "all",
        "GET",
        {},
        function (response) {
            parseFeed(JSON.parse(response))
        },
        function (response) {
            alert(response)
        }
    );
    ajaxAPI(connection)
}

function deletePin(pin) {
    console.log({_id: pin.BSONId});
    var connection = new _haitoRequest(
        "remove",
        "Post",
        {_id: pin.BSONId},
        function (response) {
            alert("Usuwanie zakończono pomyślnie")
        }, function (response) {
            alert(response)
        }
    );

    ajaxAPI(connection)
}

function update(data) {
    var connection = new _haitoRequest(
        "update",
        "POST",
        data,
        function (response) {

        }, function (response) {
            alert(response)
        }
    );

    ajaxAPI(connection)
}

function parseFeed(array) {
    for (var i = 0; i < array.length; i++) {
        var object = array[i];
        currentPins.push(new _memo(object.id, object.width, object.height, object.posLeft, object.posTop, object.content, object._id.$oid))
    }
}


text:
"""
bitcoin-python - Easy-to-use Bitcoin API client
"""

def connect_to_local(filename=None):
    """
    Connect to default bitcoin instance owned by this user, on this machine.

    Returns a :class:`~bitcoinrpc.connection.BitcoinConnection` object.

    Arguments:

        - `filename`: Path to a configuration file in a non-standard location (optional)
    """
    from bitcoinpy.bitcoinrpc.connection import BitcoinConnection
    from bitcoinpy.bitcoinrpc.config import read_default_config

    cfg = read_default_config(filename)
    if cfg is None:
        cfg = {}
    port = int(cfg.get('rpcport', '18332' if cfg.get('testnet') else '8332'))
    rpcuser = cfg.get('rpcuser', '')
    rpcpassword = cfg.get('rpcpassword', '')

    return BitcoinConnection(rpcuser, rpcpassword, 'localhost', port)

def connect_to_remote(user, password, host='localhost', port=8332,
                      use_https=False):
    """
    Connect to remote or alternative local bitcoin client instance.

    Returns a :class:`~bitcoinrpc.connection.BitcoinConnection` object.
    """
    from bitcoinpy.bitcoinrpc.connection import BitcoinConnection

    return BitcoinConnection(user, password, host, port, use_https)


text:
require 'active_resource'
module ActiveResource
  module Observing
    def self.prepended(klass)
      klass.prepend ActiveModel::Observing
    end

    def create(*)
      notify_observers(:before_create)
      if result = super
        notify_observers(:after_create)
      end
      result
    end

    def save(*)
      notify_observers(:before_save)
      if result = super
        notify_observers(:after_save)
      end
      result
    end

    def update(*)
      notify_observers(:before_update)
      if result = super
        notify_observers(:after_update)
      end
      result
    end

    def destroy(*)
      notify_observers(:before_destroy)
      if result = super
        notify_observers(:after_destroy)
      end
      result
    end
  end
end


text:
!INCLUDE ..\Makefiles\ms.common

APPNAME = VolInfo

LIBS = $(LIB_PATH)\Common.lib

OBJECTS = VolInfo.obj

!INCLUDE ..\Makefiles\ms.app


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ProductMonitor</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
	<string name="service_name">Amazon Product Monitor</string>
</resources>


text:
/*
 * src/samples/screen.css
 */

#root > section > header {
    position: absolute;
    float: left;
    width: 200px;
}

#root > section > header > nav > ul {
    list-style: none;
}

#root > section > article {
    position: relative;
    margin-left: 200px;
}

#root > section > article > section {
    padding-bottom: 1em;
}

/* office-ui-fabric: 2.0.1 */

.ms-Dialog.ms-Dialog--is-disabled {
    display: none;
}

.ms-TextField.ms-TextField--placeholder .ms-TextField-field {
    position: relative;
    background-color: transparent;
    z-index: 5; /* @ms-zIndex-middle */
}

.ms-TextField.ms-TextField--placeholder .ms-Label {
    z-index: 0; /* @ms-zIndex-back */
}

.ms-Toggle-description.is-required:after {
    content: ' *';
    color: #a80000; /* @ms-color-error */
}

.ms-Toggle-description.is-disabled {
    color: #a6a6a6; /* @ms-color-neutralTertiary */
}


text:
#ifndef _UDI_HID_KBD_CONF_H_
#define _UDI_HID_KBD_CONF_H_

/**
 * \ingroup udi_hid_keyboard_group
 * \defgroup udi_hid_keyboard_group_conf Default HID keyboard configuration
 * for a USB Device with a single interface HID
 *
 * @{
 */

//! Control endpoint size
#define  USB_DEVICE_EP_CTRL_SIZE    8

//! Endpoint number used by HID keyboard interface
#define  UDI_HID_KBD_EP_IN           (1 | USB_EP_DIR_IN)

//! Interface number
#define  UDI_HID_KBD_IFACE_NUMBER    0

/**
 * \name UDD Configuration
 */
//@{
//! 1 endpoint used by HID keyboard standard interface
#define  USB_DEVICE_MAX_EP             1
//@}

//@}

#include "udi_hid_kbd.h"

#endif // _UDI_HID_KBD_CONF_H_


text:
// 输出分割的结果

/*#include <cuda_runtime.h>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>*/

#include <cv.h>
#include <highgui.h>
#include <cxcore.h>

#include <cstring>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <utility>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <iostream>

#include <leveldb/db.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "caffe/caffe.hpp"
#include "caffe/util/io.hpp"

#include <string>
#include <fstream>

using namespace std;
using namespace cv;
using namespace caffe;
using std::vector;
#define LABEL_LEN 1
#define LABEL_SIZE 4
#define IMG_LENGTH 256

/*int readLeveldb(string &source, string &des)
{
	int counts_ = 0;
	leveldb::DB* db_temp;
	leveldb::Options options;
	options.create_if_missing = false;
	options.max_open_files = 100;
	LOG(INFO) << "Opening leveldb " << source;
	leveldb::Status status = leveldb::DB::Open(options, source, &db_temp);
	CHECK(status.ok()) << "Failed to open leveldb ";

	shared_ptr<leveldb::DB> db_;
	shared_ptr<leveldb::Iterator> iter_;
	db_.reset(db_temp);
	iter_.reset(db_->NewIterator(leveldb::ReadOptions()));
	iter_->SeekToFirst();
	for (iter_->SeekToFirst(); iter_->Valid(); iter_->Next()) counts_++;
	iter_->SeekToFirst();

	FILE * file = fopen(des.c_str(), "w");
	for(int i = 0; i < counts_; i ++)
	{
		Datum datum;
		datum.ParseFromString(iter_->value().ToString());
		string fileName = iter_->key().ToString();
		fprintf(file, "%s ", fileName.c_str());
		int len = LABEL_LEN * LABEL_LEN;
		for(int j = 0; j < len; j ++)
		{
			fprintf(file, "%d ", datum.label(j));
		}
		fprintf(file, "\n");
	}
	fclose(file);

	return counts_;

}*/

int CreateDir(const char *sPathName, int beg) {
	char DirName[256];
	strcpy(DirName, sPathName);
	int i, len = strlen(DirName);
	if (DirName[len - 1] != '/')
		strcat(DirName, "/");

	len = strlen(DirName);

	for (i = beg; i < len; i++) {
		if (DirName[i] == '/') {
			DirName[i] = 0;
			if (access(DirName, 0) != 0) {
				CHECK(mkdir(DirName, 0755) == 0)<< "Failed to create folder "<< sPathName;
			}
			DirName[i] = '/';
		}
	}

	return 0;
}

char buf[101000];
int main(int argc, char** argv)
{

	//cudaSetDevice(0);
	Caffe::set_phase(Caffe::TEST);
	//Caffe::SetDevice(3);
	//Caffe::set_mode(Caffe::CPU);

	if (argc == 8 && strcmp(argv[7], "CPU") == 0) {
		LOG(ERROR) << "Using CPU";
		Caffe::set_mode(Caffe::CPU);
	} else {
		LOG(ERROR) << "Using GPU";
		Caffe::set_mode(Caffe::GPU);
	}

	Caffe::set_mode(Caffe::CPU);
	NetParameter test_net_param;
	ReadProtoFromTextFile(argv[1], &test_net_param);
	Net<float> caffe_test_net(test_net_param);
	NetParameter trained_net_param;
	ReadProtoFromBinaryFile(argv[2], &trained_net_param);
	caffe_test_net.CopyTrainedLayersFrom(trained_net_param);

	vector<shared_ptr<Layer<float> > > layers = caffe_test_net.layers();
	//const DataLayer<float> *datalayer = dynamic_cast<const DataLayer<float>* >(layers[0].get());
	//CHECK(datalayer);

	string labelFile(argv[3]);
	int data_counts = 0;
	FILE * file = fopen(labelFile.c_str(), "r");
	while(fgets(buf,100000,file) > 0)
	{
		data_counts++;
	}
	fclose(file);

	vector<Blob<float>*> dummy_blob_input_vec;
	string rootfolder(argv[4]);
	rootfolder.append("/");
	CreateDir(rootfolder.c_str(), rootfolder.size() - 1);
	string folder;
	string fName;

	float output;
	int counts = 0;

	file = fopen(labelFile.c_str(), "r");

	Blob<float>* c1 = (*(caffe_test_net.bottom_vecs().rbegin()))[0];
    int c2 = c1->num();
	int batchCount = std::ceil(data_counts / (floor)(c2));//(test_net_param.layers(0).layer().batchsize()));//                (test_net_param.layers(0).layer().batchsize() ));

	string resulttxt = rootfolder + "locResult.txt";
	FILE * resultfile = fopen(resulttxt.c_str(), "w");

	for (int batch_id = 0; batch_id < batchCount; ++batch_id)
	{
		LOG(INFO)<< "processing batch :" << batch_id+1 << "/" << batchCount <<"...";

		const vector<Blob<float>*>& result = caffe_test_net.Forward(dummy_blob_input_vec);
		Blob<float>* bboxs = (*(caffe_test_net.bottom_vecs().rbegin()))[0];
		int bsize = bboxs->num();

		const Blob<float>* labels = (*(caffe_test_net.bottom_vecs().rbegin()))[1];
		for (int i = 0; i < bsize && counts < data_counts; i++, counts++)
		{
			char fname[1010];
			fscanf(file, "%s", fname);
			/*for(int w = 0; w < LABEL_SIZE; w ++)
				for(int h = 0; h < LABEL_SIZE; h ++)
				{
					int lbl;
					fscanf(file,"%d",&lbl);
				}*/
			fprintf(resultfile, "%s ", fname);
			int channels = bboxs->channels();
			int height   = bboxs->height();
			int width    = bboxs->width();
			for(int c = 0; c < channels; c ++)
			{
				for(int h = 0; h < height; h ++)
					for(int w = 0; w < width; w ++)
						{
							// output_mat[c * HEIGHT * WIDTH + (off_w + w) * HEIGHT + off_h + h ] = (float)(bboxs->data_at(i, c, h, w));
							fprintf(resultfile, "%f ", (float)(bboxs->data_at(i, c, h, w)) );
						}
				fprintf(resultfile, "\n");
			}
		}
	}

	fclose(resultfile);
	fclose(file);

	return 0;
}


text:
/*
 * 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.
 */
package com.addthis.hydra.data.filter.bundle;

import com.addthis.bundle.core.Bundle;
import com.addthis.bundle.util.AutoField;
import com.addthis.bundle.value.ValueFactory;
import com.addthis.bundle.value.ValueObject;
import com.addthis.codec.annotations.FieldConfig;
import com.addthis.hydra.data.filter.value.ValueFilter;
import com.addthis.hydra.data.filter.value.ValueFilterSet;

/**
 *
This {@link BundleFilter BundleFilter} assigns a value to a specific bundle field.
 *

 *
For similar functionality see: value filter {@link ValueFilterSet set}

 *
Example:

 *

 *    {value {to:"USERNAME", value:"Bobby Tables"}}
 *

 *
 * @user-reference
 */
public class BundleFilterValue implements BundleFilter {

    /**
     * The value to assign into a bundle field. This field is required.
     */
    @FieldConfig(codable = true, required = true)
    private String value;

    /**
     * The bundle field name for the new value. This field is required.
     */
    @FieldConfig(codable = true, required = true)
    private AutoField to;

    /**
     * Optional filter to apply on the input value.
     */
    @FieldConfig(codable = true)
    private ValueFilter filter;

    /**
     * If true then return false when the input value is null. Default is true.
     */
    @FieldConfig(codable = true)
    private boolean nullFail = true;

    @Override
    public boolean filter(Bundle bundle) {
        ValueObject val = ValueFactory.create(value);
        if (filter != null) {
            val = filter.filter(val, bundle);
        }
        if (nullFail && val == null) {
            return false;
        }
        to.setValue(bundle, val);
        return true;
    }

    public BundleFilterValue setValue(String value) {
        this.value = value;
        return this;
    }

    public BundleFilterValue setToField(AutoField field) {
        this.to = field;
        return this;
    }

    public BundleFilterValue setFilter(ValueFilter filter) {
        this.filter = filter;
        return this;
    }

    public BundleFilterValue setNullFail(boolean nullFail) {
        this.nullFail = nullFail;
        return this;
    }

}


text:
require 'spec_helper'

namespace :db do
  task :setup  do
    # noop
  end
end

describe 'MigrationTasks' do
  before do
    ROM.setup(:sql, ['postgres://localhost/rom'])
    ROM.finalize
  end

  let(:migrator) { ROM.env.repositories[:default].migrator }

  context 'db:reset' do
    it 'calls proper commands' do
      expect(migrator).to receive(:run).with(target: 0)
      expect(migrator).to receive(:run)

      expect {
        Rake::Task["db:reset"].invoke
      }.to output("<= db:reset executed\n").to_stdout
    end
  end

  context 'db:migrate' do
    context 'with VERSION' do
      it 'calls proper commands' do
        expect(migrator).to receive(:run).with(target: 1)

        expect {
          Rake::Task["db:migrate"].invoke(1)
        }.to output("<= db:migrate version=[1] executed\n").to_stdout
      end
    end

    context 'without VERSION' do
      it 'calls proper commands' do
        expect(migrator).to receive(:run)

        expect {
          Rake::Task["db:migrate"].execute
        }.to output("<= db:migrate executed\n").to_stdout
      end
    end
  end

  context 'db:clean' do
    it 'calls proper commands' do
      expect(migrator).to receive(:run).with(target: 0)

      expect {
        Rake::Task["db:clean"].invoke
      }.to output("<= db:clean executed\n").to_stdout
    end
  end

  context 'db:create_migration' do
    context 'without NAME' do
      it 'exit without creating any file' do
        expect(File).to_not receive(:write)

        expect {
          expect {
            Rake::Task["db:create_migration"].execute
          }.to output(/No NAME specified/).to_stdout
        }.to raise_error(SystemExit)
      end
    end

    context 'with NAME' do
      let(:dirname) { 'tmp/db/migrate' }
      let(:name) { 'foo_bar' }
      let(:version) { '001' }
      let(:filename) { "#{version}_#{name}.rb" }
      let(:path) { File.join(dirname, filename) }

      it 'calls proper commands with default VERSION' do
        expect(migrator).to receive(:create_file).with(name).and_return(path)

        expect {
          Rake::Task["db:create_migration"].execute(
            Rake::TaskArguments.new([:name], [name]))
        }.to output("<= migration file created #{path}\n").to_stdout
      end

      it 'calls proper commands with manualy set VERSION' do
        expect(migrator).to receive(:create_file).with(name, version).and_return(path)

        expect {
          Rake::Task["db:create_migration"].execute(
            Rake::TaskArguments.new([:name, :version], [name, version]))
        }.to output("<= migration file created #{path}\n").to_stdout
      end
    end
  end
end


text:
import os
import sys
import textwrap
import time
from contextlib import contextmanager

from prettytable import PrettyTable

from .. import constants
from ..compiler.spec_assembler import (get_expanded_libs_specs, get_specs_repo,
                                       get_same_container_repos, get_same_container_repos_from_spec)
from ..compiler.compose import get_volume_mounts, get_testing_compose_dict, container_code_path
from ..systems.docker.testing_image import test_image_exists, create_test_image, update_test_image, test_image_name, ImageCreationError
from ..systems.docker import get_docker_client
from ..systems.docker.compose import write_composefile, compose_up
from ..systems.docker.config import (get_authed_registries, registry_from_image,
                                     log_in_to_registry)
from ..systems import nfs
from ..systems.virtualbox import initialize_docker_vm
from ..log import log_to_client
from ..command_file import make_test_command_files, dusty_command_file_name
from ..source import Repo
from ..payload import daemon_command
from ..parallel import parallel_task_queue
from ..changeset import RepoChangeSet

@daemon_command
def test_info_for_app_or_lib(app_or_lib_name):
    expanded_specs = get_expanded_libs_specs()
    spec = expanded_specs.get_app_or_lib(app_or_lib_name)
    if not spec['test']['suites']:
        log_to_client('No test suite registered for {}'.format(app_or_lib_name))
        return

    table = PrettyTable(['Test Suite', 'Description', 'Default Args'])
    for suite_spec in spec['test']['suites']:
        table.add_row([suite_spec['name'],
                       '\n'.join(textwrap.wrap(suite_spec['description'], 80)),
                       suite_spec['default_args']])
    log_to_client(table.get_string(sortby='Test Suite'))

def _update_test_repos(app_or_lib_name):
    specs_repo = get_specs_repo()
    if not specs_repo.is_overridden:
        log_to_client('Updating managed copy of specs-repo before loading specs')
        specs_repo.update_local_repo()
    with parallel_task_queue() as queue:
        for repo in get_same_container_repos(app_or_lib_name):
            if not repo.is_overridden:
                repo.update_local_repo_async(queue)

def _get_suite_spec(app_or_lib_name, suite_name):
    spec = get_expanded_libs_specs().get_app_or_lib(app_or_lib_name)
    for suite_spec in spec['test']['suites']:
        if suite_spec['name'] == suite_name:
            return suite_spec
    raise RuntimeError('Suite {} not found for {}'.format(suite_name, app_or_lib_name))

@daemon_command
def ensure_valid_suite_name(app_or_lib_name, suite_name):
    _get_suite_spec(app_or_lib_name, suite_name)

@daemon_command
def ensure_vm_initialized():
    log_to_client('Making sure Dusty VM is initialized and running')
    initialize_docker_vm()

def log_in_to_required_registries(app_or_lib_name):
    spec = get_expanded_libs_specs().get_app_or_lib(app_or_lib_name)
    if not spec['test'].get('image') or not spec['test'].get('image_requires_login'):
        return
    registry = registry_from_image(spec['test']['image'])
    if registry not in get_authed_registries():
        log_in_to_registry(registry)

@daemon_command
def setup_for_test(app_or_lib_name, pull_repos=False, force_recreate=False):
    expanded_specs = get_expanded_libs_specs()
    log_to_client('Writing test command files to VM')
    make_test_command_files(app_or_lib_name, expanded_specs)
    if pull_repos:
        _update_test_repos(app_or_lib_name)
    spec = expanded_specs.get_app_or_lib(app_or_lib_name)
    log_to_client('Rigging up NFS mounts for repos under test')
    nfs.update_nfs_with_repos(get_same_container_repos_from_spec(spec))
    ensure_current_image(app_or_lib_name, force_recreate)

def ensure_current_image(app_or_lib_name, force_recreate):
    changeset = RepoChangeSet(constants.CHANGESET_TESTING_KEY, app_or_lib_name)
    if force_recreate or not test_image_exists(app_or_lib_name):
        create_test_image(app_or_lib_name)
        changeset.update()
    elif changeset.has_changed():
        update_test_image(app_or_lib_name)
        changeset.update()

def run_one_suite(app_or_lib_name, suite_name, test_arguments):
    exit_code = _run_tests_with_image(app_or_lib_name, suite_name, test_arguments)

    log_to_client('TESTS {} {}'.format(suite_name, 'FAILED' if exit_code != 0 else 'PASSED'))
    sys.exit(exit_code)

def run_all_suites(app_or_lib_name):
    spec = get_expanded_libs_specs().get_app_or_lib(app_or_lib_name)

    summary_table = PrettyTable(['Suite', 'Description', 'Result', 'Time (s)'])
    exit_code = 0

    for suite_spec in spec['test']['suites']:
        log_to_client('Running test {}'.format(suite_spec['name']))
        start_time = time.time()

        test_result = _run_tests_with_image(app_or_lib_name, suite_spec['name'], None)

        result_str = 'FAIL' if test_result else 'PASS'
        elapsed_time = "{0:.1f}".format(time.time() - start_time)
        summary_table.add_row([suite_spec['name'], suite_spec['description'], result_str, elapsed_time])
        exit_code |= test_result

    log_to_client(summary_table.get_string())
    log_to_client('TESTS {}'.format('FAILED' if exit_code != 0 else 'PASSED'))
    sys.exit(exit_code)

def _construct_test_command(app_or_lib_name, suite_name, test_arguments):
    suite_spec = _get_suite_spec(app_or_lib_name, suite_name)
    if not test_arguments:
        test_arguments = suite_spec['default_args'].split(' ')
    return 'sh {}/{} {}'.format(constants.CONTAINER_COMMAND_FILES_DIR, dusty_command_file_name(app_or_lib_name, test_name=suite_name), ' '.join(test_arguments))

def _test_composefile_path(service_name):
    return os.path.expanduser('~/.dusty-testing/test_{}.yml'.format(service_name))

def _compose_project_name(service_name, suite_name):
    # Suite names should be able to have underscores. docker-compose does not allow project name to have underscores
    return 'test{}{}'.format(service_name.lower(), suite_name.lower().replace('_', ''))

def _test_compose_container_name(compose_project_name, app_or_lib_name):
    return '{}_{}_1'.format(compose_project_name, app_or_lib_name)

def _services_compose_up(expanded_specs, app_or_lib_name, services, suite_name):
    previous_container_names = []
    for service_name in services:
        service_spec = expanded_specs['services'][service_name]
        compose_project_name = _compose_project_name(app_or_lib_name, suite_name)
        container_name = _test_compose_container_name(compose_project_name, service_name)
        kwargs = {'container_name': container_name}
        if previous_container_names:
            kwargs['net_container_identifier'] = previous_container_names[-1]
        service_compose_config = get_testing_compose_dict(service_name, service_spec.plain_dict(), **kwargs)

        composefile_path = _test_composefile_path(service_name)
        write_composefile(service_compose_config, composefile_path)

        compose_up(composefile_path, compose_project_name, quiet=True)
        previous_container_names.append(container_name)
    return previous_container_names

def _app_or_lib_compose_up(test_suite_compose_spec, app_or_lib_name, app_or_lib_volumes, test_command, previous_container_name, suite_name):
    image_name = test_image_name(app_or_lib_name)
    compose_project_name = _compose_project_name(app_or_lib_name, suite_name)
    container_name = _test_compose_container_name(compose_project_name, app_or_lib_name)
    kwargs = {'testing_image_identifier': image_name,
              'volumes': app_or_lib_volumes,
              'command': test_command,
              'container_name': container_name}

    if previous_container_name is not None:
        kwargs['net_container_identifier'] = previous_container_name
    composefile_path = _test_composefile_path(app_or_lib_name)
    compose_config = get_testing_compose_dict(app_or_lib_name, test_suite_compose_spec, **kwargs)
    write_composefile(compose_config, composefile_path)

    compose_up(composefile_path, compose_project_name, quiet=True)
    return container_name

def _cleanup_test_container(client, container_name):
    """
       It is possible that the past test run exited in a bad state.  This will clean it up
    """
    log_to_client('Killing testing container {}'.format(container_name))
    running_containers = client.containers(filters={'name': container_name})
    if running_containers != []:
        client.kill(container_name)

    containers = client.containers(all=True, filters={'name': container_name})
    if containers != []:
        client.remove_container(container_name, v=True)

def _cleanup_containers(app_or_lib_name, suite_name, services):
    compose_project_name = _compose_project_name(app_or_lib_name, suite_name)
    client = get_docker_client()
    for service_name in services:
        service_container_name = _test_compose_container_name(compose_project_name, service_name)
        _cleanup_test_container(client, service_container_name)

    app_container_name = _test_compose_container_name(compose_project_name, app_or_lib_name)
    _cleanup_test_container(client, app_container_name)

@contextmanager
def run_safe_tests(app_or_lib_name, suite_name, services):
    try:
        yield
    #Except needs to be here to catch KeyboardInterrupts
    except:
        raise
    finally:
        _cleanup_containers(app_or_lib_name, suite_name, services)

def _run_tests_with_image(app_or_lib_name, suite_name, test_arguments):
    client = get_docker_client()
    expanded_specs = get_expanded_libs_specs()
    suite_spec = _get_suite_spec(app_or_lib_name, suite_name)
    test_command = _construct_test_command(app_or_lib_name, suite_name, test_arguments)
    volumes = get_volume_mounts(app_or_lib_name, expanded_specs, test=True)

    with run_safe_tests(app_or_lib_name, suite_name, suite_spec['services']):
        previous_container_names = _services_compose_up(expanded_specs, app_or_lib_name, suite_spec['services'], suite_name)
        previous_container_name = previous_container_names[-1] if previous_container_names else None
        test_container_name = _app_or_lib_compose_up(suite_spec['compose'], app_or_lib_name,
                                                     volumes, test_command, previous_container_name, suite_name)

        for line in client.logs(test_container_name, stdout=True, stderr=True, stream=True):
            log_to_client(line.strip())
        exit_code = client.wait(test_container_name)

    return exit_code


text:
#ifndef MockWebAudioDevice_h
#define MockWebAudioDevice_h

#include "TestCommon.h"
#include "public/platform/WebAudioDevice.h"
#include "public/platform/WebNonCopyable.h"

namespace WebTestRunner {

class MockWebAudioDevice : public blink::WebAudioDevice, public blink::WebNonCopyable {
public:
    explicit MockWebAudioDevice(double sampleRate);
    virtual ~MockWebAudioDevice();

    virtual void start();
    virtual void stop();
    virtual double sampleRate();

private:
    double m_sampleRate;
};

} // namespace WebTestRunner

#endif // MockWebAudioDevice_h


text:
package apple.uikit;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.coreanimation.*;
import apple.coredata.*;
import apple.coreimage.*;
import apple.coretext.*;
import apple.corelocation.*;

/*<javadoc>*/
/*</javadoc>*/
@Adapter
public abstract class UIViewControllerTransitionCoordinatorContextAdapter
    extends Object
    implements UIViewControllerTransitionCoordinatorContext {

    @NotImplemented("isAnimated")
    public boolean isAnimated() { throw new UnsupportedOperationException(); }
    @NotImplemented("presentationStyle")
    public @Representing("UIModalPresentationStyle") long getPresentationStyle() { throw new UnsupportedOperationException(); }
    @NotImplemented("initiallyInteractive")
    public boolean isInitiallyInteractive() { throw new UnsupportedOperationException(); }
    @NotImplemented("isInteractive")
    public boolean isInteractive() { throw new UnsupportedOperationException(); }
    @NotImplemented("isCancelled")
    public boolean isCancelled() { throw new UnsupportedOperationException(); }
    @NotImplemented("transitionDuration")
    public double getTransitionDuration() { throw new UnsupportedOperationException(); }
    @NotImplemented("percentComplete")
    public @MachineSizedFloat double getPercentComplete() { throw new UnsupportedOperationException(); }
    @NotImplemented("completionVelocity")
    public @MachineSizedFloat double getCompletionVelocity() { throw new UnsupportedOperationException(); }
    @NotImplemented("completionCurve")
    public @Representing("UIViewAnimationCurve") long getCompletionCurve() { throw new UnsupportedOperationException(); }
    @NotImplemented("viewControllerForKey:")
    public UIViewController getViewController(String key) { throw new UnsupportedOperationException(); }
    /**
     * @since Available in iOS 8.0 and later.
     */
    @NotImplemented("viewForKey:")
    public UIView getView(String key) { throw new UnsupportedOperationException(); }
    @NotImplemented("containerView")
    public UIView getContainerView() { throw new UnsupportedOperationException(); }
    /**
     * @since Available in iOS 8.0 and later.
     */
    @NotImplemented("targetTransform")
    public CGAffineTransform getTargetTransform() { throw new UnsupportedOperationException(); }

}


text:
Common UVA Library styles

_[Demo](https://uvalib-components.github.io/uvalib-theme/components/uvalib-theme/demo/)_

## Install the Polymer-CLI

First, make sure you have the [Polymer CLI](https://www.npmjs.com/package/polymer-cli) installed. Then run `polymer serve` to serve your application locally.

## Viewing Your Application

```
$ polymer serve
```

## Building Your Application

```
$ polymer build
```

This will create a `build/` folder with `bundled/` and `unbundled/` sub-folders
containing a bundled (Vulcanized) and unbundled builds, both run through HTML,
CSS, and JS optimizers.

You can serve the built versions by giving `polymer serve` a folder to serve
from:

```
$ polymer serve build/bundled
```

## Running Tests

```
$ polymer test
```

Your application is already set up to be tested via [web-component-tester](https://github.com/Polymer/web-component-tester). Run `polymer test` to run your application's test suite locally.


text:
using JetBrains.Annotations;
using WireMock.Settings;

namespace WireMock.ResponseBuilders
{
    /// <summary>
    /// The ProxyResponseBuilder interface.
    /// </summary>
    public interface IProxyResponseBuilder : IStatusCodeResponseBuilder
    {
        /// <summary>
        /// WithProxy URL using Client X509Certificate2.
        /// </summary>
        /// <param name="proxyUrl">The proxy url.</param>
        /// <param name="clientX509Certificate2ThumbprintOrSubjectName">The X509Certificate2 file to use for client authentication.</param>
        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
        IResponseBuilder WithProxy([NotNull] string proxyUrl, [CanBeNull] string clientX509Certificate2ThumbprintOrSubjectName = null);

        /// <summary>
        /// WithProxy using IProxyAndRecordSettings.
        /// </summary>
        /// <param name="settings">The IProxyAndRecordSettings.</param>
        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
        IResponseBuilder WithProxy([NotNull] IProxyAndRecordSettings settings);
    }
}


text:
package pax.TrainsSchedule.API;

public class API {
    public static final String RASP_BASE    = "https://api.rasp.yandex.net/v1.0";
    public static final String SUGGEST_BASE = "https://suggests.rasp.yandex.ru";
}


text:
#region License

#endregion
using System.Collections.Generic;
namespace System.Patterns.Caching
{
    /// <summary>
    /// DataCacheRegistration
    /// </summary>
    public class DataCacheRegistration
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DataCacheRegistration"/> class.
        /// </summary>
        internal DataCacheRegistration(string id)
        {
            // used for registration-links only
            if (string.IsNullOrEmpty(id))
                throw new ArgumentNullException("id");
            Id = id;
            CacheCommand = new CacheCommand("DataCacheRegistration", -1);
        }
        /// <summary>
        /// Adds the data source.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="builder">The builder.</param>
        /// <param name="dependencyArray">The dependency array.</param>
        public DataCacheRegistration(string id, DataCacheBuilder builder, params string[] dependencies)
            : this(id, new CacheCommand("DataCacheRegistration"), builder, dependencies) { }
        /// <summary>
        /// Adds the data source.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="minuteTimeout">The minute timeout.</param>
        /// <param name="builder">The builder.</param>
        /// <param name="dependencyArray">The dependency array.</param>
        public DataCacheRegistration(string id, int minuteTimeout, DataCacheBuilder builder, params string[] dependencies)
            : this(id, new CacheCommand("DataCacheRegistration", minuteTimeout), builder, dependencies) { }
        /// <summary>
        /// Adds the data source.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="cacheCommand">The cache command.</param>
        /// <param name="builder">The builder.</param>
        /// <param name="dependencyArray">The dependency array.</param>
        public DataCacheRegistration(string id, CacheCommand cacheCommand, DataCacheBuilder builder, params string[] dependencies)
        {
            if (string.IsNullOrEmpty(id))
                throw new ArgumentNullException("id");
            if (cacheCommand == null)
                throw new ArgumentNullException("cacheCommand");
            if (builder == null)
                throw new ArgumentNullException("builder");
            Id = id;
            Builder = builder;
            if ((dependencies != null) && (dependencies.Length > 0))
            {
                if (cacheCommand.Dependency != null)
                    throw new InvalidOperationException(Local.RedefineCacheDependency);
                cacheCommand.Dependency = new CacheDependency { CacheKeys = dependencies };
            }
            CacheCommand = cacheCommand;
            Tags = new List<string>();
        }

        /// <summary>
        /// Gets or sets the key.
        /// </summary>
        /// <value>The key.</value>
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the cache command.
        /// </summary>
        /// <value>The cache command.</value>
        public CacheCommand CacheCommand { get; set; }

        /// <summary>
        /// Gets or sets the builder.
        /// </summary>
        /// <value>The builder.</value>
        public DataCacheBuilder Builder { get; set; }

        /// <summary>
        /// Tags
        /// </summary>
        internal List<string> Tags;

        /// <summary>
        /// Registrar
        /// </summary>
        internal DataCacheRegistrar Registrar;

        /// <summary>
        /// Gets the cache.
        /// </summary>
        /// <param name="values">The values.</param>
        /// <returns></returns>
        internal CacheEx GetCacheSystem(object[] values)
        {
            return (values == null ? CacheEx.Default : CacheEx.GetNamespace(values));
        }
    }
}


text:
package org.emmalanguage
package compiler

import api.DataBag
import api.backend.LocalOps._
import api._
import api.alg.Count
import mitos._
import mitos.operators._
import mitos.partitioners._
import ir.DSCFAnnotations.loopBody
import ir.DSCFAnnotations.suffix
import ir.DSCFAnnotations.whileLoop

import org.apache.flink.core.fs.FileInputSplit

import java.util.UUID

class TestInt(var v: Int) {
  def addd(u: Int, w: Int, x: Int)(m: Int, n: Int)(s: Int, t: Int) : Int =
    this.v + u + w + x + m + n + s + t

  def add1() : Unit = { v = v + 1 }
}

class mitosCompilerSpec extends BaseCompilerSpec
  with mitosCompilerAware
  with mitosAware {

  //implicit val env = defaultFlinkStreamEnv

  case class Config
  (
    // general parameters
    command     : Option[String]       = None,
    // union of all parameters bound by a command option or argument
    // (in alphabetic order)
    csv         : CSV                  = CSV(),
    epsilon     : Double               = 0,
    iterations  : Int                  = 0,
    input       : String               = System.getProperty("java.io.tmpdir"),
    output      : String               = System.getProperty("java.io.tmpdir")
  ) extends FlinkConfig

  val c = Config()

  override val compiler = new RuntimeCompiler(codegenDir) with mitosCompiler

  import compiler._
  import u.reify

  protected override def wrapInClass(tree: u.Tree): u.Tree = {
    import u.Quasiquote

    val Cls = api.TypeName(UUID.randomUUID().toString)
    val run = api.TermName(RuntimeCompiler.default.runMethod)
    val prs = api.Tree.closure(tree).map { sym =>
      val x = sym.name
      val T = sym.info
      q"val $x: $T"
    }

    q"""
    class $Cls {
      def $run(..$prs)(implicit flink: ${api.Type[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]}) =
        $tree
    }
    """
  }

  def withBackendContext[T](f: Env => T): T =
    withDefaultFlinkStreamEnv(f)

  val anfPipeline: u.Expr[Any] => u.Tree =
    pipeline(typeCheck = true)(
      Core.anf,
      Core.unnest
    ).compose(_.tree)

  val noopPipeline: u.Expr[Any] => u.Tree = pipeline(typeCheck = true)().compose(_.tree)

  def applyXfrm(xfrm: Xfrm): u.Expr[Any] => u.Tree = {

    pipeline(typeCheck = true)(
      Core.lnf,
      xfrm.timed,
      Core.unnest
    ).compose(_.tree)
  }

  def applyLabynization(): u.Expr[Any] => u.Tree = {
    pipeline(typeCheck = true)(
      Core.lnf,
      mitosNormalize.timed,
      mitosLabynize.timed
    ).compose(_.tree)
  }

  def applyLabynizationOnly(): u.Expr[Any] => u.Tree = {
    pipeline(typeCheck = true)(
      mitosLabynize.timed
    ).compose(_.tree)
  }

  // ---------------------------------------------------------------------------
  // Spec tests
  // ---------------------------------------------------------------------------

  // helper
  def add1(x: Int) : Int = x + 1
  def str(x: Int) : String = x.toString
  def add(x: Int, y: Int) : Int = x + y
  def add(u: Int, v: Int, w: Int, x: Int, y: Int, z: Int)(m: Int, n: Int)(s: Int, t: Int) : Int =
    u + v + w + x + y + z + m + n + s + t

  // actual tests
  "normalization" - {

    "ValDef only" in {
      val inp = reify {
        val a = 1
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        })
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "replace refs on valdef rhs" in {
      val inp = reify {
        val a = 1; val b = a; val c = a; b
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        });
        val b = a;
        val c = a;
        b
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "ValDef only, SingSrc rhs" in {
      val inp = reify {
        val a = 1;
        val b = DB.singSrc(() => {
          val tmp = 2; tmp
        })
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        });
        val b = DB.singSrc(() => {
          val tmp = 2; tmp
        })
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "ValDef only, DataBag rhs" in {
      val inp = reify {
        val a = 1
        val b = DataBag(Seq(2))
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        })
        val s = DB.singSrc(() => {
          val tmp = Seq(2); tmp
        })
        val sb = DB.fromSingSrcApply(s)
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "ValDef only, DataBag rhs 2" in {
      val inp = reify {
        val fun = add1(2)
        val s = Seq(fun)
        val b = DataBag(s)
      }
      val exp = reify {
        val lbdaFun = () => {
          val tmp = add1(2); tmp
        }
        val dbFun = DB.singSrc(lbdaFun)
        val dbs = dbFun.map(e => Seq(e))
        val res = DB.fromSingSrcApply(dbs)
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "replace refs simple" in {
      val inp = reify {
        val a = 1; a
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        }); a
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method one argument" in {
      val inp = reify {
        val a = 1;
        val b = add1(a);
        b
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        });
        val b = a.map(e => add1(e));
        b
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method one argument 2" in {
      val inp = reify {
        val a = new TestInt(1);
        val b = a.add1()
        a
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = new TestInt(1); tmp
        });
        val b = a.map((e: TestInt) => e.add1());
        a
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method fold1" in {
      val inp = reify {
        val s = Seq(1)
        val b = DataBag(s)
        val count = Count[Int](_ => true)
        val c: Long = b.fold(count)
        c
      }
      val exp = reify {
        val a = DB.singSrc(() => { val tmp = Seq(1); tmp })
        val b: DataBag[Int] = DB.fromSingSrcApply(a)
        val count = Count[Int](_ => true)
        val c: DataBag[Long] = DB.fold1[Int, Long](b, count)
        c
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method fold2" in {
      val inp = reify {
        val s = Seq(1)
        val b = DataBag(s)
        val c: Int = b.fold(0)(i => i, (a, b) => a + b)
        c
      }
      val exp = reify {
        val s = DB.singSrc(() => { val tmp = Seq(1); tmp })
        val b: DataBag[Int] = DB.fromSingSrcApply(s)
        val c: DataBag[Int] = DB.fold2[Int, Int](b, 0, (i: Int) => i, (a, b) => a + b)
        c
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method collect" in {
      val inp = reify {
        val s = Seq(1)
        val b = DataBag(s)
        val c = b.collect()
        c
      }
      val exp = reify {
        val s = DB.singSrc(() => { val tmp = Seq(1); tmp })
        val b: DataBag[Int] = DB.fromSingSrcApply(s)
        val c = DB.collect(b)
        c
      }
      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method one argument typechange" in {
      val inp = reify {
        val a = 1;
        val b = str(a);
        b
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        });
        val b = a.map(e => str(e));
        b
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method two arguments no constant" in {
      val inp = reify {
        val a = 1
        val b = 2
        val c = add(a, b)
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        })
        val b = DB.singSrc(() => {
          val tmp = 2; tmp
        })
        val c = cross(a, b).map((t: (Int, Int)) => add(t._1, t._2))
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method two arguments with constants" in {
      val inp = reify {
        val a = 1
        val b = 2
        val c = add(3, 4, a, 5, 6, 7)(8, 9)(10, b)
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        })
        val b = DB.singSrc(() => {
          val tmp = 2; tmp
        })
        val c = cross(a, b).map((t: (Int, Int)) => add(3, 4, t._1, 5, 6, 7)(8, 9)(10, t._2))
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method two arguments 2" in {
      val inp = reify {
        val a = new TestInt(1)
        val b = 2
        val c = a.addd(1, b, 3)(4, 5)(6, 7)
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = new TestInt(1); tmp
        })
        val b = DB.singSrc(() => {
          val tmp = 2; tmp
        })
        val c = cross(a, b).map((t: (TestInt, Int)) => t._1.addd(1, t._2, 3)(4, 5)(6, 7))
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method three arguments with constants" in {
      val inp = reify {
        val a = 1
        val b = 2
        val c = 3
        val d = add(3, 4, a, 5, 6, 7)(c, 9)(10, b)
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = 1; tmp
        })
        val b = DB.singSrc(() => {
          val tmp = 2; tmp
        })
        val c = DB.singSrc(() => {
          val tmp = 3; tmp
        })
        val d = DB.cross3(a, c, b).map((t: (Int, Int, Int)) => add(3, 4, t._1, 5, 6, 7)(t._2, 9)(10, t._3))
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "method three arguments 2" in {
      val inp = reify {
        val a = new TestInt(1)
        val b = 2
        val c = 3
        val d = a.addd(1, b, 3)(4, c)(6, 7)
      }
      val exp = reify {
        val a = DB.singSrc(() => {
          val tmp = new TestInt(1); tmp
        })
        val b = DB.singSrc(() => {
          val tmp = 2; tmp
        })
        val c = DB.singSrc(() => {
          val tmp = 3; tmp
        })
        val d = DB.cross3(a, b, c).map((t: (TestInt, Int, Int)) => t._1.addd(1, t._2, 3)(4, t._3)(6, 7))
      }

      applyXfrm(mitosNormalize)(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }
  }

  implicit val defaultEnv = defaultFlinkStreamEnv

  "labynization" - {

    /*
    for now
    .setparallelism(1)
    partitioner always0 with para = 1
     */

    "lambda only" in {
      val inp = reify {
        val a = () => 1
      }

      val exp = reify {
        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)
        val a = () => 1
        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        val exec = LabyStatics.executeWithCatch(env)
        exec
      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "singSrc rhs" in {
      val inp = reify {
        val a = 1
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)
        val a = new LabyNode[mitos.util.Nothing, Int](
          "fromNothing",
          ScalaOps.fromNothing[Int]( () => { val tmp = 1; tmp } ),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)
      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "databag rhs" in {
      val inp = reify {
        val s = Seq(1)
        val db = DataBag(s)
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)
        val n1 = new LabyNode[mitos.util.Nothing, Seq[Int]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[Int]](() => {
            val tmp = Seq(1); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[Int]](Memo.typeInfoForType[Seq[Int]])
        )
          .setParallelism(1)

        val n2 = new LabyNode[Seq[Int], Int](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[Int, Seq[Int]](),
          0,
          new Always0[Seq[Int]](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n1, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)
      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "map" in {
      val inp = reify {
        val s = Seq(1,2,3)
        val db = DataBag(s)
        val dbm = db.map(x => add1(x))
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)

        val n1 = new LabyNode[mitos.util.Nothing, Seq[Int]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[Int]](() => {
            val tmp = Seq(1,2,3); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[Int]](Memo.typeInfoForType[Seq[Int]])
        )
          .setParallelism(1)

        val n2 = new LabyNode[Seq[Int], Int](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[Int, Seq[Int]](),
          0,
          new Always0[Seq[Int]](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n1, true, false)
          .setParallelism(1)

        val n3 = new LabyNode[Int, Int](
          "map",
          ScalaOps.map(x => add1(x)),
          0,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n2, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)
      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "flatmap" in {
      val inp = reify {
        val s = Seq(1, 2, 3)
        val db = DataBag(s)
        val dbm = db.flatMap(x => DataBag(Seq(0, add1(x))))
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)

        val n1 = new LabyNode[mitos.util.Nothing, Seq[Int]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[Int]](() => {
            val tmp = Seq(1, 2, 3);
            tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[Int]](Memo.typeInfoForType[Seq[Int]])
        )
          .setParallelism(1)

        val n2 = new LabyNode[Seq[Int], Int](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[Int, Seq[Int]](),
          0,
          new Always0[Seq[Int]](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n1, true, false)
          .setParallelism(1)

        val n3 = new LabyNode[Int, Int](
          "flatMap",
          ScalaOps.flatMapDataBagHelper(x => DataBag(Seq(0, add1(x)))),
          0,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n2, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)
      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "cross" in {
      val inp = reify {
        val db1 = DataBag(Seq(1,2,3))
        val db2 = DataBag(Seq("1","2","3"))
        val dbc = cross(db1, db2)
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)

        val n1_1 = new LabyNode[mitos.util.Nothing, Seq[Int]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[Int]](() => {
            val tmp = Seq(1,2,3); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[Int]](Memo.typeInfoForType[Seq[Int]])
        )
          .setParallelism(1)

        val n1_2 = new LabyNode[Seq[Int], Int](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[Int, Seq[Int]](),
          0,
          new Always0[Seq[Int]](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n1_1, true, false)
          .setParallelism(1)

        val n2_1 = new LabyNode[mitos.util.Nothing, Seq[String]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[String]](() => {
            val tmp = Seq("1","2","3"); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[String]](Memo.typeInfoForType[Seq[String]])
        )
          .setParallelism(1)

        val n2_2 = new LabyNode[Seq[String], String](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[String, Seq[String]](),
          0,
          new Always0[Seq[String]](1),
          null,
          new ElementOrEventTypeInfo[String](Memo.typeInfoForType[String])
        )
          .addInput(n2_1, true, false)
          .setParallelism(1)

        val n1_3 = new LabyNode[Int, Either[Int,String]](
          "map",
          ScalaOps.map(i => scala.util.Left(i)),
          0,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Either[Int,String]](Memo.typeInfoForType[Either[Int,String]])
        )
          .addInput(n1_2, true, false)
          .setParallelism(1)

        val n2_3 = new LabyNode[String, Either[Int,String]](
          "map",
          ScalaOps.map(s => scala.util.Right(s)),
          0,
          new Always0[String](1),
          null,
          new ElementOrEventTypeInfo[Either[Int,String]](Memo.typeInfoForType[Either[Int,String]])
        )
          .addInput(n2_2, true, false)
          .setParallelism(1)

        val n_cross = new LabyNode[Either[Int, String], (Int, String)](
          "cross",
          ScalaOps.cross[Int, String],
          0,
          new Always0[Either[Int,String]](1),
          null,
          new ElementOrEventTypeInfo[(Int, String)](Memo.typeInfoForType[(Int, String)])
        )
          .addInput(n1_3, true, false)
          .addInput(n2_3, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)

      }
      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "equiJoin" in {
      val inp = reify {
        val db1 = DataBag(Seq("a", "bb", "ddd"))
        val db2 = DataBag(Seq(2 , 5, 2))
        val extrA = (t: String) => t.length
        val extrB = (t: Int) => t
        val dbc = equiJoin[String, Int, Int](extrA, extrB )(db1, db2)
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)

        val n1_1 = new LabyNode[mitos.util.Nothing, Seq[String]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[String]](() => {
            val tmp = Seq("a", "bb", "ddd"); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[String]](Memo.typeInfoForType[Seq[String]])
        )
          .setParallelism(1)

        val n1_2 = new LabyNode[Seq[String], String](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[String, Seq[String]](),
          0,
          new Always0[Seq[String]](1),
          null,
          new ElementOrEventTypeInfo[String](Memo.typeInfoForType[String])
        )
          .addInput(n1_1, true, false)
          .setParallelism(1)

        val n2_1 = new LabyNode[mitos.util.Nothing, Seq[Int]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[Int]](() => {
            val tmp = Seq(2 , 5, 2); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[Int]](Memo.typeInfoForType[Seq[Int]])
        )
          .setParallelism(1)

        val n2_2 = new LabyNode[Seq[Int], Int](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[Int, Seq[Int]](),
          0,
          new Always0[Seq[Int]](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n2_1, true, false)
          .setParallelism(1)

        val extrA = (t: String) => t.length
        val extrB = (t: Int) => t

        val n1_3 = new LabyNode[String, Either[String, Int]](
          "map",
          ScalaOps.map(i => scala.util.Left(i)),
          0,
          new Always0[String](1),
          null,
          new ElementOrEventTypeInfo[Either[String, Int]](Memo.typeInfoForType[Either[String, Int]])
        )
          .addInput(n1_2, true, false)
          .setParallelism(1)

        val n2_3 = new LabyNode[Int, Either[String, Int]](
          "map",
          ScalaOps.map(s => scala.util.Right(s)),
          0,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Either[String, Int]](Memo.typeInfoForType[Either[String, Int]])
        )
          .addInput(n2_2, true, false)
          .setParallelism(1)

        val n_join = new LabyNode[Either[String, Int], (String,Int)](
          "join",
          ScalaOps.joinScala[String, Int, Int](extrA, extrB),
          0,
          new Always0[Either[String, Int]](1),
          null,
          new ElementOrEventTypeInfo[(String, Int)](Memo.typeInfoForType[(String, Int)])
        )
          .addInput(n1_3, true, false)
          .addInput(n2_3, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)

      }
      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "fold1" in {
      val inp = reify {
        val s = Seq(1)
        val b = DataBag(s)
        val count = Count[Int](_ => true)
        val c: Long = b.fold(count)
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)

        val n1 = new LabyNode[mitos.util.Nothing, Seq[Int]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[Int]](() => {
            val tmp = Seq(1); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[Int]](Memo.typeInfoForType[Seq[Int]])
        )
          .setParallelism(1)

        val n2 = new LabyNode[Seq[Int], Int](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[Int, Seq[Int]](),
          0,
          new Always0[Seq[Int]](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n1, true, false)
          .setParallelism(1)

        val count = Count[Int](_ => true)

        val c = new LabyNode[Int, Long](
          "fold1",
          ScalaOps.foldAlgHelper(count),
          0,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Long](Memo.typeInfoForType[Long])
        )
          .addInput(n2, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)
      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "fold2" in {
      val inp = reify {
        val s = Seq("foo")
        val b = DataBag(s)
        val c: Int = b.fold(0)((s: String) => s.length, (a, b) => a + b)
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)

        val n1 = new LabyNode[mitos.util.Nothing, Seq[String]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[String]](() => {
            val tmp = Seq("foo"); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[String]](Memo.typeInfoForType[Seq[String]])
        )
          .setParallelism(1)

        val n2 = new LabyNode[Seq[String], String](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[String, Seq[String]](),
          0,
          new Always0[Seq[String]](1),
          null,
          new ElementOrEventTypeInfo[String](Memo.typeInfoForType[String])
        )
          .addInput(n1, true, false)
          .setParallelism(1)

        val c = new LabyNode[String, Int](
          "fold2",
          ScalaOps.fold(0, (s: String) => s.length, (a,b) => a + b),
          0,
          new Always0[String](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(n2, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)
      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "read Text" in {
      val inp = reify {
        val p = "path"
        val rt = DataBag.readText(p)
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)

        val n1 = new LabyNode[mitos.util.Nothing, String](
          "fromNothing",
          ScalaOps.fromNothing[String](() => {
            val tmp = "path"; tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[String](Memo.typeInfoForType[String])
        )
          .setParallelism(1)

        val n2 = new LabyNode[String, InputFormatWithInputSplit[String, FileInputSplit]](
          "inputSplits",
          ScalaOps.textSource,
          0,
          new Always0[String](1),
          null,
          new ElementOrEventTypeInfo[InputFormatWithInputSplit[String, FileInputSplit]](
            Memo.typeInfoForType[InputFormatWithInputSplit[String, FileInputSplit]]
          )
        )
          .addInput(n1, true, false)
          .setParallelism(1)

        val n3 = new LabyNode[InputFormatWithInputSplit[String, FileInputSplit], String](
          "readSplits",
          ScalaOps.textReader,
          0,
          new Always0[InputFormatWithInputSplit[String, FileInputSplit]](1),
          null,
          new ElementOrEventTypeInfo[String](Memo.typeInfoForType[String])
        )
          .addInput(n2, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)
      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

    "write csv" in {
      val inp = reify {
        val fun1: () => Seq[Int] = () => { val tmp = Seq(1, 2); tmp }
        val d = DB.singSrc[Seq[Int]](fun1)
        val db = DB.fromSingSrcApply[Int](d)
        val fun2: () => String = () => { val tmp = "path"; tmp }
        val p = DB.singSrc[String](fun2)
        val fun3: () => CSV = () => {val tmp = csvDummy; tmp }
        val csv = DB.singSrc[org.emmalanguage.io.csv.CSV](fun3)
        val s = DB.fromDatabagWriteCSV(db, p, csv)
      }

      val exp = reify {

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(0)
        LabyStatics.setKickoffSource(0)

        val nData = new LabyNode[mitos.util.Nothing, Seq[Int]](
          "fromNothing",
          ScalaOps.fromNothing[Seq[Int]](() => {
            val tmp = Seq(1, 2); tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Seq[Int]](Memo.typeInfoForType[Seq[Int]])
        )
          .setParallelism(1)

        val nDataFSS = new LabyNode[Seq[Int], Int](
          "fromSingSrcApply",
          ScalaOps.fromSingSrcApply[Int, Seq[Int]](),
          0,
          new Always0[Seq[Int]](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(nData, true, false)
          .setParallelism(1)

        val nPath = new LabyNode[mitos.util.Nothing, String](
          "fromNothing",
          ScalaOps.fromNothing[String](() => {
            val tmp = "path"; tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[String](Memo.typeInfoForType[String])
        )
          .setParallelism(1)

        val nCSV = new LabyNode[mitos.util.Nothing, org.emmalanguage.io.csv.CSV](
          "fromNothing",
          ScalaOps.fromNothing[org.emmalanguage.io.csv.CSV](() => {
            val tmp = csvDummy; tmp
          }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[org.emmalanguage.io.csv.CSV](Memo.typeInfoForType[org.emmalanguage.io.csv.CSV])
        )
          .setParallelism(1)

        val dataEither = new LabyNode[Int, Either[Int,org.emmalanguage.io.csv.CSV]](
          "map",
          ScalaOps.map(i => scala.util.Left(i)),
          0,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Either[Int,org.emmalanguage.io.csv.CSV]](
            Memo.typeInfoForType[Either[Int,org.emmalanguage.io.csv.CSV]]
          )
        )
          .addInput(nDataFSS, true, false)
          .setParallelism(1)

        val csvEither = new LabyNode[org.emmalanguage.io.csv.CSV, Either[Int,org.emmalanguage.io.csv.CSV]](
          "map",
          ScalaOps.map(s => scala.util.Right(s)),
          0,
          new Always0[org.emmalanguage.io.csv.CSV](1),
          null,
          new ElementOrEventTypeInfo[Either[Int,org.emmalanguage.io.csv.CSV]](
            Memo.typeInfoForType[Either[Int,org.emmalanguage.io.csv.CSV]]
          )
        )
          .addInput(nCSV, true, false)
          .setParallelism(1)

        val nToCsvString = new LabyNode[Either[Int, CSV], String](
          "toCsvString",
          ScalaOps.toCsvString[Int],
          0,
          new Always0[Either[Int, CSV]](1),
          null,
          new ElementOrEventTypeInfo[String](Memo.typeInfoForType[String])
        )
          .addInput(dataEither, true, false)
          .addInput(csvEither, true, false)
          .setParallelism(1)

        val nStringSink = new LabyNode[String, Unit](
          "stringFileSink",
          ScalaOps.writeString,
          0,
          new Always0[String](1),
          null,
          new ElementOrEventTypeInfo[Unit](Memo.typeInfoForType[Unit])
        )
          .addInput(nPath, true, false)
          .addInput(nToCsvString, true, false)
          .setParallelism(1)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)

      }

      applyLabynizationOnly()(inp) shouldBe alphaEqTo(anfPipeline(exp))

    }

  }

  "control flow" - {

    "with trivial body" in {
      val inp = reify {
        //        var i = 0
        //        while (i < 100) i += 1
        //        println(i)

        @whileLoop def while$1(i: Int): Unit = {
          val x$1 = i < 100
          @loopBody def body$1(): Unit = {
            val i$3 = i + 1
            while$1(i$3)
          }
          @suffix def suffix$1(): Unit = {
            println(i)
          }
          if (x$1) body$1()
          else suffix$1()
        }
        while$1(0)
      }

      val exp = reify {

        // outer    -> 0
        // while$1  -> 1
        // body$1   -> 2
        // suffix$1 -> 3

        // kickoff:  0
        // terminal: 3

        LabyStatics.registerCustomSerializer()
        LabyStatics.setTerminalBbid(3)
        LabyStatics.setKickoffSource(0, 1)

        val n1 = new LabyNode[mitos.util.Nothing, Int](
          "fromNothing",
          ScalaOps.fromNothing(() => {val tmp = 0; tmp }),
          0,
          new Always0[mitos.util.Nothing](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .setParallelism(1)

        val iPhi = LabyStatics.phi[Int](
          "arg$r1Phi",
          1,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )

        val x$1 = new LabyNode[Int, Boolean](
          "map",
          ScalaOps.map(_ < 100),
          1,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Boolean](Memo.typeInfoForType[Boolean])
        )
          .addInput(iPhi, true, false)
          .setParallelism(1)

        val i$3 = new LabyNode[Int, Int](
          "map",
          ScalaOps.map(_ + 1),
          2,
          new Always0[Int](1), null,
          new ElementOrEventTypeInfo[Int](Memo.typeInfoForType[Int])
        )
          .addInput(iPhi, false, true)
          .setParallelism(1)

        val addInp1 = iPhi.addInput(i$3, false, true)

        val printlnNode = new LabyNode[Int, Unit](
          "map",
          ScalaOps.map( (i:Int) => println(i)),
          3,
          new Always0[Int](1),
          null,
          new ElementOrEventTypeInfo[Unit](Memo.typeInfoForType[Unit])
        )
          .addInput(iPhi, false, true)
          .setParallelism(1)

        val ifCondNode = new LabyNode(
          "condNode",
          ScalaOps.condNode(
            Seq(2, 1),
            Seq(3)
          ),
          1,
          new Always0[Boolean](1),
          null,
          new ElementOrEventTypeInfo[mitos.util.Unit](Memo.typeInfoForType[mitos.util.Unit])
        )
          .addInput(x$1, true, false)
          .setParallelism(1)

        val addInp2 = iPhi.addInput(n1, false, true)

        val env = implicitly[org.apache.flink.streaming.api.scala.StreamExecutionEnvironment]
        LabyStatics.translateAll
        LabyStatics.executeWithCatch(env)

      }

      applyLabynization()(inp) shouldBe alphaEqTo(anfPipeline(exp))
    }

  }

  def expandAndAnf(t: u.Tree) : u.Tree = {
    val tt = compiler.unTypeCheck(t)
    pipeline(typeCheck = true)(
      Core.anf,
      Core.unnest
    )(tt)
  }

  val csvDummy = CSV()
}

case class Edge[V](src: V, dst: V)
case class LEdge[V, L](@emma.pk src: V, @emma.pk dst: V, label: L)
case class LVertex[V, L](@emma.pk id: V, label: L)
case class Triangle[V](x: V, y: V, z: V)
case class Message[K, V](@emma.pk tgt: K, payload: V)


text:
__author__ = 'Alex Baranov'

from unittest import TestCase
from box import Box
from orthogonal_packing import orthogonal_packer

__author__ = 'Alex Baranov'

class TestOrthogonalPacker(TestCase):
    """
    Contains the unit tests for the orthogonal packer.
    """
    def test_orthogonal_packed_valid(self):
        """
        Verify the valid orthogonal packing scenarios
        """
        c = Box(size=(5, 5, 5))
        b = Box(size=(2, 3, 1))

        r = orthogonal_packer(c, b, allowed_rotation_axes=(1, 0, 1))

        # check packing result
        self.assertTrue(r[0])

        # check packed box parameters
        self.assertEqual(r[1].size, (1,3,2))