text:
"""Cassandra utilities factoring code across tests.

The dependencies for this module are not included in requirements.txt or in the package
dependencies, instead one needs the elements of tests-requirements.txt .
"""
from __future__ import absolute_import
from __future__ import print_function

import logging
import os
import sys

from cassandra import cluster as c_cluster

HAS_CASSANDRA_HOME = bool(os.getenv("CASSANDRA_HOME"))
CASSANDRA_HOSTPORT = os.getenv("CASSANDRA_HOSTPORT")
HAS_CASSANDRA = HAS_CASSANDRA_HOME or CASSANDRA_HOSTPORT

# Only try to import cassandra if we are going to use it. This is better
# than using try/except because the failure case is easier to handle.
if HAS_CASSANDRA_HOME:
    from testing import cassandra3 as testing_cassandra

class CassandraHelper:
    """Helper for an ephemeral Cassandra cluster."""

    KEYSPACE = "testkeyspace"

    @classmethod
    def get_accessor_settings(cls):
        """Prepare accessor settings for Cassandra driver."""
        return {
            "cassandra_keyspace": cls.KEYSPACE,
            "cassandra_contact_points": cls.contact_points,
            "cassandra_port": cls.port,
            "cassandra_timeout": 60,
        }

    @classmethod
    def setUpClass(cls):
        """Create the test Cassandra Cluster as cls.cassandra."""
        cls.cassandra = None
        if CASSANDRA_HOSTPORT:
            host, cls.port = CASSANDRA_HOSTPORT.split(":")
            cls.contact_points = [host]
        else:
            cls.setUpCassandra()

        # Make it easy to do raw queries to Cassandra.
        cls.cluster = c_cluster.Cluster(cls.contact_points, cls.port)
        cls.session = cls.cluster.connect()
        cls._reset_keyspace(cls.session, cls.KEYSPACE)
        cls._reset_keyspace(cls.session, cls.KEYSPACE + "_metadata")

    @classmethod
    def setUpCassandra(cls):
        """Start Cassandra."""
        cls.cassandra = testing_cassandra.Cassandra(auto_start=False)
        try:
            cls.cassandra.setup()
            cls.cassandra.start()
        except Exception as e:
            logging.exception(e)
            print(
                "fail to starting cassandra, logging potentially useful debug info",
                file=sys.stderr,
            )
            for attr in (
                "cassandra_home",
                "cassandra_yaml",
                "cassandra_bin",
                "base_dir",
                "settings",
            ):
                print(
                    attr, ":", getattr(cls.cassandra, attr, "Unknown"), file=sys.stderr
                )
            cls.cassandra.cleanup()
            raise

        # testing.cassandra is meant to be used with the Thrift API, so we need to
        # extract the IPs and native port for use with the native driver.
        cls.contact_points = [s.split(":")[0] for s in cls.cassandra.server_list()]
        cls.port = cls.cassandra.cassandra_yaml["native_transport_port"]

    @classmethod
    def tearDownClass(cls):
        """Stop the test Cassandra Cluster."""
        cls.cluster.shutdown()
        cls.session = None
        cls.cluster = None
        if cls.cassandra:
            cls.cassandra.stop()
            cls.cassandra = None

    @classmethod
    def _reset_keyspace(cls, session, keyspace):
        cls.drop_keyspace(session, keyspace)
        cls.create_unreplicated_keyspace(session, keyspace)

    @staticmethod
    def create_unreplicated_keyspace(session, keyspace):
        """Create a keyspace, mostly used for tests."""
        template = (
            'CREATE KEYSPACE "%s" '
            " WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1}"
            " AND durable_writes = false;"
        )
        session.execute(template % keyspace)

    @staticmethod
    def drop_keyspace(session, keyspace):
        """Drop a keyspace, mostly used for tests."""
        template = 'DROP KEYSPACE IF EXISTS "%s";'
        session.execute(template % keyspace)

    def flush(self, accessor):
        """Flush all kind of buffers related to Cassandra."""
        # When using Lucene, we need to force a refresh on the index as the default
        # refresh period is 60s.
        if accessor.use_lucene:
            statements = accessor.metadata_query_generator.sync_queries()
            for statement in statements:
                self.session.execute(statement)

        # Hope that after this all async calls will have been processed.
        self.cluster.refresh_schema_metadata()


text:
#include <algorithm>
#include <memory>
#include <utility>

#include "gml_st/IR/gml_st_ops.h"
#include "gml_st/interfaces/tiling_interface_impl.h"
#include "gml_st/transforms/fusion/fusion.h"
#include "gml_st/transforms/passes.h"
#include "gml_st/transforms/tiling/tiling.h"
#include "gml_st/transforms/transforms.h"
#include "gml_st/utils/linalg_utils.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"

namespace mlir {
namespace gml_st {
namespace {

#define GEN_PASS_DEF_TILINGCWISEPASS
#include "gml_st/transforms/passes.h.inc"

bool isRootOfCwiseExpr(Operation *op) {
  return isCwiseGenericOp(op) &&
         llvm::none_of(op->getUsers(), [](Operation *user) {
           return isCwiseGenericOp(user) || llvm::isa<MaterializeOp>(user);
         });
}

struct TilingCwisePass : public impl::TilingCwisePassBase<TilingCwisePass> {
  TilingCwisePass() = default;
  TilingCwisePass(bool distribute, ArrayRef<int64_t> tileSizes,
                  StringRef distributionLabel) {
    distribute_ = distribute;
    tileSizes_ = tileSizes;
    distributionLabel_ = distributionLabel.str();
  }

  void getDependentDialects(DialectRegistry &registry) const final {
    registry
        .insert<GmlStDialect, linalg::LinalgDialect, tensor::TensorDialect>();
    registerGmlStTilingInterfaceExternalModels(registry);
  }

