text:
package edu.mayo.mprc.swift.ui.server;

import edu.mayo.mprc.GWTServiceExceptionFactory;
import edu.mayo.mprc.MprcException;
import edu.mayo.mprc.common.client.GWTServiceException;
import edu.mayo.mprc.common.server.SpringGwtServlet;
import edu.mayo.mprc.database.Change;
import edu.mayo.mprc.dbcurator.model.CurationDao;
import edu.mayo.mprc.msmseval.MSMSEvalParamFile;
import edu.mayo.mprc.swift.MainFactoryContext;
import edu.mayo.mprc.swift.db.SearchEngine;
import edu.mayo.mprc.swift.db.SwiftDao;
import edu.mayo.mprc.swift.dbmapping.SearchRun;
import edu.mayo.mprc.swift.dbmapping.SwiftSearchDefinition;
import edu.mayo.mprc.swift.params2.*;
import edu.mayo.mprc.swift.params2.mapping.ParamsInfo;
import edu.mayo.mprc.swift.params2.mapping.ParamsValidations;
import edu.mayo.mprc.swift.params2.mapping.Validation;
import edu.mayo.mprc.swift.params2.mapping.ValidationSeverity;
import edu.mayo.mprc.swift.resources.WebUi;
import edu.mayo.mprc.swift.resources.WebUiHolder;
import edu.mayo.mprc.swift.search.SwiftSearcherCaller;
import edu.mayo.mprc.swift.ui.client.rpc.*;
import edu.mayo.mprc.swift.ui.client.rpc.files.*;
import edu.mayo.mprc.swift.ui.client.service.Service;
import edu.mayo.mprc.unimod.UnimodDao;
import edu.mayo.mprc.utilities.NotHiddenFilter;
import edu.mayo.mprc.utilities.exceptions.ExceptionUtilities;
import edu.mayo.mprc.workspace.User;
import edu.mayo.mprc.workspace.WorkspaceDao;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Lists files and folders for given path (relative to specified root).
 * The result is returned as a tree of objects.
 * <p/>
 * Supports the concept of "expanded paths" - those paths are recursed and returned fully,
 * otherwise the result of a single call lists just contents of a single directory without recursion.
 */
public final class ServiceImpl extends SpringGwtServlet implements Service, ApplicationContextAware {
	private static final long serialVersionUID = 20071220L;
	private static final Logger LOGGER = Logger.getLogger(ServiceImpl.class);

	// String of allowed extensions, separated by | signs. The extensions are case insensitive.
	private static final String ALLOWED_EXTENSIONS = ".RAW|.raw|.mgf|.mzML";
	public static final InputFileFilter FILTER = new InputFileFilter(ALLOWED_EXTENSIONS, ".d", true);
	private static final InputFileFilter FILTER_DIRS = new InputFileFilter(ALLOWED_EXTENSIONS, "", true);

	private static final ClientUser[] EMPTY_USER_LIST = new ClientUser[0];
	public static final String AGILENT_FOLDER_SUFFIX = ".d";

	private WebUiHolder webUiHolder;

	private SwiftDao swiftDao;
	private CurationDao curationDao;
	private ParamsDao paramsDao;
	private ParamsInfo paramsInfo;
	private UnimodDao unimodDao;
	private WorkspaceDao workspaceDao;
	private SwiftSearcherCaller swiftSearcherCaller;

	public ServiceImpl() {
	}

	@Override
	public Entry listFiles(final String relativePath, final String[] expandedPaths) throws GWTServiceException {
		try {
			final Entry rootEntry = new DirectoryEntry("(root)");
			final File[] expandedFiles;
			if (expandedPaths == null) {
				expandedFiles = EMPTY_EXPANDED_FILES;
			} else {
				expandedFiles = new File[expandedPaths.length];
				for (int i = 0; i < expandedPaths.length; i++) {
					expandedFiles[i] = new File(getBrowseRoot(), expandedPaths[i]);
				}
			}
			listDirectoryContents(rootEntry, new File(getBrowseRoot(), relativePath), expandedFiles);
			return rootEntry;
		} catch (Exception t) {
			LOGGER.error("Could not list files", t);
			throw GWTServiceExceptionFactory.createException("Could not list files", t);
		}
	}

	@Override
	public ClientUser[] listUsers() throws GWTServiceException {
		try {
			getWorkspaceDao().begin();
			final List<User> users = getWorkspaceDao().getUsers(true);

			final ClientUser[] result;
			if (users != null) {
				result = new ClientUser[users.size()];
				for (int i = 0; i < users.size(); i++) {
					final User user = users.get(i);
					result[i] = getClientProxyGenerator().convertTo(user);
				}
			} else {
				result = EMPTY_USER_LIST;
			}
			getWorkspaceDao().commit();
			return result;
		} catch (Exception t) {
			getWorkspaceDao().rollback();
			LOGGER.error("Could not list users", t);
			throw GWTServiceExceptionFactory.createException("Could not list users", t);
		}
	}

	/**
	 * TODO: This shoudl be in {@link edu.mayo.mprc.swift.search.DefaultSwiftSearcherCaller}, however the caller has no clue about {@link ClientSwiftSearchDefinition}.
	 */
	@Override
	public void startSearch(final ClientSwiftSearchDefinition def) throws GWTServiceException {
		try {
			final HttpSession session = getSession();
			getSwiftDao().begin();
			final ParameterSetCache cache = new ParameterSetCache(session, getParamsDao());

			SearchEngineParameters parameters = cache.getFromCacheHibernate(def.getParamSet());
			if (parameters.getId() == null) {
				parameters = getParamsDao().addSearchEngineParameters(parameters);
			}

			SwiftSearchDefinition swiftSearch = getClientProxyGenerator().convertFrom(def, parameters);

			final SearchRun previousSearchRun = getPreviousSearchRun(def.getPreviousSearchRunId(), swiftSearch);

			final SwiftSearchDefinition newSwiftSearch = getSwiftSearcherCaller().validateAndSaveSearchDefinition(swiftSearch);

			getSwiftDao().commit(); // We must commit here before we send the search over (it is loaded from the database)

			getSwiftSearcherCaller().submitSearch(newSwiftSearch.getId(),
					newSwiftSearch.getTitle(),
					previousSearchRun == null ? 0 : previousSearchRun.getId(),
					def.isFromScratch(),
					def.isLowPriority() ? -1 : 0);
		} catch (Exception e) {
			getSwiftDao().rollback();
			LOGGER.error("Search could not be started", e);
			throw GWTServiceExceptionFactory.createException("Search could not be started", e);
		}
	}

	private SearchRun getPreviousSearchRun(final int previousSearchRunId, final SwiftSearchDefinition swiftSearch) {
		boolean rerunPreviousSearch = false;
		SearchRun previousSearchRun;
		if (previousSearchRunId > 0) {
			// We already ran the search before.
			previousSearchRun = getSwiftDao().getSearchRunForId(previousSearchRunId);
			if (previousSearchRun.getTitle().equals(swiftSearch.getTitle())) {
				// The titles match, output folders match, but since this is a reload, it is okay
				rerunPreviousSearch = true;
				final Integer searchId = previousSearchRun.getSwiftSearch();
				final SwiftSearchDefinition searchDefinition = getSwiftDao().getSwiftSearchDefinition(searchId);
				if (searchDefinition == null || !searchDefinition.getOutputFolder().equals(swiftSearch.getOutputFolder())) {
					previousSearchRun = null;
					// Since the folders do not match, we will rerun, but will not hide the previous search run
					// from the list
				}
			} else {
				previousSearchRun = null;
			}
		} else {
			previousSearchRun = null;
		}
		return previousSearchRun;
	}

	@Override
	public ClientLoadedSearch loadSearch(final int searchRunId) throws GWTServiceException {
		try {
			final HttpSession session = getSession();
			getSwiftDao().begin();
			final ParameterSetCache cache = new ParameterSetCache(session, getParamsDao());
			final SearchRun searchRun = getSwiftDao().getSearchRunForId(searchRunId);
			final SwiftSearchDefinition original = getSwiftDao().getSwiftSearchDefinition(searchRun.getSwiftSearch());
			final Resolver resolver = new Resolver(cache);
			final ClientSwiftSearchDefinition proxy = getClientProxyGenerator().convertTo(original, resolver);
			final ClientLoadedSearch result = new ClientLoadedSearch(searchRunId, proxy, resolver.isClientParamSetListChanged() ? makeParamSetList(cache) : null);
			getSwiftDao().commit();
			return result;
		} catch (Exception e) {
			getSwiftDao().rollback();
			LOGGER.error("Could not load existing search for id: " + searchRunId, e);
			throw GWTServiceExceptionFactory.createException("Search could not be loaded for id: " + searchRunId, e);
		}
	}

	@Override
	public List<ClientSearchEngine> listSearchEngines() throws GWTServiceException {
		final List<ClientSearchEngine> infos = new ArrayList<ClientSearchEngine>();
		for (final SearchEngine engine : getSearchEngines()) {
			infos.add(new ClientSearchEngine(
					new ClientSearchEngineConfig(engine.getCode(), engine.getVersion()),
					engine.getFriendlyName(), engine.isOnByDefault(),
					engine.getEngineMetadata().getOrder()));
		}
		return infos;
	}

	@Override
	public List<SpectrumQaParamFileInfo> listSpectrumQaParamFiles() throws GWTServiceException {

		final List<SpectrumQaParamFileInfo> paramFiles = new ArrayList<SpectrumQaParamFileInfo>();
		if (isMsmsEval()) {
			for (final MSMSEvalParamFile paramFile : getSpectrumQaParamFiles()) {
				paramFiles.add(new SpectrumQaParamFileInfo(paramFile.getPath(), paramFile.getDescription()));
			}
		}
		return paramFiles;
	}

	@Override
	public boolean isScaffoldReportEnabled() throws GWTServiceException {
		return isScaffoldReport();
	}

	@Override
	public FileInfo[] findFiles(final String[] relativePaths) throws GWTServiceException {
		try {
			// Filter paths so we never have both parent and a child in the list.
			final List<String> filteredPaths = new ArrayList<String>();
			for (int i = 0; i < relativePaths.length; i++) {
				int j;
				for (j = 0; j < relativePaths.length; j++) {
					// Our path is a child, throw it away
					if (i != j && relativePaths[i].startsWith(relativePaths[j])) {
						break;
					}
				}
				// This path is legitimate, not a child of anything
				if (j == relativePaths.length) {
					filteredPaths.add(relativePaths[i]);
				}
			}

			final List<FileInfo> list = new ArrayList<FileInfo>();

			for (final String path : filteredPaths) {
				addPathToList(new File(getBrowseRoot(), path), list);
			}

			final FileInfo[] results = new FileInfo[list.size()];
			return list.toArray(results);
		} catch (Exception t) {
			LOGGER.error("Could not find files", t);
			throw GWTServiceExceptionFactory.createException("Could not find files", t);
		}
	}

