text:
package com.thoughtworks.go.util;

import com.thoughtworks.go.utils.Timeout;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.Serializable;
import java.util.Properties;

public class SystemEnvironment implements Serializable, ConfigDirProvider {

    private static final Logger LOG = Logger.getLogger(SystemEnvironment.class);

    public static final String CRUISE_LISTEN_HOST = "cruise.listen.host";
    private static final String CRUISE_DATABASE_PORT = "cruise.database.port";
    public static final String CRUISE_SERVER_PORT = "cruise.server.port";
    public static final String CRUISE_SERVER_SSL_PORT = "cruise.server.ssl.port";
    public static final String AGENT_JAR_PATH = "agent.jar";
    public static final String AGENT_LAUNCHER_JAR_PATH = "agent-launcher.jar";
    static final String AGENT_CONNECTION_TIMEOUT_IN_SECONDS = "agent.connection.timeout";
    private static final String JETTY_XML = "jetty.xml";
    public static final String CRUISE_SERVER_WAR_PROPERTY = "cruise.server.war";

    public static final String CRUISE_CONFIG_REPO_DIR = "cruise.config.repo.dir";
    private static final String DB_BASE_DIR = "db/";
    private static final String DB_DEFAULT_PATH = DB_BASE_DIR + "h2db";
    private static final String CONFIG_REPO_DEFAULT_PATH = DB_BASE_DIR + "config.git";
    public static final String CRUISE_DB_CACHE_SIZE = "cruise.db.cache.size";
    public static final String CRUISE_DB_CACHE_SIZE_DEFAULT = String.valueOf(128 * 1024); // 128MB Cache Size by default
    public static final String ACTIVEMQ_USE_JMX = "activemq.use.jmx";
    public static final String ACTIVEMQ_QUEUE_PREFETCH = "activemq.queue.prefetch";
    private static final String ACTIVEMQ_CONNECTOR_PORT = "activemq.conn.port";
    public static final int NUMBER_OF_DAYS_TO_EXPIRY = 30;

    public static final String NUMBER_OF_DAYS_TO_EXPIRY_PROPERTY = "number.of.days.to.expiry";
    public static final String PARENT_LOADER_PRIORITY = "parent.loader.priority";
    public static final String AGENT_CONTENT_MD5_HEADER = "Agent-Content-MD5";

    public static final String AGENT_LAUNCHER_CONTENT_MD5_HEADER = "Agent-Launcher-Content-MD5";

    public static final String AGENT_PLUGINS_ZIP_MD5_HEADER = "Agent-Plugins-Content-MD5";

    public static final String EMPTY_STRING = "";
    public static final String BLANK_STRING = EMPTY_STRING;
    public static final String ENFORCE_SERVERID_MUTABILITY = "go.enforce.serverId.immutability";

    public static final String CONFIGURATION_YES = "Y";

    public static final String CONFIGURATION_NO = "N";
    public static final String RESOLVE_FANIN_REVISIONS = "resolve.fanin.revisions";
    public static final String RESOLVE_FANIN_FALLBACK_TRIANGLE = "resolve.fanin.fallback.triangle";
    private String hsqlPath = null;

    public static final String ENABLE_CONFIG_MERGE_PROPERTY = "enable.config.merge";
    public static final GoSystemProperty<Boolean> ENABLE_CONFIG_MERGE_FEATURE = new CachedProperty<Boolean>(new GoBooleanSystemProperty(ENABLE_CONFIG_MERGE_PROPERTY, Boolean.TRUE));

    private String defaultDbPort = "9153";
    private static final String DB_UPGRADE_H2_DELTAS_FOLDER = "h2deltas";
    private boolean debug;

    public static final String CRUISE_PROPERTIES = "/cruise.properties";
    private Properties properties;
    public static final String CRUISE_EXPERIMENTAL_ENABLE_ALL = "cruise.experimental.enable-all";

    public static final String ARTIFACT_FULL_SIZE_LIMIT = "artifact.full.size.limit";
    public static final String DATABASE_FULL_SIZE_LIMIT = "db.full.size.limit";
    public static final String ARTIFACT_WARNING_SIZE_LIMIT = "artifact.warning.size.limit";
    public static final String DATABASE_WARNING_SIZE_LIMIT = "db.warning.size.limit";
    public static final String AGENT_SIZE_LIMIT = "agent.size.limit";
    private static final String DISK_SPACE_CACHE_REFRESHER_INTERVAL = "disk.space.cache.refresher.interval";
    private static final String COMMAND_REPOSITORY_WARNING_TIMEOUT = "command.repo.warning.timeout";
    public static final String AGENT_SOCKET_TYPE_NIO = "nio";

    private static final String AGENT_SOCKET_TYPE_PROPERTY = "agent.socket.type";

    public static final String CONFIG_FILE_PROPERTY = "cruise.config.file";
    public static final String INTERVAL = "cruise.console.publish.interval";
    private static final String SERVICE_URL = "serviceUrl";
    public static final String CONFIG_DIR_PROPERTY = "cruise.config.dir";
    public static final String CONFIG_CIPHER = "cipher";
    public static final String HOSTNAME_SHINE_USES = "localhost";
    public static final String SHINE_XSL_TRANSFORMER_REGISTRY_CACHE_SIZE = "shine.xsl.transformer.registry.cache.size";
    private static final String DEFAULT_SHINE_XSL_TRANSFORMER_REGISTRY_CACHE_SIZE = "20";
    public static final int TFS_SOCKET_TIMEOUT_IN_MILLISECONDS = 20 * 60 * 1000;
    public static final String TFS_SOCKET_TIMEOUT_PROPERTY = "tfs.socket.block.timeout";

    public static GoSystemProperty<Integer> RESOLVE_FANIN_MAX_BACK_TRACK_LIMIT = new CachedProperty<Integer>(new GoIntSystemProperty("resolve.fanin.max.backtrack.limit", 100));
    public static GoSystemProperty<Integer> MATERIAL_UPDATE_INACTIVE_TIMEOUT = new CachedProperty<Integer>(new GoIntSystemProperty("material.update.inactive.timeout", 15));

    public static GoSystemProperty<Integer> H2_DB_TRACE_LEVEL = new GoIntSystemProperty("h2.trace.level", 1);
    public static GoSystemProperty<Integer> H2_DB_TRACE_FILE_SIZE_MB = new GoIntSystemProperty("h2.trace.file.size.mb", 16);
    private static GoSystemProperty<String> CRUISE_DATABASE_DIR = new GoStringSystemProperty("cruise.database.dir", DB_DEFAULT_PATH);

    public static final String MATERIAL_UPDATE_IDLE_INTERVAL_PROPERTY = "material.update.idle.interval";
    private static GoSystemProperty<Long> MATERIAL_UPDATE_IDLE_INTERVAL = new GoLongSystemProperty(MATERIAL_UPDATE_IDLE_INTERVAL_PROPERTY, 60000L);

    public static GoSystemProperty<Integer> PLUGIN_LOCATION_MONITOR_INTERVAL_IN_SECONDS = new GoIntSystemProperty("pluginLocationMonitor.sleepTimeInSecs", -1);
    public static final String PLUGINS_PATH = "plugins";
    public static GoSystemProperty<String> PLUGIN_GO_PROVIDED_PATH = new GoStringSystemProperty("plugins.go.provided.path", PLUGINS_PATH + System.getProperty("file.separator") + "bundled");
    public static GoSystemProperty<String> PLUGIN_EXTERNAL_PROVIDED_PATH = new GoStringSystemProperty("plugins.external.provided.path", PLUGINS_PATH + System.getProperty("file.separator") + "external");
    public static GoSystemProperty<String> PLUGIN_BUNDLE_PATH = new CachedProperty<String>(new GoStringSystemProperty("plugins.work.path", "plugins_work"));
    public static GoSystemProperty<String> PLUGIN_ACTIVATOR_JAR_PATH = new CachedProperty<String>(new GoStringSystemProperty("plugins.activator.jar.path", "lib/go-plugin-activator.jar"));
    public static GoSystemProperty<Boolean> PLUGIN_FRAMEWORK_ENABLED = new GoBooleanSystemProperty("plugins.framework.enabled", Boolean.TRUE);
    public static GoSystemProperty<String> ALL_PLUGINS_ZIP_PATH = new GoStringSystemProperty("plugins.all.zip.path", new File(PLUGINS_PATH, "go-plugins-all.zip").getAbsolutePath());
    public static GoSystemProperty<String> ADDONS_PATH = new GoStringSystemProperty("addons.path", "addons");
    public static GoSystemProperty<String> AVAILABLE_FEATURE_TOGGLES_FILE_PATH = new GoStringSystemProperty("available.toggles.path", "/available.toggles");
    public static GoSystemProperty<String> USER_FEATURE_TOGGLES_FILE_PATH_RELATIVE_TO_CONFIG_DIR = new GoStringSystemProperty("user.toggles.path", "go.feature.toggles");

    public static GoSystemProperty<String> DEFAULT_COMMAND_SNIPPETS_ZIP = new CachedProperty<String>(
            new GoStringSystemProperty("default.command.snippets.zip.location", "/defaultFiles/defaultCommandSnippets.zip"));
    public static GoSystemProperty<String> DEFAULT_PLUGINS_ZIP = new CachedProperty<String>(
            new GoStringSystemProperty("default.plugins.zip.location", "/defaultFiles/plugins.zip"));
    public static final GoSystemProperty<String> AGENT_PLUGINS_PATH = new CachedProperty<String>(new GoStringSystemProperty("agent.plugins.path", PLUGINS_PATH));
    public static GoSystemProperty<String> VERSION_FILE_IN_DEFAULT_COMMAND_REPOSITORY = new CachedProperty<String>(new GoStringSystemProperty("version.file.in.command.repository", "version.txt"));
    public static GoSystemProperty<Integer> COMMAND_REPOSITORY_CACHE_TIME_IN_SECONDS = new CachedProperty<Integer>(new GoIntSystemProperty("command.repo.cache.timeout.in.secs", 30 * 60));
    public static GoSystemProperty<String> COMMAND_REPOSITORY_DIRECTORY = new CachedProperty<String>(new GoStringSystemProperty("command.repo.dir", DB_BASE_DIR + "command_repository"));
    public static GoSystemProperty<Boolean> CAPTURE_METRICS = new GoBooleanSystemProperty("capture.metrics", true);
    public static GoSystemProperty<Integer> IDLE_TIMEOUT = new GoIntSystemProperty("idle.timeout", 30000);
    public static GoSystemProperty<Integer> RESPONSE_BUFFER_SIZE = new GoIntSystemProperty("response.buffer.size", 32768);
    public static final GoSystemProperty<Integer> API_REQUEST_IDLE_TIMEOUT_IN_SECONDS = new GoIntSystemProperty("api.request.idle.timeout.seconds", 300);

    public static GoSystemProperty<Integer> PLUGIN_NOTIFICATION_LISTENER_COUNT = new CachedProperty<Integer>(new GoIntSystemProperty("plugin.notification.listener.count", 1));

    /* DATABASE CONFIGURATION - Defaults are of H2 */
    public static GoSystemProperty<String> GO_DATABASE_HOST = new GoStringSystemProperty("db.host", "localhost");
    public static GoSystemProperty<String> GO_DATABASE_PORT = new GoStringSystemProperty("db.port", "");
    public static GoSystemProperty<String> GO_DATABASE_NAME = new GoStringSystemProperty("db.name", "cruise");
    public static GoSystemProperty<String> GO_DATABASE_USER = new GoStringSystemProperty("db.user", "sa");
    public static GoSystemProperty<String> GO_DATABASE_PASSWORD = new GoStringSystemProperty("db.password", "");
    public static GoIntSystemProperty GO_DATABASE_MAX_ACTIVE = new GoIntSystemProperty("db.maxActive", 32);
    public static GoIntSystemProperty GO_DATABASE_MAX_IDLE = new GoIntSystemProperty("db.maxIdle", 32);
    public static final String H2_DATABASE = "com.thoughtworks.go.server.database.H2Database";
    public static GoStringSystemProperty GO_DATABASE_PROVIDER = new GoStringSystemProperty("go.database.provider", H2_DATABASE);
    public static GoSystemProperty<Boolean> SHOULD_VALIDATE_XML_AGAINST_DTD = new GoBooleanSystemProperty("validate.xml.against.dtd", false);
    public static GoSystemProperty<String> JETTY_XML_FILE_NAME = new GoStringSystemProperty("jetty.xml.file.name", JETTY_XML);

