text:
/**
 * @file Star class. Part of the "Age of Space" project.
 * @author github.com/azziliz
 * @author github.com/thyshimrod
 * {@link https://github.com/The-game-craftmen/age-of-space/ Project page}
 * @license MIT
 */

'use strict';
var aos = aos || {};
//debugger;

/**
 * The Star class represents a stellar and planetary sytem. It contains one star and several planets.
 *
 * @class
 */
aos.Star = function () {
    /** @type {string} */
    this.id = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);

    // general data, relative to galaxy
    this.x = 0; // coordinates relative to the galaxy
    this.y = 0;
    this.isNotable = false;
    this.greekLetter = {};
    this.properName = {};
    this.constellation = {};

    // detail data for star (lore)
    this.sizeRatio = 0;
    this.luminosityClass = '?';
    this.spectralClass = '?';
    this.subSpectral = 0;
    this.temperature = 0;
    this.mass = 0;
    this.radius = 0;
    this.bolometricLuminosity = 0;
    this.color = { R: 0, G: 0, B: 0 };
    this.hasFlare = false;

    // technical private stuff, required for kruskal
    this.r = 0;
    this.group = 0;
    this.keep = true;

    //planet details
    /** @type {aos.Planet} */
    this.planets = [];
    this.selectedPlanetIndex = 0;
    this.selectedPlanet = null;

    // ship
    this.hasShip = false;
    this.shipAngle = 0;
    this.ship = null;
};

aos.Star.prototype = {

    generate: function (wantSolar) {
        // we only generate main sequence stars because they represent more than 90% of the galaxy
        // source: https://astronomy.stackexchange.com/questions/13165/what-is-the-frequency-distribution-for-luminosity-classes-in-the-milky-way-galax
        if (this.isNotable) {
            this.sizeRatio = 6.0 * Math.random(); // not squared because we want the highest possible variation, for gameplay reason
            // also blue stars are very unlikely to have planets but we keep them because they're awesome
        } else {
            this.sizeRatio = 7.0 * Math.random() * Math.random(); // squared because low energy stars are supposed to be more common in a real-world galaxy
        }
        let nbPlanets = 1 + Math.floor((10 - this.sizeRatio) * Math.random());
        if (wantSolar) {
            nbPlanets = 8;
            this.hasShip = true;
            this.ship = new aos.Ship();
            this.ship.init();
            ((this.ship.storedResources.filter(function (res) { return res.name === 'Metal' }))[0]).quantity = 30000;
            ((this.ship.storedResources.filter(function (res) { return res.name === 'Bacteria' }))[0]).quantity = 10000;
            ((this.ship.storedResources.filter(function (res) { return res.name === 'Plants' }))[0]).quantity = 10000;
            ((this.ship.storedResources.filter(function (res) { return res.name === 'Animals' }))[0]).quantity = 10000;
            ((this.ship.storedResources.filter(function (res) { return res.name === 'Humans' }))[0]).quantity = 20000;
            ((this.ship.storedResources.filter(function (res) { return res.name === 'Machines' }))[0]).quantity = 10000;
            ((this.ship.storedResources.filter(function (res) { return res.name === 'Viruses' }))[0]).quantity = 10000; // TODO remove me
        }
        for (; nbPlanets > 0 ; nbPlanets--) {
            this.planets.push(new aos.Planet());
        }
        this.planets.forEach(function (planet, idx) {
            planet.generate(wantSolar, idx);
            planet.setupEvents();
        }, this);
        //#region Lore
        this.fillFromRatio(this.sizeRatio);
        //#endregion
        this.selectedPlanetIndex = 0;
        this.selectedPlanet = this.planets[0];
    },

    fillFromRatio: function (classRatio) {
        if (classRatio < 1.0) {
            // source: https://en.wikipedia.org/wiki/Stellar_classification#Modern_classification
            this.luminosityClass = 'V'; // main sequence
            this.spectralClass = 'M';
            this.temperature = 2000.0 + 1700.0 * classRatio; // unit is K
            this.mass = 2.0 + 7.0 * classRatio; // unit is 10^29 kg ; divide by 20 to get mass in M☉
            this.radius = 3.0 + 1.9 * classRatio; // unit is 10^8 m ; divide by 7 to get radius in R☉
            this.bolometricLuminosity = 20.0 + 300.0 * classRatio; // unit is 10^22 W ; divide by 4000 to get luminosity in L☉
            // source for color is black body radiation
            // see : https://en.wikipedia.org/wiki/File:Color_temperature_black_body_radiation_logarithmic_kelvins.svg
            const colorLeft = { R: 0xFF, G: 0x88, B: 0x0F }; // 2000 K
            const colorRight = { R: 0xFF, G: 0xC8, B: 0x90 }; // 3700 K
            this.color = { // lerp --> dirty but close enough
                R: Math.floor(colorLeft.R + classRatio * (colorRight.R - colorLeft.R)),
                G: Math.floor(colorLeft.G + classRatio * (colorRight.G - colorLeft.G)),
                B: Math.floor(colorLeft.B + classRatio * (colorRight.B - colorLeft.B))
            };
            this.subSpectral = Math.floor(10 * (1 - classRatio));
            if (Math.random() < 0.2) {
                this.hasFlare = true;
            }
        } else if (classRatio < 2.0) {
            classRatio -= 1.0;
            this.luminosityClass = 'V';
            this.spectralClass = 'K';
            this.temperature = 3700.0 + 1500.0 * classRatio;
            this.mass = 9.0 + 7.0 * classRatio;
            this.radius = 4.9 + 1.8 * classRatio;
            this.bolometricLuminosity = 320.0 + 2080.0 * classRatio;
            const colorLeft = { R: 0xFF, G: 0xC8, B: 0x90 }; // 3700 K
            const colorRight = { R: 0xFF, G: 0xE7, B: 0xD3 }; // 5200 K
            this.color = {
                R: Math.floor(colorLeft.R + classRatio * (colorRight.R - colorLeft.R)),
                G: Math.floor(colorLeft.G + classRatio * (colorRight.G - colorLeft.G)),
                B: Math.floor(colorLeft.B + classRatio * (colorRight.B - colorLeft.B))
            };
            this.subSpectral = Math.floor(10 * (1 - classRatio));
        } else if (classRatio < 3.0) {
            classRatio -= 2.0;
            this.luminosityClass = 'V';
            this.spectralClass = 'G';
            this.temperature = 5200.0 + 800.0 * classRatio;
            this.mass = 16.0 + 4.8 * classRatio;
            this.radius = 6.7 + 1.3 * classRatio;
            this.bolometricLuminosity = 2400.0 + 3600.0 * classRatio;
            const colorLeft = { R: 0xFF, G: 0xE7, B: 0xD3 }; // 5200 K
            const colorRight = { R: 0xFF, G: 0xF3, B: 0xEF }; // 6000 K
            this.color = {
                R: Math.floor(colorLeft.R + classRatio * (colorRight.R - colorLeft.R)),
                G: Math.floor(colorLeft.G + classRatio * (colorRight.G - colorLeft.G)),
                B: Math.floor(colorLeft.B + classRatio * (colorRight.B - colorLeft.B))
            };
            this.subSpectral = Math.floor(10 * (1 - classRatio));
        } else if (classRatio < 4.0) {
            classRatio -= 3.0;
            this.luminosityClass = 'V';
            this.spectralClass = 'F';
            this.temperature = 6000.0 + 1500.0 * classRatio;
            this.mass = 20.8 + 7.2 * classRatio;
            this.radius = 8.0 + 1.8 * classRatio;
            this.bolometricLuminosity = 6000.0 + 14000.0 * classRatio;
            const colorLeft = { R: 0xFF, G: 0xF3, B: 0xEF }; // 6000 K
            const colorRight = { R: 0xE9, G: 0xEC, B: 0xFF }; // 7500 K
            this.color = {
                R: Math.floor(colorLeft.R + classRatio * (colorRight.R - colorLeft.R)),
                G: Math.floor(colorLeft.G + classRatio * (colorRight.G - colorLeft.G)),
                B: Math.floor(colorLeft.B + classRatio * (colorRight.B - colorLeft.B))
            };
            this.subSpectral = Math.floor(10 * (1 - classRatio));
        } else if (classRatio < 5.0) {
            classRatio -= 4.0;
            this.luminosityClass = 'V';
            this.spectralClass = 'A';
            this.temperature = 7500.0 + 2500.0 * classRatio;
            this.mass = 28.0 + 14.0 * classRatio;
            this.radius = 9.8 + 2.8 * classRatio;
            this.bolometricLuminosity = 20000.0 + 80000.0 * classRatio;
            const colorLeft = { R: 0xE9, G: 0xEC, B: 0xFF }; // 7500 K
            const colorRight = { R: 0xC8, G: 0xD8, B: 0xFF }; // 10000 K
            this.color = {
                R: Math.floor(colorLeft.R + classRatio * (colorRight.R - colorLeft.R)),
                G: Math.floor(colorLeft.G + classRatio * (colorRight.G - colorLeft.G)),
                B: Math.floor(colorLeft.B + classRatio * (colorRight.B - colorLeft.B))
            };
            this.subSpectral = Math.floor(10 * (1 - classRatio));
        } else if (classRatio < 6.0) {
            classRatio -= 5.0;
            this.luminosityClass = 'IV';
            this.spectralClass = 'B';
            this.temperature = 10000.0 + 20000.0 * classRatio;
            this.mass = 42.0 + 278.0 * classRatio;
            this.radius = 12.6 + 33.6 * classRatio;
            this.bolometricLuminosity = 100000.0 + 120000000.0 * classRatio;
            const colorLeft = { R: 0xC8, G: 0xD8, B: 0xFF }; // 10000 K
            const colorRight = { R: 0x99, G: 0xBA, B: 0xFF }; // 30000 K
            this.color = {
                R: Math.floor(colorLeft.R + classRatio * (colorRight.R - colorLeft.R)),
                G: Math.floor(colorLeft.G + classRatio * (colorRight.G - colorLeft.G)),
                B: Math.floor(colorLeft.B + classRatio * (colorRight.B - colorLeft.B))
            };
            this.subSpectral = Math.floor(10 * (1 - classRatio));
        } else if (classRatio < 7.0) {
            classRatio -= 6.0;
            this.luminosityClass = 'III';
            this.spectralClass = 'O';
            this.temperature = 30000.0 + 20000.0 * classRatio;
            this.mass = 320.0 + 1360.0 * classRatio;
            this.radius = 46.2 + 28.7 * classRatio;
            this.bolometricLuminosity = 120000000.0 + 3528000000.0 * classRatio;
            const colorLeft = { R: 0x99, G: 0xBA, B: 0xFF }; // 30000 K
            const colorRight = { R: 0x92, G: 0xB5, B: 0xFF }; // 50000 K
            this.color = {
                R: Math.floor(colorLeft.R + classRatio * (colorRight.R - colorLeft.R)),
                G: Math.floor(colorLeft.G + classRatio * (colorRight.G - colorLeft.G)),
                B: Math.floor(colorLeft.B + classRatio * (colorRight.B - colorLeft.B))
            };
            this.subSpectral = Math.floor(10 * (1 - classRatio));
        }
    },

    setSelectedPlanetIndex: function (planetId) {
        this.selectedPlanetIndex = planetId;
        this.selectedPlanet = this.planets[planetId];
        //this.selectedPlanet.renderModel.selectedTile = -1;
        //this.selectedPlanet.addResource('Metal', 'storage', 20000);
        [].forEach.call(document.getElementById('miniatureTabs').childNodes, function (li) {
            if (+li.dataset.index === planetId) {
                li.className = 'active';
            } else {
                li.className = 'inactive';
            }
        });
        aos.game.emitEvent('requestUiSlowRefresh', {});
    },

    buildUi: function () {
        document.getElementById('miniatureTabs').innerHTML = '';
        const planetImgs = [
            "./data/img/Desert_planet_resource.png",
            "./data/img/Planets7.png",
            "./data/img/Planets9.png",
            "./data/img/Planets13.png",
            "./data/img/Desert_planet_resource.png",
            "./data/img/Planets7.png",
            "./data/img/Planets9.png",
            "./data/img/Planets13.png",
            "./data/img/Desert_planet_resource.png",
            "./data/img/Planets7.png",
            "./data/img/Planets9.png",
            "./data/img/Planets13.png",
            "./data/img/Desert_planet_resource.png",
            "./data/img/Planets7.png",
            "./data/img/Planets9.png",
            "./data/img/Planets13.png",
        ];
        this.planets.forEach(function (planet, i) {
            document.getElementById('miniatureTabs').innerHTML +=
                '
' +
                '
';
        }, this);

        // see animateLargeStar for formula explanation
        const overflow = 120;
        const leftBorderMaxCosine = 300;
        const RMaxOuter = (leftBorderMaxCosine * leftBorderMaxCosine + overflow * overflow) / (2 * overflow);
        const ROuter = (this.sizeRatio + 3) / 10 * RMaxOuter - 20;
        const centerX = 100 - ROuter;

        let wrapperInnerTxt = "";
        let idx = 0;
        let wrapperWidth = 0;
        for (idx = 0; idx < 30; idx++) {
            wrapperWidth = idx * 10 > ROuter ? 0 : Math.sqrt(ROuter * ROuter - 100 * idx * idx) + centerX;
            wrapperInnerTxt = "

" + wrapperInnerTxt + "

";
        }
        wrapperInnerTxt = "

" + wrapperInnerTxt + "

";
        //wrapperInnerTxt += "
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.        Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet?
";

        document.getElementById('starWrapperPlaceholder').appendChild(document.getElementById('storageBlock'));
        //document.getElementById('starWrapperBlock').innerHTML = wrapperInnerTxt;
        document.getElementById('starWrapperBlock').innerHTML = '';
        document.getElementById('starWrapperBlock').appendChild(document.getElementById('storageBlock'));

        this.setSelectedPlanetIndex(this.selectedPlanetIndex);
    },

    animateLargeStar: function () {
        const canvas = document.getElementById('largeStar');
        const ctx = canvas.getContext("2d");
        /*
          _____
         /    .\
        /     . \
        |   x . |
        \     . /
         \____./.
              . .
              | | 120 px

        R² = (R-120px)² + 300px²
        R² - (R² - 240R + 120²) = 300²
        240R = 300² + 120²

        */
        const overflow = 120;
        const leftBorderMaxCosine = 300;
        const RMaxOuter = (leftBorderMaxCosine * leftBorderMaxCosine + overflow * overflow) / (2 * overflow);
        const ROuter = (this.sizeRatio + 3) / 10 * RMaxOuter;
        const RInner = ROuter - 120;
        const centerX = 120 - ROuter;

        //ctx.clearRect(0, 0, 125, 600);

        //ctx.fillStyle = "#400";
        //ctx.beginPath();
        //ctx.arc(centerX, 300, ROuter, 0, 2 * Math.PI);
        //ctx.fill();

        //ctx.fillStyle = "#430";
        //ctx.beginPath();
        //ctx.arc(centerX, 300, RInner, 0, 2 * Math.PI);
        //ctx.fill();

        ctx.clearRect(0, 0, 125, 600);
        const gradient = ctx.createRadialGradient(centerX, 300, RInner, centerX, 300, ROuter);

        const leftSide = new aos.Star();
        leftSide.fillFromRatio(Math.max(this.sizeRatio - 1, 0));
        const colorLeft = leftSide.color;
        const rightSide = new aos.Star();
        rightSide.fillFromRatio(Math.min(this.sizeRatio + 0, 7));
        const colorRight = rightSide.color;

        gradient.addColorStop(0, 'rgba(' + colorRight.R + ', ' + colorRight.G + ', ' + colorRight.B + ', 1)');
        gradient.addColorStop(0.4, 'rgba(' + colorRight.R + ', ' + colorRight.G + ', ' + colorRight.B + ', 1)');
        gradient.addColorStop(0.7, 'rgba(' + colorLeft.R + ', ' + colorLeft.G + ', ' + colorLeft.B + ', 1)');
        gradient.addColorStop(0.72, 'rgba(' + colorLeft.R + ', ' + colorLeft.G + ', ' + colorLeft.B + ', 0.5)');
        gradient.addColorStop(1, 'rgba(' + colorLeft.R + ', ' + colorLeft.G + ', ' + colorLeft.B + ', 0)');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, 125, 600);
    },

    showShip: function () {
        if (this.hasShip) {
            document.getElementById('starWrapperBlock').style.display = 'block';
            document.getElementById('shipAnimation').style.display = 'block';
            document.getElementById('planetStorageColumn').className = 'sendToShipVisible';
            this.ship.updateBars();
        } else {
            document.getElementById('starWrapperBlock').style.display = 'none';
            document.getElementById('shipAnimation').style.display = 'none';
            document.getElementById('planetStorageColumn').className = 'sendToShipInvisible';
        }
    },

    animateShip: function () {
        // TODO
        if (this.hasShip) {
            this.shipAngle += 3;
            document.getElementById('shipAnimation').style.transform = 'rotate(' + this.shipAngle + 'deg)';
        }
    },

};


