text:
package org.apache.druid.cli;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.MapBinder;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Names;
import com.google.inject.servlet.GuiceFilter;
import com.google.inject.util.Providers;
import io.airlift.airline.Command;
import org.apache.druid.audit.AuditManager;
import org.apache.druid.client.indexing.HttpIndexingServiceClient;
import org.apache.druid.client.indexing.IndexingService;
import org.apache.druid.client.indexing.IndexingServiceClient;
import org.apache.druid.client.indexing.IndexingServiceSelectorConfig;
import org.apache.druid.discovery.NodeRole;
import org.apache.druid.guice.IndexingServiceFirehoseModule;
import org.apache.druid.guice.IndexingServiceInputSourceModule;
import org.apache.druid.guice.IndexingServiceModuleHelper;
import org.apache.druid.guice.IndexingServiceTaskLogsModule;
import org.apache.druid.guice.IndexingServiceTuningConfigModule;
import org.apache.druid.guice.JacksonConfigProvider;
import org.apache.druid.guice.Jerseys;
import org.apache.druid.guice.JsonConfigProvider;
import org.apache.druid.guice.LazySingleton;
import org.apache.druid.guice.LifecycleModule;
import org.apache.druid.guice.ListProvider;
import org.apache.druid.guice.ManageLifecycle;
import org.apache.druid.guice.PolyBind;
import org.apache.druid.guice.annotations.Json;
import org.apache.druid.indexing.common.actions.LocalTaskActionClientFactory;
import org.apache.druid.indexing.common.actions.TaskActionClientFactory;
import org.apache.druid.indexing.common.actions.TaskActionToolbox;
import org.apache.druid.indexing.common.actions.TaskAuditLogConfig;
import org.apache.druid.indexing.common.config.TaskConfig;
import org.apache.druid.indexing.common.config.TaskStorageConfig;
import org.apache.druid.indexing.common.stats.DropwizardRowIngestionMetersFactory;
import org.apache.druid.indexing.common.task.IndexTaskClientFactory;
import org.apache.druid.indexing.common.task.batch.parallel.ParallelIndexSupervisorTaskClient;
import org.apache.druid.indexing.common.task.batch.parallel.ShuffleClient;
import org.apache.druid.indexing.common.tasklogs.SwitchingTaskLogStreamer;
import org.apache.druid.indexing.common.tasklogs.TaskRunnerTaskLogStreamer;
import org.apache.druid.indexing.overlord.ForkingTaskRunnerFactory;
import org.apache.druid.indexing.overlord.HeapMemoryTaskStorage;
import org.apache.druid.indexing.overlord.IndexerMetadataStorageAdapter;
import org.apache.druid.indexing.overlord.MetadataTaskStorage;
import org.apache.druid.indexing.overlord.RemoteTaskRunnerFactory;
import org.apache.druid.indexing.overlord.TaskLockbox;
import org.apache.druid.indexing.overlord.TaskMaster;
import org.apache.druid.indexing.overlord.TaskRunnerFactory;
import org.apache.druid.indexing.overlord.TaskStorage;
import org.apache.druid.indexing.overlord.TaskStorageQueryAdapter;
import org.apache.druid.indexing.overlord.autoscaling.PendingTaskBasedWorkerProvisioningConfig;
import org.apache.druid.indexing.overlord.autoscaling.PendingTaskBasedWorkerProvisioningStrategy;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningSchedulerConfig;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningStrategy;
import org.apache.druid.indexing.overlord.autoscaling.SimpleWorkerProvisioningConfig;
import org.apache.druid.indexing.overlord.autoscaling.SimpleWorkerProvisioningStrategy;
import org.apache.druid.indexing.overlord.config.TaskLockConfig;
import org.apache.druid.indexing.overlord.config.TaskQueueConfig;
import org.apache.druid.indexing.overlord.helpers.OverlordHelper;
import org.apache.druid.indexing.overlord.helpers.TaskLogAutoCleaner;
import org.apache.druid.indexing.overlord.helpers.TaskLogAutoCleanerConfig;
import org.apache.druid.indexing.overlord.hrtr.HttpRemoteTaskRunnerFactory;
import org.apache.druid.indexing.overlord.hrtr.HttpRemoteTaskRunnerResource;
import org.apache.druid.indexing.overlord.http.OverlordRedirectInfo;
import org.apache.druid.indexing.overlord.http.OverlordResource;
import org.apache.druid.indexing.overlord.sampler.SamplerModule;
import org.apache.druid.indexing.overlord.setup.WorkerBehaviorConfig;
import org.apache.druid.indexing.overlord.supervisor.SupervisorManager;
import org.apache.druid.indexing.overlord.supervisor.SupervisorModule;
import org.apache.druid.indexing.overlord.supervisor.SupervisorResource;
import org.apache.druid.indexing.worker.config.WorkerConfig;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.metadata.input.InputSourceModule;
import org.apache.druid.query.lookup.LookupSerdeModule;
import org.apache.druid.segment.incremental.RowIngestionMetersFactory;
import org.apache.druid.segment.realtime.appenderator.AppenderatorsManager;
import org.apache.druid.segment.realtime.appenderator.DummyForInjectionAppenderatorsManager;
import org.apache.druid.segment.realtime.firehose.ChatHandlerProvider;
import org.apache.druid.segment.realtime.firehose.NoopChatHandlerProvider;
import org.apache.druid.server.audit.AuditManagerProvider;
import org.apache.druid.server.coordinator.CoordinatorOverlordServiceConfig;
import org.apache.druid.server.http.RedirectFilter;
import org.apache.druid.server.http.RedirectInfo;
import org.apache.druid.server.http.SelfDiscoveryResource;
import org.apache.druid.server.initialization.ServerConfig;
import org.apache.druid.server.initialization.jetty.JettyServerInitUtils;
import org.apache.druid.server.initialization.jetty.JettyServerInitializer;
import org.apache.druid.server.metrics.TaskCountStatsProvider;
import org.apache.druid.server.metrics.TaskSlotCountStatsProvider;
import org.apache.druid.server.security.AuthConfig;
import org.apache.druid.server.security.AuthenticationUtils;
import org.apache.druid.server.security.Authenticator;
import org.apache.druid.server.security.AuthenticatorMapper;
import org.apache.druid.tasklogs.TaskLogStreamer;
import org.apache.druid.tasklogs.TaskLogs;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import java.util.List;

/**
 */
@Command(
    name = "overlord",
    description = "Runs an Overlord node, see https://druid.apache.org/docs/latest/Indexing-Service.html for a description"
)
public class CliOverlord extends ServerRunnable
{
  private static Logger log = new Logger(CliOverlord.class);

  protected static final List<String> UNSECURED_PATHS = ImmutableList.of(
      "/druid/indexer/v1/isLeader",
      "/status/health"
  );

  public CliOverlord()
  {
    super(log);
  }

  @Override
  protected List<? extends Module> getModules()
  {
    return getModules(true);
  }

