text:
package org.opencb.opencga.catalog;

import org.opencb.datastore.core.ObjectMap;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.datastore.core.QueryResult;
import org.opencb.datastore.core.config.DataStoreServerAddress;
import org.opencb.datastore.mongodb.MongoDBConfiguration;
import org.opencb.opencga.catalog.db.api.CatalogDBAdaptorFactory;
import org.opencb.opencga.catalog.exceptions.CatalogException;
import org.opencb.opencga.catalog.managers.*;
import org.opencb.opencga.catalog.managers.api.*;
import org.opencb.opencga.catalog.authentication.AuthenticationManager;
import org.opencb.opencga.catalog.authentication.CatalogAuthenticationManager;
import org.opencb.opencga.catalog.authorization.AuthorizationManager;
import org.opencb.opencga.catalog.authorization.CatalogAuthorizationManager;
import org.opencb.opencga.catalog.utils.CatalogFileUtils;
import org.opencb.opencga.catalog.models.*;
import org.opencb.opencga.catalog.client.CatalogClient;
import org.opencb.opencga.catalog.client.CatalogDBClient;
import org.opencb.opencga.catalog.exceptions.CatalogDBException;
import org.opencb.opencga.catalog.db.mongodb.CatalogMongoDBAdaptor;
import org.opencb.opencga.catalog.exceptions.CatalogIOException;
import org.opencb.opencga.catalog.io.CatalogIOManagerFactory;