	private void addPathToList(final File file, final List<FileInfo> list) {
		if (!file.exists() || file.isHidden()) {
			return;
		}
		if (file.isDirectory() && !isDirectoryTreatedAsFile(file)) {
			// Recursively add the contents
			// TODO: Limit the running time
			final File[] files = file.listFiles(FILTER_DIRS);
			Arrays.sort(files);
			for (final File path : files) {
				addPathToList(path, list);
			}
		} else {
			if (FILTER.accept(file.getParentFile(), file.getName())) {
				String path = file.getAbsolutePath();
				path = path.substring(getBrowseRoot().getAbsolutePath().length());
				path = path.replaceAll(Pattern.quote(File.separator), "/");
				list.add(new FileInfo(path, file.length(), new Date(file.lastModified())));
			}
		}
	}

	private boolean isDirectoryTreatedAsFile(final File file) {
		return file.getName().endsWith(AGILENT_FOLDER_SUFFIX);
	}

	/**
	 * Returns true if at least one of the subs is subfolder (direct or indirect) of dir.
	 * If subs are null, the result is false, if dir is null, the result is true. This
	 * follows the logic, that the subs are a list of "expanded" paths and we are trying to determine,
	 * whether the given folder should be expanded or not.
	 *
	 * @param dir  The folder that has to contain at least one of the subs.
	 * @param subs Array of subfolder paths.
	 * @return True when at least one of the subs is inside dir (directly or not).
	 */
	private boolean isSubfolder(final File dir, final File[] subs) {
		if (subs == null) {
			return false;
		}
		if (dir == null) {
			return true;
		}
		for (final File sub : subs) {
			if (sub.getPath().startsWith(dir.getPath())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Lists contents of given directory and appends them to given file element.
	 * Errors are appended as special "error node".
	 *
	 * @param rootEntry     Entry to insert contents into.
	 * @param root          Root directory.
	 * @param expandedPaths List of paths that have to be expanded in the listing.
	 */
	private void listDirectoryContents(final Entry rootEntry, final File root, final File[] expandedPaths) {
		// find all directories
		File dirs[] = null;
		try {
			dirs = root.listFiles(new NotHiddenFilter());
		} catch (SecurityException e) {
			LOGGER.debug("Could not list contents of " + root.getAbsolutePath(), e);
			rootEntry.addChild(new ErrorEntry(MessageFormat.format("Could not list contents of {0}: {1}", root.getAbsolutePath(), e.getMessage())));
			return;
		}

		if (dirs != null) {
			Arrays.sort(dirs, new FilenameComparator());
			for (final File dir : dirs) {
				if (dir.isDirectory()) {
					final DirectoryEntry directory = new DirectoryEntry(dir.getName());
					rootEntry.addChild(directory);
					// If this directory should be expanded
					if (isSubfolder(dir, expandedPaths)) {
						listDirectoryContents(directory, dir, expandedPaths);
					}
				}
			}
		}

		// find all the files with allowed extension
		File[] files = null;
		try {
			files = root.listFiles(FILTER);
		} catch (SecurityException e) {
			LOGGER.debug("Could not list contents of " + root.getAbsolutePath(), e);
			rootEntry.addChild(new ErrorEntry(MessageFormat.format("Could not list contents of {0}: {1}", root.getAbsolutePath(), e.getMessage())));
			return;
		}
		if (files != null) {
			Arrays.sort(files, new FilenameComparator());
			for (final File file : files) {
				if (!file.isDirectory()) {
					rootEntry.addChild(new FileEntry(file.getName()));
				}
			}
		}
	}

	private static final File[] EMPTY_EXPANDED_FILES = new File[0];

	@Override
	public Boolean login(final String userName, final String password) throws GWTServiceException {
		return true;
	}

	@Override
	public synchronized ClientParamSet save(final ClientParamSet toCopy, final String newName, final String ownerEmail,
	                                        final String ownerInitials,
	                                        final boolean permanent) throws GWTServiceException {
		try {
			final HttpSession session = getSession();
			getParamsDao().begin();
			final ParameterSetCache cache = new ParameterSetCache(session, getParamsDao());
			SearchEngineParameters ps = cache.getFromCacheHibernate(toCopy);
			final ClientParamSet ret;
			if (!permanent) {
				ret = cache.cloneTemporary(toCopy);
			} else {
				final Change change = new Change("Saving parameter set " + newName, new DateTime());

				// Delete if already exists
				final SavedSearchEngineParameters params = getParamsDao().findSavedSearchEngineParameters(newName);
				if (params != null) {
					getParamsDao().deleteSavedSearchEngineParameters(params, change);
				}

				ps = getParamsDao().addSearchEngineParameters(ps);
				final User user = getWorkspaceDao().getUserByEmail(ownerEmail);

				SavedSearchEngineParameters newParams = new SavedSearchEngineParameters(
						newName, user, ps);

				newParams = getParamsDao().addSavedSearchEngineParameters(newParams, change);

				if (toCopy.isTemporary()) {
					cache.removeFromCache(toCopy);
				}
				ret = new ClientParamSet(newParams.getId(), newName, ownerEmail, ownerInitials);
			}
			getParamsDao().commit();
			return ret;
		} catch (Exception e) {
			getParamsDao().rollback();
			LOGGER.error("Could not save client parameter set", e);
			throw GWTServiceExceptionFactory.createException("Could not save client parameter set", e);
		}
	}

	@Override
	public ClientParamFile[] getFiles(final ClientParamSet paramSet) throws GWTServiceException {
		try {
			final HttpSession session = getSession();
			getParamsDao().begin();
			final ParameterSetCache cache = new ParameterSetCache(session, getParamsDao());
			final SearchEngineParameters ps = cache.getFromCache(paramSet);
			Collection<SearchEngine> allEngines = getSearchEngines();
			final List<ClientParamFile> files = new ArrayList<ClientParamFile>(allEngines.size());

			for (final SearchEngine engine : allEngines) {
				if (ps.getEnabledEngines().isEnabled(engine.getEngineConfig())) {
					final String parameters = engine.parametersToString(ps, null, paramsInfo);
					files.add(new ClientParamFile(engine.getFriendlyName(), parameters));
				}
			}
			getParamsDao().commit();
			final ClientParamFile[] result = new ClientParamFile[files.size()];
			return files.toArray(result);
		} catch (Exception e) {
			getParamsDao().rollback();
			LOGGER.error("Could not get parameter files", e);
			throw GWTServiceExceptionFactory.createException("Could not get parameter files", e);
		}
	}

	@Override
	public ClientParamSetValues getParamSetValues(final ClientParamSet paramSet) throws GWTServiceException {
		try {
			final HttpSession session = getSession();
			getParamsDao().begin();
			final ParameterSetCache cache = new ParameterSetCache(session, getParamsDao());
			final SearchEngineParameters ps = cache.getFromCache(paramSet);
			Collection<SearchEngine> enabledSearchEngines = getEnabledSearchEngines(ps);
			final ParamsValidations paramsValidations = SearchEngine.validate(ps, enabledSearchEngines, paramsInfo);
			final ClientParamSetValues clientParamSetValues = getClientProxyGenerator().convertValues(ps, paramsValidations);
			getParamsDao().commit();
			return clientParamSetValues;
		} catch (Exception e) {
			getParamsDao().rollback();
			LOGGER.error("Could not get parameter set values", e);
			throw GWTServiceExceptionFactory.createException("Could not get parameter set values", e);
		}
	}

	private Collection<SearchEngine> getEnabledSearchEngines(SearchEngineParameters ps) {
		Collection<SearchEngine> enabledSearchEngines = new ArrayList<SearchEngine>();
		Collection<SearchEngine> allEngines = getSearchEngines();
		for (SearchEngineConfig config : ps.getEnabledEngines().getEngineConfigs()) {
			for (SearchEngine engine : allEngines) {
				if (engine.matchesConfig(config)) {
					enabledSearchEngines.add(engine);
				}
			}
		}
		return enabledSearchEngines;
	}

	@Override
	public synchronized ClientParamSetList getParamSetList() throws GWTServiceException {
		try {
			final HttpSession session = getSession();
			getParamsDao().begin();
			final ParameterSetCache cache = new ParameterSetCache(session, getParamsDao());
			final ClientParamSetList paramSetList = makeParamSetList(cache);
			getParamsDao().commit();
			return paramSetList;
		} catch (Exception e) {
			getParamsDao().rollback();
			LOGGER.error("Could not obtain parameter set list", e);
			throw GWTServiceExceptionFactory.createException("Could not obtain parameter set list", e);
		}
	}

	private ClientParamSetList makeParamSetList(final ParameterSetCache cache) {
		final List<SavedSearchEngineParameters> engineParametersList = getParamsDao().savedSearchEngineParametersNoData();
		return ClientProxyGenerator.getClientParamSetList(engineParametersList, cache.getTemporaryClientParamList());
	}

	@Override
	public List<List<ClientValue>> getAllowedValues(final String[] params) throws GWTServiceException {
		try {
			getParamsDao().begin();

			final List<List<ClientValue>> values = new ArrayList<List<ClientValue>>();
			for (final String param : params) {
				final ParamName name = ParamName.getById(param);
				values.add(getClientProxyGenerator().getAllowedValues(name, getParamsInfo()));
			}
			getParamsDao().commit();
			return values;
		} catch (Exception e) {
			getParamsDao().rollback();
			LOGGER.error("Could not get parameter set allowed values", e);
			throw GWTServiceExceptionFactory.createException("Could not refresh parameter set", e);
		}
	}

	@Override
	public ClientParamsValidations update(final ClientParamSet paramSet, final String param, final ClientValue value) throws GWTServiceException {
		try {
			final HttpSession session = getSession();
			getParamsDao().begin();
			final ParameterSetCache cache = new ParameterSetCache(session, getParamsDao());

			final SearchEngineParameters ps = cache.getFromCache(paramSet);
			try {
				final ParamName name = ParamName.getById(param);
				ps.setValue(name, getClientProxyGenerator().convert(value, getParamsInfo().getAllowedValues(name)));
				final ParamsValidations validations = SearchEngine.validate(ps, getEnabledSearchEngines(ps), paramsInfo);
				validateAdditionalSettings(validations, name, value);
				final ClientParamsValidations validationList = getClientProxyGenerator().convertTo(validations);
				getParamsDao().commit();
				cache.updateCache(paramSet, ps);
				return validationList;
			} catch (ClientProxyGenerator.ConversionException e) {
				return getValidationForException(param, e.getCause());
			} catch (Exception e) {
				return getValidationForException(param, e);
			}
		} catch (Exception e) {
			getParamsDao().rollback();
			LOGGER.error("Could not update parameter set", e);
			throw GWTServiceExceptionFactory.createException("Could not update parameter set", e);
		}
	}

	private void validateAdditionalSettings(final ParamsValidations validations, final ParamName name, final ClientValue value) {
		if (ParamName.ExtractMsnSettings == name && value instanceof ClientExtractMsnSettings) {
			final String command = ((ClientExtractMsnSettings) value).getCommand();
			if (ExtractMsnSettings.MSCONVERT.equals(command) && !isMsconvertEnabled()) {
				validations.addValidation(name, new Validation("msconvert is not supported", ValidationSeverity.ERROR, name,
						ExtractMsnSettings.getExtractMsnSettings(), null));
			} else if (ExtractMsnSettings.EXTRACT_MSN.equals(command) && !isExtractMsnEnabled()) {
				validations.addValidation(name, new Validation("extract_msn is not supported", ValidationSeverity.ERROR, name,
						ExtractMsnSettings.getMsconvertSettings(), null));
			}
		}
	}

	@Override
	public void delete(final ClientParamSet paramSet) throws GWTServiceException {
		try {
			final HttpSession session = getSession();
			getParamsDao().begin();
			final SavedSearchEngineParameters savedSearchEngineParameters = getParamsDao().findSavedSearchEngineParameters(paramSet.getName());
			if (savedSearchEngineParameters != null) {
				getParamsDao().deleteSavedSearchEngineParameters(savedSearchEngineParameters, new Change("Deleting saved search engine parameters [" + savedSearchEngineParameters.getName() + "] with id " + savedSearchEngineParameters.getId(), new DateTime()));
				final ParameterSetCache cache = new ParameterSetCache(session, getParamsDao());
				cache.removeFromCache(paramSet);
			}
			getParamsDao().commit();
		} catch (Exception e) {
			getParamsDao().rollback();
			final String errMsg = "Could not delete parameter set " + (paramSet != null ? paramSet.getName() : "");
			LOGGER.error(errMsg, e);
			throw GWTServiceExceptionFactory.createException(errMsg, e);
		}
	}

	private ClientParamsValidations getValidationForException(final String param, final Throwable e) {
		final ClientValidationList list = new ClientValidationList();
		final ClientValidation cv = new ClientValidation(e.getMessage());
		cv.setThrowableStackTrace(ExceptionUtilities.stringifyStackTrace(e));
		cv.setParamId(param);
		cv.setSeverity(ClientValidation.SEVERITY_ERROR);
		cv.setThrowableMessage(MprcException.getDetailedMessage(e));
		list.add(cv);
		final Map<String, ClientValidationList> map = new HashMap<String, ClientValidationList>();
		map.put(param, list);
		return new ClientParamsValidations(map);
	}

	@Override
	public InitialPageData getInitialPageData(final Integer previousSearchId) throws GWTServiceException {
		final String[] params = {
				"sequence.database",
				"sequence.enzyme",
				"sequence.missed_cleavages",
				"modifications.fixed",
				"modifications.variable",
				"tolerance.peptide",
				"tolerance.fragment",
				"instrument",
				"extractMsnSettings",
				"scaffoldSettings",
				"enabledEngines"
		};
		final List<List<ClientValue>> allowedValues = getAllowedValues(params);
		final HashMap<String, List<ClientValue>> map = new HashMap<String, List<ClientValue>>(params.length);

		final Iterator<List<ClientValue>> iterator = allowedValues.iterator();
		for (final String param : params) {
			map.put(param, iterator.next());
		}

		return new InitialPageData(
				new HashMap<String, String>(getWebUi().getUiConfiguration()),
				listUsers(),
				previousSearchId == null ? null : loadSearch(previousSearchId),
				getParamSetList(),
				map,
				listSearchEngines(),
				listSpectrumQaParamFiles(),
				isScaffoldReportEnabled(),
				isExtractMsnEnabled(),
				isMsconvertEnabled());
	}

	@Override
	public boolean outputFolderExists(final String outputFolder) throws GWTServiceException {
		final File file = new File(getBrowseRoot(), outputFolder);
		return file.exists();
	}

	@Override
	public HashMap<String, String> getUiConfig() {
		return new HashMap<String, String>(getWebUi().getUiConfiguration());
	}

	/**
	 * Compare session id from Cookie with passed in token to prevent CSRF.
	 *
	 * @see <a href="http://groups.google.com/group/Google-Web-Toolkit/web/security-for-gwt-applications">Security for GWT applications</a>
	 * @see <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">Cross-site request forgery</a>
	 */
	private HttpSession getSession() {
		return getThreadLocalRequest().getSession();
	}

	public WebUiHolder getWebUiHolder() {
		return webUiHolder;
	}

	public void setWebUiHolder(final WebUiHolder webUiHolder) {
		this.webUiHolder = webUiHolder;
	}

	public WebUi getWebUi() {
		return getWebUiHolder().getWebUi();
	}

	public Collection<SearchEngine> getSearchEngines() {
		return getWebUi().getSearchEngines();
	}

	public File getBrowseRoot() {
		return getWebUi().getBrowseRoot();
	}

	public void setSwiftDao(final SwiftDao swiftDao) {
		this.swiftDao = swiftDao;
	}

	public SwiftDao getSwiftDao() {
		return swiftDao;
	}

	public void setWorkspaceDao(final WorkspaceDao workspaceDao) {
		this.workspaceDao = workspaceDao;
	}

	public WorkspaceDao getWorkspaceDao() {
		return workspaceDao;
	}

	public void setCurationDao(final CurationDao curationDao) {
		this.curationDao = curationDao;
	}

	public CurationDao getCurationDao() {
		return curationDao;
	}

	public void setParamsDao(final ParamsDao paramsDao) {
		this.paramsDao = paramsDao;
	}

	public ParamsDao getParamsDao() {
		return paramsDao;
	}

	public void setParamsInfo(final ParamsInfo paramsInfo) {
		this.paramsInfo = paramsInfo;
	}

	public ParamsInfo getParamsInfo() {
		return paramsInfo;
	}

	public SwiftSearcherCaller getSwiftSearcherCaller() {
		return swiftSearcherCaller;
	}

	public void setSwiftSearcherCaller(SwiftSearcherCaller swiftSearcherCaller) {
		this.swiftSearcherCaller = swiftSearcherCaller;
	}

	public ClientProxyGenerator getClientProxyGenerator() {
		return new ClientProxyGenerator(getUnimodDao(), getWorkspaceDao(), getSwiftDao(), getBrowseRoot());
	}

	public List<MSMSEvalParamFile> getSpectrumQaParamFiles() {
		return getWebUi().getSpectrumQaParamFiles();
	}

	public boolean isMsmsEval() {
		return getWebUi().isMsmsEval();
	}

	public boolean isScaffoldReport() {
		return getWebUi().isScaffoldReport();
	}

	public void setUnimodDao(final UnimodDao unimodDao) {
		this.unimodDao = unimodDao;
	}

	public UnimodDao getUnimodDao() {
		return unimodDao;
	}

	@Override
	public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
		MainFactoryContext.setContext(applicationContext);
	}

	public boolean isExtractMsnEnabled() {
		return getWebUi().isExtractMsn();
	}

	public boolean isMsconvertEnabled() {
		return getWebUi().isMsconvert();
	}

	private class Resolver implements ClientParamSetResolver {

		private ParameterSetCache cache;
		private boolean clientParamSetListChanged;

		Resolver(final ParameterSetCache cache) {
			this.cache = cache;
			clientParamSetListChanged = false;
		}

		@Override
		public ClientParamSet resolve(final SearchEngineParameters parameters, final User user) {
			// Find all saved parameter sets that match these parameters
			final SavedSearchEngineParameters bestSavedSearchEngineParameters = getParamsDao().findBestSavedSearchEngineParameters(parameters, user);
			if (bestSavedSearchEngineParameters != null) {
				return new ClientParamSet(
						bestSavedSearchEngineParameters.getId(),
						bestSavedSearchEngineParameters.getName(),
						bestSavedSearchEngineParameters.getUser().getUserName(),
						bestSavedSearchEngineParameters.getUser().getInitials());
			}

			// We did not find a perfect match within saved search parameters
			// Try the temporary ones
			final ClientParamSet matchingTemporaryParamSet = cache.findMatchingTemporaryParamSet(parameters);
			if (matchingTemporaryParamSet != null) {
				return matchingTemporaryParamSet;
			}

			// We will make a plain temporary parameter set and return that one
			clientParamSetListChanged = true;
			SearchEngineParameters copy = parameters.copyNullId();
			return cache.installTemporary("Previous search parameters", user.getUserName(), user.getInitials(), copy);
		}

		@Override
		public boolean isClientParamSetListChanged() {
			return clientParamSetListChanged;
		}

	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Closing a Connection</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.0.5 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="ECPG - Embedded SQL in C"
HREF="ecpg.html"><LINK
REL="PREVIOUS"
TITLE="Connecting to the Database Server"
HREF="ecpg-connect.html"><LINK
REL="NEXT"
TITLE="Running SQL Commands"
HREF="ecpg-commands.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2011-09-22T22:21:03">

PostgreSQL 9.0.5 Documentation

Prev	Fast Backward	Chapter 33. ECPG - Embedded <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> in C	Fast Forward	Next

33.3. Closing a Connection

   To close a connection, use the following statement:

EXEC SQL DISCONNECT [<TT
CLASS="REPLACEABLE"
>connection</TT
>];

   The <TT
CLASS="REPLACEABLE"
>connection</TT
> can be specified
   in the following ways:

      <TT
CLASS="LITERAL"
><TT
CLASS="REPLACEABLE"
>connection-name</TT
></TT
>

      <TT
CLASS="LITERAL"
>DEFAULT</TT
>

      <TT
CLASS="LITERAL"
>CURRENT</TT
>

      <TT
CLASS="LITERAL"
>ALL</TT
>

   If no connection name is specified, the current connection is
   closed.

   It is good style that an application always explicitly disconnect
   from every connection it opened.

Prev	Home	Next

Connecting to the Database Server	Up	Running SQL Commands

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 17: 119 (1919)

#### Original name
Miyakeomyces bambusae Hara, 1913

### Remarks
null


text:
<?php

namespace Surfnet\StepupMiddleware\ManagementBundle\Validator;

use Assert\Assertion;
use Surfnet\StepupMiddleware\ManagementBundle\Validator\Assert as StepupAssert;

class GatewayConfigurationValidator implements ConfigurationValidatorInterface
{
    /**
     * @var \Surfnet\StepupMiddleware\ManagementBundle\Validator\IdentityProviderConfigurationValidator
     */
    private $identityProviderConfigurationValidator;

    /**
     * @var \Surfnet\StepupMiddleware\ManagementBundle\Validator\ServiceProviderConfigurationValidator
     */
    private $serviceProviderConfigurationValidator;

    public function __construct(
        IdentityProviderConfigurationValidator $identityProviderConfigurationValidator,
        ServiceProviderConfigurationValidator $serviceProviderConfigurationValidator
    ) {
        $this->identityProviderConfigurationValidator = $identityProviderConfigurationValidator;
        $this->serviceProviderConfigurationValidator = $serviceProviderConfigurationValidator;
    }

    /**
     * @param array  $gatewayConfiguration
     * @param string $propertyPath
     */
    public function validate(array $gatewayConfiguration, $propertyPath)
    {
        StepupAssert::keysMatch(
            $gatewayConfiguration,
            ['service_providers', 'identity_providers'],
            "Expected properties 'service_providers' and 'identity_providers'",
            $propertyPath
        );

        $this->validateIdentityProviders(
            $gatewayConfiguration['identity_providers'],
            $propertyPath . '.identity_providers'
        );
        $this->validateServiceProviders(
            $gatewayConfiguration['service_providers'],
            $propertyPath . '.service_providers'
        );
    }

    private function validateIdentityProviders($identityProviders, $propertyPath)
    {
        Assertion::isArray(
            $identityProviders,
            'identity_providers must have an array of identity provider configurations as value',
            $propertyPath
        );

        foreach ($identityProviders as $index => $identityProvider) {
            $path = $propertyPath . '[' . $index . ']';
            Assertion::isArray($identityProvider, 'Identity provider must be an object', $path);

            $this->identityProviderConfigurationValidator->validate($identityProvider, $path);
        }
    }

    private function validateServiceProviders($serviceProviders, $propertyPath)
    {
        Assertion::isArray(
            $serviceProviders,
            'service_providers must have an array of service provider configurations as value',
            $propertyPath
        );
        Assertion::true(
            count($serviceProviders) >= 1,
            'at least one service_provider must be configured',
            $propertyPath
        );

        foreach ($serviceProviders as $index => $serviceProvider) {
            $path = $propertyPath . '[' . $index . ']';
            Assertion::isArray($serviceProvider, 'Service provider must be an object', $path);

            $this->serviceProviderConfigurationValidator->validate($serviceProvider, $path);
        }
    }
}


text:
import subprocess
import shlex
import string
import time
import itertools
import os
import urllib
import json
import urllib2
import types
from pprint import pprint
from threading import Thread
from escravo import GerenciadorEscravo

# pertence ao no Mestre
class ProcessoDesc:
    id = 0
    init_time = ''
    status = 'wait' # wait, running, killed, finished

    def __init__(self, id=0, init_time='',status='wait'):
        self.id = id
        self.init_time = init_time
        self.status = status # wait, running, killed, finished

# pertence ao no Mestre
class Escravo:
    id = 0
    ip = "0.0.0.0"
    lista_processo = []
    # pp eh o max de processos q este no suporta
    pp = 1
    live = False
    thread = None

    def __init__(self, id=0, ip='0.0.0.0',pp=1):
        self.id = id
        self.ip = ip
        self.pp = pp
        self.live = True
        #self.processando = False

    """ {
        processo: [
            {
                id=0,
                init_time=2011-03-13 20:01:32,
                status = 'runing'
            },
            {
            ...
            }
        ]
        }
    """

    def getProcessos(self, json):
        # analisar json
        # self.lista_processo.append(new ProcessoDesc(id,init_time,status))
        print json

    def getAlive(self,):
		if isinstance(self.thread,types.NoneType):
			return False
		else:
			return self.thread.is_alive()

# pertence ao no Escravo
class GerenciadorMestre:

    id = 0
    ip = None
    port = None
    flagProcesso = False
    itera_count = 0
    escravo_count = 0
    lista_escravo = []
    nfs_path = None
    #base_init = ''
    parametros = ''

    Gprocess_count = 0

    process_count = 0   # contador de processos instanciados, zera quando inicializa processamento
    total_pro = 0   # valor setado na inicializacao do mestre(interface web)

    fase01 = ''
    fase02 = ''
    fase03 = ''

    execFase = 0 # fase01 -> 1, fase02 -> 2, fase03 -> 3, fim -> 4

    threadProcessamento = None

    '''
    def __init__(self, nfs_path='', ip='0.0.0.0', port=8080):
        self.nfs_path = nfs_path
        self.ip = ip
        self.port = port
        # inicializar webservice?
        # contactar servidor principal?
    '''

    '''
    def getProcessosStatus(self):
        """
            verificar lista_processo
            pegar status de cada processo
            e montar json
        """
        json = []
        json.append('{ processo: [')
        i=0

        for processo in self.lista_processo:
            if i==1:
                json.append(',')
            json.append('{ id:'+str(processo.processo.pid)+',')
            json.append('init_time:'+time.strftime("%Y-%m-%d %H:%M:%S")+',')
            if processo.processo.poll() == None:
                json.append("status: 'runing'")
            else:
                json.append("status: 'finished'")
            i=1
            json.append('}')
        json.append(']}')

        return "".join(json)

    def getProcesso(self, id=0):
        return lista_processo[id]

    def setProcesso(self, cmd=''):
        self.lista_processo.append(Processo(self.process_count+1, '','wait',cmd))
        #inicializa processo
        #print cmd

    def startProcessos(self):
        for processo in self.lista_processo:
            print 'Iniciando processo: '+str(processo.id)
            processo.executar()
    '''

    def getTotalProcessos(self,x):
        res = len(self.parametros)
        if res > x:
            return x
        else:
            return res

    def MyHttpRequest(self,url,wait_result=True):
        #esse metodo precisa garantir que a solicitacao tera uma resposta!
        response=''
        if url.find('http://')>=0:
            url = urllib2.Request(url)
            try:
                response = urllib2.urlopen(url)
                if(wait_result):
                    response = response.read()
                else:
                    response.close()
                return response
            except urllib2.HTTPError:
                return ''
            except urllib2.URLError:
                return ''
        else:
            return ''

    def getSetup(self):
        if isinstance(self.nfs_path,types.NoneType) and isinstance(self.ip,types.NoneType) and isinstance(self.port,types.NoneType):
            return True
        return False

    def setSetup(self, nfs_path='', ip='0.0.0.0', port=8080):
        self.nfs_path = nfs_path
        self.ip = ip
        #print 'setSetup '+str(port)
        self.port = port

    def getEscravoProcessando(self):
		for escravo in self.lista_escravo:
			if escravo.getAlive():
				return True
		# se passar por todos e nao encontrar nenhum processando
		return False

    def getStatusProcesso(self):
        pass

    def analisa(self,query=''):
        #myvars = {'metodo':None, 'cmd':None, 'id':None, 'nfs_path':None, 'num_process':None, 'server_ip':None}
        myvars = {}
        #myvars = {'status': 'false'}

        '''
        ge = GerenciadorEscravo()
        print 'ge.getSetup() '+str(ge.getSetup())
        '''

        query = query.replace('%20',' ')
        query = query.replace('%27',"'")

        query = string.split(query, '?')
        if(len(query)>1):
            if(query[0]=='/managerpp/ajax'):
                if(query[1]!=None):
                    query = string.split(query[1], '&')
                    print query
                    for vars in query:
                        aux = string.split(vars, '=')
                        myvars[aux[0]] = aux[1]
                        print myvars
        if myvars != None:
            if myvars.get('metodo',False):
                print 'Metodo: '+str(myvars.get('metodo'))
                '''
                if myvars.get('metodo') == 'setprocesso':
                    if myvars.get('pp',False):
                        for i in range(0, int(myvars.get('pp'))):
                            print i
                            if myvars.get('cmd',False):
                                self.setProcesso(myvars['cmd'])
                                myvars['status'] = 'true'
                            else:
                                myvars['status'] = 'false'
                    else:
                        if myvars.get('cmd',False):
                            self.setProcesso(myvars['cmd'])
                            myvars['status'] = 'true'
                elif myvars.get('metodo') == 'getprocessosstatus':
                    self.getProcessosStatus()
                elif myvars.get('metodo') == 'startprocessos':
                    self.startProcessos()
                elif myvars.get('metodo') == 'getprocesso':
                    if myvars.get('id',False):
                        self.getProcesso(myvars['id'])
                '''
                if myvars.get('metodo') == 'escravos':
                    #jsonvars = {escravos:[{id:1,ip:'10.0.0.1',pp:10},{id:2,ip:'10.0.0.2',pp:11}]}
                    myjson = []
                    myjson.append('{ "escravos": [')
                    i=0

                    print 'length(self.lista_escravo)'+str(len(self.lista_escravo))

                    for escravo in self.lista_escravo:
                        #print processo
                        if i==1:
                            myjson.append(',')
                        print 'id: '+str(escravo.id)
                        myjson.append('{ "id":'+str(escravo.id)+',')
                        print 'ip: '+str(escravo.ip)
                        myjson.append('"ip":"'+escravo.ip+'",')
                        print 'pp: '+str(escravo.pp)
                        myjson.append('"pp": "'+str(escravo.pp)+'"')
                        i=1
                        myjson.append('}')
                    myjson.append(']}')

                    return "".join(myjson)
                    pass
                elif myvars.get('metodo') == 'status':
                    # verificar no existentes
                    # 0 no == status -> false
                    if len(self.lista_escravo)>0:
                        # Falta testar se nos ativos
                        myvars["status"] = 'true'
                        myvars["count_no"] = len(self.lista_escravo)
                    else:
                        myvars["status"] = 'false'
                        #self.ip, self.port = self.client_address
                        myvars["ip"] = self.ip
                        print str(self.port)
                        myvars["port"] = str(self.port)
                elif myvars.get('metodo') == 'initstatus':
                    if self.flagProcesso:
                        if not self.threadProcessamento.is_alive():
                            self.flagProcesso = False
                            myvars["processando"] = 'false'
                            myvars["path_ini"] = 'false'
                            myvars["status"] = 'false'
                        else:
                            myvars["fase01"] = self.fase01
                            myvars["fase02"] = self.fase02
                            myvars["fase03"] = self.fase03
                            #myvars["total_pro"] = self.total_pro
                            #myvars["base_init"] = self.base_init
                            myvars["path_ini"] = 'true'
                            myvars["nfs_path"] = len(self.nfs_path)
                            myvars["processando"] = 'true'
                            myvars["status"] = 'true'
                    else:
                        print 'Status do processamento'
                        print self.threadProcessamento
                        print self.flagProcesso
                        '''myvars["nfs_path"] = len(self.nfs_path)'''
                        myvars["nfs_path"] = os.getcwd()
                        myvars["processando"] = 'false'
                        myvars["path_ini"] = 'true'
                        myvars["status"] = 'false'
                elif myvars.get('metodo') == 'startprocessos':
                    if not self.flagProcesso:
                        if self.escravo_count>0:
                            #definindo fases
                            if myvars.get('fase01',False):
                                self.fase01 = myvars.get('fase01')
                            if myvars.get('fase02',False):
                                self.fase02 = myvars.get('fase02')
                            if myvars.get('fase03',False):
                                self.fase03 = myvars.get('fase03')
                            #if myvars.get('total_pro',False):
                            #    self.total_pro = int(myvars.get('total_pro'))
                            #    self.process_count = 0
                            #    self.itera_count = 0
                            #if myvars.get('base_init',False):
                            #    self.base_init = myvars.get('base_init')
                            if myvars.get('parametros',False):
                                #print 'PARAMETROS'
                                #print myvars.get('parametros').encode("utf-8")
                                #print myvars.get('parametros')
                                #print urllib.unquote(myvars.get('parametros').encode("utf-8"))
                                #raw_input('Aperte ENTER para prosseguir: ')
                                self.parametros = json.loads(urllib.unquote(myvars.get('parametros').encode("utf-8")))
                                p=[]
                                for j in self.parametros:
								    p.append(self.parametros.get(json.dumps(j).replace('"','')))
                                self.parametros = list(itertools.product(*p))
                                self.total_pro = len(self.parametros)
                                self.process_count = 0
                                self.itera_count = 0

                            self.threadProcessamento=Thread( target=controleDeFluxo, args = (self,) )
                            self.threadProcessamento.start()
                            print 'Thread iniciada'
                            print self.threadProcessamento.is_alive()

                            #definir valor da flag
                            self.flagProcesso = True

                            myvars["status"] = 'true'
                        else:
                            #nao tem processo para iniciar
                            myvars["status"] = 'false'
                    else:
                        print 'processando'
                        myvars["status"] = 'false'
                elif myvars.get('metodo') == 'add_no':
                    pp=1
                    if myvars.get('pp',False):
                        pp = myvars.get('pp')
                    if myvars.get('ip',False):
                        #verificar se esse ip ja foi cadastrado
                        nalista = False
                        for escravo in self.lista_escravo:
                            if escravo.ip == myvars.get('ip'):
                                nalista = True
                        if not nalista:
                            self.escravo_count = self.escravo_count+int(pp)
                            self.lista_escravo.append(Escravo(self.escravo_count, myvars.get('ip'), int(pp)))
                elif myvars.get('metodo') == 'list_nfs_files':
                    print self.nfs_path
                    if len(self.nfs_path) >0:
                        i=0
                        files=[]
                        dirList=os.listdir(self.nfs_path)
                        for fname in dirList:
                            if os.path.isfile(self.nfs_path+'/'+fname):
                                if i==1:
                                    files.append(',')
                                files.append('{"file":"'+fname+'"}')
                                i=1
                        #myvars["files"] = '[{"file":"file_exec"},{"file":"file_exec2"}]';
                        myvars["files"] = '['+''.join(files)+']';
                        print myvars["files"]
                    if myvars.get('_dc',False):
                        del myvars["_dc"]
                    if myvars.get('metodo',False):
                        del myvars["metodo"]
                    # {"files":[{"file":"/home/renedet/nfspath/file_exec"},{"file":"/home/renedet/nfspath/file_exec2"}]}
                elif myvars.get('metodo') == 'break_process':
                    '''
                    if not isinstance(self.threadProcessamento, types.NoneType):
                        if self.threadProcessamento.isAlive():
                            self.threadProcessamento
                    '''
                    pass
                elif myvars.get('metodo') == 'setup':
                    if myvars.get('nfs_path',False):
                        if os.path.isdir(urllib.unquote(myvars['nfs_path'].encode("utf-8"))):
                            self.nfs_path = urllib.unquote(myvars['nfs_path'].encode("utf-8"))
                            myvars['nfs_path'] = 'true'
                            print self.nfs_path
                        else:
                            myvars['nfs_path'] = 'false'
                    if myvars.get('num_process',False):
                        self.max_active_process = myvars['num_process']
                        #Falta verificar quantos processos suporta, agora e como fazer isso?
                    myvars["status"] = 'true'
        return myvars

def controleEscravo(gerenciadormestre,escravo,processo,idprocesso):
	erro = True
	#url = 'http://'+escravo.ip+'/managerpp/ajax?metodo=setprocesso&idprocess='+str(idprocesso)+'&cmd=./'+urllib.quote(gerenciadormestre.fase02+' '+str(gerenciadormestre.itera_count)+' '+' '.join(processo))
	url = 'http://'+escravo.ip+'/managerpp/ajax?metodo=setprocesso&idprocess='+str(idprocesso)+'&cmd='+urllib.quote(gerenciadormestre.fase02+' '+' '.join(processo))
	print 'URL metodo=setprocesso'
	print url
	#url = urllib.unquote(url)
	auxjson = gerenciadormestre.MyHttpRequest(''.join(url),True)
	print auxjson
	if 0<len(auxjson):
		resultado = json.loads(auxjson)
		print resultado.get('status')
		if resultado.get('status'):
			url = urllib.unquote('http://'+escravo.ip+'/managerpp/ajax?metodo=startprocessos')
			print url
			gerenciadormestre.MyHttpRequest(''.join(url),False)
			erro = False
			teste = True
			# verificando se terminou de processar ou se esta ativo
			while teste:
				time.sleep(1)
				url = urllib.unquote('http://'+escravo.ip+'/managerpp/ajax?metodo=getprocessosstatus')
				auxjson = gerenciadormestre.MyHttpRequest(''.join(url),True)
				print 'verificando se processamento terminou'
				if len(auxjson)==0:
					time.sleep(2)
					auxjson = gerenciadormestre.MyHttpRequest(''.join(url),True)
					if len(auxjson)==0:
						# devolvendo processo para lista
						gerenciadormestre.lista_escravo.append(processo)
						# marcando escravo como inativo
						escravo.live=False
						#escravo.processando=False
						teste = False
						erro = True
						break;
				if len(auxjson)>0:
					processos = json.loads(auxjson)
					processos = processos.get('processo')
					p=0
					for pro in processos:
						print pro.get('status')
						if 'finished'!=pro.get('status'):
							p+=1
					if p==0:
						# todos os processos enceraram
						teste = False
						#escravo.processando=False
	if erro:
		# devolvendo processo para lista
		gerenciadormestre.lista_escravo.append(processo)
		# marcando escravo como inativo
		escravo.live=False

def controleDeFluxo(gerenciadormestre):

    # verificando se fase02 existe
    if os.path.exists(gerenciadormestre.nfs_path):
        if os.path.isdir(gerenciadormestre.nfs_path):
            while True:
                aux = True
                #iniciando fase01 (sem parametros)
                gerenciadormestre.execFase = 1
                print 'Verificando result.mat'
                # verifica se result.mat existe para executar fase01
                if os.path.isfile(gerenciadormestre.nfs_path+'/result.mat'):
                    #processar gerenciadormestre.fase01
                    print 'Iniciando fase01'
                    ge = GerenciadorEscravo()
                    ge.setSetup(gerenciadormestre.nfs_path,'',0)
                    #gerenciadormestre.process_count+=1
                    #nao conta processos internos
                    print 'Processo adicionado?'
                    # adiciona fase01 na lista para ser executado
                    print ge.setProcesso('./'+gerenciadormestre.fase01,1)
                    print 'Processo iniciado?'
                    # inicia execucao de fase01
                    print ge.startProcessos()

                    print 'Lista de Processos '+str(len(ge.lista_processo)) #0!!!
                    for processo in ge.lista_processo:
                        print 'Status do processo: '+processo.status
                        #while processo.poll() < 0:
                        while isinstance(processo.processo.poll(),types.NoneType):
                            #espera x segundos para testar de novo
                            time.sleep(1)
                    # fase01 analisa result.mat para gerar true.file
                    if os.path.isfile(gerenciadormestre.nfs_path+'/true.file'):
                        print gerenciadormestre.nfs_path+'/true.file gerado!'
                        aux = False
                    else:
                        print '# '+str(gerenciadormestre.itera_count)
                else:
                    print 'Pulou fase01'
                    #time.sleep(10)
                if aux == False:
                    print 'Finalizando processamento!'
                    break
                #else:
                #    print 'Valor de aux:'
                #    print aux
                #iniciando fase02 (numiterac, filename, processo_id) processo_id e passado pelo escravo
                gerenciadormestre.execFase = 2
                #enviando processos para os nos
                #falta definir o numero de processo para cada no
                print 'Iniciando fase02'
                gerenciadormestre.itera_count+=1
                #time.sleep(10)
                idprocesso=0
                while 0 < len(gerenciadormestre.parametros) or gerenciadormestre.getEscravoProcessando():
					#print 'verificando escravo livre'
					# o problema ocorre se nao houver escravos ativos escravo.live==True
					time.sleep(2)
					for escravo in gerenciadormestre.lista_escravo:
						#time.sleep(5)
						#pprint (vars(escravo))
						if escravo.live:
							#print 'escravo processando'
							#print escravo.getAlive()
							#if False==escravo.processando:
							if not escravo.getAlive():
								#escravo.processando=True
								#print 'escravo.pp'
								print escravo.pp
								processos_dist = gerenciadormestre.getTotalProcessos(escravo.pp)
								print 'distribuindo processo'
								print processos_dist
								for i in range(1,processos_dist+1):
									# contador de processos he diferente de len(gerenciadormestre.parametros)
									idprocesso+=1
									escravo.thread=Thread( target=controleEscravo, args = (gerenciadormestre,escravo,gerenciadormestre.parametros.pop(),idprocesso,) )
									escravo.thread.start()
                """
                #while gerenciadormestre.process_count < gerenciadormestre.total_pro:
                while gerenciadormestre.process_count < len(gerenciadormestre.parametros):
                    #print 'process_count '+str(gerenciadormestre.process_count)
                    #print 'total_pro '+str(gerenciadormestre.total_pro)
                    #local_process_count = gerenciadormestre.process_count
                    # distribuindo processos para os nos
                    for escravo in gerenciadormestre.lista_escravo:
                        #gerenciadormestre.process_count+=1
                        #url = 'http://'+escravo.ip+'/ajax?metodo=setprocesso&pp='+str(escravo.pp)+'&idprocess='+str(gerenciadormestre.process_count)+'&cmd=./'+urllib.quote(gerenciadormestre.fase02+' '+str(gerenciadormestre.itera_count)+' '+gerenciadormestre.nfs_path+'/'+gerenciadormestre.base_init+' '+str(gerenciadormestre.process_count))
                        #url = 'http://'+escravo.ip+'/ajax?metodo=setprocesso&pp='+str(escravo.pp)+'&idprocess='+str(gerenciadormestre.process_count)+'&cmd=./'+urllib.quote(gerenciadormestre.fase02+' '+str(gerenciadormestre.itera_count)+' '+gerenciadormestre.nfs_path+'/'+gerenciadormestre.base_init)
                        processos_dist = gerenciadormestre.getTotalProcessos(escravo.pp)
                        #url = 'http://'+escravo.ip+'/managerpp/ajax?metodo=setprocesso&pp='+str(processos_dist)+'&idprocess='+str(1+local_process_count+gerenciadormestre.Gprocess_count)+'&cmd=./'+urllib.quote(gerenciadormestre.fase02+' '+str(gerenciadormestre.itera_count)+' '+gerenciadormestre.nfs_path+'/'+gerenciadormestre.base_init)
                        # preciso guardar estes dados para poder recuperar caso fique fora do ar
                        # falta os parametros self.parametros
                        #url = 'http://'+escravo.ip+'/managerpp/ajax?metodo=setprocesso&pp='+str(processos_dist)+'&idprocess='+str(1+local_process_count+gerenciadormestre.Gprocess_count)+'&cmd=./'+urllib.quote(gerenciadormestre.fase02+' '+str(gerenciadormestre.itera_count)+' '+str(gerenciadormestre.parametros[gerenciadormestre.itera_count]))
                        for i in range(1,processos_dist+1):
							url = 'http://'+escravo.ip+'/managerpp/ajax?metodo=setprocesso&idprocess='+str(1+local_process_count+gerenciadormestre.Gprocess_count)+'&cmd=./'+urllib.quote(gerenciadormestre.fase02+' '+str(gerenciadormestre.itera_count)+' '+str(gerenciadormestre.parametros[gerenciadormestre.itera_count]))
							print url
							gerenciadormestre.MyHttpRequest(''.join(url),False)
							url = urllib.unquote('http://'+escravo.ip+'/managerpp/ajax?metodo=getprocessosstatus')
							auxjson = gerenciadormestre.MyHttpRequest(''.join(url),True)
							#time.sleep(1)
							print auxjson
							processos = json.loads(auxjson)
							processos = processos.get('processo')
							for p in processos:
								if p.get('status',False):
									print 'OK'
                        #local_process_count = gerenciadormestre.process_count

                    #solicitando para nos processarem
                    print 'Iniciando processos'
                    #time.sleep(10)
                    for escravo in gerenciadormestre.lista_escravo:
                        url = urllib.unquote('http://'+escravo.ip+'/managerpp/ajax?metodo=startprocessos')
                        print url
                        gerenciadormestre.MyHttpRequest(''.join(url),False)

                    #verifica de tempos em tempos se todos os nos terminaram de processar
                    #verificador...
                    print 'Verificando se processos terminaram'
                    #time.sleep(10)
                    verificador = 1
                    while verificador > 0:
                        verificador = 0
                        # menor tempo de processamento fase02
						# 80 seg * 8 processos >= 1040 seg >= 17,33 minutos
                        time.sleep(30)
                        for escravo in gerenciadormestre.lista_escravo:
                            url = urllib.unquote('http://'+escravo.ip+'/managerpp/ajax?metodo=getprocessosstatus')
                            while True:
								auxjson = gerenciadormestre.MyHttpRequest(''.join(url),True)
								if len(auxjson)>0:
									break
								else:
									escravo.live = False
                            # se caso nao houver resposta o metodo anterior
                            # tera que distribuir o processo para outro no

                            #print auxjson
                            processos = json.loads(auxjson)
                            processos = processos.get('processo')
                            for p in processos:
								# enquanto todos os processos nao terminar
								# de executar vai continuar verificando
                                if p.get('status') != 'finished':
                                    verificador+=1
                """
                # inicializando contator para proximo ciclo
                #gerenciadormestre.Gprocess_count+=gerenciadormestre.process_count
                #gerenciadormestre.process_count = 0

                #se todos os nos finalizaram executa fase03

                #iniciando fase03 (numiterac)
                print 'Iniciando fase03'
                #time.sleep(10)
                gerenciadormestre.execFase = 3
                #para gerar gerenciadormestre.nfs_path+'/result.mat'
                ge = GerenciadorEscravo()
                ge.setSetup(gerenciadormestre.nfs_path,'',0)
                #gerenciadormestre.process_count+=1
                print ge.setProcesso('./'+gerenciadormestre.fase03+' '+str(gerenciadormestre.itera_count),1)
                print ge.startProcessos()
                for processo in ge.lista_processo:
                    #esperando processo terminar
                    #while processo.poll() < 0:
                    while isinstance(processo.processo.poll(),types.NoneType):
                        #espera x segundos para testar de novo
                        time.sleep(1)

                print 'Fim do ciclo '+str(gerenciadormestre.itera_count)
                #time.sleep(10)
                #incrementa iterador
                #gerenciadormestre.itera_count+=1
        else:
            gerenciadormestre.flagProcesso = False
    else:
        gerenciadormestre.flagProcesso = False
    gerenciadormestre.flagProcesso = False


text:
namespace chrono {
namespace fea {

/// Class for material for FEA electrostatic problems

class ChContinuumElectrostatics : public ChContinuumPoisson3D {
  private:
    double e_permittivity;

  public:
    ChContinuumElectrostatics() {
        // default
        e_permittivity = 1.0;
    }

    virtual ~ChContinuumElectrostatics(){};

    /// Sets the e absolute permittivity constant of the material,
    /// expressed in Faraday per meter  [ F/m ].
    /// Sets the conductivity matrix as isotropic (diagonal k)
    void SetPermittivity(double me) {
        e_permittivity = me;
        this->ConstitutiveMatrix.Reset();
        this->ConstitutiveMatrix.FillDiag(e_permittivity);
    }
    /// Sets the e absolute permittivity by using the relative
    /// permittivity er, since e = er*e0 with e0 the constant permittivity
    /// of vacuum, so this is easier than using SetPermittivity(),
    /// Examples: air er=1.000589, rubber er=7, water er=80, glass 4-10 (approx.)
    void SetRelativePermettivity(double re) { SetPermittivity(re * 8.854187817e-12); }

    /// Gets the e absolute permittivity constant of the material,
    /// expressed in Faraday per meter  [ F/m ].
    double GetPermittivity() { return e_permittivity; }

    /// Get the e permittivity matrix
    ChMatrixDynamic<> Get_PermittivityEmatrix() { return ConstitutiveMatrix; }
};

}  //___end of namespace fea___
}  //___end of namespace chrono___

#endif


text:
'''
  apkg
  ~~~~

  A package manager for Agda.

'''

# ----------------------------------------------------------------------------

import click
import os

from pathlib             import Path
from distutils.dir_util  import copy_tree

from ..config            import ( AGDA_VERSION
                                , LIB_SUFFIX
                                , PKG_SUFFIX
                                , SUPPORT_FILES_PATH
                                )
from ..service.logging   import logger, clog

# ----------------------------------------------------------------------------

# -- Command def.
@click.group()
def nixos(): pass

@nixos.command()
@click.option('--yes'
             , type=bool
             , is_flag=True
             , help='Yes for everything.')
@clog.simple_verbosity_option(logger)
def nixos(yes):
  """Set up a NixOS environment for Agda"""
  MSG = "Agda-pkg will copy the following files to the current directory."
  click.echo(MSG)
  for file in SUPPORT_FILES_PATH.iterdir():
    print(file.as_posix())
  if click.confirm('Do you want to proceed?'):
    pwd = Path().cwd()
    copy_tree(SUPPORT_FILES_PATH.as_posix(), pwd.as_posix(), update=1, verbose=1)


text:
r"""Wildman-Crippen LogP/MR descriptor.

References
    * :doi:`10.1021/ci990307l`

"""
from rdkit.Chem import Crippen

from ._base import Descriptor

__all__ = ("SLogP", "SMR")

class WildmanCrippenBase(Descriptor):
    __slots__ = ()

    @classmethod
    def preset(cls, version):
        yield cls()

    def __str__(self):
        return self.__class__.__name__

    def parameters(self):
        return ()

    explicit_hydrogens = False

    rtype = float

class SLogP(WildmanCrippenBase):
    r"""Wildman-Crippen LogP descriptor(rdkit wrapper)."""

    since = "1.0.0"
    __slots__ = ()

    def description(self):
        return "Wildman-Crippen LogP"

    def calculate(self):
        return Crippen.MolLogP(self.mol)

class SMR(WildmanCrippenBase):
    r"""Wildman-Crippen MR descriptor(rdkit wrapper)."""

    since = "1.0.0"
    __slots__ = ()

    def description(self):
        return "Wildman-Crippen MR"

    def calculate(self):
        return Crippen.MolMR(self.mol)


text:
    var Group = require('zrender/lib/container/Group');
    var componentUtil = require('../util/component');
    var clazzUtil = require('../util/clazz');

    var Component = function () {
        /**
         * @type {module:zrender/container/Group}
         * @readOnly
         */
        this.group = new Group();

        /**
         * @type {string}
         * @readOnly
         */
        this.uid = componentUtil.getUID('viewComponent');
    };

    Component.prototype = {

        constructor: Component,

        init: function (ecModel, api) {},

        render: function (componentModel, ecModel, api, payload) {},

        dispose: function () {}
    };

    var componentProto = Component.prototype;
    componentProto.updateView
        = componentProto.updateLayout
        = componentProto.updateVisual
        = function (seriesModel, ecModel, api, payload) {
            // Do nothing;
        };
    // Enable Component.extend.
    clazzUtil.enableClassExtend(Component);

    // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
    clazzUtil.enableClassManagement(Component, {registerWhenExtend: true});

    module.exports = Component;


text:
package nc.is.sql2o_dao.services;

import org.apache.tapestry5.ioc.Registry;
import org.apache.tapestry5.ioc.RegistryBuilder;

public enum QaRegistry {
	INSTANCE;

	private final Registry registry = RegistryBuilder
			.buildAndStartupRegistry(QaModule.class);

	public Registry getRegistry() {
		return registry;
	}

	public <T> T getService(Class<T> tClass) {
		return registry.getService(tClass);
	}

}


text:
Remove the prefix from these files to use them as `.lvimrc` files in their
respective folders.


text:
import EventEmitter from 'events'
import CommandHandler from '../src/commands'

import traceEvents from './__fixtures__/traceEvents.json'

class MyEmitter extends EventEmitter {}

jest.mock('../src/utils', () => ({
    readIOStream: jest.fn().mockReturnValue('foobar'),
    sumByKey: jest.fn().mockReturnValue('foobar')
}))

test('initialization', () => {
    const clientMock = { on: jest.fn() }
    const browserMock = { addCommand: jest.fn(), emit: jest.fn() }
    new CommandHandler(clientMock, browserMock)
    expect(browserMock.addCommand.mock.calls).toHaveLength(10)
    expect(clientMock.on).toBeCalled()

    const event = { method: 'foobar.bar', params: 123 }
    expect(browserMock.emit).not.toBeCalled()
    clientMock.on.mock.calls[4][1](event)
    expect(browserMock.emit).toBeCalled()
})

test('cdp', async () => {
    const clientMock = {
        on: jest.fn(),
        Network: {
            enable: jest.fn().mockImplementation((args, cb) => cb(null, 'foobar'))
        }
    }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)

    expect(() => handler.cdp('foobar', 'enable')).toThrow()
    expect(() => handler.cdp('Network', 'foobar')).toThrow()
    expect(await handler.cdp('Network', 'enable')).toBe('foobar')
})

test('cdpConnection', () => {
    const clientMock = {
        on: jest.fn(),
        host: 'localhost',
        port: 8473,
        foo: 'bar'
    }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)

    expect(handler.cdpConnection()).toEqual({ host: 'localhost', port: 8473 })
})

test('getNodeId', async () => {
    const clientMock = { on: jest.fn() }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)

    handler.cdp = jest.fn()
        .mockReturnValueOnce({ root: { nodeId: 123 } })
        .mockReturnValueOnce({ nodeId: 42 })
    expect(await handler.getNodeId('selector')).toBe(42)
    expect(handler.cdp.mock.calls[0]).toEqual([ 'DOM', 'getDocument' ])
    expect(handler.cdp.mock.calls[1]).toEqual(
        ['DOM', 'querySelector', { nodeId: 123, selector: 'selector' }])
})

test('getNodeIds', async () => {
    const clientMock = { on: jest.fn() }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)

    handler.cdp = jest.fn()
        .mockReturnValueOnce({ root: { nodeId: 123 } })
        .mockReturnValueOnce({ nodeIds: [ 1, 2, 3 ] })
    expect(await handler.getNodeIds('selector')).toEqual([ 1, 2, 3 ])
    expect(handler.cdp.mock.calls[0]).toEqual([ 'DOM', 'getDocument' ])
    expect(handler.cdp.mock.calls[1]).toEqual(
        ['DOM', 'querySelectorAll', { nodeId: 123, selector: 'selector' }])
})