  protected List<? extends Module> getModules(final boolean standalone)
  {
    return ImmutableList.of(
        new Module()
        {
          @Override
          public void configure(Binder binder)
          {
            if (standalone) {
              binder.bindConstant()
                    .annotatedWith(Names.named("serviceName"))
                    .to(IndexingServiceSelectorConfig.DEFAULT_SERVICE_NAME);
              binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8090);
              binder.bindConstant().annotatedWith(Names.named("tlsServicePort")).to(8290);
            }

            JsonConfigProvider.bind(binder, "druid.coordinator.asOverlord", CoordinatorOverlordServiceConfig.class);
            JsonConfigProvider.bind(binder, "druid.indexer.queue", TaskQueueConfig.class);
            JsonConfigProvider.bind(binder, "druid.indexer.tasklock", TaskLockConfig.class);
            JsonConfigProvider.bind(binder, "druid.indexer.task", TaskConfig.class);
            JsonConfigProvider.bind(binder, "druid.indexer.auditlog", TaskAuditLogConfig.class);

            binder.bind(TaskMaster.class).in(ManageLifecycle.class);
            binder.bind(TaskCountStatsProvider.class).to(TaskMaster.class);
            binder.bind(TaskSlotCountStatsProvider.class).to(TaskMaster.class);

            binder.bind(TaskLogStreamer.class).to(SwitchingTaskLogStreamer.class).in(LazySingleton.class);
            binder.bind(
                new TypeLiteral<List<TaskLogStreamer>>()
                {
                }
            )
                  .toProvider(
                      new ListProvider<TaskLogStreamer>()
                          .add(TaskRunnerTaskLogStreamer.class)
                          .add(TaskLogs.class)
                  )
                  .in(LazySingleton.class);

            binder.bind(TaskActionClientFactory.class).to(LocalTaskActionClientFactory.class).in(LazySingleton.class);
            binder.bind(TaskActionToolbox.class).in(LazySingleton.class);
            binder.bind(TaskLockbox.class).in(LazySingleton.class);
            binder.bind(TaskStorageQueryAdapter.class).in(LazySingleton.class);
            binder.bind(IndexerMetadataStorageAdapter.class).in(LazySingleton.class);
            binder.bind(SupervisorManager.class).in(LazySingleton.class);

            binder.bind(IndexingServiceClient.class).to(HttpIndexingServiceClient.class).in(LazySingleton.class);
            binder.bind(new TypeLiteral<IndexTaskClientFactory<ParallelIndexSupervisorTaskClient>>()
            {
            }).toProvider(Providers.of(null));
            binder.bind(ShuffleClient.class).toProvider(Providers.of(null));
            binder.bind(ChatHandlerProvider.class).toProvider(Providers.of(new NoopChatHandlerProvider()));

            PolyBind.createChoice(
                binder,
                "druid.indexer.task.rowIngestionMeters.type",
                Key.get(RowIngestionMetersFactory.class),
                Key.get(DropwizardRowIngestionMetersFactory.class)
            );
            final MapBinder<String, RowIngestionMetersFactory> rowIngestionMetersHandlerProviderBinder =
                PolyBind.optionBinder(binder, Key.get(RowIngestionMetersFactory.class));
            rowIngestionMetersHandlerProviderBinder
                .addBinding("dropwizard")
                .to(DropwizardRowIngestionMetersFactory.class)
                .in(LazySingleton.class);
            binder.bind(DropwizardRowIngestionMetersFactory.class).in(LazySingleton.class);

            configureTaskStorage(binder);
            configureAutoscale(binder);
            configureRunners(binder);
            configureOverlordHelpers(binder);

            binder.bind(AuditManager.class)
                  .toProvider(AuditManagerProvider.class)
                  .in(ManageLifecycle.class);

            if (standalone) {
              binder.bind(RedirectFilter.class).in(LazySingleton.class);
              binder.bind(RedirectInfo.class).to(OverlordRedirectInfo.class).in(LazySingleton.class);
              binder.bind(JettyServerInitializer.class)
                    .to(OverlordJettyServerInitializer.class)
                    .in(LazySingleton.class);
            }

            Jerseys.addResource(binder, OverlordResource.class);
            Jerseys.addResource(binder, SupervisorResource.class);
            Jerseys.addResource(binder, HttpRemoteTaskRunnerResource.class);

            binder.bind(AppenderatorsManager.class)
                  .to(DummyForInjectionAppenderatorsManager.class)
                  .in(LazySingleton.class);

            if (standalone) {
              LifecycleModule.register(binder, Server.class);
            }

            bindNodeRoleAndAnnouncer(
                binder,
                IndexingService.class,
                DiscoverySideEffectsProvider.builder(NodeRole.OVERLORD).build()
            );

            Jerseys.addResource(binder, SelfDiscoveryResource.class);
            LifecycleModule.registerKey(binder, Key.get(SelfDiscoveryResource.class));
          }

          private void configureTaskStorage(Binder binder)
          {
            JsonConfigProvider.bind(binder, "druid.indexer.storage", TaskStorageConfig.class);

            PolyBind.createChoice(
                binder,
                "druid.indexer.storage.type",
                Key.get(TaskStorage.class),
                Key.get(HeapMemoryTaskStorage.class)
            );
            final MapBinder<String, TaskStorage> storageBinder =
                PolyBind.optionBinder(binder, Key.get(TaskStorage.class));

            storageBinder.addBinding("local").to(HeapMemoryTaskStorage.class);
            binder.bind(HeapMemoryTaskStorage.class).in(LazySingleton.class);

            storageBinder.addBinding("metadata").to(MetadataTaskStorage.class).in(ManageLifecycle.class);
            binder.bind(MetadataTaskStorage.class).in(LazySingleton.class);
          }

          private void configureRunners(Binder binder)
          {
            JsonConfigProvider.bind(binder, "druid.worker", WorkerConfig.class);

            PolyBind.createChoice(
                binder,
                "druid.indexer.runner.type",
                Key.get(TaskRunnerFactory.class),
                Key.get(ForkingTaskRunnerFactory.class)
            );
            final MapBinder<String, TaskRunnerFactory> biddy = PolyBind.optionBinder(
                binder,
                Key.get(TaskRunnerFactory.class)
            );

            IndexingServiceModuleHelper.configureTaskRunnerConfigs(binder);
            biddy.addBinding("local").to(ForkingTaskRunnerFactory.class);
            binder.bind(ForkingTaskRunnerFactory.class).in(LazySingleton.class);

            biddy.addBinding(RemoteTaskRunnerFactory.TYPE_NAME)
                 .to(RemoteTaskRunnerFactory.class)
                 .in(LazySingleton.class);
            binder.bind(RemoteTaskRunnerFactory.class).in(LazySingleton.class);

            biddy.addBinding(HttpRemoteTaskRunnerFactory.TYPE_NAME)
                 .to(HttpRemoteTaskRunnerFactory.class)
                 .in(LazySingleton.class);
            binder.bind(HttpRemoteTaskRunnerFactory.class).in(LazySingleton.class);

            JacksonConfigProvider.bind(binder, WorkerBehaviorConfig.CONFIG_KEY, WorkerBehaviorConfig.class, null);
          }

          private void configureAutoscale(Binder binder)
          {
            JsonConfigProvider.bind(binder, "druid.indexer.autoscale", ProvisioningSchedulerConfig.class);
            JsonConfigProvider.bind(
                binder,
                "druid.indexer.autoscale",
                PendingTaskBasedWorkerProvisioningConfig.class
            );
            JsonConfigProvider.bind(binder, "druid.indexer.autoscale", SimpleWorkerProvisioningConfig.class);

            PolyBind.createChoice(
                binder,
                "druid.indexer.autoscale.strategy.type",
                Key.get(ProvisioningStrategy.class),
                Key.get(SimpleWorkerProvisioningStrategy.class)
            );
            final MapBinder<String, ProvisioningStrategy> biddy = PolyBind.optionBinder(
                binder,
                Key.get(ProvisioningStrategy.class)
            );
            biddy.addBinding("simple").to(SimpleWorkerProvisioningStrategy.class);
            biddy.addBinding("pendingTaskBased").to(PendingTaskBasedWorkerProvisioningStrategy.class);
          }

          private void configureOverlordHelpers(Binder binder)
          {
            JsonConfigProvider.bind(binder, "druid.indexer.logs.kill", TaskLogAutoCleanerConfig.class);
            Multibinder.newSetBinder(binder, OverlordHelper.class)
                       .addBinding()
                       .to(TaskLogAutoCleaner.class);
          }
        },
        new IndexingServiceFirehoseModule(),
        new IndexingServiceInputSourceModule(),
        new IndexingServiceTaskLogsModule(),
        new IndexingServiceTuningConfigModule(),
        new InputSourceModule(),
        new SupervisorModule(),
        new LookupSerdeModule(),
        new SamplerModule()
    );
  }

  /**
   */
  private static class OverlordJettyServerInitializer implements JettyServerInitializer
  {
    private final AuthConfig authConfig;
    private final ServerConfig serverConfig;

    @Inject
    OverlordJettyServerInitializer(AuthConfig authConfig, ServerConfig serverConfig)
    {
      this.authConfig = authConfig;
      this.serverConfig = serverConfig;
    }

    @Override
    public void initialize(Server server, Injector injector)
    {
      final ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);
      root.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

      ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);

      root.addServlet(holderPwd, "/");

      final ObjectMapper jsonMapper = injector.getInstance(Key.get(ObjectMapper.class, Json.class));
      final AuthenticatorMapper authenticatorMapper = injector.getInstance(AuthenticatorMapper.class);

      AuthenticationUtils.addSecuritySanityCheckFilter(root, jsonMapper);

      // perform no-op authorization/authentication for these resources
      AuthenticationUtils.addNoopAuthenticationAndAuthorizationFilters(root, UNSECURED_PATHS);
      WebConsoleJettyServerInitializer.intializeServerForWebConsoleRoot(root);
      AuthenticationUtils.addNoopAuthenticationAndAuthorizationFilters(root, authConfig.getUnsecuredPaths());

      final List<Authenticator> authenticators = authenticatorMapper.getAuthenticatorChain();
      AuthenticationUtils.addAuthenticationFilterChain(root, authenticators);

      AuthenticationUtils.addAllowOptionsFilter(root, authConfig.isAllowUnauthenticatedHttpOptions());
      JettyServerInitUtils.addAllowHttpMethodsFilter(root, serverConfig.getAllowedHttpMethods());

      JettyServerInitUtils.addExtensionFilters(root, injector);

      // Check that requests were authorized before sending responses
      AuthenticationUtils.addPreResponseAuthorizationCheckFilter(
          root,
          authenticators,
          jsonMapper
      );

      // add some paths not to be redirected to leader.
      root.addFilter(GuiceFilter.class, "/status/*", null);
      root.addFilter(GuiceFilter.class, "/druid-internal/*", null);

      // redirect anything other than status to the current lead
      root.addFilter(new FilterHolder(injector.getInstance(RedirectFilter.class)), "/*", null);

      // Can't use /* here because of Guice and Jetty static content conflicts
      root.addFilter(GuiceFilter.class, "/druid/*", null);

      root.addFilter(GuiceFilter.class, "/druid-ext/*", null);

      HandlerList handlerList = new HandlerList();
      handlerList.setHandlers(
          new Handler[]{
              WebConsoleJettyServerInitializer.createWebConsoleRewriteHandler(),
              JettyServerInitUtils.getJettyRequestLogHandler(),
              JettyServerInitUtils.wrapWithDefaultGzipHandler(
                  root,
                  serverConfig.getInflateBufferSize(),
                  serverConfig.getCompressionLevel()
              )
          }
      );

      server.setHandler(handlerList);
    }
  }
}


text:
    MS

    MyanmarSeaman

      Toggle navigation

            User Name Here

          Profile
          Sign out

 Companies

      Blank page
      it all starts here

 Home

Examples

Blank page

Title

      Start creating your amazing application!

      Footer

  Copyright © 2016 Myanmar Seaman. All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
package batch.sql;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Stack;

import batch.sql.results.NullResultSet;
import batch.sql.results.QueryResults;
import batch.sql.results.ResultLevelStack;
import batch.sql.results.ResultLevelStack.ResultLevel;
import batch.sql.results.ResultSetLike;
import batch.sql.results.ResultSetStored;
import batch.sql.results.ResultSetStream;
import batch.sql.syntax.SQLQuery;
import batch.sql.syntax.SQLTranslation.SQLAction;
import static batch.sql.SQLForestItem.SQLForestItemType.*;
import batch.util.ForestListWriter;
import batch.util.ForestReader;
import batch.util.ForestReaderHelper;
import batch.util.ForestWriter;

/**
 * Assumes read once in order.
 * For out of order, use copyTo(new Forest())
 */