import org.opencb.opencga.catalog.utils.ParamUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public class CatalogManager implements AutoCloseable {

    /* DBAdaptor properties */
    public static final String CATALOG_DB_USER = "OPENCGA.CATALOG.DB.USER";
    public static final String CATALOG_DB_DATABASE = "OPENCGA.CATALOG.DB.DATABASE";
    public static final String CATALOG_DB_PASSWORD = "OPENCGA.CATALOG.DB.PASSWORD";
    public static final String CATALOG_DB_HOSTS = "OPENCGA.CATALOG.DB.HOSTS";
    public static final String CATALOG_DB_AUTHENTICATION_DB = "OPENCGA.CATALOG.DB.AUTHENTICATION.DB";
    /* IOManager properties */
    public static final String CATALOG_MAIN_ROOTDIR = "OPENCGA.CATALOG.MAIN.ROOTDIR";
    public static final String CATALOG_JOBS_ROOTDIR = "OPENCGA.CATALOG.JOBS.ROOTDIR";
    /* Manager policies properties */
    public static final String CATALOG_MANAGER_POLICY_CREATION_USER = "OPENCGA.CATALOG.MANAGER.POLICY.CREATION_USER";
    /* Other properties */
    public static final String CATALOG_MAIL_USER = "CATALOG.MAIL.USER";
    public static final String CATALOG_MAIL_PASSWORD = "CATALOG.MAIL.PASSWORD";
    public static final String CATALOG_MAIL_HOST = "CATALOG.MAIL.HOST";
    public static final String CATALOG_MAIL_PORT = "CATALOG.MAIL.PORT";

    private CatalogDBAdaptorFactory catalogDBAdaptorFactory;
    private CatalogIOManagerFactory catalogIOManagerFactory;
    private CatalogClient catalogClient;

    private IUserManager userManager;
    private IProjectManager projectManager;
    private IStudyManager studyManager;
    private IFileManager fileManager;
    private IJobManager jobManager;
    private IIndividualManager individualManager;
    private ISampleManager sampleManager;

    private Properties properties;

    protected static Logger logger = LoggerFactory.getLogger(CatalogManager.class);
    private AuthenticationManager authenticationManager;
    private AuthorizationManager authorizationManager;

    public CatalogManager(CatalogDBAdaptorFactory catalogDBAdaptorFactory, Properties catalogProperties)
            throws IOException, CatalogIOException {
        this.catalogDBAdaptorFactory = catalogDBAdaptorFactory;
        this.properties = catalogProperties;

        configureIOManager(properties);
        configureManagers(properties);
    }

    public CatalogManager(Properties catalogProperties)
            throws CatalogException {
        this.properties = catalogProperties;
        logger.debug("CatalogManager configureDBAdaptor");
        configureDBAdaptor(properties);
        logger.debug("CatalogManager configureIOManager");
        configureIOManager(properties);
        logger.debug("CatalogManager configureManager");
        configureManagers(properties);

        if (!catalogDBAdaptorFactory.isCatalogDBReady()) {
            catalogDBAdaptorFactory.initializeCatalogDB();
            User admin = new User("admin", "admin", "admin@email.com", "", "openCB", User.Role.ADMIN, "active");
            catalogDBAdaptorFactory.getCatalogUserDBAdaptor().insertUser(admin, null);
            authenticationManager.newPassword("admin", "admin");
        }
    }

    private void configureManagers(Properties properties) {
        catalogClient = new CatalogDBClient(this);
        //TODO: Check if catalog is empty
        //TODO: Setup catalog if it's empty.

        authenticationManager = new CatalogAuthenticationManager(catalogDBAdaptorFactory.getCatalogUserDBAdaptor(), properties);
        authorizationManager = new CatalogAuthorizationManager(catalogDBAdaptorFactory);
        userManager = new UserManager(authorizationManager, authenticationManager, catalogDBAdaptorFactory, catalogIOManagerFactory, properties);
        fileManager = new FileManager(authorizationManager, authenticationManager, catalogDBAdaptorFactory, catalogIOManagerFactory, properties);
        studyManager = new StudyManager(authorizationManager, authenticationManager, catalogDBAdaptorFactory, catalogIOManagerFactory, properties);
        projectManager = new ProjectManager(authorizationManager, authenticationManager, catalogDBAdaptorFactory, catalogIOManagerFactory, properties);
        jobManager = new JobManager(authorizationManager, authenticationManager, catalogDBAdaptorFactory, catalogIOManagerFactory, properties);
        sampleManager = new SampleManager(authorizationManager, authenticationManager, catalogDBAdaptorFactory, catalogIOManagerFactory, properties);
        individualManager = new IndividualManager(authorizationManager, authenticationManager, catalogDBAdaptorFactory, catalogIOManagerFactory, properties);
    }

    public CatalogClient client() {
        return client("");
    }

    public CatalogClient client(String sessionId) {
        catalogClient.setSessionId(sessionId);
        return catalogClient;
    }

    public CatalogIOManagerFactory getCatalogIOManagerFactory() {
        return catalogIOManagerFactory;
    }

    private void configureIOManager(Properties properties)
            throws CatalogIOException {
        catalogIOManagerFactory = new CatalogIOManagerFactory(properties);
    }

    private void configureDBAdaptor(Properties properties)
            throws CatalogDBException {

        MongoDBConfiguration mongoDBConfiguration = MongoDBConfiguration.builder()
                .add("username", properties.getProperty(CATALOG_DB_USER, null))
                .add("password", properties.getProperty(CATALOG_DB_PASSWORD, null))
                .add("authenticationDatabase", properties.getProperty(CATALOG_DB_AUTHENTICATION_DB, null))
                .build();

        List<DataStoreServerAddress> dataStoreServerAddresses = new LinkedList<>();
        for (String hostPort : properties.getProperty(CATALOG_DB_HOSTS, "localhost").split(",")) {
            if (hostPort.contains(":")) {
                String[] split = hostPort.split(":");
                Integer port = Integer.valueOf(split[1]);
                dataStoreServerAddresses.add(new DataStoreServerAddress(split[0], port));
            } else {
                dataStoreServerAddresses.add(new DataStoreServerAddress(hostPort, 27017));
            }
        }
        catalogDBAdaptorFactory = new CatalogMongoDBAdaptor(dataStoreServerAddresses, mongoDBConfiguration, properties.getProperty(CATALOG_DB_DATABASE, ""));
    }

    @Override
    public void close() throws CatalogException {
        catalogDBAdaptorFactory.close();
    }

    /**
     * Getter path methods
     * ***************************
     */

    public URI getUserUri(String userId) throws CatalogIOException {
        return catalogIOManagerFactory.getDefault().getUserUri(userId);
    }

    public URI getProjectUri(String userId, String projectId) throws CatalogIOException {
        return catalogIOManagerFactory.getDefault().getProjectUri(userId, projectId);
    }

    public URI getStudyUri(int studyId)
            throws CatalogException {
        return fileManager.getStudyUri(studyId);
    }

    public URI getFileUri(File file) throws CatalogException {
        return fileManager.getFileUri(file);
    }

    public URI getFileUri(Study study, File file) throws CatalogException {
        return fileManager.getFileUri(study, file);
    }

    public URI getFileUri(int studyId, String relativeFilePath)
            throws CatalogException {
        return fileManager.getFileUri(studyId, relativeFilePath);
    }

    @Deprecated
    public URI getFileUri(URI studyUri, String relativeFilePath)
            throws CatalogException {
        return fileManager.getFileUri(studyUri, relativeFilePath);
    }

    public boolean isExternal(File file) throws CatalogException {
        return fileManager.isExternal(file);
    }

    public int getProjectIdByStudyId(int studyId) throws CatalogException {
        return studyManager.getProjectId(studyId);
    }

    /**
     * Id methods
     * <user>@project:study:directories:filePath
     * ***************************
     */

    public int getProjectId(String id) throws CatalogException {
        return projectManager.getProjectId(id);
    }

    public int getStudyId(String id) throws CatalogException {
        return studyManager.getStudyId(id);
    }

    public int getFileId(String id) throws CatalogException {
        return fileManager.getFileId(id);
    }

    public int getToolId(String id) throws CatalogException {
        return jobManager.getToolId(id);
    }

    /**
     * User methods
     * ***************************
     */

    public QueryResult<User> createUser(String id, String name, String email, String password, String organization, QueryOptions options)
            throws CatalogException {
        return createUser(id, name, email, password, organization, options, null);
    }

    public QueryResult<User> createUser(String id, String name, String email, String password, String organization, QueryOptions options, String sessionId)
            throws CatalogException {
        return userManager.create(id, name, email, password, organization, options, sessionId);
    }

    public QueryResult<ObjectMap> loginAsAnonymous(String sessionIp)
            throws CatalogException, IOException {
        return userManager.loginAsAnonymous(sessionIp);
    }

    public QueryResult<ObjectMap> login(String userId, String password, String sessionIp)
            throws CatalogException, IOException {
        return userManager.login(userId, password, sessionIp);
    }

    public QueryResult logout(String userId, String sessionId) throws CatalogException {
        return userManager.logout(userId, sessionId);
    }

    public QueryResult logoutAnonymous(String sessionId) throws CatalogException {
        return userManager.logoutAnonymous(sessionId);
    }

    public QueryResult changePassword(String userId, String oldPassword, String newPassword, String sessionId)
            throws CatalogException {
        userManager.changePassword(userId, oldPassword, newPassword);
        return new QueryResult("changePassword", 0, 0, 0, "", "", Collections.emptyList());
    }

    public QueryResult changeEmail(String userId, String nEmail, String sessionId) throws CatalogException {
        return userManager.update(userId, new ObjectMap("email", nEmail), null, sessionId);
    }

    public QueryResult resetPassword(String userId, String email) throws CatalogException {
        return userManager.resetPassword(userId, email);
    }

    public QueryResult<User> getUser(String userId, String lastActivity, String sessionId) throws CatalogException {
        return getUser(userId, lastActivity, new QueryOptions(), sessionId);
    }

    public QueryResult<User> getUser(String userId, String lastActivity, QueryOptions options, String sessionId)
            throws CatalogException {
        return userManager.read(userId, lastActivity, options, sessionId);
    }

    public String getUserIdBySessionId(String sessionId) {
        return userManager.getUserId(sessionId);
    }

    public String getUserIdByStudyId(int studyId) throws CatalogException {
        return studyManager.getUserId(studyId);
    }

    public String getUserIdByProjectId(int projectId) throws CatalogException {
        return projectManager.getUserId(projectId);
    }

    public QueryResult modifyUser(String userId, ObjectMap parameters, String sessionId)
            throws CatalogException {
        return userManager.update(userId, parameters, null, sessionId);  //TODO: Add query options
    }

    public void deleteUser(String userId, String sessionId) throws CatalogException {
        userManager.delete(userId, null, sessionId);
    }

    /**
     * Project methods
     * ***************************
     */

    public QueryResult<Project> createProject(String ownerId, String name, String alias, String description,
                                              String organization, QueryOptions options, String sessionId)
            throws CatalogException {
        return projectManager.create(ownerId, name, alias, description, organization, options, sessionId);
    }

    public QueryResult<Project> getProject(int projectId, QueryOptions options, String sessionId)
            throws CatalogException {
        return projectManager.read(projectId, options, sessionId);
    }

    public QueryResult<Project> getAllProjects(String ownerId, QueryOptions options, String sessionId)
            throws CatalogException {
        return projectManager.readAll(new QueryOptions("ownerId", ownerId), options, sessionId);
    }

    public QueryResult renameProject(int projectId, String newProjectAlias, String sessionId)
            throws CatalogException {
        return projectManager.update(projectId, new QueryOptions("alias", newProjectAlias), null, sessionId);//TODO: Add query options
    }

    /**
     * Modify some params from the specified project:
     *

     * name
     * description
     * organization
     * status
     * attributes
     *
     * @param projectId  Project identifier
     * @param parameters Parameters to change.
     * @param sessionId  sessionId to check permissions
     * @return
     * @throws org.opencb.opencga.catalog.exceptions.CatalogDBException
     */
    public QueryResult modifyProject(int projectId, ObjectMap parameters, String sessionId)
            throws CatalogException {
        return projectManager.update(projectId, parameters, null, sessionId);//TODO: Add query options
    }

    public QueryResult shareProject(int projectId, Acl acl, String sessionId) throws CatalogException {
        return authorizationManager.setProjectACL(projectId, acl, sessionId);
    }

    /**
     * Study methods
     * ***************************
     */
    public QueryResult<Study> createStudy(int projectId, String name, String alias, Study.Type type, String description,
                                          String sessionId)
            throws CatalogException, IOException {
        return createStudy(projectId, name, alias, type, null, null, description, null, null, null, null, null, null, null, null, sessionId);
    }

    /**
     * Creates a new Study in catalog
     * @param projectId     Parent project id
     * @param name          Study Name
     * @param alias         Study Alias. Must be unique in the project's studies
     * @param type          Study type: CONTROL_CASE, CONTROL_SET, ... (see org.opencb.opencga.catalog.models.Study.Type)
     * @param creatorId     Creator user id. If null, user by sessionId
     * @param creationDate  Creation date. If null, now
     * @param description   Study description. If null, empty string
     * @param status        Unused
     * @param cipher        Unused
     * @param uriScheme     UriScheme to select the CatalogIOManager. Default: CatalogIOManagerFactory.DEFAULT_CATALOG_SCHEME
     * @param uri           URI for the folder where to place the study. Scheme must match with the uriScheme. Folder must exist.
     * @param datastores    DataStores information
     * @param stats         Optional stats
     * @param attributes    Optional attributes
     * @param options       QueryOptions
     * @param sessionId     User's sessionId
     * @return              Generated study
     * @throws CatalogException
     * @throws IOException
     */
    public QueryResult<Study> createStudy(int projectId, String name, String alias, Study.Type type,
                                          String creatorId, String creationDate, String description, String status,
                                          String cipher, String uriScheme, URI uri,
                                          Map<File.Bioformat, DataStore> datastores, Map<String, Object> stats,
                                          Map<String, Object> attributes, QueryOptions options, String sessionId)
            throws CatalogException, IOException {
        QueryResult<Study> result = studyManager.create(projectId, name, alias, type, creatorId, creationDate, description, status, cipher, uriScheme,
                uri, datastores, stats, attributes, options, sessionId);
        createFolder(result.getResult().get(0).getId(), Paths.get("data"), true, null, sessionId);
        createFolder(result.getResult().get(0).getId(), Paths.get("analysis"), true, null, sessionId);
        return result;
    }

    public QueryResult<Study> getStudy(int studyId, String sessionId)
            throws CatalogException {
        return getStudy(studyId, sessionId, null);
    }

    public QueryResult<Study> getStudy(int studyId, String sessionId, QueryOptions options)
            throws CatalogException {
        return studyManager.read(studyId, options, sessionId);
    }

    public QueryResult<Study> getAllStudies(int projectId, QueryOptions options, String sessionId)
            throws CatalogException {
        return studyManager.readAll(new QueryOptions("projectId", projectId), options, sessionId);
    }

    public QueryResult renameStudy(int studyId, String newStudyAlias, String sessionId)
            throws CatalogException {
        return studyManager.update(studyId, new ObjectMap("alias", newStudyAlias), null, sessionId);
    }

    /**
     * Modify some params from the specified study:
     *

     * name
     * description
     * organization
     * status
     *

     * attributes
     * stats
     *
     * @param studyId    Study identifier
     * @param parameters Parameters to change.
     * @param sessionId  sessionId to check permissions
     * @return
     * @throws org.opencb.opencga.catalog.exceptions.CatalogDBException
     */
    public QueryResult modifyStudy(int studyId, ObjectMap parameters, String sessionId)
            throws CatalogException {
        return studyManager.update(studyId, parameters, null, sessionId);
    }

    public QueryResult shareStudy(int studyId, Acl acl, String sessionId) throws CatalogException {
        return authorizationManager.setStudyACL(studyId, acl, sessionId);
    }

    /**
     * File methods
     * ***************************
     */

    public String getFileOwner(int fileId) throws CatalogException {
        return fileManager.getUserId(fileId);
    }

    public int getStudyIdByFileId(int fileId) throws CatalogException {
        return fileManager.getStudyId(fileId);
    }

    //create file with byte[]
    public QueryResult<File> createFile(int studyId, File.Format format, File.Bioformat bioformat, String path, byte[] bytes, String description,
                                        boolean parents, String sessionId)
            throws CatalogException, IOException {
        QueryResult<File> queryResult = fileManager.create(studyId, File.Type.FILE, format, bioformat, path, null, null,
                description, File.Status.STAGE, 0, -1, null, -1, null, null, parents, null, sessionId);
        new CatalogFileUtils(this).upload(new ByteArrayInputStream(bytes), queryResult.first(), sessionId, false, false, true);
        return getFile(queryResult.first().getId(), sessionId);
    }

    public QueryResult<File> createFile(int studyId, File.Format format, File.Bioformat bioformat, String path, URI fileLocation, String description,
                                        boolean parents, String sessionId)
            throws CatalogException, IOException {
        QueryResult<File> queryResult = fileManager.create(studyId, File.Type.FILE, format, bioformat, path, null, null,
                description, File.Status.STAGE, 0, -1, null, -1, null, null, parents, null, sessionId);
        new CatalogFileUtils(this).upload(fileLocation, queryResult.first(), null, sessionId, false, false, true, true, Integer.MAX_VALUE);
        return getFile(queryResult.first().getId(), sessionId);
    }

    public QueryResult<File> createFile(int studyId, File.Format format, File.Bioformat bioformat, String path, String description,
                                        boolean parents, int jobId, String sessionId)
            throws CatalogException {
        return fileManager.create(studyId, File.Type.FILE, format, bioformat, path, null, null, description, null, 0, -1, null,
                jobId, null, null, parents, null, sessionId);
    }

    public QueryResult<File> createFile(int studyId, File.Type type, File.Format format, File.Bioformat bioformat, String path,
                                        String ownerId, String creationDate, String description, File.Status status,
                                        long diskUsage, int experimentId, List<Integer> sampleIds, int jobId,
                                        Map<String, Object> stats, Map<String, Object> attributes,
                                        boolean parents, QueryOptions options, String sessionId)
            throws CatalogException {
        return fileManager.create(studyId, type, format, bioformat, path, ownerId, creationDate, description, status,
                diskUsage, experimentId, sampleIds, jobId, stats, attributes, parents, options, sessionId);
    }

    public QueryResult<File> createFolder(int studyId, Path folderPath, boolean parents, QueryOptions options, String sessionId)
            throws CatalogException {
        ParamUtils.checkPath(folderPath, "folderPath");
        return fileManager.createFolder(studyId, folderPath.toString() + "/", null, parents, null, options, sessionId);
    }

    public QueryResult<File> createFolder(int studyId, Path folderPath, File.Status status, boolean parents, String description, QueryOptions options, String sessionId)
            throws CatalogException {
        ParamUtils.checkPath(folderPath, "folderPath");
        return fileManager.createFolder(studyId, folderPath.toString() + "/", status, parents, description, options, sessionId);
    }

    public QueryResult deleteFolder(int folderId, String sessionId)
            throws CatalogException, IOException {
        return deleteFile(folderId, sessionId);
    }

    public QueryResult deleteFile(int fileId, String sessionId)
            throws CatalogException, IOException {
        return fileManager.delete(fileId, null, sessionId);
    }

    public QueryResult moveFile(int fileId, String newPath, QueryOptions options, String sessionId) throws CatalogException {
        return fileManager.move(fileId, newPath, options, sessionId);
    }

    public QueryResult renameFile(int fileId, String newName, String sessionId)
            throws CatalogException {
        return fileManager.rename(fileId, newName, sessionId);
    }

    /**
     * Modify some params from the specified file:
     *

     * name
     * type
     * format
     * bioformat
     * description
     * status
     *

     * attributes
     * stats
     *
     * @param fileId     File identifier
     * @param parameters Parameters to change.
     * @param sessionId  sessionId to check permissions
     * @return
     * @throws org.opencb.opencga.catalog.exceptions.CatalogDBException
     */
    public QueryResult modifyFile(int fileId, ObjectMap parameters, String sessionId)
            throws CatalogException {
        return fileManager.update(fileId, parameters, null, sessionId); //TODO: Add query options
    }

    public QueryResult<File> getFileParent(int fileId, QueryOptions options, String sessionId)
            throws CatalogException {
        return fileManager.getParent(fileId, options, sessionId);
    }

    public QueryResult<File> getFileParents(int fileId, QueryOptions options, String sessionId)
            throws CatalogException {
        return fileManager.getParents(fileId, options, sessionId);
    }

    public QueryResult<File> getFile(int fileId, String sessionId)
            throws CatalogException {
        return getFile(fileId, null, sessionId);
    }

    public QueryResult<File> getFile(int fileId, QueryOptions options, String sessionId)
            throws CatalogException {
        return fileManager.read(fileId, options, sessionId);
    }

    public QueryResult<File> getAllFiles(int studyId, QueryOptions options, String sessionId) throws CatalogException {
        return fileManager.readAll(studyId, options, options, sessionId);
    }

    public QueryResult<File> getAllFilesInFolder(int folderId, QueryOptions options, String sessionId) throws CatalogException {
        ParamUtils.checkParameter(sessionId, "sessionId");
        ParamUtils.checkId(folderId, "folderId");
        options = ParamUtils.defaultObject(options, QueryOptions::new);
        int studyId = getStudyIdByFileId(folderId);
        File folder = getFile(folderId, sessionId).first();
        if (!folder.getType().equals(File.Type.FOLDER)) {
            throw new CatalogDBException("File {id:" + folderId + ", path:'" + folder.getPath() + "'} is not a folder.");
        }
        options.put("directory", folder.getPath());
        return fileManager.readAll(studyId, options, options, sessionId);
    }

    public DataInputStream downloadFile(int fileId, String sessionId)
            throws IOException, CatalogException {
        return downloadFile(fileId, -1, -1, sessionId);
    }

    public DataInputStream downloadFile(int fileId, int start, int limit, String sessionId)
            throws IOException, CatalogException {
        return fileManager.download(fileId, start, limit, null, sessionId);
    }

    public DataInputStream grepFile(int fileId, String pattern, boolean ignoreCase, boolean multi, String sessionId)
            throws CatalogException {
        QueryOptions options = new QueryOptions("ignoreCase", ignoreCase);
        options.put("multi", multi);
        return fileManager.grep(fileId, pattern, options, sessionId);
    }

    /**
     * TODO: Set per-file ACL
     */
    private QueryResult shareFile(int fileId, Acl acl, String sessionId)
            throws CatalogException {
        return authorizationManager.setFileACL(fileId, acl, sessionId);
    }

    /*Require role admin*/
    public QueryResult<File> searchFile(QueryOptions query, QueryOptions options, String sessionId)
            throws CatalogException {
        return searchFile(-1, query, options, sessionId);
    }

    public QueryResult<File> searchFile(int studyId, QueryOptions query, String sessionId)
            throws CatalogException {
        return searchFile(studyId, query, null, sessionId);
    }

    public QueryResult<File> searchFile(int studyId, QueryOptions query, QueryOptions options, String sessionId)
            throws CatalogException {
        return fileManager.readAll(studyId, query, options, sessionId);
    }

    public QueryResult<Dataset> createDataset(int studyId, String name, String description, List<Integer> files,
                                              Map<String, Object> attributes, QueryOptions options, String sessionId)
            throws CatalogException {
        return fileManager.createDataset(studyId, name, description, files, attributes, options, sessionId);
    }

    public QueryResult<Dataset> getDataset(int dataSetId, QueryOptions options, String sessionId)
            throws CatalogException {
        return fileManager.readDataset(dataSetId, options, sessionId);
    }

    public QueryResult refreshFolder(final int folderId, final String sessionId)
            throws CatalogDBException, IOException {
        throw new UnsupportedOperationException();
    }

    /**
     * **************************
     * Job methods
     * ***************************
     */

    public int getStudyIdByJobId(int jobId) throws CatalogException {
        return jobManager.getStudyId(jobId);
    }

    public QueryResult<Job> createJob(int studyId, String name, String toolName, String description, String commandLine,
                                      URI tmpOutDirUri, int outDirId, List<Integer> inputFiles, List<Integer> outputFiles, Map<String, Object> attributes,
                                      Map<String, Object> resourceManagerAttributes, Job.Status status,
                                      long startTime, long endTime, QueryOptions options, String sessionId)
            throws CatalogException {
        return jobManager.create(studyId, name, toolName, description, commandLine, tmpOutDirUri, outDirId, inputFiles,
                outputFiles, attributes, resourceManagerAttributes, status, startTime, endTime, options, sessionId);
    }

    public URI createJobOutDir(int studyId, String dirName, String sessionId)
            throws CatalogException, CatalogIOException {
        return jobManager.createJobOutDir(studyId, dirName, sessionId);
    }

    public QueryResult<ObjectMap> incJobVisites(int jobId, String sessionId) throws CatalogException {
        return jobManager.visit(jobId, sessionId);
    }

    public QueryResult deleteJob(int jobId, String sessionId) throws CatalogException {
        return jobManager.delete(jobId, null, sessionId);
    }

    public QueryResult<Job> getJob(int jobId, QueryOptions options, String sessionId) throws CatalogException {
        return jobManager.read(jobId, options, sessionId);
    }

    public QueryResult<Job> getUnfinishedJobs(String sessionId) throws CatalogException {
        return jobManager.readAll(new QueryOptions("status",
                Arrays.asList(
                        Job.Status.PREPARED.toString(),
                        Job.Status.QUEUED.toString(),
                        Job.Status.RUNNING.toString(),
                        Job.Status.DONE.toString()
                )
        ), null, sessionId);
    }

    public QueryResult<Job> getAllJobs(int studyId, String sessionId) throws CatalogException {
        return jobManager.readAll(studyId, null, null, sessionId);
    }

    public QueryResult modifyJob(int jobId, ObjectMap parameters, String sessionId) throws CatalogException {
        return jobManager.update(jobId, parameters, null, sessionId); //TODO: Add query options
    }

    /**
     * Project methods
     * ***************************
     */

    public QueryResult<Individual> createIndividual(int studyId, String name, String family, int fatherId, int motherId,
                                                    Individual.Gender gender, QueryOptions options, String sessionId)
            throws CatalogException {
        return individualManager.create(studyId, name, family, fatherId, motherId, gender, options, sessionId);
    }

    public QueryResult<Individual> getIndividual(int individualId, QueryOptions options, String sessionId)
            throws CatalogException {
        return individualManager.read(individualId, options, sessionId);
    }

    public QueryResult<Individual> getAllIndividuals(int studyId, QueryOptions options, String sessionId) throws CatalogException {
        return individualManager.readAll(studyId, options, sessionId);
    }

    public QueryResult<Individual> modifyIndividual(int individualId, QueryOptions options, String sessionId) throws CatalogException {
        return individualManager.update(individualId, options, options, sessionId);
    }

    public QueryResult<Individual> deleteIndividual(int individualId, QueryOptions options, String sessionId) throws CatalogException {
        return individualManager.delete(individualId, options, sessionId);
    }

    /**
     * Samples methods
     * ***************************
     */

    public QueryResult<Sample> createSample(int studyId, String name, String source, String description,
                                            Map<String, Object> attributes, QueryOptions options, String sessionId)
            throws CatalogException {
        return sampleManager.create(studyId, name, source, description, attributes, options, sessionId);
    }

    public QueryResult<Sample> getSample(int sampleId, QueryOptions options, String sessionId)
            throws CatalogException {
        return sampleManager.read(sampleId, options, sessionId);
    }

    public QueryResult<Sample> getAllSamples(int studyId, QueryOptions options, String sessionId) throws CatalogException {
        return sampleManager.readAll(studyId, options, options, sessionId);
    }

    public QueryResult<Sample> modifySample(int sampleId, QueryOptions queryOptions, String sessionId) throws CatalogException {
        return sampleManager.update(sampleId, queryOptions, queryOptions, sessionId);
    }

    public QueryResult<AnnotationSet> annotateSample(int sampleId, String id, int variableSetId,
                                                     Map<String, Object> annotations,
                                                     Map<String, Object> attributes,
                                                     String sessionId) throws CatalogException {
        return annotateSample(sampleId, id, variableSetId, annotations, attributes, true, sessionId);
    }

    public QueryResult<AnnotationSet> annotateSample(int sampleId, String id, int variableSetId,
                                                            Map<String, Object> annotations,
                                                            Map<String, Object> attributes,
                                                            boolean checkAnnotationSet,
                                                            String sessionId)
            throws CatalogException {
        return sampleManager.annotate(sampleId, id, variableSetId, annotations, attributes, checkAnnotationSet, sessionId);
    }

    public QueryResult<Sample> deleteSample(int sampleId, QueryOptions options, String sessionId) throws CatalogException {
        return sampleManager.delete(sampleId, options, sessionId);
    }

    /**
     * VariableSet methods
     * ***************************
     */

    public QueryResult<VariableSet> createVariableSet(int studyId, String name, Boolean unique,
                                                      String description, Map<String, Object> attributes,
                                                      List<Variable> variables, String sessionId)
            throws CatalogException {
        return sampleManager.createVariableSet(studyId, name, unique, description, attributes, variables, sessionId);
    }

    public QueryResult<VariableSet> createVariableSet(int studyId, String name, Boolean unique,
                                                      String description, Map<String, Object> attributes,
                                                      Set<Variable> variables, String sessionId)
            throws CatalogException {
        return sampleManager.createVariableSet(studyId, name, unique, description, attributes, variables, sessionId);
    }

    public QueryResult<VariableSet> getVariableSet(int variableSet, QueryOptions options, String sessionId)
            throws CatalogException {
        return sampleManager.readVariableSet(variableSet, options, sessionId);
    }

    public QueryResult<VariableSet> getAllVariableSet(int studyId, QueryOptions options, String sessionId)
            throws CatalogException {
        return sampleManager.readAllVariableSets(studyId, options, sessionId);
    }

    public QueryResult<VariableSet> deleteVariableSet(int variableSetId, QueryOptions queryOptions, String sessionId)
            throws CatalogException {
        return sampleManager.deleteVariableSet(variableSetId, queryOptions, sessionId);
    }

    /**
     * Cohort methods
     * ***************************
     */

    public int getStudyIdByCohortId(int cohortId) throws CatalogException {
        return sampleManager.getStudyIdByCohortId(cohortId);
    }

    public QueryResult<Cohort> getCohort(int cohortId, QueryOptions options, String sessionId) throws CatalogException {
        return sampleManager.readCohort(cohortId, options, sessionId);
    }

    public QueryResult<Cohort> getAllCohorts(int studyId, QueryOptions options, String sessionId) throws CatalogException {
        return sampleManager.readAllCohort(studyId, options, sessionId);
    }

    public QueryResult<Cohort> createCohort(int studyId, String name, Cohort.Type type, String description, List<Integer> sampleIds,
                                            Map<String, Object> attributes, String sessionId) throws CatalogException {
        return sampleManager.createCohort(studyId, name, type, description, sampleIds, attributes, sessionId);
    }

    public QueryResult<Cohort> modifyCohort(int cohortId, ObjectMap updateParams, String sessionId) throws CatalogException {
        return sampleManager.updateCohort(cohortId, updateParams, sessionId);
    }

    public QueryResult<Cohort> deleteCohort(int cohortId, ObjectMap options, String sessionId) throws CatalogException {
        return sampleManager.deleteCohort(cohortId, options, sessionId);
    }

    /**
     * Tools methods
     * ***************************
     */

    public QueryResult<Tool> createTool(String alias, String description, Object manifest, Object result,
                                        String path, boolean openTool, String sessionId) throws CatalogException {
        return jobManager.createTool(alias, description, manifest, result, path, openTool, sessionId);
    }

    public QueryResult<Tool> getTool(int id, String sessionId) throws CatalogException {
        return jobManager.readTool(id, sessionId);
    }

}