test('startTracing', () => {
    const clientMock = { on: jest.fn() }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)
    handler.cdp = jest.fn()

    handler.startTracing()

    expect(handler.isTracing).toBe(true)
    expect(::handler.startTracing).toThrow()
})

test('endTracing', async () => {
    const clientMock = { on: jest.fn() }
    const browserMock = new MyEmitter()
    browserMock.addCommand = jest.fn()

    const handler = new CommandHandler(clientMock, browserMock)
    handler.cdp = jest.fn()
    handler.isTracing = true

    process.nextTick(() => browserMock.emit('Tracing.tracingComplete', { stream: 42 }))
    const stream = await handler.endTracing()

    expect(handler.cdp).toBeCalledWith('Tracing', 'end')
    expect(stream).toBe(42)
    expect(handler.traceEvents).toBe('foobar')
    expect(handler.isTracing).toBe(false)
})

test('endTracing throws if not tracing', async () => {
    const clientMock = { on: jest.fn() }
    const browserMock = new MyEmitter()
    browserMock.addCommand = jest.fn()

    const handler = new CommandHandler(clientMock, browserMock)
    await expect(handler.endTracing()).rejects.toBeInstanceOf(Error)
})

test('getTraceLogs', () => {
    const clientMock = { on: jest.fn() }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)
    handler.traceEvents = 'foobar'
    expect(handler.getTraceLogs()).toBe('foobar')
})

