text:
package kafka.tools;

import joptsimple.*;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import kafka.utils.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * This is a  kafka 0.7 to 0.8 online migration tool used for migrating data from 0.7 to 0.8 cluster. Internally,
 * it's composed of a kafka 0.7 consumer and kafka 0.8 producer. The kafka 0.7 consumer consumes data from the
 * 0.7 cluster, and the kafka 0.8 producer produces data to the 0.8 cluster.
 *
 * The 0.7 consumer is loaded from kafka 0.7 jar using a "parent last, child first" java class loader.
 * Ordinary class loader is "parent first, child last", and kafka 0.8 and 0.7 both have classes for a lot of
 * class names like "kafka.consumer.Consumer", etc., so ordinary java URLClassLoader with kafka 0.7 jar will
 * will still load the 0.8 version class.
 *
 * As kafka 0.7 and kafka 0.8 used different version of zkClient, the zkClient jar used by kafka 0.7 should
 * also be used by the class loader.
 *
 * The user need to provide the configuration file for 0.7 consumer and 0.8 producer. For 0.8 producer,
 * the "serializer.class" config is set to "kafka.serializer.DefaultEncoder" by the code.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public class KafkaMigrationTool
{
  private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(KafkaMigrationTool.class.getName());
  private static final String KAFKA_07_STATIC_CONSUMER_CLASS_NAME = "kafka.consumer.Consumer";
  private static final String KAFKA_07_CONSUMER_CONFIG_CLASS_NAME = "kafka.consumer.ConsumerConfig";
  private static final String KAFKA_07_CONSUMER_STREAM_CLASS_NAME = "kafka.consumer.KafkaStream";
  private static final String KAFKA_07_CONSUMER_ITERATOR_CLASS_NAME = "kafka.consumer.ConsumerIterator";
  private static final String KAFKA_07_CONSUMER_CONNECTOR_CLASS_NAME = "kafka.javaapi.consumer.ConsumerConnector";
  private static final String KAFKA_07_MESSAGE_AND_METADATA_CLASS_NAME = "kafka.message.MessageAndMetadata";
  private static final String KAFKA_07_MESSAGE_CLASS_NAME = "kafka.message.Message";
  private static final String KAFKA_07_WHITE_LIST_CLASS_NAME = "kafka.consumer.Whitelist";
  private static final String KAFKA_07_TOPIC_FILTER_CLASS_NAME = "kafka.consumer.TopicFilter";
  private static final String KAFKA_07_BLACK_LIST_CLASS_NAME = "kafka.consumer.Blacklist";

  private static Class<?> KafkaStaticConsumer_07 = null;
  private static Class<?> ConsumerConfig_07 = null;
  private static Class<?> ConsumerConnector_07 = null;
  private static Class<?> KafkaStream_07 = null;
  private static Class<?> TopicFilter_07 = null;
  private static Class<?> WhiteList_07 = null;
  private static Class<?> BlackList_07 = null;
  private static Class<?> KafkaConsumerIteratorClass_07 = null;
  private static Class<?> KafkaMessageAndMetatDataClass_07 = null;
  private static Class<?> KafkaMessageClass_07 = null;

  public static void main(String[] args) throws InterruptedException, IOException {
    OptionParser parser = new OptionParser();
    ArgumentAcceptingOptionSpec<String> consumerConfigOpt
      = parser.accepts("consumer.config", "Kafka 0.7 consumer config to consume from the source 0.7 cluster. " + "You man specify multiple of these.")
      .withRequiredArg()
      .describedAs("config file")
      .ofType(String.class);

    ArgumentAcceptingOptionSpec<String> producerConfigOpt
      =  parser.accepts("producer.config", "Producer config.")
      .withRequiredArg()
      .describedAs("config file")
      .ofType(String.class);

    ArgumentAcceptingOptionSpec<Integer> numProducersOpt
      =  parser.accepts("num.producers", "Number of producer instances")
      .withRequiredArg()
      .describedAs("Number of producers")
      .ofType(Integer.class)
      .defaultsTo(1);

    ArgumentAcceptingOptionSpec<String> zkClient01JarOpt
      = parser.accepts("zkclient.01.jar", "zkClient 0.1 jar file")
      .withRequiredArg()
      .describedAs("zkClient 0.1 jar file required by Kafka 0.7")
      .ofType(String.class);

    ArgumentAcceptingOptionSpec<String> kafka07JarOpt
      = parser.accepts("kafka.07.jar", "Kafka 0.7 jar file")
      .withRequiredArg()
      .describedAs("kafka 0.7 jar")
      .ofType(String.class);

    ArgumentAcceptingOptionSpec<Integer> numStreamsOpt
      = parser.accepts("num.streams", "Number of consumer streams")
      .withRequiredArg()
      .describedAs("Number of consumer threads")
      .ofType(Integer.class)
      .defaultsTo(1);

    ArgumentAcceptingOptionSpec<String> whitelistOpt
      = parser.accepts("whitelist", "Whitelist of topics to migrate from the 0.7 cluster")
      .withRequiredArg()
      .describedAs("Java regex (String)")
      .ofType(String.class);

    ArgumentAcceptingOptionSpec<String> blacklistOpt
      = parser.accepts("blacklist", "Blacklist of topics to migrate from the 0.7 cluster")
      .withRequiredArg()
      .describedAs("Java regex (String)")
      .ofType(String.class);

    ArgumentAcceptingOptionSpec<Integer> queueSizeOpt
      =  parser.accepts("queue.size", "Number of messages that are buffered between the 0.7 consumer and 0.8 producer")
      .withRequiredArg()
      .describedAs("Queue size in terms of number of messages")
      .ofType(Integer.class)
      .defaultsTo(10000);

    OptionSpecBuilder helpOpt
      = parser.accepts("help", "Print this message.");

    OptionSet options = parser.parse(args);

    if (options.has(helpOpt)) {
      parser.printHelpOn(System.out);
      System.exit(0);
    }

    checkRequiredArgs(parser, options, new OptionSpec[]{consumerConfigOpt, producerConfigOpt, zkClient01JarOpt, kafka07JarOpt});
    int whiteListCount = options.has(whitelistOpt) ? 1 : 0;
    int blackListCount = options.has(blacklistOpt) ? 1 : 0;
    if(whiteListCount + blackListCount != 1) {
      System.err.println("Exactly one of whitelist or blacklist is required.");
      System.exit(1);
    }

    String kafkaJarFile_07 = options.valueOf(kafka07JarOpt);
    String zkClientJarFile = options.valueOf(zkClient01JarOpt);
    String consumerConfigFile_07 = options.valueOf(consumerConfigOpt);
    int numConsumers = options.valueOf(numStreamsOpt);
    String producerConfigFile_08 = options.valueOf(producerConfigOpt);
    int numProducers = options.valueOf(numProducersOpt);
    final List<MigrationThread> migrationThreads = new ArrayList<MigrationThread>(numConsumers);
    final List<ProducerThread> producerThreads = new ArrayList<ProducerThread>(numProducers);

    try {
      File kafkaJar_07 = new File(kafkaJarFile_07);
      File zkClientJar = new File(zkClientJarFile);
      ParentLastURLClassLoader c1 = new ParentLastURLClassLoader(new URL[] {
        kafkaJar_07.toURI().toURL(),
        zkClientJar.toURI().toURL()
      });

      /** Construct the 07 consumer config **/
      ConsumerConfig_07 = c1.loadClass(KAFKA_07_CONSUMER_CONFIG_CLASS_NAME);
      KafkaStaticConsumer_07 = c1.loadClass(KAFKA_07_STATIC_CONSUMER_CLASS_NAME);
      ConsumerConnector_07 = c1.loadClass(KAFKA_07_CONSUMER_CONNECTOR_CLASS_NAME);
      KafkaStream_07 = c1.loadClass(KAFKA_07_CONSUMER_STREAM_CLASS_NAME);
      TopicFilter_07 = c1.loadClass(KAFKA_07_TOPIC_FILTER_CLASS_NAME);
      WhiteList_07 = c1.loadClass(KAFKA_07_WHITE_LIST_CLASS_NAME);
      BlackList_07 = c1.loadClass(KAFKA_07_BLACK_LIST_CLASS_NAME);
      KafkaMessageClass_07 = c1.loadClass(KAFKA_07_MESSAGE_CLASS_NAME);
      KafkaConsumerIteratorClass_07 = c1.loadClass(KAFKA_07_CONSUMER_ITERATOR_CLASS_NAME);
      KafkaMessageAndMetatDataClass_07 = c1.loadClass(KAFKA_07_MESSAGE_AND_METADATA_CLASS_NAME);

      Constructor ConsumerConfigConstructor_07 = ConsumerConfig_07.getConstructor(Properties.class);
      Properties kafkaConsumerProperties_07 = new Properties();
      kafkaConsumerProperties_07.load(new FileInputStream(consumerConfigFile_07));
      /** Disable shallow iteration because the message format is different between 07 and 08, we have to get each individual message **/
      if(kafkaConsumerProperties_07.getProperty("shallow.iterator.enable", "").equals("true")) {
        logger.warn("Shallow iterator should not be used in the migration tool");
        kafkaConsumerProperties_07.setProperty("shallow.iterator.enable", "false");
      }
      Object consumerConfig_07 = ConsumerConfigConstructor_07.newInstance(kafkaConsumerProperties_07);

      /** Construct the 07 consumer connector **/
      Method ConsumerConnectorCreationMethod_07 = KafkaStaticConsumer_07.getMethod("createJavaConsumerConnector", ConsumerConfig_07);
      final Object consumerConnector_07 = ConsumerConnectorCreationMethod_07.invoke(null, consumerConfig_07);
      Method ConsumerConnectorCreateMessageStreamsMethod_07 = ConsumerConnector_07.getMethod(
        "createMessageStreamsByFilter",
        TopicFilter_07, int.class);
      final Method ConsumerConnectorShutdownMethod_07 = ConsumerConnector_07.getMethod("shutdown");
      Constructor WhiteListConstructor_07 = WhiteList_07.getConstructor(String.class);
      Constructor BlackListConstructor_07 = BlackList_07.getConstructor(String.class);
      Object filterSpec = null;
      if(options.has(whitelistOpt))
        filterSpec = WhiteListConstructor_07.newInstance(options.valueOf(whitelistOpt));
      else
        filterSpec = BlackListConstructor_07.newInstance(options.valueOf(blacklistOpt));

      Object retKafkaStreams = ConsumerConnectorCreateMessageStreamsMethod_07.invoke(consumerConnector_07, filterSpec, numConsumers);

      Properties kafkaProducerProperties_08 = new Properties();
      kafkaProducerProperties_08.load(new FileInputStream(producerConfigFile_08));
      kafkaProducerProperties_08.setProperty("serializer.class", "kafka.serializer.DefaultEncoder");
      // create a producer channel instead
      int queueSize = options.valueOf(queueSizeOpt);
      ProducerDataChannel<KeyedMessage<String, byte[]>> producerDataChannel = new ProducerDataChannel<KeyedMessage<String, byte[]>>(queueSize);
      int threadId = 0;

      Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
          try {
            ConsumerConnectorShutdownMethod_07.invoke(consumerConnector_07);
          } catch(Exception e) {
            logger.error("Error while shutting down Kafka consumer", e);
          }
          for(MigrationThread migrationThread : migrationThreads) {
            migrationThread.shutdown();
          }
          for(ProducerThread producerThread : producerThreads) {
            producerThread.shutdown();
          }
          for(ProducerThread producerThread : producerThreads) {
            producerThread.awaitShutdown();
          }
          logger.info("Kafka migration tool shutdown successfully");
        }
      });

      // start consumer threads
      for(Object stream: (List)retKafkaStreams) {
        MigrationThread thread = new MigrationThread(stream, producerDataChannel, threadId);
        threadId ++;
        thread.start();
        migrationThreads.add(thread);
      }

      String clientId = kafkaProducerProperties_08.getProperty("client.id");
      // start producer threads
      for (int i = 0; i < numProducers; i++) {
        kafkaProducerProperties_08.put("client.id", clientId + "-" + i);
        ProducerConfig producerConfig_08 = new ProducerConfig(kafkaProducerProperties_08);
        Producer producer = new Producer(producerConfig_08);
        ProducerThread producerThread = new ProducerThread(producerDataChannel, producer, i);
        producerThread.start();
        producerThreads.add(producerThread);
      }
    }
    catch (Throwable e){
      System.out.println("Kafka migration tool failed due to: " + Utils.stackTrace(e));
      logger.error("Kafka migration tool failed: ", e);
    }
  }

  private static void checkRequiredArgs(OptionParser parser, OptionSet options, OptionSpec[] required) throws IOException {
    for(OptionSpec arg : required) {
      if(!options.has(arg)) {
        System.err.println("Missing required argument \"" + arg + "\"");
        parser.printHelpOn(System.err);
        System.exit(1);
      }
    }
  }

  private static class ProducerDataChannel<T> {
    private final int producerQueueSize;
    private final BlockingQueue<T> producerRequestQueue;

    public ProducerDataChannel(int queueSize) {
      producerQueueSize = queueSize;
      producerRequestQueue = new ArrayBlockingQueue<T>(producerQueueSize);
    }

    public void sendRequest(T data) throws InterruptedException {
      producerRequestQueue.put(data);
    }

    public T receiveRequest() throws InterruptedException {
      return producerRequestQueue.take();
    }
  }

  private static class MigrationThread extends Thread {
    private final Object stream;
    private final ProducerDataChannel<KeyedMessage<String, byte[]>> producerDataChannel;
    private final int threadId;
    private final String threadName;
    private final org.apache.log4j.Logger logger;
    private CountDownLatch shutdownComplete = new CountDownLatch(1);
    private final AtomicBoolean isRunning = new AtomicBoolean(true);

    MigrationThread(Object _stream, ProducerDataChannel<KeyedMessage<String, byte[]>> _producerDataChannel, int _threadId) {
      stream = _stream;
      producerDataChannel = _producerDataChannel;
      threadId = _threadId;
      threadName = "MigrationThread-" + threadId;
      logger = org.apache.log4j.Logger.getLogger(MigrationThread.class.getName());
      this.setName(threadName);
    }

    public void run() {
      try {
        Method MessageGetPayloadMethod_07 = KafkaMessageClass_07.getMethod("payload");
        Method KafkaGetMessageMethod_07 = KafkaMessageAndMetatDataClass_07.getMethod("message");
        Method KafkaGetTopicMethod_07 = KafkaMessageAndMetatDataClass_07.getMethod("topic");
        Method ConsumerIteratorMethod = KafkaStream_07.getMethod("iterator");
        Method KafkaStreamHasNextMethod_07 = KafkaConsumerIteratorClass_07.getMethod("hasNext");
        Method KafkaStreamNextMethod_07 = KafkaConsumerIteratorClass_07.getMethod("next");
        Object iterator = ConsumerIteratorMethod.invoke(stream);

        while (((Boolean) KafkaStreamHasNextMethod_07.invoke(iterator)).booleanValue()) {
          Object messageAndMetaData_07 = KafkaStreamNextMethod_07.invoke(iterator);
          Object message_07 = KafkaGetMessageMethod_07.invoke(messageAndMetaData_07);
          Object topic = KafkaGetTopicMethod_07.invoke(messageAndMetaData_07);
          Object payload_07 = MessageGetPayloadMethod_07.invoke(message_07);
          int size = ((ByteBuffer)payload_07).remaining();
          byte[] bytes = new byte[size];
          ((ByteBuffer)payload_07).get(bytes);
          if(logger.isDebugEnabled())
            logger.debug("Migration thread " + threadId + " sending message of size " + bytes.length + " to topic "+ topic);
          KeyedMessage<String, byte[]> producerData = new KeyedMessage((String)topic, null, bytes);
          producerDataChannel.sendRequest(producerData);
        }
        logger.info("Migration thread " + threadName + " finished running");
      } catch (InvocationTargetException t){
        logger.fatal("Migration thread failure due to root cause ", t.getCause());
      } catch (Throwable t){
        logger.fatal("Migration thread failure due to ", t);
      } finally {
        shutdownComplete.countDown();
      }
    }

    public void shutdown() {
      logger.info("Migration thread " + threadName + " shutting down");
      isRunning.set(false);
      interrupt();
      try {
        shutdownComplete.await();
      } catch(InterruptedException ie) {
        logger.warn("Interrupt during shutdown of MigrationThread", ie);
      }
      logger.info("Migration thread " + threadName + " shutdown complete");
    }
  }

  private static class ProducerThread extends Thread {
    private final ProducerDataChannel<KeyedMessage<String, byte[]>> producerDataChannel;
    private final Producer<String, byte[]> producer;
    private final int threadId;
    private String threadName;
    private org.apache.log4j.Logger logger;
    private CountDownLatch shutdownComplete = new CountDownLatch(1);
    private KeyedMessage<String, byte[]> shutdownMessage = new KeyedMessage("shutdown", null, null);

    public ProducerThread(ProducerDataChannel<KeyedMessage<String, byte[]>> _producerDataChannel,
                          Producer<String, byte[]> _producer,
                          int _threadId) {
      producerDataChannel = _producerDataChannel;
      producer = _producer;
      threadId = _threadId;
      threadName = "ProducerThread-" + threadId;
      logger = org.apache.log4j.Logger.getLogger(ProducerThread.class.getName());
      this.setName(threadName);
    }

    public void run() {
      try{
        while(true) {
          KeyedMessage<String, byte[]> data = producerDataChannel.receiveRequest();
          if(!data.equals(shutdownMessage))
            producer.send(data);
          else
            break;
        }
        logger.info("Producer thread " + threadName + " finished running");
      } catch (Throwable t){
        logger.fatal("Producer thread failure due to ", t);
      } finally {
        shutdownComplete.countDown();
      }
    }

    public void shutdown() {
      try {
        logger.info("Producer thread " + threadName + " shutting down");
        producerDataChannel.sendRequest(shutdownMessage);
      } catch(InterruptedException ie) {
        logger.warn("Interrupt during shutdown of ProducerThread", ie);
      }
    }

    public void awaitShutdown() {
      try {
        shutdownComplete.await();
        logger.info("Producer thread " + threadName + " shutdown complete");
      } catch(InterruptedException ie) {
        logger.warn("Interrupt during shutdown of ProducerThread", ie);
      }
    }
  }

  /**
   * A parent-last class loader that will try the child class loader first and then the parent.
   * This takes a fair bit of doing because java really prefers parent-first.
   */
  private static class ParentLastURLClassLoader extends ClassLoader {
    private ChildURLClassLoader childClassLoader;

    /**
     * This class allows me to call findClass on a class loader
     */
    private static class FindClassClassLoader extends ClassLoader {
      public FindClassClassLoader(ClassLoader parent) {
        super(parent);
      }
      @Override
      public Class<?> findClass(String name) throws ClassNotFoundException {
        return super.findClass(name);
      }
    }

    /**
     * This class delegates (child then parent) for the findClass method for a URLClassLoader.
     * We need this because findClass is protected in URLClassLoader
     */
    private static class ChildURLClassLoader extends URLClassLoader {
      private FindClassClassLoader realParent;
      public ChildURLClassLoader( URL[] urls, FindClassClassLoader realParent) {
        super(urls, null);
        this.realParent = realParent;
      }

      @Override
      public Class<?> findClass(String name) throws ClassNotFoundException {
        try{
          // first try to use the URLClassLoader findClass
          return super.findClass(name);
        }
        catch( ClassNotFoundException e ) {
          // if that fails, we ask our real parent class loader to load the class (we give up)
          return realParent.loadClass(name);
        }
      }
    }

    public ParentLastURLClassLoader(URL[] urls) {
      super(Thread.currentThread().getContextClassLoader());
      childClassLoader = new ChildURLClassLoader(urls, new FindClassClassLoader(this.getParent()));
    }

    @Override
    protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
      try {
        // first we try to find a class inside the child class loader
        return childClassLoader.findClass(name);
      }
      catch( ClassNotFoundException e ) {
        // didn't find it, try the parent
        return super.loadClass(name, resolve);
      }
    }
  }
}