  void runOnOperation() override {
    func::FuncOp f = getOperation();
    MLIRContext *ctx = &getContext();

    // Populate tiling options.
    TilingOptions opts;
    opts.distribute = distribute_;
    opts.tileSizeComputationFn = [&](OpBuilder &b, Operation *op) {
      Location loc = op->getLoc();
      int64_t rank =
          op->getResultTypes().front().dyn_cast<RankedTensorType>().getRank();
      SmallVector<Value> tileSizesValues(
          rank, b.create<arith::ConstantIndexOp>(loc, 1));

      // Materialize the given right-aligned tile sizes as constants.
      int64_t i = rank - 1;
      for (int64_t t : llvm::reverse(tileSizes_)) {
        tileSizesValues[i--] = b.create<arith::ConstantIndexOp>(loc, t);
        if (i < 0) break;
      }

      return tileSizesValues;
    };
    opts.distributionLabel = distributionLabel_;

    // Tile the roots of cwise expressions and fuse all cwise operands greedily.
    auto tileRootOfCwiseExprFn = [](TilingInterface op) {
      return success(isRootOfCwiseExpr(op));
    };
    auto fuseCwiseOperandsGreedilyFn = [](MaterializeOp op) {
      return success(isCwiseGenericOp(op.getSource().getDefiningOp()));
    };

    // Populate tiling and fusion patterns.
    RewritePatternSet patterns(ctx);
    populateTilingPatterns(ctx, tileRootOfCwiseExprFn, opts, &patterns);
    populateFusionPatterns(ctx, fuseCwiseOperandsGreedilyFn, &patterns);

    if (failed(applyPatternsAndFoldGreedily(f, std::move(patterns)))) {
      return signalPassFailure();
    }

    // Clean up by removing temporary attributes.
    f.walk([](Operation *op) { removeTransformationAttr(op); });
  }
};

}  // namespace

std::unique_ptr<OperationPass<func::FuncOp>> createTilingCwisePass() {
  return std::make_unique<TilingCwisePass>();
}

std::unique_ptr<OperationPass<func::FuncOp>> createTilingCwisePass(
    bool distribute, ArrayRef<int64_t> tileSizes, StringRef distributionLabel) {
  return std::make_unique<TilingCwisePass>(distribute, tileSizes,
                                           distributionLabel);
}

}  // namespace gml_st
}  // namespace mlir

redpajama_set_name: RedPajamaGithub


text:
/*****************************************************************************
  BlockedIntervals.h

  (c) 2009 - Aaron Quinlan
  Hall Laboratory
  Department of Biochemistry and Molecular Genetics
  University of Virginia
  aaronquinlan@gmail.com

  Licensed under the GNU General Public License 2.0 license.
******************************************************************************/
#include "BlockedIntervals.h"

void GetBamBlocks(const BamAlignment &bam,
                  const string &chrom,
                  bedVector &bedBlocks,
                  bool breakOnDeletionOps,
                  bool breakOnSkipOps)
{
    vector<int> starts;
    vector<int> lengths;
    starts.push_back(0);

    string strand;
    bam.IsReverseStrand() ? strand = "-" : strand = "+";
    CHRPOS currPosition = bam.Position;
    int blockLength  = 0;

    //  Rip through the CIGAR ops and figure out if there is more
    //  than one block for this alignment
    vector<CigarOp>::const_iterator cigItr = bam.CigarData.begin();
    vector<CigarOp>::const_iterator cigEnd = bam.CigarData.end();
    for (; cigItr != cigEnd; ++cigItr) {
        switch (cigItr->Type) {
            case ('M') :case ('X'): case ('='):
                blockLength += cigItr->Length;
            case ('I') : break;
            case ('S') : break;
            case ('D') :
                if (!breakOnDeletionOps)
                    blockLength += cigItr->Length;
                else {
                    bedBlocks.push_back( BED(chrom, currPosition, currPosition + blockLength,
                                          bam.Name, ToString(bam.MapQuality), strand) );
                    currPosition += cigItr->Length + blockLength;
                    blockLength = 0;
                }
            case ('P') : break;
            case ('N') :
                if (!breakOnSkipOps)
                    blockLength += cigItr->Length;
                else {
                    bedBlocks.push_back( BED(chrom, currPosition, currPosition + blockLength,
                                          bam.Name, ToString(bam.MapQuality), strand) );
                    currPosition += cigItr->Length + blockLength;
                    blockLength = 0;
                }
            case ('H') : break;                             // for 'H' - do nothing, move to next op
            default    :
                fprintf(stderr,"ERROR: Invalid Cigar op type \'%c\'.\n",cigItr->Type);   // shouldn't get here
                exit(1);
        }
    }
    bedBlocks.push_back( BED(chrom, currPosition, currPosition + blockLength,
                          bam.Name, ToString(bam.MapQuality), strand) );
}

void GetBedBlocks(const BED &bed, bedVector &bedBlocks) {

    // nothing to do if it is not a BED12 intervals
    if (bed.fields.size() != 12) {
        bedBlocks.push_back(bed);
        return;
    }

    int blockCount = atoi(bed.fields[9].c_str());
    if ( blockCount <= 0 ) {
        cerr << "Input error: found interval having <= 0 blocks." << endl;
        exit(1);
    }
    else if ( blockCount == 1 ) {
        //take a short-cut for single blocks
        bedBlocks.push_back(bed);
    }
    else {
        // get the comma-delimited strings for the BED12 block starts and block ends.
        string blockSizes(bed.fields[10]);
        string blockStarts(bed.fields[11]);

        vector<int> sizes;
        vector<int> starts;
        Tokenize(blockSizes, sizes, ',');
        Tokenize(blockStarts, starts, ',');

        if ( sizes.size() != (size_t) blockCount || starts.size() != (size_t) blockCount ) {
            cerr << "Input error: found interval with block-counts not matching starts/sizes on line." << endl;
            exit(1);
        }

        // add each BED block to the bedBlocks vector
        for (UINT i = 0; i < (UINT) blockCount; ++i) {
            CHRPOS blockStart = bed.start + starts[i];
            CHRPOS blockEnd   = bed.start + starts[i] + sizes[i];
            BED currBedBlock(bed.chrom, blockStart, blockEnd,
                             bed.name, bed.score, bed.strand, bed.fields, bed.other_idxs);
            bedBlocks.push_back(currBedBlock);
        }
    }
}

int GetTotalBlockLength(const bedVector &bedBlocks) {
    int total_size = 0;
    bedVector::const_iterator blockItr = bedBlocks.begin();
    bedVector::const_iterator blockEnd = bedBlocks.end();
    for (; blockItr != blockEnd; ++blockItr) {
        total_size += blockItr->end - blockItr->start;
    }
    return total_size;
}


text:
#include <arpa/inet.h>
#include <chrono>
#include <fcntl.h>
#include <iomanip>
#include <netinet/in.h>
#include <openssl/ssl.h>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unordered_map>

#include <tscore/ink_inet.h>

#include "session_data.h"
#include "global_variables.h"
#include "transaction_data.h"

