text:
package com.samsung.sec.dexter.core.util;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.google.common.base.Strings;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.samsung.sec.dexter.core.analyzer.ResultFileConstant;
import com.samsung.sec.dexter.core.config.DefectGroup;
import com.samsung.sec.dexter.core.checker.CheckerConfig;
import com.samsung.sec.dexter.core.config.DexterCode;
import com.samsung.sec.dexter.core.config.DexterConfig;
import com.samsung.sec.dexter.core.config.IDexterStandaloneListener;
import com.samsung.sec.dexter.core.defect.Defect;
import com.samsung.sec.dexter.core.plugin.IDexterPlugin;
import com.samsung.sec.dexter.core.exception.DexterException;
import com.samsung.sec.dexter.core.exception.DexterRuntimeException;
import com.samsung.sec.dexter.core.filter.DefectFilter;
import com.samsung.sec.dexter.core.filter.FalseAlarmConfigurationTree;
import com.samsung.sec.dexter.core.filter.IFalseAlarmConfiguration;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.impl.provider.entity.StringProvider;

public class DexterClient implements IDexterClient, IDexterStandaloneListener {
	private final static Logger LOG = Logger.getLogger(DexterClient.class);

	private IDexterWebResource webResource;

    private static final String AUTHORIZATION = "Authorization";
	private static final String APPLICATION_TYPE_JSON = "application/json";
	private static final String HTTP_PREFIX = "http://";
	private static final int TIME_OUT = 15000;

	/** Dexter Server Info. */
	private String serverHost = "";
	private int serverPort = -1;
	private boolean isLogin = false;
	private String currentUserId = "";
	private String currentUserPwd = "";
	private int currentUserNo;
	private boolean isCurrentUserAdmin = false;
	//private String text;

	private final  List<IDexterLoginInfoListener> loginInfoListenerList = new ArrayList<IDexterLoginInfoListener>();

	private static class DexterClientHolder {
		private final static DexterClient INSTANCE = new DexterClient();
	}

	/**
	 * Before using methods for the class, you have to setup once as below.
	 *
	 * the followings are preconditions:
	 *   1) Set Dexter Server Connection Info. : setServerHost(host) and setServerPort(port)
	 *   2) Log in to Dexter Server : login(userId, userPwd)
	 *
	 * @return
	 */
	public static DexterClient getInstance() {
		return DexterClientHolder.INSTANCE;
	}

	/**
	 * singleton
	 */
	private DexterClient() {
		this.webResource = new JerseyDexterWebResource();
		LOG.debug("DexterClient");
	}

	/**
	 * If you want to your own WebResource object, use this method.
	 * Unless you use this method, DexterClient will use DefaultWebResource object which is built-in
	 *
	 * @param resource
	 */
	@Override
    public void setWebResource(IDexterWebResource resource){
		this.webResource = resource;
	}

	/**
	 * @return the isLogin
	 */
	@Override
    public boolean isLogin() {
		return isLogin;
	}

	/**
	 * @return the currentUserId
	 */
	@Override
    public String getCurrentUserId() {
		return currentUserId;
	}

	/**
	 * @param trim
	 */
	@Override
    public void setDexterServer(final String serverAddress) {
		final StringTokenizer st = new StringTokenizer(serverAddress, ":");

		if (st.hasMoreTokens()) {
			this.serverHost = st.nextToken();
		}

		if (st.hasMoreTokens()) {
			final String portStr = st.nextToken();
			if (portStr.matches("[0-9]+")) {
				this.serverPort = Integer.parseInt(portStr);
			}
		}
	}

	/**
	 * set Dexter Server Info.
	 *
	 * @precondition serverHost should not be null and serverPort should be over 0
	 * @param string
	 * @param i
	 *            void
	 */
	@Override
    public void setDexterServer(final String serverHost, final int serverPort) {
		assert !Strings.isNullOrEmpty(serverHost);
		assert serverPort > 0;

		this.serverHost = serverHost;
		this.serverPort = serverPort;
	}

	private boolean isResultOk(final String resultText){
		final Map<String, String> result = getResultMap(resultText);

		if ("ok".equals(result.get("result")) || "ok".equals(result.get("status"))) {
			return true;
		} else {
			LOG.debug("DexterClient Error: " + result.get("errorMessage") + "\n" + resultText);
			return false;
		}
	}

	private void checkResultOk(final String resultText){
		final Map<String, String> result = getResultMap(resultText);
		if (!"ok".equals(result.get("result")) && !"ok".equals(result.get("status"))) {
			DexterUtil.dumpAllStackTracesForCurrentThread(LOG);
			throw new DexterRuntimeException(result.get("errorMessage") + "\nRESULT: " + resultText);
		}
	}

	private Map<String, String> getResultMap(final String text) {
		final Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		final Map<String, String> result = gson.fromJson(text, Map.class);
		return result;
	}

	/**
	 * login to Dexter Server
	 *
	 * @precondition : both serverHost and serverPort fields are set and correct
	 * @param id
	 * @param pwd
	 * @return boolean
	 */
	@Override
    public void login(final String id, final String pwd){
		assert Strings.isNullOrEmpty(id) == false;
		assert Strings.isNullOrEmpty(pwd) == false;

		String text = webResource.getText(getServiceUrl(DexterConfig.CHECK_ACCOUNT), id, pwd);

		final Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		final Map<String, Object> result = gson.fromJson(text, Map.class);

		if ("ok".equals(result.get("result"))) {
			this.isLogin = true;
			this.currentUserNo = ((Double) result.get("userNo")).intValue();
			this.currentUserId = result.get("userId").toString();
			this.currentUserPwd = result.get("userPwd").toString();
			this.isCurrentUserAdmin = "true".equals(result.get("isAdmin").toString());
		} else {
			this.isLogin = false;
			throw new DexterRuntimeException("ID or Password is invalid.");
		}
	}

	private String getServiceUrl(String serviceUrl){
		return HTTP_PREFIX + this.serverHost + ":" + this.serverPort + serviceUrl;
	}

	/**
	 * @return boolean
	 */
	@Override
    public void login() {
		assert Strings.isNullOrEmpty(this.currentUserId) == false;
		assert Strings.isNullOrEmpty(this.currentUserPwd) == false;

		try {
	        login(this.currentUserId, this.currentUserPwd);
	        LOG.debug("Log-in successfully : " + this.currentUserId);
        } catch (DexterRuntimeException e) {
        	LOG.debug(e.getMessage(), e);
        }
	}

	/**
	 * @param resultJson
	 * @throws DexterException
	 */
	@Override
    public void sendAnalsysisResult(final String resultJson){
		if (Strings.isNullOrEmpty(resultJson)) {
			throw new DexterRuntimeException("The result file has no content to send");
		}

		if (isLogin == false) {
			throw new DexterRuntimeException("You are not log-in or your account("
			        + DexterClient.getInstance().currentUserId + ") doesn't exist in Dexter Server.");
		}

		String resultText= "";
		Map<String, Object> body = new HashMap<String, Object>();
		body.put("result", resultJson);

		if(DexterConfig.getInstance().getRunMode() == DexterConfig.RunMode.CLI){
			Gson gson = new Gson();
			String jsonBody = gson.toJson(body);
			resultText = webResource.postWithBodyforCLI(getServiceUrl(DexterConfig.PUT_ANALYSIS_RESULT_V2),
					this.currentUserId, this.currentUserPwd, jsonBody);
		}else{
			resultText = webResource.postWithBody(getServiceUrl(DexterConfig.PUT_ANALYSIS_RESULT_V2),
				this.currentUserId, this.currentUserPwd, body);
		}
		checkResultOk(resultText);
	}

	/**
	 * @param resultJson
	 *            void
	 * @throws CertificateException
	 */
	@Override
    public void insertSourceCode(final long snapshotId, final long defectGroupId,
    		final String modulePath, final String fileName, final String sourceCode){
		assert Strings.isNullOrEmpty(fileName) == false;

		if (Strings.isNullOrEmpty(sourceCode)) {
			throw new DexterRuntimeException("Invalide Parameter of sourceCode: null or empty.  fileName:" + fileName);
		}

		final Map<String, Object> body = new HashMap<String, Object>();
		body.put(ResultFileConstant.SNAPSHOT_ID, snapshotId);
		body.put(ResultFileConstant.GROUP_ID, defectGroupId);
		body.put(ResultFileConstant.MODULE_PATH, modulePath);
		body.put(ResultFileConstant.FILE_NAME, fileName);
		body.put(ResultFileConstant.SOURCE_CODE, DexterUtil.getBase64String(sourceCode));

		String resultText = "";

		if(DexterConfig.getInstance().getRunMode().equals(DexterConfig.RunMode.CLI)){
			Gson gson = new Gson();
			String jsonBody = gson.toJson(body);
			resultText = webResource.postWithBodyforCLI(getServiceUrl(DexterConfig.POST_SNAPSHOT_SOURCECODE),
					this.currentUserId, this.currentUserPwd, jsonBody);
		}else{
			resultText = webResource.postWithBody(getServiceUrl(DexterConfig.POST_SNAPSHOT_SOURCECODE),
				this.currentUserId, this.currentUserPwd, body);
		}

		checkResultOk(resultText);
	}

	/**
	 * @precondition
	 * 		1. installation nodejs  2. installation of Dexter Server  3. installation of Database
	 *
	 * @param dexterServerFullPath : DexterServer location in the same PC
	 * @param optionMap
	 * 		database.host :
	 * 		database.port :
	 * 		database.name :
	 * 		database.user :
	 * 		database.password :
	 *
	 * @return port to run Dexter Server
	 */
	public static int startDexterServer(final String dexterServerFullPath) {
		final Runtime rt = Runtime.getRuntime();
		final int MaxPortNumber = 65535;

		int port = 4982;

		while(DexterUtil.isAvailablePort("localhost", port++) && port < MaxPortNumber);

		if(port > MaxPortNumber){
			return -1;
		}

		try {
			rt.exec("node " + dexterServerFullPath + "\\server.js");
			return port;
		} catch (IOException e) {
			LOG.error(e);
			return -1;
		}
	}