test('getSpeedIndex', async () => {
    const clientMock = { on: jest.fn() }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)
    const speedIndex = await handler.getSpeedIndex()
    expect(speedIndex).toEqual({ speedIndex: 1234, perceptualSpeedIndex: 4321 })
})

test('getPerformanceMetrics', () => {
    const clientMock = { on: jest.fn() }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)
    handler.traceEvents = traceEvents
    expect(handler.getPerformanceMetrics()).toEqual({
        firstPaint: 735.666,
        firstContentfulPaint: 735.669,
        firstMeaningfulPaint: 735.671,
        domContentLoaded: 574.546,
        timeToFirstInteractive: 735.671,
        load: 1379.895
    })
})

test('getPageWeight', () => {
    const clientMock = { on: jest.fn() }
    const browserMock = { addCommand: jest.fn() }
    const handler = new CommandHandler(clientMock, browserMock)
    handler.networkHandler.requestTypes = {
        Document: { size: 23343, encoded: 7674, count: 1 },
        Image: { size: 53479, encoded: 53479, count: 6 },
        Other: { size: 0, encoded: 0, count: 1 }
    }

    const { pageWeight, transferred, requestCount, details } = handler.getPageWeight()
    expect(pageWeight).toBe('foobar')
    expect(transferred).toBe('foobar')
    expect(requestCount).toBe('foobar')
    expect(details).toEqual(handler.networkHandler.requestTypes)
})