public class JDBCForestReader extends ForestReaderHelper implements Iterator<SQLForestItem>, Iterable<SQLForestItem> {

  final boolean usePrepared = true;
  final Connection conn;
  final Statement stmt;
  final DatabaseMetaData dbMeta;
  final ForestReader data;
  final Iterator<SQLQuery> remainingQueries;
  final ResultLevelStack levels = new ResultLevelStack();
  boolean inTable = false;

  // "jdbc:mysql://localhost/test?user=monty&password=greatsqldb"
  public JDBCForestReader(
        final SQLQuery rootQuery,
        ForestReader data,
        String url
      ) {
    // Setup connection
    try {
      conn = DriverManager.getConnection(url);
      batch.sql.syntax.SQLTable.tagNum = 1;
      if (!usePrepared) {
        stmt = conn.createStatement();
      } else {
        stmt = null;
      }
      dbMeta = conn.getMetaData();
      if (!dbMeta.getDatabaseProductName().equals("MySQL")) {
        System.err.println("WARNING: Streaming results not implemented for " + dbMeta.getDatabaseProductName());
      }
    } catch (SQLException e) {
      // avoid warnings about variables like conn not being initialized
      throw new Error(this.<String>handleError(e));
    }

    // Setup iteration values
    this.data = data;
    switch (rootQuery.getAction()) {
    case INSERT:
    case UPDATE:
    case DELETE:
    case SELECT:
      remainingQueries = new ArrayList<SQLQuery>() {{
        add(rootQuery);
      }}.iterator();
      break;
    default:
      remainingQueries = rootQuery.getSubqueries().iterator();
    }
  }

  private QueryResults startQueries(final SQLQuery q, ForestReader data) throws SQLException {
    return startQueries(q, data, true);
  }

  private QueryResults startQueries(
        final SQLQuery q,
        ForestReader data,
        boolean isLastOfParent
      ) throws SQLException {
    final ResultSet results;
    List<SQLQuery> subQueries = q.getSubqueries();
    boolean shouldStream = subQueries.isEmpty() && isLastOfParent;
    switch (q.getAction()) {
    case INSERT:
      results = executeUpdate(q, data, shouldStream, true);
      break;
    case UPDATE:
    case DELETE:
      // Update and Delete don't have results
      executeUpdate(q, data, shouldStream, false);
      shouldBe(subQueries.isEmpty());
      return null;
    case SELECT:
      results = executeQuery(q, data, shouldStream);
      break;
    default:
      results = null;
    }
    // Determine how to store results.
    final ResultSetLike rsl;
    if (results == null) {
      rsl = new NullResultSet();
    } else if (shouldStream) {
      // Keep last results streaming
      rsl = new ResultSetStream(results);
    } else {
      // Store results locally since we can't keep multiple result sets open
      rsl = new ResultSetStored(results);
    }
    // Execute sub queries
    Iterator<SQLQuery> subIt = subQueries.iterator();
    List<QueryResults> subs = new ArrayList<QueryResults>(subQueries.size());
    while(subIt.hasNext()) {
      SQLQuery sub = subIt.next();
      subs.add(startQueries(sub, data, isLastOfParent && !subIt.hasNext()));
    }
    rsl.next();
    return new QueryResults(rsl, q, subs);
  }

  private ResultSet executeQuery(
        SQLQuery q,
        ForestReader data,
        boolean shouldStream
      ) throws SQLException {
    ResultSet qr;
    if (!usePrepared) {
      setToStream(stmt, shouldStream);
      String sql = SQLBatch.getSQL(q, null, data);
      qr = stmt.executeQuery(sql);
    } else {
      List<Object> params = new ArrayList<Object>();
      String sql = SQLBatch.getSQL(q, params, data);
      PreparedStatement pstmt = conn.prepareStatement(sql);
      setToStream(pstmt, shouldStream);
      int i = 1;
      for (Object param : params)
        pstmt.setObject(i++, param);
      qr = pstmt.executeQuery();
    }
    return qr;
  }

  private ResultSet executeUpdate(SQLQuery q, ForestReader data, boolean shouldStream, boolean returnKeys)
      throws SQLException {
    int num;
    ResultSet result = null;
    int autoGeneratedKeys = returnKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS;
    if (!usePrepared) {
      setToStream(stmt, shouldStream);
      String sql = SQLBatch.getSQL(q, null, data);
      num = stmt.executeUpdate(sql, autoGeneratedKeys);
      if (returnKeys)
        result = stmt.getGeneratedKeys();
    } else {
      List<Object> params = new ArrayList<Object>();
      String sql = SQLBatch.getSQL(q, params, data);
      PreparedStatement pstmt = conn.prepareStatement(sql, autoGeneratedKeys);
      setToStream(pstmt, shouldStream);
      int i = 1;
      for (Object param : params)
        pstmt.setObject(i++, param);
      num = pstmt.executeUpdate();
      if (returnKeys)
        result = pstmt.getGeneratedKeys();
    }
    System.out.println("Affected " + num + " rows");
    return result;
  }

  protected void setToStream(Statement stmt, boolean shouldStream) {
    try {
      String dbName = dbMeta.getDatabaseProductName();
      if (dbName.equals("MySQL")) {
        if (shouldStream) {
          stmt.setFetchSize(Integer.MIN_VALUE);
        } else {
          stmt.setFetchSize(0);
        }
      }
    } catch (SQLException e) {
      handleError(e);
    }
  }

  /**************************
   * Iterable interface
   *************************/

  public Iterator<SQLForestItem> iterator() {
    return this;
  }

  /**************************
   * Iterator interface
   *************************/

  private boolean peeked = false;
  @Override
  public boolean hasNext() {
    if (!peeked) {
      peeked = true;
      step();
    }
    return _next.type != END;
  }

  // Reuse to not create tons of objects
  @Override
  public SQLForestItem next() {
    if (!peeked) {
      step();
    } else {
      peeked = false;
    }
    if (_next.type == END) {
      throw new NoSuchElementException();
    }
    return _next;
  }

  private final SQLForestItem _next = new SQLForestItem();
  private boolean startedTable = false;
  private boolean startedIteration = false;
  private boolean endedIteration = false;
  private SQLForestItem step() {
    try {
      if (levels.isEmpty()) {
        if (!remainingQueries.hasNext()) {
          return _next.set(END, null, null);
        }
        QueryResults queryResults = startQueries(remainingQueries.next(), data);
        if (queryResults != null) {
          levels.push(queryResults, null);
        }
        return step();
      }
      QueryResults queryResults = levels.peek().queryResults;
      SQLQuery q = queryResults.query;
      ResultSetLike results = queryResults.results;
      Object currParent = levels.peek().currParent;
      boolean isPartOfTable = !q.isSingleRow();
      if (!startedTable && isPartOfTable) {
        startedTable = true;
        return _next.set(START_TABLE, q.getVar(), null);
      }
      if (currParent != null) {
        results.popOrphans();
      }
      if (!results.hasCurr()
          ||
          (currParent != null && !currParent.equals(results.getObject("parent")))) {
        levels.pop();
        if (isPartOfTable) {
          startedTable = false;
          return _next.set(END_TABLE, null, null);
        } else {
          return step();
        }
      }
      if (!startedIteration && isPartOfTable) {
        startedIteration = true;
        return _next.set(START_ITERATION, null, null);
      }

      ResultLevel level = levels.peek();
      if (!level.wroteElements) {
        if (q.getAction() == SQLAction.INSERT) {
          level.wroteElements = true;
          return _next.set(
            ELEMENT,
            q.insertResultName,
            results.getFirst()
          );
        } else {
          if (level.remainingProjections == null) {
            level.remainingProjections = queryResults.query.getProjections().iterator();
          }
          if (level.remainingProjections.hasNext()) {
            String name = level.remainingProjections.next().getLocation();
            return _next.set(
              ELEMENT,
              name,
              results.getObject(name)
            );
          } else {
            level.wroteElements = true;
          }
        }
      }

      if (level.remainingSubs == null) {
        level.remainingSubs = queryResults.subs.iterator();
      }
      if (level.remainingSubs.hasNext()) {
        Object subsParent = isPartOfTable ? results.getObject(q.getSubTag()) : null;
        QueryResults sub = level.remainingSubs.next();
        levels.push(
          sub,
          subsParent
        );
        return step();
      }

      if (!endedIteration && isPartOfTable) {
        endedIteration = true;
        return _next.set(END_ITERATION, null, null);
      }

      level.remainingSubs = null;
      level.remainingProjections = null;
      level.wroteElements = false;
      startedIteration = false;
      endedIteration = false;
      results.next();
      return step();
    } catch (SQLException e) {
      return handleError(e);
    }
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException();
  }

  /**************************
   * ForestReader interface
   *************************/

  @Override
  public Object get(String variable) {
    SQLForestItem next = next();
    shouldBe(next.type == ELEMENT && next.name.equals(variable));
    return next.value;
  }

  @Override
  public Iterable<ForestReader> getTable(String variable) {
    {
      SQLForestItem first = next();
      shouldBe(first.type == START_TABLE && first.name.equals(variable));
    }
    final JDBCForestReader reader = this;
    shouldBe(reader.hasNext());
    final boolean wasInTable = reader.inTable;
    reader.inTable = true;
    return new Iterable<ForestReader>() {
      public Iterator<ForestReader> iterator() {
        return new Iterator<ForestReader>() {
          private boolean first = true;
          private boolean peeked = false;
          private void step() {
            if (!first) {
              reader.next();
              shouldBe(reader._next.type == END_ITERATION);
            }
            reader.next();
            shouldBe(reader._next.type != END);
            if (reader._next.type == END_TABLE) {
              reader.inTable = wasInTable;
            }
          }
          public boolean hasNext() {
            if (!peeked) {
              peeked = true;
              step();
            }
            return reader._next.type != END_TABLE;
          }
          public ForestReader next() {
            if (!peeked) {
              step();
            } else {
              peeked = false;
            }
            first = false;
            if (reader._next.type != START_ITERATION) {
              throw new NoSuchElementException();
            }
            return reader;
          }
          public void remove() {
            throw new UnsupportedOperationException();
          }
        };
      }
    };
  }