	/**
	 * Only for Testing
	 *
	 * @param serverHost
	 * @param serverPort
	 * @param userId
	 * @param userPwd
	 * @return
	 * @return boolean
	 */
	public static boolean stopDexterServer(final String serverHost, final int serverPort, final String userId, final String userPwd) {
		assert Strings.isNullOrEmpty(serverHost) == false;
		assert serverPort > 0;
		assert Strings.isNullOrEmpty(userId) == false;
		assert Strings.isNullOrEmpty(userPwd) == false;

		Client client = null;
		try{
			final ClientConfig config = new DefaultClientConfig();
			config.getClasses().add(StringProvider.class);
			config.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, TIME_OUT);
			config.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, TIME_OUT);

			client = Client.create(config);
			client.setConnectTimeout(TIME_OUT);
			client.setReadTimeout(TIME_OUT);

			final WebResource resource = client.resource(DexterClient.getInstance().getServiceUrl(DexterConfig.STOP_SERVER));
			final String text = resource.accept(APPLICATION_TYPE_JSON)
					.header(AUTHORIZATION, "Basic " + DexterUtil.getBase64String(userId + ":" + userPwd))
					.delete(String.class);

			return "ok".equals(text);
		} catch (Exception e){
			e.printStackTrace();
			return false;
		} finally {
			if(client != null){
				client.destroy();
			}
		}

	}

	public static boolean deleteDexterDatabase(final String serverHost, final int serverPort, final String userId, final String userPwd) {
		assert Strings.isNullOrEmpty(serverHost) == false;
		assert serverPort > 0;
		assert Strings.isNullOrEmpty(userId) == false;
		assert Strings.isNullOrEmpty(userPwd) == false;

		Client client = null;
		try{
			final ClientConfig config = new DefaultClientConfig();
			config.getClasses().add(StringProvider.class);
			config.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, TIME_OUT);
			config.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, TIME_OUT);

			client = Client.create(config);
			client.setConnectTimeout(TIME_OUT);
			client.setReadTimeout(TIME_OUT);

			final WebResource resource = client.resource(
					DexterClient.getInstance().getServiceUrl("/api/dexter-db"));
			final String text = resource.accept(APPLICATION_TYPE_JSON)
					.header(AUTHORIZATION, "Basic " + DexterUtil.getBase64String(userId + ":" + userPwd))
					.delete(String.class);

			return "ok".equals(text);
		} catch (Exception e){
			e.printStackTrace();
			return false;
		} finally {
			if(client != null){
				client.destroy();
			}
		}

	}

	/**
	 * @param text
	 * @return boolean
	 */
	@Override
    public boolean isServerAddressOk(final String serverAddress) {
		assert Strings.isNullOrEmpty(serverAddress) == false;

		try {
			final String text = webResource.getText(HTTP_PREFIX + serverAddress + DexterConfig.CHECK_SERVER_ADDRESS,
					this.currentUserId, this.currentUserPwd);
			return "ok".equals(text);
		} catch (Exception e) {
			LOG.debug(e.getMessage(), e);
			return false;
		}
	}

	/**
	 * @precondition serverHost field should not be null and serverPort field should be over 0
	 *
	 * @param text
	 * @return boolean
	 */
	@Override
    public boolean isServerAlive() {
		if (Strings.isNullOrEmpty(serverHost) || serverPort <= 0) {
			LOG.debug("Invalid Dexter Server or Port, maybe you need to login on Dexter Server");
			return false;
		}

		try {
			final String text = webResource.getText(getServiceUrl(DexterConfig.CHECK_SERVER_ADDRESS), this.currentUserId, this.currentUserPwd);
			return "ok".equals(text);
		} catch (Exception e) {
			if ("java.net.ConnectException: Connection refused: connect".equals(e.getMessage())) {
				LOG.debug("Dexter Server is not running or network problem");
			} else {
				LOG.debug(e.getMessage(), e);
			}
			return false;
		}
	}

	public boolean hasSupportedHelpHtmlFile(final StringBuilder url) {
		try {
			if ("true".equals(DexterConfig.getInstance().isStandalone())) {
				throw new Exception();
			} else {
				final String text = webResource.getConnectionResult(url.toString(), this.currentUserId,	this.currentUserPwd);
				if ("false".equals(text)) {
					return false;
				} else {
					return true;
				}
			}
		} catch (IllegalStateException | UniformInterfaceException e) {
			LOG.debug(e.getMessage(), e);
			return false;
		} catch (Exception e) {
			throw new DexterRuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * @param id
	 * @param pwd
	 * @return Object
	 */
	@Override
    public boolean hasAccount(final String id) {
		if(Strings.isNullOrEmpty(id)){
			LOG.error("Invalid Parameter : id is null or empty");
			return false;
		}

        try {
	        final String text = webResource.getText(getServiceUrl(DexterConfig.CHECK_HAS_ACCOUNT + "/" + id),
	        		this.currentUserId, this.currentUserPwd);
	        return isResultOk(text);
        } catch (DexterRuntimeException e) {
        	LOG.debug(e.getMessage(), e);
        	return false;
        }
	}

	/**
	 * @param id
	 * @param pwd
	 * @return boolean
	 */
	@Override
    public void createAccount(final String id, final String pwd, final boolean isAdmin) {
		assert Strings.isNullOrEmpty(id) == false;
		assert Strings.isNullOrEmpty(pwd) == false;

		if (pwd.length() < 4 || pwd.length() > 20) {
			throw new DexterRuntimeException("Password length must be 4 to 20.");
		}

		final StringBuilder url = new StringBuilder();
		url.append(getServiceUrl(DexterConfig.ADD_ACCOUNT)).append("?userId=").append(id).append("&userId2=").append(pwd);

		if (isAdmin) {
			url.append("&isAdmin=Y");
		} else {
			url.append("&isAdmin=N");
		}

		final String text = webResource.postText(url.toString(), this.currentUserId, this.currentUserPwd);

		checkResultOk(text);
	}

	/**
	 * @param defect
	 */
	@Override
    public void changeDefectStatus(final Defect defect, final String status){
		assert defect != null;
		assert !Strings.isNullOrEmpty(status);

		final Map<String, Object> body = new HashMap<String, Object>();
		body.put("defect", defect.toJson());
		body.put("defectStatus", status);
		body.put("a", status);

		String text = webResource.postWithBody(getServiceUrl(DexterConfig.DISMISS_DEFECT),
				this.currentUserId, this.currentUserPwd, body);
		checkResultOk(text);
	}

	/**
	 * @param defect
	 */
	@Override
    public void insertDefectFilter(final Defect defect){
		assert defect != null;

		final Map<String, Object> body = new HashMap<String, Object>();
		body.put("defect", defect.toJson());

		final String text = webResource.postWithBody(getServiceUrl(DexterConfig.FILTER_FALSE_ALARM),
				this.currentUserId, this.currentUserPwd, body);
		checkResultOk(text);
	}

	/**
	 * @precondition Defect object should not be null
	 * @param defect
	 *            void
	 * @throws DexterException
	 */
	@Override
    public void removeDefectFilter(final Defect defect){
		assert defect != null;

		final Map<String, Object> body = new HashMap<String, Object>();
		body.put("defect", defect.toJson());

		String text = webResource.postWithBody(getServiceUrl(DexterConfig.FILTER_DELETE_FALSE_ALARM), this.currentUserId, this.currentUserPwd, body);
		checkResultOk(text);
	}

	/**
	 * @return
	 */
	@Override
    public int getLastFalseAlarmVersion() {
        try {
            Map<String, Object> result = webResource.getMap(getServiceUrl(DexterConfig.GET_FALSE_ALARM_VERSION),
	        			currentUserId, currentUserPwd);

	        if (result == null || result.get("version") == null) {
	        	LOG.debug("There is no version for False Alarm Data");
	        	return -2;
	        }

	        Object obj = result.get("version");
	        if(obj instanceof Integer){
	        	return (Integer) obj;
	        } else {
	        	return -3;
	        }
        } catch (DexterRuntimeException e) {
	        LOG.error(e.getMessage(), e);
	        return -4;
        }
	}

	/**
	 * @return
	 * @throws DexterException
	 */
	@Override
    public IFalseAlarmConfiguration getFalseAlarmTree() {
		final IFalseAlarmConfiguration tree = new FalseAlarmConfigurationTree();

		final String text = webResource.getText(getServiceUrl(DexterConfig.FILTER_FALSE_ALARM), this.currentUserId, this.currentUserPwd);
		@SuppressWarnings("unchecked")
        final List<Map<String, String>> result = new Gson().fromJson(text, List.class);

		for(Map<String, String> map : result){
			final DefectFilter filter = new DefectFilter();
			//filter.setFid(map.get(""));
			filter.setToolName(map.get(ResultFileConstant.TOOL_NAME));
			filter.setLanguage(map.get(ResultFileConstant.LANGUAGE));
			filter.setFileName(map.get(ResultFileConstant.FILE_NAME));
			filter.setModulePath(map.get(ResultFileConstant.MODULE_PATH));
			filter.setClassName(map.get(ResultFileConstant.CLASS_NAME));
			filter.setMethodName(map.get(ResultFileConstant.METHOD_NAME));
			filter.setCheckerCode(map.get(ResultFileConstant.CHECKER_CODE));
			filter.setActive(true);

			tree.addFalseAlarm(filter);
		}

		return tree;
	}

	@Override
    public String getDexterPluginUpdateUrl() {
		try {
        	final StringBuilder url = new StringBuilder();
    		url.append(getServiceUrl(DexterConfig.GET_DEXTER_PLUGIN_UPDATE_URL)).append("/").append(DexterUtil.getBit());

        	final String text = webResource.getText(url.toString(), "", "");

        	final Map<String, String> result = getResultMap(text);

	        if ("ok".equals(result.get("status"))) {
	        	return result.get("url");
	        }
        } catch (DexterRuntimeException e) {
	        LOG.error(e.getMessage(), e);
        }
		return "";
    }

	/**
	 * @param localDid
	 * @return long
	 */
	@Override
    public long getGlobalDid(final Defect defect) {
		assert defect != null;

		final Map<String, Object> body = new HashMap<String, Object>();
		body.put("defect", defect.toJson());

        try {
	        final String text = webResource.postWithBody(getServiceUrl(DexterConfig.POST_GLOBAL_DID),
	        		this.currentUserId, this.currentUserPwd, body);

	        final Map<String, String> result = getResultMap(text);

	        if ("ok".equals(result.get("result"))) {
	        	return Long.parseLong(result.get("globalDid"));
	        } else {
	        	LOG.error(result.get("errorMessage"));
	        	return -1l;
	        }
        } catch (DexterRuntimeException e) {
	        LOG.error(e.getMessage(), e);
	        return -2l;
        }
	}

	/**
	 * @param replace
	 * @param name
	 */
	@Override
    public void deleteDefects(final String modulePath, final String fileName){
		assert Strings.isNullOrEmpty(fileName) == false;

		final Map<String, Object> body = new HashMap<String, Object>();
		body.put(ResultFileConstant.MODULE_PATH, modulePath);
		body.put(ResultFileConstant.FILE_NAME, fileName);

		final String text = webResource.deleteWithBody(getServiceUrl(DexterConfig.DEFECT_DELETE),
				this.currentUserId, this.currentUserPwd, body);
		checkResultOk(text);
	}

	/**
	 * @return String
	 */
	@Override
    public List<DefectGroup> getDefectGroupByGroupName(final String groupName) {
		assert !Strings.isNullOrEmpty(groupName);

        final Map<String, Object> result = webResource.getMap(getServiceUrl(DexterConfig.DEFECT_GROUP + "/" + groupName),
				this.currentUserId, this.currentUserPwd);

		if ("ok".equals(result.get("status"))) {
			final String resultJson = (String) result.get("result");
			final List<DefectGroup> resultList = new Gson().fromJson(resultJson, new TypeToken<List<DefectGroup>>() {
                private static final long serialVersionUID = 7128024360990021164L;
			}.getType());
			return resultList;
		} else {
			throw new DexterRuntimeException("" + result.get("errorMessage"));
		}
	}

	/**
	 * you can't specify id for DefectGroup
	 *
	 * @param defectGroup
	 * @return boolean
	 */
	@Override
    public void insertDefectGroup(final DefectGroup defectGroup){
		assert defectGroup != null;

		final Map<String, Object> body = new HashMap<String, Object>();
		body.put("groupName", defectGroup.getGroupName());
		body.put("groupType", defectGroup.getGroupType());
		body.put("description", defectGroup.getDescription());
		body.put("createdDateTime", (Long) defectGroup.getCreatedDateTime());
		body.put("creatorNo", defectGroup.getCreatorNo());
		body.put("parentId", defectGroup.getParentId());

		final String text = webResource.postWithBody(getServiceUrl(DexterConfig.DEFECT_GROUP), this.currentUserId, this.currentUserPwd, body);
		checkResultOk(text);
	}

	/**
	 * do not specify id for DefectGroup programmatically
	 *
	 * @param defectGroup
	 * @return boolean
	 */
	@Override
    public boolean updateDefectGroup(final DefectGroup defectGroup) {
		assert defectGroup != null;

		final Map<String, Object> body = new HashMap<String, Object>();
		body.put(ResultFileConstant.GROUP_ID, defectGroup.getId());
		body.put("groupName", defectGroup.getGroupName());
		body.put("groupType", defectGroup.getGroupType());
		body.put("description", defectGroup.getDescription());
		body.put("createdDateTime", (Long) defectGroup.getCreatedDateTime());
		body.put("creatorNo", defectGroup.getCreatorNo());
		body.put("parentId", defectGroup.getParentId());

        try {
	        final String text = webResource.putWithBody(getServiceUrl(DexterConfig.DEFECT_GROUP), this.currentUserId, this.currentUserPwd, body);
	        return isResultOk(text);
        } catch (DexterRuntimeException e) {
        	LOG.error(e.getMessage(), e);
        	return false;
        }

	}

	@Override
    public boolean deleteDefectGroup(final long defectGroupId) {
		assert defectGroupId > 0;

		try {
	        String text = webResource.deleteWithBody(getServiceUrl(DexterConfig.DEFECT_GROUP + "/" + defectGroupId),
	        		this.currentUserId, this.currentUserPwd, new HashMap<String,Object>(0));
	        return isResultOk(text);
        } catch (DexterRuntimeException e) {
        	LOG.error(e.getMessage(), e);
        	return false;
        }
	}

	@Override
    public List<DefectGroup> getDefectGroupList() {
		String text;
        try {
	        text = webResource.getText(getServiceUrl(DexterConfig.DEFECT_GROUP), this.currentUserId, this.currentUserPwd);
        } catch (DexterRuntimeException e) {
	        LOG.error(e.getMessage(), e);
	        return new ArrayList<DefectGroup>(0);
        }

		final Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		final Map<String, Object> result = gson.fromJson(text, Map.class);

		if ("ok".equals(result.get("status"))) {
			final String resultJson = (String) result.get("result");
			final List<DefectGroup> resultList = gson.fromJson(resultJson, new TypeToken<List<DefectGroup>>() {
                private static final long serialVersionUID = 721969096430380905L;
			}.getType());
			return resultList;
		} else {
			LOG.error(result.get("errorMessage"));
			return new ArrayList<DefectGroup>(0);
		}
	}

	@Override
    public List<DexterCode> getCodes(final String codeKey) {
		assert !Strings.isNullOrEmpty(codeKey);

		try {
			final String text = webResource.getText(getServiceUrl(DexterConfig.CODE + "/" + codeKey), this.currentUserId, this.currentUserPwd);

			final Gson gson = new Gson();
			final Map<String, String> result = getResultMap(text);

			if ("ok".equals(result.get("status"))) {
				final List<DexterCode> resultList = gson.fromJson(result.get("result"), new TypeToken<List<DexterCode>>() {
					private static final long serialVersionUID = -685254649838058063L;
				}.getType());
				return resultList;
			} else {
				LOG.error(result.get("errorMessage"));
				return new ArrayList<DexterCode>(0);
			}
		} catch (DexterRuntimeException e) {
			LOG.error(e.getMessage(), e);
			return new ArrayList<DexterCode>(0);
		}
	}

	/**
	 * @return char[]
	 */
	@Override
    public String getSourceCode(final String modulePath, final String fileName) {
		final String url = DexterConfig.SOURCE_CODE + "?fileName=" + fileName + "&modulePath=" + modulePath + "&changeToBase64=false";

		try {
			return webResource.getText(getServiceUrl(url), this.currentUserId, this.currentUserPwd);
		} catch (DexterRuntimeException e) {
			LOG.error(e.getMessage(), e);
			return "";
		}
	}

	// ////////////////////////////////////////////////////////////////////////////////
	/**
	 * @return String
	 */
	@Override
    public String getCurrentUserPwd() {
		return this.currentUserPwd;
	}

	/**
	 * @param tempIsLogin
	 *            void
	 */
	@Override
	public void setLogin(final boolean isLogin) {
		this.isLogin = isLogin;
	}

	/**
	 * @param tempUserId
	 *            void
	 */
	@Override
    public void setUserId(final String userId) {
		this.currentUserId = userId;
	}

	/**
	 * @param tempUserPwd
	 *            void
	 */
	@Override
    public void setUserPwd(final String userPwd) {
		this.currentUserPwd = userPwd;
	}

	/**
	 * @return the serverHost
	 */
	@Override
    public String getServerHost() {
		if (Strings.isNullOrEmpty(serverHost)){
			throw new DexterRuntimeException("ServerHost is not set");
		}

		return serverHost;
	}

	/**
	 * @return the serverPort
	 */
	@Override
    public int getServerPort() {
		return serverPort;
	}

	/**
	 * @param serverHost
	 *            the serverHost to set
	 */
	@Override
    public void setServerHost(final String serverHost) {
		this.serverHost = serverHost;
	}

	/**
	 * @param serverPort
	 *            the serverPort to set
	 */
	@Override
    public void setServerPort(final int serverPort) {
		this.serverPort = serverPort;
	}

	/**
	 * @param currentUserId
	 *            the currentUserId to set
	 */
	@Override
    public void setCurrentUserId(final String currentUserId) {
		this.currentUserId = currentUserId;
	}

	/**
	 * @param currentUserPwd
	 *            the currentUserPwd to set
	 */
	@Override
    public void setCurrentUserPwd(final String currentUserPwd) {
		this.currentUserPwd = currentUserPwd;
	}

	/**
	 * @param userNo
	 *            void
	 */
	@Override
    public void setCurrentUserNo(final int userNo) {
		this.currentUserNo = userNo;
	}

	/**
	 * @return the currentUserNo
	 */
	@Override
    public int getCurrentUserNo() {
		return currentUserNo;
	}

	/**
	 * @return the isCurrentUserAdmin
	 */
	@Override
    public boolean isCurrentUserAdmin() {
		return isCurrentUserAdmin;
	}

	/**
	 * @param isCurrentUserAdmin
	 *            the isCurrentUserAdmin to set
	 */
	@Override
	public void setCurrentUserAdmin(final boolean isCurrentUserAdmin) {
		this.isCurrentUserAdmin = isCurrentUserAdmin;
	}

	/**
	 * @return String
	 */
	@Override
    public String getDexterWebUrl() {
		if (getServerHost().startsWith("http")) {
			return this.serverHost + ":" + this.serverPort + "/defect";
		} else {
			return HTTP_PREFIX + this.serverHost + ":" + this.serverPort + "/defect";
		}
	}

	/**
	 * @return String
	 */
	@Override
    public String getDexterDashboardUrl() {
		if (getServerHost().startsWith("http")) {
			return this.serverHost + ":" + this.serverPort + "/dashboard";
		} else {
			return HTTP_PREFIX + this.serverHost + ":" + this.serverPort + "/dashboard";
		}
	}

	/**
	 * @return String
	 */
	public String getDexterCodeMetricsUrl() {
		if (getServerHost().startsWith("http")) {
			return this.serverHost + ":" + this.serverPort + "/codeMetrics";
		} else {
			return HTTP_PREFIX + this.serverHost + ":" + this.serverPort + "/codeMetrics";
		}
	}

	/**
	 * @return String
	 */
	public String getDexterFunctionMetricsUrl() {
		if (getServerHost().startsWith("http")) {
			return this.serverHost + ":" + this.serverPort + "/functionMetrics";
		} else {
			return HTTP_PREFIX + this.serverHost + ":" + this.serverPort + "/functionMetrics";
		}
	}

	@Override
	public synchronized void addLoginInfoListener(final IDexterLoginInfoListener listener){
		if(!loginInfoListenerList.contains(listener)){
			loginInfoListenerList.add(listener);
		}
	}

	@Override
	public synchronized void removeLoginInfoListener(final IDexterLoginInfoListener listener){
		loginInfoListenerList.remove(listener);
	}

	@Override
	public synchronized void runLoginInfoHandler(String oldServerHost, int oldServerPort, String oldUserId) {
		if (oldServerHost.equals(this.serverHost) &&
				oldServerPort == this.serverPort &&
				oldUserId.equals(this.currentUserId)) {
			return;
		}

		for (int i=0; i<loginInfoListenerList.size();i++){
			final IDexterLoginInfoListener listener = loginInfoListenerList.get(i);

			if(listener != null){
				listener.handleDexterLoginInfoChanged();
			} else {
				loginInfoListenerList.remove(i--);
			}
		}
	}

	@Override
	public void handleDexterStandaloneChanged() {
		if (DexterConfig.getInstance().isStandalone()) {
    		setWebResource(new DummyDexterWebResource());
    	} else {
    		setWebResource(new JerseyDexterWebResource());
    	}
	}

	public CheckerConfig getDexterPluginChecker(IDexterPlugin plugin, String pluginName) {
		try {
			String text = webResource.postText(getServiceUrl(DexterConfig.GET_DEXTER_PLUGIN_CHECKER_JSON_FILE + "/" + pluginName), this.currentUserId, this.currentUserPwd);
			if(!(text.equals(DexterConfig.NO_UPDATE_CHECKER_CONFIG)))
			{
				Gson gson = new Gson();
				CheckerConfig cc = gson.fromJson(text, CheckerConfig.class);
				return cc;
			} else {
				CheckerConfig cc = plugin.getCheckerConfig();
				return cc;
			}
		} catch (DexterRuntimeException e) {
			LOG.error(e.getMessage(), e);
			throw new DexterRuntimeException(e.getMessage(), e);
		}
	}

	public void getFunctionMetrics(String fileName, String modulePath, List<String> functionList){
		try{
			final Map<String, Object> body = new HashMap<String, Object>();
			body.put(ResultFileConstant.FILE_NAME,fileName);
			body.put(ResultFileConstant.MODULE_PATH, modulePath);
			body.put(ResultFileConstant.FUNCTION_LIST, functionList);

			final String text = webResource.postWithBody(getServiceUrl(DexterConfig.POST_FUNCTION_METRICS),
		        		this.currentUserId, this.currentUserPwd, body);

			 checkResultOk(text);
		}catch (DexterRuntimeException e){
			LOG.error(e.getMessage(), e);
			throw new DexterRuntimeException(e.getMessage(), e);
		}
	}
}


text:
package br.eti.archanjo.webcron.exceptions;

public class NotFoundException extends Exception {

    public NotFoundException(String message) {
        super(message);
    }
}

redpajama_set_name: RedPajamaGithub


text:
LIB=	lldReaderWriterPECOFF

.include <bsd.init.mk>

.PATH: ${LLD_SRCDIR}/lib/ReaderWriter/PECOFF

SRCS+=	PECOFFLinkingContext.cpp \
	ReaderCOFF.cpp \
	ReaderImportHeader.cpp \
	WriterPECOFF.cpp

.if defined(HOSTLIB)
.include <bsd.hostlib.mk>
.else
.include <bsd.lib.mk>
.endif


text:
<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Core\Exception;

use InvalidArgumentException as SplInvalidArgumentException;

class InvalidArgumentException extends SplInvalidArgumentException implements ExceptionInterface
{
}


text:
[cmdletbinding()]
param()

# Arrange.
. $PSScriptRoot\..\..\lib\Initialize-Test.ps1
. $PSScriptRoot\..\..\..\Tasks\Gulp\Helpers.ps1
Register-Mock Get-Command { 'Some gulp command' } -- -Name 'gulp' -ErrorAction 'SilentlyContinue'

# Act.
$actual = Get-GulpCommand

# Assert.
Assert-AreEqual -Expected 'Some gulp command' -Actual $actual


text:
from __future__ import unicode_literals

# This file is only used if you use `make publish` or
# explicitly specify it as your config file.

import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *

SITEURL = 'https://dicasdejava.com.br'
RELATIVE_URLS = False

FEED_ALL_ATOM = 'feeds/all.atom.xml'
CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'

DELETE_OUTPUT_DIRECTORY = True

# Plugins
PLUGIN_PATHS = ['./pelican-plugins']
PLUGINS = ['sitemap', 'minify', 'tag_cloud']

SITEMAP = {
    'format': 'xml',
    'exclude': ['autor/', 'tag/', 'categoria/', 'arquivo/'],
    'priorities': {
        'articles': 0.5,
        'indexes': 0.5,
        'pages': 0.5
    },
    'changefreqs': {
        'articles': 'monthly',
        'indexes': 'daily',
        'pages': 'monthly'
    }
}

# Following items are often useful when publishing

DISQUS_SITENAME = "dicas-de-java"

MINIFY = {
 'remove_comments': True,
 'remove_all_empty_space': True,
 'remove_optional_attribute_quotes': False
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator

package com.microsoft.azure.keyvault.models;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * A Deleted Secret consisting of its previous id, attributes and its tags, as
 * well as information on when it will be purged.
 */
public class DeletedSecretBundle extends SecretBundle {
    /**
     * The url of the recovery object, used to identify and recover the deleted
     * secret.
     */
    @JsonProperty(value = "recoveryId")
    private String recoveryId;

    /**
     * The time when the secret is scheduled to be purged, in UTC.
     */
    @JsonProperty(value = "scheduledPurgeDate", access = JsonProperty.Access.WRITE_ONLY)
    private Long scheduledPurgeDate;

    /**
     * The time when the secret was deleted, in UTC.
     */
    @JsonProperty(value = "deletedDate", access = JsonProperty.Access.WRITE_ONLY)
    private Long deletedDate;

    /**
     * Get the recoveryId value.
     *
     * @return the recoveryId value
     */
    public String recoveryId() {
        return this.recoveryId;
    }

    /**
     * Set the recoveryId value.
     *
     * @param recoveryId the recoveryId value to set
     * @return the DeletedSecretBundle object itself.
     */
    public DeletedSecretBundle withRecoveryId(String recoveryId) {
        this.recoveryId = recoveryId;
        return this;
    }

    /**
     * Get the scheduledPurgeDate value.
     *
     * @return the scheduledPurgeDate value
     */
    public DateTime scheduledPurgeDate() {
        if (this.scheduledPurgeDate == null) {
            return null;
        }
        return new DateTime(this.scheduledPurgeDate * 1000L, DateTimeZone.UTC);
    }

    /**
     * Get the deletedDate value.
     *
     * @return the deletedDate value
     */
    public DateTime deletedDate() {
        if (this.deletedDate == null) {
            return null;
        }
        return new DateTime(this.deletedDate * 1000L, DateTimeZone.UTC);
    }

}


text:
namespace PremierLeagueApp.DataAccessLayer.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class InitialForDALProject : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(InitialForDALProject));

        string IMigrationMetadata.Id
        {
            get { return "201703291142556_InitialForDALProject"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
from __future__ import absolute_import, division

import copy
from datetime import datetime
from itertools import chain

import six
import sqlalchemy as sa
from six.moves import range, zip
from sqlalchemy import func

from tests.models import ArchiveTable, MultiColumnUserTable, UserTable
from tests.utils import SQLiteTestBase
from versionalchemy.api import delete, get
from versionalchemy.api.data import _get_conditions_list
from versionalchemy.utils import get_dialect

try:
    from unittest import mock  # PY3
except ImportError:
    import mock

class TestDeleteAPI(SQLiteTestBase):
    def setUp(self):
        super(TestDeleteAPI, self).setUp()

        p1 = UserTable(**self.p1)
        p3 = UserTable(**self.p3)
        self.session.add_all([p1, p3])
        self.session.flush()

        p1.col1 = 'change1'
        p2 = UserTable(**self.p2)
        self.session.add_all([p1, p2])
        self.session.flush()

        p1.col3 = False
        p1.col1 = 'change2'
        self.session.add(p1)
        self.session.flush()

        p1.col2 = 15
        p2.col2 = 12
        self.session.add_all([p1, p2])
        self.session.flush()

    def test_delete_single_row(self):
        conds = [{'product_id': 10}]
        delete(UserTable, self.session, conds=conds)
        self._verify_deleted(conds[0])

    def test_delete_multi_row(self):
        conds = [{'product_id': 11}, {'product_id': 10}]
        delete(UserTable, self.session, conds=conds)
        for c in conds:
            self._verify_deleted(c)

    def test_delete_rollback(self):
        conds = [{'product_id': 10}]
        cond_list_1 = _get_conditions_list(UserTable, conds)
        with mock.patch(
            'versionalchemy.api.data._get_conditions_list',
            side_effect=[cond_list_1, Exception()]
        ):
            try:
                delete(UserTable, self.session, conds=conds)
                self.assertTrue(False, 'Should have raised an exception')
            except Exception:
                version_col_names = UserTable.va_version_columns
                and_clause = sa.and_(*[
                    getattr(UserTable.ArchiveTable, col_name) == conds[0][col_name]
                    for col_name in version_col_names
                ])
                res = self.session.execute(
                    sa.select([func.count(UserTable.ArchiveTable.va_id)])
                    .where(and_clause)
                )
                self.assertEqual(res.scalar(), 4)

                and_clause = sa.and_(*[
                    getattr(UserTable, col_name) == conds[0][col_name]
                    for col_name in version_col_names
                ])
                res = self.session.execute(
                    sa.select([func.count(UserTable.id)])
                    .where(and_clause)
                )
                self.assertEqual(res.scalar(), 1)

class TestMultiColDeleteAPI(SQLiteTestBase):
    UserTable = MultiColumnUserTable

    def setUp(self):
        super(TestMultiColDeleteAPI, self).setUp()
        r1 = {
            'product_id_1': 11,
            'product_id_2': 'foo',
            'col1': 'foo',
            'col2': 100,
        }
        p1 = self.UserTable(**r1)
        r2 = {
            'product_id_1': 11,
            'product_id_2': 'bar',
            'col1': 'foo',
            'col2': 100,
        }
        p2 = self.UserTable(**r2)
        self.session.add_all([p1, p2])
        self.session.flush()

        p1.col1 = 'change1'
        self.session.add(p1)
        self.session.flush()

        p1.col1 = 'change2'
        self.session.add(p1)
        self.session.flush()

        p1.col2 = 15
        p2.col2 = 12
        self.session.add_all([p1, p2])
        self.session.flush()

    def test_delete_single_row(self):
        conds = [{'product_id_1': 11, 'product_id_2': 'foo'}]
        delete(self.UserTable, self.session, conds=conds)
        self._verify_deleted(conds[0])

    def test_delete_multi_row(self):
        conds = [
            {'product_id_1': 11, 'product_id_2': 'bar'},
            {'product_id_1': 11, 'product_id_2': 'foo'}
        ]
        delete(self.UserTable, self.session, conds=conds)
        for c in conds:
            self._verify_deleted(c)

class TestGetAPI(SQLiteTestBase):
    def setUp(self):
        super(TestGetAPI, self).setUp()
        self.p1_history, self.p2_history, self.p3_history = [], [], []

        self.t1 = datetime.utcfromtimestamp(10)
        p1 = UserTable(**self.p1)
        p3 = UserTable(**self.p3)
        with mock.patch('versionalchemy.models.datetime') as p:
            p.now.return_value = self.t1
            self.session.add_all([p1, p3])
            self.session.flush()
            self.p1_history.append(self._history(p1, self.t1, 0))
            self.p3_history.append(self._history(p3, self.t1, 0))

        self.t2 = datetime.utcfromtimestamp(20)
        p1.col1 = 'change1'
        p2 = UserTable(**self.p2)
        with mock.patch('versionalchemy.models.datetime') as p:
            p.now.return_value = self.t2
            self.session.add_all([p1, p2])
            self.session.flush()
            self.p1_history.append(self._history(p1, self.t2, 1))
            self.p2_history.append(self._history(p2, self.t2, 0))

        self.t3 = datetime.utcfromtimestamp(30)
        p1.col3 = False
        p1.col1 = 'change2'
        with mock.patch('versionalchemy.models.datetime') as p:
            p.now.return_value = self.t3
            self.session.add(p1)
            self.session.flush()
            self.p1_history.append(self._history(p1, self.t3, 2))

        self.t4 = datetime.utcfromtimestamp(40)
        p1.col2 = 15
        p2.col2 = 12
        with mock.patch('versionalchemy.models.datetime') as p:
            p.now.return_value = self.t4
            self.session.add_all([p1, p2])
            self.session.flush()
            self.p1_history.append(self._history(p1, self.t4, 3))
            self.p2_history.append(self._history(p2, self.t4, 1))

    def test_get_single_product_no_change(self):
        '''
        Performs a query for p3 which has no changes for current time, previous time slice,
        a time period that includes t1, and a time period that does not include t1.
        '''
        conds = [{'product_id': 2546}]
        result = get(UserTable, self.session, conds=conds)
        self._assert_result(result, self.p3_history)

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(5),
            conds=conds,
        )
        self.assertEqual(len(result), 0)

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(15),
            conds=conds,
        )
        self._assert_result(result, self.p3_history)

        result = get(
            UserTable,
            self.session,
            t1=self.t1,
            conds=conds,
        )
        self._assert_result(result, self.p3_history)

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(5),
            t2=datetime.utcfromtimestamp(11),
            conds=conds,
        )
        self._assert_result(result, self.p3_history)

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(11),
            t2=datetime.utcfromtimestamp(15),
            conds=conds,
        )
        self.assertEqual(len(result), 0)

    def test_get_single_product_with_change(self):
        '''
        Performs a query for p1 which has been changed 3 times for current time, previous time
        slices, and various time periods.
        '''
        conds = [{'product_id': 10}]
        result = get(UserTable, self.session, conds=conds)
        self._assert_result(result, self.p1_history[-1:])

        result = get(UserTable, self.session, t1=datetime.utcfromtimestamp(15), conds=conds)
        self._assert_result(result, self.p1_history[:1])

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(35),
            conds=conds,
        )
        self._assert_result(result, self.p1_history[2:3])

        result = get(
            UserTable,
            self.session,
            t2=datetime.utcfromtimestamp(35),
            conds=conds,
        )
        self._assert_result(result, self.p1_history[:3])

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(11),
            t2=datetime.utcfromtimestamp(45),
            conds=conds,
        )
        self._assert_result(result, self.p1_history[1:])

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(11),
            t2=datetime.utcfromtimestamp(35),
            conds=conds,
        )
        self._assert_result(result, self.p1_history[1:3])

    def test_get_multiple_products(self):
        conds = [{'product_id': 10}, {'product_id': 11}]
        result = get(UserTable, self.session, conds=conds)
        self._assert_result(result, [self.p1_history[-1], self.p2_history[-1]])

        result = get(UserTable, self.session, t1=datetime.utcfromtimestamp(15), conds=conds)
        self._assert_result(result, self.p1_history[:1])

        result = get(UserTable, self.session, t1=datetime.utcfromtimestamp(25), conds=conds)
        self._assert_result(result, [self.p1_history[1], self.p2_history[0]])

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(11),
            t2=datetime.utcfromtimestamp(45),
            conds=conds,
        )
        self._assert_result(result, list(chain(self.p1_history[1:], self.p2_history)))

    def test_get_all_products(self):
        result = get(UserTable, self.session)
        self._assert_result(result, [self.p1_history[-1], self.p2_history[-1], self.p3_history[-1]])

        result = get(UserTable, self.session, t1=datetime.utcfromtimestamp(31))
        self._assert_result(result, [self.p1_history[2], self.p2_history[0], self.p3_history[0]])

        result = get(UserTable, self.session, t1=datetime.utcfromtimestamp(11))
        self._assert_result(result, [self.p1_history[0], self.p3_history[0]])

        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(11),
            t2=datetime.utcfromtimestamp(45),
        )
        self._assert_result(result, list(chain(self.p1_history[1:], self.p2_history)))

    def test_get_products_after_va_id(self):
        result = get(
            UserTable,
            self.session,
            va_id=3,
        )
        self._assert_result(result, [
            self.p1_history[1], self.p1_history[2], self.p1_history[3], self.p2_history[1]
        ])

    def test_fields_query(self):
        '''
        Test specifying fields and make sure dedup happens correctly.
        '''
        def prune_data(d, fields):
            return {k: d[k] for k in fields}

        conds = [{'product_id': 10}]

        fields = ['col2']
        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(9),
            t2=datetime.utcfromtimestamp(45),
            conds=conds,
            fields=fields,
        )
        expected = [self.p1_history[0], self.p1_history[3]]
        self._assert_result(result, expected, fields=fields)

        fields = ['col1', 'col2']
        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(9),
            t2=datetime.utcfromtimestamp(45),
            conds=conds,
            fields=fields,
        )
        self._assert_result(result, self.p1_history, fields=fields)

        fields = ['col1']
        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(9),
            t2=datetime.utcfromtimestamp(45),
            fields=fields,
        )
        self._assert_result(
            result,
            list(chain(self.p1_history[:3], self.p2_history[:1], self.p3_history)),
            fields=fields,
        )

        fields = ['col1', 'col2']
        result = get(
            UserTable,
            self.session,
            t1=datetime.utcfromtimestamp(11),
            conds=conds,
            fields=fields,
        )
        self._assert_result(result, self.p1_history[:1], fields=fields)

        fields = ['col1', 'col2']
        result = get(
            UserTable,
            self.session,
            conds=conds,
            fields=fields,
        )
        self._assert_result(result, self.p1_history[-1:], fields=fields)

        fields = ['col1', 'invalid_col']
        result = get(
            UserTable,
            self.session,
            conds=conds,
            fields=fields,
        )
        self.p1_history[-1]['va_data']['invalid_col'] = None
        self._assert_result(result, self.p1_history[-1:], fields=fields)

    def test_failure_conditions(self):
        '''
        Pass invalid conds arguments and ensure the query fails.
        '''
        conds = [{'product_id': 10, 'foo': 15}]
        with self.assertRaises(ValueError):
            get(UserTable, self.session, t1=datetime.utcfromtimestamp(31), conds=conds)

        conds = [{'pid': 10}]
        with self.assertRaises(ValueError):
            get(UserTable, self.session, t1=datetime.utcfromtimestamp(31), conds=conds)

        with self.assertRaises(ValueError):
            get(UserTable, self.session, page=-10)

    def test_paging_results(self):
        self.session.execute('delete from {}'.format(UserTable.__tablename__))
        self.session.execute('delete from {}'.format(ArchiveTable.__tablename__))
        t = datetime.utcfromtimestamp(10000)
        with mock.patch('versionalchemy.models.datetime') as p:
            p.now.return_value = t
            history = []
            self.p1['col2'] = 0
            p1 = UserTable(**self.p1)
            self.session.add(p1)
            self.session.commit()
            history.append(self._history(p1, t, self.p1['col2']))
            # make 500 changes
            for i in range(500):
                self.p1['col2'] += 1
                self.p1['col3'] = int(i < 250)
                self.p1['col1'] = 'foobar' + '1' * ((i + 1) // 10)
                [setattr(p1, k, v) for k, v in six.iteritems(self.p1)]
                self.session.add(p1)
                self.session.commit()
                history.append(self._history(p1, t, self.p1['col2']))
            result = get(
                UserTable,
                self.session,
                t1=datetime.utcfromtimestamp(0),
                t2=datetime.utcfromtimestamp(10000000000),
                page=1,
                page_size=1000,
            )
            self._assert_result(result, history)
            result = get(
                UserTable,
                self.session,
                t1=datetime.utcfromtimestamp(0),
                t2=datetime.utcfromtimestamp(10000000000),
                page=1,
                page_size=100
            )
            self._assert_result(result, history[:100])
            result = get(
                UserTable,
                self.session,
                t1=datetime.utcfromtimestamp(0),
                t2=datetime.utcfromtimestamp(10000000000),
                page=3,
                page_size=100
            )
            self._assert_result(result, history[200:300])
            result = get(
                UserTable,
                self.session,
                t1=datetime.utcfromtimestamp(0),
                t2=datetime.utcfromtimestamp(10000000000),
                page=5,
                page_size=100
            )
            self._assert_result(result, history[400:500])
            result = get(
                UserTable,
                self.session,
                t1=datetime.utcfromtimestamp(0),
                t2=datetime.utcfromtimestamp(10000000000),
                fields=['col1'],
                page=1,
                page_size=80
            )
            self._assert_result(result, history[0:80:10], fields=['col1'])

    def _assert_result(self, result, expected, fields=None):
        self.assertEqual(len(result), len(expected))
        for res, exp in zip(result, expected):
            res = copy.deepcopy(res)
            exp = copy.deepcopy(exp)
            self.assertEqual(res['va_id'], exp['va_data']['va_id'])
            del res['va_id']
            if 'id' in res['va_data']:
                del res['va_data']['id']
            del res['user_id']
            del exp['va_data']['id']
            del exp['va_data']['va_id']
            if fields is not None:
                for k in list(exp['va_data']):
                    if k not in fields:
                        del exp['va_data'][k]
            self.assertEqual(res, exp)

    def _history(self, row, ts, version):
        self.assertEqual(row.version(self.session), version)
        d = row._to_dict(get_dialect(self.session))
        self.assertNotIn('va_id', d)
        d['va_id'] = row.va_id
        return {
            'va_data': d,
            'va_updated_at': ts,
            'va_deleted': False,
            'va_version': version,
            'product_id': row.product_id
        }


text:
using XenAdmin.Commands;
using XenAPI;

namespace XenAdmin.TabPages
{
    partial class SrStoragePage
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SrStoragePage));
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.rescanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.moveVirtualDiskToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.deleteVirtualDiskToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.editVirtualDiskToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.TitleLabel = new System.Windows.Forms.Label();
            this.RemoveButtonContainer = new XenAdmin.Controls.ToolTipContainer();
            this.RemoveButton = new XenAdmin.Commands.CommandButton();
            this.EditButtonContainer = new XenAdmin.Controls.ToolTipContainer();
            this.EditButton = new System.Windows.Forms.Button();
            this.addVirtualDiskButton = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
            this.toolTipContainerRescan = new XenAdmin.Controls.ToolTipContainer();
            this.buttonRescan = new System.Windows.Forms.Button();
            this.toolTipContainerMove = new XenAdmin.Controls.ToolTipContainer();
            this.buttonMove = new XenAdmin.Commands.CommandButton();
            this.dataGridViewVDIs = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
            this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnVolume = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnDesc = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnSize = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnVM = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColumnCBT = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.pageContainerPanel.SuspendLayout();
            this.contextMenuStrip1.SuspendLayout();
            this.RemoveButtonContainer.SuspendLayout();
            this.EditButtonContainer.SuspendLayout();
            this.flowLayoutPanel1.SuspendLayout();
            this.toolTipContainerRescan.SuspendLayout();
            this.toolTipContainerMove.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewVDIs)).BeginInit();
            this.tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            //
            // pageContainerPanel
            //
            this.pageContainerPanel.Controls.Add(this.tableLayoutPanel1);
            resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel");
            //
            // contextMenuStrip1
            //
            this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.rescanToolStripMenuItem,
            this.addToolStripMenuItem,
            this.moveVirtualDiskToolStripMenuItem,
            this.deleteVirtualDiskToolStripMenuItem,
            this.toolStripSeparator1,
            this.editVirtualDiskToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1");
            this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening);
            //
            // rescanToolStripMenuItem
            //
            this.rescanToolStripMenuItem.Name = "rescanToolStripMenuItem";
            resources.ApplyResources(this.rescanToolStripMenuItem, "rescanToolStripMenuItem");
            this.rescanToolStripMenuItem.Click += new System.EventHandler(this.rescanToolStripMenuItem_Click);
            //
            // addToolStripMenuItem
            //
            this.addToolStripMenuItem.Name = "addToolStripMenuItem";
            resources.ApplyResources(this.addToolStripMenuItem, "addToolStripMenuItem");
            this.addToolStripMenuItem.Click += new System.EventHandler(this.addToolStripMenuItem_Click);
            //
            // moveVirtualDiskToolStripMenuItem
            //
            this.moveVirtualDiskToolStripMenuItem.Name = "moveVirtualDiskToolStripMenuItem";
            resources.ApplyResources(this.moveVirtualDiskToolStripMenuItem, "moveVirtualDiskToolStripMenuItem");
            this.moveVirtualDiskToolStripMenuItem.Click += new System.EventHandler(this.moveVirtualDiskToolStripMenuItem_Click);
            //
            // deleteVirtualDiskToolStripMenuItem
            //
            this.deleteVirtualDiskToolStripMenuItem.Name = "deleteVirtualDiskToolStripMenuItem";
            resources.ApplyResources(this.deleteVirtualDiskToolStripMenuItem, "deleteVirtualDiskToolStripMenuItem");
            this.deleteVirtualDiskToolStripMenuItem.Click += new System.EventHandler(this.deleteVirtualDiskToolStripMenuItem_Click);
            //
            // toolStripSeparator1
            //
            this.toolStripSeparator1.Name = "toolStripSeparator1";
            resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
            //
            // editVirtualDiskToolStripMenuItem
            //
            this.editVirtualDiskToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16;
            resources.ApplyResources(this.editVirtualDiskToolStripMenuItem, "editVirtualDiskToolStripMenuItem");
            this.editVirtualDiskToolStripMenuItem.Name = "editVirtualDiskToolStripMenuItem";
            this.editVirtualDiskToolStripMenuItem.Click += new System.EventHandler(this.editVirtualDiskToolStripMenuItem_Click);
            //
            // TitleLabel
            //
            resources.ApplyResources(this.TitleLabel, "TitleLabel");
            this.TitleLabel.ForeColor = System.Drawing.Color.White;
            this.TitleLabel.Name = "TitleLabel";
            //
            // RemoveButtonContainer
            //
            this.RemoveButtonContainer.Controls.Add(this.RemoveButton);
            resources.ApplyResources(this.RemoveButtonContainer, "RemoveButtonContainer");
            this.RemoveButtonContainer.Name = "RemoveButtonContainer";
            //
            // RemoveButton
            //
            resources.ApplyResources(this.RemoveButton, "RemoveButton");
            this.RemoveButton.Name = "RemoveButton";
            this.RemoveButton.UseVisualStyleBackColor = true;
            //
            // EditButtonContainer
            //
            resources.ApplyResources(this.EditButtonContainer, "EditButtonContainer");
            this.EditButtonContainer.Controls.Add(this.EditButton);
            this.EditButtonContainer.Name = "EditButtonContainer";
            //
            // EditButton
            //
            resources.ApplyResources(this.EditButton, "EditButton");
            this.EditButton.Name = "EditButton";
            this.EditButton.UseVisualStyleBackColor = true;
            this.EditButton.Click += new System.EventHandler(this.EditButton_Click);
            //
            // addVirtualDiskButton
            //
            resources.ApplyResources(this.addVirtualDiskButton, "addVirtualDiskButton");
            this.addVirtualDiskButton.Name = "addVirtualDiskButton";
            this.addVirtualDiskButton.UseVisualStyleBackColor = true;
            this.addVirtualDiskButton.Click += new System.EventHandler(this.addVirtualDiskButton_Click);
            //
            // label1
            //
            resources.ApplyResources(this.label1, "label1");
            this.label1.Name = "label1";
            //
            // flowLayoutPanel1
            //
            this.flowLayoutPanel1.Controls.Add(this.toolTipContainerRescan);
            this.flowLayoutPanel1.Controls.Add(this.addVirtualDiskButton);
            this.flowLayoutPanel1.Controls.Add(this.toolTipContainerMove);
            this.flowLayoutPanel1.Controls.Add(this.RemoveButtonContainer);
            this.flowLayoutPanel1.Controls.Add(this.EditButtonContainer);
            resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
            this.flowLayoutPanel1.Name = "flowLayoutPanel1";
            //
            // toolTipContainerRescan
            //
            this.toolTipContainerRescan.Controls.Add(this.buttonRescan);
            resources.ApplyResources(this.toolTipContainerRescan, "toolTipContainerRescan");
            this.toolTipContainerRescan.Name = "toolTipContainerRescan";
            //
            // buttonRescan
            //
            resources.ApplyResources(this.buttonRescan, "buttonRescan");
            this.buttonRescan.Name = "buttonRescan";
            this.buttonRescan.UseVisualStyleBackColor = true;
            this.buttonRescan.Click += new System.EventHandler(this.buttonRescan_Click);
            //
            // toolTipContainerMove
            //
            this.toolTipContainerMove.Controls.Add(this.buttonMove);
            resources.ApplyResources(this.toolTipContainerMove, "toolTipContainerMove");
            this.toolTipContainerMove.Name = "toolTipContainerMove";
            //
            // buttonMove
            //
            resources.ApplyResources(this.buttonMove, "buttonMove");
            this.buttonMove.Name = "buttonMove";
            this.buttonMove.UseVisualStyleBackColor = true;
            //
            // dataGridViewVDIs
            //
            this.dataGridViewVDIs.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
            this.dataGridViewVDIs.BackgroundColor = System.Drawing.SystemColors.Window;
            this.dataGridViewVDIs.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
            this.dataGridViewVDIs.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dataGridViewVDIs.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.ColumnName,
            this.ColumnVolume,
            this.ColumnDesc,
            this.ColumnSize,
            this.ColumnVM,
            this.ColumnCBT});
            resources.ApplyResources(this.dataGridViewVDIs, "dataGridViewVDIs");
            this.dataGridViewVDIs.MultiSelect = true;
            this.dataGridViewVDIs.Name = "dataGridViewVDIs";
            this.dataGridViewVDIs.ReadOnly = true;
            this.dataGridViewVDIs.SelectionChanged += new System.EventHandler(this.dataGridViewVDIs_SelectedIndexChanged);
            this.dataGridViewVDIs.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.DataGridViewObject_SortCompare);
            this.dataGridViewVDIs.KeyUp += new System.Windows.Forms.KeyEventHandler(this.dataGridViewVDIs_KeyUp);
            this.dataGridViewVDIs.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dataGridViewVDIs_MouseUp);
            //
            // ColumnName
            //
            this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.ColumnName, "ColumnName");
            this.ColumnName.Name = "ColumnName";
            this.ColumnName.ReadOnly = true;
            //
            // ColumnVolume
            //
            this.ColumnVolume.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.ColumnVolume, "ColumnVolume");
            this.ColumnVolume.Name = "ColumnVolume";
            this.ColumnVolume.ReadOnly = true;
            //
            // ColumnDesc
            //
            this.ColumnDesc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.ColumnDesc, "ColumnDesc");
            this.ColumnDesc.Name = "ColumnDesc";
            this.ColumnDesc.ReadOnly = true;
            //
            // ColumnSize
            //
            this.ColumnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
            resources.ApplyResources(this.ColumnSize, "ColumnSize");
            this.ColumnSize.Name = "ColumnSize";
            this.ColumnSize.ReadOnly = true;
            //
            // ColumnVM
            //
            this.ColumnVM.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            resources.ApplyResources(this.ColumnVM, "ColumnVM");
            this.ColumnVM.Name = "ColumnVM";
            this.ColumnVM.ReadOnly = true;
            //
            // ColumnCBT
            //
            this.ColumnCBT.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
            resources.ApplyResources(this.ColumnCBT, "ColumnCBT");
            this.ColumnCBT.Name = "ColumnCBT";
            this.ColumnCBT.ReadOnly = true;
            //
            // tableLayoutPanel1
            //
            resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
            this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 2);
            this.tableLayoutPanel1.Controls.Add(this.dataGridViewVDIs, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            //
            // SrStoragePage
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            this.BackColor = System.Drawing.Color.Transparent;
            this.DoubleBuffered = true;
            this.Name = "SrStoragePage";
            this.Controls.SetChildIndex(this.pageContainerPanel, 0);
            this.pageContainerPanel.ResumeLayout(false);
            this.contextMenuStrip1.ResumeLayout(false);
            this.RemoveButtonContainer.ResumeLayout(false);
            this.EditButtonContainer.ResumeLayout(false);
            this.flowLayoutPanel1.ResumeLayout(false);
            this.toolTipContainerRescan.ResumeLayout(false);
            this.toolTipContainerMove.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewVDIs)).EndInit();
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
        private System.Windows.Forms.ToolStripMenuItem editVirtualDiskToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem deleteVirtualDiskToolStripMenuItem;
        private System.Windows.Forms.Button addVirtualDiskButton;
        private System.Windows.Forms.Label TitleLabel;
        private XenAdmin.Controls.ToolTipContainer EditButtonContainer;
        private System.Windows.Forms.Button EditButton;
        private XenAdmin.Controls.ToolTipContainer RemoveButtonContainer;
        private XenAdmin.Commands.CommandButton RemoveButton;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
        private System.Windows.Forms.Button buttonRescan;
        private XenAdmin.Controls.ToolTipContainer toolTipContainerRescan;
        private XenAdmin.Controls.ToolTipContainer toolTipContainerMove;
        private XenAdmin.Commands.CommandButton buttonMove;
        private System.Windows.Forms.ToolStripMenuItem moveVirtualDiskToolStripMenuItem;
        private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
        private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewVDIs;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.ToolStripMenuItem rescanToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem;
        private System.Windows.Forms.DataGridViewTextBoxColumn ColumnName;
        private System.Windows.Forms.DataGridViewTextBoxColumn ColumnVolume;
        private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDesc;
        private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSize;
        private System.Windows.Forms.DataGridViewTextBoxColumn ColumnVM;
        private System.Windows.Forms.DataGridViewTextBoxColumn ColumnCBT;

    }
}