text:
package org.gwtproject.http.client;

/** Thrown to indicate that an HTTP request has timed out. */
@SuppressWarnings("serial")
public class RequestTimeoutException extends RequestException {
  private static String formatMessage(int timeoutMillis) {
    return "A request timeout has expired after " + timeoutMillis + " ms";
  }

  /** Time, in milliseconds, of the timeout. */
  private final int timeoutMillis;

  /** Request object which experienced the timed out. */
  private final Request request;

  /**
   * Constructs a timeout exception for the given {@link Request}.
   *
   * @param request the request which timed out
   * @param timeoutMillis the number of milliseconds which expired
   */
  public RequestTimeoutException(Request request, int timeoutMillis) {
    super(formatMessage(timeoutMillis));
    this.request = request;
    this.timeoutMillis = timeoutMillis;
  }

  /**
   * Returns the {@link Request} instance which timed out.
   *
   * @return the {@link Request} instance which timed out
   */
  public Request getRequest() {
    return request;
  }

  /**
   * Returns the request timeout value in milliseconds.
   *
   * @return the request timeout value in milliseconds
   */
  public int getTimeoutMillis() {
    return timeoutMillis;
  }
}


text:
/**
 *
 */
package com.livescribe.community.dao;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.livescribe.community.BaseTest;
import com.livescribe.community.config.CommunityProperties;
import com.livescribe.community.orm.ActiveUser;
import com.livescribe.community.orm.UserProfile;
import com.livescribe.base.utils.WOAppMigrationUtils;