text:
<?php

namespace Never5\DownloadMonitor\Shop\Cart\Item;

use Never5\DownloadMonitor\Shop\Services\Services;

class Factory {

	/**
	 * Make Item for given Download ID
	 *
	 * @param int $product_id
	 *
	 * @return Item
	 * @throws \Exception
	 */
	public function make( $product_id ) {

		/**
		 * Fetch the download
		 *
		 * @var \Never5\DownloadMonitor\Shop\Product\Product $product
		 */
		$product = Services::get()->service( 'product_repository' )->retrieve_single( $product_id );

		if ( ! in_array( $product->get_status(), array( 'publish' ) ) ) {
			throw new \Exception( 'Product not purchasable' );
		}

		// build item
		$item = new Item();
		$item->set_product_id( $product_id );
		$item->set_qty( 1 );
		$item->set_label( $product->get_title() );
		$item->set_subtotal( $product->get_price() );
		$item->set_tax_total( 0 );
		/** @todo [TAX] Implement taxes */
		$item->set_total( $product->get_price() );

		return $item;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.opengamma.web.portfolio;

import java.net.URI;
import java.util.Stack;

import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

import com.opengamma.DataNotFoundException;
import com.opengamma.id.UniqueId;
import com.opengamma.master.portfolio.ManageablePortfolioNode;
import com.opengamma.master.portfolio.PortfolioDocument;

/**
 * RESTful resource for all nodes in a portfolio version.
 */
@Path("/portfolios/{portfolioId}/versions/{versionId}/nodes")
public class WebPortfolioVersionNodesResource extends WebPortfolioNodesResource {

  /**
   * Creates the resource.
   * @param parent  the parent resource, not null
   */
  public WebPortfolioVersionNodesResource(AbstractWebPortfolioResource parent) {
    super(parent);
  }

  //-------------------------------------------------------------------------
  @Override
  @Path("{nodeId}")
  public WebPortfolioNodeResource findNode(@PathParam("nodeId") String idStr) {
    data().setUriNodeId(idStr);
    UniqueId oid = UniqueId.parse(idStr);
    PortfolioDocument portfolioDoc = data().getVersioned();
    Stack<ManageablePortfolioNode> nodes = portfolioDoc.getPortfolio().getRootNode().findNodeStackByObjectId(oid);
    if (nodes.isEmpty()) {
      throw new DataNotFoundException("PortfolioNode not found: " + idStr);
    }
    data().setNode(nodes.pop());
    if (nodes.size() > 0) {
      data().setParentNode(nodes.pop());
    }
    return new WebPortfolioVersionNodeResource(this);
  }

  //-------------------------------------------------------------------------
  /**
   * Builds a URI for this resource.
   * @param data  the data, not null
   * @return the URI, not null
   */
  public static URI uri(final WebPortfoliosData data) {
    String portfolioId = data.getBestPortfolioUriId(null);
    return data.getUriInfo().getBaseUriBuilder().path(WebPortfolioNodesResource.class).build(portfolioId);
  }

}


text:
namespace winrt::SDKTemplate::implementation
{
    struct Scenario1_DetectInPhoto : Scenario1_DetectInPhotoT<Scenario1_DetectInPhoto>
    {
        Scenario1_DetectInPhoto();

        fire_and_forget OpenFile_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
        void PhotoCanvas_SizeChanged(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::SizeChangedEventArgs const& e);

    private:
        SDKTemplate::MainPage rootPage{ MainPage::Current() };

        // Limit on the height of the source image (in pixels) passed into FaceDetector for performance considerations.
        // Images larger that this size will be downscaled proportionally.
        //
        // This is an arbitrary value that was chosen for this scenario, in which FaceDetector performance isn't too important but face
        // detection accuracy is; a generous size is used.
        // Your application may have different performance and accuracy needs and you'll need to decide how best to control input.
        static constexpr uint32_t sourceImageHeightLimit = 1280;

        void SetupVisualization(Windows::UI::Xaml::Media::Imaging::WriteableBitmap const& displaySource, Windows::Foundation::Collections::IVector<Windows::Media::FaceAnalysis::DetectedFace> const& foundFaces);
        void ClearVisualization();
        Windows::Graphics::Imaging::BitmapTransform ComputeScalingTransformForSourceImage(Windows::Graphics::Imaging::BitmapDecoder const& sourceDecoder);
    };
}

namespace winrt::SDKTemplate::factory_implementation
{
    struct Scenario1_DetectInPhoto : Scenario1_DetectInPhotoT<Scenario1_DetectInPhoto, implementation::Scenario1_DetectInPhoto>
    {
    };
}


text:
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/mm.h>

#include <asm/mmu_context.h>
#include <asm/tlbflush.h>

static DEFINE_SPINLOCK(cpu_asid_lock);
unsigned int cpu_last_asid = ASID_FIRST_VERSION;

/*
 * We fork()ed a process, and we need a new context for the child
 * to run in.  We reserve version 0 for initial tasks so we will
 * always allocate an ASID. The ASID 0 is reserved for the TTBR
 * register changing sequence.
 */
void __init_new_context(struct task_struct *tsk, struct mm_struct *mm)
{
	mm->context.id = 0;
}

void __new_context(struct mm_struct *mm)
{
	unsigned int asid;

	spin_lock(&cpu_asid_lock);
	asid = ++cpu_last_asid;
	if (asid == 0)
		asid = cpu_last_asid = ASID_FIRST_VERSION;

	/*
	 * If we've used up all our ASIDs, we need
	 * to start a new version and flush the TLB.
	 */
	if (unlikely((asid & ~ASID_MASK) == 0)) {
		asid = ++cpu_last_asid;
		/* set the reserved ASID before flushing the TLB */
		asm("mcr	p15, 0, %0, c13, c0, 1	@ set reserved context ID\n"
		    :
		    : "r" (0));
		isb();
		flush_tlb_all();
		if (icache_is_vivt_asid_tagged()) {
			__flush_icache_all();
			dsb();
		}
	}
	spin_unlock(&cpu_asid_lock);

	cpumask_copy(mm_cpumask(mm), cpumask_of(smp_processor_id()));
	mm->context.id = asid;
}


text:
package chrome.webRequest.bindings

import scala.scalajs.js

object BlockingResponse {
  def apply(cancel: js.UndefOr[Boolean] = js.undefined,
            redirectUrl: js.UndefOr[String] = js.undefined,
            responseHeaders: js.UndefOr[js.Array[HttpHeader]] = js.undefined,
            authCredentials: js.UndefOr[AuthCredentials] = js.undefined,
            requestHeaders: js.UndefOr[js.Array[HttpHeader]] = js.undefined): BlockingResponse = {
    js.Dynamic.literal(
      cancel = cancel,
      redirectUrl = redirectUrl,
      responseHeaders = responseHeaders,
      authCredentials = authCredentials,
      requestHeaders = requestHeaders
    ).asInstanceOf[BlockingResponse]
  }
}

@js.native
trait BlockingResponse extends js.Object {
  /**
    * Optional:
    * If true, the request is cancelled. Used in onBeforeRequest, this prevents the request from being sent.
    */
  val cancel: js.UndefOr[Boolean] = js.native

  /**
    * Optional:
    * Only used as a response to the onBeforeRequest and onHeadersReceived events. If set, the original request is
    * prevented from being sent/completed and is instead redirected to the given URL. Redirections to non-HTTP
    * schemes such as data: are allowed. Redirects initiated by a redirect action use the original request method
    * for the redirect, with one exception: If the redirect is initiated at the onHeadersReceived stage, then the
    * redirect will be issued using the GET method.
    */
  val redirectUrl: js.UndefOr[String] = js.native

  /**
    * Optional:
    * Only used as a response to the onHeadersReceived event. If set, the server is assumed to have responded with these
    * response headers instead. Only return responseHeaders if you really want to modify the headers in order to limit
    * the number of conflicts (only one extension may modify responseHeaders for each request).
    */
  val responseHeaders: js.UndefOr[js.Array[HttpHeader]] = js.native

  /**
    * Optional:
    * Only used as a response to the onAuthRequired event. If set, the request is made using the supplied credentials.
    */
  val authCredentials: js.UndefOr[AuthCredentials] = js.native

  /**
    * Optional:
    * Only used as a response to the onBeforeSendHeaders event. If set, the request is made with these request headers
    * instead.
    */
  val requestHeaders: js.UndefOr[js.Array[HttpHeader]] = js.native
}


text:
package com.bkahlert.nebula.widgets.composer;

import com.bkahlert.nebula.widgets.browser.extended.html.IAnker;

/**
 * Instances of this class provide labels for existing anker tags (e.g. bkahlert.com).
 *
 * @author bkahlert
 *
 */
public interface IAnkerLabelProvider {
	/**
	 * Returns true if this {@link IAnkerLabelProvider} is responsible for the
	 * given {@link IElement}.
	 *

	 * Please note that only up to one {@link IAnkerLabelProvider} can be
	 * responsible. As soon as one {@link IAnkerLabelProvider} return
	 * responsibility the other registered {@link IAnkerLabelProvider}s are
	 * skipped for the given {@link IElement}.
	 *
	 * @param uri
	 * @return
	 */
	public boolean isResponsible(IAnker anker);

	public String getHref(IAnker anker);

	public String[] getClasses(IAnker anker);

	public String getContent(IAnker anker);
}


text:
/* -*- C++ -*- */

//=============================================================================
/**
 *  @file    Event_Handler_T.h
 *
 *  @author Douglas C. Schmidt <schmidt@cs.wustl.edu>
 */
//=============================================================================

#ifndef ACE_EVENT_HANDLER_T_H
#define ACE_EVENT_HANDLER_T_H
#include /**/ "ace/pre.h"

#include "ace/Event_Handler.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

/**
 * @class ACE_Event_Handler_T
 *
 * @brief Enable a class that doesn't inherit from the
 * ACE_Event_Handler to be incorporated into the ACE_Reactor
 * framework.  Thanks to Greg Lavender (g.lavender@isode.com)
 * for sharing this idea.
 *
 * It is sometimes the case that an application has a hierarchy
 * of operation dispatcher classes that have their own
 * inheritance hierarchy but also would like to integrate with
 * the ACE_Reactor.  Rather than adopt a "mixin" approach, it is
 * often cleaner to define a template as a subclass of
 * ACE_Event_Handler and parameterize it with an operation
 * dispatcher type.
 * When constructing an instantiation of the ACE_Event_Handler_T
 * object, a set of pointers to member functions must be
 * provided so that when one of the handle_* methods is called
 * by the ACE_Reactor, the appropriate method is called on the
 * underlying operations object.  This is done since in some
 * cases it is useful to map any event that happens to the same
 * method on an object.
 * The ACE_Event_Handler_T template is instantiated by an
 * operations object and registered with the ACE_Reactor, and it
 * then calls the appropriate op_handler.  So, it's basically
 * just another level of indirection in event dispatching. The
 * coupling betweent the ultimate handler of the event and the
 * ACE_Event_Handler class is relaxed a bit by have this
 * intermediate <op_handler_> object of type <T> around. The
 * client object can then dynamically change the bindings for
 * the various handlers so that during the life of one of the
 * operation objects, it can change how it wants events to be
 * handled. It just instantiates a new instance of the template
 * with different bindings and reregisters this new object with
 * the ACE_Reactor.
 */
template <class T>
class ACE_Event_Handler_T : public ACE_Event_Handler
{
public:
  // = Typedefs to simplify pointer-to-member-function registration.

  // Get/set the underlying handle.
  typedef ACE_HANDLE (T::*GET_HANDLE) (void) const;
  typedef void (T::*SET_HANDLE) (ACE_HANDLE);

  /// Handle I/O events.
  typedef int (T::*IO_HANDLER) (ACE_HANDLE);

  /// Handle timeout events.
  typedef int (T::*TO_HANDLER) (const ACE_Time_Value &, const void *);

  /// Handle close events.
  typedef int (T::*CL_HANDLER) (ACE_HANDLE, ACE_Reactor_Mask);

  /// = Initialization and termination methods.
  typedef int (T::*SIG_HANDLER) (int, siginfo_t*, ucontext_t*);

  /// Initialize the op_handler.
  ACE_Event_Handler_T (T *op_handler,
                       int delete_handler,
                       GET_HANDLE get_handle = 0,
                       IO_HANDLER input = 0,
                       CL_HANDLER close = 0,
                       SIG_HANDLER sig = 0,
                       TO_HANDLER timeout = 0,
                       IO_HANDLER output = 0,
                       SET_HANDLE set_handle = 0,
                       IO_HANDLER except = 0);

  /// Close down and delete the <op_handler>
  ~ACE_Event_Handler_T (void);

  // = Override all the ACE_Event_Handler methods.

  // These methods all delegate down to the <T> operations handler.
  virtual ACE_HANDLE get_handle (void) const;
  virtual void set_handle (ACE_HANDLE);
  virtual int handle_input (ACE_HANDLE fd = ACE_INVALID_HANDLE);
  virtual int handle_output (ACE_HANDLE fd = ACE_INVALID_HANDLE);
  virtual int handle_exception (ACE_HANDLE fd = ACE_INVALID_HANDLE);
  virtual int handle_timeout (const ACE_Time_Value &tv, const void *arg = 0);
  virtual int handle_close (ACE_HANDLE fd, ACE_Reactor_Mask close_mask);
  virtual int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0);

  // = Get/set the operations handler.
  T *op_handler (void);
  void op_handler (T *);

  // = Get/set the target pointer-to-method used for dispatching.

  GET_HANDLE handle_get (void);
  void handle_get (GET_HANDLE);

  SET_HANDLE handle_set (void);
  void handle_set (SET_HANDLE);

  IO_HANDLER input_handler (void);
  void input_handler (IO_HANDLER);

  IO_HANDLER output_handler (void);
  void output_handler (IO_HANDLER);

  IO_HANDLER except_handler (void);
  void except_handler (IO_HANDLER);

  TO_HANDLER to_handler (void);
  void to_handler (TO_HANDLER);

  CL_HANDLER cl_handler (void);
  void cl_handler (CL_HANDLER);

  SIG_HANDLER sig_handler (void);
  void sig_handler (SIG_HANDLER);

  /// Dump the state of an object.
  void dump (void) const;

  /// Declare the dynamic allocation hooks.
  ACE_ALLOC_HOOK_DECLARE;

protected:
  /// Pointer to the object that handles all the delegated operations.
  T *op_handler_;

  // = Handle input, output, and exception events.
  IO_HANDLER input_handler_;
  IO_HANDLER output_handler_;
  IO_HANDLER except_handler_;

  /// Handle timeout events.
  TO_HANDLER to_handler_;

  /// Handle close events.
  CL_HANDLER cl_handler_;

  /// Handle signal events.
  SIG_HANDLER sig_handler_;

  /// Keeps track of whether we need to delete the handler in the
  /// destructor.
  int delete_handler_;

  // = Get/set underlying handle.
  SET_HANDLE set_handle_;
  GET_HANDLE get_handle_;
};

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "ace/Event_Handler_T.inl"
#endif /* __ACE_INLINE__ */

#if defined (ACE_TEMPLATES_REQUIRE_SOURCE)
#include "ace/Event_Handler_T.cpp"
#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */

#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA)
#pragma implementation ("Event_Handler_T.cpp")
#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */

#include /**/ "ace/post.h"
#endif /* ACE_EVENT_HANDLER_H */


text:
@implementation MBEMetalView

+ (Class)layerClass
{
    return [CAMetalLayer class];
}

- (CAMetalLayer *)metalLayer
{
    return (CAMetalLayer *)self.layer;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];