namespace
{
/** The final string used to close a JSON session. */
char const constexpr *const json_closing = "]}]}";

/**
 * A mapping from IP_PROTO_TAG to the string describing the JSON protocol node.
 */
std::unordered_map<std::string_view, std::string> tag_to_node = {
  {IP_PROTO_TAG_IPV4, R"("name":"ip","version":"4")"},
  {IP_PROTO_TAG_IPV6, R"("name":"ip","version":"6")"},

  {IP_PROTO_TAG_TCP, R"("name":"tcp")"},
  {IP_PROTO_TAG_UDP, R"("name":"udp")"},

  {IP_PROTO_TAG_QUIC, R"("name:":"quic")"},

  {IP_PROTO_TAG_TLS_1_0, R"("name":"tls","version":"1.0")"},
  {IP_PROTO_TAG_TLS_1_1, R"("name":"tls","version":"1.1")"},
  {IP_PROTO_TAG_TLS_1_2, R"("name":"tls","version":"1.2")"},
  {IP_PROTO_TAG_TLS_1_3, R"("name":"tls","version":"1.3")"},

  {IP_PROTO_TAG_HTTP_0_9, R"("name":"http","version":"0.9")"},
  {IP_PROTO_TAG_HTTP_1_0, R"("name":"http","version":"1.0")"},
  {IP_PROTO_TAG_HTTP_1_1, R"("name":"http","version":"1.1")"},
  {IP_PROTO_TAG_HTTP_2_0, R"("name":"http","version":"2")"},

  {IP_PROTO_TAG_HTTP_QUIC, R"("name":"http","version":"0.9")"},
  {IP_PROTO_TAG_HTTP_3, R"("name":"http","version":"3")"},
};

std::unordered_map<std::string_view, std::string> http_tag_to_version = {
  {IP_PROTO_TAG_HTTP_0_9, "0.9"}, {IP_PROTO_TAG_HTTP_1_0, "1.0"},  {IP_PROTO_TAG_HTTP_1_1, "1.1"},
  {IP_PROTO_TAG_HTTP_2_0, "2"},   {IP_PROTO_TAG_HTTP_QUIC, "0.9"}, {IP_PROTO_TAG_HTTP_3, "3"},
};

/** Create a TLS characteristics node.
 *
 * This function encapsulates the logic common between the client-side and
 * server-side logic for populating a "tls" node.
 *
 * @param[in] vconn The virtual connection for the session.
 *
 * @return The node describing the TLS properties of this session.
 */
std::string
get_tls_description_helper(TSVConn vconn)
{
  if (vconn == nullptr) {
    return "";
  }
  SSL *ssl_obj = reinterpret_cast<SSL *>(TSVConnSslConnectionGet(vconn));
  if (ssl_obj == nullptr) {
    return "";
  }
  std::ostringstream tls_description;
  tls_description << R"("name":"tls",)";
  char const *version_ptr = SSL_get_version(ssl_obj);
  if (version_ptr != nullptr) {
    std::string_view version{version_ptr};
    if (!version.empty()) {
      tls_description << R"("version":")" << version << R"(",)";
    }
  }
  char const *sni_ptr = SSL_get_servername(ssl_obj, TLSEXT_NAMETYPE_host_name);
  if (sni_ptr != nullptr) {
    std::string_view sni{sni_ptr};
    if (!sni.empty()) {
      tls_description << R"("sni":")" << sni << R"(",)";
    }
  }

  int verify_mode = SSL_get_verify_mode(ssl_obj);
  tls_description << R"("proxy-verify-mode":)" << std::to_string(verify_mode) << ",";
  bool provided_cert = TSVConnProvidedSslCert(vconn);
  tls_description << R"("proxy-provided-cert":)" << (provided_cert ? "true" : "false");
  return tls_description.str();
}

/** Create a client-side TLS characteristics node.
 *
 * @param[in] ssnp The pointer for this session.
 *
 * @return The node describing the TLS properties of this session.
 */
std::string
get_client_tls_description(TSHttpSsn ssnp)
{
  TSVConn client_ssn_vc = TSHttpSsnClientVConnGet(ssnp);
  return get_tls_description_helper(client_ssn_vc);
}

/** Create a server-side TLS characteristics node.
 *
 * @param[in] ssnp The pointer for this session.
 *
 * @return The node describing the TLS properties of this session.
 */
std::string
get_server_tls_description(TSHttpTxn txnp)
{
  TSVConn server_ssn_vc = TSHttpTxnServerVConnGet(txnp);
  return get_tls_description_helper(server_ssn_vc);
}
} // namespace