text:
package org.keycloak.userprofile;

import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.provider.Spi;

/**
 * @author Markus Till
 */
public class UserProfileSpi implements Spi {

    public static final String ID = "userProfile";

    @Override
    public boolean isInternal() {
        return true;
    }

    @Override
    public String getName() {
        return ID;
    }

    @Override
    public Class<? extends Provider> getProviderClass() {
        return UserProfileProvider.class;
    }

    @Override
    public Class<? extends ProviderFactory> getProviderFactoryClass() {
        return UserProfileProviderFactory.class;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.sequenceiq.environment.experience.liftie;

import static com.sequenceiq.cloudbreak.util.NullUtil.putIfPresent;

import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;

import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sequenceiq.environment.exception.ExperienceOperationFailedException;
import com.sequenceiq.environment.experience.InvocationBuilderProvider;
import com.sequenceiq.environment.experience.QueryParamInjectorUtil;
import com.sequenceiq.environment.experience.ResponseReader;
import com.sequenceiq.environment.experience.RetryableWebTarget;
import com.sequenceiq.environment.experience.api.LiftieApi;
import com.sequenceiq.environment.experience.liftie.responses.DeleteClusterResponse;
import com.sequenceiq.environment.experience.liftie.responses.ListClustersResponse;
import com.sequenceiq.environment.experience.policy.response.ExperiencePolicyResponse;

@Service
public class LiftieConnectorService implements LiftieApi {

    private static final String LIFTIE_CALL_EXEC_FAILED_MSG = "Something happened while the Kubernetes Experience connection has attempted!";

    private static final String LIFTIE_RESPONSE_RESOLVE_ERROR_MSG = "Unable to find the Kubernetes dependencies of this environment due to internal error.";

    private static final Logger LOGGER = LoggerFactory.getLogger(LiftieConnectorService.class);

    private final InvocationBuilderProvider invocationBuilderProvider;

    private final RetryableWebTarget retryableWebTarget;

    private final LiftiePathProvider liftiePathProvider;

    private final ResponseReader responseReader;

    private final Client client;

    public LiftieConnectorService(LiftiePathProvider liftiePathProvider, LiftieResponseReader liftieResponseReader, RetryableWebTarget retryableWebTarget,
            Client client, InvocationBuilderProvider invocationBuilderProvider) {
        this.invocationBuilderProvider = invocationBuilderProvider;
        this.liftiePathProvider = liftiePathProvider;
        this.retryableWebTarget = retryableWebTarget;
        this.responseReader = liftieResponseReader;
        this.client = client;
    }

    @NotNull
    @Override
    public ListClustersResponse listClusters(@NotNull String env, @NotNull String tenant, @Nullable String workload, @Nullable Integer page) {
        LOGGER.debug("About to connect Kubernetes Experience API to list clusters for environment '{}' account '{}' workload '{}', page '{}'",
                env, tenant, workload, page == null ? Integer.valueOf(0) : page);
        WebTarget webTarget = client.target(liftiePathProvider.getPathToClustersEndpoint());
        Map<String, String> queryParams = new LinkedHashMap<>();
        putIfPresent(queryParams, "env", env);
        putIfPresent(queryParams, "tenant", tenant);
        putIfPresent(queryParams, "workloads", workload);
        putIfPresent(queryParams, "page", page != null ? page.toString() : null);
        webTarget = QueryParamInjectorUtil.setQueryParams(webTarget, queryParams);
        LOGGER.info("WebTarget has created for getting Kubernetes clusters related to the given environment environment [name: {}]: {}",
                env, webTarget.toString());
        Invocation.Builder call = invocationBuilderProvider.createInvocationBuilder(webTarget);
        try (Response result = executeCall(webTarget.getUri(), () -> retryableWebTarget.get(call))) {
            return responseReader.read(webTarget.getUri().toString(), result, ListClustersResponse.class)
                    .orElseThrow(() -> new ExperienceOperationFailedException(LIFTIE_RESPONSE_RESOLVE_ERROR_MSG));
        } catch (RuntimeException e) {
            LOGGER.warn(LIFTIE_CALL_EXEC_FAILED_MSG, e);
            throw new ExperienceOperationFailedException(LIFTIE_RESPONSE_RESOLVE_ERROR_MSG, e);
        }
    }

    @Override
    public DeleteClusterResponse deleteCluster(@NotNull String clusterId) {
        LOGGER.debug("About to connect Kubernetes Experience API to delete cluster {}", clusterId);
        WebTarget webTarget = client.target(liftiePathProvider.getPathToClusterEndpoint(clusterId));
        LOGGER.info("WebTarget has created for deleting Kubernetes cluster with the following cluster id [id: {}]: {}",
                clusterId, webTarget.toString());
        Invocation.Builder call = invocationBuilderProvider.createInvocationBuilder(webTarget);
        try (Response result = executeCall(webTarget.getUri(), () -> retryableWebTarget.delete(call))) {
            return responseReader.read(webTarget.getUri().toString(), result, DeleteClusterResponse.class)
                    .orElseThrow(() -> new ExperienceOperationFailedException(LIFTIE_RESPONSE_RESOLVE_ERROR_MSG));
        } catch (RuntimeException e) {
            LOGGER.warn(LIFTIE_CALL_EXEC_FAILED_MSG, e);
            throw new ExperienceOperationFailedException(LIFTIE_RESPONSE_RESOLVE_ERROR_MSG, e);
        }
    }

    @Override
    public ExperiencePolicyResponse getPolicy(String cloudPlatform) {
        WebTarget webTarget = client.target(liftiePathProvider.getPathToPolicyEndpoint(cloudPlatform));
        LOGGER.info("WebTarget has created for getting Kubernetes clusters related minimal policies for cloud platform [platform: {}]: {}",
                cloudPlatform, webTarget.toString());
        Invocation.Builder call = invocationBuilderProvider.createInvocationBuilderForInternalActor(webTarget);
        try (Response result = executeCall(webTarget.getUri(), () -> retryableWebTarget.get(call))) {
            return responseReader.read(webTarget.getUri().toString(), result, ExperiencePolicyResponse.class)
                    .orElseThrow(() -> new ExperienceOperationFailedException(LIFTIE_RESPONSE_RESOLVE_ERROR_MSG));
        } catch (RuntimeException e) {
            LOGGER.warn(LIFTIE_CALL_EXEC_FAILED_MSG, e);
            throw new ExperienceOperationFailedException(LIFTIE_RESPONSE_RESOLVE_ERROR_MSG, e);
        }
    }

    private Response executeCall(URI path, Callable<Response> toCall) {
        LOGGER.debug("About to connect to Kubernetes Experience on path: {}", path);
        try {
            return toCall.call();
        } catch (Exception re) {
            LOGGER.warn("Kubernetes Experience http call execution has failed due to:", re);
            throw new ExperienceOperationFailedException(re);
        }
    }

}


text:
/**
 *
 */
@javax.annotation.ParametersAreNonnullByDefault
package com.github.rinde.dynurg;


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="blog-unit" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>blog</jta-data-source>
    <class>org.yy.blog.model.User</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <!--<property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/struts-tutorial"/>-->
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
      <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WeblogicTransactionManagerLookup" />
      <!--<property name="hibernate.session_factory_name" value="hibernate.session_factory" />

        --><!--
       <property name="jboss.entity.manager.factory.jndi.name" value="java:/StrutsTutorial"/>  NOTE
    --></properties>
  </persistence-unit>
</persistence>


text:
package jodd.petite.data;

import jodd.petite.meta.PetiteBean;

@PetiteBean
public class MyBiz implements Biz {

	@Override
	public void calculate() {
	}
}


text: from pyface.workbench.traits_ui_view import *


text:
//
//  TheSecondCarResultViewController.m
//  Lebao
//
//  Created by David on 16/4/15.
//  Copyright © 2016年 David. All rights reserved.
//

#import "TheSecondCarResultViewController.h"
#import "UpLoadImageManager.h"
#import "XLDataService.h"
#import "AlreadysentproductViewController.h"
#define ImageURlText @"/product/default"
#define ImageURlDiagramText @"/diagram/product/default"
#define ImageDefault @"ImageDefault"
#define ImageDiagram @"ImageDiagram"
//保存产品和房源
#define Saveproduct [NSString stringWithFormat:@"%@product/savecar",HttpURL]

//发布文章
#define CreatearticleUrl  [NSString stringWithFormat:@"%@release/create",HttpURL]
@interface TheSecondCarResultViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)BaseButton *selectedTag;
@property(nonatomic,strong)NSMutableArray *selecteds;
@property(nonatomic,strong)NSMutableArray *selectedItems;

@property(nonatomic,strong)BaseButton *feimianBtn;

@property(nonatomic,strong)UITextView *textFieldone;

@property(nonatomic,strong)UITextField *titleTextField;
@property(nonatomic,strong)NSMutableDictionary *fengmianImageUrl;

@property(nonatomic,strong)UISwitch *personalInformationSwitch;
@property(nonatomic,strong)UISwitch *infoSwitch;
@property(nonatomic,strong)UISwitch *collectSwitch;
@property(nonatomic,strong)UISwitch *redSwitch;

@property(nonatomic,strong)UITextField *redTextField;
@end

typedef NS_ENUM(int,SwitchActionTag) {

    SwitchActionTagInfo  =2,
    SwitchActionTagCollect,
    SwitchActionTagRed,
    SwitchActionTagPersonalInformation
};
@implementation TheSecondCarResultViewController
{

    float redHight;
    UIView *_redViewBg;

    UIView *_info;

    UILabel *_personalInformationLb;
    UILabel *_infoLb;
    UILabel *_collectLb;
    UILabel *_redLb;
    UIView *_redView;

    BOOL isHaveDian;
    BaseButton *_nextBtn;

    UIView *setImageView;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self navView];