    // During the first layout pass, we will not be in a view hierarchy, so we guess our scale
    CGFloat scale = [UIScreen mainScreen].scale;

    // If we've moved to a window by the time our frame is being set, we can take its scale as our own
    if (self.window)
    {
        scale = self.window.screen.scale;
    }

    CGSize drawableSize = self.bounds.size;

    // Since drawable size is in pixels, we need to multiply by the scale to move from points to pixels
    drawableSize.width *= scale;
    drawableSize.height *= scale;

    self.metalLayer.drawableSize = drawableSize;
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 29: 272 (1890)

#### Original name
Botrytis sporotrichoides P. Karst.

### Remarks
null


text:
package com.stupidman.admin.collectionandroiddemo.litepal.bean;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2015/5/26.
 */
public class Users extends DataSupport {

    private int id;
    private String username;//用户名
    private String password;//密码
    private List<Comments> commentsList = new ArrayList<Comments>();

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public List<Comments> getCommentsList() {
        //return commentsList;
        return DataSupport.where("id = ?", String.valueOf(id)).find(Comments.class);
    }

    public void setCommentsList(List<Comments> commentsList) {
        this.commentsList = commentsList;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Russula pseudoolivascens subsp. squalens Kärcher

### Remarks
null


text:
#region Copyright (c) all rights reserved.
// <copyright file="CheckStartedEvent.cs">
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
#endregion

namespace Ditto.DataCheck.DomainEvents
{
    using Ditto.DomainEvents;

    /// <summary>
    /// Check started event.
    /// </summary>
    public class CheckStartedEvent : IDomainEvent
    {
        /// <summary>
        /// Gets or sets the check name.
        /// </summary>
        /// <value>
        /// The check name.
        /// </value>
        public string Name { get; set; }
    }
}


text:
/*
 * Windows support routines for PhysicsFS.
 *
 * Please see the file LICENSE.txt in the source's root directory.
 *
 *  This file written by Ryan C. Gordon, and made sane by Gregory S. Read.
 */

#define __PHYSICSFS_INTERNAL__
#include "physfs_platforms.h"

#ifdef PHYSFS_PLATFORM_WINDOWS

/* Forcibly disable UNICODE macro, since we manage this ourselves. */
#ifdef UNICODE
#undef UNICODE
#endif

#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS 1
#endif

#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>

#ifndef PHYSFS_PLATFORM_WINRT
#include <userenv.h>
#include <shlobj.h>
#endif

#if !defined(PHYSFS_NO_CDROM_SUPPORT)
#include <dbt.h>
#endif

#include <errno.h>
#include <ctype.h>
#include <time.h>

#ifdef allocator  /* apparently Windows 10 SDK conflicts here. */
#undef allocator
#endif

#include "physfs_internal.h"

/*
 * Users without the platform SDK don't have this defined.  The original docs
 *  for SetFilePointer() just said to compare with 0xFFFFFFFF, so this should
 *  work as desired.
 */
#define PHYSFS_INVALID_SET_FILE_POINTER  0xFFFFFFFF

/* just in case... */
#define PHYSFS_INVALID_FILE_ATTRIBUTES   0xFFFFFFFF

/* Not defined before the Vista SDK. */
#define PHYSFS_FILE_ATTRIBUTE_REPARSE_POINT 0x400
#define PHYSFS_IO_REPARSE_TAG_SYMLINK    0xA000000C

#define UTF8_TO_UNICODE_STACK(w_assignto, str) { \
    if (str == NULL) \
        w_assignto = NULL; \
    else { \
        const size_t len = (PHYSFS_uint64) ((strlen(str) + 1) * 2); \
        w_assignto = (WCHAR *) __PHYSFS_smallAlloc(len); \
        if (w_assignto != NULL) \
            PHYSFS_utf8ToUtf16(str, (PHYSFS_uint16 *) w_assignto, len); \
    } \
} \

/* Note this counts WCHARs, not codepoints! */
static PHYSFS_uint64 wStrLen(const WCHAR *wstr)
{
    PHYSFS_uint64 len = 0;
    while (*(wstr++))
        len++;
    return len;
} /* wStrLen */

static char *unicodeToUtf8Heap(const WCHAR *w_str)
{
    char *retval = NULL;
    if (w_str != NULL)
    {
        void *ptr = NULL;
        const PHYSFS_uint64 len = (wStrLen(w_str) * 4) + 1;
        retval = allocator.Malloc(len);
        BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
        PHYSFS_utf8FromUtf16((const PHYSFS_uint16 *) w_str, retval, len);
        ptr = allocator.Realloc(retval, strlen(retval) + 1); /* shrink. */
        if (ptr != NULL)
            retval = (char *) ptr;
    } /* if */
    return retval;
} /* unicodeToUtf8Heap */

/* Some older APIs aren't in WinRT (only the "Ex" version, etc).
   Since non-WinRT might not have the "Ex" version, we tapdance to use
   the perfectly-fine-and-available-even-on-Win95 API on non-WinRT targets. */

static inline HANDLE winFindFirstFileW(const WCHAR *path, LPWIN32_FIND_DATAW d)
{
    #ifdef PHYSFS_PLATFORM_WINRT
    return FindFirstFileExW(path, FindExInfoStandard, d,
                            FindExSearchNameMatch, NULL, 0);
    #else
    return FindFirstFileW(path, d);
    #endif
} /* winFindFirstFileW */

static inline BOOL winInitializeCriticalSection(LPCRITICAL_SECTION lpcs)
{
    #ifdef PHYSFS_PLATFORM_WINRT
    return InitializeCriticalSectionEx(lpcs, 2000, 0);
    #else
    InitializeCriticalSection(lpcs);
    return TRUE;
    #endif
} /* winInitializeCriticalSection */

static inline HANDLE winCreateFileW(const WCHAR *wfname, const DWORD mode,
                                    const DWORD creation)
{
    const DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE;
    #ifdef PHYSFS_PLATFORM_WINRT
    return CreateFile2(wfname, mode, share, creation, NULL);
    #else
    return CreateFileW(wfname, mode, share, NULL, creation,
                       FILE_ATTRIBUTE_NORMAL, NULL);
    #endif
} /* winCreateFileW */

static BOOL winSetFilePointer(HANDLE h, const PHYSFS_sint64 pos,
                              PHYSFS_sint64 *_newpos, const DWORD whence)
{
    #ifdef PHYSFS_PLATFORM_WINRT
    LARGE_INTEGER lipos;
    LARGE_INTEGER linewpos;
    BOOL rc;
    lipos.QuadPart = (LONGLONG) pos;
    rc = SetFilePointerEx(h, lipos, &linewpos, whence);
    if (_newpos)
        *_newpos = (PHYSFS_sint64) linewpos.QuadPart;
    return rc;
    #else
    const LONG low = (LONG) (pos & 0xFFFFFFFF);
    LONG high = (LONG) ((pos >> 32) & 0xFFFFFFFF);
    const DWORD rc = SetFilePointer(h, low, &high, whence);
    /* 0xFFFFFFFF could be valid, so you have to check GetLastError too! */
    if (_newpos)
        *_newpos = ((PHYSFS_sint64) rc) | (((PHYSFS_sint64) high) << 32);
    if ((rc == PHYSFS_INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR))
        return FALSE;
    return TRUE;
    #endif
} /* winSetFilePointer */

static PHYSFS_sint64 winGetFileSize(HANDLE h)
{
    #ifdef PHYSFS_PLATFORM_WINRT
    FILE_STANDARD_INFO info;
    const BOOL rc = GetFileInformationByHandleEx(h, FileStandardInfo,
                                                 &info, sizeof (info));
    return rc ? (PHYSFS_sint64) info.EndOfFile.QuadPart : -1;
    #else
    DWORD high = 0;
    const DWORD rc = GetFileSize(h, &high);
    if ((rc == PHYSFS_INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR))
        return -1;
    return (PHYSFS_sint64) ((((PHYSFS_uint64) high) << 32) | rc);
    #endif
} /* winGetFileSize */

static PHYSFS_ErrorCode errcodeFromWinApiError(const DWORD err)
{
    /*
     * win32 error codes are sort of a tricky thing; Microsoft intentionally
     *  doesn't list which ones a given API might trigger, there are several
     *  with overlapping and unclear meanings...and there's 16 thousand of
     *  them in Windows 7. It looks like the ones we care about are in the
     *  first 500, but I can't say this list is perfect; we might miss
     *  important values or misinterpret others.
     *
     * Don't treat this list as anything other than a work in progress.
     */
    switch (err)
    {
        case ERROR_SUCCESS: return PHYSFS_ERR_OK;
        case ERROR_ACCESS_DENIED: return PHYSFS_ERR_PERMISSION;
        case ERROR_NETWORK_ACCESS_DENIED: return PHYSFS_ERR_PERMISSION;
        case ERROR_NOT_READY: return PHYSFS_ERR_IO;
        case ERROR_CRC: return PHYSFS_ERR_IO;
        case ERROR_SEEK: return PHYSFS_ERR_IO;
        case ERROR_SECTOR_NOT_FOUND: return PHYSFS_ERR_IO;
        case ERROR_NOT_DOS_DISK: return PHYSFS_ERR_IO;
        case ERROR_WRITE_FAULT: return PHYSFS_ERR_IO;
        case ERROR_READ_FAULT: return PHYSFS_ERR_IO;
        case ERROR_DEV_NOT_EXIST: return PHYSFS_ERR_IO;
        case ERROR_BUFFER_OVERFLOW: return PHYSFS_ERR_BAD_FILENAME;
        case ERROR_INVALID_NAME: return PHYSFS_ERR_BAD_FILENAME;
        case ERROR_BAD_PATHNAME: return PHYSFS_ERR_BAD_FILENAME;
        case ERROR_DIRECTORY: return PHYSFS_ERR_BAD_FILENAME;
        case ERROR_FILE_NOT_FOUND: return PHYSFS_ERR_NOT_FOUND;
        case ERROR_PATH_NOT_FOUND: return PHYSFS_ERR_NOT_FOUND;
        case ERROR_DELETE_PENDING: return PHYSFS_ERR_NOT_FOUND;
        case ERROR_INVALID_DRIVE: return PHYSFS_ERR_NOT_FOUND;
        case ERROR_HANDLE_DISK_FULL: return PHYSFS_ERR_NO_SPACE;
        case ERROR_DISK_FULL: return PHYSFS_ERR_NO_SPACE;
        case ERROR_WRITE_PROTECT: return PHYSFS_ERR_READ_ONLY;
        case ERROR_LOCK_VIOLATION: return PHYSFS_ERR_BUSY;
        case ERROR_SHARING_VIOLATION: return PHYSFS_ERR_BUSY;
        case ERROR_CURRENT_DIRECTORY: return PHYSFS_ERR_BUSY;
        case ERROR_DRIVE_LOCKED: return PHYSFS_ERR_BUSY;
        case ERROR_PATH_BUSY: return PHYSFS_ERR_BUSY;
        case ERROR_BUSY: return PHYSFS_ERR_BUSY;
        case ERROR_NOT_ENOUGH_MEMORY: return PHYSFS_ERR_OUT_OF_MEMORY;
        case ERROR_OUTOFMEMORY: return PHYSFS_ERR_OUT_OF_MEMORY;
        case ERROR_DIR_NOT_EMPTY: return PHYSFS_ERR_DIR_NOT_EMPTY;
        default: return PHYSFS_ERR_OS_ERROR;
    } /* switch */
} /* errcodeFromWinApiError */

static inline PHYSFS_ErrorCode errcodeFromWinApi(void)
{
    return errcodeFromWinApiError(GetLastError());
} /* errcodeFromWinApi */

#if defined(PHYSFS_NO_CDROM_SUPPORT)
#define detectAvailableCDs(cb, data)
#define deinitCDThread()
#else
static HANDLE detectCDThreadHandle = NULL;
static HWND detectCDHwnd = NULL;
static volatile DWORD drivesWithMediaBitmap = 0;

typedef BOOL (WINAPI *fnSTEM)(DWORD, LPDWORD b);

static DWORD pollDiscDrives(void)
{
    /* Try to use SetThreadErrorMode(), which showed up in Windows 7. */
    HANDLE lib = LoadLibraryA("kernel32.dll");
    fnSTEM stem = NULL;
    char drive[4] = { 'x', ':', '\\', '\0' };
    DWORD oldErrorMode = 0;
    DWORD drives = 0;
    DWORD i;

    if (lib)
        stem = (fnSTEM) GetProcAddress(lib, "SetThreadErrorMode");

    if (stem)
        stem(SEM_FAILCRITICALERRORS, &oldErrorMode);
    else
        oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);