    public static final String JETTY6 = "com.thoughtworks.go.server.Jetty6Server";
    public static final String JETTY9 = "com.thoughtworks.go.server.Jetty9Server";
    public static GoSystemProperty<String> APP_SERVER = new CachedProperty<String>(new GoStringSystemProperty("app.server", JETTY9));
    public static GoSystemProperty<String> GO_SERVER_STATE = new GoStringSystemProperty("go.server.state", "active");
    public static GoSystemProperty<String> GO_LANDING_PAGE = new GoStringSystemProperty("go.landing.page", "/pipelines");

    public static GoSystemProperty<Boolean> FETCH_ARTIFACT_AUTO_SUGGEST = new GoBooleanSystemProperty("go.fetch-artifact.auto-suggest", true);

    private volatile static Integer agentConnectionTimeout;
    private volatile static Integer cruiseSSlPort;
    private volatile static String cruiseConfigDir;
    private volatile static Long databaseFullSizeLimit;
    private volatile static Long artifactFullSizeLimit;
    private volatile static Long diskSpaceCacheRefresherInterval;
    public static final String UNRESPONSIVE_JOB_WARNING_THRESHOLD = "cruise.unresponsive.job.warning";
    private File configDir;
    private volatile Boolean enforceRevisionCompatibilityWithUpstream;
    private volatile Boolean enforceFanInFallbackTriangle;

    public SystemEnvironment() {
    }

    public SystemEnvironment(Properties properties) {
        this.properties = properties;
    }

    public SystemEnvironment(String hsqlPath, String defaultDbPort) {
        if (defaultDbPort == null) {
            throw ExceptionUtils.bomb("Default db port cannot be null");
        }
        this.hsqlPath = hsqlPath;
        this.defaultDbPort = defaultDbPort;
        debug = getPropertyImpl("DB_DEBUG_MODE") != null
                && !(getPropertyImpl("DB_DEBUG_MODE").equals("false"));

    }

    public <T> T get(GoSystemProperty<T> systemProperty) {
        return systemProperty.getValue();
    }

    public <T> void set(GoSystemProperty<T> systemProperty, T value) {
        System.setProperty(systemProperty.propertyName, "" + value);
        if (systemProperty instanceof CachedProperty) {
            ((CachedProperty) systemProperty).clear();
        }
    }

    public void set(GoSystemProperty<Boolean> systemProperty, boolean value) {
        System.setProperty(systemProperty.propertyName, value ? "Y" : "N");
        if (systemProperty instanceof CachedProperty) {
            ((CachedProperty) systemProperty).clear();
        }
    }

    public File configDir() {
        if (configDir == null) {
            configDir = new File(getPropertyImpl(CONFIG_FILE_PROPERTY, "config/cruise-config.xml")).getParentFile();
        }
        return configDir;
    }

    public File keystore() {
        return new File(configDir(), "keystore");
    }

    public File truststore() {
        return new File(configDir(), "truststore");
    }

    public File agentkeystore() {
        return new File(configDir(), "agentkeystore");
    }

    public int getServerPort() {
        return Integer.parseInt(getPropertyImpl(CRUISE_SERVER_PORT, "8153"));
    }

    public String getListenHost() {
        return getPropertyImpl(CRUISE_LISTEN_HOST);
    }

    public long getArtifactReposiotryFullLimit() {
        if (artifactFullSizeLimit != null) {
            return artifactFullSizeLimit;
        }
        return artifactFullSizeLimit = Long.parseLong(trimMegaFromSize(getPropertyImpl(ARTIFACT_FULL_SIZE_LIMIT, "100M")));
    }

    public long getDatabaseDiskSpaceFullLimit() {
        if (databaseFullSizeLimit != null) {
            return databaseFullSizeLimit;
        }
        return databaseFullSizeLimit = Long.parseLong(trimMegaFromSize(getPropertyImpl(DATABASE_FULL_SIZE_LIMIT, "100M")));
    }

    public long getDiskSpaceCacheRefresherInterval() {
        if (diskSpaceCacheRefresherInterval != null) {
            return diskSpaceCacheRefresherInterval;
        }
        return diskSpaceCacheRefresherInterval = Long.parseLong(getPropertyImpl(DISK_SPACE_CACHE_REFRESHER_INTERVAL, "5000"));
    }

    //Used in Tests
    public void setDiskSpaceCacheRefresherInterval(long interval) {
        diskSpaceCacheRefresherInterval = interval;
    }

    public long getAgentSizeLimit() {
        return Long.parseLong(trimMegaFromSize(getPropertyImpl(AGENT_SIZE_LIMIT, "100M"))) * 1024 * 1024;
    }

    public long getArtifactReposiotryWarningLimit() {
        return Long.parseLong(trimMegaFromSize(getPropertyImpl(ARTIFACT_WARNING_SIZE_LIMIT, "1024M")));
    }

    public long getDatabaseDiskSpaceWarningLimit() {
        return Long.parseLong(trimMegaFromSize(getPropertyImpl(DATABASE_WARNING_SIZE_LIMIT, "1024M")));
    }

    private String trimMegaFromSize(String sizeInMega) {
        return StringUtils.removeEndIgnoreCase(sizeInMega, "M");
    }

    public int getSslServerPort() {
        if (cruiseSSlPort != null) {
            return cruiseSSlPort;
        }
        return cruiseSSlPort = Integer.parseInt(getPropertyImpl(CRUISE_SERVER_SSL_PORT, "8154"));
    }

    public String getConfigDir() {
        if (cruiseConfigDir != null) {
            return cruiseConfigDir;
        }
        return cruiseConfigDir = getPropertyImpl(CONFIG_DIR_PROPERTY, "config");
    }

    public File getJettyConfigFile() {
        return new File(getConfigDir(), get(JETTY_XML_FILE_NAME));
    }

    /**
     * @deprecated use new SystemEnvironment().getXXXXX() instead.
     */
    public static String getProperty(String property, String defaultValue) {
        return new SystemEnvironment().getPropertyImpl(property, defaultValue);
    }

    /**
     * @deprecated use new SystemEnvironment().getXXXXX() instead.
     */
    public static String getProperty(String property) {
        return new SystemEnvironment().getPropertyImpl(property);
    }

    private String getPropertyImpl(String property, String defaultValue) {
        return System.getProperty(property, defaultValue);
    }

    public String getPropertyImpl(String property) {
        return System.getProperty(property);
    }

    public OperatingSystem getCurrentOperatingSystem() {
        return OperatingSystem.fromProperty();
    }

    public String getOperatingSystemName() {
        return getPropertyImpl("os.name");
    }

    public int getDatabaseSeverPort() {
        String port = getDatabasePort();
        try {
            return Integer.parseInt(port);
        } catch (NumberFormatException e) {
            LOG.info("Could not parse port=" + port);
        }
        return Integer.parseInt(defaultDbPort);
    }

    private String getDatabasePort() {
        String port = getPropertyImpl(CRUISE_DATABASE_PORT);
        if (port == null) {
            port = defaultDbPort;
        }
        return port;
    }

    public boolean getEnableRequestTimeLogging() {
        return Boolean.parseBoolean(getPropertyImpl("cruise.request.time.logging", "false"));
    }

    public int getActivemqQueuePrefetch() {
        return Integer.parseInt(getPropertyImpl(ACTIVEMQ_QUEUE_PREFETCH, "0"));
    }

    public long getCommandRepoWarningTimeout() {
        return Long.parseLong(getPropertyImpl(COMMAND_REPOSITORY_WARNING_TIMEOUT, String.valueOf(Timeout.ONE_HOUR.inMillis())));
    }

    public boolean getActivemqUseJmx() {
        return Boolean.parseBoolean(getPropertyImpl(ACTIVEMQ_USE_JMX, "false"));
    }

    public int getActivemqConnectorPort() {
        return Integer.parseInt(getPropertyImpl(ACTIVEMQ_CONNECTOR_PORT, "1099"));
    }

    public String getScriptPath() {
        return new File(getDbPath(), "cruise").getAbsolutePath();
    }

    public File getDBDeltasPath() {
        return new File(getDbFolder(), DB_UPGRADE_H2_DELTAS_FOLDER);
    }

    public File getDbPath() {
        if (hsqlPath == null) {
            hsqlPath = get(CRUISE_DATABASE_DIR);
        }
        return new File(hsqlPath);
    }

    public File getConfigRepoDir() {
        return new File(properties().getProperty(CRUISE_CONFIG_REPO_DIR, CONFIG_REPO_DEFAULT_PATH));
    }

    public File getCipherFile() {
        return new File(getConfigDir(), CONFIG_CIPHER);
    }

    public File getDbFolder() {
        return getDbPath().getParentFile();
    }

    public int getNumberOfMaterialCheckListener() {
        return Integer.parseInt(getPropertyImpl("material.check.threads", "10"));
    }

    public int getNumberOfPluginNotificationListener() {
        return PLUGIN_NOTIFICATION_LISTENER_COUNT.getValue();
    }

    public File getAgentJarFile() {
        return new File(AGENT_JAR_PATH);
    }

    public String getAgentMd5() {
        return getPropertyImpl(GoConstants.AGENT_JAR_MD5, BLANK_STRING);
    }

    public String getGivenAgentLauncherMd5() {
        return getPropertyImpl(GoConstants.GIVEN_AGENT_LAUNCHER_JAR_MD5, BLANK_STRING);
    }

    public String getAgentPluginsMd5() {
        return getPropertyImpl(GoConstants.AGENT_PLUGINS_MD5, BLANK_STRING);
    }

    public boolean inDbDebugMode() {
        return debug;
    }

    public boolean usingRemoteDb() {
        return getPropertyImpl("DB_REMOTE") != null
                && !(getPropertyImpl("DB_REMOTE").equals("false"));
    }

    public void setDebugMode(boolean debug) {
        this.debug = debug;
    }

    public boolean isFeatureEnabled(String value) {
        if (Boolean.parseBoolean(properties().getProperty(CRUISE_EXPERIMENTAL_ENABLE_ALL, "false"))) {
            return true;
        }
        return Boolean.parseBoolean(properties().getProperty(value, "false"));
    }

    private Properties properties() {
        if (properties == null) {
            properties = new Properties();
            try {
                properties.load(getClass().getResourceAsStream(CRUISE_PROPERTIES));
            } catch (Exception e) {
                LOG.error("Unable to load newProperties file " + CRUISE_PROPERTIES);
            }
        }
        return properties;
    }

    public boolean useNioSslSocket() {
        String socketType = getPropertyImpl(AGENT_SOCKET_TYPE_PROPERTY, AGENT_SOCKET_TYPE_NIO);
        return AGENT_SOCKET_TYPE_NIO.equalsIgnoreCase(socketType);
    }

    public String getCruiseConfigFile() {
        return getPropertyImpl(CONFIG_FILE_PROPERTY, getConfigDir() + "/cruise-config.xml");
    }

    public int getAgentConnectionTimeout() {
        if (agentConnectionTimeout != null) {
            return agentConnectionTimeout;
        }
        return agentConnectionTimeout = Integer.parseInt(getPropertyImpl(AGENT_CONNECTION_TIMEOUT_IN_SECONDS, "300"));
    }

    public Integer getConsolePublishInterval() {
        return Integer.valueOf(getPropertyImpl(INTERVAL, "5"));
    }

    public String getServiceUrl() {
        return getPropertyImpl(SERVICE_URL, defaultRemotingUrl());
    }

    private String defaultRemotingUrl() {
        return "https://localhost:8443" + getWebappContextPath();
    }

    public boolean useCompressedJs() {
        return Boolean.parseBoolean(getPropertyImpl(GoConstants.USE_COMPRESSED_JAVASCRIPT, "true"));
    }

    public String getEnvironmentVariable(String key) {
        return System.getenv(key);
    }

    public String getBaseUrlForShine() {
        return String.format("http://%s:%s%s", HOSTNAME_SHINE_USES, getServerPort(), getWebappContextPath());
    }

    public String getBaseSslUrlForShineWithoutContextPath() {
        return String.format("https://%s:%s", HOSTNAME_SHINE_USES, getSslServerPort());
    }

    public String getBaseSslUrlForShine() {
        return getBaseSslUrlForShineWithoutContextPath() + getWebappContextPath();
    }