  @Override
  public void complete() {
    if (!inTable) {
      if(_next.type != END) {
        // Finish any empty-result queries
        step();
      }
      shouldBe(_next.type == END);
      cleanUp();
    }
  }

  private void cleanUp() {
    // it is a good idea to release
    // resources in a finally{} block
    // in reverse-order of their creation
    // if they are no-longer needed

    if (stmt != null) {
      try {
        stmt.close();
      } catch (SQLException sqlEx) {
      } // ignore
    }

    if (conn != null) {
      try {
        conn.close();
      } catch (SQLException sqlEx) {
      } // ignore
    }
  }

  @Override
  public void copyTo(final ForestWriter out) {
    boolean nextIteration = false;
    Stack<ForestWriter> writers = new Stack<ForestWriter>() {{
      push(out);
    }};
    Stack<ForestListWriter> listWriters = new Stack<ForestListWriter>();

    for (SQLForestItem item : this) {
      // manage writers
      switch(item.type) {
      case ELEMENT:
      case START_TABLE:
          // be sure to start iterations
          if (nextIteration) {
            writers.push(listWriters.peek().newIteration());
            nextIteration = false;
          }
          break;
      case START_ITERATION:
          nextIteration = true;
          break;
      case END_ITERATION:
          if (!nextIteration) {
            // added element to iteration so pop writer
            writers.pop().complete();
          }
          break;
      }

      // manage listWriters
      switch (item.type) {
      case START_TABLE:
          listWriters.push(writers.peek().newTable(item.name));
          break;
      case END_TABLE:
          listWriters.pop().complete();
          break;
      }

      // write values
      switch (item.type) {
      case ELEMENT:
          writers.peek().put(item.name, item.value);
          break;
      }
    }
    out.complete();
    complete();
  }

  /**************************
   * Error handlers
   *************************/

  private <E> E handleError(SQLException ex) {
    cleanUp(); // clean up
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());
    throw new Error("database exception", ex);
  }

  private void shouldBe(boolean assertion) {
    if (!assertion) {
      shouldNotOccur();
    }
  }

  private void shouldNotOccur() {
    cleanUp();
    throw new Error("Invalid usage of JDBCForestReader, should not occur in generated code");
  }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using Encog.Persist;
using Encog.Util;
using Encog.Util.CSV;

namespace Encog.Neural.Thermal
{
    /// <summary>
    /// Persist the Hopfield network.
    /// </summary>
    ///
    public class PersistHopfield : IEncogPersistor
    {
        #region EncogPersistor Members

        /// <summary>
        /// The file version.
        /// </summary>
        public virtual int FileVersion
        {
            get { return 1; }
        }

        /// <summary>
        /// The class string.
        /// </summary>
        ///
        public virtual String PersistClassString
        {
            get { return typeof (HopfieldNetwork).Name; }
        }

        /// <summary>
        /// Read a an object.
        /// </summary>
        public Object Read(Stream mask0)
        {
            var result = new HopfieldNetwork();
            var ins0 = new EncogReadHelper(mask0);
            EncogFileSection section;

            while ((section = ins0.ReadNextSection()) != null)
            {
                if (section.SectionName.Equals("HOPFIELD")
                    && section.SubSectionName.Equals("PARAMS"))
                {
                    IDictionary<String, String> paras = section.ParseParams();
                    EngineArray.PutAll(paras, result.Properties);
                }
                if (section.SectionName.Equals("HOPFIELD")
                    && section.SubSectionName.Equals("NETWORK"))
                {
                    IDictionary<String, String> p = section.ParseParams();
                    result.Weights = NumberList.FromList(CSVFormat.EgFormat,
                                                         (p[PersistConst.Weights]));
                    result.SetCurrentState(NumberList.FromList(CSVFormat.EgFormat,
                                                               (p[PersistConst.Output])));
                    result.NeuronCount = EncogFileSection.ParseInt(p,
                                                                   PersistConst.NeuronCount);
                }
            }

            return result;
        }

        /// <summary>
        ///
        /// </summary>
        ///
        public void Save(Stream os, Object obj)
        {
            var xout = new EncogWriteHelper(os);
            var hopfield = (HopfieldNetwork) obj;
            xout.AddSection("HOPFIELD");
            xout.AddSubSection("PARAMS");
            xout.AddProperties(hopfield.Properties);
            xout.AddSubSection("NETWORK");
            xout.WriteProperty(PersistConst.Weights, hopfield.Weights);
            xout.WriteProperty(PersistConst.Output, hopfield.CurrentState.Data);
            xout.WriteProperty(PersistConst.NeuronCount, hopfield.NeuronCount);
            xout.Flush();
        }

        /// <inheritdoc/>
        public Type NativeType
        {
            get { return typeof(HopfieldNetwork); }
        }

        #endregion
    }
}


text:
<?php get_header(); ?>

                        Eleanor Palmer

                        Web Developer and Research Professional

Portfolio

About

My goal is to solve problems and communicate ideas in the best way possible.

My background in psychology research makes me uniquely suited for work in web development and market research. I build websites and analyze problems through keen attention to detail, all the while never losing sight of the big picture.

I am currently seeking full-time employment in North Carolina. I am also available for freelance work. Send me an e-mail and let me put my skills to use for you!

Skills

Javascript

jQuery

HTML

CSS

Bootstrap

Wordpress

Research Methods

Data Analysis

Education

Wake Forest University

M.A. in Psychology

St. Edward's University

B.A. in Psychology

Contact Me

                    <form name="sentMessage" id="contactForm" novalidate>

                                Name
                                <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">

                                Email Address
                                <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">

                                Phone Number
                                <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">

                                Message
                                <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-success btn-lg">Send</button>

                    </form>

North Star LGBT Center Website

Implemented a new website design for North Star LGBT Center by customizing a Wordpress child theme using CSS. Migrated old content to new web hosting.

Client:
                                    North Star LGBT Center

Date:
                                    August 2014

Skills:
                                    Wordpress Customization, CSS

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Google Clone

Clone of Google homepage built from scratch using HTML and CSS.

Client:
                                    Project for Thinkful: Front-End Web Development Course

Date:
                                    August 2014

Skills:
                                    HTML, CSS

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Project Title

Business website built from scratch using HTML and CSS. (Contact form not currently functional.)

Client:
                                    Project for Thinkful: Front-End Web Development Course

Date:
                                    September 2014

Skills:
                                    HTML, CSS

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Hot or Cold Game

Game functionality added using Javascript and jQuery.

Client:
                                    Project for Thinkful: Front-End Web Development Course

Date:
                                    January 2015

Skills:
                                    Javascript, jQuery

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Shopping List App

Shopping list app built from scratch using CSS, HTML, and jQuery.

Client:
                                    Project for Thinkful: Front-End Web Development Course

Date:
                                    September 2014

Skills:
                                    jQuery, Javascript, HTML, CSS

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Interactive Quiz

Interactive Javascript + jQuery Quiz on naming endangered animals.

Client:
                                    Project for Thinkful: Front-End Web Development Course

Date:
                                    January 2015

Skills:
                                    Javascript, jQuery, HTML, CSS

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

<?php get_footer(); ?>


text:
class VgFlickr

  def initialize(url=nil, options={})
    # general settings
    @url = url
    @video_id = parse_url(url)
    settings ||= YAML.load_file(RAILS_ROOT + '/config/unvlogable.yml') rescue {}
    @details = Flickr::Photo.new(@video_id, options.nil? || options[:key].nil? ? settings['flickr_key'] : options[:key])
    raise if @details.media != "video"
  end

  def title
    @details.title
  end

  def thumbnail
    @details.source('Small')
  end

  def embed_url
    "http://www.flickr.com/apps/video/stewart.swf?v=63881&intl_lang=en-us&photo_secret=#{@details.secret}&photo_id=#{@video_id}"
  end

  def embed_html(width=425, height=344, options={}, params={})
    "<object type='application/x-shockwave-flash' width='#{width}' height='#{height}' data='http://www.flickr.com/apps/video/stewart.swf?v=63881' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'><param name='movie' value='#{embed_url}'></param> <param name='bgcolor' value='#000000'></param> <param name='allowFullScreen' value='true'></param><embed type='application/x-shockwave-flash' src='#{embed_url}' bgcolor='#000000' allowfullscreen='true' width='#{width}' height='#{height}'></embed></object>"
  end

  def download_url
    nil
  end

  def duration
    nil
  end

  def service
    "Flickr"
  end

  private

  def parse_url(url)
    video_id = URI::parse(url).path.split("/")[3]
    raise unless video_id
    video_id
  rescue
    nil
  end

end


text: import pynamodb