    /* Do detection. This may block if a disc is spinning up. */
    for (i = 'A'; i <= 'Z'; i++)
    {
        DWORD tmp = 0;
        drive[0] = (char) i;
        if (GetDriveTypeA(drive) != DRIVE_CDROM)
            continue;

        /* If this function succeeds, there's media in the drive */
        if (GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0))
            drives |= (1 << (i - 'A'));
    } /* for */

    if (stem)
        stem(oldErrorMode, NULL);
    else
        SetErrorMode(oldErrorMode);

    if (lib)
        FreeLibrary(lib);

    return drives;
} /* pollDiscDrives */

static LRESULT CALLBACK detectCDWndProc(HWND hwnd, UINT msg,
                                        WPARAM wp, LPARAM lparam)
{
    PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR) lparam;
    PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME) lparam;
    const int removed = (wp == DBT_DEVICEREMOVECOMPLETE);

    if (msg == WM_DESTROY)
        return 0;
    else if ((msg != WM_DEVICECHANGE) ||
             ((wp != DBT_DEVICEARRIVAL) && (wp != DBT_DEVICEREMOVECOMPLETE)) ||
             (lpdb->dbch_devicetype != DBT_DEVTYP_VOLUME) ||
             ((lpdbv->dbcv_flags & DBTF_MEDIA) == 0))
    {
        return DefWindowProcW(hwnd, msg, wp, lparam);
    } /* else if */

    if (removed)
        drivesWithMediaBitmap &= ~lpdbv->dbcv_unitmask;
    else
        drivesWithMediaBitmap |= lpdbv->dbcv_unitmask;

    return TRUE;
} /* detectCDWndProc */