    public File shineDb() {
        return new File(properties().getProperty("cruise.shine.store.folder"));
    }

    public void setProperty(String name, String value) {
        clearCachedSystemEnvironment();
        System.setProperty(name, value);
    }

    public void clearProperty(String name) {
        clearCachedSystemEnvironment();
        System.clearProperty(name);
    }

    private void clearCachedSystemEnvironment() {
        agentConnectionTimeout = null;
        cruiseSSlPort = null;
        cruiseConfigDir = null;
        databaseFullSizeLimit = null;
        artifactFullSizeLimit = null;
    }

    public String getWebappContextPath() {
        return getPropertyImpl("cruise.server.context", "/go");
    }

    public String pathFor(String appPath) {
        return (getWebappContextPath() + "/" + appPath).replaceAll("//", "/");
    }

    public String getCruiseWar() {
        return getPropertyImpl(CRUISE_SERVER_WAR_PROPERTY, "cruise.war");
    }

    public String getCruiseDbCacheSize() {
        return getPropertyImpl(CRUISE_DB_CACHE_SIZE, CRUISE_DB_CACHE_SIZE_DEFAULT);
    }

    public int getShineXslTransformerRegistryCacheSize() {
        return Integer.parseInt(getPropertyImpl(SHINE_XSL_TRANSFORMER_REGISTRY_CACHE_SIZE, DEFAULT_SHINE_XSL_TRANSFORMER_REGISTRY_CACHE_SIZE));
    }

    public long getUnresponsiveJobWarningThreshold() {
        return Long.parseLong(getPropertyImpl(UNRESPONSIVE_JOB_WARNING_THRESHOLD, "5")) * 60 * 1000;//mins to mills
    }

    public int getLicenseExpiryWarningTime() {
        return Integer.parseInt(getPropertyImpl(NUMBER_OF_DAYS_TO_EXPIRY_PROPERTY, String.valueOf(NUMBER_OF_DAYS_TO_EXPIRY)));
    }

    public boolean getParentLoaderPriority() {
        return Boolean.parseBoolean(getPropertyImpl(PARENT_LOADER_PRIORITY, "false"));
    }

    public String getUserDirectory() {
        return getPropertyImpl("user.dir");
    }

    public boolean isPluginsEnabled() {
        return GoConstants.ENABLE_PLUGINS_RESPONSE_TRUE.equals(pluginStatus());
    }

    public String pluginStatus() {
        String property = getPropertyImpl(GoConstants.ENABLE_PLUGINS_PROPERTY, GoConstants.N_NO);
        return GoConstants.Y_YES.equals(property) ? GoConstants.ENABLE_PLUGINS_RESPONSE_TRUE : GoConstants.ENABLE_PLUGINS_RESPONSE_FALSE;
    }

    public String getAgentLauncherVersion() {
        return getPropertyImpl(GoConstants.AGENT_LAUNCHER_VERSION, EMPTY_STRING);
    }

    public static final ThreadLocal<Boolean> enforceServerIdImmutability = new ThreadLocal<Boolean>() {
        @Override
        protected Boolean initialValue() {
            return false;
        }
    };

    public boolean enforceServerIdImmutability() {
        return CONFIGURATION_YES.equals(getPropertyImpl(ENFORCE_SERVERID_MUTABILITY, CONFIGURATION_YES)) || enforceServerIdImmutability.get();
    }

    public boolean enforceRevisionCompatibilityWithUpstream() {
        if (enforceRevisionCompatibilityWithUpstream == null) {
            enforceRevisionCompatibilityWithUpstream = CONFIGURATION_YES.equals(getPropertyImpl(RESOLVE_FANIN_REVISIONS, CONFIGURATION_YES));
        }
        return enforceRevisionCompatibilityWithUpstream;
    }

    public int getTfsSocketTimeout() {
        return Integer.parseInt(getPropertyImpl(TFS_SOCKET_TIMEOUT_PROPERTY, String.valueOf(TFS_SOCKET_TIMEOUT_IN_MILLISECONDS)));
    }

    public boolean enforceFanInFallbackBehaviour() {
        if (enforceFanInFallbackTriangle == null) {
            enforceFanInFallbackTriangle = CONFIGURATION_YES.equals(getPropertyImpl(RESOLVE_FANIN_FALLBACK_TRIANGLE, CONFIGURATION_YES));
        }
        return enforceFanInFallbackTriangle;
    }

    public int getCruiseDbTraceLevel() {
        return H2_DB_TRACE_LEVEL.getValue();
    }

    public int getCruiseDbTraceFileSize() {
        return H2_DB_TRACE_FILE_SIZE_MB.getValue();
    }

    public Level pluginLoggingLevel(String pluginId) {
        return Level.toLevel(getPropertyImpl("plugin." + pluginId + ".log.level", "INFO"), Level.INFO);
    }

    public File getDefaultCommandRepository() {
        return new File(get(COMMAND_REPOSITORY_DIRECTORY), "default");
    }

    public String getCommandRepositoryRootLocation() {
        return new File(get(COMMAND_REPOSITORY_DIRECTORY)).getAbsolutePath();
    }

    public String getExternalPluginAbsolutePath() {
        return new File(get(PLUGIN_EXTERNAL_PROVIDED_PATH)).getAbsolutePath();
    }

    public String getBundledPluginAbsolutePath() {
        return new File(get(PLUGIN_GO_PROVIDED_PATH)).getAbsolutePath();
    }

    public <T> void reset(GoSystemProperty<T> systemProperty) {
        System.clearProperty(systemProperty.propertyName());
        if (systemProperty instanceof CachedProperty) {
            ((CachedProperty) systemProperty).clear();
        }
    }

    public long getMaterialUpdateIdleInterval() {
        return MATERIAL_UPDATE_IDLE_INTERVAL.getValue();
    }

    public boolean isDefaultDbProvider() {
        return GO_DATABASE_PROVIDER.getValue().equals(H2_DATABASE);
    }

    public String getDatabaseProvider() {
        return GO_DATABASE_PROVIDER.getValue();
    }

    public String landingPage() {
        return GO_LANDING_PAGE.getValue();
    }

    public boolean usingJetty9() {
        return get(APP_SERVER).equals(JETTY9);
    }

    public boolean isServerActive() {
        return GO_SERVER_STATE.getValue().equalsIgnoreCase("active");
    }

    public void switchToActiveState() {
        set(GO_SERVER_STATE, "active");
    }

    public void switchToPassiveState() {
        set(GO_SERVER_STATE, "passive");
    }

    public static abstract class GoSystemProperty<T> {
        private String propertyName;
        private T defaultValue;

        protected GoSystemProperty(String propertyName, T defaultValue) {
            this.propertyName = propertyName;
            this.defaultValue = defaultValue;
        }

        T getValue() {
            String propertyValue = System.getProperty(propertyName);
            return convertValue(propertyValue, defaultValue);
        }

        protected abstract T convertValue(String propertyValueFromSystem, T defaultValue);

        public String propertyName() {
            return propertyName;
        }
    }

    private static class GoIntSystemProperty extends GoSystemProperty<Integer> {
        public GoIntSystemProperty(String propertyName, Integer defaultValue) {
            super(propertyName, defaultValue);
        }

        @Override
        protected Integer convertValue(String propertyValueFromSystem, Integer defaultValue) {
            try {
                return Integer.parseInt(propertyValueFromSystem);
            } catch (NumberFormatException e) {
                return defaultValue;
            }
        }
    }

    private static class GoLongSystemProperty extends GoSystemProperty<Long> {
        public GoLongSystemProperty(String propertyName, Long defaultValue) {
            super(propertyName, defaultValue);
        }

        @Override
        protected Long convertValue(String propertyValueFromSystem, Long defaultValue) {
            try {
                return Long.parseLong(propertyValueFromSystem);
            } catch (NumberFormatException e) {
                return defaultValue;
            }
        }
    }

    private static class GoStringSystemProperty extends GoSystemProperty<String> {
        public GoStringSystemProperty(String propertyName, String defaultValue) {
            super(propertyName, defaultValue);
        }

        @Override
        protected String convertValue(String propertyValueFromSystem, String defaultValue) {
            return propertyValueFromSystem == null ? defaultValue : propertyValueFromSystem;
        }
    }

    private static class CachedProperty<T> extends GoSystemProperty<T> {
        private GoSystemProperty<T> wrappedProperty;
        private T cachedValue;

        public CachedProperty(GoSystemProperty<T> goSystemProperty) {
            super(goSystemProperty.propertyName, goSystemProperty.defaultValue);
            wrappedProperty = goSystemProperty;
        }

        @Override
        protected T convertValue(String propertyValueFromSystem, T defaultValue) {
            if (cachedValue == null) {
                cachedValue = wrappedProperty.convertValue(propertyValueFromSystem, defaultValue);
            }
            return cachedValue;
        }

        public void clear() {
            cachedValue = null;
        }
    }

    private static class GoBooleanSystemProperty extends GoSystemProperty<Boolean> {
        public GoBooleanSystemProperty(String propertyName, Boolean defaultValue) {
            super(propertyName, defaultValue);
        }

        @Override
        protected Boolean convertValue(String propertyValueFromSystem, Boolean defaultValue) {
            if (propertyValueFromSystem == null) {
                return defaultValue;
            }
            return "Y".equalsIgnoreCase(propertyValueFromSystem);
        }
    }

    private static class GoFileSystemProperty extends GoSystemProperty<File> {
        public GoFileSystemProperty(String propertyName, File defaultFile) {
            super(propertyName, defaultFile);
        }

        @Override
        protected File convertValue(String propertyValueFromSystem, File defaultValue) {
            return propertyValueFromSystem == null ? defaultValue : new File(propertyValueFromSystem);
        }
    }
}


text:
from cls.randomfunc import random_func
from cls.animal import Animal
from cls.zebra import Zebra

def run():
    # general module import
    random_func()

    # class import
    animal = Animal()
    print(animal)

    # sub-class import
    zebra = Zebra()
    print(zebra)

if __name__ == '__main__':
    run()

redpajama_set_name: RedPajamaGithub


text:
namespace lsd {

int const error::MESSAGE_SIZE;

error::error(const std::string& format, ...) :
	std::exception(),
	type_(LSD_UNKNOWN_ERROR)
{
	va_list args;
	va_start(args, format);
	vsnprintf(message_, MESSAGE_SIZE, format.c_str(), args);
	va_end(args);
}

error::error(enum error_type type, const std::string& format, ...) :
	std::exception(),
	type_(type)
{
	va_list args;
	va_start(args, format);
	vsnprintf(message_, MESSAGE_SIZE, format.c_str(), args);
	va_end(args);
}

error::~error() throw () {
}

error::error(const error& other) : std::exception(other) {
	memcpy(message_, other.message_, MESSAGE_SIZE);
}

error&
error::operator = (const error& other) {
	memcpy(message_, other.message_, MESSAGE_SIZE);
	return *this;
}

char const*
error::what() const throw () {
	return message_;
}

} // namespace lsd


text:
package org.ppl.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.ppl.common.function;

public class cUrl extends function {
	private List<NameValuePair> params = new ArrayList<NameValuePair>();
	private List<Header> cHeader = new ArrayList<>();
	private CloseableHttpClient httpclient = null;
	ResponseHandler<String> responseHandler = null;
	RequestConfig requestConfig = null;

