text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.groboclown.idea.p4ic.v2.server.connection;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import net.groboclown.idea.p4ic.config.ServerConfig;
import net.groboclown.idea.p4ic.server.RawServerExecutor;
import net.groboclown.idea.p4ic.server.ServerStoreService;
import net.groboclown.idea.p4ic.server.exceptions.P4InvalidConfigException;
import net.groboclown.idea.p4ic.v2.server.cache.ClientServerId;
import net.groboclown.idea.p4ic.v2.server.cache.UpdateGroup;
import net.groboclown.idea.p4ic.v2.server.cache.state.PendingUpdateState;
import net.groboclown.idea.p4ic.v2.server.cache.sync.ClientCacheManager;
import net.groboclown.idea.p4ic.v2.ui.alerts.ConfigurationProblemHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * The multi-threaded connections to the Perforce server for a specific client.
 * <p>
 * This is a future replacement for the {@link RawServerExecutor}, {@link ServerStoreService}, and
 * {@link net.groboclown.idea.p4ic.server.ServerStatus}.
 */
public class ServerConnection {
    private static final Logger LOG = Logger.getInstance(ServerConnection.class);
    private static final ThreadGroup CONNECTION_THREAD_GROUP = new ThreadGroup("Server Connection");
    private static final ThreadLocal<Boolean> THREAD_EXECUTION_ACTIVE = new ThreadLocal<Boolean>();
    private final Lock connectionLock = new ReentrantLock();
    private final BlockingQueue<UpdateAction> pendingUpdates = new LinkedBlockingDeque<UpdateAction>();
    private final Queue<UpdateAction> redo = new ArrayDeque<UpdateAction>();
    private final Lock redoLock = new ReentrantLock();
    private final AlertManager alertManager;
    private final ClientCacheManager cacheManager;
    private final ServerConfig config;
    private final ServerStatusController statusController;
    private final String clientName;
    private final Object clientExecLock = new Object();
    private final Thread background;
    private volatile boolean disposed = false;
    private boolean loadedPendingUpdateStates = false;
    @Nullable
    private ClientExec clientExec;

    public static void assertInServerConnection() {
        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        if (currentGroup != CONNECTION_THREAD_GROUP && THREAD_EXECUTION_ACTIVE.get() != Boolean.TRUE) {
            throw new IllegalStateException("Activity can only be run from within the ServerConnection action thread");
        }
    }

    public interface CreateUpdate {
        @NotNull
        Collection<PendingUpdateState> create(@NotNull ClientCacheManager mgr);
    }

    public interface CacheQuery<T> {
        T query(@NotNull ClientCacheManager mgr) throws InterruptedException;
    }

    public ServerConnection(@NotNull final AlertManager alertManager,
            @NotNull ClientServerId clientServerId, @NotNull ClientCacheManager cacheManager,
            @NotNull ServerConfig config, @NotNull ServerStatusController statusController) {
        this.alertManager = alertManager;
        this.cacheManager = cacheManager;
        this.config = config;
        this.statusController = statusController;
        this.clientName = clientServerId.getClientId();

        background = new Thread(new QueueRunner());
        background.setDaemon(false);
        background.setPriority(Thread.NORM_PRIORITY - 1);
        background.start();
    }

    public synchronized void postSetup(@NotNull Project project) {
        if (! loadedPendingUpdateStates) {
            queueUpdateActions(project, cacheManager.getCachedPendingUpdates());
            loadedPendingUpdateStates = true;
        }
    }

    public void dispose() {
        disposed = true;
        background.interrupt();
        synchronized (clientExecLock) {
            if (clientExec != null) {
                clientExec.dispose();
                clientExec = null;
            }
        }
    }

    public void queueAction(@NotNull Project project, @NotNull ServerUpdateAction action) {
        LOG.info("Queueing action for execution: " + action);
        pendingUpdates.add(new UpdateAction(project, action));
    }

    /**
     * Run the command within the current thread.  This will still block if another action
     * is happening within the other thread.
     *
     * @param action action to run
     */
    public void runImmediately(@NotNull Project project, @NotNull ServerUpdateAction action)
            throws InterruptedException {
        startImmediateAction();
        try {
            action.perform(getExec(project), cacheManager, ServerConnection.this, alertManager);
        } catch (P4InvalidConfigException e) {
            alertManager.addCriticalError(new ConfigurationProblemHandler(), e);
        } finally {
            stopImmediateAction();
        }
    }

    @Nullable
    public <T> T query(@NotNull Project project, @NotNull ServerQuery<T> query) throws InterruptedException {
        startImmediateAction();
        try {
            return query.query(getExec(project), cacheManager, ServerConnection.this, alertManager);
        } catch (P4InvalidConfigException e) {
            alertManager.addCriticalError(new ConfigurationProblemHandler(), e);
            return null;
        } finally {
            stopImmediateAction();
        }
    }

    /**
     * Retry running a command that failed.  This should usually be put back at the head
     * of the action queue.  It is sometimes necessary if the command fails due to a
     * login or config issue.
     *
     * @param action action
     */
    public void requeueAction(@NotNull Project project, @NotNull ServerUpdateAction action) {
        redoLock.lock();
        try {
            redo.add(new UpdateAction(project, action));
        } finally {
            redoLock.unlock();
        }
    }

    public boolean isWorkingOnline() {
        return statusController.isWorkingOnline();
    }

    public boolean isWorkingOffline() {
        return statusController.isWorkingOffline();
    }

    public void workOffline() {
        statusController.disconnect();
    }

    public void workOnline() {
        statusController.connect();
    }

    public void queueUpdates(@NotNull Project project, @NotNull CreateUpdate update) {
        final Collection<PendingUpdateState> updates = update.create(cacheManager);
        List<PendingUpdateState> nonNullUpdates = new ArrayList<PendingUpdateState>(updates.size());
        for (PendingUpdateState updateState : updates) {
            if (updateState != null) {
                cacheManager.addPendingUpdateState(updateState);
                nonNullUpdates.add(updateState);
            }
        }
        queueUpdateActions(project, nonNullUpdates);
    }

    public <T> T cacheQuery(@NotNull CacheQuery<T> q) throws InterruptedException {
        return q.query(cacheManager);
    }

    P4Exec2 getExec(@NotNull Project project) throws P4InvalidConfigException {
        if (disposed) {
            throw new IllegalStateException("connection disposed");
        }
        // double-check locking.  This is why clientExec must be volatile.
        synchronized (clientExecLock) {
            if (clientExec == null) {
                clientExec = new ClientExec(config, statusController, clientName);
            }
            return new P4Exec2(project, clientExec);
        }
    }

    private void queueUpdateActions(@NotNull Project project, @NotNull Collection<PendingUpdateState> updates) {
        UpdateGroup currentGroup = null;
        List<PendingUpdateState> currentGroupUpdates = null;
        for (PendingUpdateState update : updates) {
            // FIXME debug
            LOG.info("adding update state as action: " + update);

            if (currentGroup != null && !update.getUpdateGroup().equals(currentGroup)) {
                // new group, so add the old stuff and clear it out.
                if (!currentGroupUpdates.isEmpty()) {
                    queueAction(project,
                            currentGroup.getServerUpdateActionFactory().create(currentGroupUpdates));
                }
                currentGroupUpdates = null;
            }
            currentGroup = update.getUpdateGroup();
            if (currentGroupUpdates == null) {
                currentGroupUpdates = new ArrayList<PendingUpdateState>();
            }
            currentGroupUpdates.add(update);
        }
        if (currentGroup != null && currentGroupUpdates != null && !currentGroupUpdates.isEmpty()) {
            queueAction(project,
                    currentGroup.getServerUpdateActionFactory().create(currentGroupUpdates));
        }
    }

    void goOffline() {
        synchronized (clientExecLock) {
            if (clientExec != null) {
                clientExec.dispose();
                clientExec = null;
            }
        }
    }