static DWORD WINAPI detectCDThread(LPVOID arg)
{
    HANDLE initialDiscDetectionComplete = *((HANDLE *) arg);
    const char *classname = "PhysicsFSDetectCDCatcher";
    const char *winname = "PhysicsFSDetectCDMsgWindow";
    HINSTANCE hInstance = GetModuleHandleW(NULL);
    ATOM class_atom = 0;
    WNDCLASSEXA wce;
    MSG msg;

    memset(&wce, '\0', sizeof (wce));
    wce.cbSize = sizeof (wce);
    wce.lpfnWndProc = detectCDWndProc;
    wce.lpszClassName = classname;
    wce.hInstance = hInstance;
    class_atom = RegisterClassExA(&wce);
    if (class_atom == 0)
    {
        SetEvent(initialDiscDetectionComplete);  /* let main thread go on. */
        return 0;
    } /* if */

    detectCDHwnd = CreateWindowExA(0, classname, winname, WS_OVERLAPPEDWINDOW,
                        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                        CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL);

    if (detectCDHwnd == NULL)
    {
        SetEvent(initialDiscDetectionComplete);  /* let main thread go on. */
        UnregisterClassA(classname, hInstance);
        return 0;
    } /* if */

    /* We'll get events when discs come and go from now on. */

    /* Do initial detection, possibly blocking awhile... */
    drivesWithMediaBitmap = pollDiscDrives();

    SetEvent(initialDiscDetectionComplete);  /* let main thread go on. */

    do
    {
        const BOOL rc = GetMessageW(&msg, detectCDHwnd, 0, 0);
        if ((rc == 0) || (rc == -1))
            break;  /* don't care if WM_QUIT or error break this loop. */
        TranslateMessage(&msg);
        DispatchMessageW(&msg);
    } while (1);

    /* we've been asked to quit. */
    DestroyWindow(detectCDHwnd);
    UnregisterClassA(classname, hInstance);
    return 0;
} /* detectCDThread */

static void detectAvailableCDs(PHYSFS_StringCallback cb, void *data)
{
    char drive_str[4] = { 'x', ':', '\\', '\0' };
    DWORD drives = 0;
    DWORD i;

    /*
     * If you poll a drive while a user is inserting a disc, the OS will
     *  block this thread until the drive has spun up. So we swallow the risk
     *  once for initial detection, and spin a thread that will get device
     *  events thereafter, for apps that use this interface to poll for
     *  disc insertion.
     */
    if (!detectCDThreadHandle)
    {
        HANDLE initialDetectDone = CreateEvent(NULL, TRUE, FALSE, NULL);
        if (!initialDetectDone)
            return;  /* oh well. */

        detectCDThreadHandle = CreateThread(NULL, 0, detectCDThread,
                                            &initialDetectDone, 0, NULL);
        if (detectCDThreadHandle)
            WaitForSingleObject(initialDetectDone, INFINITE);
        CloseHandle(initialDetectDone);

        if (!detectCDThreadHandle)
            return;  /* oh well. */
    } /* if */

    drives = drivesWithMediaBitmap; /* whatever the thread has seen, we take. */
    for (i = 'A'; i <= 'Z'; i++)
    {
        if (drives & (1 << (i - 'A')))
        {
            drive_str[0] = (char) i;
            cb(data, drive_str);
        } /* if */
    } /* for */
} /* detectAvailableCDs */

static void deinitCDThread(void)
{
    if (detectCDThreadHandle)
    {
        if (detectCDHwnd)
            PostMessageW(detectCDHwnd, WM_QUIT, 0, 0);
        CloseHandle(detectCDThreadHandle);
        detectCDThreadHandle = NULL;
        drivesWithMediaBitmap = 0;
    } /* if */
} /* deinitCDThread */
#endif

void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
{
    detectAvailableCDs(cb, data);
} /* __PHYSFS_platformDetectAvailableCDs */

#ifdef PHYSFS_PLATFORM_WINRT
static char *calcDirAppendSep(const WCHAR *wdir)
{
    size_t len;
    void *ptr;
    char *retval;
    BAIL_IF(!wdir, errcodeFromWinApi(), NULL);
    retval = unicodeToUtf8Heap(wdir);
    BAIL_IF_ERRPASS(!retval, NULL);
    len = strlen(retval);
    ptr = allocator.Realloc(retval, len + 2);
    if (!ptr)
    {
        allocator.Free(retval);
        BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
    } /* if */
    retval = (char *) ptr;
    retval[len] = '\\';
    retval[len+1] = '\0';
    return retval;
} /* calcDirAppendSep */
#endif

char *__PHYSFS_platformCalcBaseDir(const char *argv0)
{
#ifdef PHYSFS_PLATFORM_WINRT
    return calcDirAppendSep((const WCHAR *) __PHYSFS_winrtCalcBaseDir());
#else
    char *retval = NULL;
    DWORD buflen = 64;
    LPWSTR modpath = NULL;

    while (1)
    {
        DWORD rc;
        void *ptr;

        if ( (ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) == NULL )
        {
            allocator.Free(modpath);
            BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
        } /* if */
        modpath = (LPWSTR) ptr;

        rc = GetModuleFileNameW(NULL, modpath, buflen);
        if (rc == 0)
        {
            allocator.Free(modpath);
            BAIL(errcodeFromWinApi(), NULL);
        } /* if */

        if (rc < buflen)
        {
            buflen = rc;
            break;
        } /* if */

        buflen *= 2;
    } /* while */

    if (buflen > 0)  /* just in case... */
    {
        WCHAR *ptr = (modpath + buflen) - 1;
        while (ptr != modpath)
        {
            if (*ptr == '\\')
                break;
            ptr--;
        } /* while */

        if ((ptr == modpath) && (*ptr != '\\'))
            PHYSFS_setErrorCode(PHYSFS_ERR_OTHER_ERROR);  /* oh well. */
        else
        {
            *(ptr+1) = '\0';  /* chop off filename. */
            retval = unicodeToUtf8Heap(modpath);
        } /* else */
    } /* else */
    allocator.Free(modpath);

    return retval;   /* w00t. */
#endif
} /* __PHYSFS_platformCalcBaseDir */

char *__PHYSFS_platformCalcPrefDir(const char *org, const char *app)
{
#ifdef PHYSFS_PLATFORM_WINRT
    return calcDirAppendSep((const WCHAR *) __PHYSFS_winrtCalcPrefDir());
#else
    /*
     * Vista and later has a new API for this, but SHGetFolderPath works there,
     *  and apparently just wraps the new API. This is the new way to do it:
     *
     *     SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_CREATE,
     *                          NULL, &wszPath);
     */

    WCHAR path[MAX_PATH];
    char *utf8 = NULL;
    size_t len = 0;
    char *retval = NULL;

    if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE,
                                   NULL, 0, path)))
        BAIL(PHYSFS_ERR_OS_ERROR, NULL);

    utf8 = unicodeToUtf8Heap(path);
    BAIL_IF_ERRPASS(!utf8, NULL);
    len = strlen(utf8) + strlen(org) + strlen(app) + 4;
    retval = allocator.Malloc(len);
    if (!retval)
    {
        allocator.Free(utf8);
        BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
    } /* if */

    snprintf(retval, len, "%s\\%s\\%s\\", utf8, org, app);
    allocator.Free(utf8);
    return retval;
#endif
} /* __PHYSFS_platformCalcPrefDir */

char *__PHYSFS_platformCalcUserDir(void)
{
#ifdef PHYSFS_PLATFORM_WINRT
    return calcDirAppendSep((const WCHAR *) __PHYSFS_winrtCalcPrefDir());
#else
    typedef BOOL (WINAPI *fnGetUserProfDirW)(HANDLE, LPWSTR, LPDWORD);
    fnGetUserProfDirW pGetDir = NULL;
    HANDLE lib = NULL;
    HANDLE accessToken = NULL;       /* Security handle to process */
    char *retval = NULL;

    lib = LoadLibraryA("userenv.dll");
    BAIL_IF(!lib, errcodeFromWinApi(), NULL);
    pGetDir=(fnGetUserProfDirW) GetProcAddress(lib,"GetUserProfileDirectoryW");
    GOTO_IF(!pGetDir, errcodeFromWinApi(), done);

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &accessToken))
        GOTO(errcodeFromWinApi(), done);
    else
    {
        DWORD psize = 0;
        WCHAR dummy = 0;
        LPWSTR wstr = NULL;
        BOOL rc = 0;

        /*
         * Should fail. Will write the size of the profile path in
         *  psize. Also note that the second parameter can't be
         *  NULL or the function fails.
         */
        rc = pGetDir(accessToken, &dummy, &psize);
        GOTO_IF(rc, PHYSFS_ERR_OS_ERROR, done);  /* should have failed! */

        /* Allocate memory for the profile directory */
        wstr = (LPWSTR) __PHYSFS_smallAlloc((psize + 1) * sizeof (WCHAR));
        if (wstr != NULL)
        {
            if (pGetDir(accessToken, wstr, &psize))
            {
                /* Make sure it ends in a dirsep. We allocated +1 for this. */
                if (wstr[psize - 2] != '\\')
                {
                    wstr[psize - 1] = '\\';
                    wstr[psize - 0] = '\0';
                } /* if */
                retval = unicodeToUtf8Heap(wstr);
            } /* if */
            __PHYSFS_smallFree(wstr);
        } /* if */
    } /* if */

