text:
#include "PublishKafka.h"
#include <cstdio>
#include <algorithm>
#include <memory>
#include <string>
#include <map>
#include <set>
#include "utils/TimeUtil.h"
#include "utils/StringUtils.h"
#include "utils/ScopeGuard.h"
#include "utils/GeneralUtils.h"
#include "core/ProcessContext.h"
#include "core/ProcessSession.h"

namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace processors {

core::Property PublishKafka::SeedBrokers(
    core::PropertyBuilder::createProperty("Known Brokers")->withDescription("A comma-separated list of known Kafka Brokers in the format <host>:<port>")
        ->isRequired(true)->supportsExpressionLanguage(true)->build());

core::Property PublishKafka::Topic(
    core::PropertyBuilder::createProperty("Topic Name")->withDescription("The Kafka Topic of interest")
        ->isRequired(true)->supportsExpressionLanguage(true)->build());

core::Property PublishKafka::DeliveryGuarantee(
    core::PropertyBuilder::createProperty("Delivery Guarantee")->withDescription("Specifies the requirement for guaranteeing that a message is sent to Kafka. "
                                                                                "Valid values are 0 (do not wait for acks), "
                                                                                "-1 or all (block until message is committed by all in sync replicas) "
                                                                                "or any concrete number of nodes.")
        ->isRequired(false)->supportsExpressionLanguage(true)->withDefaultValue(DELIVERY_ONE_NODE)->build());

core::Property PublishKafka::MaxMessageSize(
    core::PropertyBuilder::createProperty("Max Request Size")->withDescription("Maximum Kafka protocol request message size")
        ->isRequired(false)->build());

core::Property PublishKafka::RequestTimeOut(
    core::PropertyBuilder::createProperty("Request Timeout")->withDescription("The ack timeout of the producer request")
        ->isRequired(false)->withDefaultValue<core::TimePeriodValue>("10 sec")->supportsExpressionLanguage(true)->build());

core::Property PublishKafka::MessageTimeOut(
    core::PropertyBuilder::createProperty("Message Timeout")->withDescription("The total time sending a message could take")
        ->isRequired(false)->withDefaultValue<core::TimePeriodValue>("30 sec")->supportsExpressionLanguage(true)->build());

core::Property PublishKafka::ClientName(
    core::PropertyBuilder::createProperty("Client Name")->withDescription("Client Name to use when communicating with Kafka")
        ->isRequired(true)->supportsExpressionLanguage(true)->build());

/**
 * These don't appear to need EL support
 */

core::Property PublishKafka::BatchSize(
    core::PropertyBuilder::createProperty("Batch Size")->withDescription("Maximum number of messages batched in one MessageSet")
        ->isRequired(false)->withDefaultValue<uint32_t>(10)->build());
core::Property PublishKafka::TargetBatchPayloadSize(
    core::PropertyBuilder::createProperty("Target Batch Payload Size")->withDescription("The target total payload size for a batch. 0 B means unlimited (Batch Size is still applied).")
        ->isRequired(false)->withDefaultValue<core::DataSizeValue>("512 KB")->build());
core::Property PublishKafka::AttributeNameRegex("Attributes to Send as Headers", "Any attribute whose name matches the regex will be added to the Kafka messages as a Header", "");
core::Property PublishKafka::QueueBufferMaxTime("Queue Buffering Max Time", "Delay to wait for messages in the producer queue to accumulate before constructing message batches", "");
core::Property PublishKafka::QueueBufferMaxSize("Queue Max Buffer Size", "Maximum total message size sum allowed on the producer queue", "");
core::Property PublishKafka::QueueBufferMaxMessage("Queue Max Message", "Maximum number of messages allowed on the producer queue", "");
core::Property PublishKafka::CompressCodec("Compress Codec", "compression codec to use for compressing message sets", COMPRESSION_CODEC_NONE);
core::Property PublishKafka::MaxFlowSegSize(
    core::PropertyBuilder::createProperty("Max Flow Segment Size")->withDescription("Maximum flow content payload segment size for the kafka record. 0 B means unlimited.")
        ->isRequired(false)->withDefaultValue<core::DataSizeValue>("0 B")->build());
core::Property PublishKafka::SecurityProtocol("Security Protocol", "Protocol used to communicate with brokers", "");
core::Property PublishKafka::SecurityCA("Security CA", "File or directory path to CA certificate(s) for verifying the broker's key", "");
core::Property PublishKafka::SecurityCert("Security Cert", "Path to client's public key (PEM) used for authentication", "");
core::Property PublishKafka::SecurityPrivateKey("Security Private Key", "Path to client's private key (PEM) used for authentication", "");
core::Property PublishKafka::SecurityPrivateKeyPassWord("Security Pass Phrase", "Private key passphrase", "");
core::Property PublishKafka::KerberosServiceName("Kerberos Service Name", "Kerberos Service Name", "");
core::Property PublishKafka::KerberosPrincipal("Kerberos Principal", "Keberos Principal", "");
core::Property PublishKafka::KerberosKeytabPath("Kerberos Keytab Path",
                                                "The path to the location on the local filesystem where the kerberos keytab is located. Read permission on the file is required.", "");
core::Property PublishKafka::MessageKeyField("Message Key Field", "The name of a field in the Input Records that should be used as the Key for the Kafka message.\n"
                                             "Supports Expression Language: true (will be evaluated using flow file attributes)",
                                             "");
core::Property PublishKafka::DebugContexts("Debug contexts", "A comma-separated list of debug contexts to enable."
                                           "Including: generic, broker, topic, metadata, feature, queue, msg, protocol, cgrp, security, fetch, interceptor, plugin, consumer, admin, eos, all", "");
const core::Property PublishKafka::FailEmptyFlowFiles(
    core::PropertyBuilder::createProperty("Fail empty flow files")
        ->withDescription("Keep backwards compatibility with <=0.7.0 bug which caused flow files with empty content to not be published to Kafka and forwarded to failure. The old behavior is "
                          "deprecated. Use connections to drop empty flow files!")
        ->isRequired(false)
        ->withDefaultValue<bool>(true)
        ->build());

core::Relationship PublishKafka::Success("success", "Any FlowFile that is successfully sent to Kafka will be routed to this Relationship");
core::Relationship PublishKafka::Failure("failure", "Any FlowFile that cannot be sent to Kafka will be routed to this Relationship");

void PublishKafka::initialize() {
  // Set the supported properties
  std::set<core::Property> properties;
  properties.insert(SeedBrokers);
  properties.insert(Topic);
  properties.insert(DeliveryGuarantee);
  properties.insert(MaxMessageSize);
  properties.insert(RequestTimeOut);
  properties.insert(MessageTimeOut);
  properties.insert(ClientName);
  properties.insert(AttributeNameRegex);
  properties.insert(BatchSize);
  properties.insert(TargetBatchPayloadSize);
  properties.insert(QueueBufferMaxTime);
  properties.insert(QueueBufferMaxSize);
  properties.insert(QueueBufferMaxMessage);
  properties.insert(CompressCodec);
  properties.insert(MaxFlowSegSize);
  properties.insert(SecurityProtocol);
  properties.insert(SecurityCA);
  properties.insert(SecurityCert);
  properties.insert(SecurityPrivateKey);
  properties.insert(SecurityPrivateKeyPassWord);
  properties.insert(KerberosServiceName);
  properties.insert(KerberosPrincipal);
  properties.insert(KerberosKeytabPath);
  properties.insert(MessageKeyField);
  properties.insert(DebugContexts);
  properties.insert(FailEmptyFlowFiles);
  setSupportedProperties(properties);
  // Set the supported relationships
  std::set<core::Relationship> relationships;
  relationships.insert(Failure);
  relationships.insert(Success);
  setSupportedRelationships(relationships);
}

void PublishKafka::onSchedule(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSessionFactory> &sessionFactory) {
  interrupted_ = false;

  // Try to get a KafkaConnection
  std::string client_id, brokers;
  if (!context->getProperty(ClientName.getName(), client_id)) {
    throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Client Name property missing or invalid");
  }
  if (!context->getProperty(SeedBrokers.getName(), brokers)) {
    throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Known Brokers property missing or invalid");
  }

  // Get some properties not (only) used directly to set up librdkafka

  // Batch Size
  context->getProperty(BatchSize.getName(), batch_size_);
  logger_->log_debug("PublishKafka: Batch Size [%lu]", batch_size_);

  // Target Batch Payload Size
  context->getProperty(TargetBatchPayloadSize.getName(), target_batch_payload_size_);
  logger_->log_debug("PublishKafka: Target Batch Payload Size [%llu]", target_batch_payload_size_);

  // Max Flow Segment Size
  context->getProperty(MaxFlowSegSize.getName(), max_flow_seg_size_);
  logger_->log_debug("PublishKafka: Max Flow Segment Size [%llu]", max_flow_seg_size_);

  // Attributes to Send as Headers
  std::string value;
  if (context->getProperty(AttributeNameRegex.getName(), value) && !value.empty()) {
    attributeNameRegex_ = utils::Regex(value);
    logger_->log_debug("PublishKafka: AttributeNameRegex [%s]", value);
  }

  key_.brokers_ = brokers;
  key_.client_id_ = client_id;

  conn_ = utils::make_unique<KafkaConnection>(key_);
  configureNewConnection(context);

  logger_->log_debug("Successfully configured PublishKafka");
}

void PublishKafka::notifyStop() {
  logger_->log_debug("notifyStop called");
  interrupted_ = true;
  std::lock_guard<std::mutex> lock(messages_mutex_);
  for (auto& messages : messages_set_) {
    messages->interrupt();
  }
  conn_.reset();
}

/**
 * Message delivery report callback using the richer rd_kafka_message_t object.
 */
void PublishKafka::messageDeliveryCallback(rd_kafka_t* rk, const rd_kafka_message_t* rkmessage, void* /*opaque*/) {
  if (rkmessage->_private == nullptr) {
    return;
  }
  // allocated in PublishKafka::ReadCallback::produce
  auto* func = reinterpret_cast<std::function<void(rd_kafka_t*, const rd_kafka_message_t*)>*>(rkmessage->_private);
  try {
    (*func)(rk, rkmessage);
  } catch (...) { }
  delete func;
}

bool PublishKafka::configureNewConnection(const std::shared_ptr<core::ProcessContext> &context) {
  std::string value;
  int64_t valInt;
  std::string valueConf;
  std::array<char, 512U> errstr{};
  rd_kafka_conf_res_t result;
  const std::string PREFIX_ERROR_MSG = "PublishKafka: configure error result: ";

  rd_kafka_conf_t* conf_ = rd_kafka_conf_new();
  if (conf_ == nullptr) {
    throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Failed to create rd_kafka_conf_t object");
  }
  utils::ScopeGuard confGuard([conf_](){
    rd_kafka_conf_destroy(conf_);
  });

  auto key = conn_->getKey();

  if (key->brokers_.empty()) {
    throw Exception(PROCESS_SCHEDULE_EXCEPTION, "There are no brokers");
  }
  result = rd_kafka_conf_set(conf_, "bootstrap.servers", key->brokers_.c_str(), errstr.data(), errstr.size());
  logger_->log_debug("PublishKafka: bootstrap.servers [%s]", key->brokers_);
  if (result != RD_KAFKA_CONF_OK) {
    auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
    throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
  }

  if (key->client_id_.empty()) {
    throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Client id is empty");
  }
  result = rd_kafka_conf_set(conf_, "client.id", key->client_id_.c_str(), errstr.data(), errstr.size());
  logger_->log_debug("PublishKafka: client.id [%s]", key->client_id_);
  if (result != RD_KAFKA_CONF_OK) {
    auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
    throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
  }

  value = "";
  if (context->getProperty(DebugContexts.getName(), value) && !value.empty()) {
    result = rd_kafka_conf_set(conf_, "debug", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: debug [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(KerberosServiceName.getName(), value) && !value.empty()) {
    result = rd_kafka_conf_set(conf_, "sasl.kerberos.service.name", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: sasl.kerberos.service.name [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(KerberosPrincipal.getName(), value) && !value.empty()) {
    result = rd_kafka_conf_set(conf_, "sasl.kerberos.principal", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: sasl.kerberos.principal [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(KerberosKeytabPath.getName(), value) && !value.empty()) {
    result = rd_kafka_conf_set(conf_, "sasl.kerberos.keytab", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: sasl.kerberos.keytab [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(MaxMessageSize.getName(), value) && !value.empty()) {
    result = rd_kafka_conf_set(conf_, "message.max.bytes", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: message.max.bytes [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(QueueBufferMaxMessage.getName(), value) && !value.empty()) {
    result = rd_kafka_conf_set(conf_, "queue.buffering.max.messages", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: queue.buffering.max.messages [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(QueueBufferMaxSize.getName(), value) && !value.empty() && core::Property::StringToInt(value, valInt)) {
    valInt = valInt / 1024;
    valueConf = std::to_string(valInt);
    result = rd_kafka_conf_set(conf_, "queue.buffering.max.kbytes", valueConf.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: queue.buffering.max.kbytes [%s]", valueConf);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(QueueBufferMaxTime.getName(), value) && !value.empty()) {
    core::TimeUnit unit;
    if (core::Property::StringToTime(value, valInt, unit) && core::Property::ConvertTimeUnitToMS(valInt, unit, valInt)) {
      valueConf = std::to_string(valInt);
      result = rd_kafka_conf_set(conf_, "queue.buffering.max.ms", valueConf.c_str(), errstr.data(), errstr.size());
      logger_->log_debug("PublishKafka: queue.buffering.max.ms [%s]", valueConf);
      if (result != RD_KAFKA_CONF_OK) {
        auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
        throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
      }
    }
  }
  value = "";
  if (context->getProperty(BatchSize.getName(), value) && !value.empty()) {
    result = rd_kafka_conf_set(conf_, "batch.num.messages", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: batch.num.messages [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(CompressCodec.getName(), value) && !value.empty() && value != "none") {
    result = rd_kafka_conf_set(conf_, "compression.codec", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: compression.codec [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }
  value = "";
  if (context->getProperty(SecurityProtocol.getName(), value) && !value.empty()) {
    if (value == SECURITY_PROTOCOL_SSL) {
      result = rd_kafka_conf_set(conf_, "security.protocol", value.c_str(), errstr.data(), errstr.size());
      logger_->log_debug("PublishKafka: security.protocol [%s]", value);
      if (result != RD_KAFKA_CONF_OK) {
        auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
        throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
      }
      value = "";
      if (context->getProperty(SecurityCA.getName(), value) && !value.empty()) {
        result = rd_kafka_conf_set(conf_, "ssl.ca.location", value.c_str(), errstr.data(), errstr.size());
        logger_->log_debug("PublishKafka: ssl.ca.location [%s]", value);
        if (result != RD_KAFKA_CONF_OK) {
          auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
          throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
        }
      }
      value = "";
      if (context->getProperty(SecurityCert.getName(), value) && !value.empty()) {
        result = rd_kafka_conf_set(conf_, "ssl.certificate.location", value.c_str(), errstr.data(), errstr.size());
        logger_->log_debug("PublishKafka: ssl.certificate.location [%s]", value);
        if (result != RD_KAFKA_CONF_OK) {
          auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
          throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
        }
      }
      value = "";
      if (context->getProperty(SecurityPrivateKey.getName(), value) && !value.empty()) {
        result = rd_kafka_conf_set(conf_, "ssl.key.location", value.c_str(), errstr.data(), errstr.size());
        logger_->log_debug("PublishKafka: ssl.key.location [%s]", value);
        if (result != RD_KAFKA_CONF_OK) {
          auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
          throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
        }
      }
      value = "";
      if (context->getProperty(SecurityPrivateKeyPassWord.getName(), value) && !value.empty()) {
        result = rd_kafka_conf_set(conf_, "ssl.key.password", value.c_str(), errstr.data(), errstr.size());
        logger_->log_debug("PublishKafka: ssl.key.password [%s]", value);
        if (result != RD_KAFKA_CONF_OK) {
          auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
          throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
        }
      }
    } else {
      auto error_msg = utils::StringUtils::join_pack("PublishKafka: unknown Security Protocol: ", value);
      throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
    }
  }

  // Add all of the dynamic properties as librdkafka configurations
  const auto &dynamic_prop_keys = context->getDynamicPropertyKeys();
  logger_->log_info("PublishKafka registering %d librdkafka dynamic properties", dynamic_prop_keys.size());

  for (const auto &prop_key : dynamic_prop_keys) {
    value = "";
    if (context->getDynamicProperty(prop_key, value) && !value.empty()) {
      logger_->log_debug("PublishKafka: DynamicProperty: [%s] -> [%s]", prop_key, value);
      result = rd_kafka_conf_set(conf_, prop_key.c_str(), value.c_str(), errstr.data(), errstr.size());
      if (result != RD_KAFKA_CONF_OK) {
        auto error_msg = utils::StringUtils::join_pack(PREFIX_ERROR_MSG, errstr.data());
        throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
      }
    } else {
      logger_->log_warn("PublishKafka Dynamic Property '%s' is empty and therefore will not be configured", prop_key);
    }
  }

  // Set the delivery callback
  rd_kafka_conf_set_dr_msg_cb(conf_, &PublishKafka::messageDeliveryCallback);

  // Set the logger callback
  rd_kafka_conf_set_log_cb(conf_, &KafkaConnection::logCallback);

  rd_kafka_t* producer = rd_kafka_new(RD_KAFKA_PRODUCER, conf_, errstr.data(), errstr.size());

  if (producer == nullptr) {
    auto error_msg = utils::StringUtils::join_pack("Failed to create Kafka producer ", errstr.data());
    throw Exception(PROCESS_SCHEDULE_EXCEPTION, error_msg);
  }

  // The producer took ownership of the configuration, we must not free it
  confGuard.disable();

  conn_->setConnection(producer);

  return true;
}

bool PublishKafka::createNewTopic(const std::shared_ptr<core::ProcessContext> &context, const std::string& topic_name) {
  rd_kafka_topic_conf_t* topic_conf_ = rd_kafka_topic_conf_new();
  if (topic_conf_ == nullptr) {
    logger_->log_error("Failed to create rd_kafka_topic_conf_t object");
    return false;
  }
  utils::ScopeGuard confGuard([topic_conf_](){
    rd_kafka_topic_conf_destroy(topic_conf_);
  });

  rd_kafka_conf_res_t result;
  std::string value;
  std::array<char, 512U> errstr{};
  int64_t valInt;
  std::string valueConf;

  value = "";
  if (context->getProperty(DeliveryGuarantee.getName(), value) && !value.empty()) {
    /*
     * Because of a previous error in this processor, the default value of this property was "DELIVERY_ONE_NODE".
     * As this is not a valid value for "request.required.acks", the following rd_kafka_topic_conf_set call failed,
     * but because of an another error, this failure was silently ignored, meaning that the the default value for
     * "request.required.acks" did not change, and thus remained "-1". This means that having "DELIVERY_ONE_NODE" as
     * the value of this property actually caused the processor to wait for delivery ACKs from ALL nodes, instead
     * of just one. In order not to break configurations generated with earlier versions and keep the same behaviour
     * as they had, we have to map "DELIVERY_ONE_NODE" to "-1" here.
     */
    if (value == "DELIVERY_ONE_NODE") {
      value = "-1";
      logger_->log_warn("Using DELIVERY_ONE_NODE as the Delivery Guarantee property is deprecated and is translated to -1 "
                        "(block until message is committed by all in sync replicas) for backwards compatibility. "
                        "If you want to wait for one acknowledgment use '1' as the property.");
    }
    result = rd_kafka_topic_conf_set(topic_conf_, "request.required.acks", value.c_str(), errstr.data(), errstr.size());
    logger_->log_debug("PublishKafka: request.required.acks [%s]", value);
    if (result != RD_KAFKA_CONF_OK) {
      logger_->log_error("PublishKafka: configure request.required.acks error result [%s]", errstr.data());
      return false;
    }
  }
  value = "";
  if (context->getProperty(RequestTimeOut.getName(), value) && !value.empty()) {
    core::TimeUnit unit;
    if (core::Property::StringToTime(value, valInt, unit) &&
        core::Property::ConvertTimeUnitToMS(valInt, unit, valInt)) {
      valueConf = std::to_string(valInt);
      result = rd_kafka_topic_conf_set(topic_conf_, "request.timeout.ms", valueConf.c_str(), errstr.data(), errstr.size());
      logger_->log_debug("PublishKafka: request.timeout.ms [%s]", valueConf);
      if (result != RD_KAFKA_CONF_OK) {
        logger_->log_error("PublishKafka: configure request.timeout.ms error result [%s]", errstr.data());
        return false;
      }
    }
  }
  value = "";
  if (context->getProperty(MessageTimeOut.getName(), value) && !value.empty()) {
    core::TimeUnit unit;
    if (core::Property::StringToTime(value, valInt, unit) &&
        core::Property::ConvertTimeUnitToMS(valInt, unit, valInt)) {
      valueConf = std::to_string(valInt);
      result = rd_kafka_topic_conf_set(topic_conf_, "message.timeout.ms", valueConf.c_str(), errstr.data(), errstr.size());
      logger_->log_debug("PublishKafka: message.timeout.ms [%s]", valueConf);
      if (result != RD_KAFKA_CONF_OK) {
        logger_->log_error("PublishKafka: configure message.timeout.ms error result [%s]", errstr.data());
        return false;
      }
    }
  }

  rd_kafka_topic_t* topic_reference = rd_kafka_topic_new(conn_->getConnection(), topic_name.c_str(), topic_conf_);
  if (topic_reference == nullptr) {
    rd_kafka_resp_err_t resp_err = rd_kafka_last_error();
    logger_->log_error("PublishKafka: failed to create topic %s, error: %s", topic_name.c_str(), rd_kafka_err2str(resp_err));
    return false;
  }

  // The topic took ownership of the configuration, we must not free it
  confGuard.disable();

  std::shared_ptr<KafkaTopic> kafkaTopicref = std::make_shared<KafkaTopic>(topic_reference);

  conn_->putTopic(topic_name, kafkaTopicref);

  return true;
}

void PublishKafka::onTrigger(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSession> &session) {
  // Check whether we have been interrupted
  if (interrupted_) {
    logger_->log_info("The processor has been interrupted, not running onTrigger");
    context->yield();
    return;
  }

  std::lock_guard<std::mutex> lock_connection(connection_mutex_);
  logger_->log_debug("PublishKafka onTrigger");

  // Collect FlowFiles to process
  uint64_t actual_bytes = 0U;
  std::vector<std::shared_ptr<core::FlowFile>> flowFiles;
  for (uint32_t i = 0; i < batch_size_; i++) {
    std::shared_ptr<core::FlowFile> flowFile = session->get();
    if (flowFile == nullptr) {
      break;
    }
    actual_bytes += flowFile->getSize();
    flowFiles.emplace_back(std::move(flowFile));
    if (target_batch_payload_size_ != 0U && actual_bytes >= target_batch_payload_size_) {
      break;
    }
  }
  if (flowFiles.empty()) {
    context->yield();
    return;
  }
  logger_->log_debug("Processing %lu flow files with a total size of %llu B", flowFiles.size(), actual_bytes);

  auto messages = std::make_shared<Messages>();
  // We must add this to the messages set, so that it will be interrupted when notifyStop is called
  {
    std::lock_guard<std::mutex> lock(messages_mutex_);
    messages_set_.emplace(messages);
  }
  // We also have to insure that it will be removed once we are done with it
  utils::ScopeGuard messagesSetGuard([&]() {
    std::lock_guard<std::mutex> lock(messages_mutex_);
    messages_set_.erase(messages);
  });

  // Process FlowFiles
  for (auto& flowFile : flowFiles) {
    size_t flow_file_index = messages->addFlowFile();

    // Get Topic (FlowFile-dependent EL property)
    std::string topic;
    if (!context->getProperty(Topic, topic, flowFile)) {
      logger_->log_error("Flow file %s does not have a valid Topic", flowFile->getUUIDStr());
      messages->modifyResult(flow_file_index, [](FlowFileResult& flow_file_result) {
        flow_file_result.flow_file_error = true;
      });
      continue;
    }

    // Add topic to the connection if needed
    if (!conn_->hasTopic(topic)) {
      if (!createNewTopic(context, topic)) {
        logger_->log_error("Failed to add topic %s", topic);
        messages->modifyResult(flow_file_index, [](FlowFileResult& flow_file_result) {
          flow_file_result.flow_file_error = true;
        });
        continue;
      }
    }

    std::string kafkaKey;
    kafkaKey = "";
    if (context->getDynamicProperty(MessageKeyField, kafkaKey, flowFile) && !kafkaKey.empty()) {
      logger_->log_debug("PublishKafka: Message Key Field [%s]", kafkaKey);
    } else {
      kafkaKey = flowFile->getUUIDStr();
    }

    auto thisTopic = conn_->getTopic(topic);
    if (thisTopic == nullptr) {
      logger_->log_error("Topic %s is invalid", topic);
      messages->modifyResult(flow_file_index, [](FlowFileResult& flow_file_result) {
        flow_file_result.flow_file_error = true;
      });
      continue;
    }

    bool failEmptyFlowFiles = true;
    context->getProperty(FailEmptyFlowFiles.getName(), failEmptyFlowFiles);

    PublishKafka::ReadCallback callback(max_flow_seg_size_, kafkaKey, thisTopic->getTopic(), conn_->getConnection(), *flowFile,
                                        attributeNameRegex_, messages, flow_file_index, failEmptyFlowFiles);
    session->read(flowFile, &callback);

    if (!callback.called_) {
      // workaround: call callback since ProcessSession doesn't do so for empty flow files without resource claims
      callback.process(nullptr);
    }

    if (flowFile->getSize() == 0 && failEmptyFlowFiles) {
      logger_->log_debug("Deprecated behavior, use connections to drop empty flow files! Failing empty flow file with uuid: %s", flowFile->getUUIDStr());
      messages->modifyResult(flow_file_index, [](FlowFileResult& flow_file_result) {
        flow_file_result.flow_file_error = true;
      });
    }

    if (callback.status_ < 0) {
      logger_->log_error("Failed to send flow to kafka topic %s, error: %s", topic, callback.error_);
      messages->modifyResult(flow_file_index, [](FlowFileResult& flow_file_result) {
        flow_file_result.flow_file_error = true;
      });
      continue;
    }
  }

  logger_->log_trace("PublishKafka::onTrigger waitForCompletion start");
  messages->waitForCompletion();
  if (messages->wasInterrupted()) {
    logger_->log_warn("Waiting for delivery confirmation was interrupted, some flow files might be routed to Failure, even if they were successfully delivered.");
  }
  logger_->log_trace("PublishKafka::onTrigger waitForCompletion finish");

  messages->iterateFlowFiles([&](size_t index, const FlowFileResult& flow_file) {
    bool success;
    if (flow_file.flow_file_error) {
      success = false;
    } else {
      success = true;
      for (size_t segment_num = 0; segment_num < flow_file.messages.size(); segment_num++) {
        const auto& message = flow_file.messages[segment_num];
        switch (message.status) {
          case MessageStatus::MESSAGESTATUS_UNCOMPLETE:
            success = false;
            logger_->log_error("Waiting for delivery confirmation was interrupted for flow file %s segment %zu",
                flowFiles[index]->getUUIDStr(),
                segment_num);
          break;
          case MessageStatus::MESSAGESTATUS_ERROR:
            success = false;
            logger_->log_error("Failed to deliver flow file %s segment %zu, error: %s",
                flowFiles[index]->getUUIDStr(),
                segment_num,
                rd_kafka_err2str(message.err_code));
          break;
          case MessageStatus::MESSAGESTATUS_SUCCESS:
            logger_->log_debug("Successfully delivered flow file %s segment %zu",
                flowFiles[index]->getUUIDStr(),
                segment_num);
          break;
        }
      }
    }
    if (success) {
      session->transfer(flowFiles[index], Success);
    } else {
      session->transfer(flowFiles[index], Failure);
    }
  });
}

} /* namespace processors */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */


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

<title>A-Index</title>
<meta name="date" content="2015-07-06">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J K L M N O P Q R S T U V W

A

AABB - Class in engine.space

A 3D axis-aligned bounding box.

AABB(double, double, double, double) - Constructor for class engine.space.AABB

Creates a new AABB based on it's extents.

AABB(double, double, double, double, double) - Constructor for class engine.space.AABB

Creates a new AABB based on it's extents.

AABB(double, double, double, double, double, double) - Constructor for class engine.space.AABB

Creates a new AABB based on it's extents.

activate() - Method in class engine.components.RemoveComponent

Activates this component.

activate() - Method in class engine.util.menu.Menu

Activates the menu handler for the currently selected option.

add(EntityComponent) - Method in class engine.core.entity.Entity

Adds a new component to the entity.

add(JSONValue) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(int) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(long) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(byte) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(short) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(float) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(double) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(boolean) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(char) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(String) - Method in class engine.parsing.json.JSONArray

Adds a new value to the array.

add(T) - Method in class engine.space.Grid

add(T) - Method in interface engine.space.ISpatialStructure

Adds a new object to the spatial structure

add(T) - Method in class engine.space.QuadTree

addLight(LightMap, double, double, double, double, double, double, double, double, Color) - Method in class engine.rendering.LightMap

Adds another light to this LightMap.

applyLighting() - Method in interface engine.rendering.IRenderContext

Applies all accumulated lighting operations to whatever has currently
 been drawn.

applyLighting() - Method in class engine.rendering.RenderContext

ArrayBitmap - Class in engine.rendering

Stores images in an array of 32-bit ARGB pixels.

ArrayBitmap(int, int) - Constructor for class engine.rendering.ArrayBitmap

Creates a new ArrayBitmap

ArrayBitmap(int, int, int[]) - Constructor for class engine.rendering.ArrayBitmap

Creates a new ArrayBitmap from an existing array of 32-bit ARGB pixels.

ArrayBitmap(int, int, int[], int, int, int) - Constructor for class engine.rendering.ArrayBitmap

Creates a new ArrayBitmap from a subset of an existing array of 32-bit
 ARGB pixels.

ArrayBitmap(String) - Constructor for class engine.rendering.ArrayBitmap

Create an ArrayBitmap from a file

ArrayBitmap.IVisitor - Interface in engine.rendering

Interface for visiting every pixel in an ArrayBitmap.

asArray() - Method in class engine.parsing.json.JSONArray

asArray() - Method in class engine.parsing.json.JSONValue

Interprets this as an array.

asBoolean() - Method in class engine.parsing.json.JSONLiteral

asBoolean() - Method in class engine.parsing.json.JSONValue

Interprets this as a boolean.

asDouble() - Method in class engine.parsing.json.JSONNumber

asDouble() - Method in class engine.parsing.json.JSONValue

Interprets this as a double.

asFloat() - Method in class engine.parsing.json.JSONNumber

asFloat() - Method in class engine.parsing.json.JSONValue

Interprets this as a float.

asInt() - Method in class engine.parsing.json.JSONNumber

asInt() - Method in class engine.parsing.json.JSONValue

Interprets this as an int.

asLong() - Method in class engine.parsing.json.JSONNumber

asLong() - Method in class engine.parsing.json.JSONValue

Interprets this as a long.

asObject() - Method in class engine.parsing.json.JSONObject

asObject() - Method in class engine.parsing.json.JSONValue

Interprets this as an object.

asString() - Method in class engine.parsing.json.JSONString

asString() - Method in class engine.parsing.json.JSONValue

Interprets this as a String.

AudioComponent - Class in engine.components

Holds sounds that can be played by an entity.

AudioComponent(Entity, String[], Sound[]) - Constructor for class engine.components.AudioComponent

Creates a new AudioComponent

A B C D E F G H I J K L M N O P Q R S T U V W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
/**
 * @since 2018-09-17 08:48:01
 * @author vivaxy
 */

import * as ET from '../enums/event-types.js';
import * as RS from '../enums/render-sequence.js';
import * as sizes from '../enums/sizes.js';
import Ball from '../class/ball.js';

let balls = [];

function init(ee, canvas) {

  ee.on(ET.TICK, renderBall);
  ee.on(ET.GAME_START, handleStartGame);
  ee.on(ET.GAME_OVER, handleGameOver);
  ee.on(ET.GAME_RESET, handleGameReset);

  handleGameReset();

  function renderBall() {
    ee.emit(ET.APPLY_RENDER, { render, sequence: RS.BALLS });
  }

  function moveBall(et, { delta }) {
    move(delta);
  }

  function handleStartGame() {
    ee.on(ET.TICK, moveBall);
  }

  function handleGameOver() {
    ee.off(ET.TICK, moveBall);
  }

  function handleGameReset() {
    balls = [new Ball(
      sizes.PLATE_X + sizes.PLATE_WIDTH / 2,
      sizes.PLATE_Y - sizes.BALL_RADIUS,
      sizes.BALL_RADIUS,
      'rgba(150, 200, 200, 1)',
      0.5,
      -0.4117,
    )];
  }

  function render(ctx) {
    balls.forEach((ball) => {
      ball.render(ctx);
    });
  }

  function move(delta) {
    balls.forEach((ball) => {
      ball.move(delta, canvas);
    });
  }

}

function getBalls() {
  return balls;
}

function removeBall(ball) {
  const index = balls.indexOf(ball);
  if (index !== -1) {
    balls.splice(index, 1);
  }
}

function addBall(ball) {
  balls.push(ball);
}

export default { init, getBalls, addBall, removeBall };


text:
package org.trafodion.dcs.servermt.serverHandler;

import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;

class DataEvent {
    public ServerHandler server;
    SelectionKey key;

    public DataEvent(ServerHandler server, SelectionKey key) {
        this.server = server;
        this.key = key;
    }
}


text:
package org.nanoframework.commons.support.message;

import java.io.Serializable;

/**
 * Provides an abstract superclass for MessageFactory implementations with default implementations.
 * <p>
 * This class is immutable.
 * </p>
 * @author yanghe
 * @since 1.4.0
 */
public abstract class AbstractMessageFactory implements MessageFactory, Serializable {

    private static final long serialVersionUID = 1L;

    /*
     * (non-Javadoc)
     *
     * @see org.apache.logging.log4j.message.MessageFactory#newMessage(java.lang.Object)
     */
    @Override
    public Message newMessage(final Object message) {
        return new ObjectMessage(message);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.logging.log4j.message.MessageFactory#newMessage(java.lang.String)
     */
    @Override
    public Message newMessage(final String message) {
        return new SimpleMessage(message);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.apache.logging.log4j.message.MessageFactory#newMessage(java.lang.String, java.lang.Object)
     */
    @Override
    public abstract Message newMessage(String message, Object... params);
}


text:
import sys
import os

from ...core import __version__

from ..qt import QtGui, QtWidgets, QtCore

from .control import CompositionWidget, DataWidget, OptimizationWidget, OptionsWidget, DensityOptimizationWidget, \
    ExtrapolationWidget, DiamondWidget, ConfigurationWidget, SollerWidget, TransferFunctionWidget
from .custom import PatternWidget

from .custom import ExpandableBox

class GlassureWidget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super(GlassureWidget, self).__init__(*args, **kwargs)
        self.horizontal_layout = QtWidgets.QHBoxLayout(self)
        self.horizontal_layout.setContentsMargins(0, 0, 0, 0)
        self.horizontal_layout.setSpacing(0)

        self.pattern_widget = PatternWidget()
        self.left_control_widget = LeftControlWidget()
        self.right_control_widget = RightControlWidget()

        self.left_control_scroll_area = QtWidgets.QScrollArea()
        self.left_control_scroll_area.setWidget(self.left_control_widget)
        self.left_control_scroll_area.setWidgetResizable(True)

        self.left_control_scroll_area.setMaximumWidth(300)
        self.left_control_scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        self.right_control_scroll_area = QtWidgets.QScrollArea()
        self.right_control_scroll_area.setWidget(self.right_control_widget)
        self.right_control_scroll_area.setWidgetResizable(True)

        self.right_control_scroll_area.setMaximumWidth(300)
        self.right_control_scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        self.horizontal_layout.addWidget(self.left_control_scroll_area)
        self.horizontal_layout.addWidget(self.pattern_widget)
        self.horizontal_layout.addWidget(self.right_control_scroll_area)

        self.horizontal_layout.setStretch(0, 0)
        self.horizontal_layout.setStretch(1, 100)
        self.horizontal_layout.setStretch(2, 0)

        self.setLayout(self.horizontal_layout)

        self.load_stylesheet()

        self.create_widget_shortcuts()
        self.create_function_shortcuts()

        self.setWindowTitle("Glassure v{}".format(__version__))

    def create_widget_shortcuts(self):
        self.load_data_btn = self.left_control_widget.data_widget.file_widget.load_data_btn
        self.load_bkg_btn = self.left_control_widget.data_widget.file_widget.load_background_btn
        self.data_filename_lbl = self.left_control_widget.data_widget.file_widget.data_filename_lbl
        self.bkg_filename_lbl = self.left_control_widget.data_widget.file_widget.background_filename_lbl

        self.bkg_scaling_sb = self.left_control_widget.data_widget.background_options_gb.scale_sb
        self.bkg_scaling_step_txt = self.left_control_widget.data_widget.background_options_gb.scale_step_txt

        self.smooth_sb = self.left_control_widget.data_widget.smooth_gb.smooth_sb
        self.smooth_step_txt = self.left_control_widget.data_widget.smooth_gb.smooth_step_txt

        self.add_element_btn = self.left_control_widget.composition_widget.add_element_btn
        self.delete_element_btn = self.left_control_widget.composition_widget.delete_element_btn
        self.composition_tw = self.left_control_widget.composition_widget.composition_tw
        self.density_txt = self.left_control_widget.composition_widget.density_txt

        self.q_max_txt = self.left_control_widget.options_widget.q_max_txt
        self.q_min_txt = self.left_control_widget.options_widget.q_min_txt
        self.r_max_txt = self.left_control_widget.options_widget.r_max_txt
        self.r_min_txt = self.left_control_widget.options_widget.r_min_txt
        self.use_modification_cb = self.left_control_widget.options_widget.modification_fcn_cb

        self.activate_extrapolation_cb = self.left_control_widget.extrapolation_widget.activate_cb
        self.extrapolation_q_max_txt = self.left_control_widget.extrapolation_widget.q_max_txt

        self.optimize_activate_cb = self.right_control_widget.optimization_widget.activate_cb
        self.optimize_r_cutoff_txt = self.right_control_widget.optimization_widget.r_cutoff_txt
        self.optimize_iterations_txt = self.right_control_widget.optimization_widget.optimize_iterations_txt
        self.optimize_attenuation_sb = self.right_control_widget.optimization_widget.attenuation_factor_sb

        self.save_sq_btn = self.pattern_widget.mouse_position_widget.save_sq_btn
        self.save_gr_btn = self.pattern_widget.mouse_position_widget.save_gr_btn

        self.configuration_widget = self.right_control_widget.configuration_widget
        self.freeze_configuration_btn = self.right_control_widget.configuration_widget.freeze_btn
        self.remove_configuration_btn = self.right_control_widget.configuration_widget.remove_btn
        self.configuration_tw = self.right_control_widget.configuration_widget.configuration_tw

        self.soller_widget = self.right_control_widget.soller_widget
        self.soller_active_cb = self.right_control_widget.soller_widget.activate_cb

        self.transfer_widget = self.right_control_widget.transfer_widget
        self.transfer_active_cb = self.right_control_widget.transfer_widget.activate_cb

    def create_function_shortcuts(self):
        self.set_composition = self.left_control_widget.composition_widget.set_composition
        self.get_composition = self.left_control_widget.composition_widget.get_composition
        self.get_density = self.left_control_widget.composition_widget.get_density

        self.get_parameter = self.left_control_widget.options_widget.get_parameter

        self.set_extrapolation_method = self.left_control_widget.extrapolation_widget.set_extrapolation_method
        self.get_extrapolation_method = self.left_control_widget.extrapolation_widget.get_extrapolation_method
        self.set_extrapolation_parameters = self.left_control_widget.extrapolation_widget.set_extrapolation_parameters
        self.get_extrapolation_parameters = self.left_control_widget.extrapolation_widget.get_extrapolation_parameters

        self.set_optimization_parameter = self.right_control_widget.optimization_widget.set_parameter
        self.get_optimization_parameter = self.right_control_widget.optimization_widget.get_parameter

        self.set_soller_parameter = self.right_control_widget.soller_widget.set_parameters
        self.get_soller_parameter = self.right_control_widget.soller_widget.get_parameters

    def show(self):
        QtWidgets.QWidget.show(self)
        if sys.platform == "darwin":
            self.setWindowState(
                self.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
            self.activateWindow()
            self.raise_()

    def load_stylesheet(self):
        stylesheet_file = open(os.path.join(module_path(), "DioptasStyle.qss"), 'r')
        stylesheet_str = stylesheet_file.read()
        self.setStyleSheet(stylesheet_str)

class LeftControlWidget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super(LeftControlWidget, self).__init__(*args, **kwargs)
        self.vertical_layout = QtWidgets.QVBoxLayout()
        self.vertical_layout.setSpacing(8)
        self.vertical_layout.setContentsMargins(5, 5, 5, 5)

        self.data_widget = DataWidget()
        self.composition_widget = CompositionWidget()
        self.options_widget = OptionsWidget()
        self.density_optimization_widget = DensityOptimizationWidget()
        self.extrapolation_widget = ExtrapolationWidget()

        self.vertical_layout.addWidget(ExpandableBox(self.data_widget, "Data"))
        self.vertical_layout.addWidget(ExpandableBox(self.composition_widget, "Composition"))
        self.vertical_layout.addWidget(ExpandableBox(self.options_widget, "Options"))
        self.vertical_layout.addWidget(ExpandableBox(self.extrapolation_widget, "Extrapolation"))

        self.vertical_layout.addSpacerItem(QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Fixed,
                                                                 QtWidgets.QSizePolicy.Expanding))

        self.setLayout(self.vertical_layout)

class RightControlWidget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super(RightControlWidget, self).__init__(*args, **kwargs)
        self.vertical_layout = QtWidgets.QVBoxLayout()
        self.vertical_layout.setSpacing(8)
        self.vertical_layout.setContentsMargins(5, 5, 5, 5)

        self.configuration_widget = ConfigurationWidget()
        self.optimization_widget = OptimizationWidget()
        self.density_optimization_widget = DensityOptimizationWidget()
        self.diamond_widget = DiamondWidget()
        self.soller_widget = SollerWidget()
        self.transfer_widget = TransferFunctionWidget()

        self.vertical_layout.addWidget(ExpandableBox(self.configuration_widget, "Configurations"))
        self.vertical_layout.addWidget(ExpandableBox(self.optimization_widget, "Optimization"))
        self.vertical_layout.addWidget(ExpandableBox(self.density_optimization_widget, "Density Optimization", True))
        self.vertical_layout.addWidget(ExpandableBox(self.diamond_widget, "Diamond Correction", True))
        self.vertical_layout.addWidget(ExpandableBox(self.soller_widget, "Soller Slit Correction", True))
        self.vertical_layout.addWidget(ExpandableBox(self.transfer_widget, "Transfer Function Correction", True))

        self.vertical_layout.addSpacerItem(QtWidgets.QSpacerItem(20, 50, QtWidgets.QSizePolicy.Fixed,
                                                                 QtWidgets.QSizePolicy.MinimumExpanding))

        self.setLayout(self.vertical_layout)

def we_are_frozen():
    # All of the modules are built-in to the interpreter, e.g., by py2exe
    return hasattr(sys, "frozen")

def module_path():
    return os.path.dirname(__file__)


text:
void hpcrun_do_custom_init(void);

#endif //CUSTOM_INIT_H


text:
google-spreadsheet
==================

This is a simple app to add and delete items in google spreadsheet in nodejs


text:
module MagicCloud
  class Layouter
    class PlaceNotFound < RuntimeError
    end

    # Incapsulating place lookup process
    # 1. find initial random place
    # 2. at each step, shift in spiral from the previous place
    # 3. always knows, if the place "ready" for shape (empty and inside board)
    class Place
      def initialize(layouter, shape)
        @layouter, @shape = layouter, shape

        # initial position
        @start_x = (@layouter.width/2-@shape.width/2).to_i
        @start_y = (@layouter.height/2-@shape.height/2).to_i

        # when shift of position is more than max delta (diagonal of cloud)
        # there is no hope it will eventually found its place
        @max_delta = Math.sqrt(@layouter.width**2 + @layouter.height**2)

        # algo of next position calc
        @spiral = make_spiral(@shape.size)

        # direction of spiral
        @dt = rand < 0.5 ? 1 : -1

        # initial point of time before we start to look for place
        @t = -@dt
      end

      def next!
        @t += @dt
        dx, dy = @spiral.call(@t)

        fail PlaceNotFound if [dx, dy].map(&:abs).min > @max_delta

        @shape.x = @start_x + dx
        @shape.y = @start_y + dy
      end

      def ready?
        !out_of_board? && !@layouter.board.collides?(@shape)
      end

      private

      def out_of_board?
        @shape.left < 0 || @shape.top < 0 ||
          @shape.right > @layouter.width || @shape.bottom > @layouter.height
      end

      # FIXME: now we always use "rectangular spiral"
      # d3.layout.cloud had two of them as an option - rectangular and
      # archimedean. I assume, it should be checked if usage of two
      # spirals produce significantly different results, and then
      # either one spiral should left, or it should became an option.
      def make_spiral(step)
        rectangular_spiral(step)
      end

      # rubocop:disable Metrics/AbcSize
      def archimedean_spiral(size)
        e = width / height
        ->(t){
          t1 = t * size * 0.01

          [
            e * t1 * Math.cos(t1),
            t1 * Math.sin(t1)
          ].map(&:round)
        }
      end

      def rectangular_spiral(size)
        dy = 4 * size * 0.1
        dx = dy * @layouter.width / @layouter.height
        x = 0
        y = 0
        ->(t){
          sign = t < 0 ? -1 : 1

          # zverok: this is original comment & code from d3.layout.cloud.js
          # Looks too witty for me.
          #
          # See triangular numbers: T_n = n * (n + 1) / 2.
          case (Math.sqrt(1 + 4 * sign * t) - sign).to_i & 3
          when 0 then x += dx
          when 1 then y += dy
          when 2 then x -= dx
          else        y -= dy
          end

          [x, y].map(&:round)
        }
      end
      # rubocop:enable Metrics/AbcSize
    end
  end
end


text:
package org.kaazing.nuklei.amqp_1_0.codec.types;

import static java.lang.Double.doubleToLongBits;
import static java.lang.Double.longBitsToDouble;
import static java.math.MathContext.DECIMAL64;

import java.math.BigDecimal;
import java.util.function.Consumer;

import org.kaazing.nuklei.Flyweight;

import uk.co.real_logic.agrona.BitUtil;
import uk.co.real_logic.agrona.DirectBuffer;

/*
 * See AMQP 1.0 specification, section 1.6.14 "decimal64"
 */
public final class Decimal64Type extends Type
{

    private static final int OFFSET_KIND = 0;
    private static final int SIZEOF_KIND = BitUtil.SIZE_OF_BYTE;

    private static final int OFFSET_VALUE = OFFSET_KIND + SIZEOF_KIND;
    private static final int SIZEOF_VALUE_MAX = BitUtil.SIZE_OF_INT;

    static final int SIZEOF_INT_MAX = SIZEOF_KIND + SIZEOF_VALUE_MAX;

    private static final short WIDTH_KIND_8 = 0x84;

    @Override
    public Kind kind()
    {
        return Kind.DECIMAL64;
    }

    @Override
    public Decimal64Type watch(Consumer<Flyweight> observer)
    {
        super.watch(observer);
        return this;
    }

    @Override
    public Decimal64Type wrap(DirectBuffer buffer, int offset, boolean mutable)
    {
        super.wrap(buffer, offset, mutable);
        return this;
    }

    public Decimal64Type set(BigDecimal value)
    {
        widthKind(WIDTH_KIND_8);
        int64Put(mutableBuffer(), offset() + OFFSET_VALUE, toLongBits(value));
        notifyChanged();
        return this;
    }

    public BigDecimal get()
    {
        switch (widthKind())
        {
        case WIDTH_KIND_8:
            return fromLongBits(int64Get(buffer(), offset() + OFFSET_VALUE));
        default:
            throw new IllegalStateException();
        }
    }

    public int limit()
    {
        switch (widthKind())
        {
        case WIDTH_KIND_8:
            return offset() + OFFSET_VALUE + 8;
        default:
            throw new IllegalStateException();
        }
    }

    private void widthKind(short value)
    {
        uint8Put(mutableBuffer(), offset() + OFFSET_KIND, value);
    }

    private int widthKind()
    {
        return uint8Get(buffer(), offset() + OFFSET_KIND);
    }

    private long toLongBits(BigDecimal value)
    {
        // TODO: use IEEE 754 decimal64 format (not binary64)
        return doubleToLongBits(value.doubleValue());
    }

    private BigDecimal fromLongBits(long value)
    {
        // TODO: use IEEE 754 decimal64 format (not binary64)
        return new BigDecimal(longBitsToDouble(value), DECIMAL64);
    }

}


text:
using System;

namespace Twity.DataModels.StreamMessages
{
    [Serializable]
    public class StatusWithheld
    {
        public long id;
        public long user_id;
        public string[] withheld_in_countries;
    }
}


text:
package postgres

import (
	"context"
	"crypto/sha256"
	"database/sql"
	"encoding/binary"
	"fmt"
	"strings"
	"time"

	"github.com/golang/glog"
	"github.com/golang/protobuf/ptypes"
	"github.com/google/trillian"
)

const (
	// If this statement ORDER BY clause is changed refer to the comment in removeSequencedLeaves
	selectQueuedLeavesSQL = `SELECT leaf_identity_hash,merkle_leaf_hash,queue_timestamp_nanos,queue_id
                        FROM unsequenced
                        WHERE tree_id=$1
                        AND Bucket=0
                        AND queue_timestamp_nanos<=$2
                        ORDER BY queue_timestamp_nanos,leaf_identity_hash ASC LIMIT $3`
	insertUnsequencedEntrySQL = `INSERT INTO unsequenced(tree_id,Bucket,leaf_identity_hash,merkle_leaf_hash,queue_timestamp_nanos,queue_id) VALUES($1,0,$2,$3,$4,$5)`
	deleteUnsequencedSQL      = "DELETE FROM unsequenced WHERE queue_id IN (<placeholder>)"
)

type dequeuedLeaf []byte

func dequeueInfo(_ []byte, queueID []byte) dequeuedLeaf {
	return dequeuedLeaf(queueID)
}

func (t *logTreeTX) dequeueLeaf(rows *sql.Rows) (*trillian.LogLeaf, dequeuedLeaf, error) {
	var leafIDHash []byte
	var merkleHash []byte
	var queueTimestamp int64
	var queueID []byte

	err := rows.Scan(&leafIDHash, &merkleHash, &queueTimestamp, &queueID)
	if err != nil {
		glog.Warningf("Error scanning work rows: %s", err)
		return nil, nil, err
	}

	queueTimestampProto, err := ptypes.TimestampProto(time.Unix(0, queueTimestamp))
	if err != nil {
		return nil, dequeuedLeaf{}, fmt.Errorf("got invalid queue timestamp: %v", err)
	}
	// Note: the LeafData and ExtraData being nil here is OK as this is only used by the
	// sequencer. The sequencer only writes to the SequencedLeafData table and the client
	// supplied data was already written to LeafData as part of queueing the leaf.
	leaf := &trillian.LogLeaf{
		LeafIdentityHash: leafIDHash,
		MerkleLeafHash:   merkleHash,
		QueueTimestamp:   queueTimestampProto,
	}
	return leaf, dequeueInfo(leafIDHash, queueID), nil
}

func generateQueueID(treeID int64, leafIdentityHash []byte, timestamp int64) []byte {
	h := sha256.New()
	b := make([]byte, 10)
	binary.PutVarint(b, treeID)
	h.Write(b)
	b = make([]byte, 10)
	binary.PutVarint(b, timestamp)
	h.Write(b)
	h.Write(leafIdentityHash)
	return h.Sum(nil)
}

func queueArgs(treeID int64, identityHash []byte, queueTimestamp time.Time) []interface{} {
	timestamp := queueTimestamp.UnixNano()
	return []interface{}{timestamp, generateQueueID(treeID, identityHash, timestamp)}
}

func (t *logTreeTX) UpdateSequencedLeaves(ctx context.Context, leaves []*trillian.LogLeaf) error {
	querySuffix := []string{}
	args := []interface{}{}
	for _, leaf := range leaves {
		iTimestamp, err := ptypes.Timestamp(leaf.IntegrateTimestamp)
		if err != nil {
			return fmt.Errorf("got invalid integrate timestamp: %v", err)
		}
		querySuffix = append(querySuffix, valuesPlaceholder5)
		args = append(args, t.treeID, leaf.LeafIdentityHash, leaf.MerkleLeafHash, leaf.LeafIndex, iTimestamp.UnixNano())
	}
	result, err := t.tx.ExecContext(ctx, insertSequencedLeafSQL+strings.Join(querySuffix, ","), args...)
	if err != nil {
		glog.Warningf("Failed to update sequenced leaves: %s", err)
	}
	return checkResultOkAndRowCountIs(result, err, int64(len(leaves)))
}

func (m *postgresLogStorage) getDeleteUnsequencedStmt(ctx context.Context, num int) (*sql.Stmt, error) {
	stmt := &statementSkeleton{
		sql:               deleteUnsequencedSQL,
		firstInsertion:    "%s",
		firstPlaceholders: 1,
		restInsertion:     "%s",
		restPlaceholders:  1,
		num:               num,
	}
	return m.getStmt(ctx, stmt)
}

// removeSequencedLeaves removes the passed in leaves slice (which may be
// modified as part of the operation).
func (t *logTreeTX) removeSequencedLeaves(ctx context.Context, queueIDs []dequeuedLeaf) error {
	// Don't need to re-sort because the query ordered by leaf hash. If that changes because
	// the query is expensive then the sort will need to be done here. See comment in
	// QueueLeaves.
	tmpl, err := t.ls.getDeleteUnsequencedStmt(ctx, len(queueIDs))
	if err != nil {
		glog.Warningf("Failed to get delete statement for sequenced work: %s", err)
		return err
	}
	stx := t.tx.StmtContext(ctx, tmpl)
	args := make([]interface{}, len(queueIDs))
	for i, q := range queueIDs {
		args[i] = []byte(q)
	}
	result, err := stx.ExecContext(ctx, args...)
	if err != nil {
		// Error is handled by checkResultOkAndRowCountIs() below
		glog.Warningf("Failed to delete sequenced work: %s", err)
	}
	return checkResultOkAndRowCountIs(result, err, int64(len(queueIDs)))
}


text:
package com.android.webview.chromium;

import android.content.Context;
import android.webkit.WebViewDatabase;

import org.chromium.android_webview.AwFormDatabase;
import org.chromium.android_webview.HttpAuthDatabase;

/**
 * Chromium implementation of WebViewDatabase -- forwards calls to the
 * chromium internal implementation.
 */
final class WebViewDatabaseAdapter extends WebViewDatabase {

    private AwFormDatabase mFormDatabase;
    private HttpAuthDatabase mHttpAuthDatabase;

    public WebViewDatabaseAdapter(AwFormDatabase formDatabase, HttpAuthDatabase httpAuthDatabase) {
        mFormDatabase = formDatabase;
        mHttpAuthDatabase = httpAuthDatabase;
    }

    @Override
    public boolean hasUsernamePassword() {
        // This is a deprecated API: intentional no-op.
        return false;
    }

    @Override
    public void clearUsernamePassword() {
        // This is a deprecated API: intentional no-op.
    }

    @Override
    public boolean hasHttpAuthUsernamePassword() {
        return mHttpAuthDatabase.hasHttpAuthUsernamePassword();
    }

    @Override
    public void clearHttpAuthUsernamePassword() {
        mHttpAuthDatabase.clearHttpAuthUsernamePassword();
    }

    @Override
    public boolean hasFormData() {
        return mFormDatabase.hasFormData();
    }

    @Override
    public void clearFormData() {
        mFormDatabase.clearFormData();
    }
}


text:
using System;

namespace Matozap.Entities.StoredProcedures
{
    public interface IStoredProcedure
    {
        double MovieSales(DateTime? beginningDate, DateTime? endingDate);
    }
}


text:
package org.apereo.cas.config;

import org.apereo.cas.audit.AuditTrailRecordResolutionPlanConfigurer;
import org.apereo.cas.authentication.bypass.audit.MultifactorAuthenticationProviderBypassAuditResourceResolver;
import org.apereo.cas.configuration.CasConfigurationProperties;

import org.apereo.inspektr.audit.spi.support.DefaultAuditActionResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * This is {@link CasCoreMultifactorAuthenticationAuditConfiguration}.
 *
 * @author Travis Schmidt
 * @since 6.0.0
 */
@Configuration(value = "casCoreMultifactorAuthenticationAuditConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasCoreMultifactorAuthenticationAuditConfiguration {

    @Bean
    public AuditTrailRecordResolutionPlanConfigurer casCoreMfaAuditTrailRecordResolutionPlanConfigurer() {
        return plan -> {
            plan.registerAuditResourceResolver("MFA_BYPASS_RESOURCE_RESOLVER",
                new MultifactorAuthenticationProviderBypassAuditResourceResolver());
            plan.registerAuditActionResolver("MFA_BYPASS_ACTION_RESOLVER", new DefaultAuditActionResolver());
        };
    }
}


text:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *bgImg;
@property (weak, nonatomic) IBOutlet UIImageView *addImg;
@property (weak, nonatomic) IBOutlet UIButton *leftTime;
@property (nonatomic,weak) NSTimer *timer;

@property (nonatomic,assign) int left;

@end

@implementation ViewController
static int const ZJDuration = 3;

- (void)viewDidLoad {
    [super viewDidLoad];

    if ([UIScreen mainScreen].bounds.size.height == 568) {
        self.bgImg.image = [UIImage imageNamed:@"LaunchImage-568h@2x"];
    }else if ([UIScreen mainScreen].bounds.size.height == 736)
    {
        self.bgImg.image = [UIImage imageNamed:@"LaunchImage-800-Portrait-736h@3x"];
    }
    else if ([UIScreen mainScreen].bounds.size.height == 667)
    {
        self.bgImg.image = [UIImage imageNamed:@"LaunchImage-800-667h@2x"];
    }else
    {
        self.bgImg.image = [UIImage imageNamed:@"LaunchImage"];
    }

//相当于广告
    [self.addImg sd_setImageWithURL:[NSURL URLWithString:@"http://p17.qhimg.com/dr/48_48_/t012d281e8ec8e27c06.png"] placeholderImage:[UIImage imageNamed:@"广告.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        NSLog(@"%@,%ld,%@",image,(long)cacheType,imageURL);
    }];

    self.addImg.userInteractionEnabled = YES;
    //给图片添加手势
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];

    [self.addImg addGestureRecognizer:tapGes];

    self.left = ZJDuration;
    //添加一个定时器
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(leftTimes) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

- (void)leftTimes
{
    NSString *title = [NSString stringWithFormat:@"点击跳过了(%zd)",self.left--];
    [self.leftTime setTitle:title forState:UIControlStateNormal];

    // 当那个界面跳到0s的时候,就进行页面的跳转
    if (self.left == -1) {

        [self skip:nil];
    }
}

- (void)tap
{
    //首先要移除定时器
    [self.timer invalidate];

    [UIApplication sharedApplication].keyWindow.rootViewController = [[ZJTabBarController alloc] init];

}

//点击倒数的按钮进行跳转
- (IBAction)skip:(id)sender {

    //首先要移除定时器
    [self.timer invalidate];

    [UIApplication sharedApplication].keyWindow.rootViewController = [[ZJTabBarController alloc] init];
}

@end


text:
package com.tadamski.marfeel.crawler.crawler.qualifier;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.tadamski.marfeel.crawler.crawler.QualificationResult;
import com.tadamski.marfeel.crawler.crawler.Webpage;

import junitparams.JUnitParamsRunner;
import junitparams.Parameters;

@RunWith(JUnitParamsRunner.class)
public class TitleTagQualifierTest {

    private TitleTagQualifier sut = new TitleTagQualifier();

    @Test
    public void shouldNotQualifyEmptyPage() {
        //when
        QualificationResult result = sut.qualify(emptyPage());

        //then
        assertThat(result.isQualified()).isFalse();
    }

    @Test
    @Parameters({
            "News",
            "news",
            "abcdnewsef",
            "noticias",
            "AAAAAAAaaaaaaa NoTiCiAs!!!!!!!!!!!!"
    })
    public void shouldQualifyPageWithTitleTag(String titleTag) throws IOException {
        //when
        QualificationResult result = sut.qualify(pageWithTitleTag(titleTag));

        //then
        assertThat(result.isQualified()).isTrue();
    }

    @Test
    public void shouldNotQualifyPageWithNotMatchingTitleTag() throws IOException {
        //when
        QualificationResult result = sut.qualify(pageWithTitleTag("not matching title tag"));

        //then
        assertThat(result.isQualified()).isFalse();
    }

    @Test
    public void shouldNotQualifyPageWithMisplacedTitleTag() throws IOException {
        //when
        QualificationResult qualificationResult = sut.qualify(pageWith("misplaced_title_tag"));

        //then
        assertThat(qualificationResult.isQualified()).isFalse();
    }

    @Test
    public void shouldNotQualifyPageWithDoubleTitleTag() throws IOException {
        //when
        QualificationResult qualificationResult = sut.qualify(pageWith("doubled_title_tag"));

        //then
        assertThat(qualificationResult.isQualified()).isFalse();
    }

    @Test
    public void shouldNotQualifyPageWithNoTitleTag() throws IOException {
        //when
        QualificationResult qualificationResult = sut.qualify(pageWith("no_title_tag"));

        //then
        assertThat(qualificationResult.isQualified()).isFalse();
    }

    private Webpage pageWith(String s) throws IOException {
        return Webpage.withContent(getTestPageContent(s + ".html"));
    }

    private Webpage pageWithTitleTag(String titleTag) throws IOException {
        return Webpage.withContent(
                getTestPageContent("simple.html").replace("{{title}}", titleTag)
        );
    }

    private String getTestPageContent(String fileName) throws IOException {
        return IOUtils.toString(
                this.getClass().getClassLoader().getResource("crawler/qualifier/test/pages/" + fileName)
        );
    }

    private Webpage emptyPage() {
        return Webpage.withContent("");
    }
}


text:
==============================
Igor, your personal IoT butler
==============================

	This documentation was generated for Igor version |release|

.. toctree::
	:maxdepth: 1
	:caption: Contents:

	overview
	install
	setup
	administration
	std-plugins/readme
	programs
	modules
	rest
	schema
	capabilities
	plugin-structure
	implementation

Getting started
===============

First read the :doc:`overview` to get a feeling for what Igor does, how it does it
and whether this fits your needs. Also check the :doc:`available standard plugins <std-plugins/readme>`
to check for which devices and services plugins are available, and that these
match the things you want to use Igor for.

Then read the documentation on :doc:`installing the software <install>` and install
the Igor software. Next you should check :doc:`setup` which will tell you how to initialize
your database, with the various options you want (mainly to do with security and
access control).

Then :doc:`administration` and :doc:`programs` will show you how to use Igor in
normal operation.

To interface between Igor and other applications or services you should check the
:doc:`programs` documentation for interfacing to shell scripts, :doc:`modules` for
interfacing to Python programs and :doc:`rest` for interfacing to REST services.

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

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


text:
[![License](https://img.shields.io/github/license/w4/reaper.svg?style=flat-square)](https://github.com/w4/reaper) [![Downloads](https://img.shields.io/crates/d/reaper.svg?style=flat-square)](https://crates.io/crates/reaper) [![Version](https://img.shields.io/crates/v/reaper.svg?style=flat-square)](https://crates.io/crates/reaper)

[League of Legends](http://leagueoflegends.com) mass summoner name checker. Supply a region and a list
and the application will check the list for available summoner names. Common uses are finding quick
variations of your name or finding rare (or "OG") names for selling. An API Key is required to do use
this script, they are available for free from [Riot Games](https://developer.riotgames.com/).

You can find a list of the servers you can query from on
[Riot's website](https://developer.riotgames.com/regional-endpoints.html). Examples of inputs for
SERVER: `euw1`, `na1`, `pbe1`.

    Reaper 0.1.0
    Jordan Doyle <jordan@9t9t9.com>
    Scans over a given list for available usernames on League of Legends

    USAGE:
        reaper [FLAGS] [OPTIONS] <SERVER> <INPUT> <API KEY>

    FLAGS:
        -h, --help       Prints help information
        -V, --version    Prints version information
        -v, --verbose    Increases logging verbosity each use up to 3 times

    OPTIONS:
        -o, --output <FILE>    Sets an output file to write available usernames to

    ARGS:
        <SERVER>     Sets the server to search for usernames on
        <INPUT>      Sets the input file to use
        <API KEY>    Sets the API key to use

For example:

    ./reaper euw1 username_list.txt my-api-key -o output.txt

Will check the list `username_list.txt` for available summoner names on Europe West using API key `my-api-key` and
outputs what it finds to output.txt

### Installation

You can install via cargo by running `cargo install reaper`. This will install the latest version of reaper and the
executable will be available globally on your operating system.

Builds are available under [GitHub Releases](https://github.com/w4/reaper/releases) or you can build it from source
by pulling down the code and running `cargo build --release`.


text:
\hypertarget{interface_c_s_route_view}{
\subsection{CSRouteView Klassenreferenz}
\label{interface_c_s_route_view}\index{CSRouteView@{CSRouteView}}
}

{\ttfamily \#import $<$CSRouteView.h$>$}\subsubsection*{Öffentliche Methoden}
\begin{DoxyCompactItemize}
\item
(void) -\/ \hyperlink{interface_c_s_route_view_a32f44e359ed911edd65611b02ae32208}{regionChanged}
\item
(id) -\/ \hyperlink{interface_c_s_route_view_a12dc74e4cd6d4c33fa16abcf6c06e768}{initWithFrame:drawArrows:}
\end{DoxyCompactItemize}
\subsubsection*{Geschützte Attribute}
\begin{DoxyCompactItemize}
\item
MKMapView $\ast$ \hyperlink{interface_c_s_route_view_a3178cd8d5a40441d57450b035e0ccb0b}{\_\-mapView}
\item
\hyperlink{interface_c_s_route_view_internal}{CSRouteViewInternal} $\ast$ \hyperlink{interface_c_s_route_view_a92cd1128c9f172fff59f1eb3e4c674cf}{\_\-internalRouteView}
\end{DoxyCompactItemize}
\subsubsection*{Propertys}
\begin{DoxyCompactItemize}
\item
MKMapView $\ast$ \hyperlink{interface_c_s_route_view_a52bb7d64fe9655c610dd8815851059a1}{mapView}
\end{DoxyCompactItemize}

\subsubsection{Ausführliche Beschreibung}

Definiert in Zeile 15 der Datei CSRouteView.h.

\subsubsection{Dokumentation der Elementfunktionen}
\hypertarget{interface_c_s_route_view_a12dc74e4cd6d4c33fa16abcf6c06e768}{
\index{CSRouteView@{CSRouteView}!initWithFrame:drawArrows:@{initWithFrame:drawArrows:}}
\index{initWithFrame:drawArrows:@{initWithFrame:drawArrows:}!CSRouteView@{CSRouteView}}
\paragraph[{initWithFrame:drawArrows:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (id) initWithFrame: (CGRect) {\em frame}\/ drawArrows: (BOOL) {\em drawArrows}}\hfill}
\label{interface_c_s_route_view_a12dc74e4cd6d4c33fa16abcf6c06e768}

Definiert in Zeile 200 der Datei CSRouteView.m.

Benutzt \_\-internalRouteView, CSRouteViewInternal::drawArrows und CSRouteViewInternal::routeView.\hypertarget{interface_c_s_route_view_a32f44e359ed911edd65611b02ae32208}{
\index{CSRouteView@{CSRouteView}!regionChanged@{regionChanged}}
\index{regionChanged@{regionChanged}!CSRouteView@{CSRouteView}}
\paragraph[{regionChanged}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (void) regionChanged }\hfill}
\label{interface_c_s_route_view_a32f44e359ed911edd65611b02ae32208}

Definiert in Zeile 229 der Datei CSRouteView.m.

Benutzt \_\-internalRouteView und \_\-mapView.

\subsubsection{Dokumentation der Datenelemente}
\hypertarget{interface_c_s_route_view_a92cd1128c9f172fff59f1eb3e4c674cf}{
\index{CSRouteView@{CSRouteView}!\_\-internalRouteView@{\_\-internalRouteView}}
\index{\_\-internalRouteView@{\_\-internalRouteView}!CSRouteView@{CSRouteView}}
\paragraph[{\_\-internalRouteView}]{\setlength{\rightskip}{0pt plus 5cm}-\/ ({\bf CSRouteViewInternal}$\ast$) {\bf \_\-internalRouteView}\hspace{0.3cm}{\ttfamily  \mbox{[}protected\mbox{]}}}\hfill}
\label{interface_c_s_route_view_a92cd1128c9f172fff59f1eb3e4c674cf}

Definiert in Zeile 19 der Datei CSRouteView.h.

Wird benutzt von initWithFrame:drawArrows: und regionChanged.\hypertarget{interface_c_s_route_view_a3178cd8d5a40441d57450b035e0ccb0b}{
\index{CSRouteView@{CSRouteView}!\_\-mapView@{\_\-mapView}}
\index{\_\-mapView@{\_\-mapView}!CSRouteView@{CSRouteView}}
\paragraph[{\_\-mapView}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (MKMapView$\ast$) {\bf \_\-mapView}\hspace{0.3cm}{\ttfamily  \mbox{[}protected\mbox{]}}}\hfill}
\label{interface_c_s_route_view_a3178cd8d5a40441d57450b035e0ccb0b}

Definiert in Zeile 17 der Datei CSRouteView.h.

Wird benutzt von regionChanged.

\subsubsection{Dokumentation der Propertys}
\hypertarget{interface_c_s_route_view_a52bb7d64fe9655c610dd8815851059a1}{
\index{CSRouteView@{CSRouteView}!mapView@{mapView}}
\index{mapView@{mapView}!CSRouteView@{CSRouteView}}
\paragraph[{mapView}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (MKMapView$\ast$) mapView\hspace{0.3cm}{\ttfamily  \mbox{[}read, write, retain\mbox{]}}}\hfill}
\label{interface_c_s_route_view_a52bb7d64fe9655c610dd8815851059a1}

Definiert in Zeile 26 der Datei CSRouteView.h.

Die Dokumentation für diese Klasse wurde erzeugt aufgrund der Dateien:\begin{DoxyCompactItemize}
\item
Classes/\hyperlink{_c_s_route_view_8h}{CSRouteView.h}\item
Classes/\hyperlink{_c_s_route_view_8m}{CSRouteView.m}\end{DoxyCompactItemize}


text:
A block based UITableView/UICollectionView data source

# Features
- Clean Table View & Collection View Code
- Move tableView data source & delegate method into viewDidLoad with blocks
- Mutiple cells with different class to a single array
- Both xib cell and none-xib cell are supported

# Usage

    //cells for cell models
    NSDictionary *modelCellMap = @{ @"DemoCellModel":@"DemoCell", @"DemoCellModel_XIB":@"DemoCell_XIB" };

    //create a data source
    WFDataSource *dataSource = [[WFDataSource alloc] initWithModelCellMap:modelCellMap cellConfigBlock:^(id cell, id item, NSIndexPath *indexPath) {
        [cell configWithItem:item];
    }];

    //on select cell
    dataSource.didSelectCellBlock = ^(id item, NSIndexPath *indexPath) {
        NSLog(@"%@ - section %@, row %@",item, @(indexPath.section), @(indexPath.row));
    };

    //cell height
    dataSource.heightForRow = ^CGFloat (id item, NSIndexPath *indexPath) {
        return 44;
    };

    //section header view
    dataSource.headerViewForSection = ^ UIView *(id sectionItem, NSInteger section){
        WFDataSourceSection *sectionData = (WFDataSourceSection *)sectionItem;
        if (sectionData.sectionTitle) {
            UIView *bg = [UIView new];
            bg.frame = CGRectMake(0, 0, 0, 30);
            bg.backgroundColor = [UIColor lightGrayColor];

            UILabel *label = [UILabel new];
            label.frame = CGRectMake(10, 0, 100, 30);
            label.text = sectionData.sectionTitle;
            [bg addSubview:label];
            return bg;
        }
            return nil;
        };

    self.dataSource.tableView = self.tableView;

    //reload cell with model array
    [self.dataSource reloadWithSectionItems:[self sectionModels]];

    //or
    [self.dataSource reloadWithItems:[self models]];

# 中文文档
基于block的TableView/CollectionView数据源和代理方法的封装

# 特性
- 让 Table View & Collection 代码更加整洁
- 使用 block 将 tableView 的数据源和代理方法扁平化到 viewDidLoad: 中
- 可包含多个不同类的 cell
- 同时支持 XIB 和纯代码创建的 cell

# 简介
iOS界面开发中,每个控制器中重复度最高的代码,可能就是 TableView 的相关方法了。

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

上面的代码在项目中大量出现,Table View 通过这些数据源方法和代理方法与 view controllers 之间传递信息,而几乎所有的任务都在 view controller 中进行。为了避免让 view controllers 做所有的事,我们可以将所有的这些繁琐的任务,交给一个专门的类来处理,view controllers 只需在 viewDidLoad: 中告诉这个类要做什么。基于这个思路,我对 Table View / Collection View 的数据源和代理方法进行了封装。

在MVC模式下,每个 Cell 应该有一个对应的 Model 来处理数据业务,在初始化 WFDataSource 时,需要传入Model与Cell的对应关系。通过block回调,将 cell 与 model 对应起来。

    //cells for cell models
    NSDictionary *modelCellMap = @{ @"DemoCellModel":@"DemoCell", @"DemoCellModel_XIB":@"DemoCell_XIB" };

    //create a data source
    WFDataSource *dataSource = [[WFDataSource alloc] initWithModelCellMap:modelCellMap cellConfigBlock:^(id cell, id item, NSIndexPath *indexPath) {
        [cell configWithItem:item];
    }];

在项目中往往会出现使用XIB创建的Cell和纯代码Cell混用的情形,而两者在通过 table view 的缓存池机制创建 cell 时的差异,可以通过下面两个方法进行统一。

    - (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier;
    - (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier;

WFDataSource 对此进行了处理, 传入的cell 支持任意方式创建,并可以混用。Table View 的其他数据源方法和代理方法,通过 block 的方式扁平化处理。

    //on select cell
    dataSource.didSelectCellBlock = ^(id item, NSIndexPath *indexPath) {
        NSLog(@"%@ - section %@, row %@",item, @(indexPath.section), @(indexPath.row));
    };

    //cell height
    dataSource.heightForRow = ^CGFloat (id item, NSIndexPath *indexPath) {
        return 44;
    };

    //section header view
    dataSource.headerViewForSection = ^ UIView *(id sectionItem, NSInteger section){
        WFDataSourceSection *sectionData = (WFDataSourceSection *)sectionItem;
        if (sectionData.sectionTitle) {
            UIView *bg = [UIView new];
            bg.frame = CGRectMake(0, 0, 0, 30);
            bg.backgroundColor = [UIColor lightGrayColor];

            UILabel *label = [UILabel new];
            label.frame = CGRectMake(10, 0, 100, 30);
            label.text = sectionData.sectionTitle;
            [bg addSubview:label];
            return bg;
        }
            return nil;
    };

dataSource 创建后,需要将绑定的table view 赋给它。并刷新cell

self.dataSource.tableView = self.tableView;

    //reload cell with model array
    [self.dataSource reloadWithSectionItems:[self sectionModels]];

    //or
    [self.dataSource reloadWithItems:[self models]];


text:
package org.eclipse.rdf4j.sail.elasticsearchstore.config;

import static org.assertj.core.api.Assertions.assertThat;

import org.eclipse.rdf4j.sail.config.SailConfigException;
import org.eclipse.rdf4j.sail.elasticsearchstore.ElasticsearchStore;
import org.junit.Before;
import org.junit.Test;

public class ElasticsearchStoreFactoryTest {

	private ElasticsearchStoreFactory subject;

	@Before
	public void setUp() throws Exception {
		subject = new ElasticsearchStoreFactory();
	}

	@Test
	public void getSailTypeReturnsCorrectValue() {
		assertThat(subject.getSailType()).isEqualTo(ElasticsearchStoreFactory.SAIL_TYPE);
	}

	/**
	 * Verify that the created sail is configured according to the supplied default configuration.
	 */
	@Test(expected = SailConfigException.class)
	public void getSailWithDefaultConfigFails() {
		ElasticsearchStoreConfig config = new ElasticsearchStoreConfig();
		ElasticsearchStore sail = (ElasticsearchStore) subject.getSail(config);
	}

	/**
	 * Verify that the created sail is configured according to the supplied customized configuration.
	 */
	@Test
	public void getSailWithCustomConfigSetsConfigurationCorrectly() {
		ElasticsearchStoreConfig config = new ElasticsearchStoreConfig();

		// set everything to the opposite of its default
		config.setHostname("localhost");
		config.setClusterName("elasticsearch");
		config.setIndex("index1");
		config.setPort(9300);

		ElasticsearchStore sail = (ElasticsearchStore) subject.getSail(config);
		assertMatchesConfig(sail, config);
	}

	private void assertMatchesConfig(ElasticsearchStore sail, ElasticsearchStoreConfig config) {
		assertThat(sail.getClusterName()).isEqualTo(config.getClusterName());
		assertThat(sail.getHostname()).isEqualTo(config.getHostname());
		assertThat(sail.getIndex()).isEqualTo(config.getIndex());
		assertThat(sail.getPort()).isEqualTo(config.getPort());

	}

}


text:
version=1.0.0

set -e -o pipefail

TMP="$(mktemp -d)"
trap "rm -rf $TMP" EXIT

rm -rf cmdliner
mkdir -p cmdliner/src

(cd $TMP && opam source cmdliner.$version)

SRC=$TMP/cmdliner.$version

cp -v $SRC/LICENSE.md cmdliner
cp -v $SRC/src/*.{ml,mli} cmdliner/src

git checkout cmdliner/src/jbuild
git add -A .


text:
class CPDF_TextObject;
class CPDF_PathObject;
class CPDF_ImageObject;
class CPDF_ShadingObject;
class CPDF_FormObject;

class CPDF_PageObject : public CPDF_GraphicStates {
 public:
  enum Type {
    TEXT = 1,
    PATH,
    IMAGE,
    SHADING,
    FORM,
  };

  CPDF_PageObject();
  ~CPDF_PageObject() override;

  virtual Type GetType() const = 0;
  virtual void Transform(const CFX_Matrix& matrix) = 0;
  virtual bool IsText() const;
  virtual bool IsPath() const;
  virtual bool IsImage() const;
  virtual bool IsShading() const;
  virtual bool IsForm() const;
  virtual CPDF_TextObject* AsText();
  virtual const CPDF_TextObject* AsText() const;
  virtual CPDF_PathObject* AsPath();
  virtual const CPDF_PathObject* AsPath() const;
  virtual CPDF_ImageObject* AsImage();
  virtual const CPDF_ImageObject* AsImage() const;
  virtual CPDF_ShadingObject* AsShading();
  virtual const CPDF_ShadingObject* AsShading() const;
  virtual CPDF_FormObject* AsForm();
  virtual const CPDF_FormObject* AsForm() const;

  void TransformClipPath(CFX_Matrix& matrix);
  void TransformGeneralState(CFX_Matrix& matrix);

  CFX_FloatRect GetRect() const {
    return CFX_FloatRect(m_Left, m_Bottom, m_Right, m_Top);
  }
  FX_RECT GetBBox(const CFX_Matrix* pMatrix) const;

  FX_FLOAT m_Left;
  FX_FLOAT m_Right;
  FX_FLOAT m_Top;
  FX_FLOAT m_Bottom;
  CPDF_ContentMark m_ContentMark;

 protected:
  void CopyData(const CPDF_PageObject* pSrcObject);

 private:
  CPDF_PageObject(const CPDF_PageObject& src) = delete;
  void operator=(const CPDF_PageObject& src) = delete;
};

#endif  // CORE_FPDFAPI_PAGE_CPDF_PAGEOBJECT_H_


text:
const path = require('path')
const webpack = require('webpack')

module.exports = {
    entry: [
        path.join(__dirname, 'src/index.js')
    ],
    output: {
        path: path.join(__dirname, '/dist/'),
        filename: 'app.bundle.js',
        publicPath: '/'
    },

    plugins: [
        // OccurenceOrderPlugin is needed for webpack 1.x only
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.NoErrorsPlugin(),
        // TODO: Not sure why it doesn't work
        // new webpack.optimize.UglifyJsPlugin({
        //     compressor: {
        //         warnings: false,
        //         screw_ie8: true
        //     }
        // }),
    ],

    loaders: [{
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader"
    }, {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
    }]
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Mycol. Soc. Japan 17(3-4): 288 (1976)

#### Original name
Cercosporella aesculi Y. Harada & Katsuki

### Remarks
null


text:
#include "El.hpp"

namespace El {
namespace transpose {

// (U,V) |-> (V,Collect(U))
template<typename T>
void ColAllGather
( const AbstractDistMatrix<T>& A,
        AbstractDistMatrix<T>& B, bool conjugate )
{
    DEBUG_ONLY(
        CallStackEntry cse("transpose::ColAllGather");
        if( B.ColDist() != A.RowDist() ||
            B.RowDist() != Collect(A.ColDist()) )
            LogicError("Incompatible distributions");
    )
    std::unique_ptr<AbstractDistMatrix<T>> ATrans
    ( A.ConstructTranspose(A.Grid(),A.Root()) );
    ATrans->AlignWith( A );
    ATrans->Resize( A.Width(), A.Height() );
    Transpose( A.LockedMatrix(), ATrans->Matrix(), conjugate );
    Copy( *ATrans, B );
}

template<typename T>
void ColAllGather
( const AbstractBlockDistMatrix<T>& A,
        AbstractBlockDistMatrix<T>& B, bool conjugate )
{
    DEBUG_ONLY(
        CallStackEntry cse("transpose::ColAllGather");
        if( B.ColDist() != A.RowDist() ||
            B.RowDist() != Collect(A.ColDist()) )
            LogicError("Incompatible distributions");
    )
    std::unique_ptr<AbstractBlockDistMatrix<T>> ATrans
    ( A.ConstructTranspose(A.Grid(),A.Root()) );
    ATrans->AlignWith( A );
    ATrans->Resize( A.Width(), A.Height() );
    Transpose( A.LockedMatrix(), ATrans->Matrix(), conjugate );
    Copy( *ATrans, B );
}

#define PROTO(T) \
  template void ColAllGather \
  ( const AbstractDistMatrix<T>& A, \
          AbstractDistMatrix<T>& B, bool conjugate ); \
  template void ColAllGather \
  ( const AbstractBlockDistMatrix<T>& A, \
          AbstractBlockDistMatrix<T>& B, bool conjugate );

#include "El/macros/Instantiate.h"

} // namespace transpose
} // namespace El


text:
/**
 * Created by baebae on 4/05/16.
 */

import {
  SET_MAP_PACKAGE_REGION,
  UPDATE_PACKAGE_RUNNING_STATUS,
  UPDATE_PACKAGE_STATUS_MESSAGE
} from '../actions/MapPackageActions';
import defaultState from './defaultState';

export default function mapPackageInfo (state = defaultState.mapPackageInfo, action) {
  switch (action.type) {

    case SET_MAP_PACKAGE_REGION:
      return Object.assign({}, state, {
        region: action.region,
      });
    case UPDATE_PACKAGE_RUNNING_STATUS:
      return Object.assign({}, state, {
        running: action.running,
      });
    case UPDATE_PACKAGE_STATUS_MESSAGE:
      return Object.assign({}, state, {
        message: action.message,
      });

    default:
      return state;
  }
}


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

<title>org.canova.api.records</title>
<meta name="date" content="2016-06-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.canova.api.records

Interfaces

Index

Classes

Buffer

Utils


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_memmove_52c.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.label.xml
Template File: sources-sink-52c.tmpl.c
*/
/*
 * @description
 * CWE: 121 Stack Based Buffer Overflow
 * BadSource:  Set data pointer to the bad buffer
 * GoodSource: Set data pointer to the good buffer
 * Sink: memmove
 *    BadSink : Copy int64_t array to data using memmove
 * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
 *
 * */

#include "std_testcase.h"

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

void CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_memmove_52c_badSink(int64_t * data)
{
    {
        int64_t source[100] = {0}; /* fill with 0's */
        /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
        memmove(data, source, 100*sizeof(int64_t));
        printLongLongLine(data[0]);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_memmove_52c_goodG2BSink(int64_t * data)
{
    {
        int64_t source[100] = {0}; /* fill with 0's */
        /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
        memmove(data, source, 100*sizeof(int64_t));
        printLongLongLine(data[0]);
    }
}

#endif /* OMITGOOD */