text:
package org.telegram.api.input.messages.filter;

/**
 * The type TL messages filter document.
 */
public class TLMessagesFilterDocument extends TLAbsMessagesFilter {
    /**
     * The constant CLASS_ID.
     */
    public static final int CLASS_ID = 0x9eddf188;

    public int getClassId() {
        return CLASS_ID;
    }

    public String toString() {
        return "inputMessagesFilterDocument#9eddf188";
    }
}


text:
class WXDLLIMPEXP_FWD_CORE wxFrame;
class WXDLLIMPEXP_FWD_CORE wxWindowMac;
class WXDLLIMPEXP_FWD_CORE wxApp ;
class WXDLLIMPEXP_FWD_CORE wxKeyEvent;
class WXDLLIMPEXP_FWD_BASE wxLog;
class WXDLLIMPEXP_FWD_CORE wxMacAutoreleasePool;

// Force an exit from main loop
void WXDLLIMPEXP_CORE wxExit();

// Yield to other apps/messages
bool WXDLLIMPEXP_CORE wxYield();

// Represents the application. Derive OnInit and declare
// a new App object to start application
class WXDLLIMPEXP_CORE wxApp: public wxAppBase
{
    wxDECLARE_DYNAMIC_CLASS(wxApp);

    wxApp();
    virtual ~wxApp();