done:
    if (accessToken)
        CloseHandle(accessToken);
    FreeLibrary(lib);
    return retval;  /* We made it: hit the showers. */
#endif
} /* __PHYSFS_platformCalcUserDir */

int __PHYSFS_platformInit(void)
{
    return 1;  /* It's all good */
} /* __PHYSFS_platformInit */

void __PHYSFS_platformDeinit(void)
{
    deinitCDThread();
} /* __PHYSFS_platformDeinit */

void *__PHYSFS_platformGetThreadID(void)
{
    return ( (void *) ((size_t) GetCurrentThreadId()) );
} /* __PHYSFS_platformGetThreadID */

PHYSFS_EnumerateCallbackResult __PHYSFS_platformEnumerate(const char *dirname,
                               PHYSFS_EnumerateCallback callback,
                               const char *origdir, void *callbackdata)
{
    PHYSFS_EnumerateCallbackResult retval = PHYSFS_ENUM_OK;
    HANDLE dir = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAW entw;
    size_t len = strlen(dirname);
    char *searchPath = NULL;
    WCHAR *wSearchPath = NULL;

    /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
    searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
    BAIL_IF(!searchPath, PHYSFS_ERR_OUT_OF_MEMORY, PHYSFS_ENUM_ERROR);

    /* Copy current dirname */
    strcpy(searchPath, dirname);

    /* if there's no '\\' at the end of the path, stick one in there. */
    if (searchPath[len - 1] != '\\')
    {
        searchPath[len++] = '\\';
        searchPath[len] = '\0';
    } /* if */

    /* Append the "*" to the end of the string */
    strcat(searchPath, "*");

    UTF8_TO_UNICODE_STACK(wSearchPath, searchPath);
    __PHYSFS_smallFree(searchPath);
    BAIL_IF_ERRPASS(!wSearchPath, PHYSFS_ENUM_ERROR);

    dir = winFindFirstFileW(wSearchPath, &entw);
    __PHYSFS_smallFree(wSearchPath);
    BAIL_IF(dir==INVALID_HANDLE_VALUE, errcodeFromWinApi(), PHYSFS_ENUM_ERROR);

    do
    {
        const WCHAR *fn = entw.cFileName;
        char *utf8;

        if (fn[0] == '.')  /* ignore "." and ".." */
        {
            if ((fn[1] == '\0') || ((fn[1] == '.') && (fn[2] == '\0')))
                continue;
        } /* if */

        utf8 = unicodeToUtf8Heap(fn);
        if (utf8 == NULL)
            retval = -1;
        else
        {
            retval = callback(callbackdata, origdir, utf8);
            allocator.Free(utf8);
            if (retval == PHYSFS_ENUM_ERROR)
                PHYSFS_setErrorCode(PHYSFS_ERR_APP_CALLBACK);
        } /* else */
    } while ((retval == PHYSFS_ENUM_OK) && (FindNextFileW(dir, &entw) != 0));

    FindClose(dir);

    return retval;
} /* __PHYSFS_platformEnumerate */

int __PHYSFS_platformMkDir(const char *path)
{
    WCHAR *wpath;
    DWORD rc;
    UTF8_TO_UNICODE_STACK(wpath, path);
    rc = CreateDirectoryW(wpath, NULL);
    __PHYSFS_smallFree(wpath);
    BAIL_IF(rc == 0, errcodeFromWinApi(), 0);
    return 1;
} /* __PHYSFS_platformMkDir */

static HANDLE doOpen(const char *fname, DWORD mode, DWORD creation)
{
    HANDLE fileh;
    WCHAR *wfname;

    UTF8_TO_UNICODE_STACK(wfname, fname);
    BAIL_IF(!wfname, PHYSFS_ERR_OUT_OF_MEMORY, NULL);

    fileh = winCreateFileW(wfname, mode, creation);
    __PHYSFS_smallFree(wfname);

    if (fileh == INVALID_HANDLE_VALUE)
        BAIL(errcodeFromWinApi(), INVALID_HANDLE_VALUE);

    return fileh;
} /* doOpen */

void *__PHYSFS_platformOpenRead(const char *filename)
{
    HANDLE h = doOpen(filename, GENERIC_READ, OPEN_EXISTING);
    return (h == INVALID_HANDLE_VALUE) ? NULL : (void *) h;
} /* __PHYSFS_platformOpenRead */

void *__PHYSFS_platformOpenWrite(const char *filename)
{
    HANDLE h = doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS);
    return (h == INVALID_HANDLE_VALUE) ? NULL : (void *) h;
} /* __PHYSFS_platformOpenWrite */

void *__PHYSFS_platformOpenAppend(const char *filename)
{
    HANDLE h = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS);
    BAIL_IF_ERRPASS(h == INVALID_HANDLE_VALUE, NULL);

    if (!winSetFilePointer(h, 0, NULL, FILE_END))
    {
        const PHYSFS_ErrorCode err = errcodeFromWinApi();
        CloseHandle(h);
        BAIL(err, NULL);
    } /* if */

    return (void *) h;
} /* __PHYSFS_platformOpenAppend */

PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buf, PHYSFS_uint64 len)
{
    HANDLE h = (HANDLE) opaque;
    PHYSFS_sint64 totalRead = 0;

    if (!__PHYSFS_ui64FitsAddressSpace(len))
        BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);

    while (len > 0)
    {
        const DWORD thislen = (len > 0xFFFFFFFF) ? 0xFFFFFFFF : (DWORD) len;
        DWORD numRead = 0;
        if (!ReadFile(h, buf, thislen, &numRead, NULL))
            BAIL(errcodeFromWinApi(), -1);
        len -= (PHYSFS_uint64) numRead;
        totalRead += (PHYSFS_sint64) numRead;
        if (numRead != thislen)
            break;
    } /* while */

    return totalRead;
} /* __PHYSFS_platformRead */

PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
                                     PHYSFS_uint64 len)
{
    HANDLE h = (HANDLE) opaque;
    PHYSFS_sint64 totalWritten = 0;

    if (!__PHYSFS_ui64FitsAddressSpace(len))
        BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);

    while (len > 0)
    {
        const DWORD thislen = (len > 0xFFFFFFFF) ? 0xFFFFFFFF : (DWORD) len;
        DWORD numWritten = 0;
        if (!WriteFile(h, buffer, thislen, &numWritten, NULL))
            BAIL(errcodeFromWinApi(), -1);
        len -= (PHYSFS_uint64) numWritten;
        totalWritten += (PHYSFS_sint64) numWritten;
        if (numWritten != thislen)
            break;
    } /* while */

    return totalWritten;
} /* __PHYSFS_platformWrite */

int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
{
    HANDLE h = (HANDLE) opaque;
    const PHYSFS_sint64 spos = (PHYSFS_sint64) pos;
    BAIL_IF(!winSetFilePointer(h,spos,NULL,FILE_BEGIN), errcodeFromWinApi(), 0);
    return 1;  /* No error occured */
} /* __PHYSFS_platformSeek */

PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
{
    HANDLE h = (HANDLE) opaque;
    PHYSFS_sint64 pos = 0;
    BAIL_IF(!winSetFilePointer(h,0,&pos,FILE_CURRENT), errcodeFromWinApi(), -1);
    return pos;
} /* __PHYSFS_platformTell */

PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
{
    HANDLE h = (HANDLE) opaque;
    const PHYSFS_sint64 retval = winGetFileSize(h);
    BAIL_IF(retval < 0, errcodeFromWinApi(), -1);
    return retval;
} /* __PHYSFS_platformFileLength */

int __PHYSFS_platformFlush(void *opaque)
{
    HANDLE h = (HANDLE) opaque;
    BAIL_IF(!FlushFileBuffers(h), errcodeFromWinApi(), 0);
    return 1;
} /* __PHYSFS_platformFlush */

void __PHYSFS_platformClose(void *opaque)
{
    HANDLE h = (HANDLE) opaque;
    (void) CloseHandle(h); /* ignore errors. You should have flushed! */
} /* __PHYSFS_platformClose */

static int doPlatformDelete(LPWSTR wpath)
{
    WIN32_FILE_ATTRIBUTE_DATA info;
    if (!GetFileAttributesExW(wpath, GetFileExInfoStandard, &info))
        BAIL(errcodeFromWinApi(), 0);
    else
    {
        const int isdir = (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
        const BOOL rc = isdir ? RemoveDirectoryW(wpath) : DeleteFileW(wpath);
        BAIL_IF(!rc, errcodeFromWinApi(), 0);
    } /* else */
    return 1;   /* if you made it here, it worked. */
} /* doPlatformDelete */

int __PHYSFS_platformDelete(const char *path)
{
    int retval = 0;
    LPWSTR wpath = NULL;
    UTF8_TO_UNICODE_STACK(wpath, path);
    BAIL_IF(!wpath, PHYSFS_ERR_OUT_OF_MEMORY, 0);
    retval = doPlatformDelete(wpath);
    __PHYSFS_smallFree(wpath);
    return retval;
} /* __PHYSFS_platformDelete */

void *__PHYSFS_platformCreateMutex(void)
{
    LPCRITICAL_SECTION lpcs;
    lpcs = (LPCRITICAL_SECTION) allocator.Malloc(sizeof (CRITICAL_SECTION));
    BAIL_IF(!lpcs, PHYSFS_ERR_OUT_OF_MEMORY, NULL);

    if (!winInitializeCriticalSection(lpcs))
    {
        allocator.Free(lpcs);
        BAIL(errcodeFromWinApi(), NULL);
    } /* if */

    return lpcs;
} /* __PHYSFS_platformCreateMutex */

void __PHYSFS_platformDestroyMutex(void *mutex)
{
    DeleteCriticalSection((LPCRITICAL_SECTION) mutex);
    allocator.Free(mutex);
} /* __PHYSFS_platformDestroyMutex */

int __PHYSFS_platformGrabMutex(void *mutex)
{
    EnterCriticalSection((LPCRITICAL_SECTION) mutex);
    return 1;
} /* __PHYSFS_platformGrabMutex */

void __PHYSFS_platformReleaseMutex(void *mutex)
{
    LeaveCriticalSection((LPCRITICAL_SECTION) mutex);
} /* __PHYSFS_platformReleaseMutex */

static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
{
    SYSTEMTIME st_utc;
    SYSTEMTIME st_localtz;
    TIME_ZONE_INFORMATION tzi;
    DWORD tzid;
    PHYSFS_sint64 retval;
    struct tm tm;
    BOOL rc;

    BAIL_IF(!FileTimeToSystemTime(ft, &st_utc), errcodeFromWinApi(), -1);
    tzid = GetTimeZoneInformation(&tzi);
    BAIL_IF(tzid == TIME_ZONE_ID_INVALID, errcodeFromWinApi(), -1);
    rc = SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz);
    BAIL_IF(!rc, errcodeFromWinApi(), -1);

    /* Convert to a format that mktime() can grok... */
    tm.tm_sec = st_localtz.wSecond;
    tm.tm_min = st_localtz.wMinute;
    tm.tm_hour = st_localtz.wHour;
    tm.tm_mday = st_localtz.wDay;
    tm.tm_mon = st_localtz.wMonth - 1;
    tm.tm_year = st_localtz.wYear - 1900;
    tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
    tm.tm_yday = -1;
    tm.tm_isdst = -1;

    /* Convert to a format PhysicsFS can grok... */
    retval = (PHYSFS_sint64) mktime(&tm);
    BAIL_IF(retval == -1, PHYSFS_ERR_OS_ERROR, -1);
    return retval;
} /* FileTimeToPhysfsTime */