    private void startImmediateAction() throws InterruptedException {
        connectionLock.lock();
        try {
            // FIXME make timeout configurable
            alertManager.waitForNoCriticalErrors(-1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            connectionLock.unlock();
            throw e;
        }
        THREAD_EXECUTION_ACTIVE.set(Boolean.TRUE);
    }

    private void stopImmediateAction() {
        THREAD_EXECUTION_ACTIVE.remove();
        connectionLock.unlock();
    }

    class QueueRunner implements Runnable {
        @Override
        public void run() {
            try {
                while (!disposed) {
                    // Wait for something to do first
                    UpdateAction action;
                    redoLock.lock();
                    try {
                        action = redo.poll();
                    } finally {
                        redoLock.unlock();
                    }
                    if (action == null) {
                        try {
                            // FIXME debug
                            LOG.info("Polling pending updates for action");
                            action = pendingUpdates.take();
                        } catch (InterruptedException e) {
                            // This triggers us to check for a disposed state.
                            LOG.info(e);
                            continue;
                        }
                    }

                    // wait for us to come online
                    // FIXME make configurable
                    try {
                        // FIXME debug
                        LOG.info("waiting for server to come online");
                        statusController.waitForOnline(-1, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                        // need to reloop to check for disposed state, but first re-insert the update
                        LOG.info(e);
                        redoLock.lock();
                        try {
                            redo.add(action);
                        } finally {
                            redoLock.unlock();
                        }
                        continue;
                    }

                    // Now wait for the alerts to finish up.
                    // FIXME make the wait time configurable
                    connectionLock.lock();
                    try {
                        // FIXME debug
                        LOG.info("waiting for no critical errors");
                        alertManager.waitForNoCriticalErrors(-1, TimeUnit.MINUTES);
                    } catch (InterruptedException e) {
                        connectionLock.unlock();

                        // need to reloop to check for disposed state, but first re-insert the update
                        LOG.info(e);
                        redoLock.lock();
                        try {
                            redo.add(action);
                        } finally {
                            redoLock.unlock();
                        }
                        continue;
                    }

                    if (statusController.isWorkingOffline()) {
                        // Went offline, probably due to the waited-on critical error.
                        // need to reloop to check for disposed state, but first re-insert the update
                        LOG.info("Went offline - retrying execution loop");
                        redoLock.lock();
                        try {
                            redo.add(action);
                        } finally {
                            redoLock.unlock();
                        }
                        continue;
                    }

                    // We now have something to do, and we can perform the action.
                    // Note that it's possible for another critical error to pop up in this small
                    // window of time; that's currently considered an acceptable situation.
                    // Even if it does, it would be because of a separate server configuration,
                    // and thus would be unrelated to this configuration's execution; we know this
                    // because all executions of this connection are single-threaded.

                    try {
                        // FIXME debug
                        LOG.info("Performing action " + action);
                        action.action
                                .perform(getExec(action.project), cacheManager, ServerConnection.this, alertManager);
                    } catch (P4InvalidConfigException e) {
                        alertManager.addCriticalError(new ConfigurationProblemHandler(), e);
                    } catch (InterruptedException e) {
                        // Do not requeue the action
                        LOG.info(e);
                    } finally {
                        connectionLock.unlock();
                    }
                }
            } catch (Exception e) {
                LOG.error(e);
            }
        }
    }

    static class UpdateAction {
        final ServerUpdateAction action;
        final Project project;

        UpdateAction(@NotNull Project project, @NotNull ServerUpdateAction action) {
            this.action = action;
            this.project = project;
        }

        @Override
        public String toString() {
            return "Action " + action;
        }
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client.impl;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;

/**
 * Parses command line arguments
 *
 * @author bjorncs
 */
class CliArguments {

    private static final Options optionsDefinition = createOptions();

    private static final String BENCHMARK_OPTION = "benchmark";
    private static final String CA_CERTIFICATES_OPTION = "ca-certificates";
    private static final String CERTIFICATE_OPTION = "certificate";
    private static final String CONNECTIONS_OPTION = "connections";
    private static final String DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION = "disable-ssl-hostname-verification";
    private static final String DRYRUN_OPTION = "dryrun";
    private static final String SPEED_TEST_OPTION = "speed-test";
    private static final String TEST_PAYLOAD_SIZE_OPTION = "test-payload-size";
    private static final String ENDPOINT_OPTION = "endpoint";
    private static final String FILE_OPTION = "file";
    private static final String HEADER_OPTION = "header";
    private static final String HELP_OPTION = "help";
    private static final String MAX_STREAMS_PER_CONNECTION = "max-streams-per-connection";
    private static final String PRIVATE_KEY_OPTION = "private-key";
    private static final String ROUTE_OPTION = "route";
    private static final String TIMEOUT_OPTION = "timeout";
    private static final String TRACE_OPTION = "trace";
    private static final String VERBOSE_OPTION = "verbose";
    private static final String SHOW_ERRORS_OPTION = "show-errors";
    private static final String SHOW_ALL_OPTION = "show-all";
    private static final String SILENT_OPTION = "silent";
    private static final String VERSION_OPTION = "version";
    private static final String STDIN_OPTION = "stdin";
    private static final String DOOM_OPTION = "max-failure-seconds";
    private static final String PROXY_OPTION = "proxy";

    private final CommandLine arguments;

    private CliArguments(CommandLine arguments) throws CliArgumentsException {
        validateArgumentCombination(arguments);
        this.arguments = arguments;
    }

    static CliArguments fromRawArgs(String[] rawArgs) throws CliArgumentsException {
        CommandLineParser parser = new DefaultParser();
        try {
            return new CliArguments(parser.parse(optionsDefinition, rawArgs));
        } catch (ParseException e) {
            throw new CliArgumentsException(e);
        }
    }

    private static void validateArgumentCombination(CommandLine args) throws CliArgumentsException {
        if (!args.hasOption(HELP_OPTION) && !args.hasOption(VERSION_OPTION)) {
            if (!args.hasOption(ENDPOINT_OPTION)) {
                throw new CliArgumentsException("Endpoint must be specified");
            }
            if (args.hasOption(SPEED_TEST_OPTION)) {
                if (   args.hasOption(FILE_OPTION) && (args.hasOption(STDIN_OPTION) || args.hasOption(TEST_PAYLOAD_SIZE_OPTION))
                    || args.hasOption(STDIN_OPTION) && args.hasOption(TEST_PAYLOAD_SIZE_OPTION)) {
                    throw new CliArgumentsException(String.format("At most one of '%s', '%s' and '%s' may be specified", FILE_OPTION, STDIN_OPTION, TEST_PAYLOAD_SIZE_OPTION));
                }
            }
            else {
                if (args.hasOption(FILE_OPTION) == args.hasOption(STDIN_OPTION)) {
                    throw new CliArgumentsException(String.format("Exactly one of '%s' and '%s' must be specified", FILE_OPTION, STDIN_OPTION));
                }
                if (args.hasOption(TEST_PAYLOAD_SIZE_OPTION)) {
                    throw new CliArgumentsException(String.format("Option '%s' can only be specified together with '%s'", TEST_PAYLOAD_SIZE_OPTION, SPEED_TEST_OPTION));
                }
            }
            if (args.hasOption(CERTIFICATE_OPTION) != args.hasOption(PRIVATE_KEY_OPTION)) {
                throw new CliArgumentsException(
                        String.format("Both '%s' and '%s' must be specified together", CERTIFICATE_OPTION, PRIVATE_KEY_OPTION));
            }
        } else if (args.hasOption(HELP_OPTION) && args.hasOption(VERSION_OPTION)) {
            throw new CliArgumentsException(String.format("Cannot specify both '%s' and '%s'", HELP_OPTION, VERSION_OPTION));
        }
    }

    URI endpoint() throws CliArgumentsException {
        try {
            return ((URL) arguments.getParsedOptionValue(ENDPOINT_OPTION)).toURI();
        } catch (ParseException | URISyntaxException e) {
            throw new CliArgumentsException("Invalid endpoint: " + e.getMessage(), e);
        }
    }

    boolean helpSpecified() { return has(HELP_OPTION); }

    boolean versionSpecified() { return has(VERSION_OPTION); }

    OptionalInt connections() throws CliArgumentsException {  return intValue(CONNECTIONS_OPTION); }

    OptionalInt maxStreamsPerConnection() throws CliArgumentsException { return intValue(MAX_STREAMS_PER_CONNECTION); }

    Optional<CertificateAndKey> certificateAndKey() throws CliArgumentsException {
        Path certificateFile = fileValue(CERTIFICATE_OPTION).orElse(null);
        Path privateKeyFile = fileValue(PRIVATE_KEY_OPTION).orElse(null);
        if (privateKeyFile == null && certificateFile == null) return Optional.empty();
        return Optional.of(new CertificateAndKey(certificateFile, privateKeyFile));
    }

    Optional<Path> caCertificates() throws CliArgumentsException { return fileValue(CA_CERTIFICATES_OPTION); }

    Optional<Path> inputFile() throws CliArgumentsException {
        return fileValue(FILE_OPTION);
    }

    Map<String, String> headers() throws CliArgumentsException {
        String[] rawArguments = arguments.getOptionValues(HEADER_OPTION);
        if (rawArguments == null) return Collections.emptyMap();
        Map<String, String> headers = new HashMap<>();
        for (String rawArgument : rawArguments) {
            if (rawArgument.startsWith("\"") || rawArgument.startsWith("'")) {
                rawArgument = rawArgument.substring(1);
            }
            if (rawArgument.endsWith("\"") || rawArgument.endsWith("'")) {
                rawArgument = rawArgument.substring(0, rawArgument.length() - 1);
            }
            int colonIndex = rawArgument.indexOf(':');
            if (colonIndex == -1) throw new CliArgumentsException("Invalid header: '" + rawArgument + "'");
            headers.put(rawArgument.substring(0, colonIndex), rawArgument.substring(colonIndex + 1).trim());
        }
        return Collections.unmodifiableMap(headers);
    }

    boolean sslHostnameVerificationDisabled() { return has(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION); }

    boolean benchmarkModeEnabled() { return has(BENCHMARK_OPTION); }

    boolean showProgress() { return ! has(SILENT_OPTION); }

    boolean showErrors() { return has(SHOW_ERRORS_OPTION) || has(SHOW_ALL_OPTION); }

    boolean showSuccesses() { return has(SHOW_ALL_OPTION); }

    Optional<String> route() { return stringValue(ROUTE_OPTION); }

    OptionalInt traceLevel() throws CliArgumentsException { return intValue(TRACE_OPTION); }

    OptionalInt doomSeconds() throws CliArgumentsException { return intValue(DOOM_OPTION); }

    Optional<Duration> timeout() throws CliArgumentsException {
        OptionalDouble timeout = doubleValue(TIMEOUT_OPTION);
        return timeout.isPresent()
                ? Optional.of(Duration.ofMillis((long)(timeout.getAsDouble()*1000)))
                : Optional.empty();
    }

    boolean verboseSpecified() { return has(VERBOSE_OPTION); }

    boolean readFeedFromStandardInput() { return has(STDIN_OPTION); }

    boolean dryrunEnabled() { return has(DRYRUN_OPTION); }

    boolean speedTest() { return has(SPEED_TEST_OPTION); }

    OptionalInt testPayloadSize() throws CliArgumentsException { return intValue(TEST_PAYLOAD_SIZE_OPTION); }

    Optional<URI> proxy() throws CliArgumentsException {
        try {
            URL url = (URL) arguments.getParsedOptionValue(PROXY_OPTION);
            if (url == null) return Optional.empty();
            return Optional.of(url.toURI());
        } catch (ParseException | URISyntaxException e) {
            throw new CliArgumentsException("Invalid proxy: " + e.getMessage(), e);
        }
    }

    private OptionalInt intValue(String option) throws CliArgumentsException {
        try {
            Number number = (Number) arguments.getParsedOptionValue(option);
            return number != null ? OptionalInt.of(number.intValue()) : OptionalInt.empty();
        } catch (ParseException e) {
            throw newInvalidValueException(option, e);
        }
    }

    private Optional<Path> fileValue(String option) throws CliArgumentsException {
        try {
            File certificateFile = (File) arguments.getParsedOptionValue(option);
            if (certificateFile == null) return Optional.empty();
            return Optional.of(certificateFile.toPath());
        } catch (ParseException e) {
            throw newInvalidValueException(option, e);
        }
    }

    private Optional<String> stringValue(String option) { return Optional.ofNullable(arguments.getOptionValue(option)); }

    private OptionalDouble doubleValue(String option) throws CliArgumentsException {
        try {
            Number number = (Number) arguments.getParsedOptionValue(option);
            return number != null ? OptionalDouble.of(number.doubleValue()) : OptionalDouble.empty();
        } catch (ParseException e) {
            throw newInvalidValueException(option, e);
        }
    }

    private boolean has(String option) { return arguments.hasOption(option); }

    private static CliArgumentsException newInvalidValueException(String option, ParseException cause) {
        return new CliArgumentsException(String.format("Invalid value for '%s': %s", option, cause.getMessage()), cause);
    }

    private static Options createOptions() {
        return new Options()
                .addOption(Option.builder()
                        .longOpt(HELP_OPTION)
                        .build())
                .addOption(Option.builder()
                        .longOpt(VERSION_OPTION)
                        .build())
                .addOption(Option.builder()
                        .longOpt(ENDPOINT_OPTION)
                        .desc("URI to feed endpoint")
                        .hasArg()
                        .type(URL.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(HEADER_OPTION)
                        .desc("HTTP header on the form 'Name: value'")
                        .hasArgs()
                        .build())
                .addOption(Option.builder()
                        .longOpt(FILE_OPTION)
                        .type(File.class)
                        .desc("Path to feed file in JSON format")
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(CONNECTIONS_OPTION)
                        .desc("Number of concurrent HTTP/2 connections")
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(MAX_STREAMS_PER_CONNECTION)
                        .desc("Maximum number of concurrent streams per HTTP/2 connection")
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(CERTIFICATE_OPTION)
                        .desc("Path to PEM encoded X.509 certificate file")
                        .type(File.class)
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(PRIVATE_KEY_OPTION)
                        .desc("Path to PEM/PKCS#8 encoded private key file")
                        .type(File.class)
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(CA_CERTIFICATES_OPTION)
                        .desc("Path to file containing CA X.509 certificates encoded as PEM")
                        .type(File.class)
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION)
                        .desc("Disable SSL hostname verification")
                        .build())
                .addOption(Option.builder()
                        .longOpt(BENCHMARK_OPTION)
                        .desc("Print statistics to stdout when done")
                        .build())
                .addOption(Option.builder()
                        .longOpt(ROUTE_OPTION)
                        .desc("Target Vespa route for feed operations")
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(TIMEOUT_OPTION)
                        .desc("Feed operation timeout (in seconds)")
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(TRACE_OPTION)
                        .desc("The trace level of network traffic. Disabled by default (=0)")
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                                 .longOpt(STDIN_OPTION)
                                 .desc("Read JSON input from standard input")
                                 .build())
                .addOption(Option.builder()
                        .longOpt(DOOM_OPTION)
                        .desc("Exit if specified number of seconds ever pass without any successful operations. Disabled by default")
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(DRYRUN_OPTION)
                        .desc("Let each operation succeed after " + DryrunCluster.DELAY.toMillis() + "ms, instead of sending it across the network ")
                        .build())
                .addOption(Option.builder()
                        .longOpt(SPEED_TEST_OPTION)
                        .desc("Perform a network speed test, where the server immediately responds to each feed operation with a successful response. Requires Vespa version ≥ 8.35 on the server")
                        .build())
                .addOption(Option.builder()
                        .longOpt(TEST_PAYLOAD_SIZE_OPTION)
                        .desc("Document JSON test payload size in bytes, for use with --speed-test; requires --file and -stdin to not be set; default is 1024")
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(VERBOSE_OPTION)
                        .desc("Print stack traces on errors")
                        .build())
                .addOption(Option.builder()
                        .longOpt(SILENT_OPTION)
                        .desc("Disable periodic status printing to stderr")
                        .build())
                .addOption(Option.builder()
                        .longOpt(SHOW_ERRORS_OPTION)
                        .desc("Print every feed operation failure")
                        .build())
                .addOption(Option.builder()
                        .longOpt(SHOW_ALL_OPTION)
                        .desc("Print the result of every feed operation")
                        .build())
                .addOption(Option.builder()
                        .longOpt(PROXY_OPTION)
                        .desc("URI to proxy endpoint")
                        .hasArg()
                        .type(URL.class)
                        .build());
    }

    void printHelp(OutputStream out) {
        HelpFormatter formatter = new HelpFormatter();
        PrintWriter writer = new PrintWriter(out);
        formatter.printHelp(
                writer,
                formatter.getWidth(),
                "vespa-feed-client <options>",
                "Vespa feed client",
                optionsDefinition,
                formatter.getLeftPadding(),
                formatter.getDescPadding(),
                "");
        writer.flush();
    }

    static class CliArgumentsException extends Exception {
        CliArgumentsException(String message, Throwable cause) { super(message, cause); }
        CliArgumentsException(Throwable cause) { super(cause.getMessage(), cause); }
        CliArgumentsException(String message) { super(message); }
    }

    static class CertificateAndKey {
        final Path certificateFile;
        final Path privateKeyFile;

        CertificateAndKey(Path certificateFile, Path privateKeyFile) {
            this.certificateFile = certificateFile;
            this.privateKeyFile = privateKeyFile;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
    <meta charset="UTF-8">
    <title>Event Reg</title>
    <link rel="stylesheet" href="bower_components/html5-boilerplate/css/normalize.css">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/css/main.css">
    <link rel="stylesheet" type="text/css" media="all"
          href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/smoothness/jquery-ui.css"    />

Date:
<input id="eventDate" type="text" date-picker/>

Text to Copy: <input type="text" ng-model="text"/>

{{text}}


text:
using System.Web;
using System.Web.Mvc;

namespace TelerikAcademy.ForumSystem.Web
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}


text:
from tests.unit import unittest
from tests.unit import AWSMockServiceTestCase

from boto.ec2.autoscale import AutoScaleConnection
from boto.ec2.autoscale.group import AutoScalingGroup

class TestAutoScaleGroup(AWSMockServiceTestCase):
    connection_class = AutoScaleConnection

    def setUp(self):
        super(TestAutoScaleGroup, self).setUp()

    def default_body(self):
        return """
            <CreateLaunchConfigurationResponse>
              <ResponseMetadata>
                <RequestId>requestid</RequestId>
              </ResponseMetadata>
            </CreateLaunchConfigurationResponse>
        """

    def test_autoscaling_group_with_termination_policies(self):
        self.set_http_response(status_code=200)
        autoscale = AutoScalingGroup(
            name='foo', launch_config='lauch_config',
            min_size=1, max_size=2,
            termination_policies=['OldestInstance', 'OldestLaunchConfiguration'])
        self.service_connection.create_auto_scaling_group(autoscale)
        self.assert_request_parameters({
            'Action': 'CreateAutoScalingGroup',
            'AutoScalingGroupName': 'foo',
            'LaunchConfigurationName': 'lauch_config',
            'MaxSize': 2,
            'MinSize': 1,
            'TerminationPolicies.member.1': 'OldestInstance',
            'TerminationPolicies.member.2': 'OldestLaunchConfiguration',
        }, ignore_params_values=['Version'])

class TestParseAutoScaleGroupResponse(AWSMockServiceTestCase):
    connection_class = AutoScaleConnection

    def default_body(self):
        return """
          <DescribeAutoScalingGroupsResult>
             <AutoScalingGroups>
               <member>
                 <Tags/>
                 <SuspendedProcesses/>
                 <AutoScalingGroupName>test_group</AutoScalingGroupName>
                 <HealthCheckType>EC2</HealthCheckType>
                 <CreatedTime>2012-09-27T20:19:47.082Z</CreatedTime>
                 <EnabledMetrics/>
                 <LaunchConfigurationName>test_launchconfig</LaunchConfigurationName>
                 <Instances>
                   <member>
                     <HealthStatus>Healthy</HealthStatus>
                     <AvailabilityZone>us-east-1a</AvailabilityZone>
                     <InstanceId>i-z118d054</InstanceId>
                     <LaunchConfigurationName>test_launchconfig</LaunchConfigurationName>
                     <LifecycleState>InService</LifecycleState>
                   </member>
                 </Instances>
                 <DesiredCapacity>1</DesiredCapacity>
                 <AvailabilityZones>
                   <member>us-east-1c</member>
                   <member>us-east-1a</member>
                 </AvailabilityZones>
                 <LoadBalancerNames/>
                 <MinSize>1</MinSize>
                 <VPCZoneIdentifier/>
                 <HealthCheckGracePeriod>0</HealthCheckGracePeriod>
                 <DefaultCooldown>300</DefaultCooldown>
                 <AutoScalingGroupARN>myarn</AutoScalingGroupARN>
                 <TerminationPolicies>
                   <member>OldestInstance</member>
                   <member>OldestLaunchConfiguration</member>
                 </TerminationPolicies>
                 <MaxSize>2</MaxSize>
               </member>
             </AutoScalingGroups>
          </DescribeAutoScalingGroupsResult>
        """

    def test_get_all_groups_is_parsed_correctly(self):
        self.set_http_response(status_code=200)
        response = self.service_connection.get_all_groups(names=['test_group'])
        self.assertEqual(len(response), 1, response)
        as_group = response[0]
        self.assertEqual(as_group.availability_zones, ['us-east-1c', 'us-east-1a'])
        self.assertEqual(as_group.default_cooldown, 300)
        self.assertEqual(as_group.desired_capacity, 1)
        self.assertEqual(as_group.enabled_metrics, [])
        self.assertEqual(as_group.health_check_period, 0)
        self.assertEqual(as_group.health_check_type, 'EC2')
        self.assertEqual(as_group.launch_config_name, 'test_launchconfig')
        self.assertEqual(as_group.load_balancers, [])
        self.assertEqual(as_group.min_size, 1)
        self.assertEqual(as_group.max_size, 2)
        self.assertEqual(as_group.name, 'test_group')
        self.assertEqual(as_group.suspended_processes, [])
        self.assertEqual(as_group.tags, [])
        self.assertEqual(as_group.termination_policies,
                         ['OldestInstance', 'OldestLaunchConfiguration'])

class TestDescribeTerminationPolicies(AWSMockServiceTestCase):
    connection_class = AutoScaleConnection

    def default_body(self):
        return """
          <DescribeTerminationPolicyTypesResponse>
            <DescribeTerminationPolicyTypesResult>
              <TerminationPolicyTypes>
                <member>ClosestToNextInstanceHour</member>
                <member>Default</member>
                <member>NewestInstance</member>
                <member>OldestInstance</member>
                <member>OldestLaunchConfiguration</member>
              </TerminationPolicyTypes>
            </DescribeTerminationPolicyTypesResult>
            <ResponseMetadata>
              <RequestId>requestid</RequestId>
            </ResponseMetadata>
          </DescribeTerminationPolicyTypesResponse>
        """

    def test_autoscaling_group_with_termination_policies(self):
        self.set_http_response(status_code=200)
        response = self.service_connection.get_termination_policies()
        self.assertListEqual(
            response,
            ['ClosestToNextInstanceHour', 'Default',
             'NewestInstance', 'OldestInstance', 'OldestLaunchConfiguration'])

if __name__ == '__main__':
    unittest.main()


text:
@interface SFStyleKitTests : XCTestCase

@end

@implementation SFStyleKitTests

- (NSDictionary *)dataFromJSONFileNamed:(NSString *)fileName
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSError *error;
    NSDictionary *json= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    return json;
}

- (void)testLoadUser
{
    SFStyle *style = [SFStyle sharedInstance];
}

@end


text:
GTDPI
=====

GmailThis! [Dangerous Penguins Inc.](http://dangerouspenguins.com/)

GmailThis! Dangerous Penguins Inc. henceforth referred to as GTDPI - Is a bookmarklet based on GmailThis! http://www.contrapants.org/2005/07/gmailthis.html  and GmailThis! for bookmarking http://nikak.blogspot.com/2005/12/txt-gmailthis-modified-for-bookmarking.html

GTDPI is essentially a very quick way to send a link through gmail. After clicking the bookmark the following happens;

1: A new window will pop up

2: The 'To' Field will be populated as you configure it to in the bookmarklet (just edit targetEmailAddress)

3: The 'Subject' of the email filled out as the title of your current webpage followed by "--- (bookmark)" to make future searching more easy.

4: The email 'Body' is whatever text you have highlighted followed by the URL of the current page.

Shortly after you click send the window will disappear.

What's different about this and other GmailThis! Variations? The Java Script has been cleaned up and formatted to make it easier to customize and there is also a bugfix that allows the bookmarklet work on all page titles. Previously, some titles with special characters would fail to work.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <item name="iv_image" type="id"></item>
    <item name="btn_comment" type="id"></item>
    <item name="btn_retry" type="id"></item>
    <item name="btn_webview" type="id"></item>
    <item name="vp_viewpager" type="id"/>
    <item name="titleDivider" type="id"/>

</resources>


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>IFWebViewController Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				SCFFLD

				innerfunction

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/allowedExternalURLs">allowedExternalURLs</option>

		<option value="//api/name/backgroundColor">backgroundColor</option>

		<option value="//api/name/content">content</option>

		<option value="//api/name/contentURL">contentURL</option>

		<option value="//api/name/loadExternalLinks">loadExternalLinks</option>

		<option value="//api/name/loadingImage">loadingImage</option>

		<option value="//api/name/opaque">opaque</option>

		<option value="//api/name/scrollViewBounces">scrollViewBounces</option>

		<option value="//api/name/showLoadingIndicator">showLoadingIndicator</option>

		<option value="//api/name/useHTMLTitle">useHTMLTitle</option>

	</optgroup>

	<optgroup label="Instance Methods">

		<option value="//api/name/afterIOCConfiguration:">- afterIOCConfiguration:</option>

	</optgroup>

</select>

IFWebViewController Class Reference

	Inherits from
	IFViewController : UIViewController

	Conforms to
	IFMessageReceiver
UIWebViewDelegate

	Declared in
	IFWebViewController.h
IFWebViewController.m

Overview

A configurable web view for display HTML etc.
The class implements the IFMessageReceiver protocol and responds to the following message:
- load: Load new content into the web view. The message must have a content parameter.
See the component’s content property.

Other Methods

  loadingImage

An image to be displayed whilst the initial page loads.

@property (nonatomic, strong) UIImage *loadingImage

Discussion

An image to be displayed whilst the initial page loads.

Declared In

IFWebViewController.h

  showLoadingIndicator

Whether to display a loading indicator.

@property (nonatomic, assign) BOOL showLoadingIndicator

Discussion

Whether to display a loading indicator.

Declared In

IFWebViewController.h

  loadExternalLinks

A flag indicating whether to load external links within the web view.

@property (nonatomic, assign) BOOL loadExternalLinks

Discussion

A flag indicating whether to load external links within the web view.

Declared In

IFWebViewController.h

  useHTMLTitle

A flag indicating whether the view controller should use the title of the loaded HTML page as its title.

@property (nonatomic, assign) BOOL useHTMLTitle

Discussion

A flag indicating whether the view controller should use the title of the loaded HTML page as its title.

Declared In

IFWebViewController.h

  backgroundColor

The view background colour.

@property (nonatomic, strong) UIColor *backgroundColor

Discussion

The view background colour.

Declared In

IFWebViewController.h

  opaque

Whether the webview is opaque. iOS only property.

@property (nonatomic, assign) BOOL opaque

Discussion

Whether the webview is opaque. iOS only property.

Declared In

IFWebViewController.h

  scrollViewBounces

Whether the webview bounces during scroll. iOS only property.

@property (nonatomic, assign) BOOL scrollViewBounces

Discussion

Whether the webview bounces during scroll. iOS only property.

Declared In

IFWebViewController.h

  allowedExternalURLs

A list of allowed external URLs.

@property (nonatomic, strong) NSArray *allowedExternalURLs

Discussion

A list of allowed external URLs.

Declared In

IFWebViewController.h

  contentURL

A URL to load content from. Only called if no content is directly specified.

@property (nonatomic, strong) NSString *contentURL

Discussion

A URL to load content from. Only called if no content is directly specified.

Declared In

IFWebViewController.h

  content

The web view content. May be specified using a string or a URI resource.

@property (nonatomic, strong) id content

Discussion

The web view content. May be specified using a string or a URI resource.

Declared In

IFWebViewController.h

Other Methods

– afterIOCConfiguration:

Called immediately after the object is configured via dependency injection.

- (void)afterIOCConfiguration:(id)configuration

Parameters

						configuration

The object’s configuration.

Discussion

Called immediately after the object is configured via dependency injection.

Declared In

IFIOCConfigurationAware.h

Copyright © 2017 innerfunction. All rights reserved. Updated: 2017-02-08

Generated by appledoc 2.2.1 (build 1334).


text:
(function(window, undefined) {

	if (window.Aloha === undefined || window.Aloha === null) {
		var Aloha = window.Aloha = {};
	}

	/*
		This is a minimal Aloha Editor configuration

		In this Aloha Editor Demo Demo we add a custom plugin.
		This plugin is located in our own specific plugin bundle.
	*/
	Aloha.settings = {
		logLevels: { 'error': true, 'warn': true, 'info': true, 'debug': true, 'deprecated': true },
		locale: 'en',
		bundles: {
			// Path for custom bundle relative from Aloha.settings.baseUrl usually path of aloha.js
			cmsplugin: '../demo/demo-app/app/aloha-plugins'
		}
	};
})(window);


text:
{{{
  "title": "Migrating a PHP Application to AppFog v2",
  "date": "10-28-2015",
  "author": "Ben Heisel",
  "attachments": [],
  "related-products" : [],
  "contentIsHTML": false,
  "sticky": true
}}}

### IMPORTANT

This document is for users of AppFog v1 for migration to the next generation of AppFog that is located in CenturyLink Cloud Control Portal.

Before deleting any applications or services on AppFog v1 ensure you have local copies. Once apps and services are deleted it is **permanent**. We will not be able to provide a backup.

When migration is complete your billing subscription can be canceled from the [Account](https://console.appfog.com/#account) page of the web console. Please be sure to cancel your subscription as we are not aware when individual user migration is complete. The billing system will not automatically prorate the subscription and issue a refund. If applicable, please open a [Support Ticket](https://support.appfog.com/tickets/new) or email support@appfog.com to receive a prorated refund of your subscription.

### PHP Migration
The AppFog v2 PHP buildpack default differs from AppFog v1 configuration. This article provides some options for customizing the configuration.  More documentaion on modifying the PHP buildpack can be found at https://github.com/cloudfoundry/php-buildpack/blob/master/docs/config.md.

### PHP Version
The PHP buildpack defaults to version 5.5. To use a different version create a `.bp-config/options.json` file in the application's root directory and use the following variable:
```
{
"PHP_VERSION" : "{PHP_56_LATEST}"
}
```
The default PHP buildpack does not support PHP 5.3, and soon will not support PHP 5.4. This is because both PHP versions are no longer supported. AppFog developers have created a custom buildpack to support PHP 5.3 and 5.4 on AppFog v2. To use PHP 5.3 or 5.4 specify the version as described above and include the custom buildpack when pushing your app:
`cf push <appname> -b https://github.com/CenturyLinkCloud/php-buildpack#af_custom_php`. When using the PHP custom buildpack only predefined environment variables can be utilized. This means user set environment variables will not be available to the deployed PHP application. The VCAP_SERVICES environment variable is available for use connecting to an AppFog marketplace service offering. This buildpack commit lists the [available environment variables](https://github.com/CenturyLinkCloud/php-buildpack/commit/6bd12f73bc68950856e67cae9a08c4d89c2dfefc) defined in the custom buildpack.

### .htaccess
* AppFog v2 allows for the use of an `.htaccess` file in the root of your application for URL rewriting: http://docs.cloudfoundry.org/buildpacks/php/gsg-php-usage.html.

### .user.ini
* Users can modify the default settings by adding a `.user.ini` file to their applicaiton root directory.
* The AppFog v2 PHP buildpack default is short_open_tag = Off. AppFog v1 set this value as "On". With the short_open_tag set to "Off" users will receive a 500 error and AppFog will read the code as plain text if their file reads as
```
<?
echo "Hello World";
?>
```
instead of
```
<?php
echo "Hello World";
?>
```
### PHP Extensions
* AppFog v1 made several PHP extensions available that are not enabled by default with the AppFog v2 PHP buildpack. To enable PHP extensions with the buildpack, create a `.bp-config/options.json` file in the application's root directory and include extensions to enable. This is not a complete list, but these are some common extensions enabled on AppFog v1 that you may want to enable on AppFog v2:
```
{
"PHP_EXTENSIONS": ["pdo", "pdo_mysql", "mysqli", "mysql", "mbstring", "mcrypt", "gd", "zip", "curl", "openssl", "sockets", "pdo_pgsql", "pdo_sqlite", "pgsql", "mongo"]
}
```
### VCAP_SERVICES
The VCAP_SERVICES environment varialbe is available on AppFog v2. Some of the fields are slightly different than AppFog v1. Here is an example to connect to a MySQL instance:
```
$services = json_decode($_ENV['VCAP_SERVICES'], true);
$service = $services['ctl_mysql'][0];
define('DB_NAME', $service['credentials']['dbname']);
define('DB_USER', $service['credentials']['username']);
define('DB_PASSWORD', $service['credentials']['password']);
define('DB_HOST', $service['credentials']['host'] . ':' . $service['credentials']['port']);
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '')
```


text:
package voicenavigator

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// BeginDialogue invokes the voicenavigator.BeginDialogue API synchronously
func (client *Client) BeginDialogue(request *BeginDialogueRequest) (response *BeginDialogueResponse, err error) {
	response = CreateBeginDialogueResponse()
	err = client.DoAction(request, response)
	return
}

// BeginDialogueWithChan invokes the voicenavigator.BeginDialogue API asynchronously
func (client *Client) BeginDialogueWithChan(request *BeginDialogueRequest) (<-chan *BeginDialogueResponse, <-chan error) {
	responseChan := make(chan *BeginDialogueResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.BeginDialogue(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// BeginDialogueWithCallback invokes the voicenavigator.BeginDialogue API asynchronously
func (client *Client) BeginDialogueWithCallback(request *BeginDialogueRequest, callback func(response *BeginDialogueResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *BeginDialogueResponse
		var err error
		defer close(result)
		response, err = client.BeginDialogue(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// BeginDialogueRequest is the request struct for api BeginDialogue
type BeginDialogueRequest struct {
	*requests.RpcRequest
	ConversationId  string           `position:"Query" name:"ConversationId"`
	InitialContext  string           `position:"Query" name:"InitialContext"`
	CallingNumber   string           `position:"Query" name:"CallingNumber"`
	InstanceId      string           `position:"Query" name:"InstanceId"`
	CalledNumber    string           `position:"Query" name:"CalledNumber"`
	InstanceOwnerId requests.Integer `position:"Query" name:"InstanceOwnerId"`
}

// BeginDialogueResponse is the response struct for api BeginDialogue
type BeginDialogueResponse struct {
	*responses.BaseResponse
	Action        string `json:"Action" xml:"Action"`
	Interruptible bool   `json:"Interruptible" xml:"Interruptible"`
	RequestId     string `json:"RequestId" xml:"RequestId"`
	ActionParams  string `json:"ActionParams" xml:"ActionParams"`
	TextResponse  string `json:"TextResponse" xml:"TextResponse"`
}

// CreateBeginDialogueRequest creates a request to invoke BeginDialogue API
func CreateBeginDialogueRequest() (request *BeginDialogueRequest) {
	request = &BeginDialogueRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("VoiceNavigator", "2018-06-12", "BeginDialogue", "voicebot", "openAPI")
	request.Method = requests.POST
	return
}

// CreateBeginDialogueResponse creates a response to parse from BeginDialogue response
func CreateBeginDialogueResponse() (response *BeginDialogueResponse) {
	response = &BeginDialogueResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

// This script controls the visibility of the recorder button.

public class RecorderScript : MonoBehaviour {

    private string previousHint = "";
    private GameObject Texture;
    private Text myText;

    void Start()
    {
        GameObject Texture = GameObject.FindGameObjectWithTag("Messenger");
        myText = Texture.GetComponent<Text>();
    }

    void OnMouseEnter()
    {

        previousHint = myText.text;

        myText.text = "Audio Recorder. An essential item for quickly and accurately collecting data.\n"+
            "Always use it during interviews.";
        //print("OnMouseEnter RecorderScript");

    }

    void OnMouseExit()
    {

        myText.text = previousHint;
        //print("OnMouseExit RecorderScript");

    }

    void OnMouseDown()
    {

        if (!CameraController.isKitLoaded)
        {
            CameraController.isKitLoaded = true;
            CameraController.showingRecorder = false;
            //CameraController.firstTime = true;

            gameObject.SetActive(false);
        }

    }

}


text:
package com.rasterfoundry.database

import io.estatico.newtype.macros.newtype

import java.util.UUID

@SuppressWarnings(Array("AsInstanceOf"))
object types {
  // to differentiate copy operations between parent and child annotation projects
  @newtype case class ParentAnnotationProjectId(parentAnnotationProjectId: UUID)
  @newtype case class ChildAnnotationProjectId(childAnnotationProjectId: UUID)
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>C++ command line parameters parser: Data Fields</title>
<link href="own.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Namespaces

Data Structures

Files

Data Structures

Class Hierarchy

Data Fields

All

Functions

Variables

Typedefs

a

b

c

d

e

f

g

h

i

n

o

p

r

s

t

u

v

Here is a list of all struct and union fields with links to the structures/unions they belong to:

- t -

there_is_nothing_to_parse()
: clpp::command_line_parameters_parser

this_is_not_name()
: clpp::detail::unnamed_parameters_handler

this_is_parameter_with_value()
: clpp::detail::values_semantic_checker
, clpp::detail::user_functions_caller
, clpp::detail::parameters_values_checker

this_is_parameter_without_value()
: clpp::detail::user_functions_caller

this_is_unnamed_parameter()
: clpp::detail::unnamed_parameters_handler

<address style="text-align: right;">Generated on Thu Oct 28 17:45:49 2010 for C++ command line parameters parser by

 1.5.6 </address>


text:
package pl.newicom.dddd.test.dummy

import akka.actor.Props
import org.scalacheck.Gen
import pl.newicom.dddd.actor.PassivationConfig
import pl.newicom.dddd.aggregate.AggregateRootActorFactory
import pl.newicom.dddd.eventhandling.LocalPublisher
import pl.newicom.dddd.test.dummy.DummyAggregateRoot._
import pl.newicom.dddd.test.support.OfficeSpec
import pl.newicom.dddd.test.support.TestConfig._
import DummyOfficeWithGenSpec._

import scala.concurrent.duration.{Duration, _}

object DummyOfficeWithGenSpec {
  implicit def actorFactory(implicit it: Duration = 1.minute): AggregateRootActorFactory[DummyAggregateRoot] =
    new AggregateRootActorFactory[DummyAggregateRoot] {
      override def props(pc: PassivationConfig): Props = Props(new DummyAggregateRoot with LocalPublisher)
      override def inactivityTimeout: Duration = it
    }
}

class DummyOfficeWithGenSpec extends OfficeSpec[DummyAggregateRoot](Some(testSystem)) {

  def dummyOffice = officeUnderTest

  def dummyId = aggregateId

  //
  // Command generators
  //
  implicit def create: Gen[CreateDummy] = for {
    name <- Gen.alphaStr
    description <- Gen.alphaStr
    value <- Gen.numStr
  } yield {
    CreateDummy(dummyId, name, description, value)
  }
  implicit def changeName: Gen[ChangeName] = for { name <- Gen.alphaStr } yield ChangeName(dummyId, name)
  implicit def generateValue: Gen[GenerateValue] = aggregateIdGen.flatMap(GenerateValue(_))

  "Dummy office" should {
    /**
     * Commands are generated (see generators above).
     * The command under test (created inside When clause)
     * is accessible from inside Then/expect clause.
     *
     * No need to define val members for name, description, ...
     * No need to define concrete values for name, description, ...
     */
    "create Dummy" in {
      when {
        a [CreateDummy]
      }
      .expect { c =>
        DummyCreated(c.id, c.name, c.description, c.value)
      }
    }

    /**
     * Events triggered by Given command(s) are accessible from inside When clause.
     * Gen.suchThat can be used to configure command generator inside test body.
     */
    "update Dummy's name" in {
      given {
        a [CreateDummy]
      }
      .when { implicit hist =>
        a [ChangeName] suchThat (_.name != past[DummyCreated].name)
      }
      .expect { c =>
        NameChanged(c.id, c.name)
      }
    }

    /**
     * No problem with two or more commands inside Given clause.
     */
    "handle subsequent Update command" in {
      given(
        a_list_of [CreateDummy, ChangeName]
      )
      .when {
        a [ChangeName]
      }
      .expect { c =>
        NameChanged(c.id, c.name)
      }
    }

    /**
     * Events triggered by Given command(s) are accessible from inside Then/expect clause.
     */
    "confirm generated value" in {
      given(
        a_list_of [CreateDummy, GenerateValue]
      )
      .when { implicit hist =>
        ConfirmGeneratedValue(dummyId, past[ValueGenerated].confirmationToken)
      }
      .expect { implicit c =>
        ValueChanged(c.id, past[ValueGenerated].value, dummyVersion = 2)
      }
    }

    /**
     * Gen.map can be used to modify generated command.
     */
    "reject null value" in {
      when {
        a [CreateDummy] map (_ copy(value = null))
        // alternatively:
        //arbitraryOf[CreateDummy](_ copy(value = null))
      }
      .expectException[RuntimeException]("null value not allowed")
    }
  }

}


text:
using System;
using FFImageLoading.Work;

namespace FFImageLoading.Transformations
{
	public class FlipTransformation : ITransformation
	{
		private const string DoNotReference = "You are referencing the Portable version in your App - you need to reference the platform (iOS/Android) version";

		public FlipTransformation(FlipType flipType)
		{
			throw new Exception(DoNotReference);
		}

		public IBitmap Transform(IBitmap source)
		{
			throw new Exception(DoNotReference);
		}
		public string Key
		{
			get
			{
				throw new Exception(DoNotReference);
			}
		}
	}
}


text:
from __future__ import absolute_import, print_function, unicode_literals
import os
"""
Deployment based configuration

When deploying topology specify a deployment to match with a settings key.

    -o "'topology.deployment=\"local\"'"

Spouts / Bolts in the topolgoy will then pull the settings then need from this module

"""

ALL_SETTINGS = {}

ALL_SETTINGS['local'] = {
    'topology':'local',
    'appid': 'datawake',
    'crawler-in-topic' : 'crawler-in',
    'crawler-out-topic' : 'crawler-out',
    'visited-topic': 'memex-datawake-visited',
    'conn_pool' : "localhost:9092",
    'user':'root',
    'database':'memex_sotera',
    'password':'root',
    'host':'localhost'
}

ALL_SETTINGS['cluster'] = {
    'topology':'cluster',
    'hbase_host':'localhost',
    'appid': 'datawake',
    'crawler-in-topic' : 'crawler-in',
    'crawler-out-topic' : 'crawler-out',
    'visited-topic': 'memex-datawake-visited',
    'conn_pool' : "localhost:9092",

    'user':'root',
    'database':'memex_sotera',
    'password':'root',
    'host':'localhost'
}

ALL_SETTINGS['local-docker'] = {
    'topology':'local',
    'appid': 'datawake',
    'crawler-in-topic' : 'crawler-in',
    'crawler-out-topic' : 'crawler-out',
    'visited-topic': 'memex-datawake-visited',
    'conn_pool' : os.environ['KAFKA_PORT_9092_TCP_ADDR']+":9092",

    'user':'root',
    'database':'memex_sotera',
    'password':os.environ['MYSQL_ENV_MYSQL_ROOT_PASSWORD'],
    'host':os.environ['MYSQL_PORT_3306_TCP_ADDR']
}

def get_settings(key):
    return ALL_SETTINGS[key]


text:
void
Reconstruct()
{
  //  AliCDBManager* cdb = AliCDBManager::Instance();
  //  cdb->SetDefaultStorage("local://cdb");
  AliLog::SetModuleDebugLevel("T0", 10);
  AliReconstruction rec;
  rec.SetRunLocalReconstruction("T0");
  rec.SetRunVertexFinder(kFALSE);
  rec.SetRunTracking(" ");
  rec.SetFillESD("T0");
  rec.SetInput("./");
//      rec.Run("raw.root");
   rec.Run();
}

//
// EOF
//


text:
from .common_fixtures import *  # NOQA
from .common_libvirt_fixtures import *  # NOQA

import stat

if enabled():
    from cattle.plugins.libvirt_qemu_volume import Qcow2ImageDriver

@if_libvirt
def test_qcow2_inspect():
    volume = Qcow2ImageDriver().inspect(None, QCOW_TEST_FILE)

    assert volume is not None
    assert volume.get_format() == 'qcow2'

    return volume

@if_libvirt
def test_promote(pool_dir, random_qcow2):
    qcow = Qcow2ImageDriver().inspect(None, random_qcow2)

    assert qcow is not None

    qcow.promote(pool_dir, JsonObject({
        'uuid': 'test_file'
    }))

    dest_file = os.path.join(pool_dir, 'test_file.qcow2')
    assert os.path.exists(dest_file)

    os.remove(dest_file)

@if_libvirt
def test_download(pool_dir, random_qcow2):
    image = fake_image(file=random_qcow2)
    pool = fake_pool(pool_dir)

    driver = DirectoryPoolDriver()
    driver.image_activate(image, pool, LogProgress())

    dest_file = os.path.join(pool_dir, '{0}.qcow2'.format(image.uuid))
    assert os.path.exists(dest_file)

    return image.uuid

@if_libvirt
def test_image_exists(pool_dir, random_qcow2):
    uuid = test_download(pool_dir, random_qcow2)

    image = fake_image(None)
    pool = fake_pool(pool_dir)
    image.uuid = uuid

    driver = DirectoryPoolDriver()
    assert driver.is_image_active(image, pool)

@if_libvirt
def test_get_image(pool_dir, random_qcow2):
    image = fake_image(file=random_qcow2)
    pool = fake_pool(pool_dir)

    driver = DirectoryPoolDriver()
    driver.image_activate(image, pool, LogProgress())

    found = driver.get_image(image, pool)

    assert found is not None
    assert found.file == os.path.join(pool_dir, '{0}.qcow2'.format(image.uuid))
    assert found.get_format() == 'qcow2'

    _check_file_mode(found.file, '400')

def _check_file_mode(file_name, str_mode):
    assert oct(os.stat(file_name)[stat.ST_MODE])[-3:] == str_mode

@if_libvirt
def test_volume_activate(pool_dir, random_qcow2):
    volume = fake_volume(image_file=random_qcow2)
    image = volume.image
    pool = fake_pool(pool_dir)

    driver = DirectoryPoolDriver()
    driver.image_activate(image, pool, LogProgress())
    driver.volume_activate(volume, pool, LogProgress())

    found = driver.get_volume(volume, pool)
    found_image = driver.get_image(image, pool)

    assert found is not None
    assert found.info['backing-filename'] == os.path.basename(found_image.file)
    assert found.info['virtual-size'] == found_image.info['virtual-size']
    assert os.path.dirname(found.file) == pool_dir

@if_libvirt
def test_volume_remove(random_volume, pool_dir, random_qcow2):
    volume, volume_obj, driver, pool = random_volume
    image_obj = driver.get_image(volume.image, pool)

    assert os.path.exists(volume_obj.file)
    assert os.path.exists(image_obj.file)
    assert not driver.is_volume_removed(volume, pool)

    driver.volume_remove(volume, pool, LogProgress())

    assert not os.path.exists(volume_obj.file)
    assert os.path.exists(image_obj.file)
    assert driver.is_volume_removed(volume, pool)

@if_libvirt
def test_volume_deactivate(random_volume, pool_dir, random_qcow2):
    volume, volume_obj, driver, pool = random_volume
    driver.get_image(volume.image, pool)

    # There is not deactivate in a directory pool
    assert driver.is_volume_inactive(volume, pool)


text:
testing for objects set
--FILE--
<?php

$T = new Blitz();

$body = <<<BODY
{{ IF object }}
object is set and not empty
{{ ELSE }}
object not set or empty
{{ END object }}
===================================================================

BODY;

$T->load($body);

$object = new stdClass();
$data = array(
    'object' => $object
);
$T->display($data);

$data = array(
);
$T->display($data);

$object->key = 'value';
$data = array(
    'object' => $object
);
$T->display($data);

?>
--EXPECT--
object not set or empty
===================================================================
object not set or empty
===================================================================
object is set and not empty
===================================================================


text:
Mayhem Documentation
====================

The Mayhem packages aims to provide a Python interface for the programmatic
manipulation of executable files at runtime on both the Linux and Windows
platforms.

The source code is available on the `GitHub homepage`_.

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   mayhem/index.rst

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

.. _GitHub homepage: https://github.com/zeroSteiner/mayhem


text:
class BenefitsLinksMigrator

  REGEXP = /#(overview|what-youll-get|eligibility|how-to-claim)/

  def report
    matching_editions = match_editions
    modified_latest_editions = 0

    matching_editions.each do |e|
      if e.latest_edition?
        report_edition(e)
        if e.respond_to?("body")
          m = REGEXP.match(e.body)
          if m
            report_match(m, e.body)
          end
        end
        if e.respond_to?("parts")
          e.parts.each do |p|
            if p.body =~ REGEXP
              m = REGEXP.match(p.body)
              report_match(m, p.body)
            end
          end
        end
        modified_latest_editions += 1
      end
    end
    puts "#{modified_latest_editions} editions would be modified."
  end

  def report_edition(e)
    puts [e._id, e._type, e.title, e.slug, e.state].join(", ")
  end

  def report_match(match, str)
    puts "---------------------------------------------------------------------"
    puts "Anchor match : '#{match}' would be replaced with '/#{match[1]}'"
    puts "---------------------------------------------------------------------"
    puts "Original content is:"
    puts "---------------------------------------------------------------------"
    puts str
    puts "---------------------------------------------------------------------"
    puts "Modified content would be:"
    puts "---------------------------------------------------------------------"
    puts replace_matching_anchors(str)
    puts "---------------------------------------------------------------------\n\n"
  end

  def replace_anchors(user_name)
    u = User.where(name: user_name).first

    match_editions.each do |e|
      if e.latest_edition?
        if e.respond_to?("body")
          e.body = replace_matching_anchors(e.body)
        end
        if e.respond_to?("parts")
          e.parts.each do |p|
            if p.body =~ REGEXP
              p.body = replace_matching_anchors(p.body)
            end
          end
        end
        update_msg = "Updated by development task. Benefits link anchors changed to paths."
        if e.state == 'published'
          clone = e.build_clone
          clone.new_action(u, Action::REQUEST_REVIEW, {})
          clone.state = 'in_review'
          u.record_note(clone, update_msg)
          updated = clone.save!
        else
          u.record_note(e, update_msg)
          updated = e.save
        end
        puts "#{e._id} (#{e.slug}) #{(updated ? '' : 'was not')} modified."
      end
    end
  end

  def replace_matching_anchors(str)
    str.gsub(REGEXP) { |m|
      "/#{$1}"
    }
  end

  def match_editions
    matching_editions = []
    Edition.where(body: REGEXP).each { |e| matching_editions << e unless e.state == 'archived' }
    Edition.where('parts.body' => REGEXP).each { |e| matching_editions << e unless e.state == 'archived' }
    matching_editions
  end
end


text:
#include "CSE1_Oculus_gesture_sfun.h"
#include "sf_runtime/sfcdebug.h"

struct SfDebugInstanceStruct;
struct SfDebugInstanceStruct* sfGlobalDebugInstanceStruct = NULL;

#define PROCESS_MEX_SFUNCTION_CMD_LINE_CALL

unsigned int sf_process_check_sum_call( int nlhs, mxArray * plhs[], int nrhs,
  const mxArray * prhs[] )
{
  extern unsigned int sf_CSE1_Oculus_gesture_process_check_sum_call( int nlhs,
    mxArray * plhs[], int nrhs, const mxArray * prhs[] );
  if (sf_CSE1_Oculus_gesture_process_check_sum_call(nlhs,plhs,nrhs,prhs))
    return 1;
  return 0;
}

unsigned int sf_process_autoinheritance_call( int nlhs, mxArray * plhs[], int
  nrhs, const mxArray * prhs[] )
{
  extern unsigned int sf_CSE1_Oculus_gesture_autoinheritance_info( int nlhs,
    mxArray * plhs[], int nrhs, const mxArray * prhs[] );
  char commandName[64];
  char machineName[128];
  if (nrhs < 4) {
    return 0;
  }

  if (!mxIsChar(prhs[0]) || !mxIsChar(prhs[1]))
    return 0;
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"get_autoinheritance_info"))
    return 0;
  mxGetString(prhs[1], machineName,sizeof(machineName)/sizeof(char));
  machineName[(sizeof(machineName)/sizeof(char)-1)] = '\0';
  if (strcmp(machineName, "CSE1_Oculus_gesture") == 0) {
    const mxArray *newRhs[3] = { NULL, NULL, NULL };

    newRhs[0] = prhs[0];
    newRhs[1] = prhs[2];
    newRhs[2] = prhs[3];
    return sf_CSE1_Oculus_gesture_autoinheritance_info(nlhs,plhs,3,newRhs);
  }

  return 0;
}

unsigned int sf_process_get_third_party_uses_info_call( int nlhs, mxArray *
  plhs[], int nrhs, const mxArray * prhs[] )
{
  extern unsigned int sf_CSE1_Oculus_gesture_third_party_uses_info( int nlhs,
    mxArray * plhs[], int nrhs, const mxArray * prhs[] );
  char commandName[64];
  char machineName[128];
  if (nrhs < 4) {
    return 0;
  }

  if (!mxIsChar(prhs[0]) || !mxIsChar(prhs[1]))
    return 0;
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"get_third_party_uses_info"))
    return 0;
  mxGetString(prhs[1], machineName,sizeof(machineName)/sizeof(char));
  machineName[(sizeof(machineName)/sizeof(char)-1)] = '\0';
  if (strcmp(machineName, "CSE1_Oculus_gesture") == 0) {
    const mxArray *newRhs[3] = { NULL, NULL, NULL };

    newRhs[0] = prhs[0];
    newRhs[1] = prhs[2];
    newRhs[2] = prhs[3];
    return sf_CSE1_Oculus_gesture_third_party_uses_info(nlhs,plhs,3,newRhs);
  }

  return 0;
}

unsigned int sf_process_get_updateBuildInfo_args_info_call( int nlhs, mxArray *
  plhs[], int nrhs, const mxArray * prhs[] )
{
  extern unsigned int sf_CSE1_Oculus_gesture_updateBuildInfo_args_info( int nlhs,
    mxArray * plhs[], int nrhs, const mxArray * prhs[] );
  char commandName[64];
  char machineName[128];
  if (nrhs < 4) {
    return 0;
  }

  if (!mxIsChar(prhs[0]) || !mxIsChar(prhs[1]))
    return 0;
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"get_updateBuildInfo_args_info"))
    return 0;
  mxGetString(prhs[1], machineName,sizeof(machineName)/sizeof(char));
  machineName[(sizeof(machineName)/sizeof(char)-1)] = '\0';
  if (strcmp(machineName, "CSE1_Oculus_gesture") == 0) {
    const mxArray *newRhs[3] = { NULL, NULL, NULL };

    newRhs[0] = prhs[0];
    newRhs[1] = prhs[2];
    newRhs[2] = prhs[3];
    return sf_CSE1_Oculus_gesture_updateBuildInfo_args_info(nlhs,plhs,3,newRhs);
  }

  return 0;
}

unsigned int sf_process_get_eml_resolved_functions_info_call( int nlhs, mxArray *
  plhs[], int nrhs, const mxArray * prhs[] )
{
  extern unsigned int sf_CSE1_Oculus_gesture_get_eml_resolved_functions_info
    ( int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[] );
  char commandName[64];
  char machineName[128];
  if (nrhs < 3) {
    return 0;
  }

  if (!mxIsChar(prhs[0]) || !mxIsChar(prhs[1]))
    return 0;
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"get_eml_resolved_functions_info"))
    return 0;
  mxGetString(prhs[1], machineName,sizeof(machineName)/sizeof(char));
  machineName[(sizeof(machineName)/sizeof(char)-1)] = '\0';
  if (strcmp(machineName, "CSE1_Oculus_gesture") == 0) {
    const mxArray *newRhs[2] = { NULL, NULL };

    newRhs[0] = prhs[0];
    newRhs[1] = prhs[2];
    return sf_CSE1_Oculus_gesture_get_eml_resolved_functions_info(nlhs,plhs,2,
      newRhs);
  }

  return 0;
}

unsigned int sf_mex_unlock_call( int nlhs, mxArray * plhs[], int nrhs, const
  mxArray * prhs[] )
{
  char commandName[20];
  if (nrhs<1 || !mxIsChar(prhs[0]) )
    return 0;

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_mex_unlock"))
    return 0;
  while (mexIsLocked()) {
    mexUnlock();
  }

  return(1);
}

extern unsigned int sf_debug_api(struct SfDebugInstanceStruct* debugInstance,
  int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[] );
static unsigned int sf_debug_api_wrapper( int nlhs, mxArray * plhs[], int nrhs,
  const mxArray * prhs[] )
{
  return sf_debug_api(sfGlobalDebugInstanceStruct, nlhs, plhs, nrhs, prhs);
}

static unsigned int ProcessMexSfunctionCmdLineCall(int nlhs, mxArray * plhs[],
  int nrhs, const mxArray * prhs[])
{
  if (sf_debug_api_wrapper(nlhs,plhs,nrhs,prhs))
    return 1;
  if (sf_process_check_sum_call(nlhs,plhs,nrhs,prhs))
    return 1;
  if (sf_mex_unlock_call(nlhs,plhs,nrhs,prhs))
    return 1;
  if (sf_process_autoinheritance_call(nlhs,plhs,nrhs,prhs))
    return 1;
  if (sf_process_get_third_party_uses_info_call(nlhs,plhs,nrhs,prhs))
    return 1;
  if (sf_process_get_updateBuildInfo_args_info_call(nlhs,plhs,nrhs,prhs))
    return 1;
  if (sf_process_get_eml_resolved_functions_info_call(nlhs,plhs,nrhs,prhs))
    return 1;
  mexErrMsgTxt("Unsuccessful command.");
  return 0;
}

static unsigned int sfGlobalMdlStartCallCounts = 0;
unsigned int sf_machine_global_initializer_called(void)
{
  return(sfGlobalMdlStartCallCounts > 0);
}

extern unsigned int sf_CSE1_Oculus_gesture_method_dispatcher(SimStruct *S,
  unsigned int chartFileNumber, const char* specsCksum, int_T method, void *data);
unsigned int sf_machine_global_method_dispatcher(SimStruct *simstructPtr, const
  char *machineName, unsigned int chartFileNumber, const char* specsCksum, int_T
  method, void *data)
{
  if (!strcmp(machineName,"CSE1_Oculus_gesture")) {
    return(sf_CSE1_Oculus_gesture_method_dispatcher(simstructPtr,chartFileNumber,
            specsCksum,method,data));
  }

  return 0;
}

extern void CSE1_Oculus_gesture_terminator(void);
void sf_machine_global_terminator(void)
{
  sfGlobalMdlStartCallCounts--;
  if (sfGlobalMdlStartCallCounts == 0) {
    CSE1_Oculus_gesture_terminator();
    sf_debug_terminate(sfGlobalDebugInstanceStruct);
    sfGlobalDebugInstanceStruct = NULL;
  }

  return;
}

extern void CSE1_Oculus_gesture_initializer(void);
extern void CSE1_Oculus_gesture_register_exported_symbols(SimStruct* S);
extern void CSE1_Oculus_gesture_debug_initialize(struct SfDebugInstanceStruct*);
void sf_register_machine_exported_symbols(SimStruct* S)
{
  CSE1_Oculus_gesture_register_exported_symbols(S);
}

bool callCustomFcn(char initFlag)
{
  return false;
}

void sf_machine_global_initializer(SimStruct* S)
{
  bool simModeIsRTWGen = sim_mode_is_rtw_gen(S);
  sfGlobalMdlStartCallCounts++;
  if (sfGlobalMdlStartCallCounts == 1) {
    if (simModeIsRTWGen) {
      sf_register_machine_exported_symbols(S);
    }

    sfGlobalDebugInstanceStruct = sf_debug_create_debug_instance_struct();
    if (!simModeIsRTWGen) {
      CSE1_Oculus_gesture_debug_initialize(sfGlobalDebugInstanceStruct);
    }

    CSE1_Oculus_gesture_initializer();
  }

  return;
}

#include "sf_runtime/stateflow_mdl_methods.stub"


text:
package org.edx.indonesiax.model.course;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

/**
 * Created by hanning on 5/19/15.
 */
public class EncodedVideos implements Serializable{
    @SerializedName("fallback")
    public VideoInfo fallback;

    @SerializedName("mobile_high")
    public VideoInfo mobileHigh;

    @SerializedName("mobile_low")
    public VideoInfo mobileLow;

    @SerializedName("youtube")
    public VideoInfo youtube;

    public VideoInfo getPreferredVideoInfo(){
        if ( mobileLow != null )
            return mobileLow;
        if ( mobileHigh != null )
            return mobileHigh;
        if ( fallback != null)
            return fallback;
        return new VideoInfo(); //should not be here
    }

}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#if !NO_PERF
using System;

namespace System.Reactive.Linq.ObservableImpl
{
    class Where<TSource> : Producer<TSource>
    {
        private readonly IObservable<TSource> _source;
        private readonly Func<TSource, bool> _predicate;
        private readonly Func<TSource, int, bool> _predicateI;

        public Where(IObservable<TSource> source, Func<TSource, bool> predicate)
        {
            _source = source;
            _predicate = predicate;
        }

        public Where(IObservable<TSource> source, Func<TSource, int, bool> predicate)
        {
            _source = source;
            _predicateI = predicate;
        }

        public IObservable<TSource> Omega(Func<TSource, bool> predicate)
        {
            if (_predicate != null)
                return new Where<TSource>(_source, x => _predicate(x) && predicate(x));
            else
                return new Where<TSource>(this, predicate);
        }

        protected override IDisposable Run(IObserver<TSource> observer, IDisposable cancel, Action<IDisposable> setSink)
        {
            if (_predicate != null)
            {
                var sink = new _(this, observer, cancel);
                setSink(sink);
                return _source.SubscribeSafe(sink);
            }
            else
            {
                var sink = new WhereImpl(this, observer, cancel);
                setSink(sink);
                return _source.SubscribeSafe(sink);
            }
        }

        class _ : Sink<TSource>, IObserver<TSource>
        {
            private readonly Where<TSource> _parent;

            public _(Where<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
                : base(observer, cancel)
            {
                _parent = parent;
            }

            public void OnNext(TSource value)
            {
                var shouldRun = default(bool);
                try
                {
                    shouldRun = _parent._predicate(value);
                }
                catch (Exception exception)
                {
                    base._observer.OnError(exception);
                    base.Dispose();
                    return;
                }

                if (shouldRun)
                    base._observer.OnNext(value);
            }

            public void OnError(Exception error)
            {
                base._observer.OnError(error);
                base.Dispose();
            }

            public void OnCompleted()
            {
                base._observer.OnCompleted();
                base.Dispose();
            }
        }

        class WhereImpl : Sink<TSource>, IObserver<TSource>
        {
            private readonly Where<TSource> _parent;
            private int _index;

            public WhereImpl(Where<TSource> parent, IObserver<TSource> observer, IDisposable cancel)
                : base(observer, cancel)
            {
                _parent = parent;
                _index = 0;
            }

            public void OnNext(TSource value)
            {
                var shouldRun = default(bool);
                try
                {
                    shouldRun = _parent._predicateI(value, checked(_index++));
                }
                catch (Exception exception)
                {
                    base._observer.OnError(exception);
                    base.Dispose();
                    return;
                }

                if (shouldRun)
                    base._observer.OnNext(value);
            }

            public void OnError(Exception error)
            {
                base._observer.OnError(error);
                base.Dispose();
            }

            public void OnCompleted()
            {
                base._observer.OnCompleted();
                base.Dispose();
            }
        }
    }
}
#endif