text:
<?php

namespace Google\Service\DataCatalog;

class GoogleCloudDatacatalogV1RenameTagTemplateFieldEnumValueRequest extends \Google\Model
{
  /**
   * @var string
   */
  public $newEnumValueDisplayName;

  /**
   * @param string
   */
  public function setNewEnumValueDisplayName($newEnumValueDisplayName)
  {
    $this->newEnumValueDisplayName = $newEnumValueDisplayName;
  }
  /**
   * @return string
   */
  public function getNewEnumValueDisplayName()
  {
    return $this->newEnumValueDisplayName;
  }
}

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

redpajama_set_name: RedPajamaGithub


text:
AttachEvent(window,'load',function(){
	var tocTag='ul',tocClass='tabset_tabs',tabTag='a',contentClass='tabset_content';

	function FindEl(tagName,evt){
		if (!evt && window.event) evt=event;
		if (!evt) return DebugOut("Can't find an event to handle in DLTabSet::SetTab",0);
		var el=evt.currentTarget || evt.srcElement;
		while (el && (!el.tagName || el.tagName.toLowerCase()!=tagName)) el=el.parentNode;
		return el;
	}

	function SetTabActive(tab){
		if (tab.tabTOC.activeTab){
			if (tab.tabTOC.activeTab==tab) return;
			KillClass(tab.tabTOC.activeTab,'active');
			if (tab.tabTOC.activeTab.tabContent) KillClass(tab.tabTOC.activeTab.tabContent,'tabset_content_active');
			//if (tab.tabTOC.activeTab.tabContent) tab.tabTOC.activeTab.tabContent.style.display='';
			if (tab.tabTOC.activeTab.prevTab) KillClass(tab.tabTOC.activeTab.previousTab,'preActive');
			if (tab.tabTOC.activeTab.nextTab) KillClass(tab.tabTOC.activeTab.nextTab,'postActive');
		}
		AddClass(tab.tabTOC.activeTab=tab,'active');
		if (tab.tabContent) AddClass(tab.tabContent,'tabset_content_active');
		//if (tab.tabContent) tab.tabContent.style.display='block';
		if (tab.prevTab) AddClass(tab.prevTab,'preActive');
		if (tab.nextTab) AddClass(tab.nextTab,'postActive');
	}
	function SetTabFromAnchor(evt){
		//setTimeout('document.body.scrollTop='+document.body.scrollTop,1);
		SetTabActive(FindEl('a',evt).semanticTab);
	}

	function Init(){
		window.everyTabThereIsById = {};

		var anchorMatch = /#([a-z][\w.:-]*)$/i,match;
		var activeTabs = [];

		var tocs = document.getElementsByTagName(tocTag);
		for (var i=0,len=tocs.length;i<len;i++){
			var toc = tocs[i];
			if (!HasClass(toc,tocClass)) continue;

			var lastTab;
			var tabs = toc.getElementsByTagName(tabTag);
			for (var j=0,len2=tabs.length;j<len2;j++){
				var tab = tabs[j];
				if (!tab.href || !(match=anchorMatch.exec(tab.href))) continue;
				if (lastTab){
					tab.prevTab=lastTab;
					lastTab.nextTab=tab;
				}
				tab.tabTOC=toc;
				everyTabThereIsById[tab.tabID=match[1]]=tab;
				tab.tabContent = document.getElementById(tab.tabID);

				if (HasClass(tab,'active')) activeTabs[activeTabs.length]=tab;

				lastTab=tab;
			}
			AddClass(toc.getElementsByTagName('li')[0],'firstchild');
		}

		for (var i=0,len=activeTabs.length;i<len;i++){
			SetTabActive(activeTabs[i]);
		}

		for (var i=0,len=document.links.length;i<len;i++){
			var a = document.links[i];
			if (!(match=anchorMatch.exec(a.href))) continue;
			if (a.semanticTab = everyTabThereIsById[match[1]]) AttachEvent(a,'click',SetTabFromAnchor,false);
		}

		if ((match=anchorMatch.exec(location.href)) && (a=everyTabThereIsById[match[1]])) SetTabActive(a);

		//Comment out the next line and include the file directly if you need IE5Mac or Opera7 support.
		AddStyleSheet('tabtastic.css',0);
	}
	Init();
},false);