namespace traffic_dump
{
// Static member initialization.
int SessionData::session_arg_index                 = -1;
std::atomic<int64_t> SessionData::sample_pool_size = default_sample_pool_size;
std::atomic<int64_t> SessionData::max_disk_usage   = default_max_disk_usage;
std::atomic<int64_t> SessionData::disk_usage       = 0;
ts::file::path SessionData::log_directory{default_log_directory};
uint64_t SessionData::session_counter = 0;
std::string SessionData::sni_filter;
std::optional<IpAddr> SessionData::client_ip_filter = std::nullopt;

int
SessionData::get_session_arg_index()
{
  return session_arg_index;
}

void
SessionData::set_sample_pool_size(int64_t new_sample_size)
{
  sample_pool_size = new_sample_size;
}

void
SessionData::reset_disk_usage()
{
  disk_usage = 0;
}

void
SessionData::set_max_disk_usage(int64_t new_max_disk_usage)
{
  max_disk_usage = new_max_disk_usage;
}

bool
SessionData::init(std::string_view log_directory, int64_t max_disk_usage, int64_t sample_size, std::string_view ip_filter)
{
  SessionData::log_directory    = log_directory;
  SessionData::max_disk_usage   = max_disk_usage;
  SessionData::sample_pool_size = sample_size;

  if (!ip_filter.empty()) {
    client_ip_filter.emplace();
    if (client_ip_filter->load(ip_filter)) {
      TSDebug(debug_tag, "Problems parsing IP filter address argument: %.*s", static_cast<int>(ip_filter.size()), ip_filter.data());
      TSError("[%s] Problems parsing IP filter address argument: %.*s", debug_tag, static_cast<int>(ip_filter.size()),
              ip_filter.data());
      client_ip_filter = std::nullopt;
      return false;
    } else {
      TSDebug(debug_tag, "Filtering to only dump connections with ip: %.*s", static_cast<int>(ip_filter.size()), ip_filter.data());
    }
  }

  if (TS_SUCCESS != TSUserArgIndexReserve(TS_USER_ARGS_SSN, debug_tag, "Track log related data", &session_arg_index)) {
    TSError("[%s] Unable to initialize plugin (disabled). Failed to reserve ssn arg.", traffic_dump::debug_tag);
    return false;
  }

  TSCont ssncont = TSContCreate(global_session_handler, nullptr);
  TSHttpHookAdd(TS_HTTP_SSN_START_HOOK, ssncont);
  TSHttpHookAdd(TS_HTTP_SSN_CLOSE_HOOK, ssncont);

  TSDebug(debug_tag, "Initialized with log directory: %s", SessionData::log_directory.c_str());
  TSDebug(debug_tag, "Initialized with sample pool size %" PRId64 " bytes and disk limit %" PRId64 " bytes", sample_size,
          max_disk_usage);
  return true;
}

bool
SessionData::init(std::string_view log_directory, int64_t max_disk_usage, int64_t sample_size, std::string_view ip_filter,
                  std::string_view sni_filter)
{
  if (!init(log_directory, max_disk_usage, sample_size, ip_filter)) {
    return false;
  }
  SessionData::sni_filter = sni_filter;
  TSDebug(debug_tag, "Filtering to only dump connections with SNI: %s", SessionData::sni_filter.c_str());
  return true;
}

std::string
SessionData::get_protocol_stack_helper(const get_protocol_stack_f &get_protocol_stack, const get_tls_description_f &get_tls_node,
                                       const handle_http_version_f &handle_http_version)
{
  std::ostringstream protocol_description;
  protocol_description << R"("protocol":[)";
  char const *protocol[10];
  int count = -1;
  TSAssert(TS_SUCCESS == get_protocol_stack(10, protocol, &count));
  bool is_first_printed_protocol = true;
  for (int i = 0; i < count; ++i) {
    std::string_view protocol_string(protocol[i]);
    if (!is_first_printed_protocol) {
      protocol_description << ",";
    }
    is_first_printed_protocol = false;
    if (protocol_string.find("tls") != std::string::npos) {
      protocol_description << '{' << get_tls_node() << '}';
    } else {
      auto search = tag_to_node.find(std::string(protocol_string));
      if (search == tag_to_node.end()) {
        // If the tag from get_protocol_stack is not in our list, then our
        // tag_to_node has not been updated with the new tag. Update tag_to_node.
        TSError("[%s] Missing tag node description: '%.*s'", traffic_dump::debug_tag, static_cast<int>(protocol_string.length()),
                protocol_string.data());
        protocol_description << R"({"name":")" << protocol_string << R"("})";
      } else {
        protocol_description << '{' << search->second << '}';
      }

      // See whether an HTTP version is provided. If so, record it.
      auto const it = http_tag_to_version.find(std::string(protocol_string));
      if (it != http_tag_to_version.end()) {
        handle_http_version(it->second);
      }
    }
  }
  protocol_description << "]"; // Close the "protocol" sequence.
  return protocol_description.str();
}

std::string
SessionData::get_client_protocol_description(TSHttpSsn client_ssnp)
{
  return get_protocol_stack_helper(
    [&client_ssnp](int n, const char **result, int *actual) {
      return TSHttpSsnClientProtocolStackGet(client_ssnp, n, result, actual);
    },
    [&client_ssnp]() { return get_client_tls_description(client_ssnp); },
    [this](std::string_view http_version) { this->http_version_in_client_stack = http_version; });
}

std::string
SessionData::get_server_protocol_description(TSHttpTxn server_txnp)
{
  return get_protocol_stack_helper(
    [&server_txnp](int n, const char **result, int *actual) {
      return TSHttpTxnServerProtocolStackGet(server_txnp, n, result, actual);
    },
    [&server_txnp]() { return get_server_tls_description(server_txnp); }, [](std::string_view http_version) {});
}

SessionData::SessionData()
{
  aio_cont = TSContCreate(session_aio_handler, TSMutexCreate());
  txn_cont = TSContCreate(TransactionData::global_transaction_handler, nullptr);
}

SessionData::~SessionData()
{
  if (aio_cont) {
    TSContDestroy(aio_cont);
  }
  if (txn_cont) {
    TSContDestroy(txn_cont);
  }
}

/*
 * Note this assumes that the caller holds the disk_io_mutex lock. This is a
 * private member function. The two publicly accessible functions hold the
 * lock before calling this.
 */
int
SessionData::write_to_disk_no_lock(std::string_view content)
{
  char *pBuf = nullptr;
  // Allocate a buffer for aio writing
  if ((pBuf = static_cast<char *>(TSmalloc(sizeof(char) * content.size())))) {
    memcpy(pBuf, content.data(), content.size());
    if (TS_SUCCESS == TSAIOWrite(log_fd, write_offset, pBuf, content.size(), aio_cont)) {
      // Update offset within file and aio events count
      write_offset += content.size();
      aio_count += 1;

      return TS_SUCCESS;
    }
    TSfree(pBuf);
  }
  return TS_ERROR;
}

int
SessionData::write_to_disk(std::string_view content)
{
  const std::lock_guard<std::recursive_mutex> _(disk_io_mutex);
  const int result = write_to_disk_no_lock(content);
  return result;
}

int
SessionData::write_transaction_to_disk(std::string_view content)
{
  const std::lock_guard<std::recursive_mutex> _(disk_io_mutex);

  int result = TS_SUCCESS;
  if (has_written_first_transaction) {
    // Prepend a comma.
    std::string with_comma;
    with_comma.reserve(content.size() + 1);
    with_comma.insert(0, ",");
    with_comma.insert(1, content);
    result = write_to_disk_no_lock(with_comma);
  } else {
    result                        = write_to_disk_no_lock(content);
    has_written_first_transaction = true;
  }
  return result;
}

std::string
SessionData::get_http_version_in_client_stack() const
{
  return http_version_in_client_stack;
}

// static
bool
SessionData::is_filtered_out(const sockaddr *session_client_ip)
{
  if (!client_ip_filter) {
    // The user did not configure an IP by which to filter.
    return false;
  }
  if (session_client_ip == nullptr) {
    TSDebug(debug_tag, "Found no client IP address for session. Abort.");
    return true;
  }
  if (session_client_ip->sa_family != AF_INET && session_client_ip->sa_family != AF_INET6) {
    TSDebug(debug_tag, "IP family is not v4 nor v6. Abort.");
    return true;
  }

  IpAddr session_address(*session_client_ip);
  return session_address != *client_ip_filter;
}

// static
int
SessionData::session_aio_handler(TSCont contp, TSEvent event, void *edata)
{
  switch (event) {
  case TS_EVENT_AIO_DONE: {
    TSAIOCallback cb     = static_cast<TSAIOCallback>(edata);
    SessionData *ssnData = static_cast<SessionData *>(TSContDataGet(contp));
    if (!ssnData) {
      TSDebug(debug_tag, "session_aio_handler(): No valid ssnData. Abort.");
      return TS_ERROR;
    }
    char *buf = TSAIOBufGet(cb);
    const std::lock_guard<std::recursive_mutex> _(ssnData->disk_io_mutex);

    // Free the allocated buffer and update aio_count
    if (buf) {
      TSfree(buf);
      if (--ssnData->aio_count == 0 && ssnData->ssn_closed) {
        // check for ssn close, if closed, do clean up
        TSContDataSet(contp, nullptr);
        close(ssnData->log_fd);
        std::error_code ec;
        ts::file::file_status st = ts::file::status(ssnData->log_name, ec);
        if (!ec) {
          disk_usage += ts::file::file_size(st);
          TSDebug(debug_tag, "Finish a session with log file of %" PRIuMAX " bytes", ts::file::file_size(st));
        }
        delete ssnData;
        return TS_SUCCESS;
      }
    }
    return TS_SUCCESS;
  }
  default:
    TSDebug(debug_tag, "session_aio_handler(): unhandled events %d", event);
    return TS_ERROR;
  }
  return TS_SUCCESS;
}

// static
int
SessionData::global_session_handler(TSCont contp, TSEvent event, void *edata)
{
  TSHttpSsn ssnp = static_cast<TSHttpSsn>(edata);

  switch (event) {
  case TS_EVENT_HTTP_SSN_START: {
    // Grab session id for logging against a global value rather than the local
    // session_counter.
    int64_t id = TSHttpSsnIdGet(ssnp);

    // If the user has asked for SNI filtering, filter on that first because
    // any sampling will apply just to that subset of connections that match
    // that SNI.
    if (!sni_filter.empty()) {
      TSVConn ssn_vc           = TSHttpSsnClientVConnGet(ssnp);
      TSSslConnection ssl_conn = TSVConnSslConnectionGet(ssn_vc);
      SSL *ssl_obj             = reinterpret_cast<SSL *>(ssl_conn);
      if (ssl_obj == nullptr) {
        TSDebug(debug_tag, "global_session_handler(): Ignore non-HTTPS session %" PRId64 "...", id);
        break;
      }
      char const *sni_ptr = SSL_get_servername(ssl_obj, TLSEXT_NAMETYPE_host_name);
      if (sni_ptr == nullptr) {
        TSDebug(debug_tag, "global_session_handler(): Ignore HTTPS session with non-existent SNI.");
        break;
      } else {
        const std::string_view sni{sni_ptr};
        if (sni != sni_filter) {
          TSDebug(debug_tag, "global_session_handler(): Ignore HTTPS session with non-filtered SNI: %s", sni_ptr);
          break;
        }
      }
    }
    const auto this_session_count = session_counter++;
    if (this_session_count % sample_pool_size != 0) {
      TSDebug(debug_tag, "Ignore session %" PRId64 " per the random sampling mechanism", id);
      break;
    } else if (disk_usage >= max_disk_usage) {
      TSDebug(debug_tag, "Ignore session %" PRId64 " due to disk usage %" PRId64 " bytes", id, disk_usage.load());
      break;
    } else {
      const sockaddr *client_ip = TSHttpSsnClientAddrGet(ssnp);
      if (SessionData::is_filtered_out(client_ip)) {
        TSDebug(debug_tag, "Ignore session %" PRId64 " per the client's IP filter", id);
        break;
      }
    }
    // Beginning of a new session
    /// Get epoch time
    auto start = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch());

    // Create new per session data
    SessionData *ssnData = new SessionData;
    TSUserArgSet(ssnp, session_arg_index, ssnData);

    TSContDataSet(ssnData->aio_cont, ssnData);

    // "protocol":
    // This is the protocol stack for the client side of the session.
    std::string protocol_description = ssnData->get_client_protocol_description(ssnp);
    std::string beginning = R"({"meta":{"version":"1.0"},"sessions":[{)" + protocol_description + R"(,"connection-time":)" +
                            std::to_string(start.count()) + R"(,"transactions":[)";

    // Use the session count's hex string as the filename.
    std::stringstream stream;
    stream << std::setw(16) << std::setfill('0') << std::hex << this_session_count;
    std::string session_hex_name = stream.str();

    // Use client ip as sub directory name
    char client_str[INET6_ADDRSTRLEN];
    sockaddr const *client_ip = TSHttpSsnClientAddrGet(ssnp);
    if (AF_INET == client_ip->sa_family) {
      inet_ntop(AF_INET, &(reinterpret_cast<sockaddr_in const *>(client_ip)->sin_addr), client_str, INET_ADDRSTRLEN);
    } else if (AF_INET6 == client_ip->sa_family) {
      inet_ntop(AF_INET6, &(reinterpret_cast<sockaddr_in6 const *>(client_ip)->sin6_addr), client_str, INET6_ADDRSTRLEN);
    } else {
      TSDebug(debug_tag, "global_session_handler(): Unknown address family.");
      snprintf(client_str, INET6_ADDRSTRLEN, "unknown");
    }

    // Initialize AIO file
    const std::lock_guard<std::recursive_mutex> _(ssnData->disk_io_mutex);
    if (ssnData->log_fd < 0) {
      ts::file::path log_p = log_directory / ts::file::path(std::string(client_str, 3));
      ts::file::path log_f = log_p / ts::file::path(session_hex_name);

      // Create subdir if not existing
      std::error_code ec;
      ts::file::status(log_p, ec);
      if (ec && mkdir(log_p.c_str(), 0755) == -1) {
        TSDebug(debug_tag, "global_session_handler(): Failed to create dir %s", log_p.c_str());
        TSError("[%s] Failed to create dir %s", debug_tag, log_p.c_str());
      }

      // Try to open log files for AIO
      ssnData->log_fd = open(log_f.c_str(), O_RDWR | O_CREAT, S_IRWXU);
      if (ssnData->log_fd < 0) {
        TSDebug(debug_tag, "global_session_handler(): Failed to open log files %s. Abort.", log_f.c_str());
        TSHttpSsnReenable(ssnp, TS_EVENT_HTTP_CONTINUE);
        return TS_EVENT_HTTP_CONTINUE;
      }
      ssnData->log_name = log_f;
      // Write log file beginning to disk
      ssnData->write_to_disk(beginning);
    }

    TSHttpSsnHookAdd(ssnp, TS_HTTP_TXN_START_HOOK, ssnData->txn_cont);
    TSHttpSsnHookAdd(ssnp, TS_HTTP_TXN_CLOSE_HOOK, ssnData->txn_cont);
    break;
  }
  case TS_EVENT_HTTP_SSN_CLOSE: {
    // Write session and close the log file.
    int64_t id = TSHttpSsnIdGet(ssnp);
    TSDebug(debug_tag, "global_session_handler(): Closing session %" PRId64 "...", id);
    // Retrieve SessionData
    SessionData *ssnData = static_cast<SessionData *>(TSUserArgGet(ssnp, session_arg_index));
    // If no valid ssnData, continue transaction as if nothing happened
    if (!ssnData) {
      TSDebug(debug_tag, "global_session_handler(): [TS_EVENT_HTTP_SSN_CLOSE] No ssnData found. Abort.");
      TSHttpSsnReenable(ssnp, TS_EVENT_HTTP_CONTINUE);
      return TS_SUCCESS;
    }
    ssnData->write_to_disk(json_closing);
    {
      const std::lock_guard<std::recursive_mutex> _(ssnData->disk_io_mutex);
      ssnData->ssn_closed = true;
    }

    break;
  }
  default:
    break;
  }
  TSHttpSsnReenable(ssnp, TS_EVENT_HTTP_CONTINUE);
  return TS_SUCCESS;
}

} // namespace traffic_dump


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;