	public String httpGet(String url) {
		if (httpclient == null) {
			httpclient = HttpClients.createDefault();
			requestConfig = RequestConfig.custom()
			        .setSocketTimeout(60000)
			        .setConnectTimeout(60000)
			        .build();
		}

		HttpGet httpget = new HttpGet(url);
		httpget.setConfig(requestConfig);

		if (cHeader.size() > 0) {
			for (Header mHeader : cHeader) {
				httpget.addHeader(mHeader);
			}
		}

		// Create a custom response handler
		Response();

		String responseBody = null;
		try {
			responseBody = httpclient.execute(httpget, responseHandler);

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		httpget = null;
		return responseBody;
	}

	private void Response() {
		if (responseHandler == null) {
			responseHandler = new ResponseHandler<String>() {

				public String handleResponse(final HttpResponse response)
						throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity)
								: null;
					} else {
						throw new ClientProtocolException(
								"Unexpected response status: " + status);
					}
				}

			};
		}
	}

	public String httpPost(String url) {
		if (httpclient == null) {
			httpclient = HttpClients.custom()
					.addInterceptorFirst(new HttpRequestInterceptor() {

						public void process(final HttpRequest request,
								final HttpContext context)
								throws HttpException, IOException {
							if (!request.containsHeader("Accept-Encoding")) {
								request.addHeader("Accept-Encoding", "gzip");
							}

						}
					}).addInterceptorFirst(new HttpResponseInterceptor() {

						public void process(final HttpResponse response,
								final HttpContext context)
								throws HttpException, IOException {
							HttpEntity entity = response.getEntity();
							if (entity != null) {

								Header ceheader = entity.getContentEncoding();
								if (ceheader != null) {
									HeaderElement[] codecs = ceheader
											.getElements();
									for (int i = 0; i < codecs.length; i++) {
										if (codecs[i].getName()
												.equalsIgnoreCase("gzip")) {
											response.setEntity(new GzipDecompressingEntity(
													response.getEntity()));
											return;
										}
									}
								}
							}
						}

					}).build();

		}
		HttpPost httppost = new HttpPost(url);
		if (cHeader.size() > 0) {
			for (Header mHeader : cHeader) {
				httppost.addHeader(mHeader);
			}
		}
		if (params.size() > 0) {
			try {
				httppost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		CloseableHttpResponse response;
		// ByteArrayOutputStream bao = null;
		StringBuilder sb1 = new StringBuilder();
		InputStream bis = null;
		int len = 1024;
		byte[] buf = new byte[len];
		// byte[] sBuf;
		String content = null;
		try {

			response = httpclient.execute(httppost);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				bis = response.getEntity().getContent();
				// long lenEntity = response.getEntity().getContentLength();
				Header encoding = response.getEntity().getContentEncoding();
				int count;

				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while ((count = bis.read(buf)) != -1) {

					baos.write(buf, 0, count);

				}

				String str = new String(baos.toByteArray(), 0,
						baos.toByteArray().length, "UTF-8");
				baos.close();
				// echo("lenEntity:"+lenEntity+" baos:"+baos.toByteArray().length+" str:"+str.length());
				// echo(str);
				sb1.append(str);

				bis.close();

				ByteArrayInputStream bai = new ByteArrayInputStream(sb1
						.toString().getBytes());
				if (encoding != null) {
					if (encoding.getValue().equals("gzip")
							|| encoding.getValue().equals("zip")
							|| encoding.getValue().equals(
									"application/x-gzip-compressed")) {

						GZIPInputStream gzin = new GZIPInputStream(bai);
						StringBuffer sb = new StringBuffer();
						int size;
						while ((size = gzin.read(buf)) != -1) {
							sb.append(new String(buf, 0, size, "utf-8"));
						}
						gzin.close();
						// bao.close();

						content = sb.toString();

					}
				} else {

					content = new String(sb1);
				}

			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (Exception e) {
				}
			}
		}
		return content;

	}

	public void closePost() {
		try {
			httpclient.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void clearParams() {
		params.clear();
	}

	public void addParams(String key, String val) {
		params.add(new BasicNameValuePair(key, val));
	}

	public List<Header> getcHeader() {
		return cHeader;
	}

	public void setcHeader(Header mHeader) {
		this.cHeader.add(mHeader);
	}

	public void clearHeader() {
		this.cHeader.clear();
	}
}


text:
<?php
namespace Axstrad\Bundle\UseCaseTestBundle\Tests\Unit\Test;

use Axstrad\Bundle\UseCaseTestBundle\Test\MultiUseCaseTest;

/**
 */
class MultiUseCaseTestTest extends \PHPUnit_Framework_TestCase
{
    private $originalUseCasesDir = null;

    public function setUp()
    {
        $this->originalUseCasesDir = MultiUseCaseTest::$useCasesDir;
    }

    public function tearDown()
    {
        MultiUseCaseTest::$useCasesDir = $this->originalUseCasesDir;
    }

    public function testCanGetAbsolutePathToUseCaseDir()
    {
        $this->assertEquals(
            realpath(__DIR__.'/../../UseCases'),
            MultiUseCaseTest::getAbsoluteUseCasesDir()
        );
    }

    /**
     * @expectedException Axstrad\Bundle\UseCaseTestBundle\Exception\PathDoesNotExistException
     */
    public function testExceptionThrownWhenInvalidUseCaseDir()
    {
        MultiUseCaseTest::$useCasesDir = 'i/do/not/exist';
        MultiUseCaseTest::getAbsoluteUseCasesDir();
    }
}


text:
// Copyright (c) Philipp Wagner. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using ConnectR.Infrastructure.Nancy;
using ConnectR.Requests;
using ConnectR.Responses;
using ConnectR.Services;
using Nancy;
using Nancy.ModelBinding;
using System;
using System.IO;
using Nancy.Security;
using ConnectR.Infrastructure.Authentication;

namespace ConnectR.Modules
{
    public class FileUploadModule : ConnectRModule
    {
        private readonly IRootPathProvider rootPathProvider;
        private readonly IApplicationSettings applicationSettings;
        private readonly IUploadNotificationService uploadNotificationService;

        public FileUploadModule(IRootPathProvider rootPathProvider, IApplicationSettings applicationSettings, IUploadNotificationService uploadNotificationService)
           : base("/file")
        {
            this.rootPathProvider = rootPathProvider;
            this.applicationSettings = applicationSettings;
            this.uploadNotificationService = uploadNotificationService;

            Post["/upload"] = parameters =>
            {
                if (!this.Principal.HasClaim(ConnectRClaimTypes.Admin))
                {
                    return HttpStatusCode.Forbidden;
                }

                FileUploadRequest request = this.BindAndValidate<FileUploadRequest>();
                FileUploadResponse response = StoreImage(request);

                uploadNotificationService.OnFileUploaded(response.Id);

                return Negotiate
                    .WithStatusCode(HttpStatusCode.OK)
                    .WithModel(response);
            };
        }

        // TODO Move to separate service.
        private FileUploadResponse StoreImage(FileUploadRequest request)
        {
            var uploadId = Guid.NewGuid().ToString();
            var filename = Path.Combine(GetUploadDirectory(), uploadId);
            using (FileStream fileStream = new FileStream(filename, FileMode.Create))
            {
                request.File.Value.CopyTo(fileStream);
            }
            return new FileUploadResponse()
            {
                Id = uploadId
            };
        }

        // TODO Move to separate service.
        private string GetUploadDirectory()
        {
            var uploadDirectory = Path.Combine(rootPathProvider.GetRootPath(), applicationSettings.FileUploadDirectory);

            if (!Directory.Exists(uploadDirectory))
            {
                Directory.CreateDirectory(uploadDirectory);
            }

            return uploadDirectory;
        }
    }
}


text:
namespace NGauge.Core
{
    public interface IStepTextParameterExtractor
    {
        string ExtractParameters(string stepText);
    }
}


text:
// Copyright Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;
using System.Collections;

public class ScrollSunFlareGC : MonoBehaviour
{
    public Vector2 InitialOffset = Vector2.zero;
    public Vector2 FinalOffset = Vector2.zero;

    public float InitialScale = 1;
    public float FinalScale = 1;

    private Vector2 FlareTimeRange = new Vector2(8f, 15f);
    private Vector2 TimeRangeBetweenFlares = new Vector2(0f, 5f);

    private Material mat;
    private Vector2 currentOffset;

    private void OnEnable()
    {
        var mr = gameObject.GetComponent<MeshRenderer>();
        mr.material = mat = mr.material;

        StartCoroutine(Flares(new Vector2(0, 1)));
    }

    private void OnDisable()
    {
        this.StopAllCoroutines();
    }

    private IEnumerator Flares(Vector2 initialTimeRange)
    {
        SetUpForFlare();
        float startTimeToWait = Random.Range(initialTimeRange.x, initialTimeRange.y);
        yield return new WaitForSeconds(startTimeToWait);

        while (true)
        {
            SetUpForFlare();
            float timeToWait = Random.Range(TimeRangeBetweenFlares.x, TimeRangeBetweenFlares.y);
            yield return new WaitForSeconds(timeToWait);

            float FlareTime = Random.Range(FlareTimeRange.x, FlareTimeRange.y);
            yield return StartCoroutine(DoSunFlare(FlareTime));
        }
    }

    private void SetUpForFlare()
    {
        if (mat != null)
        {
            mat.SetTextureOffset("_MainTex", InitialOffset);
        }
    }

    private IEnumerator DoSunFlare(float FlareTime)
    {
        if (FlareTime != 0)
        {
            float t = 0;

            while (t < FlareTime * 0.5f)
            {
                float i = t / FlareTime;

                Vector2 newOffset = Vector2.Lerp(InitialOffset, FinalOffset, i);
                mat.SetTextureOffset("_MainTex", newOffset);

                float newScale = Mathf.Lerp(InitialScale, FinalScale, Mathf.SmoothStep(0, 1, i * 2f));
                transform.localScale = Vector3.one * newScale;

                t += Time.deltaTime;
                yield return null;
            }

            while (t < FlareTime)
            {
                float i = t / FlareTime;

                Vector2 newOffset = Vector2.Lerp(InitialOffset, FinalOffset, i);
                mat.SetTextureOffset("_MainTex", newOffset);

                float newScale = Mathf.Lerp(FinalScale, InitialScale, Mathf.SmoothStep(0, 1, (i - 0.5f) * 2f));
                transform.localScale = Vector3.one * newScale;

                t += Time.deltaTime;
                yield return null;
            }
        }
    }
}


text:
<%page args="module"/>
<%
import os.path
import splunk.util
from splunk.appserver.mrsparkle.lib.util import make_splunkhome_path
from formencode.validators import URL
import logging

logger = logging.getLogger('splunk.appserver.lib.i18n')

src = module['src']
if splunk.util.normalizeBoolean(module['check_exists']):
    logger.warn('check_exists flag is deprecated and has no effect')
if src.startswith(('http://', 'https://')):
    u = URL(add_http=False)
elif src.startswith('/'):
    src = make_url(src)
else:
    p = make_splunkhome_path(['etc', 'apps', APP['id'], 'appserver', 'static', src])
    src = make_url(['static', 'app', APP['id'], src])
%>
<iframe src="" scrolling="no" frameborder="0" data-src="${src}"></iframe>


text:
<?php

class User {

    private $UID;
    private $Username;
    private $Password;
    private $Timestamp;

    function __construct($data) {
        $this->fromJson($data);
    }

    private function fromJson($data) {
        foreach ($data AS $key => $value) {
            $this->{$key} = $value;
        }
    }

    public function getUid() {
        return $this->UID;
    }

    public function setUid($uid) {
        $this->UID = $uid;
    }

    public function getUsername() {
        return $this->Username;
    }

    public function getPassword() {
        return $this->Password;
    }

    public function getTimestamp() {
        return $this->Timestamp;
    }

    public function setTimestamp($timestamp) {
        $this->Timestamp = $timestamp;
    }

    public function toArray() {
        return get_object_vars($this);
    }
}

?>


text:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [ServerEye].[RingBufferSchedulerMonitor](
	[SQLServerStartTime] [datetime] NOT NULL,
	[RecordID] [bigint] NOT NULL,
	[timestamp] [bigint] NOT NULL,
	[ExceptionTime] [datetime] NOT NULL,
	[UTCCaptureTime] [datetime] NOT NULL,
	[LocalCaptureTime] [datetime] NOT NULL,
	[ProcessUtilization] [int] NULL,
	[SystemIdle] [int] NULL,
	[UserModeTime] [int] NULL,
	[KernelModeTime] [int] NULL,
	[PageFaults] [int] NULL,
	[WorkingSetDelta] [int] NULL,
	[MemoryUtilization] [int] NULL,
 CONSTRAINT [PK_RingBufferSchedulerMonitor] PRIMARY KEY NONCLUSTERED
(
	[SQLServerStartTime] ASC,
	[RecordID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE CLUSTERED INDEX CL1 ON [ServerEye].[RingBufferSchedulerMonitor](UTCCaptureTime);
GO


text:
class StatisticsInfoManager;

class DevicesController {
    friend class StatisticsInfoManager;
public:
    DevicesController();

    void init(std::vector<float> args);
    void putBidToDevice(const Bid &bid);

    float getMinDeviceTime() const;
    float getMinBusyDeviceTime() const;

    void freeReadyDevices();

    friend std::ostream& operator<< (std::ostream& os, const DevicesController& arg) {
        os << "Devices:\n";
        for(auto it = arg._devices.begin(); it != arg._devices.end(); ++it) {
            os << "Dev T: " << (*it).getTime() << " Bid T: " << (*it).getBid().getTime()
               << " Bid S: " << (*it).getBid().getSource() << "\n";
        }

        return os;
    }

    void updateFreeDevices();

    bool hasFreeDevice() const;

private:
    void moveDevicePointer();
    const std::deque<Device> &getDevices() const;
private:
    std::deque<Device> _devices;
    int _currentDevice;
    int _amountDevices;
};

#endif // DEVICECONTROLLER_H


text:
import {
  JimpType,
  JimpPlugin,
} from './plugins';

// This is required as providing type arrays gives a union of all the generic
// types in the array rather than an intersection
export type UnionToIntersection<U> =
  (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;

/**
 * The values to be extracted from a WellFormedPlugin to put onto the Jimp instance
 * Left loose as "any" in order to enable the GetPluginValue to work properly
 */
export type WellFormedValues<T extends any> =
  (T extends {class: any} ? T['class'] : {}) &
  (T extends {constants: any} ? T['constants'] : {});

// Util type for the functions that deal with `@jimp/custom`
// Must accept any or no props thanks to typing of the `plugins` intersected function
export type FunctionRet<T> = Array<(...props: any[] | never) => T>;

/**
 * This conditional cannot be flipped. TS assumes that Q is `WellFormed` even
 * it does not have the `class` or `constant` props. As a result, it will end
 * up `undefined`. Because we're always extending `IllformedPlugin` on the
 * plugins, this should work fine
 */
export type GetPluginVal<Q> = Q extends Required<{class: any}> | Required<{constant: any}>
  ? WellFormedValues<Q>
  : Q;

type GetPluginFuncArrValues<PluginFuncArr> =
  // Given an array of types infer `Q` (Q should be the type value)
  PluginFuncArr extends Array<() => infer Q>
  ? // Get the plugin value, may be ill-formed or well-formed
    GetPluginVal<Q>
  : // This should never be reached
    undefined;

/**
 * A helper type to get the values to be intersected with `Jimp` to give
 * the proper typing given an array of functions for plugins and types
 */
export type GetIntersectionFromPlugins<
  PluginFuncArr extends FunctionRet<JimpPlugin | JimpType>
> = UnionToIntersection<GetPluginFuncArrValues<PluginFuncArr>>;

/**
 * While this was added to TS 3.5, in order to support down to TS 2.8, we need
 * to export this and use it in sub-packges that utilize it
 */
export type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;


text:
package org.apache.carbondata.core.statusmanager;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.constants.CarbonCommonConstants;

public class LoadMetadataDetails implements Serializable {

  private static final long serialVersionUID = 1106104914918491724L;
  private String timestamp;
  private String loadStatus;
  private String loadName;
  private String partitionCount;
  private String isDeleted = CarbonCommonConstants.KEYWORD_FALSE;

  // update delta end timestamp
  private String updateDeltaEndTimestamp = "";

  // update delta start timestamp
  private String updateDeltaStartTimestamp = "";

  // this will represent the update status file name at that point of time.
  private String updateStatusFileName = "";

  /**
   * LOGGER
   */
  private static final LogService LOGGER =
      LogServiceFactory.getLogService(LoadMetadataDetails.class.getName());

  // dont remove static as the write will fail.
  private static final SimpleDateFormat parser =
      new SimpleDateFormat(CarbonCommonConstants.CARBON_TIMESTAMP_MILLIS);
  /**
   * Segment modification or deletion time stamp
   */
  private String modificationOrdeletionTimesStamp;
  private String loadStartTime;

  private String mergedLoadName;
  /**
   * visibility is used to determine whether to the load is visible or not.
   */
  private String visibility = "true";

  /**
   * To know if the segment is a major compacted segment or not.
   */
  private String majorCompacted;

  /**
   * the file format of this segment
   */
  private FileFormat fileFormat = FileFormat.carbondata;

  public String getPartitionCount() {
    return partitionCount;
  }

  public void setPartitionCount(String partitionCount) {
    this.partitionCount = partitionCount;
  }

  public long getLoadEndTime() {
    if (timestamp == null) {
      return CarbonCommonConstants.SEGMENT_LOAD_TIME_DEFAULT;
    }
    return convertTimeStampToLong(timestamp);
  }

  public void setLoadEndTime(long timestamp) {
    this.timestamp = getTimeStampConvertion(timestamp);;
  }

  public String getLoadStatus() {
    return loadStatus;
  }

  public void setLoadStatus(String loadStatus) {
    this.loadStatus = loadStatus;
  }

  public String getLoadName() {
    return loadName;
  }

  public void setLoadName(String loadName) {
    this.loadName = loadName;
  }

  /**
   * @return the modificationOrdeletionTimesStamp
   */
  public long getModificationOrdeletionTimesStamp() {
    if (null == modificationOrdeletionTimesStamp) {
      return 0;
    }
    return convertTimeStampToLong(modificationOrdeletionTimesStamp);
  }

  /**
   * @param modificationOrdeletionTimesStamp the modificationOrdeletionTimesStamp to set
   */
  public void setModificationOrdeletionTimesStamp(long modificationOrdeletionTimesStamp) {
    this.modificationOrdeletionTimesStamp =
        getTimeStampConvertion(modificationOrdeletionTimesStamp);
  }

  /* (non-Javadoc)
   * @see java.lang.Object#hashCode()
   */
  @Override public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((loadName == null) ? 0 : loadName.hashCode());
    return result;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override public boolean equals(Object obj) {
    if (obj == null) {
      return false;

    }
    if (!(obj instanceof LoadMetadataDetails)) {
      return false;
    }
    LoadMetadataDetails other = (LoadMetadataDetails) obj;
    if (loadName == null) {
      if (other.loadName != null) {
        return false;
      }
    } else if (!loadName.equals(other.loadName)) {
      return false;
    }
    return true;
  }

  /**
   * @return the startLoadTime
   */
  public long getLoadStartTime() {
    if (loadStartTime == null) {
      return CarbonCommonConstants.SEGMENT_LOAD_TIME_DEFAULT;
    }
    return convertTimeStampToLong(loadStartTime);
  }

  /**
   * return loadStartTime
   *
   * @return
   */
  public long getLoadStartTimeAsLong() {
    return (!loadStartTime.isEmpty()) ? getTimeStamp(loadStartTime) : 0;
  }

  /**
   * This method will convert a given timestamp to long value and then to string back
   *
   * @param factTimeStamp
   * @return
   */
  private long convertTimeStampToLong(String factTimeStamp) {
    SimpleDateFormat parser = new SimpleDateFormat(CarbonCommonConstants.CARBON_TIMESTAMP_MILLIS);
    Date dateToStr = null;
    try {
      dateToStr = parser.parse(factTimeStamp);
      return dateToStr.getTime();
    } catch (ParseException e) {
      LOGGER.error("Cannot convert" + factTimeStamp + " to Time/Long type value" + e.getMessage());
      parser = new SimpleDateFormat(CarbonCommonConstants.CARBON_TIMESTAMP);
      try {
        dateToStr = parser.parse(factTimeStamp);
        return dateToStr.getTime();
      } catch (ParseException e1) {
        LOGGER
            .error("Cannot convert" + factTimeStamp + " to Time/Long type value" + e1.getMessage());
        return 0;
      }
    }
  }

  /**
   * returns load start time as long value
   *
   * @param loadStartTime
   * @return
   */
  public Long getTimeStamp(String loadStartTime) {
    Date dateToStr = null;
    try {
      dateToStr = parser.parse(loadStartTime);
      return dateToStr.getTime() * 1000;
    } catch (ParseException e) {
      LOGGER.error("Cannot convert" + loadStartTime + " to Time/Long type value" + e.getMessage());
      return null;
    }
  }

  private String getTimeStampConvertion(long time) {
    SimpleDateFormat sdf = new SimpleDateFormat(CarbonCommonConstants.CARBON_TIMESTAMP_MILLIS);
    return sdf.format(time);
  }

  /**
   * @param loadStartTime
   */
  public void setLoadStartTime(long loadStartTime) {
    this.loadStartTime = getTimeStampConvertion(loadStartTime);
  }

  /**
   * @return the mergedLoadName
   */
  public String getMergedLoadName() {
    return mergedLoadName;
  }

  /**
   * @param mergedLoadName the mergedLoadName to set
   */
  public void setMergedLoadName(String mergedLoadName) {
    this.mergedLoadName = mergedLoadName;
  }

  /**
   * @return the visibility
   */
  public String getVisibility() {
    return visibility;
  }

  /**
   * @param visibility the visibility to set
   */
  public void setVisibility(String visibility) {
    this.visibility = visibility;
  }

  /**
   * Return true if it is a major compacted segment.
   * @return majorCompacted
   */
  public String isMajorCompacted() {
    return majorCompacted;
  }

  /**
   * Set true if it is a major compacted segment.
   *
   * @param majorCompacted
   */
  public void setMajorCompacted(String majorCompacted) {
    this.majorCompacted = majorCompacted;
  }

  /**
   * To get isDeleted property.
   *
   * @return isDeleted
   */
  public String getIsDeleted() {
    return isDeleted;
  }

  /**
   * To set isDeleted property.
   *
   * @param isDeleted
   */
  public void setIsDeleted(String isDeleted) {
    this.isDeleted = isDeleted;
  }

  /**
   * To get the update delta end timestamp
   *
   * @return updateDeltaEndTimestamp
   */
  public String getUpdateDeltaEndTimestamp() {
    return updateDeltaEndTimestamp;
  }

  /**
   * To set the update delta end timestamp
   *
   * @param updateDeltaEndTimestamp
   */
  public void setUpdateDeltaEndTimestamp(String updateDeltaEndTimestamp) {
    this.updateDeltaEndTimestamp = updateDeltaEndTimestamp;
  }

  /**
   * To get the update delta start timestamp
   *
   * @return updateDeltaStartTimestamp
   */
  public String getUpdateDeltaStartTimestamp() {
    return updateDeltaStartTimestamp;
  }

  /**
   * To set the update delta start timestamp
   *
   * @param updateDeltaStartTimestamp
   */
  public void setUpdateDeltaStartTimestamp(String updateDeltaStartTimestamp) {
    this.updateDeltaStartTimestamp = updateDeltaStartTimestamp;
  }

  /**
   * To get the updateStatusFileName
   *
   * @return updateStatusFileName
   */
  public String getUpdateStatusFileName() {
    return updateStatusFileName;
  }

  /**
   * To set the updateStatusFileName
   *
   * @param updateStatusFileName
   */
  public void setUpdateStatusFileName(String updateStatusFileName) {
    this.updateStatusFileName = updateStatusFileName;
  }

  public FileFormat getFileFormat() {
    return fileFormat;
  }

  public void setFileFormat(FileFormat fileFormat) {
    this.fileFormat = fileFormat;
  }
}


text:
"""Test cases for end-to-end testing.  Run with the server_tests script."""

import calendar
import datetime
import email
import email.header
import optparse
import os
import pytest
import re
import simplejson
import sys
import tempfile
import time
import unittest
import urlparse

from google.appengine.api import images

import config
from const import ROOT_URL, PERSON_STATUS_TEXT, NOTE_STATUS_TEXT
import download_feed
from model import *
from photo import MAX_IMAGE_DIMENSION
import remote_api
from resources import Resource, ResourceBundle
import reveal
import scrape
import setup_pf as setup
from test_pfif import text_diff
from text_query import TextQuery
import utils
from server_tests_base import ServerTestsBase

# TODO(ryok): fix go_as_operator() and re-enable the tests.
#class ApiKeyManagementTests(ServerTestsBase):
#    """Tests for API key management capabilities."""
#
#    key_management_operator = "op@example.com"
#
#    def go_as_operator(self, path, **kwargs):
#        """Navigates to the given path with an operator login."""
#        if not self.logged_in_as_operator:
#            scrape.setcookies(self.s.cookiejar, self.hostport,
#                              ['dev_appserver_login=%s:True:1' %
#                                  self.key_management_operator])
#            self.logged_in_as_operator = True
#        return self.go(path, **kwargs)
#
#    def go_as_admin(self, path, **kwargs):
#        """Setting logged_in_as_operator to False."""
#        ret = ServerTestsBase.go_as_admin(self, path, **kwargs)
#        self.logged_in_as_operator = False
#        return ret
#
#    def setUp(self):
#        ServerTestsBase.setUp(self)
#        self.logged_in_as_operator = False
#        config.set_for_repo(
#            'japan',
#            key_management_operators=[self.key_management_operator])
#
#    def test_toppage(self):
#        """Check the main page of API kay management."""
#        url = 'http://%s/personfinder/japan/admin/api_keys' % self.hostport
#        doc = self.go(url, redirects=0)
#        # check if 302
#        assert self.s.status == 302
#        doc = self.go_as_operator(url, redirects=0)
#        assert self.s.status == 200
#        assert 'API Key Management' in doc.text
#        doc = self.go_as_admin(url, redirects=0)
#        assert self.s.status == 200
#        assert 'API Key Management' in doc.text
#
#    def test_manage_key(self):
#        """Check if a new API key is created/updated correctly."""
#        url = 'http://%s/personfinder/japan/admin/api_keys' % self.hostport
#        doc = self.go_as_operator(url)
#        assert self.s.status == 200
#        assert 'API Key Management' in doc.text
#        form = doc.first('form', id='create-or-update-api-key')
#        contact_name = 'Test User'
#        contact_email = 'user@example.com'
#        organization_name = 'Example, Inc.'
#        domain_write_permission = 'example.com'
#        doc = self.s.submit(
#            form,
#            contact_name=contact_name,
#            contact_email=contact_email,
#            organization_name=organization_name,
#            domain_write_permission=domain_write_permission,
#            read_permission='on',
#            full_read_permission='on',
#            search_permission='on',
#            subscribe_permission='on',
#            mark_notes_reviewed='on',
#            is_valid='on',
#        )
#        assert 'A new API key has been created successfully.' in doc.text
#        q = Authorization.all().filter('repo =', 'japan')
#        authorizations = q.fetch(10)
#        assert len(authorizations) == 1
#        authorization = authorizations[0]
#        # Check if the new key is correct.
#        assert authorization.contact_name == contact_name
#        assert authorization.contact_email == contact_email
#        assert authorization.organization_name == organization_name
#        assert authorization.domain_write_permission == domain_write_permission
#        assert authorization.read_permission is True
#        assert authorization.full_read_permission is True
#        assert authorization.search_permission is True
#        assert authorization.subscribe_permission is True
#        assert authorization.mark_notes_reviewed is True
#        assert authorization.is_valid is True
#        # Check if the management self.log is created correctly.
#        q = ApiKeyManagementLog.all().filter('repo =', 'japan')
#        logs = q.fetch(10)
#        assert len(logs) == 1
#        self.log = logs[0]
#        assert self.log.user.email() == self.key_management_operator
#        assert self.log.authorization.key() == authorization.key()
#        assert self.log.action == ApiKeyManagementLog.CREATE
#
#        # List the key and click the edit form on the list
#        url = 'http://%s/personfinder/japan/admin/api_keys/list' % self.hostport
#        doc = self.go_as_admin(url)
#        assert self.s.status == 200
#        assert 'Listing API keys for japan' in doc.text
#        form = doc.first('form')
#        doc = self.s.submit(form)
#        assert self.s.status == 200
#        assert 'Detailed information of an API key for japan' in doc.text
#
#        # Update the key
#        contact_name = 'Japanese User'
#        contact_email = 'user@example.jp'
#        organization_name = 'Example, Corp.'
#
#        form = doc.first('form')
#        doc = self.s.submit(
#            form,
#            contact_name=contact_name,
#            contact_email=contact_email,
#            organization_name=organization_name,
#            domain_write_permission='',
#            read_permission='',
#            full_read_permission='',
#            search_permission='',
#            subscribe_permission='',
#            mark_notes_reviewed='',
#            is_valid='',
#            key=str(authorization.key()),
#        )
#        assert 'The API key has been updated successfully.' in doc.text
#        q = Authorization.all().filter('repo =', 'japan')
#        authorizations = q.fetch(10)
#        assert len(authorizations) == 1
#        authorization = authorizations[0]
#        # Check if the new key is correct.
#        assert authorization.contact_name == contact_name
#        assert authorization.contact_email == contact_email
#        assert authorization.organization_name == organization_name
#        assert authorization.domain_write_permission == ''
#        assert authorization.read_permission is False
#        assert authorization.full_read_permission is False
#        assert authorization.search_permission is False
#        assert authorization.subscribe_permission is False
#        assert authorization.mark_notes_reviewed is False
#        assert authorization.is_valid is False
#        # Check if the management self.log is created correctly.
#        q = ApiKeyManagementLog.all().filter('repo =', 'japan')
#        logs = q.fetch(10)
#        assert len(logs) == 2
#        for self.log in logs:
#            assert self.log.user.email() == self.key_management_operator
#            assert self.log.authorization.key() == authorization.key()
#            if self.log.action != ApiKeyManagementLog.CREATE:
#                assert self.log.action == ApiKeyManagementLog.UPDATE


text:
# See LICENSE for license

import struct
import warnings
from XDscriptLib import FunctionInfo

class Instruction(object):
	"""
	Instruction -- represents a XD script instruction

	For the PAL version, the script interpreter is at 8023D83C

	ctx: ScriptCtx (attribute)
	label: string
	position: int, nextPosition

	OOSSPPPP
	opcode: 8-bit integer, from 0 to 17
	subOpcode: 8-bit integer, not always used
	parameter: 16-bit signed integer, not always used

	**Opcodes**:
		See below. int, float, str, and vector are the only 'copyable' types, ldvar is used for them.
		For all other existing types, ldncpvar is used (if ldncpvar is followed by setvar, the source variable is deleted)

	**Operators, functions, and their respective calling conventions**:
		Refer to FunctionInfo

	**Types**:
		Refer to ScriptVar

	**Stack**:
		It is limited to 256 elements. Each task has its own stack. See FunctionInfo for further details.

	**Tasks**:
		The XD script engine is based on multitasking. 8 tasks max., either synchronous (blocking, and in the same thread),
		or asynchronous (in a different thread). NB: GS uses its own threading system.

		Task signature: either:
			4 ints,
			or a character (for character interaction handlers)

	Properties:

		- subSubOpcodes:
			the sub-opcodes of 'loadvar',
			'setvar', 'setvector' and 'movevar', which access or modify
			variables, can be divided into 2 nibbles (4-bit) :

				- the rightmost stands for the variable's level of storage:
				see variableName

				- the leftmost, only used by 'setvector', is used
				to specify the index of the vector coordinate to be set
				(vec[0] <=> vec.vx, vec[1] <=> vec.vy, vec[2] <=> vec.vz)

		- instructionID : 24-bit integer made by concatenating the sub-opcode and the parameter,
		used by 'call', 'jumptrue', 'jumpfalse', and 'jump'

		- name: the instruction name, determined from the opcode

		- etc...

	"""

	instructionNames = ("nop", "operator", "ldimm",
	"ldvar", "setvar", "setvector",
	"pop", "call", "return",
	"callstd", "jmptrue", "jmpfalse",
	"jmp", "reserve", "release",
	"exit", "setline", "ldncpvar")

	vectorCoordNames = ("vx", "vy", "vz", '4')

	#---------------------Getters---------------------

	@property
	def name(self):
		return self.__class__.instructionNames[self._opcode]

	@property
	def position(self):
		return self._position

	@property
	def nextPosition(self):
		return self._nextPosition

	@property
	def label(self):
		return self._label

	@property
	def opcode(self):
		return self._opcode

	@property
	def subOpcode(self):
		return self._subOpcode

	@property
	def parameter(self):
		return self._parameter

	@property
	def subSubOpcodes(self):
		return ((self._subOpcode >> 4), self._subOpcode & 0xf)

	@property
	def instructionID(self):
		return (self._subOpcode << 16) | (self._parameter & 0xffff)

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

	def checkVariable(self):
		_, level = self.subSubOpcodes
		if level == 0:
			if self._parameter < 0:
				warnings.warn("negative gloabl var ID encountered ({0} \
					at instruction #{1})".format(self._parameter, hex(self.position)))
		elif level == 2:
			if self._parameter != 0:
				warnings.warn("negative $lastResult ID encountered ({0} \
					at instruction #{1})".format(self._parameter, hex(self.position)))
		elif level == 3:
			if self._parameter < 0 or self._parameter > 0x2ff or 0x120 < self._parameter < 0x200:
				warnings.warn("invalid special variable ID encountered ({0} \
					at instruction #{1})".format(self._parameter, hex(self.position)))

	@property
	def variableName(self):
		_, level = self.subSubOpcodes
		if level == 0:
			return "$globals[{0}]".format(self._parameter)
		elif level == 1:
			return "$stack[{0}]".format(self._parameter)
		elif level == 2:
				return "$lastResult"
		else:
			if self._parameter < 0 or self._parameter > 0x2ff or 0x120 < self._parameter < 0x200:
				return "$invalidSpecials[{0}]".format(self._parameter)
			elif 0 <= self._parameter < 0x80: # possible singletons (fake objects)
				name = FunctionInfo.stdfunctions_name_dict.get(self._parameter, str(self._parameter))[0]
				return "${0}".format(name[0].lower() + name[1:])
			elif 0x80 <= self._parameter <= 0x120:
				return "$characters[{0}]".format(self._parameter - 0x80)
			else:
				return "$arrays[{0}]".format(self._parameter - 0x200)

	#------------------Special methods-----------------

	def check(self):
		self._nextPosition = self._position + 1
		instrID = self.instructionID

		if self._opcode > 17:
			warnings.warn("illegal opcode encountered (opcode {0} \
			at instruction #{1})".format(self._opcode, hex(self.position)))

		elif self._opcode == 1:
			if FunctionInfo.getOperatorName(self._subOpcode) == str(self._subOpcode):
				warnings.warn("invalid operator encountered (operator '{0}' \
				at instruction #{1})".format(FunctionInfo.getOperatorName(self._subOpcode), hex(self.position)))

		elif self._opcode == 2:
			if self.ctx is not None:
				packed = None

				if self._subOpcode in (0, 1, 2, 0x35):
					assert not isinstance(self.ctx.sections["CODE"].instructions[self._position + 1], self.__class__)

					packed = struct.pack(">f", self.ctx.sections["CODE"].instructions[self._position + 1]) if\
					type(self.ctx.sections["CODE"].instructions[self._position + 1]) is float else\
					struct.pack(">I", self.ctx.sections["CODE"].instructions[self._position + 1] & 0xffffffff)

				if self._subOpcode in (0, 0x35):  # none_t/codeptr_t
					self.ctx.sections["CODE"].instructions[self._position + 1] = struct.unpack(">I", packed)[0]
					self._nextPosition = self._position + 2

				if self._subOpcode == 1:  # int
					self.ctx.sections["CODE"].instructions[self._position + 1] = struct.unpack(">i", packed)[0]
					self._nextPosition = self._position + 2

				elif self._subOpcode == 2:  # float
					self.ctx.sections["CODE"].instructions[self._position + 1] = struct.unpack(">f", packed)[0]
					self._nextPosition = self._position + 2

			if self._subOpcode == 3:
				if self._parameter < 0:
					warnings.warn("negative string offset encountered ({0} \
					at instruction #{1})".format(self._parameter, hex(self.position)))

			elif self._subOpcode == 4:
				if self._parameter < 0:
					warnings.warn("negative vector ID encountered ({0} \
					at instruction #{1})".format(self._parameter, hex(self.position)))

			elif self._subOpcode not in (0, 1, 2, 3, 4, 0x35, 0x2c):
				warnings.warn("ldimm does not support this type ({0} \
				at instruction #{1})".format(self._subOpcode, hex(self.position)))

		elif self._opcode in (3, 4, 17):
		    # ldvar, setvar, ldncpvar
			self.checkVariable()
			if self.subSubOpcodes[1] == 3 and self._opcode == 4:
				warnings.warn("cannot change immutable reference (instruction #{0})".format(hex(self.position)))

		elif self._opcode == 5:  # setvector
			vecindex, veclevel = self.subSubOpcodes

			if vecindex == 4:
				warnings.warn("out-of-range vector coordinate index encountered ({0} \
				at instruction #{1})".format(self._parameter, hex(self.position)))

			if veclevel == 3:
				warnings.warn("Invalid vector storage type encountered \
				(instruction #{0})".format(hex(self.position)))

		elif self._opcode in (7, 10, 11, 12):  # call/jmptrue/jmpfalse/jmp
			if self.ctx is not None:
				if instrID >= len(self.ctx.sections["CODE"].instructions):
					warnings.warn("out-of-range destination \
					instruction encountered in jump/call instruction \
					(at instruction #{0}: {1}\t{2})".format(hex(self.position),
					self.name, hex(instrID)))

				else:
					if self._opcode == 7 and instrID not in self.ctx.sections["HEAD"].functionOffsets:
						warnings.warn("call to unreferenced function ({0} \
						at instruction #{1})".format(instrID, hex(self.position)))

					lbl = ''.join(["sub_" if self._opcode == 7 else "loc_", hex(instrID)[2:]])
					if not self.ctx.sections["CODE"].labels[instrID]: self.ctx.sections["CODE"].labels[instrID] = lbl
					if self._opcode != 7 and (True if self.ctx is None
							   else self.position+1 < len(self.ctx.sections["CODE"].instructions)) :
						lbl2 = ''.join(["loc_", hex(self.position+1)[2:]])
						if not self.ctx.sections["CODE"].labels[self.position+1]: self.ctx.sections["CODE"].labels[self.position+1] = lbl2

		elif self._opcode == 9:  # callstd
			if FunctionInfo.stdfunctions_name_dict.get(self._subOpcode) is None:
				warnings.warn("invalid class id encountered ({0} \
				at instruction #{1})".format(self._subOpcode, hex(self.position)))

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

	#---------------------Setters---------------------

	@label.setter
	def label(self, val):
		self._label = str(val)

	@position.setter
	def position(self, val):
		if val < 0 or (self.ctx is not None and val >= len(self.ctx.sections["CODE"].instructions)):
			raise ValueError("Out-of-range position!")
		self._position = val

	@nextPosition.setter
	def nextPosition(self, val):
		self._nextPosition = int(val) if val >= 0 else 0

	@opcode.setter
	def opcode(self, value):
		val2 = int(value) & 0xff
		self._opcode = val2
		self.check()

	@subOpcode.setter
	def subOpcode(self, value):
		self._subOpcode = int(value) & 0xff
		self.check()

	@parameter.setter
	def parameter(self, value):
		val2 = int(value) & 0xffff
		# sign extend:
		self._parameter = -((~val2 + 1) & 0xffff) if ((val2 & 0x8000) == 0x8000) else val2
		self.check()

	@subSubOpcodes.setter
	def subSubOpcodes(self, values):
		self._subOpcode = ((int(values[0]) & 0xf) << 4) | (int(values[1]) & 0xf)
		self.check()

	@instructionID.setter
	def instructionID(self, value):
		val2 = int(value)
		self._subOpcode = (val2 >> 16) & 0xff
		self.parameter = val2 & 0xffff
		self.check()

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

	#---------------------Methods---------------------

	def fromRaw(self, rawWord=0):
		self._opcode = (rawWord >> 24) & 0xff
		self._subOpcode = (rawWord >> 16) & 0xff
		self.parameter = rawWord & 0xffff
		self.check()

	def toRaw(self):
		return (self._opcode << 24) | (self._subOpcode << 16) | self._parameter

	def __init__(self, rawWord=0, ctx=None, position=0, label=""):
		#print(position)
		self.ctx = ctx
		self.position = position
		self._nextPosition = position + 1
		self.label = label
		self._opcode = 0
		self._subOpcode = 0
		self._parameter = 0
		self.fromRaw(rawWord)

	def __str__(self):
		self.check()

		instrnamestr = self.name if self._opcode <= 17 else "illegal{0}".format(self._opcode)

		instrstr = None

		if self._opcode > 17:
			return ''.join([labelstr,
						"illegal{0}\t{1}, {2}, {3}".format(self._opcode, self._subOpcode, self._parameter)])

		elif self._opcode in (0, 8, 15):  # nop, return, exit
			instrstr = "{0}".format((self._subOpcode, self._parameter)) if\
			not (self._subOpcode, self._parameter) == (0, 0) else ""

		elif self._opcode == 1:  # operator
			instrstr = FunctionInfo.getOperatorName(self._subOpcode)

		elif self._opcode == 2:  # ldimm
			if self._subOpcode == 0:
				instrstr = 'none_t, ={0}'.format('None' if self.ctx is None or self.ctx.sections["CODE"].instructions[self._position + 1] == 0
									 else self.ctx.sections["CODE"].instructions[self._position + 1])
			elif self._subOpcode == 1:
				instrstr = 'int, ={0}'.format("" if self.ctx is None else str(self.ctx.sections["CODE"].instructions[self._position + 1]))
			elif self._subOpcode == 2:
				if self.ctx is None:
					instrstr = 'float, ='
				else:
					fstr = '{0:.7g}'.format(self.ctx.sections["CODE"].instructions[self._position + 1])#.rstrip('0')
					fstr = fstr if fstr else "0."
					instrstr = 'float, ={0}'.format(fstr)

			elif self._subOpcode == 3:
				instrstr = 'str, ={0}'.format(self._parameter if self.ctx is None or self.ctx.sections.get("STRG") is None
								  else '"{0}"'.format(self.ctx.sections["STRG"].getString(self._parameter)))

			elif self._subOpcode == 4:
				instrstr = "vector, ={0}".format(self._parameter if self.ctx is None or self.ctx.sections.get("VECT") is None
									 else "<{0}, {1}, {2}>".format(*self.ctx.sections["VECT"].vectors[self._parameter]) )

			elif self._subOpcode == 0x2c:
				instrstr = "type44, {0}".format(self._parameter & 0xffff)  # unsigned parameter

			elif self._subOpcode == 0x35:
				typestr = "codeptr_t"
				valuestr = "={0}".format(hex(self.ctx.sections["CODE"].instructions[self._position + 1])\
											if self.ctx is not None else "")

			else:
				instrstr = "{0}, {1}".format(self._subOpcode, self._parameter & 0xffff)

		elif self._opcode in (3, 4, 17):  # ldvar, setvar, ldncpvar
			instrstr = self.variableName

		elif self._opcode == 5:  # setvector
			instrstr = "{0}, {1}".format(self.__class__.vectorCoordNames[self.subSubOpcodes[0]], self.variableName)

		elif self._opcode in (6, 13, 14):  # pop, reserve, release
			instrstr = "{0}{1}".format(self._subOpcode, "" if self._parameter == 0 else\
			"(, {0})".format(self._parameter))

		elif self._opcode in (7, 10, 11, 12):  # call/jmptrue/jmpfalse/jmp
			instrID = self.instructionID
			instrstr = hex(instrID) if (self.ctx is None or instrID >= len(self.ctx.sections["CODE"].instructions))\
			else self.ctx.sections["CODE"].labels[instrID]

		elif self._opcode == 9:  # callstd
			instrstr = FunctionInfo.getStdFunctionName(self._subOpcode, self._parameter)

		elif self._opcode == 16:  # setline
			instrstr = str(self._parameter)

		ret = ''.join([instrnamestr, (14 - len(instrnamestr)) * ' ', instrstr])
		return ret
	#-------------------------------------------------


text:
package com.mgireesh;

public class App {

	public static void main(String[] args) {
		Solution sol = new Solution();
		int[] nums = { 1, 2, 3, 4 };
		System.out.println(sol.permute(nums));
	}

}


text:
static ColorEasing easings[NUM_EASINGS];

void Pixel::cancelEasing(CRGB &buf)
{
  if (this->easingid >= 0) {
    uint32_t val = easings[this->easingid].end();
    buf = val;
    this->easingid = -1;
  }
}

void Pixel::ease(AnywareEasing::EasingType type, const CRGB &toColor, CRGB &buf, uint16_t duration)
{
  // If we're already easing, end the easing and start another one
  if (this->easingid >= 0) this->cancelEasing(buf);

  // Find available easing
  for (uint8_t i=0;i<NUM_EASINGS;i++) {
    if (!easings[i].active) {
      this->easingid = i;
      break;
    }
  }
  if (this->easingid >= 0) {
    easings[this->easingid].start(type, buf, toColor, duration);
    if (global_debug) {
      Serial.print("DEBUG Found easing: "); Serial.println(this->easingid);
    }
  }
  else {
    printError(F("internal error"), F("No easings available"));
    buf = toColor;
  }
}

bool Pixel::applyEasing(CRGB &buf)
{
  bool retval = false;
  if (this->easingid >=0 && easings[this->easingid].active) {
    uint8_t oldval = easings[this->easingid].currval;
    CRGB col = easings[this->easingid].applyColor(millis());
    if (oldval != easings[this->easingid].currval) {
      buf = col;
      retval = true;
    }
    if (!easings[this->easingid].active) {
      this->easingid = -1;
    }
  }
  return retval;
}


text:
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>vaadin-combo basic tests</title>
  <script src="../../web-component-tester/browser.js"></script>

  <link rel="import" href="common.html">
  <script src="common.js"></script>
</head>

<body>

  <test-fixture id="combobox">
    <template>
      <vaadin-combo-box></vaadin-combo-box>
    </template>
  </test-fixture>

  <script>
    describe('scrolling', function() {

      var combobox;

      beforeEach(function() {
        combobox = fixture('combobox');
      });

      describeIf(touchDevice, 'touch devices', function() {
        it('should blur input on scroll', function() {
          combobox.open();

          combobox.$.overlay.fire('down');
          var focusedInput = Polymer.dom(combobox.root).querySelector('input:focus');

          expect(focusedInput).not.to.equal(combobox.$.input);
        });
      });

      describeIf(ios, 'iOS', function() {
        it('should have momentum scrolling enabled', function() {
          combobox.open();

          var scroller = combobox.$.overlay._unwrapIfNeeded(combobox.$.overlay.$.scroller);
          expect(getComputedStyle(scroller).WebkitOverflowScrolling).to.equal('touch');
        });
      });

      describe('scrolling position', function() {
        beforeEach(function() {
          var items = [];

          for (var i = 0; i < 100; i++) {
            items.push(i.toString());
          }

          combobox.items = items;
        });

        it('should be zero when no items are selected', function() {
          combobox.open();

          expect(combobox.$.overlay.$.scroller.scrollTop).to.equal(0);
        });

        it('should be zero when the first item is selected', function() {
          combobox.value = combobox.items[0];
          combobox.open();

          expect(combobox.$.overlay.$.scroller.scrollTop).to.equal(0);
        });

        function expectSelectedItemPositionToBeVisible() {
          var selectedItem = Polymer.dom(combobox.$.overlay.$.selector).querySelector('[selected]');
          expect(selectedItem).to.be.ok;

          var selectedItemRect = selectedItem.getBoundingClientRect();
          var overlayRect = combobox.$.overlay.getBoundingClientRect();
          expect(selectedItemRect.left).to.be.at.least(overlayRect.left);
          expect(selectedItemRect.top).to.be.at.least(overlayRect.top);
          expect(selectedItemRect.right).to.be.at.most(overlayRect.right);
          expect(selectedItemRect.bottom).to.be.at.most(overlayRect.bottom);
        }

        it('should make selected item visible after open', function() {
          combobox.value = combobox.items[50];
          combobox.open();

          expectSelectedItemPositionToBeVisible();
        });

        it('should make selected item visible after reopen', function() {
          combobox.open();

          combobox.value = combobox.items[50];
          combobox.close();
          combobox.open();

          expectSelectedItemPositionToBeVisible();
        });
      });
    });
  </script>

</body>

</html>


text:
import cgi
import MySQLdb
import sys
print "Content-Type: text/plain\n\n"

_databaseInfo = dict(
  host   = "localhost",
  user   = "root",
  passwd = "password",
  db     = "library"
)
class DataBase:
	def __init__(self):
		try:
 			self.con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');

    			self.cur = con.cursor()
    			self.cur.execute("SELECT VERSION()")

   			self.ver = cur.fetchone()

   			print "Database version : %s " % ver

		except mdb.Error, e:

 			print "Error %d: %s" % (e.args[0],e.args[1])
    			sys.exit(1)

	def executeQuery(self,query):
		cur.execute(query)


text:
tzaffi.github.io
================

Thoughts on software, teaching, mathematics, and life in general


text:
import { Component, TemplateRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';

@Component({
  // eslint-disable-next-line @angular-eslint/component-selector
  selector: 'demo-modal-service-static',
  templateUrl: './service-template.html'
})
export class DemoModalServiceStaticComponent {
  modalRef?: BsModalRef;
  constructor(private modalService: BsModalService) {}

  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template);
  }
}


text:
package netutils

import (
	"crypto/tls"
	"crypto/x509"
	"strings"
	"testing"
	"time"
)

func TestGenerateCert(t *testing.T) {
	organization := "Organization"
	host := "localhost"
	validFor := 365 * 24 * time.Hour
	rsaBits := 512

	certBytes, keyBytes, err := GenerateCert(organization, host, validFor, rsaBits)

	if err != nil {
		t.Error(err)
	}

	if !strings.HasPrefix(string(certBytes), "-----BEGIN CERTIFICATE-----") {
		t.Error("Invalid certificate output")
	}

	if !strings.HasPrefix(string(keyBytes), "-----BEGIN RSA PRIVATE KEY-----") {
		t.Error("Invalid certificate output")
	}

	cert, err := tls.X509KeyPair(certBytes, keyBytes)

	if err != nil {
		t.Error(err)
	}

	x509Cert, err := x509.ParseCertificate(cert.Certificate[0])

	if err != nil {
		t.Error(err)
	}

	if x509Cert.Subject.Organization[0] != organization {
		t.Error("Invalid organization")
	}
}


text:
<?php

namespace flexibuild\phpsafe\gii\generators\module;

use flexibuild\phpsafe\gii\generators\GeneratorWithPhpsafeExtTrait;

class Generator extends \yii\gii\generators\module\Generator
{
    use GeneratorWithPhpsafeExtTrait;

    /**
     * @inheritdoc
     * @param \yii\gii\CodeFile $file
     */
    protected function isPhpSafe($file)
    {
        return preg_match('#[\\\\/]views[\\\\/]default[\\\\/]index\.php$#', $file->path);
    }
}


text:
function initProduct(productId, div) {

		calculatePrice(productId, div);

		$(div + ' select').change(function(e) { // select element changed
			calculatePrice(productId, div);
		});

		$(div + ' :radio').change(function(e) { // radio changed
			calculatePrice(productId, div);
		});

		$(div + ' :checkbox').change(function(e) { // radio changed
			calculatePrice(productId, div);
		});

	}

    function calculatePrice(productId, div) {

		var values = new Array();
		i = 0;
		$(div).find(':input').each(function(){
			if($(this).hasClass('attribute')) {
		        if($(this).is(':checkbox')) {
		        	var checkboxSelected = $(this).is(':checked');
		        	if(checkboxSelected==true) {
						values[i] = $(this).val();
						//console.log('checkbox ' + values[i]);
						i++;
					}

				} else if ($(this).is(':radio')) {
					var radioChecked = $(this).is(':checked');
					if(radioChecked==true) {
						values[i] = $(this).val();
						//console.log('radio ' + values[i]);
						i++;
					}
				} else {
				   if($(this).val()) {
				       values[i] = $(this).val();
				       //console.log('select ' + values[i]);
				       i++;
			       }

				}
			}

	});

	if(values.length==0) {
		return;
	}

	$(div).showLoading();

	$.ajax({
		 type: 'POST',
		 url: getContextPath() + '/shop/product/' + productId + '/calculatePrice.html',
		 dataType: 'json',
		 data:{"attributeIds":values},
		 cache:false,
		 error: function(e) {
			$(div).hideLoading();
			console.log('Error while loading price');

		 },
		 success: function(price) {
			 $(div).hideLoading();
			 //console.log('product price ' + price.finalPrice);
			 var displayPrice = '' + price.finalPrice + '';
			 if(price.discounted) {
				 displayPrice = '' + price.originalPrice + ' ' + price.finalPrice + '';
			 }
			 $('#productPrice').html(displayPrice);
		 }
	});

}


text:
import java.io.*;
import java.util.*;

public class WordCountMap {
    // minimum number of occurrences needed to be printed
    public static final int OCCURRENCES = 300;

    public static void main(String[] args)
            throws FileNotFoundException {
        System.out.println("This program displays the most");
        System.out.println("frequently occurring words from");
        System.out.println("the book Ulysses.");
        System.out.println();

        // read the book into a map
        Scanner in = new Scanner(new File("C:\\Users\\windoze\\Desktop\\ulysses.txt"));
        Map<String, Integer> wordCountMap = getCountMap(in);

        Set<String> boringWords = getBoringWords();
        for (String word : wordCountMap.keySet()) {
            if(!boringWords.contains(word) ) {
                int count = wordCountMap.get(word);
                if (count > OCCURRENCES) {
                    System.out.println(word + " occurs " +
                                       count + " times.");
                }
            }
        }
    }

    // Reads book text and returns a map from words to counts
    public static Map<String, Integer> getCountMap(Scanner in) {
        Map<String, Integer> wordCountMap =
                new TreeMap<String, Integer>();

        while (in.hasNext()) {
            String word = in.next().toLowerCase();
            if (!wordCountMap.containsKey(word)) {
                // never seen this word before
                wordCountMap.put(word, 1);
            } else {
                // seen this word before; increment count
                int count = wordCountMap.get(word);
                wordCountMap.put(word, count + 1);
            }
        }

        return wordCountMap;
    }

    public static Set<String> getBoringWords() {
        Set<String> boringWords = new HashSet<String>();
        boringWords.add("a");
        return boringWords;
    }
}


text:
package authn

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"time"
)
type asset struct {
	bytes []byte
	info  os.FileInfo
}

type bindataFileInfo struct {
	name    string
	size    int64
	mode    os.FileMode
	modTime time.Time
}

func (fi bindataFileInfo) Name() string {
	return fi.name
}
func (fi bindataFileInfo) Size() int64 {
	return fi.size
}
func (fi bindataFileInfo) Mode() os.FileMode {
	return fi.mode
}
func (fi bindataFileInfo) ModTime() time.Time {
	return fi.modTime
}
func (fi bindataFileInfo) IsDir() bool {
	return false
}
func (fi bindataFileInfo) Sys() interface{} {
	return nil
}

var _dataGithub_authTmpl = []byte(`

  <button type="button" onclick="location.href='{{.GithubWebUri}}/login/oauth/authorize?scope=user:email&client_id={{.ClientId}}'">Login with GitHub</button>
  <button type="button" onclick="location.href='{{.GithubWebUri}}/settings/applications'">Revoke access</button>

`)

func dataGithub_authTmplBytes() ([]byte, error) {
	return _dataGithub_authTmpl, nil
}

func dataGithub_authTmpl() (*asset, error) {
	bytes, err := dataGithub_authTmplBytes()
	if err != nil {
		return nil, err
	}

	info := bindataFileInfo{name: "data/github_auth.tmpl", size: 348, mode: os.FileMode(420), modTime: time.Unix(1, 0)}
	a := &asset{bytes: bytes, info: info}
	return a, nil
}

var _dataGoogle_authTmpl = []byte(`

	<button id="signinButton">Sign in with Google</button>

	<button id="signOutButton">Sign out</button>

`)

func dataGoogle_authTmplBytes() ([]byte, error) {
	return _dataGoogle_authTmpl, nil
}

func dataGoogle_authTmpl() (*asset, error) {
	bytes, err := dataGoogle_authTmplBytes()
	if err != nil {
		return nil, err
	}

	info := bindataFileInfo{name: "data/google_auth.tmpl", size: 2817, mode: os.FileMode(420), modTime: time.Unix(1, 0)}
	a := &asset{bytes: bytes, info: info}
	return a, nil
}

// Asset loads and returns the asset for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func Asset(name string) ([]byte, error) {
	cannonicalName := strings.Replace(name, "\\", "/", -1)
	if f, ok := _bindata[cannonicalName]; ok {
		a, err := f()
		if err != nil {
			return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err)
		}
		return a.bytes, nil
	}
	return nil, fmt.Errorf("Asset %s not found", name)
}

// MustAsset is like Asset but panics when Asset would return an error.
// It simplifies safe initialization of global variables.
func MustAsset(name string) []byte {
	a, err := Asset(name)
	if err != nil {
		panic("asset: Asset(" + name + "): " + err.Error())
	}

	return a
}

// AssetInfo loads and returns the asset info for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func AssetInfo(name string) (os.FileInfo, error) {
	cannonicalName := strings.Replace(name, "\\", "/", -1)
	if f, ok := _bindata[cannonicalName]; ok {
		a, err := f()
		if err != nil {
			return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err)
		}
		return a.info, nil
	}
	return nil, fmt.Errorf("AssetInfo %s not found", name)
}