text:
require 'spec_helpers/base'

shared_context 'visitation', :visitation do

  # Create a visitor double expecting to see the given tag and childen.
  #
  # After the expected tag and visited object, the remaining splat is a series of runs of
  # expected children objects prefixed by their tags.  So, this invocation:
  #
  # ```
  # visitor_expecting :parent, parent, :first_child, *first, :second_child, *second
  # ```
  #
  # ..would result in a visitor expecting to visit parent with tag `:parent`, and while
  # doing so to first visit the children in `first` (each with tag `:first_child`)
  # followed by the children in `second` (tagged with `:second_child`.)
  #
  # Child objects should not be symbols!
  def visitor_expecting(tag, visited, *tags_and_children)
    double("visitor expecting #{tag}").as_null_object.tap do |visitor|
      set_visitor_expectations(visitor, tag, visited, tags_and_children)
    end
  end

  private

  def set_visitor_expectations(visitor, tag, visited, tags_and_children)
    visitor.should_receive(:"visit_#{tag}").with(visited).ordered
    set_child_expectations(visitor, tag, tags_and_children)
    visitor.should_receive(:"leave_#{tag}").with(visited).ordered
  end

  def set_child_expectations(visitor, child_tag, tags_and_children)
    tags_and_children.each do |tag_or_child|
      if tag_or_child.is_a?(Symbol)
        child_tag = tag_or_child
      else
        visitor.should_receive(:"visit_#{child_tag}").with(tag_or_child).ordered
      end
    end
  end

end


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>stderr? (Spec::Runner::Options)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/spec/runner/options.rb, line 330
      def stderr?
        @error_stream == $stderr
      end


text:
namespace TaskManager.Configuration
{
    using System;
    using TaskManager.Common;

    /// <summary>
    /// Represents schedule configuration information.
    /// </summary>
    [Serializable, CLSCompliant(true)]
    public class ScheduleData : ITaskConfigurationData
    {
        /// <summary>
        /// Gets or sets the schedule starting time (relative to zero hour in the current time zone).
        /// </summary>
        public TimeSpan From { get; set; }

        /// <summary>
        /// Gets or sets the schedule ending time (relative to zero hour in the current time zone).
        /// </summary>
        public TimeSpan To { get; set; }

        /// <summary>
        /// Gets or sets the number of task instances spawned.
        /// </summary>
        /// <remarks>Default is to spawn a single instance.</remarks>
        public int? Spawn { get; set; }

        /// <summary>
        /// Gets or sets the amount of time the SLA scheduler waits before it considers the task execution is blocked/has hanged/in error and restarts it.
        /// </summary>
        public TimeSpan? Timeout { get; set; }

        /// <summary>
        /// Gets or sets the amount of time the task is allowed to be late while waiting for an executing thread.
        /// </summary>
        /// <remarks>If the task doesn't start executing in this amount of time (after it is marked to start), and the number of executing threads is below the maximum number of threads allowed, the SLA scheduler spawns a new thread for the task.</remarks>
        public TimeSpan? SLA { get; set; }

        /// <summary>
        /// Gets or sets the minimum amount of time allowed per execution burst.
        /// </summary>
        public TimeSpan? TimeUnit { get; set; }

        /// <summary>
        /// Gets or sets the number of times a task runs per execution burst.
        /// </summary>
        public int? MaxRuns { get; set; }

        /// <summary>
        /// Gets or sets the amount of time to wait after an empty or failed execution burst.
        /// </summary>
        public TimeSpan? Wait { get; set; }
    }
}


text:
@import url("snapdragon/snapdragon-forms.css");
@import url("snapdragon/snapdragon-common.css");
@import url("jquery/jquery-ui-1.8.2.custom.css");


text:
A list of all outstanding tasks

## Protocol implementation


text:
namespace TomsToolbox.Wpf.Controls;

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

/// <summary>
/// A canvas that transforms the coordinates of it's children to the own visual before arranging them.
/// It is used to have an overlay of non-scaled object on top of a scaled object, where the coordinates of the overlay objects are expressed in the coordinate system
/// of the scaled object (<see cref="World"/>). One major use case are e.g. pin points on a map, where the map scales, while the pin points only move but keep their size.
/// While the <see cref="Canvas"/> only accepts one of <see cref="P:System.Windows.Controls.Canvas.Left"/>/<see cref="P:System.Windows.Controls.Canvas.Right"/>
/// or <see cref="P:System.Windows.Controls.Canvas.Top"/>/<see cref="P:System.Windows.Controls.Canvas.Bottom"/>,
/// with the ViewportCanvas you can specify both to stretch the object accordingly to the transformation.
/// </summary>
public class ViewportCanvas : Canvas, ILayer
{
    /// <summary>
    /// Gets or sets the physical layer. The children`s coordinates are assumed to be relative to the physical layer.
    /// </summary>
    public FrameworkElement? World
    {
        get => (FrameworkElement?)GetValue(WorldProperty);
        set => SetValue(WorldProperty, value);
    }
    /// <summary>
    /// Identifies the <see cref="World"/> dependency property.
    /// </summary>
    public static readonly DependencyProperty WorldProperty =
        DependencyProperty.Register("World", typeof(FrameworkElement), typeof(ViewportCanvas));

    /// <summary>
    /// When overridden in a derived class, measures the size in layout required for child elements and determines a size for the <see cref="T:System.Windows.FrameworkElement" />-derived class.
    /// </summary>
    /// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param>
    /// <returns>
    /// The size that this element determines it needs during layout, based on its calculations of child element sizes.
    /// </returns>
    protected override Size MeasureOverride(Size availableSize)
    {
        var worldLayer = World;
        var viewportLayer = this;

        if (worldLayer == null)
            return new Size();

        foreach (var child in InternalChildren.OfType<FrameworkElement>())
        {
            var left = GetLeft(child);
            var top = GetTop(child);
            var right = GetRight(child);
            var bottom = GetBottom(child);

            var rect = new Rect(0, 0, Math.Abs(right - left), Math.Abs(bottom - top));
            var constraint = rect.Translate(worldLayer, viewportLayer).Size;

            if (double.IsNaN(constraint.Width))
                constraint.Width = double.PositiveInfinity;
            else
                constraint.Width = Math.Max(constraint.Width, child.MinWidth);

            if (double.IsNaN(constraint.Height))
                constraint.Height = double.PositiveInfinity;
            else
                constraint.Height = Math.Max(constraint.Height, child.MinHeight);

            child.Measure(constraint);
        }

        return new Size();
    }

    /// <summary>
    /// When overridden in a derived class, positions child elements and determines a size for a <see cref="T:System.Windows.FrameworkElement" /> derived class.
    /// </summary>
    /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
    /// <returns>
    /// The actual size used.
    /// </returns>
    protected override Size ArrangeOverride(Size finalSize)
    {
        var worldLayer = World;
        var viewportLayer = this;

        if (worldLayer == null)
            return finalSize;

        foreach (UIElement? child in Children)
        {
            if (child == null)
                continue;

            var left = GetLeft(child);
            var top = GetTop(child);
            var right = GetRight(child);
            var bottom = GetBottom(child);

            var targetRect = GetTargetRect(left, right, top, bottom);

            targetRect = targetRect.Translate(worldLayer, viewportLayer);

            if (Math.Abs(targetRect.Width) < child.DesiredSize.Width)
                targetRect.Width = child.DesiredSize.Width;
            if (Math.Abs(targetRect.Height) < child.DesiredSize.Height)
                targetRect.Height = child.DesiredSize.Height;

            if (double.IsNaN(left)) // only right specified
                targetRect.X -= targetRect.Width;
            if (double.IsNaN(top)) // only bottom specified
                targetRect.Y -= targetRect.Height;

            if (double.IsNaN(targetRect.X) || double.IsNaN(targetRect.Y))
                continue;

            child.Arrange(targetRect);
        }

        return finalSize;
    }