/* check for symlinks. These exist in NTFS 3.1 (WinXP), even though
   they aren't really available to userspace before Vista. I wonder
   what would happen if you put an NTFS disk with a symlink on it
   into an XP machine, though; would this flag get set?
   NTFS symlinks are a form of "reparse point" (junction, volume mount,
   etc), so if the REPARSE_POINT attribute is set, check for the symlink
   tag thereafter. This assumes you already read in the file attributes. */
static int isSymlink(const WCHAR *wpath, const DWORD attr)
{
    WIN32_FIND_DATAW w32dw;
    HANDLE h;

    if ((attr & PHYSFS_FILE_ATTRIBUTE_REPARSE_POINT) == 0)
        return 0;  /* not a reparse point? Definitely not a symlink. */

    h = winFindFirstFileW(wpath, &w32dw);
    if (h == INVALID_HANDLE_VALUE)
        return 0;  /* ...maybe the file just vanished...? */

    FindClose(h);
    return (w32dw.dwReserved0 == PHYSFS_IO_REPARSE_TAG_SYMLINK);
} /* isSymlink */

int __PHYSFS_platformStat(const char *filename, PHYSFS_Stat *st, const int follow)
{
    WIN32_FILE_ATTRIBUTE_DATA winstat;
    WCHAR *wstr = NULL;
    DWORD err = 0;
    BOOL rc = 0;
    int issymlink = 0;

    UTF8_TO_UNICODE_STACK(wstr, filename);
    BAIL_IF(!wstr, PHYSFS_ERR_OUT_OF_MEMORY, 0);
    rc = GetFileAttributesExW(wstr, GetFileExInfoStandard, &winstat);

    if (!rc)
        err = GetLastError();
    else  /* check for symlink while wstr is still available */
        issymlink = !follow && isSymlink(wstr, winstat.dwFileAttributes);

    __PHYSFS_smallFree(wstr);
    BAIL_IF(!rc, errcodeFromWinApiError(err), 0);

    st->modtime = FileTimeToPhysfsTime(&winstat.ftLastWriteTime);
    st->accesstime = FileTimeToPhysfsTime(&winstat.ftLastAccessTime);
    st->createtime = FileTimeToPhysfsTime(&winstat.ftCreationTime);

    if (issymlink)
    {
        st->filetype = PHYSFS_FILETYPE_SYMLINK;
        st->filesize = 0;
    } /* if */

    else if (winstat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
        st->filetype = PHYSFS_FILETYPE_DIRECTORY;
        st->filesize = 0;
    } /* else if */

    else if (winstat.dwFileAttributes & (FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_DEVICE))
    {
        st->filetype = PHYSFS_FILETYPE_OTHER;
        st->filesize = (((PHYSFS_uint64) winstat.nFileSizeHigh) << 32) | winstat.nFileSizeLow;
    } /* else if */

    else
    {
        st->filetype = PHYSFS_FILETYPE_REGULAR;
        st->filesize = (((PHYSFS_uint64) winstat.nFileSizeHigh) << 32) | winstat.nFileSizeLow;
    } /* else */

    st->readonly = ((winstat.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);

    return 1;
} /* __PHYSFS_platformStat */

#endif  /* PHYSFS_PLATFORM_WINDOWS */

/* end of physfs_platform_windows.c ... */


text:
import unittest
import mock

try:
    # this test requires the dnspython package to be installed
    import dns.resolver  # noqa
    import dns.exception
except ImportError:
    skip = True
else:  # executed if the try has no errors
    skip = False
from swift.common import registry
from swift.common.middleware import cname_lookup
from swift.common.swob import Request, HTTPMovedPermanently

class FakeApp(object):

    def __call__(self, env, start_response):
        start_response('200 OK', [])
        return [b"FAKE APP"]

class RedirectSlashApp(object):

    def __call__(self, env, start_response):
        loc = env['PATH_INFO'] + '/'
        return HTTPMovedPermanently(location=loc)(env, start_response)

def start_response(*args):
    pass

class TestCNAMELookup(unittest.TestCase):

    @unittest.skipIf(skip, "can't import dnspython")
    def setUp(self):
        self.app = cname_lookup.CNAMELookupMiddleware(FakeApp(),
                                                      {'lookup_depth': 2})

    def test_pass_ip_addresses(self):
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': '10.134.23.198'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])

        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'fc00:7ea1:f155::6321:8841'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])

    @mock.patch('swift.common.middleware.cname_lookup.lookup_cname',
                new=lambda d, r: (0, d))
    def test_passthrough(self):
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'foo.example.com'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'foo.example.com:8080'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'SERVER_NAME': 'foo.example.com'},
                            headers={'Host': None})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])

    @mock.patch('swift.common.middleware.cname_lookup.lookup_cname',
                new=lambda d, r: (0, '%s.example.com' % d))
    def test_good_lookup(self):
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'mysite.com'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'mysite.com:8080'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'SERVER_NAME': 'mysite.com'},
                            headers={'Host': None})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])

    def test_lookup_chain_too_long(self):
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'mysite.com'})

        def my_lookup(d, r):
            if d == 'mysite.com':
                site = 'level1.foo.com'
            elif d == 'level1.foo.com':
                site = 'level2.foo.com'
            elif d == 'level2.foo.com':
                site = 'bar.example.com'
            return 0, site

        with mock.patch('swift.common.middleware.cname_lookup.lookup_cname',
                        new=my_lookup):
            resp = self.app(req.environ, start_response)
            self.assertEqual(resp, [b'CNAME lookup failed after 2 tries'])

    @mock.patch('swift.common.middleware.cname_lookup.lookup_cname',
                new=lambda d, r: (0, 'some.invalid.site.com'))
    def test_lookup_chain_bad_target(self):
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'mysite.com'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp,
                         [b'CNAME lookup failed to resolve to a valid domain'])

    @mock.patch('swift.common.middleware.cname_lookup.lookup_cname',
                new=lambda d, r: (0, None))
    def test_something_weird(self):
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'mysite.com'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp,
                         [b'CNAME lookup failed to resolve to a valid domain'])

    @mock.patch('swift.common.middleware.cname_lookup.lookup_cname',
                new=lambda d, r: (0, '%s.example.com' % d))
    def test_with_memcache(self):
        class memcache_stub(object):
            def __init__(self):
                self.cache = {}

            def get(self, key):
                return self.cache.get(key, None)

            def set(self, key, value, *a, **kw):
                self.cache[key] = value
        memcache = memcache_stub()
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'swift.cache': memcache},
                            headers={'Host': 'mysite.com'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                          'swift.cache': memcache},
                            headers={'Host': 'mysite.com'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])

    def test_caching(self):
        fail_to_resolve = [b'CNAME lookup failed to resolve to a valid domain']

        class memcache_stub(object):
            def __init__(self):
                self.cache = {}

            def get(self, key):
                return self.cache.get(key, None)

            def set(self, key, value, *a, **kw):
                # real memcache client will JSON-serialize, so our mock
                # should be sure to return unicode
                if isinstance(value, bytes):
                    value = value.decode('utf-8')
                self.cache[key] = value

        module = 'swift.common.middleware.cname_lookup.lookup_cname'
        dns_module = 'dns.resolver.Resolver.query'
        memcache = memcache_stub()

        with mock.patch(module) as m:
            m.return_value = (3600, 'c.example.com')
            req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                              'swift.cache': memcache},
                                headers={'Host': 'mysite2.com'})
            resp = self.app(req.environ, start_response)
            self.assertEqual(resp, [b'FAKE APP'])
            self.assertEqual(m.call_count, 1)
            self.assertEqual(memcache.cache.get('cname-mysite2.com'),
                             'c.example.com')
            self.assertIsInstance(req.environ['HTTP_HOST'], str)
            self.assertEqual(req.environ['HTTP_HOST'], 'c.example.com')

            req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                              'swift.cache': memcache},
                                headers={'Host': 'mysite2.com'})
            resp = self.app(req.environ, start_response)
            self.assertEqual(resp, [b'FAKE APP'])
            self.assertEqual(m.call_count, 1)
            self.assertEqual(memcache.cache.get('cname-mysite2.com'),
                             'c.example.com')
            self.assertIsInstance(req.environ['HTTP_HOST'], str)
            self.assertEqual(req.environ['HTTP_HOST'], 'c.example.com')

        for exc, num in ((dns.resolver.NXDOMAIN(), 3),
                         (dns.resolver.NoAnswer(), 4)):
            with mock.patch(dns_module) as m:
                m.side_effect = exc
                req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                                  'swift.cache': memcache},
                                    headers={'Host': 'mysite%d.com' % num})
                resp = self.app(req.environ, start_response)
                self.assertEqual(resp, fail_to_resolve)
                self.assertEqual(m.call_count, 1)
                self.assertEqual(memcache.cache.get('cname-mysite3.com'),
                                 False)
                req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                                  'swift.cache': memcache},
                                    headers={'Host': 'mysite%d.com' % num})
                resp = self.app(req.environ, start_response)
                self.assertEqual(resp, fail_to_resolve)
                self.assertEqual(m.call_count, 1)
                self.assertEqual(
                    memcache.cache.get('cname-mysite%d.com' % num), False)

        with mock.patch(dns_module) as m:
            m.side_effect = dns.exception.DNSException()
            req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                              'swift.cache': memcache},
                                headers={'Host': 'mysite5.com'})
            resp = self.app(req.environ, start_response)
            self.assertEqual(resp, fail_to_resolve)
            self.assertEqual(m.call_count, 1)
            self.assertFalse('cname-mysite5.com' in memcache.cache)
            req = Request.blank('/', environ={'REQUEST_METHOD': 'GET',
                                              'swift.cache': memcache},
                                headers={'Host': 'mysite5.com'})
            resp = self.app(req.environ, start_response)
            self.assertEqual(resp, fail_to_resolve)
            self.assertEqual(m.call_count, 2)
            self.assertFalse('cname-mysite5.com' in memcache.cache)

    @mock.patch('swift.common.middleware.cname_lookup.lookup_cname',
                new=lambda d, r: (0, 'c.aexample.com'))
    def test_cname_matching_ending_not_domain(self):
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'foo.com'})
        resp = self.app(req.environ, start_response)
        self.assertEqual(resp,
                         [b'CNAME lookup failed to resolve to a valid domain'])

    @mock.patch('swift.common.middleware.cname_lookup.lookup_cname',
                new=lambda d, r: (0, None))
    def test_cname_configured_with_empty_storage_domain(self):
        app = cname_lookup.CNAMELookupMiddleware(FakeApp(),
                                                 {'storage_domain': '',
                                                  'lookup_depth': 2})
        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'c.a.example.com'})
        resp = app(req.environ, start_response)
        self.assertEqual(resp, [b'FAKE APP'])

    def test_storage_domains_conf_format(self):
        conf = {'storage_domain': 'foo.com'}
        app = cname_lookup.filter_factory(conf)(FakeApp())
        self.assertEqual(app.storage_domain, ['.foo.com'])

        conf = {'storage_domain': 'foo.com, '}
        app = cname_lookup.filter_factory(conf)(FakeApp())
        self.assertEqual(app.storage_domain, ['.foo.com'])

        conf = {'storage_domain': 'foo.com, bar.com'}
        app = cname_lookup.filter_factory(conf)(FakeApp())
        self.assertEqual(app.storage_domain, ['.foo.com', '.bar.com'])

        conf = {'storage_domain': 'foo.com, .bar.com'}
        app = cname_lookup.filter_factory(conf)(FakeApp())
        self.assertEqual(app.storage_domain, ['.foo.com', '.bar.com'])

        conf = {'storage_domain': '.foo.com, .bar.com'}
        app = cname_lookup.filter_factory(conf)(FakeApp())
        self.assertEqual(app.storage_domain, ['.foo.com', '.bar.com'])

    def test_multiple_storage_domains(self):
        conf = {'storage_domain': 'storage1.com, storage2.com',
                'lookup_depth': 2}
        app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)

        def do_test(lookup_back):
            req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                                headers={'Host': 'c.a.example.com'})
            module = 'swift.common.middleware.cname_lookup.lookup_cname'
            with mock.patch(module, lambda d, r: (0, lookup_back)):
                return app(req.environ, start_response)

        resp = do_test('c.storage1.com')
        self.assertEqual(resp, [b'FAKE APP'])

        resp = do_test('c.storage2.com')
        self.assertEqual(resp, [b'FAKE APP'])

        bad_domain = [b'CNAME lookup failed to resolve to a valid domain']
        resp = do_test('c.badtest.com')
        self.assertEqual(resp, bad_domain)

    @mock.patch('dns.resolver.Resolver.query',
                side_effect=dns.exception.DNSException)
    def test_host_is_storage_domain(self, mock_lookup):
        conf = {'storage_domain': 'storage.example.com',
                'lookup_depth': 2}
        app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)

        def do_test(host):
            req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                                headers={'Host': host})
            return app(req.environ, start_response)

        bad_domain = [b'CNAME lookup failed to resolve to a valid domain']
        resp = do_test('c.badtest.com')
        self.assertEqual(resp, bad_domain)
        self.assertEqual(1, len(mock_lookup.mock_calls))
        mock_lookup.reset_mock()

        resp = do_test('storage.example.com')
        self.assertEqual(resp, [b'FAKE APP'])
        self.assertEqual(0, len(mock_lookup.mock_calls))

    def test_resolution_to_storage_domain_exactly(self):
        conf = {'storage_domain': 'example.com',
                'lookup_depth': 1}
        app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)

        req = Request.blank('/', environ={'REQUEST_METHOD': 'GET'},
                            headers={'Host': 'mysite.com'})
        module = 'swift.common.middleware.cname_lookup.lookup_cname'
        with mock.patch(module, lambda d, r: (0, 'example.com')):
            resp = app(req.environ, start_response)
            self.assertEqual(resp, [b'FAKE APP'])

    def test_redirect(self):
        app = cname_lookup.CNAMELookupMiddleware(RedirectSlashApp(), {})

        module = 'swift.common.middleware.cname_lookup.lookup_cname'
        with mock.patch(module, lambda d, r: (0, 'cont.acct.example.com')):
            req = Request.blank('/test', environ={'REQUEST_METHOD': 'GET'},
                                headers={'Host': 'mysite.com'})
            resp = req.get_response(app)
            self.assertEqual(resp.status_int, 301)
            self.assertEqual(resp.headers.get('Location'),
                             'http://mysite.com/test/')

    def test_configured_nameservers(self):
        class MockedResolver(object):
            def __init__(self):
                self.nameservers = None
                self.nameserver_ports = None

            def query(self, *args, **kwargs):
                raise Exception('Stop processing')

            def reset(self):
                self.nameservers = None
                self.nameserver_ports = None

        mocked_resolver = MockedResolver()
        dns_module = 'dns.resolver.Resolver'

        # If no nameservers provided in conf, resolver nameservers is unset
        for conf in [{}, {'nameservers': ''}]:
            mocked_resolver.reset()
            with mock.patch(dns_module, return_value=mocked_resolver):
                app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)
            self.assertIs(app.resolver, mocked_resolver)
            self.assertIsNone(mocked_resolver.nameservers)

        # If invalid nameservers provided, resolver nameservers is unset
        mocked_resolver.reset()
        conf = {'nameservers': '127.0.0.1, 127.0.0.2, a.b.c.d'}
        with mock.patch(dns_module, return_value=mocked_resolver):
            with self.assertRaises(ValueError) as exc_mgr:
                app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)
            self.assertIn('Invalid cname_lookup/nameservers configuration',
                          str(exc_mgr.exception))

        # If nameservers provided in conf, resolver nameservers is set
        mocked_resolver.reset()
        conf = {'nameservers': '127.0.0.1'}
        with mock.patch(dns_module, return_value=mocked_resolver):
            app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)
        self.assertIs(app.resolver, mocked_resolver)
        self.assertEqual(mocked_resolver.nameservers, ['127.0.0.1'])
        self.assertEqual(mocked_resolver.nameserver_ports, {})

        # IPv6 is OK
        mocked_resolver.reset()
        conf = {'nameservers': '[::1]'}
        with mock.patch(dns_module, return_value=mocked_resolver):
            app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)
        self.assertIs(app.resolver, mocked_resolver)
        self.assertEqual(mocked_resolver.nameservers, ['::1'])
        self.assertEqual(mocked_resolver.nameserver_ports, {})

        # As are port overrides
        mocked_resolver.reset()
        conf = {'nameservers': '127.0.0.1:5354'}
        with mock.patch(dns_module, return_value=mocked_resolver):
            app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)
        self.assertIs(app.resolver, mocked_resolver)
        self.assertEqual(mocked_resolver.nameservers, ['127.0.0.1'])
        self.assertEqual(mocked_resolver.nameserver_ports, {'127.0.0.1': 5354})

        # And IPv6 with port overrides
        mocked_resolver.reset()
        conf = {'nameservers': '[2001:db8::ff00:42:8329]:1234'}
        with mock.patch(dns_module, return_value=mocked_resolver):
            app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)
        self.assertIs(app.resolver, mocked_resolver)
        self.assertEqual(mocked_resolver.nameservers, [
            '2001:db8::ff00:42:8329'])
        self.assertEqual(mocked_resolver.nameserver_ports, {
            '2001:db8::ff00:42:8329': 1234})

        # Also accept lists, and bring it all together
        mocked_resolver.reset()
        conf = {'nameservers': '[::1], 127.0.0.1:5354, '
                               '[2001:db8::ff00:42:8329]:1234'}
        with mock.patch(dns_module, return_value=mocked_resolver):
            app = cname_lookup.CNAMELookupMiddleware(FakeApp(), conf)
        self.assertIs(app.resolver, mocked_resolver)
        self.assertEqual(mocked_resolver.nameservers, [
            '::1', '127.0.0.1', '2001:db8::ff00:42:8329'])
        self.assertEqual(mocked_resolver.nameserver_ports, {
            '127.0.0.1': 5354, '2001:db8::ff00:42:8329': 1234})