    virtual void WakeUpIdle() wxOVERRIDE;

    virtual void SetPrintMode(int mode) wxOVERRIDE { m_printMode = mode; }
    virtual int GetPrintMode() const { return m_printMode; }

    // calling OnInit with an auto-release pool ready ...
    virtual bool CallOnInit() wxOVERRIDE;
#if wxUSE_GUI
    // setting up all MacOS Specific Event-Handlers etc
    virtual bool OnInitGui() wxOVERRIDE;
#endif // wxUSE_GUI

    virtual int OnRun() wxOVERRIDE;

    virtual bool ProcessIdle() wxOVERRIDE;

    // implementation only
    void OnIdle(wxIdleEvent& event);
    void OnEndSession(wxCloseEvent& event);
    void OnQueryEndSession(wxCloseEvent& event);

protected:
    int                   m_printMode; // wxPRINT_WINDOWS, wxPRINT_POSTSCRIPT
    wxMacAutoreleasePool* m_macPool;

public:

    static bool           sm_isEmbedded;
    // Implementation
    virtual bool Initialize(int& argc, wxChar **argv) wxOVERRIDE;
    virtual void CleanUp() wxOVERRIDE;

    // the installed application event handler
    WXEVENTHANDLERREF    MacGetEventHandler() { return m_macEventHandler ; }
    WXEVENTHANDLERREF    MacGetCurrentEventHandlerCallRef() { return m_macCurrentEventHandlerCallRef ; }
    void MacSetCurrentEvent( WXEVENTREF event , WXEVENTHANDLERCALLREF handler )
    { m_macCurrentEvent = event ; m_macCurrentEventHandlerCallRef = handler ; }