namespace AdventureWorks.EntityClasses.HumanResources
{
	/// Class which represents the entity 'HumanResources.Shift'
	public partial class Shift
	{
		#region Class Member Declarations
		private ISet<EmployeeDepartmentHistory> _employeeDepartmentHistories;
		private System.DateTime _endTime;
		private System.DateTime _modifiedDate;
		private System.String _name;
		private System.Byte _shiftId;
		private System.DateTime _startTime;
		#endregion

		/// Initializes a new instance of the <see cref="Shift"/> class.
		public Shift() : base()
		{
			_employeeDepartmentHistories = new HashSet<EmployeeDepartmentHistory>();
			_shiftId = default(System.Byte);
			OnCreated();
		}

		/// Method called from the constructor
		partial void OnCreated();

		/// Returns a hash code for this instance.
		/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. </returns>
		public override int GetHashCode()
		{
			int toReturn = base.GetHashCode();
			toReturn ^= this.ShiftId.GetHashCode();
			return toReturn;
		}

		/// Determines whether the specified object is equal to this instance.
		/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
		/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
		public override bool Equals(object obj)
		{
			if(obj == null)
			{
				return false;
			}
			Shift toCompareWith = obj as Shift;
			return toCompareWith == null ? false : ((this.ShiftId == toCompareWith.ShiftId));
		}