    private static Rect GetTargetRect(double left, double right, double top, double bottom)
    {
        var targetRect = new Rect(0, 0, 0, 0);

        if (!double.IsNaN(left))
        {
            if (!double.IsNaN(right))
            {
                targetRect.X = Math.Min(left, right);
                targetRect.Width = Math.Abs(right - left);
            }
            else
            {
                targetRect.X = left;
            }
        }
        else
        {
            targetRect.X = right;
        }

        if (!double.IsNaN(top))
        {
            if (!double.IsNaN(bottom))
            {
                targetRect.Y = Math.Min(top, bottom);
                targetRect.Height = Math.Abs(bottom - top);
            }
            else
            {
                targetRect.Y = top;
            }
        }
        else
        {
            targetRect.Y = bottom;
        }

        return targetRect;
    }

    /// <summary>
    /// Invalidates the layout of this instance.
    /// </summary>
    public void Invalidate()
    {
        InvalidateMeasure();
    }
}


text:
package chat.multicast.compartido;

import java.net.InetAddress;

/**
 *
 * @author (at)fferegrino
 */

public class Mensaje {
    InetAddress sender;
    String texto;

    public Mensaje(InetAddress sender, String texto) {
        this.sender = sender;
        this.texto = texto;
    }

    public InetAddress getSender() {
        return sender;
    }

    public String getTexto() {
        return texto;
    }

}


text:
/**
 * MongoDB Page Schema
 * Author: Matthew Murphy
 */

var mongoose = require('mongoose');

var pageSchema = mongoose.Schema({
    _websiteId: {type: mongoose.Schema.ObjectId, ref: "AssignmentWebsiteModel"},
    description: {type: String, require: true},
    widgets: [{type: mongoose.Schema.ObjectId, ref: "AssignmentWidgetModel"}],
    name: {type: String, require: true}
}, {collection: "udergraduate_assignment_page"});

module.exports = pageSchema;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
	XML

	Copyright 2014-2020 MicroEJ Corp. All rights reserved.
	Use of this source code is governed by a BSD-style license that can be found with this software.
-->
<poem xmlns="http://www.megginson.com/ns/exp/poetry">
	<title>Roses are Red</title>
	<l>Roses are red,</l>
	<l>Violets are blue;</l>
	<l>Sugar is sweet,</l>
	<l>And I love you.</l>
</poem>


text:
<?php

namespace Gandung\Promise\Tests;

use Gandung\Promise\Promise;

class Thennable extends \PHPUnit_Framework_TestCase
{
    public function callNonPublicMethod(&$object, $method, $parameters)
    {
        $reflector = new \ReflectionClass($object);
        $q = $reflector->getMethod($method);
        $q->setAccessible(true);

        return $q->invokeArgs($object, is_array($parameters) ? $parameters
            : array_slice(func_get_args(), 2));
    }

    public function testCanThennableInPendingState()
    {
        $promise = new Promise();
        $this->callNonPublicMethod($promise, 'setState', 1);
        $promise->then(function ($q) {
            echo sprintf("%s" . PHP_EOL, $q);
        });
    }

    public function testCanThennableInFulfilledState()
    {
        $promise = new Promise();
        $this->callNonPublicMethod($promise, 'setState', 4);
        $promise->then(function ($q) {
            echo sprintf("%s" . PHP_EOL, $q);
        });
    }

    public function testCanThennableInRejectedState()
    {
        $promise = new Promise();
        $this->callNonPublicMethod($promise, 'setState', 8);
        $promise->then(function ($q) {
            echo sprintf("%s" . PHP_EOL, $q);
        });
    }
}


text:
package org.citygml4j.xml.adapter.pointcloud;

import org.citygml4j.core.model.ade.generic.GenericADEOfPointCloud;
import org.citygml4j.core.model.pointcloud.ADEOfPointCloud;
import org.citygml4j.core.model.pointcloud.PointCloud;
import org.citygml4j.core.util.CityGMLConstants;
import org.citygml4j.xml.adapter.ade.ADEBuilderHelper;
import org.citygml4j.xml.adapter.ade.ADESerializerHelper;
import org.citygml4j.xml.adapter.core.AbstractPointCloudAdapter;
import org.xmlobjects.annotation.XMLElement;
import org.xmlobjects.builder.ObjectBuildException;
import org.xmlobjects.gml.adapter.basictypes.CodeAdapter;
import org.xmlobjects.gml.adapter.geometry.aggregates.MultiPointPropertyAdapter;
import org.xmlobjects.serializer.ObjectSerializeException;
import org.xmlobjects.stream.XMLReadException;
import org.xmlobjects.stream.XMLReader;
import org.xmlobjects.stream.XMLWriteException;
import org.xmlobjects.stream.XMLWriter;
import org.xmlobjects.xml.Attributes;
import org.xmlobjects.xml.Element;
import org.xmlobjects.xml.Namespaces;

import javax.xml.namespace.QName;

@XMLElement(name = "PointCloud", namespaceURI = CityGMLConstants.CITYGML_3_0_POINTCLOUD_NAMESPACE)
public class PointCloudAdapter extends AbstractPointCloudAdapter<PointCloud> {

    @Override
    public PointCloud createObject(QName name, Object parent) throws ObjectBuildException {
        return new PointCloud();
    }

    @Override
    public void buildChildObject(PointCloud object, QName name, Attributes attributes, XMLReader reader) throws ObjectBuildException, XMLReadException {
        if (CityGMLConstants.CITYGML_3_0_POINTCLOUD_NAMESPACE.equals(name.getNamespaceURI())) {
            switch (name.getLocalPart()) {
                case "mimeType":
                    object.setMimeType(reader.getObjectUsingBuilder(CodeAdapter.class));
                    return;
                case "pointFile":
                    reader.getTextContent().ifPresent(object::setPointFile);
                    return;
                case "pointFileSrsName":
                    reader.getTextContent().ifPresent(object::setPointFileSrsName);
                    return;
                case "points":
                    object.setPoints(reader.getObjectUsingBuilder(MultiPointPropertyAdapter.class));
                    return;
                case "adeOfPointCloud":
                    ADEBuilderHelper.addADEProperty(object, GenericADEOfPointCloud::of, reader);
                    return;
            }
        }

        super.buildChildObject(object, name, attributes, reader);
    }

    @Override
    public Element createElement(PointCloud object, Namespaces namespaces) throws ObjectSerializeException {
        return Element.of(CityGMLConstants.CITYGML_3_0_POINTCLOUD_NAMESPACE, "PointCloud");
    }

    @Override
    public void writeChildElements(PointCloud object, Namespaces namespaces, XMLWriter writer) throws ObjectSerializeException, XMLWriteException {
        super.writeChildElements(object, namespaces, writer);

        if (object.getMimeType() != null)
            writer.writeElementUsingSerializer(Element.of(CityGMLConstants.CITYGML_3_0_POINTCLOUD_NAMESPACE, "mimeType"), object.getMimeType(), CodeAdapter.class, namespaces);

        if (object.getPointFile() != null)
            writer.writeElement(Element.of(CityGMLConstants.CITYGML_3_0_POINTCLOUD_NAMESPACE, "pointFile").addTextContent(object.getPointFile()));

        if (object.getPointFileSrsName() != null)
            writer.writeElement(Element.of(CityGMLConstants.CITYGML_3_0_POINTCLOUD_NAMESPACE, "pointFileSrsName").addTextContent(object.getPointFileSrsName()));

        if (object.getPoints() != null)
            writer.writeElementUsingSerializer(Element.of(CityGMLConstants.CITYGML_3_0_POINTCLOUD_NAMESPACE, "points"), object.getPoints(), MultiPointPropertyAdapter.class, namespaces);

        for (ADEOfPointCloud property : object.getADEProperties(ADEOfPointCloud.class))
            ADESerializerHelper.writeADEProperty(Element.of(CityGMLConstants.CITYGML_3_0_POINTCLOUD_NAMESPACE, "adeOfPointCloud"), property, namespaces, writer);
    }
}


text:
namespace Ui{
	class SystemWindow;
};

class SystemWindow : public QDialog{
	Q_OBJECT
public:
	SystemWindow();
	~SystemWindow();

public slots:
	void updateWindow();

private:
	Ui::SystemWindow *ui;

	//void closeAllWindows();
	bool promptAboutUpdates(bool &skip); //main bool return: continue/cancel, skip: skip updates or not

private slots:
	void sysLogout();

	void sysRestart();

	void sysShutdown();

	void sysSuspend();

	void sysCancel(){
	  this->close();
	}

	void sysLock();
};

#endif


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __LIB_NDEF_SMS_H
#define __LIB_NDEF_SMS_H

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "lib_NDEF.h"

typedef struct
{
	char PhoneNumber[16];
	char Message[400];
	char Information[400];
}sSMSInfo;

/* Struct defined in lib_NDEF.h */
typedef struct sRecordInfo sRecordInfo;

uint16_t NDEF_ReadSMS(sRecordInfo *pRecordStruct, sSMSInfo *pSMSStruct);
uint16_t NDEF_WriteSMS( sSMSInfo *pSMSStruct );
void NDEF_PrepareSMSMessage ( sSMSInfo *pSMSStruct, uint8_t *pNDEFMessage, uint16_t *size );

#ifdef __cplusplus
}
#endif

#endif /* __LIB_NDEF_SMS_H */

/******************* (C) COPYRIGHT 2014 STMicroelectronics *****END OF FILE****/


text:
package com.intellij.appengine.facet;

import com.intellij.facet.FacetConfiguration;
import com.intellij.facet.ui.FacetEditorContext;
import com.intellij.facet.ui.FacetEditorTab;
import com.intellij.facet.ui.FacetValidatorsManager;
import com.intellij.openapi.components.PersistentStateComponent;
import org.jetbrains.jps.appengine.model.PersistenceApi;
import org.jetbrains.jps.appengine.model.impl.AppEngineModuleExtensionProperties;

import java.util.List;

/**
 * @author nik
 */
public class AppEngineFacetConfiguration implements FacetConfiguration, PersistentStateComponent<AppEngineModuleExtensionProperties> {
  private AppEngineModuleExtensionProperties myProperties = new AppEngineModuleExtensionProperties();

  public FacetEditorTab[] createEditorTabs(FacetEditorContext editorContext, FacetValidatorsManager validatorsManager) {
    return new FacetEditorTab[] {
       new AppEngineFacetEditor(this, editorContext, validatorsManager)
    };
  }

  public AppEngineModuleExtensionProperties getState() {
    return myProperties;
  }

  public void loadState(AppEngineModuleExtensionProperties state) {
    myProperties = state;
  }

  public String getSdkHomePath() {
    return myProperties.mySdkHomePath;
  }

  public boolean isRunEnhancerOnMake() {
    return myProperties.myRunEnhancerOnMake;
  }

  public List<String> getFilesToEnhance() {
    return myProperties.myFilesToEnhance;
  }

  public PersistenceApi getPersistenceApi() {
    return myProperties.myPersistenceApi;
  }

  public void setSdkHomePath(String sdkHomePath) {
    myProperties.mySdkHomePath = sdkHomePath;
  }

  public void setPersistenceApi(PersistenceApi persistenceApi) {
    myProperties.myPersistenceApi = persistenceApi;
  }