    // adding a CFType object to be released only at the end of the current event cycle (increases the
    // refcount of the object passed), needed in case we are in the middle of an event concerning an object
    // we want to delete and cannot do it immediately
    // TODO change semantics to be in line with cocoa (make autrelease NOT increase the count)
    void                  MacAddToAutorelease( void* cfrefobj );
    void                  MacReleaseAutoreleasePool();

public:
    static wxWindow*      s_captureWindow ;
    static long           s_lastModifiers ;

    int                   m_nCmdShow;

    // mac specifics
protected:
#if wxOSX_USE_COCOA
    // override for support of custom app controllers
    virtual WX_NSObject   OSXCreateAppController();
#endif

private:
    virtual bool        DoInitGui();
    virtual void        DoCleanUp();

    WXEVENTHANDLERREF     m_macEventHandler ;
    WXEVENTHANDLERCALLREF m_macCurrentEventHandlerCallRef ;
    WXEVENTREF            m_macCurrentEvent ;

public:
    static long           s_macAboutMenuItemId ;
    static long           s_macPreferencesMenuItemId ;
    static long           s_macExitMenuItemId ;
    static wxString       s_macHelpMenuTitleName ;
    static wxString       s_macWindowMenuTitleName ;

    WXEVENTREF            MacGetCurrentEvent() { return m_macCurrentEvent ; }