    if (!_data.isEdit) {
        [[ToolManager shareInstance] showWithStatus];
        [XLDataService postWithUrl:CreatearticleUrl param:[Parameter parameterWithSessicon] modelClass:nil responseBlock:^(id dataObj, NSError *error) {
            if (dataObj) {
                if ([dataObj[@"rtcode"] intValue] ==1) {
                    [[ToolManager shareInstance] dismiss];
                    _data.amount =dataObj[@"amount"];
//                    NSLog(@"_data.amount =%@",_data.amount);
                    [self mainView];

                }
                else
                {
                    [[ToolManager shareInstance] showInfoWithStatus:dataObj[@"rtmsg"]];
                }
            }
            else
            {
                [[ToolManager shareInstance] showInfoWithStatus];
            }
        }];

    }
    else
    {
        [self mainView];

    }

}
#pragma mark - Navi_View
- (void)navView
{

    [self navViewTitleAndBackBtn:@"二手车源"];

}

#pragma mark
#pragma mark - buttonAction -
- (void)buttonAction:(UIButton *)sender
{
    if (sender.tag ==NavViewButtonActionNavLeftBtnTag ) {
        PopView(self);
    }
}
#pragma mark - mian_View
- (void)mainView
{
    _selecteds = [NSMutableArray new];
    _selectedItems = [NSMutableArray new];

    _fengmianImageUrl = [NSMutableDictionary new];

    if (_modal.datas.imgurl) {
        [_fengmianImageUrl setValue:_modal.datas.imgurl forKey:ImageDiagram];
        [_fengmianImageUrl setValue:_modal.datas.abbre_cover forKey:ImageDefault];
    }

    _mainScrollView = allocAndInitWithFrame(UIScrollView, frame(0, StatusBarHeight + NavigationBarHeight, APPWIDTH, APPHEIGHT - (StatusBarHeight + NavigationBarHeight)));
    _mainScrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_mainScrollView];

    UILabel *line = allocAndInitWithFrame(UILabel , frame(10, 10, 3, 28*SpacedFonts));
    line.backgroundColor = AppMainColor;
    [_mainScrollView addSubview:line];

    [UILabel createLabelWithFrame:frame(CGRectGetMaxX(line.frame) + 4, frameY(line), 4*SpacedFonts*28,  28*SpacedFonts) text:@"选择标签" fontSize:28*SpacedFonts textColor:BlackTitleColor textAlignment:NSTextAlignmentLeft inView:_mainScrollView];

//    [UILabel createLabelWithFrame:frame(CGRectGetMaxX(line.frame) + 8 + 4*SpacedFonts*28, frameY(line)+ 2, 6*SpacedFonts*24 ,  24*SpacedFonts) text:@"最多可选3项" fontSize:24*SpacedFonts textColor:LightBlackTitleColor textAlignment:NSTextAlignmentLeft inView:_mainScrollView];
    //选择标签
    UIView *_selectedTagView = allocAndInitWithFrame(UIView, frame(0, CGRectGetMaxY(line.frame) + 3, APPWIDTH, 0));
    _selectedTagView.backgroundColor = WhiteColor;
    NSArray *titles = [NSArray arrayWithObjects:@"无事故",@"有小剐蹭",@"可议价",@"一口价",@"个人一手",@"上下班用车",@"必须过户",@"可随时看车",@"全新车",@"9成新车",@"免过户费",@"可试驾",nil];

    for (int i=0;i<titles.count;i++) {
        [_selecteds addObject:@"0"];
    }
//    NSLog(@"_modal.datas.labels =%@",_modal.datas.labels);
    if (_modal.datas.labels&&![_modal.datas.labels isEqualToString:@""]) {
        NSArray *labels = [_modal.datas.labels componentsSeparatedByString:@","];
        for (NSString *str in labels) {
            [_data.labels addObject:str];

        }
        for (int i=0;i<titles.count;i++ ) {
            NSString *str = titles[i];
            if ([_data.labels containsObject:str]) {
                [_selecteds  replaceObjectAtIndex:i withObject:str];
            }
        }
    }
    float titleX = 10;
    float titleY = 15;
    float titleW  =0;
    float titleH = 27;
    float titleXW = 10;
    __weak TheSecondCarResultViewController *weakSelf = self;
    for (int i = 0; i<titles.count; i++) {
        NSString *tille =titles[i];
        titleW = tille.length*28*SpacedFonts + 10;
        titleXW =titleW+titleX+10;

        if (titleXW>APPWIDTH) {
            titleY +=(10+titleH);
            titleX =10;
            titleXW = 10;
        }
        UIColor *titleColor;
        UIColor  *setBorder;
        if ([_selecteds[i] isEqualToString:@"0"]) {
            titleColor = LightBlackTitleColor;
            setBorder = LineBg;
        }
        else
        {
            titleColor =setBorder= AppMainColor;

        }

        _selectedTag = [[BaseButton alloc]initWithFrame:frame(titleX, titleY, titleW, titleH) setTitle:tille titleSize:28*SpacedFonts titleColor:titleColor textAlignment:NSTextAlignmentCenter backgroundColor:WhiteColor inView:_selectedTagView];
        [_selectedTag setRadius:10];
        [_selectedTag setBorder:setBorder width:0.5];
        _selectedTag.didClickBtnBlock = ^
        {
            BaseButton *item = weakSelf.selectedItems[i];
            if ([weakSelf.selecteds[i] isEqualToString:@"0"]) {

                int tag =0;
                for (NSString *str  in weakSelf.selecteds) {
                    if (![str isEqualToString:@"0"]) {
                        tag ++;
                    }
                }
//                if (tag>=3) {
//                    [[ToolManager shareInstance] showInfoWithStatus:@"最多可选三个"];
//                    return;
//                }
                [weakSelf.selecteds replaceObjectAtIndex:i withObject:@"1"];

                if (![weakSelf.data.labels containsObject:titles[i]]) {
                    [weakSelf.data.labels addObject:titles[i]];
                }

                [item setTitleColor:AppMainColor forState:UIControlStateNormal];
                [item setBorder:AppMainColor width:0.5];
            }
            else
            {
                if ([weakSelf.data.labels containsObject:titles[i]]) {
                    [weakSelf.data.labels removeObject:titles[i]];
                }
                [weakSelf.selecteds replaceObjectAtIndex:i withObject:@"0"];
                [item setTitleColor:LightBlackTitleColor forState:UIControlStateNormal];
                [item setBorder:LineBg width:0.5];
            }

        };

        titleX +=titleW + 10;

        _selectedTagView.frame = frame(frameX(_selectedTagView), frameY(_selectedTagView), frameWidth(_selectedTagView), titleY + titleH + 10);
        [_selectedItems addObject:_selectedTag];
        _selectedTag = nil;
    }
    //补充说明

    UILabel *line1 = allocAndInitWithFrame(UILabel , frame(10, CGRectGetMaxY(_selectedTagView.frame)+10, 3, 28*SpacedFonts));
    line1.backgroundColor = AppMainColor;
    [_mainScrollView addSubview:line1];
    [UILabel createLabelWithFrame:frame(CGRectGetMaxX(line1.frame) + 4, frameY(line1), 4*SpacedFonts*28,  28*SpacedFonts) text:@"补充说明" fontSize:28*SpacedFonts textColor:BlackTitleColor textAlignment:NSTextAlignmentLeft inView:_mainScrollView];

    UIView *_projectView = allocAndInitWithFrame(UIView, frame(0, CGRectGetMaxY(line1.frame) + 3, APPWIDTH, 100));
    _projectView.backgroundColor = WhiteColor;

    _textFieldone = [[UITextView alloc]initWithFrame:frame(10, 10, APPWIDTH - 20, frameHeight(_projectView) - 20) ];
    [_textFieldone setBorder:LineBg width:0.5];
    [_textFieldone setRadius:5.0];
    [_projectView addSubview:_textFieldone];