class TestSwiftInfo(unittest.TestCase):
    def setUp(self):
        registry._swift_info = {}
        registry._swift_admin_info = {}

    def test_registered_defaults(self):
        cname_lookup.filter_factory({})
        swift_info = registry.get_swift_info()
        self.assertIn('cname_lookup', swift_info)
        self.assertEqual(swift_info['cname_lookup'].get('lookup_depth'), 1)

    def test_registered_nondefaults(self):
        cname_lookup.filter_factory({'lookup_depth': '2'})
        swift_info = registry.get_swift_info()
        self.assertIn('cname_lookup', swift_info)
        self.assertEqual(swift_info['cname_lookup'].get('lookup_depth'), 2)


text:
<?php

/** Error reporting */
error_reporting(E_ALL);

/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');

/** PHPExcel */
include 'PHPExcel.php';

/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';

// Create new PHPExcel object
echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();

// Set properties
echo date('H:i:s') . " Set properties\n";
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
$objPHPExcel->getProperties()->setKeywords("office 2007 openxml php");
$objPHPExcel->getProperties()->setCategory("Test result file");

// Create a first sheet
echo date('H:i:s') . " Add data\n";
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', "Quarter");
$objPHPExcel->getActiveSheet()->setCellValue('B1', "Country");
$objPHPExcel->getActiveSheet()->setCellValue('C1', "Sales");

$objPHPExcel->getActiveSheet()->setCellValue('A2', "Q1");
$objPHPExcel->getActiveSheet()->setCellValue('B2', "United States");
$objPHPExcel->getActiveSheet()->setCellValue('C2', "800");
$objPHPExcel->getActiveSheet()->setCellValue('A3', "Q2");
$objPHPExcel->getActiveSheet()->setCellValue('B3', "United States");
$objPHPExcel->getActiveSheet()->setCellValue('C3', "700");
$objPHPExcel->getActiveSheet()->setCellValue('A4', "Q3");
$objPHPExcel->getActiveSheet()->setCellValue('B4', "United States");
$objPHPExcel->getActiveSheet()->setCellValue('C4', "900");
$objPHPExcel->getActiveSheet()->setCellValue('A5', "Q4");
$objPHPExcel->getActiveSheet()->setCellValue('B5', "United States");
$objPHPExcel->getActiveSheet()->setCellValue('C5', "950");
$objPHPExcel->getActiveSheet()->setCellValue('A6', "Q1");
$objPHPExcel->getActiveSheet()->setCellValue('B6', "Belgium");
$objPHPExcel->getActiveSheet()->setCellValue('C6', "400");
$objPHPExcel->getActiveSheet()->setCellValue('A7', "Q2");
$objPHPExcel->getActiveSheet()->setCellValue('B7', "Belgium");
$objPHPExcel->getActiveSheet()->setCellValue('C7', "350");
$objPHPExcel->getActiveSheet()->setCellValue('A8', "Q3");
$objPHPExcel->getActiveSheet()->setCellValue('B8', "Belgium");
$objPHPExcel->getActiveSheet()->setCellValue('C8', "450");
$objPHPExcel->getActiveSheet()->setCellValue('A9', "Q4");
$objPHPExcel->getActiveSheet()->setCellValue('B9', "Belgium");
$objPHPExcel->getActiveSheet()->setCellValue('C9', "500");

// Set title row bold
echo date('H:i:s') . " Set title row bold\n";
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C1')->getFont()->setBold(true);

// Set autofilter
echo date('H:i:s') . " Set autofilter\n";
$objPHPExcel->getActiveSheet()->setAutoFilter('A1:C9');	// Always include the complete filter range!
														// Excel does support setting only the caption
														// row, but that's not a best practise...

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

// Save Excel 2007 file
echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));

// Echo memory peak usage
echo date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";

// Echo done
echo date('H:i:s') . " Done writing file.\r\n";