  public void setFilesToEnhance(List<String> filesToEnhance) {
    myProperties.myFilesToEnhance = filesToEnhance;
  }

  public void setRunEnhancerOnMake(boolean runEnhancerOnMake) {
    myProperties.myRunEnhancerOnMake = runEnhancerOnMake;
  }
}


text:
package org.incode.module.commchannel.integtests.demo;

import javax.inject.Inject;

import org.junit.Before;

import org.apache.isis.applib.fixturescripts.FixtureScripts;

import org.incode.module.commchannel.fixture.dom.CommChannelDemoObject;
import org.incode.module.commchannel.fixture.dom.CommChannelDemoObjectMenu;
import org.incode.module.commchannel.fixture.scripts.teardown.CommChannelDemoObjectsTearDownFixture;
import org.incode.module.commchannel.integtests.CommChannelModuleIntegTest;

public class CommChannelDemoObjectIntegTest extends CommChannelModuleIntegTest {

    @Inject
    FixtureScripts fixtureScripts;

    @Inject
    CommChannelDemoObjectMenu commChannelDemoObjectMenu;

    CommChannelDemoObject commChannelDemoObject;

    @Before
    public void setUpData() throws Exception {
        fixtureScripts.runFixtureScript(new CommChannelDemoObjectsTearDownFixture(), null);

        commChannelDemoObject = wrap(commChannelDemoObjectMenu).create("Foo");
    }

}


text:
/*************************************************************************/
/*  error_macros.cpp                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "error_macros.h"

#include "core/io/logger.h"
#include "core/os/os.h"
#include "core/string/ustring.h"

static ErrorHandlerList *error_handler_list = nullptr;

void add_error_handler(ErrorHandlerList *p_handler) {
	_global_lock();
	p_handler->next = error_handler_list;
	error_handler_list = p_handler;
	_global_unlock();
}

void remove_error_handler(ErrorHandlerList *p_handler) {
	_global_lock();

	ErrorHandlerList *prev = nullptr;
	ErrorHandlerList *l = error_handler_list;

	while (l) {
		if (l == p_handler) {
			if (prev) {
				prev->next = l->next;
			} else {
				error_handler_list = l->next;
			}
			break;
		}
		prev = l;
		l = l->next;
	}

	_global_unlock();
}

void _err_print_error(const char *p_function, const char *p_file, int p_line, const char *p_error, ErrorHandlerType p_type) {
	_err_print_error(p_function, p_file, p_line, p_error, "", p_type);
}

void _err_print_error(const char *p_function, const char *p_file, int p_line, const String &p_error, ErrorHandlerType p_type) {
	_err_print_error(p_function, p_file, p_line, p_error.utf8().get_data(), "", p_type);
}

void _err_print_error(const char *p_function, const char *p_file, int p_line, const char *p_error, const char *p_message, ErrorHandlerType p_type) {
	OS::get_singleton()->print_error(p_function, p_file, p_line, p_error, p_message, (Logger::ErrorType)p_type);

	_global_lock();
	ErrorHandlerList *l = error_handler_list;
	while (l) {
		l->errfunc(l->userdata, p_function, p_file, p_line, p_error, p_message, p_type);
		l = l->next;
	}

	_global_unlock();
}

void _err_print_error(const char *p_function, const char *p_file, int p_line, const String &p_error, const char *p_message, ErrorHandlerType p_type) {
	_err_print_error(p_function, p_file, p_line, p_error.utf8().get_data(), p_message, p_type);
}

void _err_print_error(const char *p_function, const char *p_file, int p_line, const char *p_error, const String &p_message, ErrorHandlerType p_type) {
	_err_print_error(p_function, p_file, p_line, p_error, p_message.utf8().get_data(), p_type);
}

void _err_print_error(const char *p_function, const char *p_file, int p_line, const String &p_error, const String &p_message, ErrorHandlerType p_type) {
	_err_print_error(p_function, p_file, p_line, p_error.utf8().get_data(), p_message.utf8().get_data(), p_type);
}

void _err_print_index_error(const char *p_function, const char *p_file, int p_line, int64_t p_index, int64_t p_size, const char *p_index_str, const char *p_size_str, const char *p_message, bool fatal) {
	String fstr(fatal ? "FATAL: " : "");
	String err(fstr + "Index " + p_index_str + " = " + itos(p_index) + " is out of bounds (" + p_size_str + " = " + itos(p_size) + ").");
	_err_print_error(p_function, p_file, p_line, err.utf8().get_data(), p_message);
}

void _err_print_index_error(const char *p_function, const char *p_file, int p_line, int64_t p_index, int64_t p_size, const char *p_index_str, const char *p_size_str, const String &p_message, bool fatal) {
	_err_print_index_error(p_function, p_file, p_line, p_index, p_size, p_index_str, p_size_str, p_message.utf8().get_data(), fatal);
}


text:
nereid-wishlist
===============

.. image:: https://travis-ci.org/fulfilio/nereid-wishlist.svg?branch=develop
  :target: https://travis-ci.org/fulfilio/nereid-wishlist
  :alt: Build Status
.. image:: https://pypip.in/download/fio_nereid_wishlist/badge.svg
    :target: https://pypi.python.org/pypi/fio_nereid_wishlist/
    :alt: Downloads
.. image:: https://pypip.in/version/fio_nereid_wishlist/badge.svg
    :target: https://pypi.python.org/pypi/fio_nereid_wishlist/
    :alt: Latest Version
.. image:: https://pypip.in/status/fio_nereid_wishlist/badge.svg
    :target: https://pypi.python.org/pypi/fio_nereid_wishlist/
    :alt: Development Status


text:
#include <math.h>
#include <stdlib.h>
#include <string.h>

#include "misc/nested.h"
#include "misc/misc.h"

#include "fltools.h"

static int compare(const void* _a, const void* _b)
{
	const complex float* a = _a;
	const complex float* b = _b;
	return copysignf(1., (cabsf(*a) - cabsf(*b)));
}

void zsort(int N, complex float tmp[N])
{

	qsort(tmp, N, sizeof(complex float), compare);
}

complex float zselect(int N, int k, const complex float x[N])
{
	complex float (*p)[N] = xmalloc(sizeof(*p));

	memcpy(*p, x, sizeof *p);

	zsort(N, *p);

	complex float val = (*p)[k];

	xfree(p);

	return val;
}


text:
"use strict";

function endModule() {
    module.exports = Object.freeze({
        values: require("./core/values.js")
    });
}

endModule();


text:
package com.wegas.proggame.rest;

import com.wegas.core.ejb.ScriptFacade;
import com.wegas.core.exception.WegasException;
import com.wegas.core.persistence.game.Script;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.script.ScriptException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author Francois-Xavier Aeberhard <fx@red-agent.com>
 */
@Stateless
@Path("GameModel/{gameModelId : [1-9][0-9]*}/VariableDescriptor/ProgGame/")
public class ProgGameController {

    /**
     *
     */
    @EJB
    private ScriptFacade scriptFacade;