    // For embedded use. By default does nothing.
    virtual void          MacHandleUnhandledEvent( WXEVENTREF ev );

    bool    MacSendKeyDownEvent( wxWindow* focus , long keyval , long modifiers , long when , wxChar uniChar ) ;
    bool    MacSendKeyUpEvent( wxWindow* focus , long keyval , long modifiers , long when , wxChar uniChar ) ;
    bool    MacSendCharEvent( wxWindow* focus , long keymessage , long modifiers , long when , wxChar uniChar ) ;
    void    MacCreateKeyEvent( wxKeyEvent& event, wxWindow* focus , long keymessage , long modifiers , long when , wxChar uniChar ) ;
    // in response of an openFiles message with Cocoa and an
    // open-document apple event
    virtual void         MacOpenFiles(const wxArrayString &fileNames) ;
    // called by MacOpenFiles for each file.
    virtual void         MacOpenFile(const wxString &fileName) ;
    // in response of a get-url apple event
    virtual void         MacOpenURL(const wxString &url) ;
    // in response of a print-document apple event
    virtual void         MacPrintFiles(const wxArrayString &fileNames) ;
    // called by MacPrintFiles for each file
    virtual void         MacPrintFile(const wxString &fileName) ;
    // in response of a open-application apple event
    virtual void         MacNewFile() ;
    // in response of a reopen-application apple event
    virtual void         MacReopenApp() ;