// AssetNames returns the names of the assets.
func AssetNames() []string {
	names := make([]string, 0, len(_bindata))
	for name := range _bindata {
		names = append(names, name)
	}
	return names
}

// _bindata is a table, holding each asset generator, mapped to its name.
var _bindata = map[string]func() (*asset, error){
	"data/github_auth.tmpl": dataGithub_authTmpl,
	"data/google_auth.tmpl": dataGoogle_authTmpl,
}

// AssetDir returns the file names below a certain
// directory embedded in the file by go-bindata.
// For example if you run go-bindata on data/... and data contains the
// following hierarchy:
//     data/
//       foo.txt
//       img/
//         a.png
//         b.png
// then AssetDir("data") would return []string{"foo.txt", "img"}
// AssetDir("data/img") would return []string{"a.png", "b.png"}
// AssetDir("foo.txt") and AssetDir("notexist") would return an error
// AssetDir("") will return []string{"data"}.
func AssetDir(name string) ([]string, error) {
	node := _bintree
	if len(name) != 0 {
		cannonicalName := strings.Replace(name, "\\", "/", -1)
		pathList := strings.Split(cannonicalName, "/")
		for _, p := range pathList {
			node = node.Children[p]
			if node == nil {
				return nil, fmt.Errorf("Asset %s not found", name)
			}
		}
	}
	if node.Func != nil {
		return nil, fmt.Errorf("Asset %s not found", name)
	}
	rv := make([]string, 0, len(node.Children))
	for childName := range node.Children {
		rv = append(rv, childName)
	}
	return rv, nil
}