//    NSLog(@"_modal.datas.des =%@",_modal.datas.des);
    if (_modal.datas.des) {
        _textFieldone.text = _modal.datas.des;
    }
    //车源标题
    UILabel *line2 = allocAndInitWithFrame(UILabel , frame(10, CGRectGetMaxY(_projectView.frame)+10, 3, 28*SpacedFonts));
    line2.backgroundColor = AppMainColor;
    [_mainScrollView addSubview:line2];
    [UILabel createLabelWithFrame:frame(CGRectGetMaxX(line2.frame) + 4, frameY(line2), 4*SpacedFonts*28,  28*SpacedFonts) text:@"车源标题" fontSize:28*SpacedFonts textColor:BlackTitleColor textAlignment:NSTextAlignmentLeft inView:_mainScrollView];

    UIView *_titletView = allocAndInitWithFrame(UIView, frame(0, CGRectGetMaxY(line2.frame) + 3, APPWIDTH, 62));
    _titletView.backgroundColor = WhiteColor;

    _titleTextField = [self createframe:frame(10, 10, APPWIDTH - 20, (frameHeight(_titletView) - 20)) title:@"请输入车源标题" inView:_titletView];
    _titleTextField.text = _data.pinpaiTitle;

    //车源封面
    UILabel *line3 = allocAndInitWithFrame(UILabel , frame(10, CGRectGetMaxY(_titletView.frame)+10, 3, 28*SpacedFonts));
    line3.backgroundColor = AppMainColor;
    [_mainScrollView addSubview:line3];
    [UILabel createLabelWithFrame:frame(CGRectGetMaxX(line3.frame) + 4, frameY(line3), 4*SpacedFonts*28,  28*SpacedFonts) text:@"楼书封面" fontSize:28*SpacedFonts textColor:BlackTitleColor textAlignment:NSTextAlignmentLeft inView:_mainScrollView];

    UIView *_floorView = allocAndInitWithFrame(UIView, frame(0, CGRectGetMaxY(line3.frame) + 3, APPWIDTH, 80));
    _floorView.backgroundColor = WhiteColor;

    weakSelf.feimianBtn = [[BaseButton alloc]initWithFrame:frame(10, 10, 60, 60) backgroundImage:[UIImage imageNamed:@"addition"] iconImage:nil highlightImage:nil inView:_floorView];
    if ([_fengmianImageUrl objectForKey:ImageDiagram]) {
        [[ToolManager shareInstance] imageView:weakSelf.feimianBtn setImageWithURL:[_fengmianImageUrl objectForKey:ImageDiagram] placeholderType:PlaceholderTypeOther];
    }
    weakSelf.feimianBtn.didClickBtnBlock = ^
    {
        [[ToolManager shareInstance] seleteImageFormSystem:weakSelf seleteImageFormSystemBlcok:^(UIImage *image) {
            [[UpLoadImageManager shareInstance] upLoadImageType:UploadImagesTypeCar image:image  imageBlock:^(UpLoadImageModal * upLoadImageModal) {
                [_fengmianImageUrl setValue:upLoadImageModal.imgurl forKey:ImageDefault];
                [_fengmianImageUrl setValue:upLoadImageModal.abbr_imgurl forKey:ImageDiagram];
                [[ToolManager shareInstance] imageView:weakSelf.feimianBtn setImageWithURL:upLoadImageModal.abbr_imgurl placeholderType:PlaceholderTypeOther];

            }];
        }];
    };

    float cellHeight = 40;
    //是否显示个人资料

    UIView *_personalInformation =allocAndInitWithFrame(UIView , frame(0, 10+CGRectGetMaxY(_floorView.frame), APPWIDTH, cellHeight));
    _personalInformation.backgroundColor =[UIColor whiteColor];
    [_mainScrollView addSubview:_personalInformation];

    _personalInformationLb = [UILabel createLabelWithFrame:frame(10, 0, 10*28*SpacedFonts, cellHeight) text:@"是否在个人资料中显示" fontSize:28*SpacedFonts textColor:LightBlackTitleColor textAlignment:NSTextAlignmentLeft inView:_personalInformation];

    _personalInformationSwitch =allocAndInitWithFrame(UISwitch, frame(frameWidth(_personalInformation) -60, 5, 50, 30));

    _personalInformationSwitch.onTintColor = AppMainColor;
    _personalInformationSwitch.tag = SwitchActionTagPersonalInformation;
    [_personalInformationSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    [_personalInformation addSubview:_personalInformationSwitch];

    if (_data.iscross) {
        [_personalInformationSwitch setOn:YES animated:YES];
        [self switchAction:_personalInformationSwitch];
    }
    else
    {

        [_personalInformationSwitch setOn:NO animated:YES];
        [self switchAction:_personalInformationSwitch];
    }

    //    _collect to the original

    UIView *_collect =allocAndInitWithFrame(UIView , frame(0, CGRectGetMaxY(_personalInformation.frame)+0.5, APPWIDTH, cellHeight));

    _collect.backgroundColor =[UIColor whiteColor];
    [_mainScrollView addSubview:_collect];

    _collectLb = [UILabel createLabelWithFrame:frame(10, 0, 6*28*SpacedFonts, cellHeight) text:@"收集传播路径" fontSize:28*SpacedFonts textColor:LightBlackTitleColor textAlignment:NSTextAlignmentLeft inView:_collect];

    _collectSwitch =allocAndInitWithFrame(UISwitch, frame(frameWidth(_collect) -60, 5, 50, 30));
    _collectSwitch.tag = SwitchActionTagCollect;
    _collectSwitch.onTintColor = AppMainColor;
    [_collectSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    [_collect addSubview:_collectSwitch];
    if (_data.isgetclue) {
        [_collectSwitch setOn:YES animated:YES];
        [self switchAction:_collectSwitch];
    }

    if (_data.isreward) {
        [_collectSwitch setEnabled:NO];
    }
    else
    {
        [_collectSwitch setEnabled:YES];
    }

    _info =allocAndInitWithFrame(UIView , frame(0, CGRectGetMaxY(_collect.frame)+0.5, APPWIDTH, cellHeight));
    _info.backgroundColor =[UIColor whiteColor];
    [_mainScrollView addSubview:_info];
    _infoLb = [UILabel createLabelWithFrame:frame(10, 0, 7*28*SpacedFonts, cellHeight) text:@"收集客户信息" fontSize:28*SpacedFonts textColor:LightBlackTitleColor textAlignment:NSTextAlignmentLeft inView:_info];

    _infoSwitch =allocAndInitWithFrame(UISwitch, frame(frameWidth(_collect) -60, 5, 50, 30));
    _infoSwitch.tag = SwitchActionTagInfo;
    _infoSwitch.onTintColor = AppMainColor;
    [_infoSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    [_info addSubview:_infoSwitch];

    if (_data.iscollect) {
        [_infoSwitch setOn:YES animated:YES];
        [self switchAction:_infoSwitch];

    }

    //     to the original
    _redView =allocAndInitWithFrame(UIView , frame(0, CGRectGetMaxY(_info.frame)+0.5, APPWIDTH, cellHeight));
    _redView.backgroundColor =[UIColor whiteColor];
    [_mainScrollView addSubview:_redView];
    _redLb = [UILabel createLabelWithFrame:frame(10, 0, APPWIDTH/2.0, cellHeight) text:@"跨界红包设置" fontSize:28*SpacedFonts textColor:LightBlackTitleColor textAlignment:NSTextAlignmentLeft inView:_redView];

    if (_data.isreward) {

        _redLb.text = [NSString stringWithFormat:@"红包金额:%@(元)",_data.reward];
        [_redLb setTextColor:BlackTitleColor];
    }
    else
    {
        _redSwitch =allocAndInitWithFrame(UISwitch, frame(frameWidth(_collect) -60, 5, 50, 30));
        _redSwitch.tag = SwitchActionTagRed;
        _redSwitch.onTintColor = AppMainColor;
        [_redSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        [_redView addSubview:_redSwitch];
        if (_data.isreward) {
            [_redSwitch setOn:YES animated:YES];
            [self switchAction:_redSwitch];
        }
        if (!_data.isgetclue) {
            [_collectSwitch setOn:NO animated:YES];
            [self switchAction:_collectSwitch];

        }
    }
    //输入红包
    _redViewBg = allocAndInitWithFrame(UIView, frame(0 , cellHeight, frameWidth(_mainScrollView), 42));
    _redViewBg.backgroundColor =AppViewBGColor;
    [_redView addSubview:_redViewBg];

    UIView * _redTextFieldView = allocAndInitWithFrame(UIView, frame(10 , 10, frameWidth(_redViewBg)-20, 42));
    _redTextFieldView.backgroundColor =WhiteColor;
    [_redTextFieldView setBorder:LineBg width:0.5];
    [_redTextFieldView setRadius:5.0];
    [_redViewBg addSubview:_redTextFieldView];

    _redTextField= allocAndInitWithFrame(UITextField, frame(10 ,0, frameWidth(_redTextFieldView)-20, 42));
    _redTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"请输入红包金额,最大可输入%@元",_data.amount] attributes:@{NSForegroundColorAttributeName:LightBlackTitleColor }];
    [_redTextFieldView addSubview:_redTextField];
    _redTextField.textColor = BlackTitleColor;
    _redTextField.font =  Size(24);
    _redTextField.clearButtonMode =UITextFieldViewModeWhileEditing;
    _redTextField.backgroundColor = WhiteColor;
    _redTextField.delegate = self;
    //    _redTextField.text = _data.amount;
    UILabel *desc = [UILabel createLabelWithFrame:frame(10 ,CGRectGetMaxY(_redTextField.frame) + 10, frameWidth(_redTextFieldView), 0) text:@"跨界传播内容规范:\n1.标题不带有诱导分享的字眼,如转发就给红包、转发有现金等\n2.所发内容、产品、房源不含涉黄、涉暴、涉谣等信息\n3.鼓励发布有用的内容、真实的产品,内容中可以附带个人微名片\n4.所有带跨界传播设置的内容都需要知脉后台审核,审核通过后才可以发布到知脉首页中\n5.若内容被驳回,所扣红包金额全额退回到红包账户中" fontSize:24*SpacedFonts textColor:LightBlackTitleColor textAlignment:NSTextAlignmentLeft inView:_redViewBg];
    desc.numberOfLines = 0;
    //    desc.backgroundColor = AppViewBGColor;
    CGSize size = [desc sizeWithMultiLineContent:desc.text rowWidth:frameWidth(desc) font:Size(24)];
    desc.frame = frame(frameX(desc), frameY(desc), frameWidth(desc), size.height);

    _redViewBg.frame = frame(frameX(_redViewBg), frameY(_redViewBg), APPWIDTH, size.height + 10 + frameHeight(_redViewBg));
    _redViewBg.hidden = YES;
    redHight = 40 + frameHeight(_redViewBg);

    [_mainScrollView addSubview:_selectedTagView];
    [_mainScrollView addSubview:_projectView];
    [_mainScrollView addSubview:_titletView];
    [_mainScrollView addSubview:_floorView];

    if (!_data.isgetclue) {
        _mainScrollView.contentSize = CGSizeMake(frameWidth(_mainScrollView), CGRectGetMaxY(_info.frame) + 60);
    }
    else
    {
        _mainScrollView.contentSize = CGSizeMake(frameWidth(_mainScrollView), CGRectGetMaxY(_redView.frame) + 60);
    }
    [_mainScrollView scrollRectToVisible:frame(frameX(_mainScrollView), 0, frameWidth(_mainScrollView), _mainScrollView.contentSize.height) animated:YES];

    //完成
    _nextBtn = [[BaseButton alloc]initWithFrame:frame(13*ScreenMultiple,_mainScrollView.contentSize.height - 50 , APPWIDTH - 26*ScreenMultiple, 40) setTitle:@"完成" titleSize:28*SpacedFonts  titleColor:WhiteColor textAlignment:NSTextAlignmentCenter  backgroundColor:AppMainColor inView:_mainScrollView];
    [_nextBtn
     setRoundWithfloat:4];
    _nextBtn.didClickBtnBlock =^
    {
        NSMutableDictionary *parameter = [Parameter parameterWithSessicon];
        [parameter setObject:@"car" forKey:@"actype"];
        if (weakSelf.modal.datas.acid&&_data.isEdit) {
            [parameter setObject:weakSelf.modal.datas.acid forKey:@"acid"];
        }

        if (weakSelf.data.labels.count==0) {
            [[ToolManager shareInstance] showInfoWithStatus:@"请选择标签"];

            return ;

        }
        NSMutableArray *labels = [NSMutableArray new];
        for (NSString *string in weakSelf.data.labels) {
            [labels addObject:string];
        }
        [parameter setObject:[labels mj_JSONString] forKey:@"labels"];

        if (!weakSelf.titleTextField ||[weakSelf.titleTextField.text isEqualToString:@""]) {
            [[ToolManager shareInstance] showInfoWithStatus:@"请输入标题"];

            return ;
        }
        [parameter setObject:weakSelf.titleTextField.text forKey:@"title"];

        if (!weakSelf.fengmianImageUrl[ImageDiagram]) {
            [[ToolManager shareInstance] showInfoWithStatus:@"请选择封面"];

            return ;
        }
        [parameter setObject:weakSelf.fengmianImageUrl[ImageDiagram] forKey:@"abbre_cover"];
        [parameter setObject:weakSelf.fengmianImageUrl[ImageDefault] forKey:@"cover"];
        [parameter setObject:@(weakSelf.collectSwitch.isOn) forKey:@"isgetclue"];
        [parameter setObject:@(weakSelf.infoSwitch.isOn) forKey:@"iscollect"];
        [parameter setObject:@(weakSelf.personalInformationSwitch.isOn) forKey:@"iscross"];
        [parameter setObject:@(weakSelf.redSwitch.isOn) forKey:@"isreward"];
        NSMutableArray *maidian = [NSMutableArray new];
        if (weakSelf.textFieldone.text.length>0) {
            [maidian addObject:weakSelf.textFieldone.text];

        }
        if (maidian.count>0) {
            [parameter setObject:[maidian mj_JSONString] forKey:@"salespoint"];
        }
        [parameter setObject:weakSelf.data.model_id forKey:@"model_id"];
        [parameter setObject:weakSelf.data.series_id forKey:@"series_id"];
        [parameter setObject:weakSelf.data.keyid forKey:@"keyid"];
        [parameter setObject:weakSelf.data.color  forKey:@"color"];
        [parameter setObject:weakSelf.data.cartime forKey:@"cartime"];
        [parameter setObject:weakSelf.data.carvenue  forKey:@"carvenue"];
        [parameter setObject:weakSelf.data.mileage forKey:@"mileage"];
        [parameter setObject:weakSelf.data.price  forKey:@"price"];
        [parameter setObject:weakSelf.data.buyprice forKey:@"buyprice"];
        [parameter setObject:weakSelf.textFieldone.text  forKey:@"description"];

        [parameter setObject:[weakSelf.data.images mj_JSONString] forKey:@"imgarr"];

        if (weakSelf.redSwitch.isOn) {
            if ([_redTextField.text floatValue]<=0.01) {
                if (weakSelf.collectSwitch.isOn) {
                    [[ToolManager shareInstance] showInfoWithStatus:@"请输入红包金额"];
                    return ;
                }

            }
            [parameter setObject:weakSelf.redTextField.text forKey:@"reward"];
        }
        [[ToolManager shareInstance] showWithStatus:@"保存中..."];
//        NSLog(@"parameter = %@",parameter);
        [XLDataService postWithUrl:Saveproduct param:parameter modelClass:nil responseBlock:^(id dataObj, NSError *error) {
//            NSLog(@"dataObj = %@",dataObj);
            if (dataObj) {
                if ([dataObj[@"rtcode"] intValue]==1) {
                    [[ToolManager shareInstance] dismiss];

                    if (weakSelf.data.isEdit) {
                        PopToPointView(weakSelf, @"AlreadysentproductViewController");
                    }
                    else
                    {

                        AlreadysentproductViewController *article  = allocAndInit(AlreadysentproductViewController);
                        article.ispopToRoot = YES;
                        PushView(weakSelf, article);
                    }

                }
                else
                {
                    [[ToolManager shareInstance] showInfoWithStatus:dataObj[@"rtmsg"]];
                }
            }
            else
            {
                [[ToolManager shareInstance] showInfoWithStatus] ;
            }
        }];

    };

}
- (UIView *)imageview:(NSMutableArray *)images inView:(UIView *)view tag:(int)tag
{
    for (UIView *subView in setImageView.subviews) {
        [subView removeFromSuperview];
    }

    setImageView = allocAndInitWithFrame(UIView, frame(0, 95, APPWIDTH, 130));
    [view addSubview:setImageView];
    UIScrollView *setView = allocAndInitWithFrame(UIScrollView, frame(0, 0, APPWIDTH, 60));

    __weak TheSecondCarResultViewController *weakSelf =self;
    for (int i =0; i<images.count; i++) {

        BaseButton *btn = [[BaseButton alloc]initWithFrame:frame(10+i*70, 0, 60, 60) backgroundImage:nil iconImage:nil highlightImage:nil inView:setView];
        NSDictionary *imagesDic = images[i];
        if (![imagesDic[ImageDiagram] isEqualToString:@""]) {
            [[ToolManager shareInstance] imageView:btn setImageWithURL:imagesDic[ImageDiagram] placeholderType:PlaceholderTypeOther];

        }
        btn.didClickBtnBlock = ^
        {
            if (![imagesDic[ImageDiagram] isEqualToString:@""]) {

                [_fengmianImageUrl setValue:imagesDic[ImageDiagram] forKey:ImageDiagram];
                [_fengmianImageUrl setValue:imagesDic[ImageDefault] forKey:ImageDefault];
                [[ToolManager shareInstance] imageView:weakSelf.feimianBtn setImageWithURL:imagesDic[ImageDiagram] placeholderType:PlaceholderTypeOther];

            }

        };
        if (CGRectGetMaxX(btn.frame) + 10>frameWidth(setView)) {
            setView.contentSize = CGSizeMake(frameWidth(setView),CGRectGetMaxX(btn.frame) + 10);
        }
    }

    weakSelf.feimianBtn = [[BaseButton alloc]initWithFrame:frame(10, 70, 60, 60) backgroundImage:[UIImage imageNamed:@"addition"] iconImage:nil highlightImage:nil inView:setImageView];
    if (![_fengmianImageUrl[ImageDiagram] isEqualToString:@""]&&_fengmianImageUrl[ImageDiagram]) {
        [[ToolManager shareInstance] imageView:weakSelf.feimianBtn setImageWithURL:_fengmianImageUrl[ImageDiagram] placeholderType:PlaceholderTypeOther];

    }
    weakSelf.feimianBtn.didClickBtnBlock = ^
    {
        [[ToolManager shareInstance] seleteImageFormSystem:weakSelf seleteImageFormSystemBlcok:^(UIImage *image) {
            [[UpLoadImageManager shareInstance] upLoadImageType:@"property" image:image  imageBlock:^(UpLoadImageModal * upLoadImageModal) {

                [_fengmianImageUrl setValue:upLoadImageModal.abbr_imgurl forKey:ImageDiagram];
                [_fengmianImageUrl setValue:upLoadImageModal.imgurl forKey:ImageDefault];

                [[ToolManager shareInstance] imageView:weakSelf.feimianBtn setImageWithURL:upLoadImageModal.abbr_imgurl placeholderType:PlaceholderTypeOther];

            }];
        }];
    };

    [setImageView addSubview:setView];

    return setImageView;

}

-(UITextField *)createframe:(CGRect)frame title:(NSString *)title inView:(UIView *)view
{
    UIView *texfFiledView = allocAndInitWithFrame(UIView, frame);
    texfFiledView.backgroundColor =[UIColor whiteColor];
    [texfFiledView setBorder:LineBg width:0.5];
    [texfFiledView setRadius:5.0];
    [view addSubview:texfFiledView];

    UITextField *textField = allocAndInitWithFrame(UITextField, frame(5 , 0, frameWidth(texfFiledView)-10, frameHeight(texfFiledView)));
    [texfFiledView addSubview:textField];
    textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName:LightBlackTitleColor }];
    textField.textColor = BlackTitleColor;
    textField.font = Size(24);
    //    textField.keyboardType = UIKeyboardTypeNumberPad;

    return textField;

}