    // override this to return false from a non-bundled console app in order to stay in background ...
    virtual bool         OSXIsGUIApplication() { return true; }

    // Allow the user to disable the tab bar support in the application
    void                 OSXEnableAutomaticTabbing(bool enable);

#if wxOSX_USE_COCOA_OR_IPHONE
    // immediately before the native event loop launches
    virtual void         OSXOnWillFinishLaunching();
    // immediately when the native event loop starts, no events have been served yet
    virtual void         OSXOnDidFinishLaunching();
    // OS asks to terminate app, return no to stay running
    virtual bool         OSXOnShouldTerminate();
    // before application terminates
    virtual void         OSXOnWillTerminate();

private:
    bool                m_onInitResult;
    bool                m_inited;
    wxArrayString       m_openFiles;
    wxArrayString       m_printFiles;
    wxString            m_getURL;

public:
    bool                OSXInitWasCalled() { return m_inited; }
    void                OSXStoreOpenFiles(const wxArrayString &files ) { m_openFiles = files ; }
    void                OSXStorePrintFiles(const wxArrayString &files ) { m_printFiles = files ; }
    void                OSXStoreOpenURL(const wxString &url ) { m_getURL = url ; }
#endif

    // Hide the application windows the same as the system hide command would do it.
    void MacHideApp();