type bintree struct {
	Func     func() (*asset, error)
	Children map[string]*bintree
}
var _bintree = &bintree{nil, map[string]*bintree{
	"data": &bintree{nil, map[string]*bintree{
		"github_auth.tmpl": &bintree{dataGithub_authTmpl, map[string]*bintree{}},
		"google_auth.tmpl": &bintree{dataGoogle_authTmpl, map[string]*bintree{}},
	}},
}}

// RestoreAsset restores an asset under the given directory
func RestoreAsset(dir, name string) error {
	data, err := Asset(name)
	if err != nil {
		return err
	}
	info, err := AssetInfo(name)
	if err != nil {
		return err
	}
	err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755))
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())
	if err != nil {
		return err
	}
	err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())
	if err != nil {
		return err
	}
	return nil
}

// RestoreAssets restores an asset under the given directory recursively
func RestoreAssets(dir, name string) error {
	children, err := AssetDir(name)
	// File
	if err != nil {
		return RestoreAsset(dir, name)
	}
	// Dir
	for _, child := range children {
		err = RestoreAssets(dir, filepath.Join(name, child))
		if err != nil {
			return err
		}
	}
	return nil
}

func _filePath(dir, name string) string {
	cannonicalName := strings.Replace(name, "\\", "/", -1)
	return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...)
}


text:
package io.gatling.http.feeder

import io.gatling.commons.validation._
import io.gatling.core.feeder.RecordSeqFeederBuilder
import io.gatling.core.config.GatlingConfiguration
import io.gatling.core.util.Resource

/**
 * Feeder for [[http://www.sitemaps.org/protocol.html sitemap]] file format.
 */
trait SitemapFeederSupport {

  def sitemap(fileName: String)(implicit configuration: GatlingConfiguration): RecordSeqFeederBuilder[String] = sitemap(Resource.feeder(fileName))

  def sitemap(resource: Validation[Resource]): RecordSeqFeederBuilder[String] =
    resource match {
      case Success(res)     => RecordSeqFeederBuilder(SitemapParser.parse(res))
      case Failure(message) => throw new IllegalArgumentException(s"Could not locate sitemap file: $message")
    }
}