text:
  Vantoux est
       un village
       localisé dans le département de Moselle en Lorraine. On dénombrait 915 habitants en 2008.

À coté de Vantoux sont situées les communes de
Noisseville localisée à 3 km, 990 habitants,
Saint-Julien-lès-Metz localisée à 2 km, 2 981 habitants,
Servigny-lès-Sainte-Barbe située à 3 km, 430 habitants,
Nouilly située à 2 km, 468 habitants,
Mey à 0 km, 203 habitants,
Montoy-Flanville à 3 km, 1 193 habitants,
 entre autres. De plus, Vantoux est située à seulement quatre km de Metz.

Si vous envisagez de demenager à Vantoux, vous pourrez facilement trouver une maison à acheter.

Vantoux est localisé à seulement 4 Kilomètres de Metz, les élèves qui aurons besoin de se loger à moindre coût pourront envisager de prendre un logement à Vantoux. Vantoux est également un bon investissement locatif a cause de sa proximité de Metz et de ses Universités. Il sera aisé de trouver un studio à acheter.

À Vantoux, le prix moyen à la vente d'un appartement se situe à 1 893 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 969 € du m². À la location la valeur moyenne se situe à 7,35 € du m² mensuel.

Le parc d'habitations, à Vantoux, était réparti en 2011 en 29 appartements et 309 maisons soit
 un marché plutôt équilibré.

La commune compte quelques  aménagements, elle propose entre autres un terrain de sport.


text:
package com.konifar.annict.repository;

import com.konifar.annict.model.Record;

import rx.Observable;

public interface RecordRepository {

    Observable<Record> create(Long episodeId, String comment, Float rating, boolean shareTwitter, boolean shareFacebook);

    Observable<Record> update(Long recordId, String comment, Float rating, boolean shareTwitter, boolean shareFacebook);
}

redpajama_set_name: RedPajamaGithub