    wxDECLARE_EVENT_TABLE();
};

#endif
    // _WX_APP_H_


text:
package mockcompute

import (
	"context"
	"fmt"
	"sync"

	compute "google.golang.org/api/compute/v1"
	"k8s.io/kops/upup/pkg/fi/cloudup/gce"
)

type routerClient struct {
	// routers are routers keyed by project, region, and router name.
	routers map[string]map[string]map[string]*compute.Router
	sync.Mutex
}

var _ gce.RouterClient = &routerClient{}

func newRouterClient() *routerClient {
	return &routerClient{
		routers: map[string]map[string]map[string]*compute.Router{},
	}
}

func (c *routerClient) All() map[string]interface{} {
	c.Lock()
	defer c.Unlock()
	m := map[string]interface{}{}
	for _, regions := range c.routers {
		for _, rs := range regions {
			for n, r := range rs {
				m[n] = r
			}
		}
	}
	return m
}

func (c *routerClient) Insert(project, region string, r *compute.Router) (*compute.Operation, error) {
	c.Lock()
	defer c.Unlock()
	regions, ok := c.routers[project]
	if !ok {
		regions = map[string]map[string]*compute.Router{}
		c.routers[project] = regions
	}
	rs, ok := regions[region]
	if !ok {
		rs = map[string]*compute.Router{}
		regions[region] = rs
	}
	r.SelfLink = fmt.Sprintf("https://www.googleapis.com/compute/v1/projects/%s/regions/%s/routers/%s", project, region, r.Name)
	rs[r.Name] = r
	return doneOperation(), nil
}

func (c *routerClient) Delete(project, region, name string) (*compute.Operation, error) {
	c.Lock()
	defer c.Unlock()
	regions, ok := c.routers[project]
	if !ok {
		return nil, notFoundError()
	}
	rs, ok := regions[region]
	if !ok {
		return nil, notFoundError()
	}
	if _, ok := rs[name]; !ok {
		return nil, notFoundError()
	}
	delete(rs, name)
	return doneOperation(), nil
}

func (c *routerClient) Get(project, region, name string) (*compute.Router, error) {
	c.Lock()
	defer c.Unlock()
	regions, ok := c.routers[project]
	if !ok {
		return nil, notFoundError()
	}
	rs, ok := regions[region]
	if !ok {
		return nil, notFoundError()
	}
	r, ok := rs[name]
	if !ok {
		return nil, notFoundError()
	}
	return r, nil
}

func (c *routerClient) List(ctx context.Context, project, region string) ([]*compute.Router, error) {
	c.Lock()
	defer c.Unlock()
	regions, ok := c.routers[project]
	if !ok {
		return nil, nil
	}
	rs, ok := regions[region]
	if !ok {
		return nil, nil
	}
	var l []*compute.Router
	for _, r := range rs {
		l = append(l, r)
	}
	return l, nil
}


text:
#
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_SEQ_REST_N_HPP
# define BOOST_PREPROCESSOR_SEQ_REST_N_HPP
#
# include <boost/preprocessor/arithmetic/inc.hpp>
# include <boost/preprocessor/comparison/not_equal.hpp>
# include <boost/preprocessor/config/config.hpp>
# include <boost/preprocessor/control/expr_iif.hpp>
# include <boost/preprocessor/facilities/identity.hpp>
# include <boost/preprocessor/logical/bitand.hpp>
# include <boost/preprocessor/seq/detail/is_empty.hpp>
# include <boost/preprocessor/seq/detail/split.hpp>
# include <boost/preprocessor/tuple/elem.hpp>
#
# /* BOOST_PP_SEQ_REST_N */
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
#    define BOOST_PP_SEQ_REST_N(n, seq) BOOST_PP_SEQ_REST_N_DETAIL_EXEC(n, seq, BOOST_PP_SEQ_DETAIL_EMPTY_SIZE(seq))
# else
#    define BOOST_PP_SEQ_REST_N(n, seq) BOOST_PP_SEQ_REST_N_I(n, seq)
#    define BOOST_PP_SEQ_REST_N_I(n, seq) BOOST_PP_SEQ_REST_N_DETAIL_EXEC(n, seq, BOOST_PP_SEQ_DETAIL_EMPTY_SIZE(seq))
# endif
#
#    define BOOST_PP_SEQ_REST_N_DETAIL_EXEC(n, seq, size) \
		BOOST_PP_EXPR_IIF \
			( \
			BOOST_PP_BITAND \
				( \
				BOOST_PP_SEQ_DETAIL_IS_NOT_EMPTY_SIZE(size), \
				BOOST_PP_NOT_EQUAL(n,size) \
				), \
			BOOST_PP_TUPLE_ELEM(2, 1, BOOST_PP_SEQ_SPLIT(BOOST_PP_INC(n), BOOST_PP_IDENTITY( (nil) seq )))() \
			) \
/**/
#
# endif


text:
var cdb = require('cartodb.js');

/**
 * Model that represents a visualization (v3)
 *
 * Even though a table might be represented as a Visualization in some cases, please use TableModel if you want to work
 * with the table data instead of adding table-specific methods here.
 */
module.exports = cdb.core.Model.extend({

  initialize: function (attrs, opts) {
    if (!opts.configModel) throw new Error('configModel is required');

    this._configModel = opts.configModel;
  },

  urlRoot: function () {
    var baseUrl = this._configModel.get('base_url');
    var version = this._configModel.urlVersion('visualization');
    return baseUrl + '/api/' + version + '/viz';
  }

});