#pragma mark
#pragma mark - switchAction
- (void)switchAction:(UISwitch *)sender
{
    if(sender.tag ==SwitchActionTagInfo)
    {

        if (sender.isOn) {
            _infoLb.textColor = BlackTitleColor;

        }
        else
        {
            _infoLb.textColor = LightBlackTitleColor;

        }

    }
    else if (sender.tag ==SwitchActionTagPersonalInformation)
    {
        if (sender.isOn) {
            _personalInformationLb.textColor = BlackTitleColor;
        }
        else
        {
            _personalInformationLb.textColor = LightBlackTitleColor;
        }
    }

    else if (sender.tag ==SwitchActionTagCollect)
    {

        _redView.hidden = !sender.isOn;

        if (sender.isOn) {

            _collectLb.textColor = BlackTitleColor;

            if (CGRectGetMaxY(_redView.frame) +60>frameWidth(_mainScrollView)) {

                _mainScrollView.contentSize =CGSizeMake(frameWidth(_mainScrollView), CGRectGetMaxY(_redView.frame) +60);
            }
            if (_redSwitch.isOn) {
                _redViewBg.hidden = NO;
            }
            else
            {
                _redViewBg.hidden = YES;
            }

        }
        else
        {

            _redViewBg.hidden = YES;
            _collectLb.textColor = LightBlackTitleColor;
            if (CGRectGetMaxY(_info.frame) +60>frameWidth(_mainScrollView)) {
                _mainScrollView.contentSize =CGSizeMake(frameWidth(_mainScrollView), CGRectGetMaxY(_info.frame) +60);
            }

        }

        [_mainScrollView scrollRectToVisible:frame(frameX(_mainScrollView), frameY(_mainScrollView), frameWidth(_mainScrollView), _mainScrollView.contentSize.height) animated:YES];
    }
    else if (sender.tag ==SwitchActionTagRed)
    {
        _redViewBg.hidden = !sender.isOn;

        if (sender.isOn) {

            _redLb.textColor = BlackTitleColor;

            _redView.frame = frame(frameX(_redView), frameY(_redView), frameWidth(_redView), redHight);

        }
        else
        {
            _redLb.textColor = LightBlackTitleColor;

            _redView.frame = frame(frameX(_redView), frameY(_redView), frameWidth(_redView), 40);
        }

        if (CGRectGetMaxY(_redView.frame) +60>frameWidth(_mainScrollView)) {

            _mainScrollView.contentSize =CGSizeMake(frameWidth(_mainScrollView), CGRectGetMaxY(_redView.frame) +60);
        }

        [_mainScrollView scrollRectToVisible:frame(frameX(_mainScrollView), frameY(_mainScrollView), frameWidth(_mainScrollView), _mainScrollView.contentSize.height) animated:YES];

    }
    _nextBtn.frame = frame(13*ScreenMultiple,_mainScrollView.contentSize.height - 50 , APPWIDTH - 26*ScreenMultiple, 40);

}
#pragma mark - UITextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    float money = [[NSString stringWithFormat:@"%@%@",textField.text,string] floatValue];

    if (money>[_data.amount floatValue]) {

        [[ToolManager shareInstance] showInfoWithStatus:[NSString stringWithFormat:@"最大金额%@",_data.amount]];
        return NO;
    }

    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHaveDian = NO;
    }
    if ([string length] > 0) {

        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.') {//数据格式正确

            //首字母不能为0和小数点
            if([textField.text length] == 0){
                if(single == '.') {

                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
                ////                if (single == '0') {
                ////
                ////                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                ////                    return NO;
                ////                }
            }

            //输入的字符是否是小数点
            if (single == '.') {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian = YES;
                    return YES;

                }else{

                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }else{
                if (isHaveDian) {//存在小数点

                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    if (range.location - ran.location <= 2) {
                        return YES;
                    }else{

                        return NO;
                    }
                }else{
                    return YES;
                }
            }
        }else{//输入的数据格式不正确

            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

@implementation TheSecondCarResult

@end


text:
import { IModel } from '../../../common/contracts';;
import { IAnonymousRegistration } from './';

export interface IAnonymousSubscription extends IModel {
    channel: string,
    registration?: IAnonymousRegistration,
    registrationId: string
}


text:
/////////////////////////////////////////////////////////////////////////
/// @file   thread.h
///
/// @brief  Wrappers and utilities for multithreading.
/////////////////////////////////////////////////////////////////////////

#ifndef OPENIMAGEIO_THREAD_H
#define OPENIMAGEIO_THREAD_H

#include "version.h"

// defining NOMINMAX to prevent problems with std::min/std::max
// and std::numeric_limits<type>::min()/std::numeric_limits<type>::max()
// when boost include windows.h
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# ifndef NOMINMAX
#   define NOMINMAX
# endif
#endif

#include <boost/version.hpp>
#if defined(__GNUC__) && (BOOST_VERSION == 104500)
// gcc reports errors inside some of the boost headers with boost 1.45
// See: https://svn.boost.org/trac/boost/ticket/4818
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif

#include <boost/thread.hpp>
#include <boost/thread/tss.hpp>
#include <boost/version.hpp>
#if (BOOST_VERSION == 103500)
#  include <boost/thread/shared_mutex.hpp>
#endif

#if defined(__GNUC__) && (BOOST_VERSION == 104500)
// can't restore via push/pop in all versions of gcc (warning push/pop implemented for 4.6+ only)
#pragma GCC diagnostic error "-Wunused-variable"
#endif

#if (BOOST_VERSION < 103500)
#  include <pthread.h>
#endif

#ifndef USE_TBB
#  define USE_TBB 1
#endif

// Include files we need for atomic counters.
// Some day, we hope this is all replaced by use of std::atomic<>.
#if USE_TBB
#  include <tbb/atomic.h>
   using tbb::atomic;
#  include <tbb/spin_mutex.h>
#endif

#if defined(_WIN32) && !USE_TBB
#  include <windows.h>
#  include <winbase.h>
#  pragma intrinsic (_InterlockedExchangeAdd)
#  pragma intrinsic (_InterlockedCompareExchange)
#  pragma intrinsic (_InterlockedCompareExchange64)
#  if defined(_WIN64)
#    pragma intrinsic(_InterlockedExchangeAdd64)
#  endif
#endif

#ifdef __APPLE__
#  include <libkern/OSAtomic.h>
#endif

#if defined(__GNUC__) && (defined(_GLIBCXX_ATOMIC_BUILTINS) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 401))
#if !defined(__FreeBSD__) || defined(__x86_64__)
#define USE_GCC_ATOMICS
#endif
#endif

OIIO_NAMESPACE_ENTER
{

/// Null mutex that can be substituted for a real one to test how much
/// overhead is associated with a particular mutex.
class null_mutex {
public:
    null_mutex () { }
    ~null_mutex () { }
    void lock () { }
    void unlock () { }
    void lock_shared () { }
    void unlock_shared () { }
};

/// Null lock that can be substituted for a real one to test how much
/// overhead is associated with a particular lock.
template<typename T>
class null_lock {
public:
    null_lock (T &m) { }
};

// Null thread-specific ptr that just wraps a single ordinary pointer
//
template<typename T>
class null_thread_specific_ptr {
public:
    typedef void (*destructor_t)(T *);
    null_thread_specific_ptr (destructor_t dest=NULL)
        : m_ptr(NULL), m_dest(dest) { }
    ~null_thread_specific_ptr () { reset (NULL); }
    T * get () { return m_ptr; }
    void reset (T *newptr=NULL) {
        if (m_ptr) {
            if (m_dest)
                (*m_dest) (m_ptr);
            else
                delete m_ptr;
        }
        m_ptr = newptr;
    }
private:
    T *m_ptr;
    destructor_t m_dest;
};

#ifdef NOTHREADS

// Definitions that we use for debugging to turn off all mutexes, locks,
// and atomics in order to test the performance hit of our thread safety.

// Null thread-specific ptr that just wraps a single ordinary pointer
//
template<typename T>
class thread_specific_ptr {
public:
    typedef void (*destructor_t)(T *);
    thread_specific_ptr (destructor_t dest=NULL)
        : m_ptr(NULL), m_dest(dest) { }
    ~thread_specific_ptr () { reset (NULL); }
    T * get () { return m_ptr; }
    void reset (T *newptr=NULL) {
        if (m_ptr) {
            if (m_dest)
                (*m_dest) (m_ptr);
            else
                delete m_ptr;
        }
        m_ptr = newptr;
    }
private:
    T *m_ptr;
    destructor_t m_dest;
};

typedef null_mutex mutex;
typedef null_mutex recursive_mutex;
typedef null_mutex shared_mutex;
typedef null_lock<mutex> lock_guard;
typedef null_lock<recursive_mutex> recursive_lock_guard;
typedef null_lock<shared_mutex> shared_lock;
typedef null_lock<shared_mutex> unique_lock;

#elif (BOOST_VERSION >= 103500)

// Fairly modern Boost has all the mutex and lock types we need.

typedef boost::mutex mutex;
typedef boost::recursive_mutex recursive_mutex;
typedef boost::shared_mutex shared_mutex;
typedef boost::lock_guard< boost::mutex > lock_guard;
typedef boost::lock_guard< boost::recursive_mutex > recursive_lock_guard;
typedef boost::shared_lock< boost::shared_mutex > shared_lock;
typedef boost::unique_lock< boost::shared_mutex > unique_lock;
using boost::thread_specific_ptr;

#else

// Old Boost lacks reader-writer mutexes -- UGLY!!! Make stripped down
// versions of shared_mutex, shared_lock, and exclusive_lock.  I can't
// wait for the day when we get to remove these.  Note that this uses
// pthreads, so only works on Linux & OSX.  Windows will just have to
// use a more modern Boost.

typedef boost::mutex mutex;
typedef boost::recursive_mutex recursive_mutex;
typedef boost::mutex::scoped_lock lock_guard;
typedef boost::recursive_mutex::scoped_lock recursive_lock_guard;
using boost::thread_specific_ptr;

class shared_mutex {
public:
    shared_mutex () { pthread_rwlock_init (&m_rwlock, NULL); }
    ~shared_mutex () { pthread_rwlock_destroy (&m_rwlock); }
    void lock () { pthread_rwlock_wrlock (&m_rwlock); }
    void unlock () { pthread_rwlock_unlock (&m_rwlock); }
    void lock_shared () { pthread_rwlock_rdlock (&m_rwlock); }
    void unlock_shared () { pthread_rwlock_unlock (&m_rwlock); }
private:
    pthread_rwlock_t m_rwlock;
};

class shared_lock {
public:
    shared_lock (shared_mutex &m) : m_mutex(m) { m_mutex.lock_shared (); }
    ~shared_lock () { m_mutex.unlock_shared (); }
private:
    shared_mutex &m_mutex;
};

class unique_lock {
public:
    unique_lock (shared_mutex &m) : m_mutex(m) { m_mutex.lock (); }
    ~unique_lock () { m_mutex.unlock (); }
private:
    shared_mutex &m_mutex;
};

#endif

/// Atomic version of:  r = *at, *at += x, return r
/// For each of several architectures.
inline int
atomic_exchange_and_add (volatile int *at, int x)
{
#ifdef USE_GCC_ATOMICS
    return __sync_fetch_and_add ((int *)at, x);
#elif USE_TBB
    atomic<int> *a = (atomic<int> *)at;
    return a->fetch_and_add (x);
#elif defined(__APPLE__)
    // Apple, not inline for Intel (only PPC?)
    return OSAtomicAdd32Barrier (x, at) - x;
#elif defined(_WIN32)
    // Windows
    return _InterlockedExchangeAdd ((volatile LONG *)at, x);
#else
#   error No atomics on this platform.
#endif
}

inline long long
atomic_exchange_and_add (volatile long long *at, long long x)
{
#ifdef USE_GCC_ATOMICS
    return __sync_fetch_and_add (at, x);
#elif USE_TBB
    atomic<long long> *a = (atomic<long long> *)at;
    return a->fetch_and_add (x);
#elif defined(__APPLE__)
    // Apple, not inline for Intel (only PPC?)
    return OSAtomicAdd64Barrier (x, at) - x;
#elif defined(_WIN32)
    // Windows
#  if defined(_WIN64)
    return _InterlockedExchangeAdd64 ((volatile LONGLONG *)at, x);
#  else
    return InterlockedExchangeAdd64 ((volatile LONGLONG *)at, x);
#  endif
#else
#   error No atomics on this platform.
#endif
}

/// Atomic version of:
///    if (*at == compareval) {
///        *at = newval;  return true;
///    } else {
///        return false;
///
inline bool
atomic_compare_and_exchange (volatile int *at, int compareval, int newval)
{
#ifdef USE_GCC_ATOMICS
    return __sync_bool_compare_and_swap (at, compareval, newval);
#elif USE_TBB
    atomic<int> *a = (atomic<int> *)at;
    return a->compare_and_swap (newval, compareval) == newval;
#elif defined(__APPLE__)
    return OSAtomicCompareAndSwap32Barrier (compareval, newval, at);
#elif defined(_WIN32)
    return (_InterlockedCompareExchange ((volatile LONG *)at, newval, compareval) == compareval);
#else
#   error No atomics on this platform.
#endif
}

inline bool
atomic_compare_and_exchange (volatile long long *at, long long compareval, long long newval)
{
#ifdef USE_GCC_ATOMICS
    return __sync_bool_compare_and_swap (at, compareval, newval);
#elif USE_TBB
    atomic<long long> *a = (atomic<long long> *)at;
    return a->compare_and_swap (newval, compareval) == newval;
#elif defined(__APPLE__)
    return OSAtomicCompareAndSwap64Barrier (compareval, newval, at);
#elif defined(_WIN32)
    return (_InterlockedCompareExchange64 ((volatile LONGLONG *)at, newval, compareval) == compareval);
#else
#   error No atomics on this platform.
#endif
}

#if (! USE_TBB)
// If we're not using TBB, we need to define our own atomic<>.

/// Atomic integer.  Increment, decrement, add, and subtract in a
/// totally thread-safe manner.
template<class T>
class atomic {
public:
    /// Construct with initial value.
    ///
    atomic (T val=0) : m_val(val) { }

    ~atomic () { }

    /// Retrieve value
    ///
    T operator() () const { return atomic_exchange_and_add (&m_val, 0); }

    /// Retrieve value
    ///
    operator T() const { return atomic_exchange_and_add (&m_val, 0); }

    /// Assign new value.
    ///
    T operator= (T x) {
        //incorrect? return (m_val = x);
        while (1) {
            T result = m_val;
            if (atomic_compare_and_exchange (&m_val, result, x))
                break;
        }
        return x;
    }

    /// Pre-increment:  ++foo
    ///
    T operator++ () { return atomic_exchange_and_add (&m_val, 1) + 1; }

    /// Post-increment:  foo++
    ///
    T operator++ (int) {  return atomic_exchange_and_add (&m_val, 1); }

    /// Pre-decrement:  --foo
    ///
    T operator-- () {  return atomic_exchange_and_add (&m_val, -1) - 1; }

    /// Post-decrement:  foo--
    ///
    T operator-- (int) {  return atomic_exchange_and_add (&m_val, -1); }

    /// Add to the value, return the new result
    ///
    T operator+= (T x) { return atomic_exchange_and_add (&m_val, x) + x; }

    /// Subtract from the value, return the new result
    ///
    T operator-= (T x) { return atomic_exchange_and_add (&m_val, -x) - x; }

    bool bool_compare_and_swap (T compareval, T newval) {
        return atomic_compare_and_exchange (&m_val, compareval, newval);
    }

    T operator= (const atomic &x) {
        T r = x();
        *this = r;
        return r;
    }

private:
    volatile mutable T m_val;

    // Disallow copy construction by making private and unimplemented.
    atomic (atomic const &);
};

#endif /* ! USE_TBB */

#ifdef NOTHREADS

typedef int atomic_int;
typedef long long atomic_ll;

#else

typedef atomic<int> atomic_int;
typedef atomic<long long> atomic_ll;

#endif

#ifdef NOTHREADS

typedef null_mutex spin_mutex;
typedef null_lock<spin_mutex> spin_lock;

#elif USE_TBB

// Use TBB's spin locks
typedef tbb::spin_mutex spin_mutex;
typedef tbb::spin_mutex::scoped_lock spin_lock;

#else

// Define our own spin locks.  Do we trust them?

/// A spin_mutex is semantically equivalent to a regular mutex, except
/// for the following:
///  - A spin_mutex is just 4 bytes, whereas a regular mutex is quite
///    large (44 bytes for pthread).
///  - A spin_mutex is extremely fast to lock and unlock, whereas a regular
///    mutex is surprisingly expensive just to acquire a lock.
///  - A spin_mutex takes CPU while it waits, so this can be very
///    wasteful compared to a regular mutex that blocks (gives up its
///    CPU slices until it acquires the lock).
///
/// The bottom line is that mutex is the usual choice, but in cases where
/// you need to acquire locks very frequently, but only need to hold the
/// lock for a very short period of time, you may save runtime by using
/// a spin_mutex, even though it's non-blocking.
///
/// N.B. A spin_mutex is only the size of an int.  To avoid "false
/// sharing", be careful not to put two spin_mutex objects on the same
/// cache line (within 128 bytes of each other), or the two mutexes may
/// effectively (and wastefully) lock against each other.
///
class spin_mutex {
public:
    /// Default constructor -- initialize to unlocked.
    ///
    spin_mutex (void) { m_locked = 0; }

    ~spin_mutex (void) { }

    /// Copy constructor -- initialize to unlocked.
    ///
    spin_mutex (const spin_mutex &) { m_locked = 0; }

    /// Assignment does not do anything, since lockedness should not
    /// transfer.
    const spin_mutex& operator= (const spin_mutex&) { return *this; }

    /// Acquire the lock, spin until we have it.
    ///
    void lock () {
#if defined(__APPLE__)
        // OS X has dedicated spin lock routines, may as well use them.
        OSSpinLockLock ((OSSpinLock *)&m_locked);
#else
        while (! try_lock())
            ;
#endif
    }

    /// Release the lock that we hold.
    ///
    void unlock () {
#if defined(__APPLE__)
        OSSpinLockUnlock ((OSSpinLock *)&m_locked);
#else
        m_locked = 0;
#endif
    }

    /// Try to acquire the lock.  Return true if we have it, false if
    /// somebody else is holding the lock.
    bool try_lock () {
#if defined(__APPLE__)
        return OSSpinLockTry ((OSSpinLock *)&m_locked);
#else
#  if USE_TBB
        // TBB's compare_and_swap returns the original value
        return m_locked.compare_and_swap (0, 1) == 0;
#  else
        // Our compare_and_swap returns true if it swapped
        return m_locked.bool_compare_and_swap (0, 1);
#  endif
#endif
    }

    /// Helper class: scoped lock for a spin_mutex -- grabs the lock upon
    /// construction, releases the lock when it exits scope.
    class lock_guard {
    public:
        lock_guard (spin_mutex &fm) : m_fm(fm) { m_fm.lock(); }
        ~lock_guard () { m_fm.unlock(); }
    private:
        lock_guard(); // Do not implement (even though TBB does)
        lock_guard(const lock_guard& other); // Do not implement
        lock_guard& operator = (const lock_guard& other); // Do not implement
        spin_mutex & m_fm;
    };

private:
    atomic_int m_locked;  ///< Atomic counter is zero if nobody holds the lock
};

typedef spin_mutex::lock_guard spin_lock;

#endif

/// Spinning reader/writer mutex.  This is just like spin_mutex, except
/// that there are separate locking mechanisms for "writers" (exclusive
/// holders of the lock, presumably because they are modifying whatever
/// the lock is protecting) and "readers" (non-exclusive, non-modifying
/// tasks that may access the protectee simultaneously).
class spin_rw_mutex {
public:
    /// Default constructor -- initialize to unlocked.
    ///
    spin_rw_mutex (void) { m_readers = 0; }

    ~spin_rw_mutex (void) { }

    /// Copy constructor -- initialize to unlocked.
    ///
    spin_rw_mutex (const spin_rw_mutex &) { m_readers = 0; }

    /// Assignment does not do anything, since lockedness should not
    /// transfer.
    const spin_rw_mutex& operator= (const spin_rw_mutex&) { return *this; }

    /// Acquire the reader lock.
    ///
    void read_lock () {
        // Spin until there are no writers active
        m_locked.lock();
        // Register ourself as a reader
        ++m_readers;
        // Release the lock, to let other readers work
        m_locked.unlock();
    }

    /// Release the reader lock.
    ///
    void read_unlock () {
        --m_readers;  // it's atomic, no need to lock to release
    }

    /// Acquire the writer lock.
    ///
    void write_lock () {
        // Make sure no new readers (or writers) can start
        m_locked.lock();
        // Spin until the last reader is done, at which point we will be
        // the sole owners and nobody else (reader or writer) can acquire
        // the resource until we release it.
        while (m_readers > 0)
                ;
    }

    /// Release the writer lock.
    ///
    void write_unlock () {
        // Let other readers or writers get the lock
        m_locked.unlock ();
    }

    /// Helper class: scoped read lock for a spin_rw_mutex -- grabs the
    /// read lock upon construction, releases the lock when it exits scope.
    class read_lock_guard {
    public:
        read_lock_guard (spin_rw_mutex &fm) : m_fm(fm) { m_fm.read_lock(); }
        ~read_lock_guard () { m_fm.read_unlock(); }
    private:
        read_lock_guard(); // Do not implement
        read_lock_guard(const read_lock_guard& other); // Do not implement
        read_lock_guard& operator = (const read_lock_guard& other); // Do not implement
        spin_rw_mutex & m_fm;
    };

    /// Helper class: scoped write lock for a spin_rw_mutex -- grabs the
    /// read lock upon construction, releases the lock when it exits scope.
    class write_lock_guard {
    public:
        write_lock_guard (spin_rw_mutex &fm) : m_fm(fm) { m_fm.write_lock(); }
        ~write_lock_guard () { m_fm.write_unlock(); }
    private:
        write_lock_guard(); // Do not implement
        write_lock_guard(const write_lock_guard& other); // Do not implement
        write_lock_guard& operator = (const write_lock_guard& other); // Do not implement
        spin_rw_mutex & m_fm;
    };

private:
    spin_mutex m_locked;   // write lock
    atomic_int m_readers;  // number of readers
};

typedef spin_rw_mutex::read_lock_guard spin_rw_read_lock;
typedef spin_rw_mutex::write_lock_guard spin_rw_write_lock;

}
OIIO_NAMESPACE_EXIT

#endif // OPENIMAGEIO_THREAD_H


text:
var gulp        = require("gulp4"),
    util        = require("gulp-util"),
    watchify      = require("watchify");

//Copy /dist/bundle.js to release/APPNAME.js
gulp.task("watch", function()
{
    return gulp.src(config.path.dist+config.select.bundle)
    .pipe(watchify())
});


text:
gfx = require 'gfx.js'

-- initialize context / server
gfx.listservers()

-- exit
os.exit()


text:
require "googleapps_auth/railtie" if defined?(Rails::Railtie)

require 'openid'
require 'openid/store/memory'
require 'openid/extensions/ax'

module GoogleAppsAuth
  ID_PREFIX = "https://www.google.com/accounts/o8/id"
  DOMAIN_ID_PREFIX = "https://www.google.com/accounts/o8/site-xrds?hd="
  DOMAIN_XRDS_PREFIX = "https://www.google.com/accounts/o8/user-xrds?uri="
  AX_SCHEMAS = {
    :email => "http://schema.openid.net/contact/email",
    :firstname => "http://axschema.org/namePerson/first",
    :lastname => "http://axschema.org/namePerson/last",
    :language => "http://axschema.org/pref/language",
    :country => "http://axschema.org/contact/country/home",
  }
  @@default_domain = nil

  def self.certificate_authority_file=(path)
    OpenID.fetcher.ca_file = path
  end

  def self.certificate_authority_file?
    !! OpenID.fetcher.ca_file
  end

  def self.certificate_authority_file
    OpenID.fetcher.ca_file
  end

  def self.default_domain=(domain)
    @@default_domain = domain
  end

  def self.default_domain
    @@default_domain
  end

  class Result
    attr_reader :error
    def initialize(status, error=nil, attrs=nil)
      @status = status
      @error = error
      @attrs = attrs || {}
    end

    def [](attr)
      @attrs[attr]
    end

    def succeeded?
      @status == :success
    end

    def canceled?
      @status == :canceled
    end

    def failed?
      @status == :failed
    end
  end

  class CertificateAuthorityFileError < StandardError; end

  protected

  ##
  # return_to::
  # return_action::
  # domain::
  # attrs:: zero or more of [ :email, :firstname, :lastname, :language ]
  def google_apps_auth_begin(opts={})
    assert_certificate_authority_file_present!

    opts = {
      :return_action => 'finish',
      :return_to => nil,
      :domain => GoogleAppsAuth.default_domain,
      :attrs => []
    }.merge(opts)

    begin
      oidreq = consumer.begin opts[:domain] ? GoogleAppsAuth::DOMAIN_ID_PREFIX + opts[:domain] : GoogleAppsAuth::ID_PREFIX
      return_to = opts[:return_to] || url_for(:action => opts[:return_action], :only_path => false)
      realm = request.protocol + request.host_with_port
      ax = OpenID::AX::FetchRequest.new
      opts[:attrs].each { |attr|
        ax.add OpenID::AX::AttrInfo.new(GoogleAppsAuth::AX_SCHEMAS[attr], attr.to_s, true)
      }
      oidreq.add_extension(ax)
      redirect_to oidreq.redirect_url(realm, return_to, false)
    rescue OpenID::OpenIDError => e
      Rails.logger.error "ERROR: #{e.inspect}" if defined?(Rails)

      if block_given?
        yield
      else
        flash[:notice] = "Discovery failed."
        redirect_to :action => 'index'
      end
    end
  end

  def google_apps_auth_finish
    assert_certificate_authority_file_present!

    current_url = url_for(:action => request.symbolized_path_parameters[:action], :only_path => false)
    parameters = params.reject { |k, v| request.symbolized_path_parameters[k.to_sym] }
    oidresp = consumer.complete(parameters, current_url)

    case oidresp.status
    when OpenID::Consumer::FAILURE
      GoogleAppsAuth::Result.new :failed, oidresp.message
    when OpenID::Consumer::CANCEL
      GoogleAppsAuth::Result.new :canceled, "Authentication canceled."
    when OpenID::Consumer::SUCCESS
      resp = OpenID::AX::FetchResponse.from_success_response(oidresp)
      attrs = {}

      if resp.respond_to? :data
        GoogleAppsAuth::AX_SCHEMAS.each { |name,schema|
          attrs[name] = resp.data[schema] if not resp.data[schema].nil?
        }
      end

      GoogleAppsAuth::Result.new :success, nil, attrs
    else
      GoogleAppsAuth::Result.new :failed, "Unknown error."
    end
  end

  def store
    OpenID::Store::Memory.new
  end

  def consumer
    @consumer ||= OpenID::Consumer.new(session, store)
  end

  def assert_certificate_authority_file_present!
    unless GoogleAppsAuth.certificate_authority_file?
      raise CertificateAuthorityFileError,
        "Configure a CA file through GoogleAppsAuth.certificate_authority_file="
    end

    unless File.exists?(GoogleAppsAuth.certificate_authority_file)
      raise CertificateAuthorityFileError,
        "GoogleAppsAuth.certificate_authority_file= is a non-existent file"
    end
  end
end

## TemplateURI's are not followed by the openid gem - so we have to trick it
## when we're in private domain mode.
class OpenID::Consumer::IdResHandler
  original_verify_discovery_results = instance_method(:verify_discovery_results)

  define_method(:verify_discovery_results) do
    oldid = @message.get_arg(OpenID::OPENID_NS, 'identity', nil)
    if oldid =~ /google.com\/accounts/
      original_verify_discovery_results.bind(self).call
    else
      @message.set_arg(OpenID::OPENID_NS, 'identity', GoogleAppsAuth::DOMAIN_XRDS_PREFIX + oldid)
      @message.set_arg(OpenID::OPENID_NS, 'claimed_id', GoogleAppsAuth::DOMAIN_XRDS_PREFIX + oldid)
      verify_discovery_results_openid2
      @message.set_arg(OpenID::OPENID_NS, 'identity', oldid)
      @message.set_arg(OpenID::OPENID_NS, 'claimed_id', oldid)
    end
  end
end


text:
require 'generators/rails/cocoonase_model/cocoonase_model_generator'
require 'generators/haml/scaffold/scaffold_generator'
require 'schema_attributes'

module Haml
  module Generators

    class CocoonaseGenerator < Haml::Generators::ScaffoldGenerator

      def view_ref_chain
        @view_ref_chain ||= []
      end
      def view_entity_count
        @view_entity_count ||= 0
        @view_entity_count += 1
      end
      def ref_chain
        @view_ref_chain ||= []
      end
      def entity_count
        @view_entity_count ||= 0
        @view_entity_count += 1
      end

      source_root File.expand_path("../templates", __FILE__)

      def recurse_nests
        unless defined? @ref_name
          @ref_name = [singular_name]
          template_encoded_instructions "_view_%ref_name%_fields.html.haml"
          template_encoded_instructions "_%ref_name%_fields.html.haml"
          template_encoded_instructions "_grid_%singular_name%_fields.html.haml"
          @ref_name = []
          recurse singular_name
        end
        content = parse_erb_template '_form_actions_helper.erb', instance_eval('binding')
        append_to_file app_views_file_path('_form_layout.html.haml'), content
      end

      def clean_up_views_path
        File.delete app_views_file_path('_form.html.haml') if File.exists? app_views_file_path('_form.html.haml')
      end

      protected

      def recurse ref
        SchemaAttributes.parse(ref).references.each do |name, ref|
          if ref.type == :references
            ref_chain << ref.name
            (@ref_name ||= []) << name.to_s
            src = "_view_%ref_name%_fields.html.haml"
            dst = template_encoded_instructions src
            template src.gsub(/_view/, ''), dst.gsub(/_view/, '')
            template(src.gsub(/_view/, '_grid'), dst.gsub(/_view/, '_grid')) unless ref.has_one?
            content = parse_erb_template '_form_layout_helper.erb', instance_eval('binding')
            append_to_file app_views_file_path('_form_layout.html.haml'), content
            content = parse_erb_template '_view_layout_helper.erb', instance_eval('binding')
            append_to_file app_views_file_path('_view_layout.html.haml'), content
            recurse(ref_name)
            ref_chain.pop
          end
        end
      end

      def available_views
        %w(_view_nests _view_fields _form_nests _grid_nests _sidebar_sections _form_actions _sub_navigation).each { |tpl|
          copy_file "application/#{tpl}.html.haml", "app/views/application/#{tpl}.html.haml" unless
              File.exists? "app/views/application/#{tpl}.html.haml"
        }
        %w(index edit new show _view_layout _form_layout _view)
      end

      def references
        @references ||= SchemaAttributes.parse(singular_name).references
      end

      def belongs_to
        @belongs_to ||= SchemaAttributes.parse(singular_name).belongs_to
      end

      def convert_encoded_instructions(filename)
        filename.gsub(/%(.*?)%/) do |initial_string|
          method = $1.strip
          respond_to?(method, true) ? send(method) : initial_string
        end
      end

      def ref_name
        @ref_name.last
      end

      def ref_attributes
        SchemaAttributes.parse(ref_name).accessible
      end

      def ref_references
        SchemaAttributes.parse(ref_name).references
      end

      def ref_belongs_to
        SchemaAttributes.parse(ref_name).belongs_to.reject {|n,a| n == singular_name || @ref_name.include?(n)}
      end

      def ref_hidden_attributes
        SchemaAttributes.parse(ref_name).hidden
      end

      def self_attributes
        SchemaAttributes.parse(singular_name).accessible
      end

      def grid_attributes
        ref_attributes.values + ref_hidden_attributes.values
      end

      def title_name
        @title_name ||= singular_name.titleize
      end

      def plural_title_name
        @plural_title_name ||= plural_name.titleize
      end

      def template_encoded_instructions tpl
        dst = convert_encoded_instructions(app_views_file_path(tpl))
        template tpl, dst
        dst
      end

      def app_views_file_path file
        "app/views/#{SchemaAttributes.path}#{plural_name}/#{file}"
      end

      def parse_erb_template template_file, bindings
        ERB.new(
          ::File.binread(File.expand_path(find_in_source_paths(template_file))),
          nil, '-', '@output_buffer'
        ).result(bindings)
      end

    end
  end
end


text:
package org.usergrid.mongo.protocol;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.jboss.netty.buffer.ChannelBuffer;

public class OpMsg extends Message {

	String message;

	public OpMsg() {
		opCode = OP_MSG;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	@Override
	public void decode(ChannelBuffer buffer) throws IOException {
		super.decode(buffer);
		message = readCString(buffer);
	}

	@Override
	public ChannelBuffer encode(ChannelBuffer buffer) {
		int l = 16; // 4 ints * 4 bytes

		ByteBuffer messageBytes = getCString(message);
		l += messageBytes.capacity();

		messageLength = l;

		buffer = super.encode(buffer);

		buffer.writeBytes(messageBytes);

		return buffer;
	}

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "OpMsg [message=" + message + ", messageLength=" + messageLength
                + ", requestID=" + requestID + ", responseTo=" + responseTo
                + ", opCode=" + opCode + "]";
    }

}


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

<TITLE>
com.esotericsoftware.kryonet.examples.chatrmi Class Hierarchy
</TITLE>

<META NAME="date" CONTENT="2011-02-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package com.esotericsoftware.kryonet.examples.chatrmi

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

com.esotericsoftware.kryonet.examples.chatrmi.ChatRmiClient
com.esotericsoftware.kryonet.examples.chatrmi.ChatRmiServer
com.esotericsoftware.kryonet.examples.chatrmi.Network

Interface Hierarchy

com.esotericsoftware.kryonet.examples.chatrmi.IChatFrame
com.esotericsoftware.kryonet.examples.chatrmi.IPlayer

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
#include <stdio.h>

#include "message.h"
#include "xgettext.h"

#ifdef __cplusplus
extern "C" {
#endif

#define EXTENSIONS_LIBREP \
  { "jl",        "librep"     },                                        \

#define SCANNERS_LIBREP \
  { "librep",           extract_librep,                                   \
                        &flag_table_librep, &formatstring_librep, NULL }, \

/* Scan a librep file and add its translatable strings to mdlp.  */
extern void extract_librep (FILE *fp, const char *real_filename,
                            const char *logical_filename,
                            flag_context_list_table_ty *flag_table,
                            msgdomain_list_ty *mdlp);

/* Handling of options specific to this language.  */

extern void x_librep_extract_all (void);
extern void x_librep_keyword (const char *name);

extern void init_flag_table_librep (void);

#ifdef __cplusplus
}
#endif


text:
docker-maven
============

# Supported tags and respective Dockerfile links

* [jdk-7](https://github.com/carlossg/docker-maven/blob/master/jdk-7/Dockerfile)
* [jdk-7-onbuild](https://github.com/carlossg/docker-maven/blob/master/jdk-7/onbuild/Dockerfile)
* [latest, jdk-8](https://github.com/carlossg/docker-maven/blob/master/jdk-8/Dockerfile)
* [onbuild, jdk-8-onbuild](https://github.com/carlossg/docker-maven/blob/master/jdk-8/onbuild/Dockerfile)

# What is Maven?

[Apache Maven](http://maven.apache.org) is a software project management and comprehension tool.
Based on the concept of a project object model (POM),
Maven can manage a project's build,
reporting and documentation from a central piece of information.

# How to use this image

## Create a Dockerfile in your Maven project

    FROM maven:3.3-jdk-7-onbuild
    CMD ["do-something-with-built-packages"]

Put this file in the root of your project, next to the pom.xml.

This image includes multiple ONBUILD triggers which should be all you need to bootstrap.
The build will `COPY . /usr/src/app` and `RUN mvn install`.

You can then build and run the image:

    docker build -t my-maven .
    docker run -it --name my-maven-script my-maven

## Run a single Maven command

For many simple projects, you may find it inconvenient to write a complete `Dockerfile`.
In such cases, you can run a Maven project by using the Maven Docker image directly,
passing a Maven command to `docker run`:

    docker run -it --rm --name my-maven-project -v "$(pwd)":/usr/src/mymaven -w /usr/src/mymaven maven:3.3-jdk-7 mvn clean install

# User Feedback

## Issues

If you have any problems with or questions about this image, please contact us
through a [GitHub issue](https://github.com/carlossg/docker-maven/issues).

You can also reach many of the official image maintainers via the `#docker-library` IRC channel on Freenode.

## Contributing

You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.

Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/carlossg/docker-maven/issues),
especially for more ambitious contributions.
This gives other contributors a chance to point you in the right direction,
give you feedback on your design, and help you find out if someone else is working on the same thing.


text:
<resources>
    <!--
  ~ The MIT License (MIT)
  ~
  ~ Copyright (c) 2015 Obshtestvo
  ~
  ~ Permission is hereby granted, free of charge, to any person obtaining a copy
  ~ of this software and associated documentation files (the "Software"), to deal
  ~ in the Software without restriction, including without limitation the rights
  ~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  ~ copies of the Software, and to permit persons to whom the Software is
  ~ furnished to do so, subject to the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be included in all
  ~ copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  ~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  ~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  ~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  ~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  ~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  ~ SOFTWARE.
  -->
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">160dp</dimen>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">@dimen/keyline_1</dimen>
    <dimen name="activity_vertical_margin">@dimen/keyline_1</dimen>
    <dimen name="fab_margin">0dp</dimen>
    <dimen name="fab_negative_margin">@dimen/negative_keyline_1_minus_8dp</dimen>

    <dimen name="widget_corner_radius">4dp</dimen>
    <dimen name="view_default_elevation">2dp</dimen>

    <dimen name="keyline_1">16dp</dimen>
    <dimen name="keyline_1_minus_8dp">8dp</dimen>
    <dimen name="keyline_2">72dp</dimen>
    <dimen name="keyline_2_minus_16dp">56dp</dimen>
    <dimen name="negative_keyline_1">-16dp</dimen>
    <dimen name="negative_keyline_1_minus_8dp">-8dp</dimen>

    <!-- List view -->
    <dimen name="single_line_item_height">48dp</dimen>
    <dimen name="single_line_item_with_avatar_height">56dp</dimen>
    <dimen name="two_line_item_height">56dp</dimen>

    <dimen name="text_size_xxsmall">8sp</dimen>
    <dimen name="text_size_xsmall">10sp</dimen>
    <dimen name="text_size_small">12sp</dimen>
    <dimen name="text_size_medium">14sp</dimen>
    <dimen name="text_size_medium_2">16sp</dimen>
    <dimen name="text_size_large">18sp</dimen>
    <dimen name="text_size_xlarge">32sp</dimen>

    <dimen name="map_view_right_padding">11dp</dimen>

    <dimen name="signal_detail_image_view_height">200dp</dimen>
    <dimen name="signal_detail_transparent_view_height">280dp</dimen>

</resources>


text:
<form method="post" action="{{ action }}">

        Title
        <input name="title" type="text" class="form-control" id="input-title" placeholder="" value="{{ page.title }}">

        Slug
        <input name="slug" type="text" class="form-control" id="input-slug" placeholder="" value="{{ page.slug }}">

        Parent
        <input name="parentId" type="text" class="form-control" id="input-parent-id" placeholder="Parent ID or slug" value="{{ page.parentId.toString() }}">

    Content
    <textarea name="content" class="form-control" id="input-content" rows="20">{{ page.content }}</textarea>

  <button type="submit" class="btn btn-primary">Submit</button>
  <button type="reset" class="btn btn-default">Reset</button>
</form>