text:
_variant_t CONST_VARIANT_TRUE((short)TRUE);
_variant_t CONST_VARIANT_FALSE((short)FALSE);
_variant_t CONST_VARIANT_OPTIONAL((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

//
CApplication Illusion_ExcelFile::excel_application_;

Illusion_ExcelFile::Illusion_ExcelFile():
    already_preload_(FALSE)
{
}

Illusion_ExcelFile::~Illusion_ExcelFile()
{
    //
    close_excelfile();
}

//初始化EXCEL文件,
BOOL Illusion_ExcelFile::init_excel()
{

    HRESULT hret = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    //其实这个初始化放在这儿并不见得合理,
    if (FAILED(hret))
    {
        ::AfxMessageBox(_T("初始化COM支持库失败!"));
        return FALSE;
    }

    //创建Excel 2000服务器(启动Excel)
    if (!excel_application_.CreateDispatch(_T("Excel.Application"), NULL))
    {
        ::AfxMessageBox(_T("无法启动EXCEL,请检查是否安装了Office EXCEL,或者检查注册表。"));
        return FALSE;
    }

    excel_application_.put_DisplayAlerts(FALSE);
    return TRUE;
}

//
void Illusion_ExcelFile::release_excel()
{
    excel_application_.Quit();
    excel_application_.ReleaseDispatch();
    excel_application_ = NULL;

    ::CoUninitialize();
}

//打开excel文件
BOOL Illusion_ExcelFile::open_excelfile(const CString &file_name)
{
    //先关闭
    close_excelfile();

    //利用模板文件建立新文档
    excel_books_.AttachDispatch(excel_application_.get_Workbooks(), true);

    LPDISPATCH lpDis = NULL;
    _variant_t v_fn(file_name);
    lpDis = excel_books_.Open(file_name,
                              vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
                              vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
                              vtMissing, vtMissing, vtMissing, vtMissing);
    if (lpDis)
    {
        excel_work_book_.AttachDispatch(lpDis);
        //得到Worksheets
        excel_sheets_.AttachDispatch(excel_work_book_.get_Worksheets(), true);

        //记录打开的文件名称
        open_excel_file_ = file_name;

        return TRUE;
    }

    return FALSE;

}

//关闭打开的Excel 文件,默认情况不保存文件
void Illusion_ExcelFile::close_excelfile(BOOL if_save)
{
    //如果已经打开,关闭文件
    if (open_excel_file_.IsEmpty() == FALSE)
    {
        //如果保存,交给用户控制,让用户自己存,如果自己SAVE,会出现莫名的等待
        if (if_save)
        {
            show_in_excel(TRUE);
        }
        else
        {
            //
            _variant_t v_excel_file(open_excel_file_);
            excel_work_book_.Close(CONST_VARIANT_OPTIONAL,
                                   CONST_VARIANT_OPTIONAL,
                                   CONST_VARIANT_OPTIONAL);
            excel_books_.Close();
        }

        //打开文件的名称清空
        open_excel_file_.Empty();
    }

    excel_sheets_.ReleaseDispatch();
    excel_work_sheet_.ReleaseDispatch();
    excel_current_range_.ReleaseDispatch();
    excel_work_book_.ReleaseDispatch();
    excel_books_.ReleaseDispatch();
}

void Illusion_ExcelFile::saveas_excelfile(const CString &xls_file)
{
    _variant_t v_xls_file(xls_file);
    excel_work_book_.SaveAs(v_xls_file,
                            CONST_VARIANT_OPTIONAL,
                            CONST_VARIANT_OPTIONAL,
                            CONST_VARIANT_OPTIONAL,
                            CONST_VARIANT_OPTIONAL,
                            CONST_VARIANT_OPTIONAL,
                            0,
                            CONST_VARIANT_OPTIONAL,
                            CONST_VARIANT_OPTIONAL,
                            CONST_VARIANT_OPTIONAL,
                            CONST_VARIANT_OPTIONAL,
                            CONST_VARIANT_OPTIONAL);
    return;
}

int Illusion_ExcelFile::sheets_count()
{
    return excel_sheets_.get_Count();
}

CString Illusion_ExcelFile::sheet_name(long table_index)
{
    CWorksheet sheet;
    _variant_t v_t_idx((long)table_index);
    sheet.AttachDispatch(excel_sheets_.get_Item(v_t_idx), true);
    CString name = sheet.get_Name();
    sheet.ReleaseDispatch();
    return name;
}

//按照序号加载Sheet表格,可以提前加载所有的表格内部数据
BOOL Illusion_ExcelFile::load_sheet(long table_index, BOOL pre_load)
{
    LPDISPATCH lpDis = NULL;
    excel_current_range_.ReleaseDispatch();
    excel_work_sheet_.ReleaseDispatch();
    _variant_t v_t_idx((long)table_index);
    try
    {
        lpDis = excel_sheets_.get_Item(v_t_idx);
    }
    catch (...)
    {
        lpDis = NULL;
    }

    if (lpDis)
    {
        excel_work_sheet_.AttachDispatch(lpDis, TRUE);
        excel_current_range_.AttachDispatch(excel_work_sheet_.get_Cells(), TRUE);
    }
    else
    {
        return FALSE;
    }

    already_preload_ = FALSE;
    //如果进行预先加载
    if (pre_load)
    {
        preload_sheet();
        already_preload_ = TRUE;
    }

    return TRUE;
}

//按照名称加载Sheet表格,可以提前加载所有的表格内部数据
BOOL Illusion_ExcelFile::load_sheet(const CString &sheet, BOOL pre_load)
{
    LPDISPATCH lpDis = NULL;
    excel_current_range_.ReleaseDispatch();
    excel_work_sheet_.ReleaseDispatch();
    _variant_t  v_sheet(sheet);
    try
    {
        lpDis = excel_sheets_.get_Item(v_sheet);
    }
    catch (...)
    {
        lpDis = NULL;
    }

    if (lpDis)
    {
        excel_work_sheet_.AttachDispatch(lpDis, TRUE);
        excel_current_range_.AttachDispatch(excel_work_sheet_.get_Cells(), TRUE);

    }
    else
    {
        return FALSE;
    }
    //
    already_preload_ = FALSE;
    //如果进行预先加载
    if (pre_load)
    {
        already_preload_ = TRUE;
        preload_sheet();
    }

    return TRUE;
}

//得到列的总数
long Illusion_ExcelFile::column_count()
{
    CRange range;
    CRange usedRange;
    usedRange.AttachDispatch(excel_work_sheet_.get_UsedRange(), true);
    range.AttachDispatch(usedRange.get_Columns(), true);
    long count = range.get_Count();
    usedRange.ReleaseDispatch();
    range.ReleaseDispatch();
    return count;
}

//得到行的总数
long Illusion_ExcelFile::row_count()
{
    CRange range;
    CRange usedRange;
    usedRange.AttachDispatch(excel_work_sheet_.get_UsedRange(), true);
    range.AttachDispatch(usedRange.get_Rows(), true);
    long count = range.get_Count();
    usedRange.ReleaseDispatch();
    range.ReleaseDispatch();
    return count;
}

//检查一个CELL是否是字符串
BOOL Illusion_ExcelFile::is_cell_string(long irow, long icolumn)
{
    CRange range;
    _variant_t v_row((long)irow);
    _variant_t v_column((long)icolumn);
    range.AttachDispatch(excel_current_range_.get_Item(v_row, v_column).pdispVal, true);
    COleVariant vResult = range.get_Value2();
    //VT_BSTR标示字符串
    if (vResult.vt == VT_BSTR)
    {
        return TRUE;
    }
    return FALSE;
}

//检查一个CELL是否是数值
BOOL Illusion_ExcelFile::is_cell_number(long iline, long icolumn)
{
    CRange range;
    _variant_t v_row((long)iline);
    _variant_t v_column((long)icolumn);
    range.AttachDispatch(excel_current_range_.get_Item(v_row, v_column).pdispVal, true);
    VARIANT vResult = range.get_Value2();
    //好像一般都是VT_R8
    if (vResult.vt == VT_INT || vResult.vt == VT_R8)
    {
        return TRUE;
    }
    return FALSE;
}

//
CString Illusion_ExcelFile::get_cell_cstring(long iline, long icolumn)
{

    COleVariant vResult ;
    CString str;
    //字符串
    if (already_preload_ == FALSE)
    {
        CRange range;
        _variant_t v_row(iline);
        _variant_t v_column(icolumn);
        range.AttachDispatch(excel_current_range_.get_Item(v_row, v_column).pdispVal, true);
        vResult = range.get_Value2();
        range.ReleaseDispatch();
    }
    //如果数据依据预先加载了
    else
    {
        long read_address[2];
        VARIANT val;
        read_address[0] = iline;
        read_address[1] = icolumn;
        ole_safe_array_.GetElement(read_address, &val);
        vResult = val;
    }

    if (vResult.vt == VT_BSTR)
    {
        str = vResult.bstrVal;
    }
    //整数
    else if (vResult.vt == VT_INT)
    {
        str.Format(_T("%d"), vResult.pintVal);
    }
    //8字节的数字
    else if (vResult.vt == VT_R8)
    {
        str.Format(_T("%.6f"), vResult.dblVal);
    }
    //时间格式
    else if (vResult.vt == VT_DATE)
    {
        SYSTEMTIME st;
        VariantTimeToSystemTime(vResult.date, &st);
        CTime tm(st);
        str = tm.Format(_T("%Y-%m-%d"));

    }
    //单元格空的
    else if (vResult.vt == VT_EMPTY)
    {
        str = "";
    }

    return str;
}

//VT_R8
int Illusion_ExcelFile::get_cell_int(long iline, long icolumn)
{
    int num;
    COleVariant vresult;

    if (already_preload_ == FALSE)
    {
        CRange range;
        _variant_t v_row((long)iline);
        _variant_t v_column((long)icolumn);
        range.AttachDispatch(excel_current_range_.get_Item(v_row, v_column).pdispVal, true);
        vresult = range.get_Value2();
        range.ReleaseDispatch();
    }
    else
    {
        long read_address[2];
        VARIANT val;
        read_address[0] = iline;
        read_address[1] = icolumn;
        ole_safe_array_.GetElement(read_address, &val);
        vresult = val;
    }
    //
    num = static_cast<int>(vresult.dblVal);

    return num;
}

void Illusion_ExcelFile::set_cell_string(long iline, long icolumn, const CString &new_string)
{
    _variant_t new_value(new_string);
    _variant_t v_pos("A1");
    CRange start_range = excel_work_sheet_.get_Range(v_pos, CONST_VARIANT_OPTIONAL);

    _variant_t v_row((long)iline - 1);
    _variant_t v_column((long)icolumn - 1);

    CRange write_range = start_range.get_Offset(v_row, v_column);
    write_range.put_Value2(new_value);
    start_range.ReleaseDispatch();
    write_range.ReleaseDispatch();

}

void Illusion_ExcelFile::set_cell_int(long iline, long icolumn, int new_int)
{
    _variant_t new_value((long)new_int);

    _variant_t v_pos("A1");
    CRange start_range = excel_work_sheet_.get_Range(v_pos, CONST_VARIANT_OPTIONAL);

    _variant_t v_row((long)iline - 1);
    _variant_t v_column((long)icolumn - 1);

    CRange write_range = start_range.get_Offset(v_row, v_column);
    write_range.put_Value2(new_value);
    start_range.ReleaseDispatch();
    write_range.ReleaseDispatch();
}

//
void Illusion_ExcelFile::show_in_excel(BOOL bShow)
{
    excel_application_.put_Visible(bShow);
    excel_application_.put_UserControl(bShow);
}

//返回打开的EXCEL文件名称
CString Illusion_ExcelFile::open_filename()
{
    return open_excel_file_;
}

//取得列的名称,比如27->AA
TCHAR *Illusion_ExcelFile::column_name(long column_no)
{
    static TCHAR column_name[64];
    size_t str_len = 0;

    while (column_no > 0)
    {
        int num_data = column_no % 26;
        column_no /= 26;
        if (num_data == 0)
        {
            num_data = 26;
            column_no--;
        }
        //不知道这个对不,
        column_name[str_len] = (TCHAR)((num_data - 1) + _T('A') );
        str_len ++;
    }
    column_name[str_len] = '\0';
    //反转
    _tcsrev(column_name);

    return column_name;
}

char *Illusion_ExcelFile::column_mbcs_name(long column_no)
{
    static unsigned char column_name[64];
    size_t str_len = 0;

    while (column_no > 0)
    {
        int num_data = column_no % 26;
        column_no /= 26;
        if (num_data == 0)
        {
            num_data = 26;
            column_no--;
        }
        //不知道这个对不,
        column_name[str_len] = (char)((num_data - 1) + ('A'));
        str_len++;
    }
    column_name[str_len] = '\0';
    //反转
    _mbsrev(column_name);

    return(char *) column_name;
}

//预先加载
void Illusion_ExcelFile::preload_sheet()
{

    CRange used_range;

    used_range = excel_work_sheet_.get_UsedRange();

    VARIANT ret_ary = used_range.get_Value2();
    if (!(ret_ary.vt & VT_ARRAY))
    {
        return;
    }
    //
    ole_safe_array_.Clear();
    ole_safe_array_.Attach(ret_ary);
}


text:
package com.github.markusbernhardt.xmldoclet.simpledata;

/**
 * Class12
 */
@SuppressWarnings("serial")
public class Class12 extends java.lang.Error {

}


text:
namespace FurryBuilder
{
namespace FactorIt
{
namespace Contracts
{
	typedef std::function<void(FactoryWeak::type factory)> RegisterAction_t;

	class IBindingToWeak
	{
		INTERFACE(IBindingToWeak)

		virtual void SetServiceLocator(IServiceLocator* serviceLocator) abstract;
		virtual void SetOnRegister(RegisterAction_t action) abstract;

	// Required to hide the Weak/Strong mecanism which should be considered as
	// internal code.
	protected:
		virtual void ToWeak(FactoryWeak::type factory) abstract;
	};

	template<typename TContract>
	class IBindingTo : public IBindingToWeak
	{
		INTERFACE(IBindingTo)

		template<typename TService>
		void To()
		{
			static_assert(std::is_base_of<TContract, TService>::value, "TService must be a type of TContract");
			static_assert(std::is_default_constructible<TService>::value, "TService must have a public accesible default constructor");

			ToWeak([](IServiceLocator* _){ return std::static_pointer_cast<void>(std::make_shared<TService>()); });
		}

		void To(typename FactoryStrong<TContract>::type factory)
		{
			ToWeak(static_cast<FactoryWeak::type>(factory));
		}

		template<typename TService>
		void Forward(IServiceLocator* serviceLocator)
		{
			static_assert(std::is_base_of<TContract, TService>::value, "TService must be a type of TContract");

			ToWeak([serviceLocator](IServiceLocator* _){ return std::static_pointer_cast<void>(serviceLocator->Resolve<TService>()); });
		}

		template<typename TService>
		void Forward(IServiceLocator* serviceLocator, const std::string& key)
		{
			static_assert(std::is_base_of<TContract, TService>::value, "TService must be a type of TContract");

			ToWeak([serviceLocator](IServiceLocator* _){ return std::static_pointer_cast<void>(serviceLocator->Resolve<TService>(key)); });
		}
	};
}
}
}

#endif


text:
package org.apache.jmeter.assertions;

import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;

import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.ThreadListener;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * Checks if the result is a well-formed XML content using jdom
 *
 */
public class XMLAssertion extends AbstractTestElement implements Serializable, Assertion, ThreadListener {
    private static final Logger log = LoggingManager.getLoggerForClass();

    private static final long serialVersionUID = 240L;

    // one builder for all requests in a thread
    private static final ThreadLocal<SAXBuilder> myBuilder = new ThreadLocal<SAXBuilder>() {
        @Override
        protected SAXBuilder initialValue() {
            return new SAXBuilder();
        }
    };

    /**
     * Returns the result of the Assertion. Here it checks wether the Sample
     * took to long to be considered successful. If so an AssertionResult
     * containing a FailureMessage will be returned. Otherwise the returned
     * AssertionResult will reflect the success of the Sample.
     */
    @Override
    public AssertionResult getResult(SampleResult response) {
        // no error as default
        AssertionResult result = new AssertionResult(getName());
        String resultData = response.getResponseDataAsString();
        if (resultData.length() == 0) {
            return result.setResultForNull();
        }
        result.setFailure(false);
        SAXBuilder builder = myBuilder.get();

        try {
            builder.build(new StringReader(resultData));
        } catch (JDOMException e) {
            log.debug("Cannot parse result content", e); // may well happen
            result.setFailure(true);
            result.setFailureMessage(e.getMessage());
        } catch (IOException e) {
            log.error("Cannot read result content", e); // should never happen
            result.setError(true);
            result.setFailureMessage(e.getMessage());
        }

        return result;
    }

    @Override
    public void threadStarted() {
    }

    @Override
    public void threadFinished() {
        myBuilder.set(null);
    }
}


text:
<?php

namespace Google\Service\SecurityCommandCenter;

class ListSourcesResponse extends \Google\Collection
{
  protected $collection_key = 'sources';
  /**
   * @var string
   */
  public $nextPageToken;
  protected $sourcesType = Source::class;
  protected $sourcesDataType = 'array';

  /**
   * @param string
   */
  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  /**
   * @return string
   */
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
  /**
   * @param Source[]
   */
  public function setSources($sources)
  {
    $this->sources = $sources;
  }
  /**
   * @return Source[]
   */
  public function getSources()
  {
    return $this->sources;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ListSourcesResponse::class, 'Google_Service_SecurityCommandCenter_ListSourcesResponse');


text:
package org.enterprisedomain.classmaker.impl;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.enterprisedomain.classmaker.ClassMakerPackage;
import org.enterprisedomain.classmaker.SCMOperator;
import org.enterprisedomain.classmaker.SCMRegistry;
import org.enterprisedomain.classmaker.scm.GitSCMOperator;

/**
 *  An implementation of the model object 'SCM
 * Registry'.
 *
 * @generated
 */
public class SCMRegistryImpl<T> extends EObjectImpl implements SCMRegistry<T> {

	private Map<String, SCMOperator<T>> operators = new HashMap<String, SCMOperator<T>>();

	private Map<String, T> scms = new HashMap<String, T>();

	/**
	 *
	 *
	 * @generated
	 */
	protected SCMRegistryImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return ClassMakerPackage.Literals.SCM_REGISTRY;
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public boolean contains(String projectName) {
		return operators.containsKey(projectName);
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public SCMOperator<T> get(String projectName) {
		if (!contains(projectName))
			put(projectName, createSCMOperator(projectName));
		return operators.get(projectName);
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public void put(String projectName, SCMOperator<T> operator) {
		operators.put(projectName, operator);
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public boolean containsSCM(String projectName) {
		return scms.containsKey(projectName);
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public T getSCM(String projectName) {
		if (scms.containsKey(projectName))
			return scms.get(projectName);
		return null;
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public void putSCM(String projectName, T scm) {
		scms.put(projectName, scm);
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public void removeSCM(String projectName) {
		scms.remove(projectName);
	}

	/**
	 *
	 *
	 * @generated NOT
	 */
	public SCMOperator<T> createSCMOperator(String projectName) {
		@SuppressWarnings("unchecked")
		SCMOperator<T> operator = (SCMOperator<T>) (new GitSCMOperator());
		operator.setProjectName(projectName);
		operator.setRegistry(this);
		return operator;
	}

} // SCMRegistryImpl


text:
package com.clouddatamigration.classification.model;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.annotations.Persistent;
import javax.persistence.EntityManager;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.simpledb.model.Attribute;
import com.amazonaws.services.simpledb.model.GetAttributesRequest;
import com.amazonaws.services.simpledb.model.GetAttributesResult;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.PutAttributesRequest;
import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
import com.amazonaws.services.simpledb.model.SelectRequest;
import com.spaceprogram.simplejpa.EntityManagerFactoryImpl;

public abstract class AbstractModel<T> {

	protected static final String PREFIX = "clouddatamigration-";
	protected static boolean useJpa = false;
	protected static boolean useGAE = false;
	protected static boolean useSimpleDB = true;
	private static EntityManagerFactoryImpl factory;
	protected static PersistenceManagerFactory pmf;
	protected static EntityManager em;
	protected static AmazonSimpleDBClient sdb;
	private static Map<String, Map<String, Object>> cacheById = new HashMap<String, Map<String, Object>>();
	private static Map<String, Collection<Object>> cacheList = new HashMap<String, Collection<Object>>();
	protected static AmazonS3Client s3;

	static {
		if (useJpa) {
			factory = new EntityManagerFactoryImpl("clouddatamigration", null);
			em = factory.createEntityManager();
		} else if (!useJpa && !useSimpleDB) {
			InputStream propertiesStream = Project.class
					.getResourceAsStream("/clouddatamigration.properties");
			pmf = JDOHelper.getPersistenceManagerFactory(propertiesStream);
		} else if (useSimpleDB) {
			InputStream propertiesStream = Project.class
					.getResourceAsStream("/clouddatamigration.properties");
			try {
				sdb = new AmazonSimpleDBClient(new PropertiesCredentials(
						propertiesStream));

				// reread stream
				propertiesStream = Project.class
						.getResourceAsStream("/clouddatamigration.properties");
				s3 = new AmazonS3Client(new PropertiesCredentials(
						propertiesStream));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// this type parameter is just there to get the class inside of methods
	protected Class<T> persistentClass;

	protected Logger logger = LogManager.getLogger("Persistence");

	@SuppressWarnings("unchecked")
	public AbstractModel() {
		try {
			this.persistentClass = (Class<T>) ((java.lang.reflect.ParameterizedType) getClass()
					.getGenericSuperclass()).getActualTypeArguments()[0];
		} catch (Exception e) {
			// cglib messes with the classes by enhacing them ;(
			this.persistentClass = (Class<T>) ((java.lang.reflect.ParameterizedType) ((Class<T>) getClass()
					.getGenericSuperclass()).getGenericSuperclass())
					.getActualTypeArguments()[0];
		}
	}

	public abstract String getId();

	public abstract Map<String, String> getFieldValues();

	public T save(T object) {
		if (useJpa) {
			em.persist(object);
		} else if (!useJpa && !useSimpleDB) {
			PersistenceManager pm = pmf.getPersistenceManager();
			Transaction tx = pm.currentTransaction();
			try {
				tx.begin();
				object = pm.makePersistent(object);
				object = pm.detachCopy(object);
				tx.commit();
			} finally {
				if (tx.isActive()) {
					tx.rollback();
				}
				pm.close();
			}
		} else if (useSimpleDB) {
			ArrayList<ReplaceableAttribute> attributes = new ArrayList<ReplaceableAttribute>();
			for (String name : getFieldValues().keySet()) {
				attributes.add(new ReplaceableAttribute(name, getFieldValues()
						.get(name), true));
			}
			PutAttributesRequest putAttributesRequest = new PutAttributesRequest(
					PREFIX + persistentClass.getSimpleName(), getId(),
					attributes);
			sdb.putAttributes(putAttributesRequest);
		}
		return object;
	}

	public T findByID(String id) {
		if (useJpa) {
			javax.persistence.Query query = em.createQuery("select o from "
					+ persistentClass.getName() + " o where o.id = :id");
			query.setParameter("id", id);
			@SuppressWarnings("unchecked")
			List<T> obs = (List<T>) query.getResultList();
			return obs.get(0);
		} else if (!useJpa && !useSimpleDB) {
			PersistenceManager pm = pmf.getPersistenceManager();
			pm.getFetchPlan().setMaxFetchDepth(3);
			Transaction tx = pm.currentTransaction();
			try {
				tx.begin();
				T object = (T) pm.getObjectById(persistentClass, id);
				object = pm.detachCopy(object);
				tx.commit();
				return object;
			} finally {
				if (tx.isActive()) {
					tx.rollback();
				}
				pm.close();
			}
		} else if (useSimpleDB) {
			if (cacheById.containsKey(persistentClass.getSimpleName())) {
				Map<String, Object> idList = cacheById.get(persistentClass
						.getSimpleName());
				if (idList.containsKey(id)) {
					@SuppressWarnings("unchecked")
					T t = (T) idList.get(id);
					System.out.println("Cache Hit: " + t);
					return t;
				}
			}
			GetAttributesRequest getAttributesRequest = new GetAttributesRequest(
					PREFIX + persistentClass.getSimpleName(), id);
			GetAttributesResult attributesResult = sdb
					.getAttributes(getAttributesRequest);
			List<Attribute> attributes = attributesResult.getAttributes();
			T t = parseResultToObject(attributes);
			System.out.println("Retrieved object of type "
					+ persistentClass.getSimpleName() + " (" + t + ").");
			if (cacheById.containsKey(persistentClass.getSimpleName())) {
				Map<String, Object> idList = cacheById.get(persistentClass
						.getSimpleName());
				idList.put(id, t);
			} else {
				Map<String, Object> idList = new HashMap<String, Object>();
				idList.put(id, t);
				cacheById.put(persistentClass.getSimpleName(), idList);
			}
			return t;
		} else {
			throw new RuntimeException("Datastore not set or supported.");
		}
	}

	protected T parseResultToObject(List<Attribute> attributes) {
		T t = null;
		try {
			t = persistentClass.newInstance();
			@SuppressWarnings("rawtypes")
			Class[] paramTypes = new Class[1];
			paramTypes[0] = String.class;
			for (Attribute attribute : attributes) {
				Class<T> aClass = persistentClass;
				String methodName = "set"
						+ attribute.getName().substring(0, 1).toUpperCase()
						+ attribute.getName().substring(1);
				for (Field field : aClass.getDeclaredFields()) {
					if (attribute.getName().equals(
							field.getAnnotation(Persistent.class).column())) {
						methodName = "set"
								+ field.getName().substring(0, 1).toUpperCase()
								+ field.getName().substring(1);
					}
				}
				Method m = null;
				try {
					m = aClass.getMethod(methodName, paramTypes);
				} catch (NoSuchMethodException nsme) {
					nsme.printStackTrace();
				}
				if (m != null) {
					try {
						if (attribute.getValue().startsWith("s3://")) {
							// download content from S3 using a custom link
							String[] bucketAndKey = attribute.getValue().split(
									"s3://")[1].split("/");
							S3ObjectInputStream is = s3.getObject(
									bucketAndKey[0].toLowerCase(), bucketAndKey[1])
									.getObjectContent();
							m.invoke(t,
									new Scanner(is, "UTF-8")
											.useDelimiter("\\A").next());
						} else {
							m.invoke(t, attribute.getValue());
						}
					} catch (IllegalAccessException iae) {
						iae.printStackTrace();
					} catch (InvocationTargetException ite) {
						ite.printStackTrace();
					}
				} else {
					System.out.println("Method " + methodName
							+ " does not exist for "
							+ persistentClass.getSimpleName() + ".");
				}
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return t;
	}

	public Collection<T> findAll(String order) {
		if (useJpa) {
			javax.persistence.Query query = em.createQuery("select o from "
					+ persistentClass.getName() + " o"
					+ (order != null ? " order by o." + order : ""));
			@SuppressWarnings("unchecked")
			List<T> obs = (List<T>) query.getResultList();
			return obs;
		} else if (!useJpa && !useSimpleDB) {
			PersistenceManager pm = pmf.getPersistenceManager();
			pm.getFetchPlan().setMaxFetchDepth(3);
			Transaction tx = pm.currentTransaction();
			try {
				tx.begin();
				Query query = pm.newQuery(persistentClass);
				if (order != null) {
					query.setOrdering(order);
				}
				@SuppressWarnings("unchecked")
				Collection<T> object = (Collection<T>) query.execute();
				object = pm.detachCopyAll(object);
				tx.commit();
				return object;
			} finally {
				if (tx.isActive()) {
					tx.rollback();
				}
				pm.close();
			}
		} else if (useSimpleDB) {
			if (cacheList.containsKey(persistentClass.getSimpleName())) {
				@SuppressWarnings("unchecked")
				Collection<T> list = (Collection<T>) cacheList
						.get(persistentClass.getSimpleName());
				System.out.println("Cache Hit on list "
						+ persistentClass.getSimpleName());
				return list;
			} else {
				SelectRequest selectRequest = new SelectRequest(
						"SELECT * FROM `" + PREFIX
								+ persistentClass.getSimpleName() + "`");
				List<T> items = new ArrayList<T>();
				for (Item item : sdb.select(selectRequest).getItems()) {
					items.add(parseResultToObject(item.getAttributes()));
				}
				System.out.println("Retrieved " + items.size()
						+ " objects of type " + persistentClass.getSimpleName()
						+ ".");
				@SuppressWarnings("unchecked")
				Collection<Object> list = (Collection<Object>) items;
				cacheList.put(persistentClass.getSimpleName(), list);
				return items;
			}
		} else {
			throw new RuntimeException("Datastore not set or supported.");
		}
	}

	public Collection<T> findAll() {
		return findAll(null);
	}

	public void delete(T object) {
		if (useJpa) {
			em.remove(object);
		} else {
			PersistenceManager pm = pmf.getPersistenceManager();
			Transaction tx = pm.currentTransaction();
			try {
				tx.begin();
				pm.deletePersistent(object);
				tx.commit();
			} finally {
				if (tx.isActive()) {
					tx.rollback();
				}
				pm.close();
			}
		}
	}

}


text:
var inherits = require('util').inherits;
var logger = require('winston');

var NodeManager = require('./nodemanager');

/**
 * @module Core
 */

/**
 * A NodeManager that can be used by RiakCluster.
 *
 * This NodeManager does a least-commands-executing selection of RiakNodes.
 *
 * @class LeastExecutingNodeManager
 * @param {Boolean} shuffle Shuffle nodes that have same execution count.
 * @constructor
 * @extends NodeManager
 */
function LeastExecutingNodeManager(shuffle)  {
    NodeManager.call(this, 'LeastExecutingNodeManager');
    this._shuffle = shuffle;
}

inherits(LeastExecutingNodeManager, NodeManager);

LeastExecutingNodeManager.prototype.executeOnNode = function(nodes, command, previous) {
    if (nodes.length === 0) {
        logger.error("[LeastExecutingNodeManager] zero nodes for execution of command %s", command.name);
        return false;
    }

    var n = [];
    Array.prototype.push.apply(n, nodes);
    n.sort(function (a, b) {
        return a.executeCount - b.executeCount;
    });

    var i = 0;
    if (this._shuffle) {
        var j = 0;
        for (i = 0; i < n.length - 1; i++) {
            j = i + 1;
            if (n[j].executeCount > n[i].executeCount) {
                break;
            }
        }
        if (j > 1) {
            var s = shuffleArray(n.slice(0, j));
            n = Array.prototype.concat(s, n.slice(j));
        }
    }

    var executing = false;
    for (i = 0; i < n.length; i++) {
        executing = this.tryExecute(n[i], command);
        if (executing) {
            break;
        }
    }
    return executing;
};

/**
 * Randomize array element order in-place.
 * Using Durstenfeld shuffle algorithm.
 * http://stackoverflow.com/a/12646864
 */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

module.exports = LeastExecutingNodeManager;


text:
<?xml version="1.0" ?>
<!--
  ~ Copyright (c) 2010-2019 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<role oid="2330f9df-83bc-4270-86fc-27fca2b616a7"
      xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3">
    <name>prize</name>
    <inducement>
        <policyRule>
            <name>pruning-gold</name>
            <policyConstraints>
                <exclusion>
                    <targetRef oid="0b3ad53e-7c1d-41d0-a447-ce94cd25c46a" type="RoleType"/>    <!-- gold -->
                </exclusion>
            </policyConstraints>
            <policyActions>
                <prune/>
            </policyActions>
        </policyRule>
    </inducement>
    <inducement>
        <policyRule>
            <name>pruning-silver</name>
            <policyConstraints>
                <exclusion>
                    <targetRef oid="ee5206f8-930a-4c85-bfee-c16e4462df23" type="RoleType"/> <!-- silver -->
                </exclusion>
            </policyConstraints>
            <policyActions>
                <prune/>
            </policyActions>
        </policyRule>
    </inducement>
    <inducement>
        <policyRule>
            <name>pruning-bronze</name>
            <policyConstraints>
                <exclusion>
                    <targetRef oid="f16f4dd7-2830-4d0a-b6ed-9fbf253dbaf3" type="RoleType"/> <!-- bronze -->
                </exclusion>
            </policyConstraints>
            <policyActions>
                <prune/>
            </policyActions>
        </policyRule>
    </inducement>
</role>


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

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

// LunAttribute A name/value pair optionally stored with the LUN. Attributes are available to callers to persist small amounts of application-specific metadata. They are in no way interpreted by ONTAP.<br/>
// Attribute names and values must be at least one byte and no more than 4091 bytes in length. The sum of the name and value lengths must be no more than 4092 bytes.
//
// swagger:model lun_attribute
type LunAttribute struct {

	// links
	Links *LunAttributeLinks `json:"_links,omitempty"`

	// lun
	Lun *LunAttributeLun `json:"lun,omitempty"`

	// The attribute name. Required in POST.
	//
	// Example: name1
	// Max Length: 4091
	// Min Length: 1
	Name string `json:"name,omitempty"`

	// The attribute value. Required in POST; valid in PATCH.
	//
	// Example: value1
	// Max Length: 4091
	// Min Length: 1
	Value string `json:"value,omitempty"`
}

// Validate validates this lun attribute
func (m *LunAttribute) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateLinks(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateLun(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateName(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateValue(formats); err != nil {
		res = append(res, err)
	}

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

func (m *LunAttribute) validateLinks(formats strfmt.Registry) error {
	if swag.IsZero(m.Links) { // not required
		return nil
	}

	if m.Links != nil {
		if err := m.Links.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links")
			}
			return err
		}
	}

	return nil
}

func (m *LunAttribute) validateLun(formats strfmt.Registry) error {
	if swag.IsZero(m.Lun) { // not required
		return nil
	}

	if m.Lun != nil {
		if err := m.Lun.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("lun")
			}
			return err
		}
	}

	return nil
}

func (m *LunAttribute) validateName(formats strfmt.Registry) error {
	if swag.IsZero(m.Name) { // not required
		return nil
	}

	if err := validate.MinLength("name", "body", m.Name, 1); err != nil {
		return err
	}

	if err := validate.MaxLength("name", "body", m.Name, 4091); err != nil {
		return err
	}

	return nil
}

func (m *LunAttribute) validateValue(formats strfmt.Registry) error {
	if swag.IsZero(m.Value) { // not required
		return nil
	}

	if err := validate.MinLength("value", "body", m.Value, 1); err != nil {
		return err
	}

	if err := validate.MaxLength("value", "body", m.Value, 4091); err != nil {
		return err
	}

	return nil
}

// ContextValidate validate this lun attribute based on the context it is used
func (m *LunAttribute) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateLinks(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateLun(ctx, formats); err != nil {
		res = append(res, err)
	}

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

func (m *LunAttribute) contextValidateLinks(ctx context.Context, formats strfmt.Registry) error {

	if m.Links != nil {
		if err := m.Links.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links")
			}
			return err
		}
	}

	return nil
}

func (m *LunAttribute) contextValidateLun(ctx context.Context, formats strfmt.Registry) error {

	if m.Lun != nil {
		if err := m.Lun.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("lun")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *LunAttribute) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *LunAttribute) UnmarshalBinary(b []byte) error {
	var res LunAttribute
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// LunAttributeLinks lun attribute links
//
// swagger:model LunAttributeLinks
type LunAttributeLinks struct {

	// self
	Self *Href `json:"self,omitempty"`
}

// Validate validates this lun attribute links
func (m *LunAttributeLinks) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateSelf(formats); err != nil {
		res = append(res, err)
	}

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

func (m *LunAttributeLinks) validateSelf(formats strfmt.Registry) error {
	if swag.IsZero(m.Self) { // not required
		return nil
	}

	if m.Self != nil {
		if err := m.Self.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links" + "." + "self")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this lun attribute links based on the context it is used
func (m *LunAttributeLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateSelf(ctx, formats); err != nil {
		res = append(res, err)
	}

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

func (m *LunAttributeLinks) contextValidateSelf(ctx context.Context, formats strfmt.Registry) error {

	if m.Self != nil {
		if err := m.Self.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("_links" + "." + "self")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *LunAttributeLinks) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *LunAttributeLinks) UnmarshalBinary(b []byte) error {
	var res LunAttributeLinks
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// LunAttributeLun The LUN for which the attribute is set.
//
// swagger:model LunAttributeLun
type LunAttributeLun struct {

	// links
	Links *LunAttributeLunLinks `json:"_links,omitempty"`

	// The unique identifier of the LUN.
	//
	// Example: 4ea7a442-86d1-11e0-ae1c-123478563412
	// Read Only: true
	UUID string `json:"uuid,omitempty"`
}

// Validate validates this lun attribute lun
func (m *LunAttributeLun) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateLinks(formats); err != nil {
		res = append(res, err)
	}

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

func (m *LunAttributeLun) validateLinks(formats strfmt.Registry) error {
	if swag.IsZero(m.Links) { // not required
		return nil
	}

	if m.Links != nil {
		if err := m.Links.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("lun" + "." + "_links")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this lun attribute lun based on the context it is used
func (m *LunAttributeLun) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateLinks(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateUUID(ctx, formats); err != nil {
		res = append(res, err)
	}

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

func (m *LunAttributeLun) contextValidateLinks(ctx context.Context, formats strfmt.Registry) error {

	if m.Links != nil {
		if err := m.Links.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("lun" + "." + "_links")
			}
			return err
		}
	}

	return nil
}

func (m *LunAttributeLun) contextValidateUUID(ctx context.Context, formats strfmt.Registry) error {

	if err := validate.ReadOnly(ctx, "lun"+"."+"uuid", "body", string(m.UUID)); err != nil {
		return err
	}

	return nil
}

// MarshalBinary interface implementation
func (m *LunAttributeLun) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *LunAttributeLun) UnmarshalBinary(b []byte) error {
	var res LunAttributeLun
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// LunAttributeLunLinks lun attribute lun links
//
// swagger:model LunAttributeLunLinks
type LunAttributeLunLinks struct {

	// self
	Self *Href `json:"self,omitempty"`
}

// Validate validates this lun attribute lun links
func (m *LunAttributeLunLinks) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateSelf(formats); err != nil {
		res = append(res, err)
	}

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

func (m *LunAttributeLunLinks) validateSelf(formats strfmt.Registry) error {
	if swag.IsZero(m.Self) { // not required
		return nil
	}

	if m.Self != nil {
		if err := m.Self.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("lun" + "." + "_links" + "." + "self")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this lun attribute lun links based on the context it is used
func (m *LunAttributeLunLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateSelf(ctx, formats); err != nil {
		res = append(res, err)
	}

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

func (m *LunAttributeLunLinks) contextValidateSelf(ctx context.Context, formats strfmt.Registry) error {

	if m.Self != nil {
		if err := m.Self.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("lun" + "." + "_links" + "." + "self")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *LunAttributeLunLinks) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *LunAttributeLunLinks) UnmarshalBinary(b []byte) error {
	var res LunAttributeLunLinks
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
package com.remotecraft.app.domain.service;

import com.remotecraft.app.domain.NetworkAddress;
import com.remotecraft.app.domain.provider.NetworkActionProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

@RunWith(MockitoJUnitRunner.class)
public class SearchServerServiceTest {

  private SearchServerService searchServerService;

  @Mock private NetworkActionProvider mockNetworkActionProvider;

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    searchServerService = new SearchServerService(mockNetworkActionProvider);
  }

  @Test
  public void shouldSearchServer() throws Exception {
    searchServerService.searchServer();

    verify(mockNetworkActionProvider, times(1)).searchServer();
    verifyNoMoreInteractions(mockNetworkActionProvider);
  }

  @Test
  public void shouldSearchServerForNetworkAddress() throws Exception {
    NetworkAddress mockNetworkAddress = mock(NetworkAddress.class);

    searchServerService.searchServer(mockNetworkAddress);

    verify(mockNetworkActionProvider, times(1)).searchServer(mockNetworkAddress);
    verifyNoMoreInteractions(mockNetworkActionProvider);
  }
}


text:
package org.lee.android.doodles;

import android.content.Context;

public class AppContext {
	private static AppContext instance = null;
	private Context context = null;
	private static boolean running = false;

	public static synchronized AppContext getInstance() {
		if (instance == null) {
			instance = new AppContext();
			running = true;
		}
		return instance;
	}

	public boolean isRunning() {
		return running;
	}

	public void destroy() {
		running = false;
	}

	public static Context getContext() {
		return getInstance().context;
	}

	public void setContext(Context context) {
		running = true;
		if (context != null && this.context != context) {
			this.context = context;
			initApp();
		}
	}

	private void initApp() {

	}

}


text:
package org.sparkcommerce.common.web.resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sparkcommerce.common.classloader.release.ThreadLocalManager;
import org.sparkcommerce.common.extension.ExtensionResultHolder;
import org.sparkcommerce.common.resource.GeneratedResource;
import org.sparkcommerce.common.resource.service.ResourceBundlingService;
import org.sparkcommerce.common.resource.service.ResourceMinificationService;
import org.sparkcommerce.common.web.SparkRequestContext;
import org.sparkcommerce.common.web.SparkSandBoxResolver;
import org.sparkcommerce.common.web.SparkSiteResolver;
import org.sparkcommerce.common.web.SparkThemeResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.util.StreamUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SparkResourceHttpRequestHandler extends ResourceHttpRequestHandler {
    private static final Log LOG = LogFactory.getLog(SparkResourceHttpRequestHandler.class);

    // XML Configured generated resource handlers
    protected List<AbstractGeneratedResourceHandler> handlers;
    protected List<AbstractGeneratedResourceHandler> sortedHandlers;

    @javax.annotation.Resource(name = "blResourceBundlingService")
    protected ResourceBundlingService bundlingService;

    @javax.annotation.Resource(name = "blResourceMinificationService")
    protected ResourceMinificationService minifyService;

    @javax.annotation.Resource(name = "blResourceRequestExtensionManager")
    protected ResourceRequestExtensionManager extensionManager;

    @javax.annotation.Resource(name = "blSiteResolver")
    protected SparkSiteResolver siteResolver;

    @javax.annotation.Resource(name = "blSandBoxResolver")
    protected SparkSandBoxResolver sbResolver;

    @javax.annotation.Resource(name = "blThemeResolver")
    protected SparkThemeResolver themeResolver;

    @Value("${global.admin.prefix}")
    protected String globalAdminPrefix;

    @Value("${global.admin.url}")
    protected String globalAdminUrl;

    /**
     * Checks to see if the requested path corresponds to a registered bundle. If so, returns the generated bundle.
     * Otherwise, checks to see if any of the configured GeneratedResourceHandlers can handle the given request.
     * If neither of those cases match, delegates to the normal ResourceHttpRequestHandler
     */
    @Override
	protected Resource getResource(HttpServletRequest request) {
        establishThinRequestContext();
        return getResourceInternal(request);
    }

	protected Resource getResourceInternal(HttpServletRequest request) {
		String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        if (bundlingService.hasBundle(path)) {
            return bundlingService.getBundle(path);
        }

        Resource unminifiedResource = null;

        if (sortedHandlers == null && handlers != null) {
            sortHandlers();
        }

        if (sortedHandlers != null) {
            for (AbstractGeneratedResourceHandler handler : sortedHandlers) {
                if (handler.canHandle(path)) {
                    unminifiedResource = handler.getResource(path, getLocations());
                    break;
                }
            }
        }

        if (unminifiedResource == null) {
            ExtensionResultHolder erh = new ExtensionResultHolder();
            extensionManager.getProxy().getOverrideResource(path, erh);
            if (erh.getContextMap().get(ResourceRequestExtensionHandler.RESOURCE_ATTR) != null) {
                unminifiedResource = (Resource) erh.getContextMap().get(ResourceRequestExtensionHandler.RESOURCE_ATTR);
            }
        }

        if (unminifiedResource == null) {
            unminifiedResource = super.getResource(request);
        }

        try {
            if (!minifyService.getEnabled() || !minifyService.getAllowSingleMinification()) {
                return unminifiedResource;
            }
        } finally {
            ThreadLocalManager.remove();
        }

        LOG.warn("Minifying individual file - this should only be used in development to trace down particular " +
        		 "files that are causing an exception in the minification service. The results of the minification " +
        		 "performed outside of a bundle are not stored to disk.");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = null;
        InputStream is = null;
        try {
            is = unminifiedResource.getInputStream();
            StreamUtils.copy(is, baos);
            bytes = baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                is.close();
                baos.close();
            } catch (IOException e2) {
                throw new RuntimeException("Could not close input stream", e2);
            }
        }

        LOG.debug("Attempting to minifiy " + unminifiedResource.getFilename());
        byte[] minifiedBytes = minifyService.minify(unminifiedResource.getFilename(), bytes);

        return new GeneratedResource(minifiedBytes, unminifiedResource.getFilename());
    }

    public boolean isBundleRequest(HttpServletRequest request) {
		String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        return bundlingService.hasBundle(path);
    }

    /**
     * @return a clone of the locations list that is in {@link ResourceHttpRequestHandler}. Note that we must use
     * reflection to access this field as it is marked private.
     */
    @SuppressWarnings("unchecked")
    public List<Resource> getLocations() {
        try {
            List<Resource> locations = (List<Resource>) FieldUtils.readField(this, "locations", true);
            return new ArrayList<Resource>(locations);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    protected void establishThinRequestContext() {
        SparkRequestContext oldBrc = SparkRequestContext.getSparkRequestContext();
        if (oldBrc == null || oldBrc.getSite() == null || oldBrc.getTheme() == null) {
            // Resolving sites and sandboxes is often dependent on having a security context present in the request.
            // For example, resolving a sandbox requires the current user to have the SC_ADMIN_USER in his Authentication.
            // For performance reasons, we do not go through the entire Spring Security filter chain on requests
            // for resources like JavaScript and CSS files. However, when theming is enabled, we potentially have to
            // resolve a specific version of the theme for a sandbox so that we can replace variables appropriately. This
            // then depends on the sandbox being resolved, which requires the Authentication object to be present.
            // We will grab the Authentication object associated with this user's session and set it on the
            // SecurityContextHolder since Spring Security will be bypassed.
            HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = req.getSession(false);
            SecurityContext ctx = readSecurityContextFromSession(session);
            if (ctx != null) {
                SecurityContextHolder.setContext(ctx);
            }

            SparkRequestContext newBrc = new SparkRequestContext();
            if (!isGlobalAdmin(req)) {
                ServletWebRequest swr = new ServletWebRequest(req);
                newBrc.setSite(siteResolver.resolveSite(swr, true));
                newBrc.setSandBox(sbResolver.resolveSandBox(swr, newBrc.getSite()));
                SparkRequestContext.setSparkRequestContext(newBrc);
                newBrc.setTheme(themeResolver.resolveTheme(swr));
            }
        }
    }

    protected boolean isGlobalAdmin(HttpServletRequest request) {
        String uri = request.getRequestURI();
        if (!StringUtils.isEmpty(globalAdminPrefix)) {
            if (globalAdminPrefix.equals(getContextName(request))) {
                return true;
            } else {
                if (!StringUtils.isEmpty(globalAdminUrl)) {
                    return uri.startsWith(globalAdminUrl);
                }
            }
        }
        return false;
    }

    protected String getContextName(HttpServletRequest request) {
        String contextName = request.getServerName();
        int pos = contextName.indexOf('.');
        if (pos >= 0) {
            contextName = contextName.substring(0, contextName.indexOf('.'));
        }
        return contextName;
    }

    // **NOTE** This method is lifted from HttpSessionSecurityContextRepository
    protected SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
        if (httpSession == null) {
            return null;
        }

        Object ctxFromSession = httpSession.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        if (ctxFromSession == null) {
            return null;
        }

        if (!(ctxFromSession instanceof SecurityContext)) {
            return null;
        }

        return (SecurityContext) ctxFromSession;
    }

    protected void sortHandlers() {
        sortedHandlers = new ArrayList<AbstractGeneratedResourceHandler>(handlers);
        Collections.sort(sortedHandlers, new Comparator<AbstractGeneratedResourceHandler>() {
            @Override
            public int compare(AbstractGeneratedResourceHandler o1, AbstractGeneratedResourceHandler o2) {
                return new Integer(o1.getOrder()).compareTo(o2.getOrder());
            }
        });
    }

    /* *********** */
    /* BOILERPLATE */
    /* *********** */

    public List<AbstractGeneratedResourceHandler> getHandlers() {
        if (sortedHandlers == null && handlers != null) {
            sortHandlers();
        }
        return sortedHandlers;
    }

    public void setHandlers(List<AbstractGeneratedResourceHandler> handlers) {
        this.handlers = handlers;
    }

}


text:
#ifndef Dictionary_h
#define Dictionary_h

#include "bindings/core/v8/ExceptionMessages.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/Nullable.h"
#include "bindings/core/v8/ScriptValue.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8BindingMacros.h"
#include "core/CoreExport.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/Vector.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/WTFString.h"
#include <v8.h>

namespace blink {

// Dictionary class provides ways to retrieve property values as C++ objects
// from a V8 object. Instances of this class must not outlive V8's handle scope
// because they hold a V8 value without putting it on persistent handles.
class CORE_EXPORT Dictionary final {
    DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
public:
    Dictionary();
    Dictionary(const v8::Local<v8::Value>& options, v8::Isolate*, ExceptionState&);
    ~Dictionary();

    Dictionary& operator=(const Dictionary&);

    bool isObject() const;
    bool isUndefinedOrNull() const;

    bool get(const String&, Dictionary&) const;
    bool get(const String&, v8::Local<v8::Value>&) const;

    v8::Local<v8::Value> v8Value() const { return m_options; }

    bool getOwnPropertiesAsStringHashMap(HashMap<String, String>&) const;
    bool getPropertyNames(Vector<String>&) const;

    bool hasProperty(const String&) const;

    v8::Isolate* isolate() const { return m_isolate; }
    v8::Local<v8::Context> v8Context() const
    {
        ASSERT(m_isolate);
        return m_isolate->GetCurrentContext();
    }

    bool getKey(const String& key, v8::Local<v8::Value>&) const;

private:
    bool toObject(v8::Local<v8::Object>&) const;

    v8::Local<v8::Value> m_options;
    v8::Isolate* m_isolate;
    ExceptionState* m_exceptionState;
};

template<>
struct NativeValueTraits<Dictionary> {
    static inline Dictionary nativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState)
    {
        return Dictionary(value, isolate, exceptionState);
    }
};

// DictionaryHelper is a collection of static methods for getting or
// converting a value from Dictionary.
struct DictionaryHelper {
    STATIC_ONLY(DictionaryHelper);
    template <typename T>
    static bool get(const Dictionary&, const String& key, T& value);
    template <typename T>
    static bool get(const Dictionary&, const String& key, T& value, bool& hasValue);
    template <typename T>
    static bool get(const Dictionary&, const String& key, T& value, ExceptionState&);
    template <typename T>
    static bool getWithUndefinedOrNullCheck(const Dictionary& dictionary, const String& key, T& value)
    {
        v8::Local<v8::Value> v8Value;
        if (!dictionary.getKey(key, v8Value) || isUndefinedOrNull(v8Value))
            return false;
        return DictionaryHelper::get(dictionary, key, value);
    }
    template <template <typename> class PointerType, typename T>
    static bool get(const Dictionary&, const String& key, PointerType<T>& value);
};

}

#endif // Dictionary_h


text:
module.exports = function (noty, sockets) {
  // display a warning if the server has not communicated in this many seconds
  var SECONDS = 30;
  var timeoutWarning;

  // (re)set a countdown about the server not sending any data
  function resetTimeout () {
    if (timeoutWarning !== undefined) {
      clearTimeout(timeoutWarning);
    }
    timeoutWarning = setTimeout(function () {
      noty.update('warning',
        'The server has not sent updates in the last ' +
        SECONDS + ' seconds.');
    }, 1000 * SECONDS);
  }

  // clear any notifications and reset the countdown
  function reset () {
    noty.clear();
    resetTimeout();
  }

  return {
    initialize: function () {
      // when the server sends any sort of data, clear communication errors
      sockets.on('update', reset);

      // if the server sent an error, display a notification
      sockets.on('error', function (data) {
        resetTimeout();
        noty.update('warning', 'Error communicating with PagerDuty: ' + data);
      });
    }
  };
};


text:
package org.apache.camel.component.mina;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

/**
 * @version
 */
public class MinaFileTcpTest extends BaseMinaTest {

    @Test
    public void testMinaRoute() throws Exception {
        MockEndpoint endpoint = getMockEndpoint("mock:results");
        endpoint.expectedMessageCount(1);
        endpoint.message(0).body().startsWith("Hello World");

        assertMockEndpointsSatisfied();
    }

    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                // lets setup a server
                from("mina:tcp://localhost:{{port}}?sync=false&textline=true")
                    .to("mock:results");

                from("file:src/test/data?noop=true&fileName=message1.txt").
                    to("mina:tcp://localhost:{{port}}?sync=false&textline=true");
            }
        };
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiaryAPI.Interfaces
{
    public interface IPostCommentsProcessor: ICommentProcessor, IPostProcessor
    {
    }
}


text:
#include "config.h"
#include <unistd.h>

#include "mgt/mgt.h"
#include "waiter/mgt_waiter.h"

static const struct choice waiter_choice[] = {
#define WAITER(nm) { #nm, &waiter_##nm },
#include "tbl/waiters.h"
	{ NULL,		NULL}
};

struct waiter_impl const *waiter;

void
Wait_config(const char *arg)
{

	ASSERT_MGT();

	if (arg != NULL)
		waiter = MGT_Pick(waiter_choice, arg, "waiter");
	else
		waiter = waiter_choice[0].ptr;
}


text:
layout: nil
---
<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title>Swapneel</title>
  <link href="http://brainattic.in/"/>
  <link type="application/atom+xml" rel="self" href="http://brainattic.in/atom.xml"/>
  <updated>{{ site.time | date_to_xmlschema }}</updated>
  <id>http://brainattic.in/</id>
  <author>
    <name>Swapneel</name>
  </author>

  {% for post in site.posts %}
  <entry>
    <id>http://brainattic.in{{ post.id }}</id>
    <link type="text/html" rel="alternate" href="http://brainattic.in{{ post.url }}"/>
    <title>{{ post.title }}</title>
    <published>{{ post.date | date_to_xmlschema }}</published>
    <updated>{{ post.date | date_to_xmlschema }}</updated>
    <author>
      <name>Swapneel</name>
    </author>
    <content type="html">{{ post.content | xml_escape }}</content>
  </entry>
  {% endfor %}

</feed>


text:
package net.community.chest.apache.httpclient.jmx;

import java.io.IOException;
import java.io.StreamCorruptedException;
import java.net.ConnectException;
import java.util.Collection;

import net.community.chest.apache.httpclient.HttpClientUtils;
import net.community.chest.jmx.JMXErrorHandler;
import net.community.chest.jmx.JMXProtocol;
import net.community.chest.jmx.dom.MBeanEntryDescriptor;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class JMXSession extends BaseHttpAccessor {
    public JMXSession ()
    {
        super();
    }

    private JMXErrorHandler    _eh;
    public JMXErrorHandler getJMXErrorHandler ()
    {
        return _eh;
    }

    public void setJMXErrorHandler (JMXErrorHandler eh)
    {
        _eh = eh;
    }
    /*
     * @see net.community.chest.net.proto.jmx.JMXAccessor#getValues(java.lang.String, java.util.Collection, boolean)
     */
    @Override
    public Collection<? extends MBeanEntryDescriptor> getValues (
            final String                                        domain,
            final Collection<? extends MBeanEntryDescriptor>     mbl,
            final boolean                                         includeNulls)
        throws IOException
    {
        final int                    numMBeans=(null == mbl) ? 0 : mbl.size();
        final HostConfiguration        host=getHostConfiguration();
        if (null == host)
            throw new ConnectException("getValues(" + numMBeans + "/" + domain + "/" + JMXProtocol.NULLS_PARAM + "=" + includeNulls + ") no host configuration specified");

        // NOTE !!! we run the query even if no MBean(s) requested - just as a live-check
        final Collection<NameValuePair>    npl=AccessorUtils.buildGetRequest(domain, includeNulls);
        final int                        numParams=(null == npl) ? 0 : npl.size();
        final NameValuePair[]            qp=(numParams <= 0) ? null : npl.toArray(new NameValuePair[numParams]);
        if ((null == qp) || (qp.length <= 0))
            throw new StreamCorruptedException("getValues(" + numMBeans + "/" + domain+ "/" + JMXProtocol.NULLS_PARAM + "=" + includeNulls + ") no query parameters");

        final PostMethod            gm=new PostMethod();
        gm.setFollowRedirects(false);
        gm.setPath(getAccessPath());
        gm.setQueryString(qp);

        final String                reqData=JMXProtocol.buildDescriptorsDocument(mbl);
        final StringRequestEntity    reqEntity=new StringRequestEntity(reqData, "text/xml", "UTF-8");
        gm.setRequestEntity(reqEntity);

        final long    qStart=System.currentTimeMillis();
        try
        {
            final HttpClient    hc=getClientInstance();
            final int            stCode=hc.executeMethod(host, gm);
            final long            qEnd=System.currentTimeMillis(), qDuration=qEnd - qStart;
            if (!HttpClientUtils.isOKHttpRspCode(stCode))
            {
                final byte[]    rspBody=gm.getResponseBody();    // MUST call this to flush the response regardless of status code
                throw new StreamCorruptedException("getValues(" + numMBeans + "/" + domain + "/" + JMXProtocol.NULLS_PARAM + "=" + includeNulls + ") bad response code (" + stCode + ")[" + ((null == rspBody) ? 0 : rspBody.length) + " bytes] after " + qDuration + " msec.: " + HttpClientUtils.getMethodStatusLine(gm));
            }

            try
            {
                return AccessorUtils.convertJMXServletResponse(gm, getJMXErrorHandler());
            }
            catch(Exception e)
            {
                if (e instanceof IOException)
                    throw (IOException) e;

                throw new StreamCorruptedException("getValues(" + numMBeans + "/" + JMXProtocol.NULLS_PARAM + "=" + includeNulls + ") " + e.getClass().getName() + " while converting response: " + e.getMessage());
            }
        }
        finally
        {
            gm.releaseConnection();
        }
    }
    /*
     * @see net.community.chest.net.proto.jmx.JMXAccessor#list(java.lang.String, java.lang.String, boolean, boolean, boolean, boolean, boolean)
     */
    @Override
    public Collection<? extends MBeanEntryDescriptor> list (final String    name,
                                                            final String    domain,
                                                            final boolean    withAttributes,
                                                            final boolean    withValues,
                                                            final boolean    includeNulls,
                                                            final boolean    withOperations,
                                                            final boolean    withParameters)
        throws IOException
    {
        final HostConfiguration        host=getHostConfiguration();
        if (null == host)
            throw new ConnectException("list(" + name + "/" + domain + ") no host configuration specified");

        final Collection<NameValuePair>    npl=
            AccessorUtils.buildListRequest(name, domain, withAttributes, withValues, includeNulls, withOperations, withParameters);
        final int                        numParams=(null == npl) ? 0 : npl.size();
        final NameValuePair[]            qp=(numParams <= 0) ? null : npl.toArray(new NameValuePair[numParams]);
        if ((null == qp) || (qp.length <= 0))
            throw new StreamCorruptedException("list(" + name + "/" + domain + ") no query parameters");

        final GetMethod    gm=new GetMethod();
        gm.setFollowRedirects(true);
        gm.setPath(getAccessPath());
        gm.setQueryString(qp);

        final long    qStart=System.currentTimeMillis();
        try
        {
            final HttpClient    hc=getClientInstance();
            final int            stCode=hc.executeMethod(host, gm);
            final long            qEnd=System.currentTimeMillis(), qDuration=qEnd - qStart;
            if (!HttpClientUtils.isOKHttpRspCode(stCode))
            {
                final byte[]    rspBody=gm.getResponseBody();    // MUST call this to flush the response regardless of status code
                throw new StreamCorruptedException("list(" + name + "/" + domain + ") bad response code (" + stCode + ")[" + ((null == rspBody) ? 0 : rspBody.length) + " bytes] after " + qDuration + " msec.: " + HttpClientUtils.getMethodStatusLine(gm));
            }

            try
            {
                return AccessorUtils.convertJMXServletResponse(gm, getJMXErrorHandler());
            }
            catch(Exception e)
            {
                if (e instanceof IOException)
                    throw (IOException) e;

                throw new StreamCorruptedException("list(" + name + "/" + JMXProtocol.ATTRIBUTES_PARAM + "=" + withAttributes + "/" + JMXProtocol.VALUES_PARAM + "=" + withValues + "/" + JMXProtocol.NULLS_PARAM + "=" + includeNulls + ") " + e.getClass().getName() + " while converting response: " + e.getMessage());
            }
        }
        finally
        {
            gm.releaseConnection();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Common;
using Common.ExtensionMethods;
using SmaSTraDesigner.BusinessLogic.codegeneration.loader;
using SmaSTraDesigner.BusinessLogic.codegeneration.loader.specificloaders;
using SmaSTraDesigner.BusinessLogic.nodes;
using SmaSTraDesigner.BusinessLogic.utils;

namespace SmaSTraDesigner.BusinessLogic.codegeneration.javacodegenerator
{
    class NewJavaGenerator
    {

        /// <summary>
        /// The tree to use for generation.
        /// </summary>
        private readonly TransformationTree _tree;

        /// <summary>
        /// All the code extension stuff needed.
        /// </summary>
        private readonly CodeExtension _codeExtension = new CodeExtension();

        /// <summary>
        /// Creates a new Generator.
        /// </summary>
        /// <param name="tree">To generate with.</param>
        public NewJavaGenerator(TransformationTree tree)
        {
            this._tree = tree;
        }

        /// <summary>
        /// Returns true if the Tree is valid for serialization.
        /// </summary>
        /// <returns>true if valid for building.</returns>
        public bool IsValidTree()
        {
            return IsValidTree(_tree.OutputNode, new List<Node>());
        }

        private bool IsValidTree(Node current, ICollection<Node> visited)
        {
            //Found a already visited node:
            if (visited.Contains(current))
            {
                return true;
            }

            //Find an empty input!
            if(current is OutputNode)
            {
                //Output node has to be handled seperately!
                if (current.InputNodes[0] == null) return false;
            }
            else
            {
                //No-Output node!
                for (var i = 0; i < current.InputNodes.Count(); i++)
                {
                    var inputNode = current.InputNodes[i];
                    var data = current.InputIOData[i];
                    if (inputNode == null && !data.IsSet())
                    {
                        return false;
                    }
                }
            }

            visited.Add(current);
            return current.InputNodes.NonNull().All(n => IsValidTree(current, visited));
        }

        /// <summary>
        /// Creates the Java Class and all it's dependencies at the destination
        /// </summary>
        /// <param name="destinationFolder">To create at.</param>
        /// <param name="name">To use for creation</param>
        public void CreateJavaSource(string destinationFolder, string name)
        {
            if (!name.EndsWith(".java")) name += ".java";

            //Little hack, since the visited list is populated!
            var rootNode = _tree.OutputNode;
            var nodes = new List<Node>();
            if (!IsValidTree(rootNode, nodes))
            {
                throw new InvalidTreeExection();
            }

            //Set the root node:
            var root = _tree.OutputNode.InputNodes[0];
            if (root is CombinedNode) root = (root as CombinedNode).outputNode;

            _codeExtension.RootNode = root;
            _codeExtension.Package = "Test";

            //Get our Output type.
            _codeExtension.OutputType = rootNode.InputNodes[0].Class.OutputType;
            _codeExtension.ClassName = name.RemoveAll(".java");

            //Generate the Traverse Data:
            var stack = new Stack<QueueStatus>();
            var executeStack = new Stack<Node>();

            stack.Push(new QueueStatus(_tree.OutputNode, 0));
            executeStack.Push(root);

            //Get the loader for generating.
            var loader = Singleton<NodeLoader>.Instance;

            //Pre-Process the Stack:
            while (!stack.Empty())
            {
                var current = stack.Pop();
                if(current == null) { break;  } //Should not happen! Safetynet!

                var index = current.Index;
                var node = current.Node.InputNodes[index];

                //Check for combined nodes:
                if (node is CombinedNode)
                {
                    node = (node as CombinedNode).outputNode;
                    executeStack.Push(node);
                }

                //Add next all to Stack:
                node.InputNodes
                    .ForEachNonNull((n, i) => {
                        //Prevent doubles:
                        var status = new QueueStatus(n, i);
                        if (stack.Contains(status)) return;

                        stack.Push(new QueueStatus(node, i));
                        executeStack.Push(node.InputNodes[i]);
                    });
            }

            //Now lets execute!
            while (!executeStack.Empty())
            {
                var next = executeStack.Pop();
                if (next == null) continue;

                //Now really process:
                loader.CreateCode(next, _codeExtension);
            }

            //Build the rest:
            var sensorVars = _codeExtension.BuildSensorDataVars();
            var transVars = _codeExtension.BuildTransformDataVars();
            var initCode = _codeExtension.BuildInitCode();
            var startCode = _codeExtension.BuildStartCode();
            var stopCode = _codeExtension.BuildStopCode();
            var proxyPropertyCode = _codeExtension.BuildProxyPropertyCode();
            var transformations = _codeExtension.BuildTransformations();

            var theCode = ClassTemplates.GenerateTotal(
                _codeExtension.BuildPackage(),
                _codeExtension.BuildImports(),
                _codeExtension.BuildClassName(),
                _codeExtension.BuildOutputType(),
                initCode,
                sensorVars,
                transVars,
                startCode,
                stopCode,
                proxyPropertyCode,
                transformations
                );

            var exporter = Singleton<CodeExporter>.Instance;
            exporter.save(destinationFolder, theCode, _codeExtension);
        }

    }

    public class InvalidTreeExection : Exception
    {
        public InvalidTreeExection() : base("Tree is not valid") { }
    }

    class QueueStatus
    {
        public Node Node { get; set; }
        public int Index { get; set; }

        public QueueStatus(Node node, int index)
        {
            this.Node = node;
            this.Index = index;
        }

        public override bool Equals(object obj)
        {
            if (obj is QueueStatus) return (obj as QueueStatus).Node == Node;
            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return Node.GetHashCode();
        }
    }

}


text:
@interface DDGAppDelegate : UIResponder <UIApplicationDelegate>
@end


text:
package org.ethereum.net.eth;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.ethereum.core.Block;
import org.ethereum.core.Genesis;
import org.ethereum.core.ImportResult;
import org.ethereum.core.Transaction;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.core.Blockchain;
import org.ethereum.manager.WorldManager;
import org.ethereum.net.BlockQueue;
import org.ethereum.net.MessageQueue;
import org.ethereum.net.message.ReasonCode;
import org.ethereum.net.rlpx.discover.NodeStatistics;
import org.ethereum.net.server.Channel;
import org.ethereum.util.ByteUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import org.ethereum.util.FastByteComparisons;
import org.ethereum.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

import java.util.*;

import static org.ethereum.config.SystemProperties.CONFIG;
import static org.ethereum.net.message.StaticMessages.GET_TRANSACTIONS_MESSAGE;
import static org.ethereum.util.ByteUtil.wrap;

/**
 * Process the messages between peers with 'eth' capability on the network.
 *

 * Peers with 'eth' capability can send/receive:
 *

 *
STATUS               :   Announce their status to the peer

 *
GET_TRANSACTIONS     :   Request a list of pending transactions

 *
TRANSACTIONS         :   Send a list of pending transactions

 *
GET_BLOCK_HASHES     :   Request a list of known block hashes

 *
BLOCK_HASHES         :   Send a list of known block hashes

 *
GET_BLOCKS           :   Request a list of blocks

 *
BLOCKS               :   Send a list of blocks

 *

 */
@Component
@Scope("prototype")
public class EthHandler extends SimpleChannelInboundHandler<EthMessage> {

    private final static Logger loggerSync = LoggerFactory.getLogger("sync");
    private final static Logger loggerNet = LoggerFactory.getLogger("net");

    public final static byte VERSION = 60;

    private static final int NO_MORE_BLOCKS_THRESHOLD = 5;
    private int noMoreBlocksHits = 0;

    private MessageQueue msgQueue = null;

    private String peerId;
    private SyncState syncState = SyncState.IDLE;
    private EthState peerState = EthState.INIT;
    private long blocksLoadedCnt = 0;
    private boolean processTransactions = false;

    private boolean peerDiscoveryMode = false;

    @Autowired
    private Blockchain blockchain;

    @Autowired
    private WorldManager worldManager;

    private Channel channel;

    private List<ByteArrayWrapper> sentHashes;
    private Block lastBlock = Genesis.getInstance();
    private byte[] bestHash;
    private int maxHashesAsk;

    public EthHandler() {
        this.peerDiscoveryMode = false;
    }

    public EthHandler(MessageQueue msgQueue, boolean peerDiscoveryMode) {
        this.peerDiscoveryMode = peerDiscoveryMode;
        this.msgQueue = msgQueue;
    }

    public void activate() {
        loggerNet.info("ETH protocol activated");
        worldManager.getListener().trace("ETH protocol activated");
        sendStatus();
    }

    public void setBlockchain(Blockchain blockchain) {
        this.blockchain = blockchain;
    }

    @Override
    public void channelRead0(final ChannelHandlerContext ctx, EthMessage msg) throws InterruptedException {

        if (EthMessageCodes.inRange(msg.getCommand().asByte()))
            loggerNet.trace("EthHandler invoke: [{}]", msg.getCommand());

        worldManager.getListener().trace(String.format("EthHandler invoke: [%s]", msg.getCommand()));

        channel.getNodeStatistics().ethInbound.add();

        switch (msg.getCommand()) {
            case STATUS:
                msgQueue.receivedMessage(msg);
                processStatus((StatusMessage) msg, ctx);
                break;
            case GET_TRANSACTIONS:
                // todo: eventually get_transaction is going deprecated
//                msgQueue.receivedMessage(msg);
//                sendPendingTransactions();
                break;
            case TRANSACTIONS:
                msgQueue.receivedMessage(msg);
                processTransactions((TransactionsMessage) msg);
                // List<Transaction> txList = transactionsMessage.getTransactions();
                // for(Transaction tx : txList)
                // WorldManager.getInstance().getBlockchain().applyTransaction(null,
                // tx);
                // WorldManager.getInstance().getWallet().addTransaction(tx);
                break;
            case GET_BLOCK_HASHES:
                msgQueue.receivedMessage(msg);
                processGetBlockHashes((GetBlockHashesMessage) msg);
                break;
            case BLOCK_HASHES:
                msgQueue.receivedMessage(msg);
                processBlockHashes((BlockHashesMessage) msg);
                break;
            case GET_BLOCKS:
                msgQueue.receivedMessage(msg);
                processGetBlocks((GetBlocksMessage) msg);
                break;
            case BLOCKS:
                msgQueue.receivedMessage(msg);
                processBlocks((BlocksMessage) msg);
                break;
            case NEW_BLOCK:
                msgQueue.receivedMessage(msg);
                processNewBlock((NewBlockMessage) msg);
            default:
                break;
        }
    }

    private void processTransactions(TransactionsMessage msg) {
        if(!processTransactions) {
            return;
        }

        Set<Transaction> txSet = msg.getTransactions();
        worldManager.getBlockchain().
                addPendingTransactions(txSet);

        for (Transaction tx : txSet) {
            worldManager.getWallet().addTransaction(tx);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        loggerNet.error("Eth handling failed", cause);
        returnHashes();
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        loggerNet.debug("handlerRemoved: kill timers in EthHandler");
        returnHashes();
    }

    private void disconnect(ReasonCode reason) {
        msgQueue.disconnect(reason);
        channel.getNodeStatistics().nodeDisconnectedLocal(reason);
    }

    /**
     * Processing:
     *

     *
checking if peer is using the same genesis, protocol and network

     *
seeing if total difficulty is higher than total difficulty from all other peers

     *
send GET_BLOCK_HASHES to this peer based on bestHash

     *

     *
     * @param msg is the StatusMessage
     * @param ctx the ChannelHandlerContext
     */
    public void processStatus(StatusMessage msg, ChannelHandlerContext ctx) throws InterruptedException {

        channel.getNodeStatistics().ethHandshake(msg);
        this.bestHash = msg.getBestHash();

        try {
            if (!Arrays.equals(msg.getGenesisHash(), Blockchain.GENESIS_HASH)
                    || msg.getProtocolVersion() != VERSION) {
                loggerNet.info("Removing EthHandler for {} due to protocol incompatibility", ctx.channel().remoteAddress());
                disconnect(ReasonCode.INCOMPATIBLE_PROTOCOL);

                ctx.pipeline().remove(this); // Peer is not compatible for the 'eth' sub-protocol
                peerState = EthState.STATUS_FAILED;
                ctx.pipeline().remove(this); // Peer is not compatible for the 'eth' sub-protocol
            } else if (msg.getNetworkId() != CONFIG.networkId()) {
                peerState = EthState.STATUS_FAILED;
                disconnect(ReasonCode.NULL_IDENTITY);
            } else if (peerDiscoveryMode) {
                loggerNet.debug("Peer discovery mode: STATUS received, disconnecting...");
                disconnect(ReasonCode.REQUESTED);
                ctx.close().sync();
                ctx.disconnect().sync();
            } else {
                peerState = EthState.STATUS_SUCCEEDED;
            }
        } catch (NoSuchElementException e) {
            loggerNet.debug("EthHandler already removed");
        }
    }

    private void processBlockHashes(BlockHashesMessage blockHashesMessage) {
        if(syncState != SyncState.HASH_RETRIEVING) {
            return;
        }

        List<byte[]> receivedHashes = blockHashesMessage.getBlockHashes();
        BlockQueue chainQueue = blockchain.getQueue();

        // result is empty, peer has no more hashes
        // or peer doesn't have the best hash anymore
        if (receivedHashes.isEmpty()) {
            changeState(SyncState.DONE_HASH_RETRIEVING);
        } else {
            chainQueue.addHashes(receivedHashes);
            // store unknown hashes in queue until known hash is found
            final byte[] latestHash = blockchain.getBestBlockHash();
            byte[] foundHash = CollectionUtils.find(receivedHashes, new Predicate<byte[]>() {
                @Override
                public boolean evaluate(byte[] hash) {
                    return FastByteComparisons.compareTo(hash, 0, 32, latestHash, 0, 32) == 0;
                }
            });
            if (foundHash != null) {
                changeState(SyncState.DONE_HASH_RETRIEVING); // store unknown hashes in queue until known hash is found
                loggerSync.trace("Catch up with the hashes until: {[]}", foundHash);
            }
        }

        if(syncState == SyncState.DONE_HASH_RETRIEVING) {
            loggerSync.info("Block hashes sync completed: {} hashes in queue", chainQueue.getHashStore().size());
            chainQueue.addHash(blockchain.getBestBlockHash());
        } else {
            // no known hash has been reached
            chainQueue.logHashQueueSize();
            if(syncState == SyncState.HASH_RETRIEVING) {
                sendGetBlockHashes(); // another getBlockHashes with last received hash.
            }
        }
    }

    private void processBlocks(BlocksMessage blocksMessage) {
        List<Block> blockList = blocksMessage.getBlocks();

        if (!blockList.isEmpty()) {
            Block block = blockList.get(blockList.size() - 1);
            if (block.getNumber() > lastBlock.getNumber())
                lastBlock = blockList.get(blockList.size() - 1);
        }

        // check if you got less blocks than you asked,
        // and keep the missing to ask again
        sentHashes.remove(wrap(Genesis.getInstance().getHash()));
        for (Block block : blockList){
            ByteArrayWrapper hash = wrap(block.getHash());
            sentHashes.remove(hash);
        }
        returnHashes();

        if(!blockList.isEmpty()) {
            blockchain.getQueue().addBlocks(blockList);
            blockchain.getQueue().logHashQueueSize();
            if (loggerSync.isInfoEnabled()) {
                blocksLoadedCnt += blockList.size();
            }

            if (blockchain.getQueue().isHashesEmpty()) {
                loggerSync.info("Peer {}: no more hashes in queue, idle", Utils.getNodeIdShort(peerId));
                changeState(SyncState.IDLE);
            }
        } else {
            changeState(SyncState.NO_MORE_BLOCKS);
        }

        if (syncState == SyncState.BLOCK_RETRIEVING) {
            sendGetBlocks();
        }
    }

    private void returnHashes() {
        if(sentHashes != null) {
            if(loggerSync.isDebugEnabled()) {
                loggerSync.debug("Peer {}: [{}] hashes returned", Utils.getNodeIdShort(peerId), sentHashes.size());
            }
            blockchain.getQueue().returnHashes(sentHashes);
        }
    }

    /**
     * Processing NEW_BLOCK announce message
     *
     * @param newBlockMessage - new block message
     */
    public void processNewBlock(NewBlockMessage newBlockMessage) {

        Block newBlock = newBlockMessage.getBlock();

        if (newBlock.getNumber() > this.lastBlock.getNumber())
            this.lastBlock = newBlock;

        loggerNet.info("New block received: block.index [{}]", newBlock.getNumber());

        channel.getNodeStatistics().setEthTotalDifficulty(newBlockMessage.getDifficultyAsBigInt());
        bestHash = newBlock.getHash();

        // adding block to the queue
        // there will be decided how to
        // connect it to the chain
        blockchain.getQueue().addNewBlock(newBlock);
        blockchain.getQueue().logHashQueueSize();
    }

    private void sendStatus() {
        byte protocolVersion = EthHandler.VERSION, networkId = (byte) CONFIG.networkId();
        BigInteger totalDifficulty = blockchain.getTotalDifficulty();
        byte[] bestHash = blockchain.getBestBlockHash();
        StatusMessage msg = new StatusMessage(protocolVersion, networkId,
                ByteUtil.bigIntegerToBytes(totalDifficulty), bestHash, Blockchain.GENESIS_HASH);
        sendMessage(msg);
    }

    /*
     * The wire gets data for signed transactions and
     * sends it to the net.
     */
    public void sendTransaction(Transaction transaction) {
        Set<Transaction> txs = new HashSet<>(Arrays.asList(transaction));
        TransactionsMessage msg = new TransactionsMessage(txs);
        sendMessage(msg);
    }

    public void sendNewBlock(Block block) {
        NewBlockMessage msg = new NewBlockMessage(block, block.getDifficulty());
        sendMessage(msg);
    }

    private void sendGetTransactions() {
        sendMessage(GET_TRANSACTIONS_MESSAGE);
    }

    private void sendGetBlockHashes() {
        byte[] bestHash = blockchain.getQueue().getBestHash();
        GetBlockHashesMessage msg = new GetBlockHashesMessage(bestHash, maxHashesAsk);
        sendMessage(msg);
    }

    // Parallel download blocks based on hashQueue
    public void sendGetBlocks() {
        BlockQueue queue = blockchain.getQueue();

        // retrieve list of block hashes from queue
        // save them locally in case the remote peer
        // will return less blocks than requested.
        List<byte[]> hashes = queue.getHashes();
        this.sentHashes = new ArrayList<>();
        for (byte[] hash : hashes)
            this.sentHashes.add(wrap(hash));

        if(loggerSync.isDebugEnabled()) {
            loggerSync.debug("Peer {}: [{}] hashes sent", Utils.getNodeIdShort(peerId), sentHashes.size());
        }

        if (hashes.isEmpty()) {
            return;
        }

        Collections.shuffle(hashes);
        GetBlocksMessage msg = new GetBlocksMessage(hashes);

        if (loggerNet.isTraceEnabled())
            loggerNet.debug(msg.getDetailedString());

        sendMessage(msg);
    }

    private void sendPendingTransactions() {
        Set<Transaction> pendingTxs =
                worldManager.getBlockchain()
                        .getPendingTransactions();
        TransactionsMessage msg = new TransactionsMessage(pendingTxs);
        sendMessage(msg);
    }

    private void processGetBlockHashes(GetBlockHashesMessage msg) {
        List<byte[]> hashes = blockchain.getListOfHashesStartFrom(msg.getBestHash(), msg.getMaxBlocks());

        BlockHashesMessage msgHashes = new BlockHashesMessage(hashes);
        sendMessage(msgHashes);
    }

    private void processGetBlocks(GetBlocksMessage msg) {

        List<byte[]> hashes = msg.getBlockHashes();

        Vector<Block> blocks = new Vector<>();
        for (byte[] hash : hashes) {
            Block block = blockchain.getBlockByHash(hash);
            blocks.add(block);
        }

        BlocksMessage bm = new BlocksMessage(blocks);
        sendMessage(bm);
    }

    private void sendMessage(EthMessage message) {
        msgQueue.sendMessage(message);
        channel.getNodeStatistics().ethOutbound.add();
    }

    public void setPeerId(String peerId) {
        this.peerId = peerId;
    }

    public StatusMessage getHandshakeStatusMessage() {
        return channel.getNodeStatistics().getEthLastInboundStatusMsg();
    }

    public void setMsgQueue(MessageQueue msgQueue) {
        this.msgQueue = msgQueue;
    }

    public void setPeerDiscoveryMode(boolean peerDiscoveryMode) {
        this.peerDiscoveryMode = peerDiscoveryMode;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    synchronized void changeState(SyncState newState) {
        if(newState == SyncState.HASH_RETRIEVING) {
            sendGetBlockHashes();
        }
        if(newState == SyncState.BLOCK_RETRIEVING) {
            blocksLoadedCnt = 0;
            sendGetBlocks();
        }
        if(newState == SyncState.NO_MORE_BLOCKS) {
            if(++noMoreBlocksHits < NO_MORE_BLOCKS_THRESHOLD) {
                return;
            }
        }
        if(newState == SyncState.DONE_SYNC) {
            processTransactions = true;
            newState = SyncState.IDLE;
        }
        this.syncState = newState;
    }

    public String getPeerId() {
        return peerId;
    }

    public SyncState getSyncState() {
        return syncState;
    }

    public boolean isHashRetrievingDone() {
        return syncState == SyncState.DONE_HASH_RETRIEVING;
    }

    public boolean hasNoMoreBlocks() {
        return syncState == SyncState.NO_MORE_BLOCKS;
    }

    public boolean hasInitPassed() {
        return peerState != EthState.INIT;
    }

    public boolean hasStatusSucceeded() {
        return peerState == EthState.STATUS_SUCCEEDED;
    }

    public boolean hasStatusFailed() {
        return peerState == EthState.STATUS_FAILED;
    }

    public void onDisconnect() {
        returnHashes();
    }

    void logSyncStats() {
        loggerSync.info(
                "Peer {}: [state {}, blocks count {}, last block {}]",
                Utils.getNodeIdShort(peerId),
                syncState,
                blocksLoadedCnt,
                lastBlock.getNumber()
        );
    }

    public boolean isIdle() {
        return syncState == SyncState.IDLE;
    }

    public boolean isSyncDone() {
        return syncState == SyncState.DONE_SYNC;
    }

    public NodeStatistics getNodeStatistics() {
        return channel.getNodeStatistics();
    }

    public byte[] getBestHash() {
        return bestHash;
    }

    public BigInteger getTotalDifficulty() {
        return channel.getNodeStatistics().getEthTotalDifficulty();
    }

    void setMaxHashesAsk(int maxHashesAsk) {
        this.maxHashesAsk = maxHashesAsk;
    }

    enum EthState {
        INIT,
        STATUS_SUCCEEDED,
        STATUS_FAILED
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE markables SYSTEM "markables.dtd">
<markables xmlns="www.eml.org/NameSpaces/source">
<markable anaphref="empty" id="markable_34" mmax_level="source" sentiment_ref="empty" span="word_1191" />
<markable anaphref="empty" id="markable_25" mmax_level="source" sentiment_ref="empty" span="word_990" />
<markable anaphref="empty" id="markable_20" mmax_level="source" sentiment_ref="empty" span="word_971" />
</markables>