/**
 *
 * @author Kevin F. Murdoff
 * @version 1.0
 */
public class UserDaoTest extends BaseTest {

	@Autowired
	private UserDao userDao;

	@Autowired
	private CommunityProperties communityProperties;

	/**
	 *
Default class constructor.

	 */
	public UserDaoTest() {
		super();
	}

	@Before
	public void setUp() throws Exception {

	}

	@After
	public void tearDown() throws Exception {

	}

	/**
	 *
Determines whether an ActiveUser is found and returned.

	 *
	 * @see com.livescribe.community.dao.UserDao#findActiveUserByToken(String)
	 */
//	@Test
	@Transactional
	public void testFindActiveUserByToken() {

		if (!skipTests) {
			String TEST_USER_TOKEN = communityProperties.getProperty("UserDaoTest.testFindActiveUserByToken.test.token");

			logger.debug("TEST_USER_TOKEN = " + TEST_USER_TOKEN);

			ActiveUser aUser = userDao.findActiveUserByToken(TEST_USER_TOKEN);
			assertNotNull("The returned ActiveUser was 'null'.", aUser);
		}
	}

	/**
	 *
Determines whether a UserProfile is found and returned.

	 *
	 * @see com.livescribe.community.dao.UserDao#findUserProfileByActiveUser(ActiveUser)
	 */
	@Test
	@Transactional
	public void testFindUserProfileByActiveUser() {

		if (!skipTests) {
			String TEST_USER_PRIMARY_KEY = communityProperties.getProperty("UserDaoTest.testFindUserProfileByActiveUser.test.id");
			ActiveUser aUser = new ActiveUser();
			byte[] pk = WOAppMigrationUtils.convertStringToPrimaryKey(TEST_USER_PRIMARY_KEY);
			aUser.setUserId(pk);

			logger.debug("TEST_USER_PRIMARY_KEY = " + TEST_USER_PRIMARY_KEY);

			UserProfile uProfile = userDao.findUserProfileByActiveUser(aUser);
			assertNotNull("The returned UserProfile was 'null'.", uProfile);
		}
	}
}