text:
ReDoc makes use of the following [vendor extensions](http://swagger.io/specification/#vendorExtensions)

### Swagger Object vendor extensions
Extend OpenAPI root [Swagger Object](http://swagger.io/specification/#swaggerObject)
#### x-servers
Backported from OpenAPI 3.0 [`servers`](https://github.com/OAI/OpenAPI-Specification/blob/OpenAPI.next/versions/3.0.md#server-object). Currently doesn't support templates.

#### x-tagGroups

| Field Name     |	Type	       | Description |
| :------------- | :-----------: | :---------- |
| x-tagGroups         | [ [Tag Group Object](#tagGroupObject) ] | A list of tag groups |

###### Usage in Redoc
`x-tagGroups` is used to group tags in the side menu.
If you are going to use `x-tagGroups`, please make sure you **add all tags to a group**, since a tag that is not in a group, **will not be displayed** at all!

#### Tag Group Object
Information about tags group
###### Fixed fields
| Field Name  |	Type	     | Description |
| :---------- | :--------: | :---------- |
| name        | string     | The group name |
| tags        | [ string ] | List of tags to include in this group

###### x-tagGroups example
json
```json
{
  "x-tagGroups": [
    {
      "name": "User Management",
      "tags": ["Users", "API keys", "Admin"]
    },
    {
      "name": "Statistics",
      "tags": ["Main Stats", "Secondary Stats"]
    }
  ]
}
```
yaml
```yaml
x-tagGroups:
  - name: User Management
    tags:
      - Users
      - API keys
      - Admin
  - name: Statistics
    tags:
      - Main Stats
      - Secondary Stats
```

#### x-ignoredHeaderParameters

| Field Name                  |	Type	        | Description |
| :-------------------------- | :-----------: | :---------- |
| x-ignoredHeaderParameters   | [ string ] | A list of ignored headers |

###### Usage in Redoc
`x-ignoredHeaderParameters` is used to specify header parameter names which are ignored by ReDoc

###### x-ignoredHeaderParameters example
```yaml
swagger: '2.0'
info:
  ...
tags: [...]
x-ignoredHeaderParameters:
  - Accept
  - User-Agent
  - X-Test-Header
```

### Info Object vendor extensions
Extends OpenAPI [Info Object](http://swagger.io/specification/#infoObject)
#### x-logo

| Field Name     |	Type	       | Description |
| :------------- | :-----------: | :---------- |
| x-logo         | [Logo Object](#logoObject)  | The information about API logo |

###### Usage in Redoc
`x-logo` is used to specify API logo. The corresponding image are displayed just above side-menu.

#### Logo Object
The information about API logo
###### Fixed fields
| Field Name      |	Type	   | Description |
| :-------------- | :------: | :---------- |
| url             | string   | The URL pointing to the spec logo. MUST be in the format of a URL
| backgroundColor | string   | background color to be used. MUST be RGB color in [hexadecimal format] (https://en.wikipedia.org/wiki/Web_colors#Hex_triplet)

###### x-logo example
json
```json
{
  "info": {
    "version": "1.0.0",
    "title": "Swagger Petstore",
    "x-logo": {
      "url": "https://rebilly.github.io/ReDoc/petstore-logo.png",
      "backgroundColor": "#FFFFFF"
    }
  }
}
```
yaml
```yaml
info:
  version: "1.0.0"
  title: "Swagger Petstore"
  x-logo:
    url: "https://rebilly.github.io/ReDoc/petstore-logo.png"
    backgroundColor: "#FFFFFF"
```

### Tag Object vendor extensions
Extends OpenAPI [Tag Object](http://swagger.io/specification/#tagObject)
#### x-traitTag
| Field Name     |	Type	  | Description |
| :------------- | :------: | :---------- |
| x-traitTag     | boolean  | In Swagger two operations can have multiply tags. This property distinguish between tags that are used to group operations (default) from tags that are used to mark operation with certain trait (`true` value) |

#### x-displayName

| Field Name     |	Type	  | Description |
| :------------- | :------: | :---------- |
| x-displayName  | string   | Define the text that is used for this tag in the menu and in section headings |

###### Usage in Redoc
Tags that have `x-traitTag` set to `true` are listed in side-menu but don't have any subitems (operations). Tag `description` is rendered as well.
This is useful for handling out common things like Pagination, Rate-Limits, etc.

###### x-traitTag example
json
```json
{
    "name": "Pagination",
    "description": "Pagination description (can use markdown syntax)",
    "x-traitTag": true
}
```
yaml
```yaml
name: Pagination
description: Pagination description (can use markdown syntax)
x-traitTag: true
```

### Operation Object vendor extensions
Extends OpenAPI [Operation Object](http://swagger.io/specification/#operationObject)
#### x-code-samples
| Field Name     |	Type	  | Description |
| :------------- | :------: | :---------- |
| x-code-samples | [ [Code Sample Object](#codeSampleObject) ]  | A list of code samples associated with operation |

###### Usage in ReDoc
`x-code-samples` are rendered on the right panel of ReDoc

#### Code Sample Object
Operation code sample
###### Fixed fields
| Field Name  |	Type	   | Description  |
| :---------- | :------: | :----------- |
| lang        | string   | Code sample language. Value should be one of the following [list](https://github.com/github/linguist/blob/master/lib/linguist/popular.yml) |
| source      | string   | Code sample source code |

###### Code Sample Object example
json
```json
{
  "lang": "JavaScript",
  "source": "console.log('Hello World');"
}
```
yaml
```yaml
lang: JavaScript
source: console.log('Hello World');
```

### Parameter Object vendor extensions
Extends OpenAPI [Parameter Object](http://swagger.io/specification/#parameterObject)
#### x-examples
| Field Name     |  Type    | Description |
| :------------- | :------: | :---------- |
| x-examples | [Example Object](http://swagger.io/specification/#exampleObject)  | Object that contains examples for the request. Applies when `in` is `body` and mime-type is `application/json` |

###### Usage in ReDoc
`x-examples` are rendered in the JSON tab on the right panel of ReDoc.

### Schema Object vendor extensions
Extends OpenAPI [Schema Object](http://swagger.io/specification/#schemaObject)
#### x-nullable
| Field Name     |	Type	  | Description |
| :------------- | :------: | :---------- |
| x-nullable | boolean | marks schema as a nullable |

###### Usage in ReDoc
Schemas marked as `x-nullable` are marked in ReDoc with the label Nullable

#### x-extendedDiscriminator
**ATTENTION**: This is ReDoc-specific vendor extension. It won't be supported by other tools.

| Field Name     |	Type	  | Description |
| :------------- | :------: | :---------- |
| x-extendedDiscriminator | string | specifies extended discriminator |

###### Usage in ReDoc
ReDoc uses this vendor extension to solve name-clash issues with the standard `discriminator`.
Value of this field specifies the field which will be used as a extended discriminator.
ReDoc displays definition with selectpicker using which user can select value of the `x-extendedDiscriminator`-marked field.
ReDoc displays the definition which is derived from the current (using `allOf`) and has `enum` with only one value which is the same as the selected value of the field specified as `x-extendedDiscriminator`.

###### x-extendedDiscriminator example

```yaml

Payment:
  x-extendedDiscriminator: type
  type: object
  required:
    - type
  properties:
    type:
      type: string
    name:
      type: string

CashPayment:
  allOf:
    - $ref: "#/definitions/Payment"
    - properties:
        type:
          type: string
          enum:
            - cash
        currency:
          type: string

PayPalPayment:
  allOf:
    - $ref: "#/definitions/Payment"
    - properties:
        type:
          type: string
          enum:
            - paypal
        userEmail:
          type: string
```

In the example above the names of definitions (`PayPalPayment`) are named differently than
names in the payload (`paypal`) which is not supported by default `discriminator`.


text:
<?php
namespace Oro\Bundle\DataAuditBundle\Tests\Util\Async;

use Oro\Bundle\DataAuditBundle\Async\AuditChangedEntitiesProcessor;
use Oro\Bundle\DataAuditBundle\Async\Topics;
use Oro\Component\MessageQueue\Client\TopicSubscriberInterface;
use Oro\Component\Testing\ClassExtensionTrait;

class AuditChangedEntitiesProcessorTest extends \PHPUnit_Framework_TestCase
{
    use ClassExtensionTrait;

    public function testShouldSubscribeToEntitiesChangedTopic()
    {
        $this->assertClassImplements(TopicSubscriberInterface::class, AuditChangedEntitiesProcessor::class);
        $this->assertEquals(
            [Topics::ENTITIES_CHANGED],
            AuditChangedEntitiesProcessor::getSubscribedTopics()
        );
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
    license agreements. See the NOTICE file distributed with this work for additional
    information regarding copyright ownership. The ASF licenses this file to
    you 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. -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:soap="http://cxf.apache.org/bindings/soap" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cxf="http://cxf.apache.org/core"
    xmlns:p="http://cxf.apache.org/policy"
    xsi:schemaLocation="
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/policy http://cxf.apache.org/schemas/policy.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd ">

    <import resource="classpath:CONNECT-interceptor-beans.xml" />
    <context:property-placeholder/>
    <cxf:bus>
        <cxf:features>
            <p:policies />
        </cxf:features>
    </cxf:bus>

    <!-- Audit Services -->
    <jaxws:endpoint xmlns:tns="urn:gov:hhs:fha:nhinc:nhinccomponentauditrepository" id="AuditRepositoryManagerUnsecured"
        address="/GatewayService/AuditRepositoryManagerService" serviceName="tns:AuditRepositoryManagerService"
        endpointName="tns:AuditRepositoryManagerPort" implementor="gov.hhs.fha.nhinc.auditrepository.nhinc.AuditRepositoryUnsecured"
        wsdlLocation="classpath:wsdl/NhincComponentAuditRepository.wsdl">
    </jaxws:endpoint>

    <jaxws:endpoint xmlns:tns="urn:gov:hhs:fha:nhinc:nhinccomponentauditrepository" id="AuditRepositoryManagerSecured"
        address="/GatewayService/AuditRepositoryManagerSecuredService" serviceName="tns:AuditRepositoryManagerSecuredService"
        endpointName="tns:AuditRepositoryManagerSecuredPort" implementor="gov.hhs.fha.nhinc.auditrepository.nhinc.AuditRepository"
        wsdlLocation="classpath:wsdl/NhincComponentAuditRepositorySecured.wsdl">

        <jaxws:properties>
            <entry key="ws-security.signature.properties" value="file:///${nhinc.properties.dir}/signature.properties" />
            <entry key="ws-security.encryption.properties" value="file:///${nhinc.properties.dir}/truststore.properties" />
            <entry key="ws-security.saml2.validator">
                <bean class="gov.hhs.fha.nhinc.callback.cxf.CONNECTSamlAssertionValidator" />
            </entry>
        </jaxws:properties>

    </jaxws:endpoint>

    <!-- Patient Correlation Services -->

    <jaxws:endpoint xmlns:tns="urn:gov:hhs:fha:nhinc:nhinccomponentpatientcorrelation" id="PatientCorrelationUnsecured"
        address="/GatewayService/PatientCorrelationServiceUnsecured" serviceName="tns:PatientCorrelationService"
        endpointName="tns:PatientCorrelationPort" implementor="gov.hhs.fha.nhinc.patientcorrelation.nhinc.PatientCorrelationServiceUnsecured"
        wsdlLocation="classpath:wsdl/NhincComponentPatientCorrelation.wsdl">
    </jaxws:endpoint>

    <jaxws:endpoint xmlns:tns="urn:gov:hhs:fha:nhinc:nhinccomponentpatientcorrelation" id="PatientCorrelationSecured"
        address="/GatewayService/PatientCorrelationServiceSecured" serviceName="tns:PatientCorrelationServiceSecured"
        endpointName="tns:PatientCorrelationSecuredPort" implementor="gov.hhs.fha.nhinc.patientcorrelation.nhinc.PatientCorrelationServiceSecured"
        wsdlLocation="classpath:wsdl/NhincComponentPatientCorrelationSecured.wsdl">

        <jaxws:properties>
            <entry key="ws-security.signature.properties" value="file:///${nhinc.properties.dir}/signature.properties" />
            <entry key="ws-security.encryption.properties" value="file:///${nhinc.properties.dir}/truststore.properties" />
            <entry key="ws-security.saml2.validator">
                <bean class="gov.hhs.fha.nhinc.callback.cxf.CONNECTSamlAssertionValidator" />
            </entry>
        </jaxws:properties>

    </jaxws:endpoint>

    <bean id="SOAPHeaderHandler" class="gov.hhs.fha.nhinc.callback.SOAPHeaderHandler" />
    <bean id="TransactionHandler" class="gov.hhs.fha.nhinc.logging.transaction.TransactionHandler" />
</beans>


text:
package pb

const (
	AdminShellClient = "adminShell"
)


text:
var stdin = process.openStdin();

stdin.addListener("data", function(d) {
    // note:  d is an object, and when converted to a string it will
    // end with a linefeed.  so we (rather crudely) account for that
    // with toString() and then substring()
    console.log("you entered: [" +
        d.toString().trim() + "]");
    process.closeStdin();
  });


text:
var ChildProcess = require('child_process');

// Declare internals

var internals = {
    linters: {
        eslint: __dirname + '/linters/eslint/index.js',
        jslint: __dirname + '/linters/jslint/index.js'
    }
};

exports.lint = function (settings, callback) {

    var child = ChildProcess.fork(internals.linters[settings.linter],
                                  settings['lint-options'] ? [settings['lint-options']] : [],
                                  { cwd: settings.lintingPath });
    child.once('message', function (message) {

        child.kill();

        var result = { lint: message, totalErrors: 0, totalWarnings: 0 };

        result.lint.forEach(function (lint) {

            var errors = 0;
            var warnings = 0;

            lint.errors.forEach(function (e) {

                if (e.severity === 'ERROR') {
                    errors++;
                }
                else {
                    warnings++;
                }
            });

            lint.totalErrors = errors;
            lint.totalWarnings = warnings;
            result.totalErrors += errors;
            result.totalWarnings += warnings;
        });

        result.total = result.totalErrors + result.totalWarnings;

        return callback(null, result);
    });
};


text:
class BlipService < Service
  def self.handles?(uri)
    uri.host =~ /blip.tv$/
  end

  def self.shortname
    :blip
  end

  def self.longname
    "Blip"
  end

  def display_name
    "#{account} on Blip"
  end

  def account
      /\/(?<account>[\w-]+)$/ =~ @uri.path
    account
  end

  def service_url_example
    "http://www.blip.tv/username"
  end

  def service_url_canonical
    "http://blip.tv/#{account}"
  end

  private

  def fetch_details
    {
      :account => account,
    }
  end
end

Service.register(:blip, BlipService)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clickable="true"
                tools:background="#4c000000">

    <View
        android:id="@+id/dialog_top_view"
        android:layout_width="290dp"
        android:layout_height="48dp"
        android:layout_above="@+id/dialog_container_ll"
        android:layout_centerHorizontal="true"
        android:background="@android:color/transparent"
        android:visibility="gone"
        tools:background="#55000000"
        tools:visibility="visible"/>

    <LinearLayout
        android:id="@+id/dialog_container_ll"
        android:layout_width="290dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:background="@drawable/shape_dialog_normal"
        android:divider="@drawable/shape_linear_layout_vertical_split"
        android:orientation="vertical"
        android:showDividers="middle">

        <TextView
            android:id="@+id/dialog_title"
            style="@style/dialogTextSpecial"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:background="@drawable/shape_dialog_title"
            android:gravity="left|center_vertical"
            android:paddingLeft="18sp"
            tools:text="操作提示"/>

        <LinearLayout
            android:id="@+id/dialog_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_dialog_title"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/dialog_message"
                style="@style/dialogTextNormal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="left|center_vertical"
                android:minHeight="75dp"
                android:padding="18dp"
                android:visibility="gone"
                tools:text="这里是消息的内容"
                tools:visibility="visible"/>

            <EditText
                android:id="@+id/dialog_editor"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/shape_dialog_editor"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:hint="@string/dialog_editor_tip"
                android:maxHeight="120dp"
                android:minHeight="48dp"
                android:padding="10dp"
                android:scrollbars="none"
                android:textSize="14sp"
                android:visibility="gone"
                tools:visibility="visible"/>

            <ImageView
                android:id="@+id/dialog_image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:maxHeight="300dp"
                android:minHeight="60dp"
                android:scaleType="fitXY"
                android:visibility="gone"
                tools:visibility="visible"/>

            <xyz.zimuju.dialog.ProgressLayout
                android:id="@+id/dialog_spots_progress"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="@dimen/progress_margin"
                android:visibility="gone"
                tools:visibility="visible"/>
        </LinearLayout>
    </LinearLayout>

    <View
        android:id="@+id/dialog_bottom_view"
        android:layout_width="290dp"
        android:layout_height="48dp"
        android:layout_below="@id/dialog_container_ll"
        android:layout_centerHorizontal="true"
        android:background="@android:color/transparent"
        android:visibility="gone"
        tools:background="#55000000"
        tools:visibility="visible"/>
</RelativeLayout>


text:
import { app } from 'electron';
import * as electronDownloader from 'electron-dl';
import * as shellPath from 'shell-path';

import { isDevEnv, isElectronQA, isLinux, isMac } from '../common/env';
import { logger } from '../common/logger';
import { getCommandLineArgs } from '../common/utils';
import { cleanUpAppCache, createAppCacheFile } from './app-cache-handler';
import { autoLaunchInstance } from './auto-launch-controller';
import { setChromeFlags, setSessionProperties } from './chrome-flags';
import { config } from './config-handler';
import './dialog-handler';
import './main-api-handler';
import { handlePerformanceSettings } from './perf-handler';
import { protocolHandler } from './protocol-handler';
import { ICustomBrowserWindow, windowHandler } from './window-handler';

logger.info(`App started with the args ${JSON.stringify(process.argv)}`);

const allowMultiInstance: string | boolean = getCommandLineArgs(process.argv, '--multiInstance', true) || isDevEnv;
let isAppAlreadyOpen: boolean = false;

// Setting the env path child_process issue https://github.com/electron/electron/issues/7688
(async () => {
    try {
        const paths = await shellPath();
        if (paths) {
            return process.env.PATH = paths;
        }
        if (isMac) {
            process.env.PATH = [
                './node_modules/.bin',
                '/usr/local/bin',
                process.env.PATH,
            ].join(':');
        }
    } catch (e) {
        if (isMac) {
            process.env.PATH = [
                './node_modules/.bin',
                '/usr/local/bin',
                process.env.PATH,
            ].join(':');
        }
    }
})();

electronDownloader();
handlePerformanceSettings();
setChromeFlags();

// Need this to prevent blank pop-out from 8.x versions
// Refer - SDA-1877 - https://github.com/electron/electron/issues/18397
if (!isElectronQA) {
    app.allowRendererProcessReuse = true;
}

// Electron sets the default protocol
if (!isDevEnv) {
    app.setAsDefaultProtocolClient('symphony');
}

/**
 * Main function that init the application
 */
const startApplication = async () => {
    await app.whenReady();
    logger.info(`main: app is ready, performing initial checks`);
    createAppCacheFile();
    windowHandler.createApplication();
    logger.info(`main: created application`);

    if (config.isFirstTimeLaunch()) {
        logger.info(`main: This is a first time launch! will update config and handle auto launch`);
        await config.setUpFirstTimeLaunch();
        if (!isLinux) {
            await autoLaunchInstance.handleAutoLaunch();
        }
    }

    // Setup session properties only after app ready
    setSessionProperties();
};

// Handle multiple/single instances
if (!allowMultiInstance) {
    logger.info('main: Multiple instances are not allowed, requesting lock', { allowMultiInstance });
    const gotTheLock = app.requestSingleInstanceLock();

    // quit if another instance is already running, ignore for dev env or if app was started with multiInstance flag
    if (!gotTheLock) {
        logger.info(`main: got the lock hence closing the new instance`, { gotTheLock });
        app.exit();
    } else {
        logger.info(`main: Creating the first instance of the application`);
        app.on('second-instance', (_event, argv) => {
            // Someone tried to run a second instance, we should focus our window.
            logger.info(`main: We've got a second instance of the app, will check if it's allowed and exit if not`);
            const mainWindow = windowHandler.getMainWindow();
            if (mainWindow && !mainWindow.isDestroyed()) {
                if (isMac) {
                    logger.info(`main: We are on mac, so, showing the existing window`);
                    return mainWindow.show();
                }
                if (mainWindow.isMinimized()) {
                    logger.info(`main: our main window is minimised, will restore it!`);
                    mainWindow.restore();
                }
                mainWindow.focus();
                isAppAlreadyOpen = true;
                protocolHandler.processArgv(argv, isAppAlreadyOpen);
            }
        });
        startApplication();
    }
} else {
    logger.info(`main: multi instance allowed, creating second instance`, { allowMultiInstance });
    startApplication();
}

/**
 * Is triggered when all the windows are closed
 * In which case we quit the app
 */
app.on('window-all-closed', () => {
    logger.info(`main: all windows are closed, quitting the app!`);
    app.quit();
});

/**
 * Creates a new empty cache file when the app is quit
 */
app.on('quit',  () => {
    logger.info(`main: quitting the app!`);
    cleanUpAppCache();
});

/**
 * Cleans up reference before quiting
 */
app.on('before-quit', () => windowHandler.willQuitApp = true);

/**
 * Is triggered when the application is launched
 * or clicking the application's dock or taskbar icon
 *
 * This event is emitted only on macOS at this moment
 */
app.on('activate', () => {
    const mainWindow: ICustomBrowserWindow | null = windowHandler.getMainWindow();
    if (!mainWindow || mainWindow.isDestroyed()) {
        logger.info(`main: main window not existing or destroyed, creating a new instance of the main window!`);
        startApplication();
        return;
    }
    logger.info(`main: activating & showing main window now!`);
    mainWindow.show();
});

/**
 * Validates and Sends protocol action
 *
 * This event is emitted only on macOS at this moment
 */
app.on('open-url', (_event, url) => {
    logger.info(`main: we got a protocol request with url ${url}! processing the request!`);
    protocolHandler.sendProtocol(url);
});


text:
<?php

namespace Admin\MaintenanceBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * EmployeeAnswers
 *
 * @ORM\Table(name="employee_answers", indexes={@ORM\Index(name="IDX_D09C90096BC704C7", columns={"q_id"}), @ORM\Index(name="IDX_D09C900961220EA6", columns={"creator_id"})})
 * @ORM\Entity
 */
class EmployeeAnswers
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="actionstamp", type="datetime", nullable=false)
     */
    private $actionstamp;

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=150, nullable=false)
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="value", type="string", length=150, nullable=false)
     */
    private $value;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="employee_answers_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var \Feedback\SurveyFormBundle\Entity\Questions
     *
     * @ORM\ManyToOne(targetEntity="Feedback\SurveyFormBundle\Entity\Questions")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="q_id", referencedColumnName="id")
     * })
     */
    private $q;

    /**
     * @var \Feedback\SurveyFormBundle\Entity\UserAccount
     *
     * @ORM\ManyToOne(targetEntity="Feedback\SurveyFormBundle\Entity\UserAccount")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="creator_id", referencedColumnName="id")
     * })
     */
    private $creator;

    /**
     * Set actionstamp
     *
     * @param \DateTime $actionstamp
     * @return EmployeeAnswers
     */
    public function setActionstamp($actionstamp)
    {
        $this->actionstamp = $actionstamp;

        return $this;
    }

    /**
     * Get actionstamp
     *
     * @return \DateTime
     */
    public function getActionstamp()
    {
        return $this->actionstamp;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return EmployeeAnswers
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set value
     *
     * @param string $value
     * @return EmployeeAnswers
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * Get value
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set q
     *
     * @param \Feedback\SurveyFormBundle\Entity\Questions $q
     * @return EmployeeAnswers
     */
    public function setQ( $q = null)
    {
        $this->q = $q;

        return $this;
    }

    /**
     * Get q
     *
     * @return \Feedback\SurveyFormBundle\Entity\Questions
     */
    public function getQ()
    {
        return $this->q;
    }

    /**
     * Set creator
     *
     * @param \Feedback\SurveyFormBundle\Entity\UserAccount $creator
     * @return EmployeeAnswers
     */
    public function setCreator(\Feedback\SurveyFormBundle\Entity\UserAccount $creator = null)
    {
        $this->creator = $creator;

        return $this;
    }

    /**
     * Get creator
     *
     * @return \Feedback\SurveyFormBundle\Entity\UserAccount
     */
    public function getCreator()
    {
        return $this->creator;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="abc_action_bar_home_description" msgid="4600421777120114993">"Navigeren naar startpositie"</string>
    <string name="abc_action_bar_home_description_format" msgid="1397052879051804371">"%1$s, %2$s"</string>
    <string name="abc_action_bar_home_subtitle_description_format" msgid="6623331958280229229">"%1$s, %2$s, %3$s"</string>
    <string name="abc_action_bar_up_description" msgid="1594238315039666878">"Omhoog navigeren"</string>
    <string name="abc_action_menu_overflow_description" msgid="3588849162933574182">"Meer opties"</string>
    <string name="abc_action_mode_done" msgid="4076576682505996667">"Gereed"</string>
    <string name="abc_activity_chooser_view_see_all" msgid="7468859129482906941">"Alles weergeven"</string>
    <string name="abc_activitychooserview_choose_application" msgid="2031811694353399454">"Een app selecteren"</string>
    <string name="abc_searchview_description_clear" msgid="3691816814315814921">"Zoekopdracht wissen"</string>
    <string name="abc_searchview_description_query" msgid="2550479030709304392">"Zoekopdracht"</string>
    <string name="abc_searchview_description_search" msgid="8264924765203268293">"Zoeken"</string>
    <string name="abc_searchview_description_submit" msgid="8928215447528550784">"Zoekopdracht verzenden"</string>
    <string name="abc_searchview_description_voice" msgid="893419373245838918">"Gesproken zoekopdracht"</string>
    <string name="abc_shareactionprovider_share_with" msgid="3421042268587513524">"Delen met"</string>
    <string name="abc_shareactionprovider_share_with_application" msgid="7165123711973476752">"Delen met %s"</string>

</resources>


text:
Brisket.Controller
================

Brisket provides a Controller object that provides semantics only. There is no functionality provided by the Brisket.Controller but you can use it to move logic off of a Brisket Router.

## A Use Case For a Controller
We have a route that displays an article:

```js
var ArticleRouter = RouterBrewery.create({

    routes: {
        'article/:id': 'article'
    },

    article: function(id) {
        return new ArticleView();
    }

});
```

We now want to add an article preview route without duplicating the logic in the article handler. The following will NOT work:

```js
var ArticleRouter = RouterBrewery.create({

    routes: {
        'article/:id': 'article',
        'preview/article/:id': 'previewArticle'
    },

    article: function(id, preview) {
        return new ArticleView({ preview: preview });
    },

    previewArticle: function(id) {
        return this.article(id, preview);
    }

});
```

It will not work because Brisket Router route handlers are actually modified by Brisket on creation. Use a Controller to move this logic off of the Router:

```js
var ArticleController = Brisket.Controller.extend({

    article: function(id, preview) {
        return new ArticleView({ preview: preview });
    },

    previewArticle: function(id) {
        return this.article(id, preview);
    }

});

var ArticleRouter = RouterBrewery.create({

    routes: {
        'article/:id': 'article',
        'preview/article/:id': 'previewArticle'
    },

    article: function(id) {
        return new ArticleController().article(id);
    },

    previewArticle: function(id) {
        return new ArticleController().previewArticle(id);
    }

});
```

If you do NOT have this use case, you can happily use Routers alone without any problems.


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

<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="platformConfiguration">
            <bean class="org.apache.ignite.platform.dotnet.PlatformDotNetConfiguration">
                <property name="binaryConfiguration">
                    <bean class="org.apache.ignite.platform.dotnet.PlatformDotNetBinaryConfiguration">
                        <property name="types">
                            <list>
                                <value>Apache.Ignite.ExamplesDll.Binary.Account</value>
                                <value>Apache.Ignite.ExamplesDll.Binary.Address</value>
                                <value>Apache.Ignite.ExamplesDll.Binary.Employee</value>
                                <value>Apache.Ignite.ExamplesDll.Binary.EmployeeKey</value>
                                <value>Apache.Ignite.ExamplesDll.Binary.Organization</value>
                            </list>
                        </property>
                        <property name="typesConfiguration">
                            <list>
                                <bean class="org.apache.ignite.platform.dotnet.PlatformDotNetBinaryTypeConfiguration">
                                    <property name="typeName" value="Apache.Ignite.ExamplesDll.Binary.OrganizationType" />
                                    <property name="enum" value="true" />
                                </bean>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>

        <property name="cacheConfiguration">
            <list>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="name" value="cache*"/>
                    <property name="atomicityMode" value="ATOMIC"/>
                    <property name="backups" value="1"/>
                </bean>

                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="name" value="tx"/>
                    <property name="atomicityMode" value="TRANSACTIONAL"/>
                    <property name="backups" value="1"/>
                </bean>
            </list>
        </property>

        <!-- Explicitly configure TCP discovery SPI to provide list of initial nodes. -->
        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
                        <property name="addresses">
                            <list>
                                <!-- In distributed environment, replace with actual host IP address. -->
                                <value>127.0.0.1:47500..47501</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>


text:
package util

import javax.inject.Inject

import akka.actor.ActorSystem
import akka.util.Timeout
import api.ErrorResult
import asobu.distributed.gateway.AbstractKanaloaBridge
import kanaloa.reactive.dispatcher._
import play.api.Configuration
import concurrent.duration._

class KanaloaBridge @Inject() (configuration: Configuration, system: ActorSystem) extends AbstractKanaloaBridge()(configuration, system, KanaloaBridge.clusterStartupTimeout) {

  override protected def resultChecker: ResultChecker = {
    case e: ErrorResult[_] ⇒ Left(e.toString)
    case m                ⇒ Right(m)
  }
}

object KanaloaBridge {
  val clusterStartupTimeout: Timeout = 30.seconds
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_file_44.c
Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml
Template File: source-sinks-44.tmpl.c
*/
/*
 * @description
 * CWE: 761 Free Pointer not at Start of Buffer
 * BadSource: file Read input from a file
 * Sinks:
 *    GoodSink: free() memory correctly at the start of the buffer
 *    BadSink : free() memory not at the start of the buffer
 * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif

#define SEARCH_CHAR 'S'

#ifndef OMITBAD

static void badSink(char * data)
{
    /* FLAW: We are incrementing the pointer in the loop - this will cause us to free the
     * memory block not at the start of the buffer */
    for (; *data != '\0'; data++)
    {
        if (*data == SEARCH_CHAR)
        {
            printLine("We have a match!");
            break;
        }
    }
    free(data);
}

void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_file_44_bad()
{
    char * data;
    /* define a function pointer */
    void (*funcPtr) (char *) = badSink;
    data = (char *)malloc(100*sizeof(char));
    if (data == NULL) {exit(-1);}
    data[0] = '\0';
    {
        /* Read input from a file */
        size_t dataLen = strlen(data);
        FILE * pFile;
        /* if there is room in data, attempt to read the input from a file */
        if (100-dataLen > 1)
        {
            pFile = fopen(FILENAME, "r");
            if (pFile != NULL)
            {
                /* POTENTIAL FLAW: Read data from a file */
                if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                {
                    printLine("fgets() failed");
                    /* Restore NUL terminator if fgets fails */
                    data[dataLen] = '\0';
                }
                fclose(pFile);
            }
        }
    }
    /* use the function pointer */
    funcPtr(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2GSink(char * data)
{
    {
        size_t i;
        /* FIX: Use a loop variable to traverse through the string pointed to by data */
        for (i=0; i < strlen(data); i++)
        {
            if (data[i] == SEARCH_CHAR)
            {
                printLine("We have a match!");
                break;
            }
        }
        free(data);
    }
}

static void goodB2G()
{
    char * data;
    void (*funcPtr) (char *) = goodB2GSink;
    data = (char *)malloc(100*sizeof(char));
    if (data == NULL) {exit(-1);}
    data[0] = '\0';
    {
        /* Read input from a file */
        size_t dataLen = strlen(data);
        FILE * pFile;
        /* if there is room in data, attempt to read the input from a file */
        if (100-dataLen > 1)
        {
            pFile = fopen(FILENAME, "r");
            if (pFile != NULL)
            {
                /* POTENTIAL FLAW: Read data from a file */
                if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL)
                {
                    printLine("fgets() failed");
                    /* Restore NUL terminator if fgets fails */
                    data[dataLen] = '\0';
                }
                fclose(pFile);
            }
        }
    }
    funcPtr(data);
}

void CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_file_44_good()
{
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_file_44_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_file_44_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package com.orientechnologies.orient.server.network.http;

import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

/**
 * Base test class for HTTP protocol.
 *
 * @author Luca Garulli (l.garulli--at-orientechnologies.com)
 */
public abstract class BaseHttpTest {

  private static OServer     server;
  private boolean            autoshutdownServer = false;

  private String             serverCfg          = "/com/orientechnologies/orient/server/network/orientdb-server-config-httponly.xml";
  private String             protocol           = "http";
  private String             host               = "localhost";
  private int                port               = 2498;
  private String             realm              = "OrientDB-";
  private String             userName           = "admin";
  private String             userPassword       = "admin";
  private String             databaseName;
  private Boolean            keepAlive          = null;

  private HttpRequestBase    request;
  private AbstractHttpEntity payload;
  private HttpResponse       response;
  private int                retry              = 1;

  public enum CONTENT {
    TEXT, JSON
  }

  public BaseHttpTest payload(final String s, final CONTENT iContent) {
    payload = new StringEntity(s, ContentType.create(iContent == CONTENT.JSON ? "application/json" : "plain/text", Consts.UTF_8));
    return this;
  }

  protected void startServer() throws Exception {
    if (server == null) {
      server = OServerMain.create();
      server.startup(getClass().getResourceAsStream(getServerCfg()));
      server.activate();
    }
  }

  protected void stopServer() throws Exception {
    if (autoshutdownServer && server != null) {
      server.shutdown();
      server = null;
    }
  }

  protected BaseHttpTest exec() throws IOException {
    final HttpHost targetHost = new HttpHost(getHost(), getPort(), getProtocol());

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(getUserName(), getUserPassword()));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);

    if (keepAlive != null)
      request.addHeader("Connection", keepAlive ? "Keep-Alive" : "Close");

    if (payload != null && request instanceof HttpEntityEnclosingRequestBase)
      ((HttpEntityEnclosingRequestBase) request).setEntity(payload);

    final CloseableHttpClient httpClient = HttpClients.createDefault();

//    DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(retry, false);
//    context.setAttribute(HttpMethodParams.RETRY_HANDLER, retryhandler);

    response = httpClient.execute(targetHost, request, context);

    return this;
  }

  protected BaseHttpTest get(final String url) throws IOException {
    request = new HttpGet(getBaseURL() + "/" + url);
    response = null;
    return this;
  }

  protected BaseHttpTest post(final String url) throws IOException {
    request = new HttpPost(getBaseURL() + "/" + url);
    response = null;
    return this;
  }

  protected BaseHttpTest put(final String url) throws IOException {
    request = new HttpPut(getBaseURL() + "/" + url);
    response = null;
    return this;
  }

  protected BaseHttpTest delete(final String url) throws IOException {
    request = new HttpDelete(getBaseURL() + "/" + url);
    response = null;
    return this;
  }

  protected HttpResponse getResponse() throws IOException {
    if (response == null)
      exec();
    return response;
  }

  protected BaseHttpTest setKeepAlive(final boolean iValue) {
    keepAlive = iValue;
    return this;
  }

  protected String getBaseURL() {
    return getProtocol() + "://" + getHost() + ":" + getPort();
  }

  public String getUserName() {
    return userName;
  }

  protected BaseHttpTest setUserName(final String userName) {
    this.userName = userName;
    return this;
  }

  public BaseHttpTest setRetry(final int iRetry) {
    retry = iRetry;
    return this;
  }

  protected String getUserPassword() {
    return userPassword;
  }

  protected BaseHttpTest setUserPassword(final String userPassword) {
    this.userPassword = userPassword;
    return this;
  }

  protected String getProtocol() {
    return protocol;
  }

  protected String getHost() {
    return host;
  }

  protected int getPort() {
    return port;
  }

  protected String getServerCfg() {
    return serverCfg;
  }

  protected BaseHttpTest setServerCfg(String serverCfg) {
    this.serverCfg = serverCfg;
    return this;
  }

  protected String getDatabaseName() {
    return databaseName;
  }

  protected String getRealm() {
    return realm;
  }

  protected BaseHttpTest setRealm(String realm) {
    this.realm = realm;
    return this;
  }
}


text:
import {LitElement, css, html, customElement, property, PropertyValues} from 'lit-element';
import {styleMap} from 'lit-html/directives/style-map.js';

import '@material/mwc-icon';

@customElement('litmail-nav-menu-item')
export class LitMailNavMenuItem extends LitElement {

  static styles = [css`
    :host {
      display: flex;
      align-items: center;
      height: 48px;
      padding: 0 16px;
      text-overflow: ellipsis;
      border-radius: 24px;
      cursor: pointer;
    }
    :host(:hover) {
      background: var(--primary-highlight);
    }
    :host([selected]) {
      color: var(--mdc-theme-secondary);
    }
    mwc-icon {
      margin-right: 12px;
    }
  `];

  @property({
    type: Boolean,
    reflect: true,
  })
  selected = false;

  @property()
  icon?: string;

  @property()
  color?: string;

  @property({
    attribute: 'label-id',
    reflect: true,
  })
  labelId?: string;

  constructor() {
    super();
    this.addEventListener('click', () => {
      this.dispatchEvent(new CustomEvent('litmail-nav-select', {
        bubbles: true,
        detail: { labelId: this.labelId }
      }));
    });
  }

  render() {
    return html`
      <mwc-icon style=${styleMap({color: this.color || 'inherit'})}>
        ${this.icon}
      </mwc-icon>
      <slot></slot>
    `;
  }

}


text:
FROM %%KOLLA_NAMESPACE%%/%%KOLLA_PREFIX%%base:%%KOLLA_TAG%%
MAINTAINER Kolla Project (https://launchpad.net/kolla)

ADD ./start.sh /start.sh

# Install required packages
RUN yum install -y gcc Cython sqlite-devel mysql-devel libffi-devel && yum clean all

# use the Barbican Juno version
# setting this as environment variable also keeps pbr version checking happy
# TODO: when the Barbican rpm from cloudkeep.io is usable,
# switch to using that instead
ENV PBR_VERSION 2014.2

# Get and extract the Barbican tar ball
RUN curl -o /barbican-$PBR_VERSION.tar.gz https://github.com/openstack/barbican/archive/$PBR_VERSION.tar.gz -L
RUN tar -xzf barbican-$PBR_VERSION.tar.gz

# Install Barbican requirements
RUN pip install -r barbican-$PBR_VERSION/requirements.txt
RUN pip install MySQL-python

# Install Barbican
RUN cd barbican-$PBR_VERSION && python setup.py install

# Configure Barbican
RUN mkdir -p /etc/barbican
RUN mkdir -p /var/log/barbican
RUN cp -r /barbican-$PBR_VERSION/etc/barbican/* /etc/barbican

# Instal uwsgi as that is what we will use to run Barbican
RUN pip install uwsgi

# Cleanup files not required anymore
RUN rm -rf /barbican-$PBR_VERSION
RUN rm -rf /barbican-$PBR_VERSION.tar.gz

CMD ["/start.sh"]