    /**
     *
     * @param playerId
     * @param script
     * @return
     * @throws ScriptException
     * @throws WegasException
     */
    @POST
    @Path("/Run/{playerId : [1-9][0-9]*}")
    @Produces(MediaType.APPLICATION_JSON)
    public Object run(
            @PathParam("playerId") Long playerId, String script) throws ScriptException, WegasException {

        return scriptFacade.eval(playerId, new Script("JavaScript", script));
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class TBView_Colors extends CE_Controller {

	public function __construct(){
		parent::__construct();
		// do whatever here - i often use this method for authentication controller

		$this->load->model('Mdl_Colors');
		$this->load->helper("utility");
	}

	public function ajax_list() {
		$ret = [];

		$data = $this->Mdl_Colors->_list(
			$_POST['rp'],
			$_POST['page'],
			$_POST['query'],
			$_POST['qtype'],
			$_POST['sortname'],
			$_POST['sortorder']);

		echo json_encode(array(
		  'page'=>$_POST['page'],
		  'total'=>$this->Mdl_Colors->get_length(),
		  'rows'=>$data,
		));
	}

	public function edit($id = null) {
		$color = new stdClass();

		if ($id != null) {
			$color = $this->Mdl_Colors->get($id);

			$color->isNew = false;
		}
		else {
			$color->isNew = true;

			$color->id = gen_uuid();
			$color->name = "";
		}

		parent::initView(get_class($this) . '/edit', 'Colors', 'Edit color information.',
			$color
		);

		parent::loadView();
	}

	public function save() {
		$id = $_POST["id"];
		unset($_POST["id"]);

		$this->Mdl_Colors->save($id, $_POST);

		redirect('/Colors/', 'refresh');
	}

	public function del($id) {
		$this->Mdl_Colors->del($id);

		redirect('/Colors/', 'refresh');
	}
}

?>


text:
package ru.job4j.task1;

/**
 * The class ConcurrentCounter describes a race condition situation
 * of shared and not synchronized data.
 */
public class ConcurrentCounter {

    /**
     * An amount of a loop iteration.
     */
    private static final int N = 1000_000;

    /**
     * An accumulator.
     */
    private static int counter = 0;

    /**
     * A method calling from different threads to demonstrates a cashed value.
     */
    public static void increaseCounter() {
        for (int i = 0; i < N; i++) {
            counter++;
        }
    }

    /**
     * The main method.
     * @param args args.
     * @throws InterruptedException in case of interrupt.
     */
    public static void main(String[] args) throws InterruptedException {

        Thread threadA = new Thread(() -> {
            increaseCounter();
            System.out.println("Thread A is finished");
        });

        Thread threadB = new Thread(() -> {
            increaseCounter();
            System.out.println("Thread B is finished");
        });

        threadA.start();
        threadB.start();

        threadA.join();
        threadB.join();

        System.out.println("Expected result is 2000000");
        System.out.println("    Real result is " + counter);
    }
}


text:
using namespace arangodb;
using namespace arangodb::basics;

LockfileFeature::LockfileFeature(
    application_features::ApplicationServer* server)
    : ApplicationFeature(server, "Lockfile") {
  setOptional(false);
  requiresElevatedPrivileges(false);
  startsAfter("DatabasePath");
}

void LockfileFeature::start() {
  // build lockfile name
  auto database = application_features::ApplicationServer::getFeature<DatabasePathFeature>("DatabasePath");
  _lockFilename = database->subdirectoryName("LOCK");

  TRI_ASSERT(!_lockFilename.empty());

  int res = TRI_VerifyLockFile(_lockFilename.c_str());

  if (res != TRI_ERROR_NO_ERROR) {
    std::string otherPID;
    try {
      otherPID = FileUtils::slurp(_lockFilename.c_str());
    } catch (...) {}
    if (otherPID.empty()) {
      LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "failed to read/write lockfile, please check the file permissions of the lockfile '" << _lockFilename << "'";
    } else {
      LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "database is locked by process " <<
        otherPID << "; please stop it first and check that the lockfile '" << _lockFilename << "' goes away. If you are sure no other arangod process is running, please remove the lockfile '" << _lockFilename << "' and try again";
    }
    FATAL_ERROR_EXIT();
  }

  if (TRI_ExistsFile(_lockFilename.c_str())) {
    res = TRI_UnlinkFile(_lockFilename.c_str());

    if (res != TRI_ERROR_NO_ERROR) {
      LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "failed to remove an abandoned lockfile in the database directory, please check the file permissions of the lockfile '"
        << _lockFilename << "': " << TRI_errno_string(res);
      FATAL_ERROR_EXIT();
    }
  }
  res = TRI_CreateLockFile(_lockFilename.c_str());

  if (res != TRI_ERROR_NO_ERROR) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
      << "failed to lock the database directory using '"
      << _lockFilename << "': " << TRI_errno_string(res);
    FATAL_ERROR_EXIT();
  }
}

void LockfileFeature::unprepare() {
  TRI_DestroyLockFile(_lockFilename.c_str());
}


text:
MongoDB for Developers

MongoDB university course


text:
/*
	Pokemon Showdown Bot, for NodeJS

	By: Ecuacion
*/

try {
	require('sugar');

	global.colors = require('colors');
	global.sys = require('sys');
	global.fs = require('fs');
	global.path = require('path');
	global.PSClient = require('node-ps-client');
} catch (e) {
	console.log(e.stack);
	console.log("ERROR: missing dependencies, try 'npm install'");
	process.exit(-1);
}

console.log((
	'-----------------------------------------------\n' +
	'   Welcome to Pokemon Showdown Bot for Node!   \n' +
	'-----------------------------------------------\n'
).yellow);

global.Tools = require('./tools.js');

if (!fs.existsSync('./config.js')) {
	console.log("config.js does not exist - creating one with default settings...");
	fs.writeFileSync('./config.js', fs.readFileSync('./config-example.js'));
}

global.Config = require('./config.js');
Tools.checkConfig();

global.reloadConfig = function () {
	Tools.uncacheTree('./config.js');
	global.Config = require('./config.js');
	Tools.checkConfig();
	CommandParser.reloadTokens();
};

info('Loading globals');

/* Globals */

global.Formats = {};

global.Settings = require('./settings.js');

global.DataDownloader = require('./data-downloader.js');

global.CommandParser = require('./command-parser.js');

/* Commands */

CommandParser.loadCommands();

/* Languages (translations) */

Tools.loadTranslations();

/* Features */

global.Features = {};

var featureList = fs.readdirSync('./features/');

featureList.forEach(function (feature) {
	if (fs.existsSync('./features/' + feature + '/index.js')) {
		try {
			var f = require('./features/' + feature + '/index.js');
			if (f.id) {
				Features[f.id] = f;
				ok("New feature: " + f.id + ' | ' + f.desc);
			} else {
				error("Failed to load feature: " + './features/' + feature);
			}
		} catch (e) {
			errlog(e.stack);
			error("Failed to load feature: " + './features/' + feature);
		}
	}
});

global.reloadFeatures = function () {
	var featureList = fs.readdirSync('./features/');
	var errs = [];
	featureList.forEach(function (feature) {
		if (fs.existsSync('./features/' + feature + '/index.js')) {
			try {
				Tools.uncacheTree('./features/' + feature + '/index.js');
				var f = require('./features/' + feature + '/index.js');
				if (f.id) {
					if (Features[f.id] && typeof Features[f.id].destroy === "function") Features[f.id].destroy();
					Features[f.id] = f;
					Features[f.id].init();
				}
			} catch (e) {
				errlog(e.stack);
				errs.push(feature);
			}
		}
	});
	info('Features reloaded' + (errs.length ? ('. Errors: ' + errs.join(', ')) : ''));
	return errs;
};

/* Bot creation and connection */

function botAfterConnect () {
	//join rooms
	if (typeof Config.rooms === "string") {
		joinByQueryRequest(Config.rooms);
	} else {
		var cmds = [];
		for (var i = 0; i < Config.rooms.length; i++) {
			cmds.push('|/join ' + Config.rooms[i]);
		}
		for (var i = 0; i < Config.initCmds.length; i++) {
			cmds.push(Config.initCmds[i]);
		}
		Bot.send(cmds, 2000);
	}
	if (!Config.disableDownload) {
		DataDownloader.download();
	}
}

function joinByQueryRequest(target) {
	if (target === 'official' || target === 'public' || target === 'all') {
		info('Joining ' + target + ' rooms');
	} else {
		error('Config.rooms, as a string must be "official", "public" or "all"');
		var cmds = [];
		for (var i = 0; i < Config.initCmds.length; i++) {
			cmds.push(Config.initCmds[i]);
		}
		Bot.send(cmds, 2000);
		return;
	}
	Bot.on('queryresponse', function (data) {
		data = data.split('|');
		if (data[0] === 'rooms') {
			data.splice(0, 1);
			var str = data.join('|');
			var cmds = [];
			try {
				var rooms = JSON.parse(str);
				var offRooms = [], publicRooms = [];
				if (rooms.official) {
					for (var i = 0; i < rooms.official.length; i++) {
						if (rooms.official[i].title) offRooms.push(toId(rooms.official[i].title));
					}
				}
				if (rooms.chat) {
					for (var i = 0; i < rooms.chat.length; i++) {
						if (rooms.chat[i].title) publicRooms.push(toId(rooms.chat[i].title));
					}
				}
				if (target === 'all' || target === 'official') {
					for (var i = 0; i < offRooms.length; i++) cmds.push('|/join ' + offRooms[i]);
				}
				if (target === 'all' || target === 'public') {
					for (var i = 0; i < publicRooms.length; i++) cmds.push('|/join ' + publicRooms[i]);
				}
			} catch (e) {}
			for (var i = 0; i < Config.initCmds.length; i++) {
				cmds.push(Config.initCmds[i]);
			}
			Bot.send(cmds, 2000);
			Bot.on('queryresponse', function () {return;});
		}
	});
	Bot.send('|/cmd rooms');
}

var opts = {
	serverid: Config.serverid,
	secprotocols: [],
	connectionTimeout: Config.connectionTimeout,
	loginServer: 'https://play.pokemonshowdown.com/~~' + Config.serverid + '/action.php',
	nickName: null,
	pass: null,
	retryLogin: false,
	autoConnect: false,
	autoReconnect: false,
	autoReconnectDelay: 0,
	autoJoin: [],
	showErrors: (Config.debug ? Config.debug.debug : true),
	debug: (Config.debug ? Config.debug.debug : true)
};

global.Bot = new PSClient(Config.server, Config.port, opts);

var connected = false;
Bot.on('connect', function (con) {
	ok('Connected to server ' + Config.serverid + ' (' + Tools.getDateString() + ')');
	connected = true;
	for (var f in Features) {
		try {
			Features[f].init();
		} catch (e) {
			errlog(e.stack);
			error("Feature Crash: " + f + " | " + sys.inspect(e));
		}
	}
});

Bot.on('formats', function (formats) {
	global.Formats = {};
	var formatsArr = formats.split('|');
	var commaIndex, arg, formatData, code, name;
	for (var i = 0; i < formatsArr.length; i++) {
		commaIndex = formatsArr[i].indexOf(',');
		if (commaIndex === -1) {
			Formats[toId(formatsArr[i])] = {name: formatsArr[i], team: true, ladder: true, chall: true};
		} else if (commaIndex === 0) {
			i++;
			continue;
		} else {
			name = formatsArr[i];
			formatData = {name: name, team: true, ladder: true, chall: true};
			code = commaIndex >= 0 ? parseInt(name.substr(commaIndex + 1), 16) : NaN;
			if (!isNaN(code)) {
				name = name.substr(0, commaIndex);
				if (code & 1) formatData.team = false;
				if (!(code & 2)) formatData.ladder = false;
				if (!(code & 4)) formatData.chall = false;
				if (!(code & 8)) formatData.disableTournaments = true;
			} else {
				if (name.substr(name.length - 2) === ',#') { // preset teams
					formatData.team = false;
					name = name.substr(0, name.length - 2);
				}
				if (name.substr(name.length - 2) === ',,') { // search-only
					formatData.chall = false;
					name = name.substr(0, name.length - 2);
				} else if (name.substr(name.length - 1) === ',') { // challenge-only
					formatData.ladder = false;
					name = name.substr(0, name.length - 1);
				}
			}
			formatData.name = name;
			Formats[toId(name)] = formatData;
		}
	}
	ok('Received battle formats. Total: ' + formatsArr.length);
});

Bot.on('challstr', function (challstr) {
	info('Received challstr, logging in...');
	if (!Config.nick) {
		Bot.rename('Bot ' + Tools.generateRandomNick(10));
	} else {
		Bot.rename(Config.nick, Config.pass);
	}
});

var retryingRename = false;
Bot.on('renamefailure', function (e) {
	if (e === -1)  {
		if (!Config.nick) {
			debug('Login failure - generating another random nickname');
			Bot.rename('Bot ' + Tools.generateRandomNick(10));
		} else {
			error('Login failure - name registered, invalid or no password given');
			if (!Bot.status.named) {
				info("Invalid nick + pass, using a random nickname");
				Config.nick = '';
				Bot.rename('Bot ' + Tools.generateRandomNick(10));
			}
		}
	} else {
		if (Config.autoReloginDelay) {
			error('Login failure, retrying in ' + (Config.autoReloginDelay / 1000) + ' seconds');
			retryingRename = true;
			setTimeout(function () {
				retryingRename = false;
				if (!Config.nick) {
					Bot.rename('Bot ' + Tools.generateRandomNick(10));
				} else {
					Bot.rename(Config.nick, Config.pass);
				}
			}, Config.autoReloginDelay);
		} else {
			error('Login failure');
		}
	}
});

Bot.on('rename', function (name, named) {
	monitor('Bot nickname has changed: ' + (named ? name.green : name.yellow) + (named ? '' : ' [guest]'));
	if (named) {
		if (!Config.nick) {
			if (Bot.roomcount > 0) return; // Namechange, not initial login
			ok('Succesfully logged in as ' + name);
			botAfterConnect();
		} else if (toId(Config.nick) === toId(name)) {
			ok('Succesfully logged in as ' + name);
			botAfterConnect();
		}
	}
});

/* Reconnect timer */

var reconnectTimer = null;
var reconnecting = false;
Bot.on('disconnect', function (e) {
	connected = false;
	if (Config.autoReconnectDelay) {
		if (reconnecting) return;
		reconnecting = true;
		error('Disconnected from server, retrying in ' + (Config.autoReconnectDelay / 1000) + ' seconds');
		reconnectTimer = setTimeout(function () {
			reconnecting = false;
			info('Connecting to server ' + Config.server + ':' + Config.port);
			Bot.connect();
		}, Config.autoReconnectDelay);
	} else {
		error('Disconnected from server, exiting...');
		process.exit(0);
	}
});

/* Commands */

Bot.on('chat', function (room, timeOff, by, msg) {
	CommandParser.parse(room, by, msg);
	Settings.reportSeen(by, room, 'c', []);
});

Bot.on('pm', function (by, msg) {
	CommandParser.parse(',' + by, by, msg);
});

Bot.on('userjoin', function (room, by) {
	Settings.reportSeen(by, room, 'j', []);
});

Bot.on('userleave', function (room, by) {
	Settings.reportSeen(by, room, 'l', []);
});

Bot.on('userrename', function (room, old, by) {
	Settings.reportSeen(old, room, 'n', [by]);
});

/* Features */

Bot.on('line', function (room, message, isIntro, spl) {
	for (var f in Features) {
		try {
			Features[f].parse(room, message, isIntro, spl);
		} catch (e) {
			errlog(e.stack);
			error("Feature Crash: " + f + " | " + sys.inspect(e));
			Features[f].disabled = true;
			Features[f].parse = function () {
				return true;
			};
			info("Feature " + f + " has been disabled");
		}
	}
});

/* Info and debug */

Bot.on('joinroom', function (room, type) {
	if (type === 'chat') monitor('Joined room ' + room, 'room', 'join');
	else if (type === 'battle') monitor('Joined battle ' + room, 'battle', 'join');
	else monitor('Joined room ' + room + ' [' + Bot.rooms[room].type + ']', 'room', 'join');
});

Bot.on('joinfailure', function (room, e, moreInfo) {
	monitor('Could not join ' + room + ': [' + e + '] ' + moreInfo, 'room', 'error');
});

Bot.on('leaveroom', function (room) {
	var roomType = Bot.rooms[room] ? Bot.rooms[room].type : 'chat';
	if (roomType === 'chat') monitor('Left room ' + room, 'room', 'leave');
	else if (roomType === 'battle') monitor('Left battle ' + room, 'battle', 'leave');
	else monitor('Left room ' + room + ' [' + Bot.rooms[room].type + ']', 'room', 'leave');
});

Bot.on('message', function (msg) {
	recv(msg);
});

Bot.on('send', function (msg) {
	sent(msg);
});

ok('Bot object is ready');

/* Global Monitor */

var checkSystem = function () {
	var status = '';
	var issue = false;
	status += 'Connection: ';
	if (connected) {
		status += 'connected'.green;
		status += ' | Nickname: ';
		if (Bot.status.named) {
			status += Bot.status.nickName.green;
		} else if (retryingRename) {
			status += Bot.status.nickName.yellow;
		} else {
			status += Bot.status.nickName.red;
			issue = 'login';
		}
	} else if (reconnecting) {
		status += 'retrying'.yellow;
	} else {
		issue = 'connect';
		status += 'disconnected'.red;
	}
	monitor(status + ' (' + Tools.getDateString() + ')', 'status');
	if (issue) {
		switch (issue) {
			case 'connect':
				monitor("Monitor failed: Connection issue. Reconnecting");
				Bot.connect();
				break;
			case 'login':
				monitor("Monitor failed: Login issue. Loging in a random username");
				Config.nick = '';
				Bot.rename('Bot ' + Tools.generateRandomNick(10));
				break;
		}
	}
};
var sysChecker = setInterval(checkSystem, 60 * 60 * 1000);
ok('Global monitor is working');

//CrashGuard
if (Config.crashguard) {
	process.on('uncaughtException', function (err) {
		error(("" + err.message).red);
		errlog(("" + err.stack).red);
	});
	ok("Crashguard enabled");
}

//WatchConfig
if (Config.watchconfig) {
	Tools.watchFile('./config.js', function (curr, prev) {
		if (curr.mtime <= prev.mtime) return;
		try {
			reloadConfig();
			info('config.js reloaded');
		} catch (e) {
			error('could not reload config.js');
			errlog(e.stack);
		}
	});
	ok("Watchconfig enabled");
}

console.log("\n-----------------------------------------------\n".yellow);

//Connection
info('Connecting to server ' + Config.server + ':' + Config.port);
Bot.connect();
Bot.startConnectionTimeOut();


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Module: ActiveRecord::Acts::List::InstanceMethods</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />

          Module
          ActiveRecord::Acts::List::InstanceMethods

            In:

                vendor/rails/activerecord/lib/active_record/acts/list.rb

All the methods available to a record that has had <tt>acts_as_list</tt>
specified. Each method works by assuming the object to be the item in the
list, so <tt>chapter.move_lower</tt> would move that chapter lower in the
list of all chapters. Likewise, <tt>chapter.first?</tt> would return true
if that chapter is the first in the list of all chapters.

Methods

      decrement_position
      first?
      higher_item
      in_list?
      increment_position
      insert_at
      last?
      lower_item
      move_higher
      move_lower
      move_to_bottom
      move_to_top
      remove_from_list

Public Instance methods

          decrement_position()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 126
126:         def decrement_position
127:           return unless in_list?
128:           update_attribute position_column, self.send(position_column).to_i - 1
129:         end

          first?()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 131
131:         def first?
132:           return false unless in_list?
133:           self.send(position_column) == 1
134:         end

          higher_item()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 141
141:         def higher_item
142:           return nil unless in_list?
143:           acts_as_list_class.find(:first, :conditions =>
144:             "#{scope_condition} AND #{position_column} = #{(send(position_column).to_i - 1).to_s}"
145:           )
146:         end

          in_list?()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 155
155:         def in_list?
156:           !send(position_column).nil?
157:         end

          increment_position()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 121
121:         def increment_position
122:           return unless in_list?
123:           update_attribute position_column, self.send(position_column).to_i + 1
124:         end

          insert_at(position = 1)

[Source]

    # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 79
79:         def insert_at(position = 1)
80:           insert_at_position(position)
81:         end

          last?()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 136
136:         def last?
137:           return false unless in_list?
138:           self.send(position_column) == bottom_position_in_list
139:         end

          lower_item()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 148
148:         def lower_item
149:           return nil unless in_list?
150:           acts_as_list_class.find(:first, :conditions =>
151:             "#{scope_condition} AND #{position_column} = #{(send(position_column).to_i + 1).to_s}"
152:           )
153:         end

          move_higher()

[Source]

    # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 92
92:         def move_higher
93:           return unless higher_item
94:
95:           acts_as_list_class.transaction do
96:             higher_item.increment_position
97:             decrement_position
98:           end
99:         end

          move_lower()

[Source]

    # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 83
83:         def move_lower
84:           return unless lower_item
85:
86:           acts_as_list_class.transaction do
87:             lower_item.decrement_position
88:             increment_position
89:           end
90:         end

          move_to_bottom()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 101
101:         def move_to_bottom
102:           return unless in_list?
103:           acts_as_list_class.transaction do
104:             decrement_positions_on_lower_items
105:             assume_bottom_position
106:           end
107:         end

          move_to_top()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 109
109:         def move_to_top
110:           return unless in_list?
111:           acts_as_list_class.transaction do
112:             increment_positions_on_higher_items
113:             assume_top_position
114:           end
115:         end

          remove_from_list()

[Source]

     # File vendor/rails/activerecord/lib/active_record/acts/list.rb, line 117
117:         def remove_from_list
118:           decrement_positions_on_lower_items if in_list?
119:         end

[Validate]


text:
Imports System.Data.Entity.Migrations

Namespace Migrations
    Public Partial Class Initial
        Inherits DbMigration

        Public Overrides Sub Up()
            CreateTable(
                "dbo.AspNetRoles",
                Function(c) New With
                    {
                        .Id = c.String(nullable := False, maxLength := 128),
                        .Name = c.String(nullable := False)
                    }) _
                .PrimaryKey(Function(t) t.Id)

            CreateTable(
                "dbo.AspNetUsers",
                Function(c) New With
                    {
                        .Id = c.String(nullable := False, maxLength := 128),
                        .UserName = c.String(),
                        .PasswordHash = c.String(),
                        .SecurityStamp = c.String(),
                        .Discriminator = c.String(nullable := False, maxLength := 128)
                    }) _
                .PrimaryKey(Function(t) t.Id)

            CreateTable(
                "dbo.AspNetUserClaims",
                Function(c) New With
                    {
                        .Id = c.Int(nullable := False, identity := True),
                        .ClaimType = c.String(),
                        .ClaimValue = c.String(),
                        .User_Id = c.String(nullable := False, maxLength := 128)
                    }) _
                .PrimaryKey(Function(t) t.Id) _
                .ForeignKey("dbo.AspNetUsers", Function(t) t.User_Id, cascadeDelete := True) _
                .Index(Function(t) t.User_Id)

            CreateTable(
                "dbo.AspNetUserLogins",
                Function(c) New With
                    {
                        .UserId = c.String(nullable := False, maxLength := 128),
                        .LoginProvider = c.String(nullable := False, maxLength := 128),
                        .ProviderKey = c.String(nullable := False, maxLength := 128)
                    }) _
                .PrimaryKey(Function(t) New With { t.UserId, t.LoginProvider, t.ProviderKey }) _
                .ForeignKey("dbo.AspNetUsers", Function(t) t.UserId, cascadeDelete := True) _
                .Index(Function(t) t.UserId)

            CreateTable(
                "dbo.AspNetUserRoles",
                Function(c) New With
                    {
                        .UserId = c.String(nullable := False, maxLength := 128),
                        .RoleId = c.String(nullable := False, maxLength := 128)
                    }) _
                .PrimaryKey(Function(t) New With { t.UserId, t.RoleId }) _
                .ForeignKey("dbo.AspNetRoles", Function(t) t.RoleId, cascadeDelete := True) _
                .ForeignKey("dbo.AspNetUsers", Function(t) t.UserId, cascadeDelete := True) _
                .Index(Function(t) t.RoleId) _
                .Index(Function(t) t.UserId)

        End Sub

        Public Overrides Sub Down()
            DropForeignKey("dbo.AspNetUserClaims", "User_Id", "dbo.AspNetUsers")
            DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers")
            DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles")
            DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers")
            DropIndex("dbo.AspNetUserClaims", New String() { "User_Id" })
            DropIndex("dbo.AspNetUserRoles", New String() { "UserId" })
            DropIndex("dbo.AspNetUserRoles", New String() { "RoleId" })
            DropIndex("dbo.AspNetUserLogins", New String() { "UserId" })
            DropTable("dbo.AspNetUserRoles")
            DropTable("dbo.AspNetUserLogins")
            DropTable("dbo.AspNetUserClaims")
            DropTable("dbo.AspNetUsers")
            DropTable("dbo.AspNetRoles")
        End Sub
    End Class
End Namespace


text:
function store($http, baseApiUrl) {
    const baseUrl = `${baseApiUrl}/allocation`;

    const findByEntity = (ref) => $http
            .get(`${baseUrl}/entity-ref/${ref.kind}/${ref.id}`)
            .then(d => d.data);

    const findByEntityAndScheme = (ref, schemeId) => $http
            .get(`${baseUrl}/entity-ref/${ref.kind}/${ref.id}/${schemeId}`)
            .then(d => d.data);

    const findByMeasurableAndScheme = (measurableId, schemeId) => $http
            .get(`${baseUrl}/measurable/${measurableId}/${schemeId}`)
            .then(d => d.data);

    const updateAllocations = (ref, schemeId, updatedAllocations = []) => $http
        .post(`${baseUrl}/entity-ref/${ref.kind}/${ref.id}/${schemeId}/allocations`, updatedAllocations)
        .then(d => d.data);

    return {
        findByEntity,
        findByEntityAndScheme,
        findByMeasurableAndScheme,
        updateAllocations
    };
}

store.$inject = [
    "$http",
    "BaseApiUrl"
];

const serviceName = "AllocationStore";

export default {
    serviceName,
    store
};

export const AllocationStore_API = {
    findByEntity: {
        serviceName,
        serviceFnName: "findByEntity",
        description: "findByEntity [ref]"
    },
    findByEntityAndScheme: {
        serviceName,
        serviceFnName: "findByEntityAndScheme",
        description: "findByEntityAndScheme [ref, schemeId]"
    },
    findByMeasurableAndScheme: {
        serviceName,
        serviceFnName: "findByMeasurableAndScheme",
        description: "findByMeasurableAndScheme [measurableId, schemeId]"
    },
    updateAllocations: {
        serviceName,
        serviceFnName: "updateAllocations",
        description: "updateAllocations [ref, schemeId, measurableId, updatedAllocations[{measurableId, percentage, operation}]]"
    }
};