text:
<?php

namespace Midnight\Crawler\Plugin\TestData;

class AdultAdultTestData extends AbstractTestData
{

    /**
     * @var string
     **/
    protected $rss_name = 'adult-adult.xml';

    /**
     * @var array
     **/
    protected $html_paths = array(
        'adult-adult/blog-entry-19719.html',
        'adult-adult/blog-entry-19726.html',

        // タイトルクエリの不正、画像クエリの不正
        'adult-adult/error.html',

        // 画像srcの不正
        'adult-adult/error2.html'
    );
}


text:
$cursorControlled = true;
function showCursor()
{
   if ($cursorControlled)
      lockMouse(false);
   Canvas.cursorOn();
}

function hideCursor()
{
   if ($cursorControlled)
      lockMouse(true);
   Canvas.cursorOff();
}

//---------------------------------------------------------------------------------------------
// In the CanvasCursor package we add some additional functionality to the built-in GuiCanvas
// class, of which the global Canvas object is an instance. In this case, the behavior we want
// is for the cursor to automatically display, except when the only guis visible want no
// cursor - usually the in game interface.
//---------------------------------------------------------------------------------------------
package CanvasCursorPackage
{

//---------------------------------------------------------------------------------------------
// checkCursor
// The checkCursor method iterates through all the root controls on the canvas checking each
// ones noCursor property. If the noCursor property exists as anything other than false or an
// empty string on every control, the cursor will be hidden.
//---------------------------------------------------------------------------------------------
function GuiCanvas::checkCursor(%this)
{
   %count = %this.getCount();
   for(%i = 0; %i < %count; %i++)
   {
      %control = %this.getObject(%i);
      if ((%control.noCursor $= "") || !%control.noCursor)
      {
         showCursor();
         return true;
      }
   }
   // If we get here, every control requested a hidden cursor, so we oblige.
   hideCursor();
   return false;
}

//---------------------------------------------------------------------------------------------
// The following functions override the GuiCanvas defaults that involve changing the content
// of the Canvas. Basically, all we are doing is adding a call to checkCursor to each one.
//---------------------------------------------------------------------------------------------
function GuiCanvas::setContent(%this, %ctrl)
{
   Parent::setContent(%this, %ctrl);
   %this.checkCursor();
}

function GuiCanvas::pushDialog(%this, %ctrl, %layer, %center)
{
   Parent::pushDialog(%this, %ctrl, %layer, %center);
   %this.checkCursor();
}

function GuiCanvas::popDialog(%this, %ctrl)
{
   Parent::popDialog(%this, %ctrl);
   %this.checkCursor();
}

function GuiCanvas::popLayer(%this, %layer)
{
   Parent::popLayer(%this, %layer);
   %this.checkCursor();
}

};

activatePackage(CanvasCursorPackage);


text:
#ifndef __ctkSearchBoxPlugin_h
#define __ctkSearchBoxPlugin_h

// CTK includes
#include "ctkWidgetsAbstractPlugin.h"

class CTK_WIDGETS_PLUGINS_EXPORT ctkSearchBoxPlugin :
  public QObject,
  public ctkWidgetsAbstractPlugin
{
  Q_OBJECT

public:
  ctkSearchBoxPlugin(QObject *_parent = 0);

  QWidget *createWidget(QWidget *_parent);
  QString  domXml() const;
  QIcon    icon() const;
  QString  includeFile() const;
  bool     isContainer() const;
  QString  name() const;
};

#endif


text:
		<div style="background-image: url(<?php echo base_url('upload/images/frontend/') ?>/aboutus_bg.jpg); background-size: cover; background-position: center; width: 100vw; height: 93.5vh; margin-top: 40px;">

					"It's a mili-second action that we pay attention to advance.