		#region Class Property Declarations
		/// Gets or sets the EndTime field.
		public virtual System.DateTime EndTime
		{
			get { return _endTime; }
			set { _endTime = value; }
		}

		/// Gets or sets the ModifiedDate field.
		public virtual System.DateTime ModifiedDate
		{
			get { return _modifiedDate; }
			set { _modifiedDate = value; }
		}

		/// Gets or sets the Name field.
		public virtual System.String Name
		{
			get { return _name; }
			set { _name = value; }
		}

		/// Gets the ShiftId field.
		public virtual System.Byte ShiftId
		{
			get { return _shiftId; }
		}

		/// Gets or sets the StartTime field.
		public virtual System.DateTime StartTime
		{
			get { return _startTime; }
			set { _startTime = value; }
		}

		/// Represents the navigator which is mapped onto the association 'HumanResources.EmployeeDepartmentHistory.Shift - HumanResources.Shift.EmployeeDepartmentHistories (m:1)'
		public virtual ISet<EmployeeDepartmentHistory> EmployeeDepartmentHistories
		{
			get { return _employeeDepartmentHistories; }
			set { _employeeDepartmentHistories = value; }
		}

		#endregion
	}
}


text:
export default function () {
  var duration = 500;
  this.transition(
    this.hasClass('geo-info'),
    this.toValue(true),
    this.use('toDown', {duration: 300})
  );
  this.transition(
    this.hasClass('wizard'),
    this.toValue(true),
    this.use('toRight', {duration: 200})
  );
  this.transition(
    this.hasClass('wizard'),
    this.toValue(true),
    this.use('toRight', {duration: 200})
  );
  this.transition(
    this.hasClass('slideUp'),
    this.toValue(true),
    this.use('toUp', {duration: 200}),
    this.reverse('toDown', {duration: 200})
  );

  //dashboard
  this.transition(
    this.fromRoute('index'),
    this.toRoute('s.mktg.index'),
    this.use('toUp'),
    this.reverse('toDown')
  );
  //mktg
  this.transition(
    this.fromRoute('s.mktg.index'),
    this.toRoute('s.mktg.content'),
    this.use('toRight'),
    this.reverse('toLeft')
  );
  this.transition(
    this.fromRoute('s.mktg.content'),
    this.toRoute('s.mktg.seo'),
    this.use('toRight'),
    this.reverse('toLeft')
  );
  this.transition(
    this.fromRoute('s.mktg.seo'),
    this.toRoute('s.mktg.branding'),
    this.use('toRight'),
    this.reverse('toLeft')
  );
  this.transition(
    this.fromRoute('s.mktg.branding'),
    this.toRoute('s.mktg.analytics'),
    this.use('toRight'),
    this.reverse('toLeft')
  );
  //store
  this.transition(
    this.fromRoute('s.store'),
    this.toRoute('s.vendors'),
    this.use('toUp'),
    this.reverse('toDown')
  );
  //crm
  this.transition(
    this.fromRoute('s.vendors'),
    this.toRoute('s.posts.index'),
    this.use('toUp'),
    this.reverse('toDown')
  );
  //posts
  this.transition(
    this.fromRoute('s.posts'),
    this.toRoute('s.todos'),
    this.use('toUp'),
    this.reverse('toDown')
  );
  this.transition(
    this.fromRoute('s.posts.index'),
    this.toRoute('s.posts.post'),
    this.use('toLeft'),
    this.reverse('toRight')
  );
  this.transition(
    this.fromRoute('s.posts.post.index'),
    this.toRoute('s.posts.post.edit'),
    this.use('toLeft'),
    this.reverse('toRight')
  );

  //todos
  this.transition(
    this.fromRoute('s.todos'),
    this.toRoute('s.page-manager.index'),
    this.use('toUp'),
    this.reverse('toDown')
  );

  //page manager
  this.transition(
    this.fromRoute('s.page-manager.index'),
    this.toRoute('s.page-manager.new'),
    this.use('toLeft'),
    this.reverse('toRight')
  );
  // this.transition(
  //   this.fromRoute('index'),
  //   this.toRoute('gallery'),
  //   this.use('explode', {
  //     matchBy: 'data-logo-id',
  //     use: ['flyTo', { duration } ]
  //   }, {
  //     use: ['toLeft', { duration } ]
  //   }),
  //   this.reverse('explode', {
  //     matchBy: 'data-logo-id',
  //     use: ['flyTo', { duration } ]
  //   }, {
  //     use: ['toRight', { duration } ]
  //   })
  // );
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("eWAY.Rapid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("eWAY")]
[assembly: AssemblyProduct("eWAY.Rapid")]
[assembly: AssemblyCopyright("Copyright © Web Active 2015-2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("15a9ea7e-3cdf-42c7-ab53-4ca600e261f6")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.6.3.0")]
[assembly: AssemblyFileVersion("1.6.3.0")]

[assembly: InternalsVisibleTo("eWAY.Rapid.Tests,PublicKey=00240000048000009400000006020000002400005253413100040000010001001fa88da23161933c177ff28430a896e9dc1d184b788db49eed5f7a6c101ed7cd4820b80a0f22949cc0077c5fa00d7c575a678e145d35f391caf1ec747a00602fc86df22717d7c0ee5fe4607f0c64ac2b99aa6d81198d7d308db51f457576d541e2318d58f3b54859a6ee60154193472f9d8a1bfdae9c16f26aa755d658d8f0f5")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]


text:
using System;
using System.Xml.Serialization;

namespace EZOper.NetSiteUtilities.AopApi
{
    /// <summary>
    /// AlipayCommerceEducateStudentinfoShareResponse.
    /// </summary>
    public class AlipayCommerceEducateStudentinfoShareResponse : AopResponse
    {
        /// <summary>
        /// 学生信息
        /// </summary>
        [XmlElement("student_info_share_result")]
        public EduStudentInfoShareResult StudentInfoShareResult { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/CardContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title"
        style="@style/CardTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawablePadding="4dp"
        android:ellipsize="end"
        android:lines="1" />

    <TextView
        android:id="@+id/text"
        style="@style/CardText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout><!-- From: file:/D:/AndroidStudioProjects/GoogleCodePublished_GestureProject/wear/build/intermediates/exploded-aar/com.google.android.support/wearable/1.0.0/res/layout/watch_card_content.xml -->


text:
<?php
// Text
$_['text_upload']    = 'Seu arquivo foi enviado.';

// Error
$_['error_filename'] = 'O nome do arquivo deve ter entre 3 e 64 caracteres.';
$_['error_filetype'] = 'O tipo de arquivo não é válido.';
$_['error_upload']   = 'O arquivo para upload é obrigatório.';


text:
class DelayedJob::Export::Customer < Struct.new(:store, :user, :customer_list)
  def perform

    #TO ADD .encode('iso-8859-1', undef: :replace, replace: ''), :type => 'text/csv; charset=iso-8859-1; header=present'

    filename = "Customer Export - #{Time.now.strftime("%d/%m/%Y %I:%M%p")}.csv"
    customers = CSV.generate do |csv|
      csv << Customer.field_names.map(&:last)

      customer_list.each do |c|
        clm = c.certification_level_memberships.first
        csv << [c.customer_experience_level.try(:name),
                c.given_name,
                c.family_name,
                c.default_discount_level,
                c.source,
                c.telephone,
                c.mobile_phone,
                c.email,
                c.fins,
                c.bcd,
                c.wetsuit,
                c.number_of_logged_dives,
                c.born_on,
                c.last_dive_on,
                c.hotel_name,
                c.room_number,
                c.address.first,
                c.address.second,
                c.address.city,
                c.address.state,
                c.address.country_name,
                c.address.post_code,
                c.gender,
                c.tags.join(";"),
                clm.try(:certification_agency_export),
                clm.try(:certification_level_export),
                clm.try(:membership_number_export),
                clm.try(:certification_date_export),
                clm.try(:primary?).to_s,
                c.emergency_contact_details,
                c.fins_own?.to_s,
                c.bcd_own?.to_s,
                c.wetsuit_own?.to_s,
                c.mask_own?.to_s,
                c.regulator_own?.to_s,
                c.weight, c.custom_fields_for_export,
                c.notes_for_export,
                c.send_event_related_emails.to_s,
                c.tax_id,
                c.zero_tax_rate
               ]
      end
    end

    ExportMailer.success(customers, filename, I18n.t('activerecord.models.customer.one'), user).deliver
  end
end


text:
hmac_cli
========

Simple CLI for encrypting data with a private key, using HMAC

::

    $ hmac --help
    Usage: hmac [OPTIONS] INPUT_FILE

      Encrypt data in INPUT_FILE using HMAC

      with provided secret cryptographic key

    Options:
      --key TEXT                      encryption key. Will prompt for if not
                                      provided.
      --algorithm [md5|sha1|sha224|sha256|sha384|sha512]
                                      algorithm to use
      --help                          Show this message and exit.

    $ hmac --key foo README.rst
    515902266c1a02e60452d152855aa3b46ed5b006

    $ echo "Hello" | hmac --key foo -
    aabbe57c6a0ba953cd907071004a1db16fe78891

    $ hmac -
    Key: ******
    Repeat for confirmation: ******
    Here is some text
    ^D
    c7ab7eed09fff2d0fcf258dfde8222d264013c4f


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

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

/**
 * A protocol handler that uses native rsync client to do copy.
 * You need to define the system property
 * -Djava.protocol.handler.pkgs=org.archive.net to add this handler
 * to the java.net.URL set.  Assumes rsync is in path.  Define
 * system property
 * -Dorg.archive.net.rsync.RsyncUrlConnection.path=PATH_TO_RSYNC to
 * pass path to rsync. Downloads to java.io.tmpdir.
 * @author stack
 */
public class Handler extends URLStreamHandler {
    protected URLConnection openConnection(URL u) {
        return new RsyncURLConnection(u);
    }

    /**
     * Main dumps rsync file to STDOUT.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args)
    throws IOException {
        if (args.length != 1) {
            System.out.println("Usage: java java " +
                "-Djava.protocol.handler.pkgs=org.archive.net " +
                "org.archive.net.rsync.Handler RSYNC_URL");
            System.exit(1);
        }
        URL u = new URL(args[0]);
        URLConnection connect = u.openConnection();
        // Write download to stdout.
        final int bufferlength = 4096;
        byte [] buffer = new byte [bufferlength];
        InputStream is = connect.getInputStream();
        try {
            for (int count = is.read(buffer, 0, bufferlength);
                    (count = is.read(buffer, 0, bufferlength)) != -1;) {
                System.out.write(buffer, 0, count);
            }
            System.out.flush();
        } finally {
            is.close();
        }
    }
}


text:
#include <windows.h>
#include <io.h>

#include "mman.h"

#ifndef FILE_MAP_EXECUTE
#define FILE_MAP_EXECUTE    0x0020
#endif /* FILE_MAP_EXECUTE */

static int __map_mman_error(const DWORD err, const int deferr)
{
	if(err == 0)
	{
		return 0;
	}
	//TODO: implement
	return err;
}

static DWORD __map_mmap_prot_page(const int prot)
{
	DWORD protect = 0;

	if(prot == PROT_NONE)
	{
		return protect;
	}

	if((prot & PROT_EXEC) != 0)
	{
		protect = ((prot & PROT_WRITE) != 0) ? PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ;
	}
	else
	{
		protect = ((prot & PROT_WRITE) != 0) ? PAGE_READWRITE : PAGE_READONLY;
	}

	return protect;
}

static DWORD __map_mmap_prot_file(const int prot)
{
	DWORD desiredAccess = 0;

	if(prot == PROT_NONE)
	{
		return desiredAccess;
	}

	if((prot & PROT_READ) != 0)
	{
		desiredAccess |= FILE_MAP_READ;
	}
	if((prot & PROT_WRITE) != 0)
	{
		desiredAccess |= FILE_MAP_WRITE;
	}
	if((prot & PROT_EXEC) != 0)
	{
		desiredAccess |= FILE_MAP_EXECUTE;
	}

	return desiredAccess;
}

void* mmap(void* addr, size_t len, int prot, int flags, int fildes, address_t off)
{
	HANDLE fm, h;

	void* map = MAP_FAILED;

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4293)
#endif

	const DWORD protect = __map_mmap_prot_page(prot);
	const DWORD desiredAccess = __map_mmap_prot_file(prot);
	const address_t maxSize = off + (address_t) len;

#if defined(_WIN64)
	const DWORD dwFileOffsetLow = (DWORD) (off & 0xFFFFFFFFL);
	const DWORD dwFileOffsetHigh = (DWORD) ((off >> 32) & 0xFFFFFFFFL);
	const DWORD dwMaxSizeLow = (DWORD) (maxSize & 0xFFFFFFFFL);
	const DWORD dwMaxSizeHigh = (DWORD) ((maxSize >> 32) & 0xFFFFFFFFL);
#else
	const DWORD dwFileOffsetLow = (DWORD) off;
	const DWORD dwFileOffsetHigh = (DWORD) 0;
	const DWORD dwMaxSizeLow = (DWORD) maxSize;
	const DWORD dwMaxSizeHigh = (DWORD) 0;
#endif

#ifdef _MSC_VER
#pragma warning(pop)
#endif

	errno = 0;

	if(len == 0
	   /* Unsupported flag combinations */
	   || (flags & MAP_FIXED) != 0
	   /* Usupported protection combinations */
	   || prot == PROT_EXEC)
	{
		errno = EINVAL;
		return MAP_FAILED;
	}

	h = ((flags & MAP_ANONYMOUS) == 0) ? (HANDLE) _get_osfhandle(fildes) : INVALID_HANDLE_VALUE;

	if((flags & MAP_ANONYMOUS) == 0 && h == INVALID_HANDLE_VALUE)
	{
		errno = EBADF;
		return MAP_FAILED;
	}

	fm = CreateFileMapping(h, NULL, protect, dwMaxSizeHigh, dwMaxSizeLow, NULL);

	if(fm == NULL)
	{
		errno = __map_mman_error(GetLastError(), EPERM);
		return MAP_FAILED;
	}

	map = MapViewOfFile(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len);

	CloseHandle(fm);

	if(map == NULL)
	{
		errno = __map_mman_error(GetLastError(), EPERM);
		return MAP_FAILED;
	}

	return map;
}

int munmap(void* addr, size_t len)
{
	//this is why it's failing
	//partial munmaps are not supported in windows...
	if(UnmapViewOfFile(addr))
	{
		return 0;
	}

	errno = __map_mman_error(GetLastError(), EPERM);

	return -1;
}

int _mprotect(void* addr, size_t len, int prot)
{
	DWORD newProtect = __map_mmap_prot_page(prot);
	DWORD oldProtect = 0;

	if(VirtualProtect(addr, len, newProtect, &oldProtect))
	{
		return 0;
	}

	errno = __map_mman_error(GetLastError(), EPERM);

	return -1;
}

int msync(void* addr, size_t len, int flags)
{
	if(FlushViewOfFile(addr, len))
	{
		return 0;
	}

	errno = __map_mman_error(GetLastError(), EPERM);

	return -1;
}

int mlock(const void* addr, size_t len)
{
	if(VirtualLock((LPVOID) addr, len))
	{
		return 0;
	}

	errno = __map_mman_error(GetLastError(), EPERM);

	return -1;
}

int munlock(const void* addr, size_t len)
{
	if(VirtualUnlock((LPVOID) addr, len))
	{
		return 0;
	}

	errno = __map_mman_error(GetLastError(), EPERM);

	return -1;
}


text:
module ParallelRSpec
  class Server
    attr_reader :remaining_example_group_indexes, :reporter

    def initialize(reporter)
      @remaining_example_group_indexes = RSpec.world.filtered_examples.each_with_object({}) do |(example_group, examples), results|
        results[example_group] = examples.size unless example_group.any_context_hooks? || examples.size.zero?
      end
      @reporter = reporter
      @success = true
    end

    def example_started(example, channel_to_client)
      reporter.example_started(example)
    end

    def example_passed(example, channel_to_client)
      reporter.example_passed(example)
    end

    def example_failed(example, channel_to_client)
      reporter.example_failed(example)
    end

    def example_pending(example, channel_to_client)
      reporter.example_pending(example)
    end

    def deprecation(hash, channel_to_client)
      reporter.deprecation(hash)
    end

    def next_example_to_run(channel_to_client)
      if remaining_example_group_indexes.empty?
        channel_to_client.write(nil)
      else
        klass = remaining_example_group_indexes.keys.first
        remaining_example_group_indexes[klass] -= 1
        channel_to_client.write([klass, remaining_example_group_indexes[klass]])
        remaining_example_group_indexes.delete(klass) if remaining_example_group_indexes[klass].zero?
      end
    end

    def result(success, channel_to_client)
      @success &&= success
    end

    def success?
      @success
    end
  end
end