Our 24-hour is unique, because millions of 24-hour is advanced thanks to that. We are an innovative company, everyday, we try to improve every second in people's lives and business thanks to technology. A button to sum all 100 invoices in a day can save 100 times more than normal; an announcement to 1000 customers at the same moment can save times up to 1000 times are some examples.
"

					"Who we are? We are business strategists, software developer and user experience designers. But basically we are people's best companions, so we live with them, think like them, find true issues of them and develop most possible friendly solutions with them. People's improvement in life is our main purpose. We work hard and fast, learn fast and hard.
"

Contact Us

<?php echo $infoma[0]['com_address'] ?>

<?php echo $infoma[0]['com_phone'] ?>

				<?php
					for ($i=0; $i < count($sup); $i++) {
						if ($i == (count($sup)-1)) {
				?>

<?php echo $sup[$i]['con_name'] ?>

<?php echo $sup[$i]['con_email'] ?>

<?php echo $sup[$i]['con_phone'] ?>

						<?php }
						else
						{
					?>

<?php echo $sup[$i]['con_name'] ?>

<?php echo $sup[$i]['con_email'] ?>

<?php echo $sup[$i]['con_phone'] ?>

						<?php }?>
				<?php } ?>

				<input type="hidden" name="longi" id="id_longi" value="<?php echo $infoma[0]['com_longi']; ?>">
				<input type="hidden" name="lati" id="id_lati" value="<?php echo $infoma[0]['com_lati']; ?>">

J O I N   T H E   T E A M

We are always hiring

					Looks like you also want to improve people's life?
Syslytic is giving you opportunity to explore yourself, learn from the passionate people and improve people's life. Dream it and live for it is both job description and benefit.
TAKE RISK. THIS OPPORTUNITY EITHER.

				<a href="<?php echo base_url(); ?>company/jobs">
					<input class="for_button form-control" style="width: 140px; height: 40px; margin-top: 30px;" type="button" value="See all open jobs" />


text:
typedef NS_ENUM(NSInteger, Pixel) {
    Alpha = 0,
    Blue = 1,
    Green = 2,
    Red = 3,
};

@implementation UIImage (TintColor)
- (UIImage *)textureWithTintColor:(UIColor *)color {

    CGFloat red, green, blue, alpha;

    [color getRed:&red green:&green blue:&blue alpha:&alpha];

    uint8_t blendRed = ( (1 - alpha) + alpha * red) * 255;
    uint8_t blendGreen = ( (1 - alpha) + alpha * green ) * 255;
    uint8_t blendBlue = ( (1 - alpha) + alpha * blue ) * 255;

    CGSize size = self.size;
    int width = size.width;
    int height = size.height;

    uint32_t *pixels = (uint32_t *)malloc(width * height * sizeof(uint32_t));

    memset(pixels, 0, width * height * sizeof(uint32_t));
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef ctx = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);

    CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), self.CGImage);

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
            uint8_t pixelRed = rgbaPixel[Red];
            uint8_t dgreen = rgbaPixel[Green] / 255.0 * blendGreen;
            uint8_t dblue = rgbaPixel[Blue] / 255.0 * blendBlue;
            uint8_t dred = rgbaPixel[Red] / 255.0 * blendRed;
            rgbaPixel[Red] = dred;
            rgbaPixel[Green] = dgreen;
            rgbaPixel[Blue] = dblue;
            rgbaPixel[Alpha] = pixelRed;
        }
    }
    CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    UIImage *texture = [UIImage imageWithCGImage: cgImage];
    CGImageRelease(cgImage);
    return texture;
}

@end


text:
#ifndef __COMMON_CONFIG_H
#define __COMMON_CONFIG_H

#include <stdbool.h>

#endif


text:
package com.google.cloud.filestore.v1beta1.samples;

// [START file_v1beta1_generated_CloudFilestoreManager_CreateShare_StringShareString_sync]
import com.google.cloud.filestore.v1beta1.CloudFilestoreManagerClient;
import com.google.cloud.filestore.v1beta1.InstanceName;
import com.google.cloud.filestore.v1beta1.Share;

public class SyncCreateShareStringShareString {

  public static void main(String[] args) throws Exception {
    syncCreateShareStringShareString();
  }

  public static void syncCreateShareStringShareString() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudFilestoreManagerClient cloudFilestoreManagerClient =
        CloudFilestoreManagerClient.create()) {
      String parent = InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString();
      Share share = Share.newBuilder().build();
      String shareId = "shareId2054217050";
      Share response = cloudFilestoreManagerClient.createShareAsync(parent, share, shareId).get();
    }
  }
}
// [END file_v1beta1_generated_CloudFilestoreManager_CreateShare_StringShareString_sync]


text:
SBT=sbt
SCALA_VERSION=2.11.4
PROJECT_NAME=graphique
PREFIX=/usr

package:
	$(SBT) clean assembly

install: package
	install -Dm 744 target/scala*/*-assembly*.jar $(destdir)$(PREFIX)/share/$(PROJECT_NAME)/$(PROJECT_NAME).jar
	install -Dm 755 scripts/$(PROJECT_NAME) $(destdir)$(PREFIX)/bin/$(PROJECT_NAME)
	install -dm 744 $(destdir)/var/log/$(PROJECT_NAME)/


text:
if ! [ -L /vagrant ]; then
  mkdir $HOME/apache_home
  mkdir $HOME/apache_home/html
  echo "Hello ubuntu World!" > $HOME/apache_home/html/index.html
  sudo ln -s $HOME/apache_home /vagrant
fi

# Set up the link for running  apache
if ! [ -L /var/www/html ]; then
  sudo rm -rf /var/www
  sudo ln -fs /vagrant /var/www
fi


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

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Sets nonblocking mode for file descriptor fd</title>

socket_set_block

socket_set_option

Socket Functions

PHP Manual

socket_set_nonblock

(PHP 4 >= 4.1.0, PHP 5)

socket_set_nonblock — Sets nonblocking mode for file descriptor fd

Description

   bool socket_set_nonblock
    ( resource $socket
   )

   The socket_set_nonblock() function sets the
   O_NONBLOCK flag on the socket specified by
   the socket parameter.

   When an operation (e.g. receive, send, connect, accept, ...) is performed on
   a non-blocking socket, the script will not pause its execution until it receives a
   signal or it can perform the operation. Rather, if the operation would result
   in a block, the called function will fail.

Parameters

socket

       A valid socket resource created with socket_create()
       or socket_accept().

Return Values

   Returns TRUE on success or FALSE on failure.

Examples

Example #1 socket_set_nonblock() example

<?php
$socket = socket_create_listen(1223);
socket_set_nonblock($socket);

socket_accept($socket);
?>

     This example creates a listening socket on all interfaces on port 1223 and
     sets the socket to O_NONBLOCK mode.
     socket_accept() will immediately fail unless there is a
     pending connection exactly at this moment.

See Also

socket_set_block() - Sets blocking mode on a socket resource

socket_set_option() - Sets socket options for the socket

socket_set_block

socket_set_option

Socket Functions

PHP Manual


text:
<?xml version="1.0"?>

<document>
    <properties>
    <title>
      Synapse 1.0 Release
    </title>
  </properties>

        Synapse 1.0 Release

  Distribution Name

                                             Description

        Download

              Standard Binary
              Distribution

              This is the complete version of Synapse and contains useful
              samples as well.

tar.gz MD5PGP

zip MD5PGP

              Source Distribution

              This contains the source code of Synapse standard distribution.
              One can generate a binary distribution from this by executing 'mvn
              clean install' followed by 'mvn assembly:assembly -Drelease'

tar.gz MD5PGP

zip MD5PGP

        [if-any logo] [end] The currently selected mirror is [preferred].
        If you encounter a problem with this mirror, please select another
        mirror. If all mirrors are failing, there are backup
        mirrors (at the end of the mirrors list) that should be available.

      <form action="[location]" method="get" id="SelectMirror">
        Other mirrors: <select name="Preferred">
        [if-any http][for http]
        <option value="[http]" selected="selected">
          [http]</option>[end][end][if-any ftp][for ftp]
        <option value="[ftp]">
          [ftp]</option>[end][end][if-any backup][for backup]
        <option value="[backup]">
          [backup] (backup)
        </option></select>
        <input type="submit" value="Change"/>
      </form>

        You may also consult the complete list of mirrors.

        Note: when downloading from a mirror please
        check the md5sum and verify
        the OpenPGP compatible
        signature from the main Apache site. These can be downloaded by
        following the links above. This KEYS file contains the public keys used
        for signing release. It is recommended that (when possible) a Web of trust is
        used to confirm the identity of these keys.

</document>


text:
package de.esotechnik.playservicesscala

import android.content.Intent
import android.view.View
import com.google.android.gms.common.api.{GoogleApiClient, Status, Api}
import com.google.android.gms.{games => gms}
import de.esotechnik.playservicesscala.macros.{provideApi, requireApi}

import scala.concurrent.Future

package object games {

  @requireApi(gms.Games.API) object Games extends ApiProvider {

    def getAppId()(implicit apiClient: GoogleApiClient): String = gms.Games.getAppId(apiClient)
    def getCurrentAccountName()(implicit apiClient: GoogleApiClient): String = gms.Games.getCurrentAccountName(apiClient)
    def getSdkVariant()(implicit apiClient: GoogleApiClient): Int = gms.Games.getSdkVariant(apiClient)
    def getSettingsIntent()(implicit apiClient: GoogleApiClient): Intent = gms.Games.getSettingsIntent(apiClient)
    def setGravityForPopups(gravity: Int)(implicit apiClient: GoogleApiClient): Unit = gms.Games.setGravityForPopups(apiClient, gravity)
    def setViewForPopups(gamesContentView: View)(implicit apiClient: GoogleApiClient): Unit = gms.Games.setViewForPopups(apiClient, gamesContentView)
    def signOut()(implicit apiClient: GoogleApiClient): Future[Status] = gms.Games.signOut(apiClient)

    @provideApi(gms.Games.Achievements) object Achievements {}
    @provideApi(gms.Games.Events) object Events {}
    @provideApi(gms.Games.GamesMetadata) object GamesMetadata {}
    @provideApi(gms.Games.Invitations) object Invitations {}
    @provideApi(gms.Games.Leaderboards) object Leaderboards {}
    @provideApi(gms.Games.Notifications) object Notifications {}
    @provideApi(gms.Games.Players) object Players {}
    @provideApi(gms.Games.Quests) object Quests {}
    @provideApi(gms.Games.RealTimeMultiplayer) object RealTimeMultiplayer {}
    @provideApi(gms.Games.Requests) object Requests {}
    @provideApi(gms.Games.Snapshots) object Snapshots {}
    @provideApi(gms.Games.Stats) object Stats {}
    @provideApi(gms.Games.TurnBasedMultiplayer) object TurnBasedMultiplayer {}

  }
}