repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
Heathckliff/cantera | src/thermo/IdealSolidSolnPhase.cpp | 17406 | /**
* @file IdealSolidSolnPhase.cpp Implementation file for an ideal solid
* solution model with incompressible thermodynamics (see \ref
* thermoprops and \link Cantera::IdealSolidSolnPhase
* IdealSolidSolnPhase\endlink).
*/
/*
* Copyright 2006 Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000, with Sandia Corporation, the U.S. Government
* retains certain rights in this software.
*/
#include "cantera/thermo/IdealSolidSolnPhase.h"
#include "cantera/thermo/ThermoFactory.h"
#include "cantera/base/stringUtils.h"
#include "cantera/base/ctml.h"
#include "cantera/base/utilities.h"
using namespace std;
namespace Cantera
{
IdealSolidSolnPhase::IdealSolidSolnPhase(int formGC) :
m_formGC(formGC),
m_Pref(OneAtm),
m_Pcurrent(OneAtm)
{
if (formGC < 0 || formGC > 2) {
throw CanteraError(" IdealSolidSolnPhase Constructor",
" Illegal value of formGC");
}
}
IdealSolidSolnPhase::IdealSolidSolnPhase(const std::string& inputFile,
const std::string& id_, int formGC) :
m_formGC(formGC),
m_Pref(OneAtm),
m_Pcurrent(OneAtm)
{
if (formGC < 0 || formGC > 2) {
throw CanteraError(" IdealSolidSolnPhase Constructor",
" Illegal value of formGC");
}
initThermoFile(inputFile, id_);
}
IdealSolidSolnPhase::IdealSolidSolnPhase(XML_Node& root, const std::string& id_,
int formGC) :
m_formGC(formGC),
m_Pref(OneAtm),
m_Pcurrent(OneAtm)
{
if (formGC < 0 || formGC > 2) {
throw CanteraError(" IdealSolidSolnPhase Constructor",
" Illegal value of formGC");
}
importPhase(root, this);
}
IdealSolidSolnPhase::IdealSolidSolnPhase(const IdealSolidSolnPhase& b)
{
*this = b;
}
IdealSolidSolnPhase& IdealSolidSolnPhase::operator=(const IdealSolidSolnPhase& b)
{
if (this != &b) {
ThermoPhase::operator=(b);
m_formGC = b.m_formGC;
m_Pref = b.m_Pref;
m_Pcurrent = b.m_Pcurrent;
m_speciesMolarVolume = b.m_speciesMolarVolume;
m_h0_RT = b.m_h0_RT;
m_cp0_R = b.m_cp0_R;
m_g0_RT = b.m_g0_RT;
m_s0_R = b.m_s0_R;
m_expg0_RT = b.m_expg0_RT;
m_pe = b.m_pe;
m_pp = b.m_pp;
}
return *this;
}
ThermoPhase* IdealSolidSolnPhase::duplMyselfAsThermoPhase() const
{
return new IdealSolidSolnPhase(*this);
}
int IdealSolidSolnPhase::eosType() const
{
integer res;
switch (m_formGC) {
case 0:
res = cIdealSolidSolnPhase0;
break;
case 1:
res = cIdealSolidSolnPhase1;
break;
case 2:
res = cIdealSolidSolnPhase2;
break;
default:
throw CanteraError("eosType", "Unknown type");
break;
}
return res;
}
/********************************************************************
* Molar Thermodynamic Properties of the Solution
********************************************************************/
doublereal IdealSolidSolnPhase::enthalpy_mole() const
{
doublereal htp = GasConstant * temperature() * mean_X(enthalpy_RT_ref());
return htp + (pressure() - m_Pref)/molarDensity();
}
doublereal IdealSolidSolnPhase::entropy_mole() const
{
return GasConstant * (mean_X(entropy_R_ref()) - sum_xlogx());
}
doublereal IdealSolidSolnPhase::gibbs_mole() const
{
return GasConstant * temperature() * (mean_X(gibbs_RT_ref()) + sum_xlogx());
}
doublereal IdealSolidSolnPhase::cp_mole() const
{
return GasConstant * mean_X(cp_R_ref());
}
/********************************************************************
* Mechanical Equation of State
********************************************************************/
void IdealSolidSolnPhase::calcDensity()
{
/*
* Calculate the molarVolume of the solution (m**3 kmol-1)
*/
const doublereal* const dtmp = moleFractdivMMW();
double invDens = dot(m_speciesMolarVolume.begin(),
m_speciesMolarVolume.end(), dtmp);
/*
* Set the density in the parent State object directly,
* by calling the Phase::setDensity() function.
*/
Phase::setDensity(1.0/invDens);
}
void IdealSolidSolnPhase::setDensity(const doublereal rho)
{
/*
* Unless the input density is exactly equal to the density
* calculated and stored in the State object, we throw an
* exception. This is because the density is NOT an
* independent variable.
*/
if (rho != density()) {
throw CanteraError("IdealSolidSolnPhase::setDensity",
"Density is not an independent variable");
}
}
void IdealSolidSolnPhase::setPressure(doublereal p)
{
m_Pcurrent = p;
calcDensity();
}
void IdealSolidSolnPhase::setMolarDensity(const doublereal n)
{
throw CanteraError("IdealSolidSolnPhase::setMolarDensity",
"Density is not an independent variable");
}
void IdealSolidSolnPhase::setMoleFractions(const doublereal* const x)
{
Phase::setMoleFractions(x);
calcDensity();
}
void IdealSolidSolnPhase::setMoleFractions_NoNorm(const doublereal* const x)
{
Phase::setMoleFractions(x);
calcDensity();
}
void IdealSolidSolnPhase::setMassFractions(const doublereal* const y)
{
Phase::setMassFractions(y);
calcDensity();
}
void IdealSolidSolnPhase::setMassFractions_NoNorm(const doublereal* const y)
{
Phase::setMassFractions_NoNorm(y);
calcDensity();
}
void IdealSolidSolnPhase::setConcentrations(const doublereal* const c)
{
Phase::setConcentrations(c);
calcDensity();
}
/********************************************************************
* Chemical Potentials and Activities
********************************************************************/
void IdealSolidSolnPhase::getActivityConcentrations(doublereal* c) const
{
const doublereal* const dtmp = moleFractdivMMW();
const double mmw = meanMolecularWeight();
switch (m_formGC) {
case 0:
for (size_t k = 0; k < m_kk; k++) {
c[k] = dtmp[k] * mmw;
}
break;
case 1:
for (size_t k = 0; k < m_kk; k++) {
c[k] = dtmp[k] * mmw / m_speciesMolarVolume[k];
}
break;
case 2:
double atmp = mmw / m_speciesMolarVolume[m_kk-1];
for (size_t k = 0; k < m_kk; k++) {
c[k] = dtmp[k] * atmp;
}
break;
}
}
doublereal IdealSolidSolnPhase::standardConcentration(size_t k) const
{
switch (m_formGC) {
case 0:
return 1.0;
case 1:
return 1.0 / m_speciesMolarVolume[k];
case 2:
return 1.0/m_speciesMolarVolume[m_kk-1];
}
return 0.0;
}
doublereal IdealSolidSolnPhase::referenceConcentration(int k) const
{
switch (m_formGC) {
case 0:
return 1.0;
case 1:
return 1.0 / m_speciesMolarVolume[k];
case 2:
return 1.0 / m_speciesMolarVolume[m_kk-1];
}
return 0.0;
}
doublereal IdealSolidSolnPhase::logStandardConc(size_t k) const
{
_updateThermo();
double res;
switch (m_formGC) {
case 0:
res = 0.0;
break;
case 1:
res = log(1.0/m_speciesMolarVolume[k]);
break;
case 2:
res = log(1.0/m_speciesMolarVolume[m_kk-1]);
break;
default:
throw CanteraError("eosType", "Unknown type");
break;
}
return res;
}
void IdealSolidSolnPhase::getActivityCoefficients(doublereal* ac) const
{
for (size_t k = 0; k < m_kk; k++) {
ac[k] = 1.0;
}
}
void IdealSolidSolnPhase::getChemPotentials(doublereal* mu) const
{
doublereal delta_p = m_Pcurrent - m_Pref;
const vector_fp& g_RT = gibbs_RT_ref();
for (size_t k = 0; k < m_kk; k++) {
double xx = std::max(SmallNumber, moleFraction(k));
mu[k] = RT() * (g_RT[k] + log(xx))
+ delta_p * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getChemPotentials_RT(doublereal* mu) const
{
doublereal delta_pdRT = (m_Pcurrent - m_Pref) / (temperature() * GasConstant);
const vector_fp& g_RT = gibbs_RT_ref();
for (size_t k = 0; k < m_kk; k++) {
double xx = std::max(SmallNumber, moleFraction(k));
mu[k] = (g_RT[k] + log(xx))
+ delta_pdRT * m_speciesMolarVolume[k];
}
}
/********************************************************************
* Partial Molar Properties
********************************************************************/
void IdealSolidSolnPhase::getPartialMolarEnthalpies(doublereal* hbar) const
{
const vector_fp& _h = enthalpy_RT_ref();
scale(_h.begin(), _h.end(), hbar, GasConstant * temperature());
}
void IdealSolidSolnPhase::getPartialMolarEntropies(doublereal* sbar) const
{
const vector_fp& _s = entropy_R_ref();
for (size_t k = 0; k < m_kk; k++) {
double xx = std::max(SmallNumber, moleFraction(k));
sbar[k] = GasConstant * (_s[k] - log(xx));
}
}
void IdealSolidSolnPhase::getPartialMolarCp(doublereal* cpbar) const
{
getCp_R(cpbar);
for (size_t k = 0; k < m_kk; k++) {
cpbar[k] *= GasConstant;
}
}
void IdealSolidSolnPhase::getPartialMolarVolumes(doublereal* vbar) const
{
getStandardVolumes(vbar);
}
/*****************************************************************
* Properties of the Standard State of the Species in the Solution
*****************************************************************/
void IdealSolidSolnPhase::getPureGibbs(doublereal* gpure) const
{
const vector_fp& gibbsrt = gibbs_RT_ref();
const doublereal* const gk = DATA_PTR(gibbsrt);
doublereal delta_p = (m_Pcurrent - m_Pref);
for (size_t k = 0; k < m_kk; k++) {
gpure[k] = RT() * gk[k] + delta_p * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getGibbs_RT(doublereal* grt) const
{
const vector_fp& gibbsrt = gibbs_RT_ref();
const doublereal* const gk = DATA_PTR(gibbsrt);
doublereal delta_prt = (m_Pcurrent - m_Pref)/ RT();
for (size_t k = 0; k < m_kk; k++) {
grt[k] = gk[k] + delta_prt * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getEnthalpy_RT(doublereal* hrt) const
{
const vector_fp& _h = enthalpy_RT_ref();
doublereal delta_prt = (m_Pcurrent - m_Pref) / RT();
for (size_t k = 0; k < m_kk; k++) {
hrt[k] = _h[k] + delta_prt * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getEntropy_R(doublereal* sr) const
{
const vector_fp& _s = entropy_R_ref();
copy(_s.begin(), _s.end(), sr);
}
void IdealSolidSolnPhase::getIntEnergy_RT(doublereal* urt) const
{
const vector_fp& _h = enthalpy_RT_ref();
doublereal prefrt = m_Pref / (GasConstant * temperature());
for (size_t k = 0; k < m_kk; k++) {
urt[k] = _h[k] - prefrt * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getCp_R(doublereal* cpr) const
{
const vector_fp& _cpr = cp_R_ref();
copy(_cpr.begin(), _cpr.end(), cpr);
}
void IdealSolidSolnPhase::getStandardVolumes(doublereal* vol) const
{
copy(m_speciesMolarVolume.begin(), m_speciesMolarVolume.end(), vol);
}
/*********************************************************************
* Thermodynamic Values for the Species Reference States
*********************************************************************/
void IdealSolidSolnPhase::getEnthalpy_RT_ref(doublereal* hrt) const
{
_updateThermo();
for (size_t k = 0; k != m_kk; k++) {
hrt[k] = m_h0_RT[k];
}
}
void IdealSolidSolnPhase::getGibbs_RT_ref(doublereal* grt) const
{
_updateThermo();
for (size_t k = 0; k != m_kk; k++) {
grt[k] = m_g0_RT[k];
}
}
void IdealSolidSolnPhase::getGibbs_ref(doublereal* g) const
{
_updateThermo();
double tmp = GasConstant * temperature();
for (size_t k = 0; k != m_kk; k++) {
g[k] = tmp * m_g0_RT[k];
}
}
void IdealSolidSolnPhase::getIntEnergy_RT_ref(doublereal* urt) const
{
const vector_fp& _h = enthalpy_RT_ref();
doublereal prefrt = m_Pref / (GasConstant * temperature());
for (size_t k = 0; k < m_kk; k++) {
urt[k] = _h[k] - prefrt * m_speciesMolarVolume[k];
}
}
void IdealSolidSolnPhase::getEntropy_R_ref(doublereal* er) const
{
_updateThermo();
for (size_t k = 0; k != m_kk; k++) {
er[k] = m_s0_R[k];
}
}
void IdealSolidSolnPhase::getCp_R_ref(doublereal* cpr) const
{
_updateThermo();
for (size_t k = 0; k != m_kk; k++) {
cpr[k] = m_cp0_R[k];
}
}
const vector_fp& IdealSolidSolnPhase::enthalpy_RT_ref() const
{
_updateThermo();
return m_h0_RT;
}
const vector_fp& IdealSolidSolnPhase::entropy_R_ref() const
{
_updateThermo();
return m_s0_R;
}
/*********************************************************************
* Utility Functions
*********************************************************************/
void IdealSolidSolnPhase::initThermoXML(XML_Node& phaseNode, const std::string& id_)
{
if (id_.size() > 0 && phaseNode.id() != id_) {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"phasenode and Id are incompatible");
}
/*
* Check on the thermo field. Must have:
* <thermo model="IdealSolidSolution" />
*/
if (phaseNode.hasChild("thermo")) {
XML_Node& thNode = phaseNode.child("thermo");
string mString = thNode.attrib("model");
if (lowercase(mString) != "idealsolidsolution") {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"Unknown thermo model: " + mString);
}
} else {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"Unspecified thermo model");
}
/*
* Form of the standard concentrations. Must have one of:
*
* <standardConc model="unity" />
* <standardConc model="molar_volume" />
* <standardConc model="solvent_volume" />
*/
if (phaseNode.hasChild("standardConc")) {
XML_Node& scNode = phaseNode.child("standardConc");
string formStringa = scNode.attrib("model");
string formString = lowercase(formStringa);
if (formString == "unity") {
m_formGC = 0;
} else if (formString == "molar_volume") {
m_formGC = 1;
} else if (formString == "solvent_volume") {
m_formGC = 2;
} else {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"Unknown standardConc model: " + formStringa);
}
} else {
throw CanteraError("IdealSolidSolnPhase::initThermoXML",
"Unspecified standardConc model");
}
/*
* Initialize all of the lengths now that we know how many species
* there are in the phase.
*/
initLengths();
/*
* Now go get the molar volumes
*/
XML_Node& speciesList = phaseNode.child("speciesArray");
XML_Node* speciesDB = get_XML_NameID("speciesData", speciesList["datasrc"],
&phaseNode.root());
for (size_t k = 0; k < m_kk; k++) {
XML_Node* s = speciesDB->findByAttr("name", speciesName(k));
XML_Node* ss = s->findByName("standardState");
m_speciesMolarVolume[k] = getFloat(*ss, "molarVolume", "toSI");
}
/*
* Call the base initThermo, which handles setting the initial
* state.
*/
ThermoPhase::initThermoXML(phaseNode, id_);
}
void IdealSolidSolnPhase::initLengths()
{
/*
* Obtain the reference pressure by calling the ThermoPhase
* function refPressure, which in turn calls the
* species thermo reference pressure function of the
* same name.
*/
m_Pref = refPressure();
m_h0_RT.resize(m_kk);
m_g0_RT.resize(m_kk);
m_expg0_RT.resize(m_kk);
m_cp0_R.resize(m_kk);
m_s0_R.resize(m_kk);
m_pe.resize(m_kk, 0.0);
m_pp.resize(m_kk);
m_speciesMolarVolume.resize(m_kk);
}
void IdealSolidSolnPhase::setToEquilState(const doublereal* lambda_RT)
{
const vector_fp& grt = gibbs_RT_ref();
// set the pressure and composition to be consistent with
// the temperature,
doublereal pres = 0.0;
for (size_t k = 0; k < m_kk; k++) {
m_pp[k] = -grt[k];
for (size_t m = 0; m < nElements(); m++) {
m_pp[k] += nAtoms(k,m)*lambda_RT[m];
}
m_pp[k] = m_Pref * exp(m_pp[k]);
pres += m_pp[k];
}
setState_PX(pres, &m_pp[0]);
}
double IdealSolidSolnPhase::speciesMolarVolume(int k) const
{
return m_speciesMolarVolume[k];
}
void IdealSolidSolnPhase::getSpeciesMolarVolumes(doublereal* smv) const
{
copy(m_speciesMolarVolume.begin(), m_speciesMolarVolume.end(), smv);
}
void IdealSolidSolnPhase::_updateThermo() const
{
doublereal tnow = temperature();
if (m_tlast != tnow) {
/*
* Update the thermodynamic functions of the reference state.
*/
m_spthermo->update(tnow, DATA_PTR(m_cp0_R), DATA_PTR(m_h0_RT),
DATA_PTR(m_s0_R));
m_tlast = tnow;
doublereal rrt = 1.0 / (GasConstant * tnow);
for (size_t k = 0; k < m_kk; k++) {
double deltaE = rrt * m_pe[k];
m_h0_RT[k] += deltaE;
m_g0_RT[k] = m_h0_RT[k] - m_s0_R[k];
}
m_tlast = tnow;
}
}
} // end namespace Cantera
| bsd-3-clause |
mirror/libtorrent | src/torrent_peer.cpp | 7842 | /*
Copyright (c) 2012-2013, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/torrent_peer.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/string_util.hpp"
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/crc32c.hpp"
#include "libtorrent/ip_voter.hpp"
namespace libtorrent
{
void apply_mask(boost::uint8_t* b, boost::uint8_t const* mask, int size)
{
for (int i = 0; i < size; ++i)
{
*b &= *mask;
++b;
++mask;
}
}
// 1. if the IP addresses are identical, hash the ports in 16 bit network-order
// binary representation, ordered lowest first.
// 2. if the IPs are in the same /24, hash the IPs ordered, lowest first.
// 3. if the IPs are in the ame /16, mask the IPs by 0xffffff55, hash them
// ordered, lowest first.
// 4. if IPs are not in the same /16, mask the IPs by 0xffff5555, hash them
// ordered, lowest first.
//
// * for IPv6 peers, just use the first 64 bits and widen the masks.
// like this: 0xffff5555 -> 0xffffffff55555555
// the lower 64 bits are always unmasked
//
// * for IPv6 addresses, compare /32 and /48 instead of /16 and /24
//
// * the two IP addresses that are used to calculate the rank must
// always be of the same address family
//
// * all IP addresses are in network byte order when hashed
boost::uint32_t peer_priority(tcp::endpoint e1, tcp::endpoint e2)
{
TORRENT_ASSERT(e1.address().is_v4() == e2.address().is_v4());
using std::swap;
boost::uint32_t ret;
if (e1.address() == e2.address())
{
if (e1.port() > e2.port())
swap(e1, e2);
boost::uint32_t p;
reinterpret_cast<boost::uint16_t*>(&p)[0] = htons(e1.port());
reinterpret_cast<boost::uint16_t*>(&p)[1] = htons(e2.port());
ret = crc32c_32(p);
}
#if TORRENT_USE_IPV6
else if (e1.address().is_v6())
{
const static boost::uint8_t v6mask[][8] = {
{ 0xff, 0xff, 0xff, 0xff, 0x55, 0x55, 0x55, 0x55 },
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x55, 0x55 },
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }
};
if (e1 > e2) swap(e1, e2);
address_v6::bytes_type b1 = e1.address().to_v6().to_bytes();
address_v6::bytes_type b2 = e2.address().to_v6().to_bytes();
int mask = memcmp(&b1[0], &b2[0], 4) ? 0
: memcmp(&b1[0], &b2[0], 6) ? 1 : 2;
apply_mask(&b1[0], v6mask[mask], 8);
apply_mask(&b2[0], v6mask[mask], 8);
boost::uint64_t addrbuf[4];
memcpy(&addrbuf[0], &b1[0], 16);
memcpy(&addrbuf[2], &b2[0], 16);
ret = crc32c(addrbuf, 4);
}
#endif
else
{
const static boost::uint8_t v4mask[][4] = {
{ 0xff, 0xff, 0x55, 0x55 },
{ 0xff, 0xff, 0xff, 0x55 },
{ 0xff, 0xff, 0xff, 0xff }
};
if (e1 > e2) swap(e1, e2);
address_v4::bytes_type b1 = e1.address().to_v4().to_bytes();
address_v4::bytes_type b2 = e2.address().to_v4().to_bytes();
int mask = memcmp(&b1[0], &b2[0], 2) ? 0
: memcmp(&b1[0], &b2[0], 3) ? 1 : 2;
apply_mask(&b1[0], v4mask[mask], 4);
apply_mask(&b2[0], v4mask[mask], 4);
boost::uint64_t addrbuf;
memcpy(&addrbuf, &b1[0], 4);
memcpy(reinterpret_cast<char*>(&addrbuf) + 4, &b2[0], 4);
ret = crc32c(&addrbuf, 1);
}
return ret;
}
torrent_peer::torrent_peer(boost::uint16_t port, bool conn, int src)
: prev_amount_upload(0)
, prev_amount_download(0)
, connection(0)
, peer_rank(0)
, last_optimistically_unchoked(0)
, last_connected(0)
, port(port)
, hashfails(0)
, failcount(0)
, connectable(conn)
, optimistically_unchoked(false)
, seed(false)
, fast_reconnects(0)
, trust_points(0)
, source(src)
#if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS)
// assume no support in order to
// prefer opening non-encrypyed
// connections. If it fails, we'll
// retry with encryption
, pe_support(false)
#endif
#if TORRENT_USE_IPV6
, is_v6_addr(false)
#endif
#if TORRENT_USE_I2P
, is_i2p_addr(false)
#endif
, on_parole(false)
, banned(false)
, supports_utp(true) // assume peers support utp
, confirmed_supports_utp(false)
, supports_holepunch(false)
, web_seed(false)
#if TORRENT_USE_ASSERTS
, in_use(false)
#endif
{
TORRENT_ASSERT((src & 0xff) == src);
}
boost::uint32_t torrent_peer::rank(external_ip const& external, int external_port) const
{
//TODO: how do we deal with our external address changing?
if (peer_rank == 0)
peer_rank = peer_priority(
tcp::endpoint(external.external_address(this->address()), external_port)
, tcp::endpoint(this->address(), this->port));
return peer_rank;
}
boost::uint64_t torrent_peer::total_download() const
{
if (connection != 0)
{
TORRENT_ASSERT(prev_amount_download == 0);
return connection->statistics().total_payload_download();
}
else
{
return boost::uint64_t(prev_amount_download) << 10;
}
}
boost::uint64_t torrent_peer::total_upload() const
{
if (connection != 0)
{
TORRENT_ASSERT(prev_amount_upload == 0);
return connection->statistics().total_payload_upload();
}
else
{
return boost::uint64_t(prev_amount_upload) << 10;
}
}
ipv4_peer::ipv4_peer(
tcp::endpoint const& ep, bool c, int src
)
: torrent_peer(ep.port(), c, src)
, addr(ep.address().to_v4())
{
#if TORRENT_USE_IPV6
is_v6_addr = false;
#endif
#if TORRENT_USE_I2P
is_i2p_addr = false;
#endif
}
#if TORRENT_USE_I2P
i2p_peer::i2p_peer(char const* dest, bool connectable, int src)
: torrent_peer(0, connectable, src), destination(allocate_string_copy(dest))
{
#if TORRENT_USE_IPV6
is_v6_addr = false;
#endif
is_i2p_addr = true;
}
i2p_peer::~i2p_peer()
{ free(destination); }
#endif // TORRENT_USE_I2P
#if TORRENT_USE_IPV6
ipv6_peer::ipv6_peer(
tcp::endpoint const& ep, bool c, int src
)
: torrent_peer(ep.port(), c, src)
, addr(ep.address().to_v6().to_bytes())
{
is_v6_addr = true;
#if TORRENT_USE_I2P
is_i2p_addr = false;
#endif
}
#endif // TORRENT_USE_IPV6
#if TORRENT_USE_I2P
char const* torrent_peer::dest() const
{
if (is_i2p_addr)
return static_cast<i2p_peer const*>(this)->destination;
return "";
}
#endif
libtorrent::address torrent_peer::address() const
{
#if TORRENT_USE_IPV6
if (is_v6_addr)
return libtorrent::address_v6(
static_cast<ipv6_peer const*>(this)->addr);
else
#endif
#if TORRENT_USE_I2P
if (is_i2p_addr) return libtorrent::address();
else
#endif
return static_cast<ipv4_peer const*>(this)->addr;
}
}
| bsd-3-clause |
ric2b/Vivaldi-browser | chromium/ash/shelf/drag_window_from_shelf_controller.h | 9082 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SHELF_DRAG_WINDOW_FROM_SHELF_CONTROLLER_H_
#define ASH_SHELF_DRAG_WINDOW_FROM_SHELF_CONTROLLER_H_
#include <vector>
#include "ash/ash_export.h"
#include "ash/public/cpp/shelf_types.h"
#include "ash/public/cpp/window_properties.h"
#include "ash/shelf/shelf_metrics.h"
#include "ash/wm/splitview/split_view_controller.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/timer/timer.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/aura/window_observer.h"
namespace aura {
class Window;
}
namespace gfx {
class PointF;
}
namespace ash {
// The window drag controller that will be used when a window is dragged up by
// swiping up from the shelf to homescreen, overview or splitview.
class ASH_EXPORT DragWindowFromShelfController : public aura::WindowObserver {
public:
// The deceleration threshold to open overview behind the dragged window
// when swiping up from the shelf to drag the active window.
static constexpr float kOpenOverviewThreshold = 10.f;
// The deceleration threshold to show or hide overview during window dragging
// when dragging a window up from the shelf.
static constexpr float kShowOverviewThreshold = 50.f;
// The upward velocity threshold to take the user to the home launcher screen
// when swiping up from the shelf. Can happen anytime during dragging.
static constexpr float kVelocityToHomeScreenThreshold = 1000.f;
// When swiping up from the shelf, the user can continue dragging and end with
// a downward fling. This is the downward velocity threshold required to
// restore the original window bounds.
static constexpr float kVelocityToRestoreBoundsThreshold = 1000.f;
// The upward velocity threshold to fling the window into overview when split
// view is active during dragging.
static constexpr float kVelocityToOverviewThreshold = 1000.f;
// If the window drag starts within |kDistanceFromEdge| from screen edge, it
// will get snapped if the drag ends in the snap region, no matter how far
// the window has been dragged.
static constexpr int kDistanceFromEdge = 8;
// A window has to be dragged toward the direction of the edge of the screen
// for a minimum of |kMinDragDistance| to a point within
// |kScreenEdgeInsetForSnap| of the edge of the screen, or dragged inside
// |kDistanceFromEdge| from edge to be snapped.
static constexpr int kScreenEdgeInsetForSnap = 48;
static constexpr int kMinDragDistance = 96;
// The distance for the dragged window to pass over the bottom of the display
// so that it can be dragged into home launcher or overview. If not pass this
// value (the top of the hotseat), the window will snap back to its original
// position. The value is different for standard or dense shelf.
static float GetReturnToMaximizedThreshold();
class Observer : public base::CheckedObserver {
public:
// Called when overview visibility is changed during or after window
// dragging.
virtual void OnOverviewVisibilityChanged(bool visible) {}
};
DragWindowFromShelfController(aura::Window* window,
const gfx::PointF& location_in_screen);
DragWindowFromShelfController(const DragWindowFromShelfController&) = delete;
DragWindowFromShelfController& operator=(
const DragWindowFromShelfController&) = delete;
~DragWindowFromShelfController() override;
// Called during swiping up on the shelf.
void Drag(const gfx::PointF& location_in_screen,
float scroll_x,
float scroll_y);
absl::optional<ShelfWindowDragResult> EndDrag(
const gfx::PointF& location_in_screen,
absl::optional<float> velocity_y);
void CancelDrag();
bool IsDraggedWindowAnimating() const;
// Performs the action on the dragged window depending on
// |window_drag_result_|, such as scaling up/down the dragged window. This
// method should be called after EndDrag() which computes
// |window_drag_result_|.
void FinalizeDraggedWindow();
// aura::WindowObserver:
void OnWindowDestroying(aura::Window* window) override;
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
aura::Window* dragged_window() const { return window_; }
bool drag_started() const { return drag_started_; }
bool show_overview_windows() const { return show_overview_windows_; }
bool during_window_restoration_callback() const {
return during_window_restoration_callback_;
}
private:
class WindowsHider;
void OnDragStarted(const gfx::PointF& location_in_screen);
void OnDragEnded(const gfx::PointF& location_in_screen,
bool should_drop_window_in_overview,
SplitViewController::SnapPosition snap_position);
// Updates the dragged window's transform during dragging.
void UpdateDraggedWindow(const gfx::PointF& location_in_screen);
// Returns the desired snap position on |location_in_screen| during dragging.
SplitViewController::SnapPosition GetSnapPosition(
const gfx::PointF& location_in_screen) const;
// Returns true if the dragged window should restore to its original bounds
// after drag ends. Happens when the bottom of the dragged window is
// within the GetReturnToMaximizedThreshold() threshold, or when the downward
// vertical velocity is larger than kVelocityToRestoreBoundsThreshold.
bool ShouldRestoreToOriginalBounds(const gfx::PointF& location_in_screen,
absl::optional<float> velocity_y) const;
// Returns true if we should go to home screen after drag ends. Happens when
// the upward vertical velocity is larger than kVelocityToHomeScreenThreshold
// and splitview is not active. Note when splitview is active, we do not allow
// to go to home screen by fling.
bool ShouldGoToHomeScreen(const gfx::PointF& location_in_screen,
absl::optional<float> velocity_y) const;
// Returns the desired snap position on |location_in_screen| when drag ends.
SplitViewController::SnapPosition GetSnapPositionOnDragEnd(
const gfx::PointF& location_in_screen,
absl::optional<float> velocity_y) const;
// Returns true if we should drop the dragged window in overview after drag
// ends.
bool ShouldDropWindowInOverview(const gfx::PointF& location_in_screen,
absl::optional<float> velocity_y) const;
// Reshows the windows that were hidden before drag starts.
void ReshowHiddenWindowsOnDragEnd();
// Calls when the user resumes or ends window dragging. Overview should show
// up and split view indicators should be updated.
void ShowOverviewDuringOrAfterDrag();
// Overview should be hidden when the user drags the window quickly up or
// around.
void HideOverviewDuringDrag();
// Called when the dragged window should scale down and fade out to home
// screen after drag ends.
void ScaleDownWindowAfterDrag();
// Callback function to be called after the window has been scaled down and
// faded out after drag ends.
void OnWindowScaledDownAfterDrag();
// Called when the dragged window should scale up to restore to its original
// bounds after drag ends.
void ScaleUpToRestoreWindowAfterDrag();
// Callback function to be called after the window has been restored to its
// original bounds after drag ends.
void OnWindowRestoredToOrignalBounds(bool end_overview);
// Called to do proper initialization in overview for the dragged window. The
// function is supposed to be called with an active overview session.
void OnWindowDragStartedInOverview();
aura::Window* window_ = nullptr;
gfx::PointF initial_location_in_screen_;
gfx::PointF previous_location_in_screen_;
bool drag_started_ = false;
// Whether overview was active when the drag started.
bool started_in_overview_ = false;
// Hide all eligible windows during window dragging. Depends on different
// scenarios, we may or may not reshow there windows when drag ends.
std::unique_ptr<WindowsHider> windows_hider_;
// Timer to show and update overview.
base::OneShotTimer show_overview_timer_;
// True if overview is active and its windows are showing.
bool show_overview_windows_ = false;
// A pending action from EndDrag() to be performed in FinalizeDraggedWindow().
absl::optional<ShelfWindowDragResult> window_drag_result_;
base::ObserverList<Observer> observers_;
bool during_window_restoration_callback_ = false;
SplitViewController::SnapPosition initial_snap_position_ =
SplitViewController::NONE;
SplitViewController::SnapPosition end_snap_position_ =
SplitViewController::NONE;
std::unique_ptr<PresentationTimeRecorder> presentation_time_recorder_;
base::WeakPtrFactory<DragWindowFromShelfController> weak_ptr_factory_{this};
};
} // namespace ash
#endif // ASH_SHELF_DRAG_WINDOW_FROM_SHELF_CONTROLLER_H_
| bsd-3-clause |
jnewland/kops | vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/1.5/kubernetes/typed/core/v1/doc.go | 921 | /*
Copyright 2016 The Kubernetes Authors.
Licensed 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.
*/
// This package is generated by client-gen with arguments: --clientset-name=release_1_5 --input=[api/v1,apps/v1alpha1,authentication/v1beta1,authorization/v1beta1,autoscaling/v1,batch/v1,certificates/v1alpha1,extensions/v1beta1,policy/v1alpha1,rbac/v1alpha1,storage/v1beta1]
// This package has the automatically generated typed clients.
package v1
| apache-2.0 |
airdrummingfool/fireproof | test/spec/lib/on-disconnect.js | 2784 |
'use strict';
describe('onDisconnect', function() {
var fireproof;
beforeEach(function() {
fireproof = new Fireproof(firebase);
});
describe('#set', function() {
it('promises to set the ref to the specified value on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.set(true)
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(true);
});
});
});
describe('#remove', function() {
it('promises to remove the data at specified ref on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.remove()
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(null);
});
});
});
describe('#setWithPriority', function() {
it('promises to set the ref to a value/priority on disconnect', function() {
return fireproof
.child('odSet')
.onDisconnect()
.setWithPriority(true, 5)
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odSet');
})
.then(function(snap) {
expect(snap.val()).to.equal(true);
expect(snap.getPriority()).to.equal(5);
});
});
});
describe('#update', function() {
it('promises to update the ref with the given values on disconnect', function() {
return fireproof
.child('odUpdate')
.set({ foo: 'bar', baz: 'quux' })
.then(function() {
return fireproof
.child('odUpdate')
.onDisconnect()
.update({ baz: 'bells', whistles: true });
})
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odUpdate');
})
.then(function(snap) {
expect(snap.val()).to.deep.equal({
foo: 'bar',
baz: 'bells',
whistles: true
});
});
});
});
describe('#cancel', function() {
it('promises to cancel all onDisconnect operations at the ref', function() {
return fireproof.child('odCancel')
.onDisconnect().set({ foo: 'bar '})
.then(function() {
return fireproof.child('odCancel')
.onDisconnect().cancel();
})
.then(function() {
Firebase.goOffline();
Firebase.goOnline();
return fireproof.child('odCancel');
})
.then(function(snap) {
expect(snap.val()).to.equal(null);
});
});
});
});
| isc |
jbogard/AutoMapper | src/AutoMapper/Mappers/ImplicitConversionOperatorMapper.cs | 1677 | using System.Linq.Expressions;
namespace AutoMapper.Mappers
{
using System.Linq;
using System.Reflection;
using Configuration;
public class ImplicitConversionOperatorMapper : IObjectMapExpression
{
public object Map(ResolutionContext context)
{
var implicitOperator = GetImplicitConversionOperator(context.Types);
return implicitOperator.Invoke(null, new[] {context.SourceValue});
}
public bool IsMatch(TypePair context)
{
var methodInfo = GetImplicitConversionOperator(context);
return methodInfo != null;
}
private static MethodInfo GetImplicitConversionOperator(TypePair context)
{
var destinationType = context.DestinationType;
if(destinationType.IsNullableType())
{
destinationType = destinationType.GetTypeOfNullable();
}
var sourceTypeMethod = context.SourceType
.GetDeclaredMethods()
.FirstOrDefault(mi => mi.IsPublic && mi.IsStatic && mi.Name == "op_Implicit" && mi.ReturnType == destinationType);
return sourceTypeMethod ?? destinationType.GetMethod("op_Implicit", new[] { context.SourceType });
}
public Expression MapExpression(Expression sourceExpression, Expression destExpression, Expression contextExpression)
{
var implicitOperator = GetImplicitConversionOperator(new TypePair(sourceExpression.Type, destExpression.Type));
return Expression.Call(null, implicitOperator, sourceExpression);
}
}
} | mit |
zorx/core | src/Console/Commands/Module/GeneratorCommand.php | 2135 | <?php
namespace ZEDx\Console\Commands\Module;
use File;
use Illuminate\Console\Command;
use Modules;
use ZEDx\Console\Commands\Module\Generators\FileAlreadyExistException;
use ZEDx\Console\Commands\Module\Generators\FileGenerator;
abstract class GeneratorCommand extends Command
{
/**
* The name of 'name' argument.
*
* @var string
*/
protected $argumentName = '';
/**
* Get template contents.
*
* @return string
*/
abstract protected function getTemplateContents();
/**
* Get the destination file path.
*
* @return string
*/
abstract protected function getDestinationFilePath();
/**
* Execute the console command.
*/
public function fire()
{
$path = str_replace('\\', '/', $this->getDestinationFilePath());
if (!File::isDirectory($dir = dirname($path))) {
File::makeDirectory($dir, 0777, true);
}
$contents = $this->getTemplateContents();
try {
with(new FileGenerator($path, $contents))->generate();
$this->info("Created : {$path}");
} catch (FileAlreadyExistException $e) {
$this->error("File : {$path} already exists.");
}
}
/**
* Get class name.
*
* @return string
*/
public function getClass()
{
return class_basename($this->argument($this->argumentName));
}
/**
* Get default namespace.
*
* @return string
*/
public function getDefaultNamespace()
{
return '';
}
/**
* Get class namespace.
*
* @param Module $module
*
* @return string
*/
public function getClassNamespace($module)
{
$extra = str_replace($this->getClass(), '', $this->argument($this->argumentName));
$extra = str_replace('/', '\\', $extra);
$namespace = Modules::config('namespace');
$namespace .= '\\'.$module->getStudlyName();
$namespace .= '\\'.$this->getDefaultNamespace();
$namespace .= '\\'.$extra;
return rtrim($namespace, '\\');
}
}
| mit |
erwinvanhunen/PnP-Guidance | sitescore/OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.ctor1.md | 473 | # Page.Page members
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public Page()
```
## See also
- [Page](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.Page.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)
| mit |
richq/AntennaPod | app/src/main/java/de/danoeh/antennapod/preferences/PreferenceController.java | 31136 | package de.danoeh.antennapod.preferences;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.danoeh.antennapod.BuildConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.AboutActivity;
import de.danoeh.antennapod.activity.DirectoryChooserActivity;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.activity.PreferenceActivity;
import de.danoeh.antennapod.activity.PreferenceActivityGingerbread;
import de.danoeh.antennapod.asynctask.OpmlExportWorker;
import de.danoeh.antennapod.core.preferences.GpodnetPreferences;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.util.flattr.FlattrUtils;
import de.danoeh.antennapod.dialog.AuthenticationDialog;
import de.danoeh.antennapod.dialog.AutoFlattrPreferenceDialog;
import de.danoeh.antennapod.dialog.GpodnetSetHostnameDialog;
import de.danoeh.antennapod.dialog.VariableSpeedDialog;
/**
* Sets up a preference UI that lets the user change user preferences.
*/
public class PreferenceController {
private static final String TAG = "PreferenceController";
public static final String PREF_FLATTR_SETTINGS = "prefFlattrSettings";
public static final String PREF_FLATTR_AUTH = "pref_flattr_authenticate";
public static final String PREF_FLATTR_REVOKE = "prefRevokeAccess";
public static final String PREF_AUTO_FLATTR_PREFS = "prefAutoFlattrPrefs";
public static final String PREF_OPML_EXPORT = "prefOpmlExport";
public static final String PREF_ABOUT = "prefAbout";
public static final String PREF_CHOOSE_DATA_DIR = "prefChooseDataDir";
public static final String AUTO_DL_PREF_SCREEN = "prefAutoDownloadSettings";
public static final String PREF_PLAYBACK_SPEED_LAUNCHER = "prefPlaybackSpeedLauncher";
public static final String PREF_GPODNET_LOGIN = "pref_gpodnet_authenticate";
public static final String PREF_GPODNET_SETLOGIN_INFORMATION = "pref_gpodnet_setlogin_information";
public static final String PREF_GPODNET_LOGOUT = "pref_gpodnet_logout";
public static final String PREF_GPODNET_HOSTNAME = "pref_gpodnet_hostname";
public static final String PREF_EXPANDED_NOTIFICATION = "prefExpandNotify";
private final PreferenceUI ui;
private CheckBoxPreference[] selectedNetworks;
public PreferenceController(PreferenceUI ui) {
this.ui = ui;
}
/**
* Returns the preference activity that should be used on this device.
*
* @return PreferenceActivity if the API level is greater than 10, PreferenceActivityGingerbread otherwise.
*/
public static Class getPreferenceActivity() {
if (Build.VERSION.SDK_INT > 10) {
return PreferenceActivity.class;
} else {
return PreferenceActivityGingerbread.class;
}
}
public void onCreate() {
final Activity activity = ui.getActivity();
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
// disable expanded notification option on unsupported android versions
ui.findPreference(PreferenceController.PREF_EXPANDED_NOTIFICATION).setEnabled(false);
ui.findPreference(PreferenceController.PREF_EXPANDED_NOTIFICATION).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Toast toast = Toast.makeText(activity, R.string.pref_expand_notify_unsupport_toast, Toast.LENGTH_SHORT);
toast.show();
return true;
}
}
);
}
ui.findPreference(PreferenceController.PREF_FLATTR_REVOKE).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
FlattrUtils.revokeAccessToken(activity);
checkItemVisibility();
return true;
}
}
);
ui.findPreference(PreferenceController.PREF_ABOUT).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
activity.startActivity(new Intent(
activity, AboutActivity.class));
return true;
}
}
);
ui.findPreference(PreferenceController.PREF_OPML_EXPORT).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
new OpmlExportWorker(activity)
.executeAsync();
return true;
}
}
);
ui.findPreference(PreferenceController.PREF_CHOOSE_DATA_DIR).setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
activity.startActivityForResult(
new Intent(activity,
DirectoryChooserActivity.class),
DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED
);
return true;
}
}
);
ui.findPreference(UserPreferences.PREF_THEME)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(
Preference preference, Object newValue) {
Intent i = new Intent(activity, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
activity.finish();
activity.startActivity(i);
return true;
}
}
);
ui.findPreference(UserPreferences.PREF_HIDDEN_DRAWER_ITEMS)
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
showDrawerPreferencesDialog();
return true;
}
});
ui.findPreference(UserPreferences.PREF_UPDATE_INTERVAL)
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
showUpdateIntervalTimePreferencesDialog();
return true;
}
});
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL)
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue instanceof Boolean) {
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_WIFI_FILTER).setEnabled((Boolean) newValue);
setSelectedNetworksEnabled((Boolean) newValue && UserPreferences.isEnableAutodownloadWifiFilter());
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_ON_BATTERY).setEnabled((Boolean) newValue);
}
return true;
}
});
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_WIFI_FILTER)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(
Preference preference, Object newValue) {
if (newValue instanceof Boolean) {
setSelectedNetworksEnabled((Boolean) newValue);
return true;
} else {
return false;
}
}
}
);
ui.findPreference(UserPreferences.PREF_PARALLEL_DOWNLOADS)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
if (o instanceof String) {
try {
int value = Integer.valueOf((String) o);
if (1 <= value && value <= 50) {
setParallelDownloadsText(value);
return true;
}
} catch(NumberFormatException e) {
return false;
}
}
return false;
}
}
);
// validate and set correct value: number of downloads between 1 and 50 (inclusive)
final EditText ev = ((EditTextPreference)ui.findPreference(UserPreferences.PREF_PARALLEL_DOWNLOADS)).getEditText();
ev.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if(s.length() > 0) {
try {
int value = Integer.valueOf(s.toString());
if (value <= 0) {
ev.setText("1");
} else if (value > 50) {
ev.setText("50");
}
} catch(NumberFormatException e) {
ev.setText("6");
}
ev.setSelection(ev.getText().length());
}
}
});
ui.findPreference(UserPreferences.PREF_EPISODE_CACHE_SIZE)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
if (o instanceof String) {
setEpisodeCacheSizeText(UserPreferences.readEpisodeCacheSize((String) o));
}
return true;
}
}
);
ui.findPreference(PreferenceController.PREF_PLAYBACK_SPEED_LAUNCHER)
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
VariableSpeedDialog.showDialog(activity);
return true;
}
});
ui.findPreference(PreferenceController.PREF_GPODNET_SETLOGIN_INFORMATION).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
AuthenticationDialog dialog = new AuthenticationDialog(activity,
R.string.pref_gpodnet_setlogin_information_title, false, false, GpodnetPreferences.getUsername(),
null) {
@Override
protected void onConfirmed(String username, String password, boolean saveUsernamePassword) {
GpodnetPreferences.setPassword(password);
}
};
dialog.show();
return true;
}
});
ui.findPreference(PreferenceController.PREF_GPODNET_LOGOUT).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
GpodnetPreferences.logout();
Toast toast = Toast.makeText(activity, R.string.pref_gpodnet_logout_toast, Toast.LENGTH_SHORT);
toast.show();
updateGpodnetPreferenceScreen();
return true;
}
});
ui.findPreference(PreferenceController.PREF_GPODNET_HOSTNAME).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
GpodnetSetHostnameDialog.createDialog(activity).setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
updateGpodnetPreferenceScreen();
}
});
return true;
}
});
ui.findPreference(PreferenceController.PREF_AUTO_FLATTR_PREFS).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
AutoFlattrPreferenceDialog.newAutoFlattrPreferenceDialog(activity,
new AutoFlattrPreferenceDialog.AutoFlattrPreferenceDialogInterface() {
@Override
public void onCancelled() {
}
@Override
public void onConfirmed(boolean autoFlattrEnabled, float autoFlattrValue) {
UserPreferences.setAutoFlattrSettings(autoFlattrEnabled, autoFlattrValue);
checkItemVisibility();
}
});
return true;
}
});
ui.findPreference(UserPreferences.PREF_IMAGE_CACHE_SIZE)
.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
if (o instanceof String) {
int newValue = Integer.valueOf((String) o) * 1024 * 1024;
if(newValue != UserPreferences.getImageCacheSize()) {
AlertDialog.Builder dialog = new AlertDialog.Builder(ui.getActivity());
dialog.setTitle(android.R.string.dialog_alert_title);
dialog.setMessage(R.string.pref_restart_required);
dialog.setPositiveButton(android.R.string.ok, null);
dialog.show();
}
return true;
}
return false;
}
}
);
buildSmartMarkAsPlayedPreference();
buildAutodownloadSelectedNetworsPreference();
setSelectedNetworksEnabled(UserPreferences
.isEnableAutodownloadWifiFilter());
}
public void onResume() {
checkItemVisibility();
setParallelDownloadsText(UserPreferences.getParallelDownloads());
setEpisodeCacheSizeText(UserPreferences.getEpisodeCacheSize());
setDataFolderText();
updateGpodnetPreferenceScreen();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) {
String dir = data
.getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR);
if (BuildConfig.DEBUG)
Log.d(TAG, "Setting data folder");
UserPreferences.setDataFolder(dir);
}
}
private void updateGpodnetPreferenceScreen() {
final boolean loggedIn = GpodnetPreferences.loggedIn();
ui.findPreference(PreferenceController.PREF_GPODNET_LOGIN).setEnabled(!loggedIn);
ui.findPreference(PreferenceController.PREF_GPODNET_SETLOGIN_INFORMATION).setEnabled(loggedIn);
ui.findPreference(PreferenceController.PREF_GPODNET_LOGOUT).setEnabled(loggedIn);
ui.findPreference(PreferenceController.PREF_GPODNET_HOSTNAME).setSummary(GpodnetPreferences.getHostname());
}
private String[] getUpdateIntervalEntries(final String[] values) {
final Resources res = ui.getActivity().getResources();
String[] entries = new String[values.length];
for (int x = 0; x < values.length; x++) {
Integer v = Integer.parseInt(values[x]);
switch (v) {
case 0:
entries[x] = res.getString(R.string.pref_update_interval_hours_manual);
break;
case 1:
entries[x] = v + " " + res.getString(R.string.pref_update_interval_hours_singular);
break;
default:
entries[x] = v + " " + res.getString(R.string.pref_update_interval_hours_plural);
break;
}
}
return entries;
}
private void buildSmartMarkAsPlayedPreference() {
final Resources res = ui.getActivity().getResources();
ListPreference pref = (ListPreference) ui.findPreference(UserPreferences.PREF_SMART_MARK_AS_PLAYED_SECS);
String[] values = res.getStringArray(
R.array.smart_mark_as_played_values);
String[] entries = new String[values.length];
for (int x = 0; x < values.length; x++) {
if(x == 0) {
entries[x] = res.getString(R.string.pref_smart_mark_as_played_disabled);
} else {
Integer v = Integer.parseInt(values[x]);
entries[x] = res.getQuantityString(R.plurals.time_seconds_quantified, v, v);
}
}
pref.setEntries(entries);
}
private void setSelectedNetworksEnabled(boolean b) {
if (selectedNetworks != null) {
for (Preference p : selectedNetworks) {
p.setEnabled(b);
}
}
}
@SuppressWarnings("deprecation")
private void checkItemVisibility() {
boolean hasFlattrToken = FlattrUtils.hasToken();
ui.findPreference(PreferenceController.PREF_FLATTR_SETTINGS).setEnabled(FlattrUtils.hasAPICredentials());
ui.findPreference(PreferenceController.PREF_FLATTR_AUTH).setEnabled(!hasFlattrToken);
ui.findPreference(PreferenceController.PREF_FLATTR_REVOKE).setEnabled(hasFlattrToken);
ui.findPreference(PreferenceController.PREF_AUTO_FLATTR_PREFS).setEnabled(hasFlattrToken);
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_WIFI_FILTER)
.setEnabled(UserPreferences.isEnableAutodownload());
setSelectedNetworksEnabled(UserPreferences.isEnableAutodownload()
&& UserPreferences.isEnableAutodownloadWifiFilter());
ui.findPreference(UserPreferences.PREF_ENABLE_AUTODL_ON_BATTERY)
.setEnabled(UserPreferences.isEnableAutodownload());
if (Build.VERSION.SDK_INT >= 16) {
ui.findPreference(UserPreferences.PREF_SONIC).setEnabled(true);
} else {
Preference prefSonic = ui.findPreference(UserPreferences.PREF_SONIC);
prefSonic.setSummary("[Android 4.1+]\n" + prefSonic.getSummary());
}
}
private void setParallelDownloadsText(int downloads) {
final Resources res = ui.getActivity().getResources();
String s = Integer.toString(downloads)
+ res.getString(R.string.parallel_downloads_suffix);
ui.findPreference(UserPreferences.PREF_PARALLEL_DOWNLOADS).setSummary(s);
}
private void setEpisodeCacheSizeText(int cacheSize) {
final Resources res = ui.getActivity().getResources();
String s;
if (cacheSize == res.getInteger(
R.integer.episode_cache_size_unlimited)) {
s = res.getString(R.string.pref_episode_cache_unlimited);
} else {
s = Integer.toString(cacheSize)
+ res.getString(R.string.episodes_suffix);
}
ui.findPreference(UserPreferences.PREF_EPISODE_CACHE_SIZE).setSummary(s);
}
private void setDataFolderText() {
File f = UserPreferences.getDataFolder(ui.getActivity(), null);
if (f != null) {
ui.findPreference(PreferenceController.PREF_CHOOSE_DATA_DIR)
.setSummary(f.getAbsolutePath());
}
}
private void buildAutodownloadSelectedNetworsPreference() {
final Activity activity = ui.getActivity();
if (selectedNetworks != null) {
clearAutodownloadSelectedNetworsPreference();
}
// get configured networks
WifiManager wifiservice = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> networks = wifiservice.getConfiguredNetworks();
if (networks != null) {
selectedNetworks = new CheckBoxPreference[networks.size()];
List<String> prefValues = Arrays.asList(UserPreferences
.getAutodownloadSelectedNetworks());
PreferenceScreen prefScreen = (PreferenceScreen) ui.findPreference(PreferenceController.AUTO_DL_PREF_SCREEN);
Preference.OnPreferenceClickListener clickListener = new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (preference instanceof CheckBoxPreference) {
String key = preference.getKey();
ArrayList<String> prefValuesList = new ArrayList<String>(
Arrays.asList(UserPreferences
.getAutodownloadSelectedNetworks())
);
boolean newValue = ((CheckBoxPreference) preference)
.isChecked();
if (BuildConfig.DEBUG)
Log.d(TAG, "Selected network " + key
+ ". New state: " + newValue);
int index = prefValuesList.indexOf(key);
if (index >= 0 && newValue == false) {
// remove network
prefValuesList.remove(index);
} else if (index < 0 && newValue == true) {
prefValuesList.add(key);
}
UserPreferences.setAutodownloadSelectedNetworks(
prefValuesList.toArray(new String[prefValuesList.size()])
);
return true;
} else {
return false;
}
}
};
// create preference for each known network. attach listener and set
// value
for (int i = 0; i < networks.size(); i++) {
WifiConfiguration config = networks.get(i);
CheckBoxPreference pref = new CheckBoxPreference(activity);
String key = Integer.toString(config.networkId);
pref.setTitle(config.SSID);
pref.setKey(key);
pref.setOnPreferenceClickListener(clickListener);
pref.setPersistent(false);
pref.setChecked(prefValues.contains(key));
selectedNetworks[i] = pref;
prefScreen.addPreference(pref);
}
} else {
Log.e(TAG, "Couldn't get list of configure Wi-Fi networks");
}
}
private void clearAutodownloadSelectedNetworsPreference() {
if (selectedNetworks != null) {
PreferenceScreen prefScreen = (PreferenceScreen) ui.findPreference(PreferenceController.AUTO_DL_PREF_SCREEN);
for (int i = 0; i < selectedNetworks.length; i++) {
if (selectedNetworks[i] != null) {
prefScreen.removePreference(selectedNetworks[i]);
}
}
}
}
private void showDrawerPreferencesDialog() {
final Context context = ui.getActivity();
final List<String> hiddenDrawerItems = UserPreferences.getHiddenDrawerItems();
final String[] navTitles = context.getResources().getStringArray(R.array.nav_drawer_titles);
final String[] NAV_DRAWER_TAGS = MainActivity.NAV_DRAWER_TAGS;
boolean[] checked = new boolean[MainActivity.NAV_DRAWER_TAGS.length];
for(int i=0; i < NAV_DRAWER_TAGS.length; i++) {
String tag = NAV_DRAWER_TAGS[i];
if(!hiddenDrawerItems.contains(tag)) {
checked[i] = true;
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.drawer_preferences);
builder.setMultiChoiceItems(navTitles, checked, (dialog, which, isChecked) -> {
if (isChecked) {
hiddenDrawerItems.remove(NAV_DRAWER_TAGS[which]);
} else {
hiddenDrawerItems.add(NAV_DRAWER_TAGS[which]);
}
});
builder.setPositiveButton(R.string.confirm_label, new DialogInterface
.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UserPreferences.setHiddenDrawerItems(context, hiddenDrawerItems);
}
});
builder.setNegativeButton(R.string.cancel_label, null);
builder.create().show();
}
private void showUpdateIntervalTimePreferencesDialog() {
final Context context = ui.getActivity();
MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
builder.title(R.string.pref_autoUpdateIntervallOrTime_title);
builder.content(R.string.pref_autoUpdateIntervallOrTime_message);
builder.positiveText(R.string.pref_autoUpdateIntervallOrTime_Interval);
builder.negativeText(R.string.pref_autoUpdateIntervallOrTime_TimeOfDay);
builder.neutralText(R.string.pref_autoUpdateIntervallOrTime_Disable);
builder.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getString(R.string.pref_autoUpdateIntervallOrTime_Interval));
final String[] values = context.getResources().getStringArray(R.array.update_intervall_values);
final String[] entries = getUpdateIntervalEntries(values);
builder.setSingleChoiceItems(entries, -1, (dialog1, which) -> {
int hours = Integer.valueOf(values[which]);
UserPreferences.setUpdateInterval(hours);
dialog1.dismiss();
});
builder.setNegativeButton(context.getString(R.string.cancel_label), null);
builder.show();
}
@Override
public void onNegative(MaterialDialog dialog) {
int hourOfDay = 7, minute = 0;
int[] updateTime = UserPreferences.getUpdateTimeOfDay();
if (updateTime.length == 2) {
hourOfDay = updateTime[0];
minute = updateTime[1];
}
TimePickerDialog timePickerDialog = new TimePickerDialog(context,
(view, selectedHourOfDay, selectedMinute) -> {
if (view.getTag() == null) { // onTimeSet() may get called twice!
view.setTag("TAGGED");
UserPreferences.setUpdateTimeOfDay(selectedHourOfDay, selectedMinute);
}
}, hourOfDay, minute, DateFormat.is24HourFormat(context));
timePickerDialog.setTitle(context.getString(R.string.pref_autoUpdateIntervallOrTime_TimeOfDay));
timePickerDialog.show();
}
@Override
public void onNeutral(MaterialDialog dialog) {
UserPreferences.setUpdateInterval(0);
}
});
builder.forceStacking(true);
builder.show();
}
public interface PreferenceUI {
/**
* Finds a preference based on its key.
*/
Preference findPreference(CharSequence key);
Activity getActivity();
}
}
| mit |
wdross/CAN_BUS_Shield | mcp_can_dfs.h | 10912 | /*
mcp_can_dfs.h
2012 Copyright (c) Seeed Technology Inc. All right reserved.
Author:Loovee
2014-1-16
Contributor:
Cory J. Fowler
Latonita
Woodward1
Mehtajaghvi
BykeBlast
TheRo0T
Tsipizic
ralfEdmund
Nathancheek
BlueAndi
Adlerweb
Btetz
Hurvajs
xboxpro1
The MIT License (MIT)
Copyright (c) 2013 Seeed Technology Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef _MCP2515DFS_H_
#define _MCP2515DFS_H_
#include <Arduino.h>
#include <SPI.h>
#include <inttypes.h>
#ifndef INT32U
#define INT32U unsigned long
#endif
#ifndef INT8U
#define INT8U byte
#endif
// if print debug information
#define DEBUG_MODE 0
/*
* Begin mt
*/
#define TIMEOUTVALUE 50
#define MCP_SIDH 0
#define MCP_SIDL 1
#define MCP_EID8 2
#define MCP_EID0 3
#define MCP_TXB_EXIDE_M 0x08 /* In TXBnSIDL */
#define MCP_DLC_MASK 0x0F /* 4 LSBits */
#define MCP_RTR_MASK 0x40 /* (1<<6) Bit 6 */
#define MCP_RXB_RX_ANY 0x60
#define MCP_RXB_RX_EXT 0x40
#define MCP_RXB_RX_STD 0x20
#define MCP_RXB_RX_STDEXT 0x00
#define MCP_RXB_RX_MASK 0x60
#define MCP_RXB_BUKT_MASK (1<<2)
/*
** Bits in the TXBnCTRL registers.
*/
#define MCP_TXB_TXBUFE_M 0x80
#define MCP_TXB_ABTF_M 0x40
#define MCP_TXB_MLOA_M 0x20
#define MCP_TXB_TXERR_M 0x10
#define MCP_TXB_TXREQ_M 0x08
#define MCP_TXB_TXIE_M 0x04
#define MCP_TXB_TXP10_M 0x03
#define MCP_TXB_RTR_M 0x40 /* In TXBnDLC */
#define MCP_RXB_IDE_M 0x08 /* In RXBnSIDL */
#define MCP_RXB_RTR_M 0x40 /* In RXBnDLC */
#define MCP_STAT_RXIF_MASK (0x03)
#define MCP_STAT_RX0IF (1<<0)
#define MCP_STAT_RX1IF (1<<1)
#define MCP_EFLG_RX1OVR (1<<7)
#define MCP_EFLG_RX0OVR (1<<6)
#define MCP_EFLG_TXBO (1<<5)
#define MCP_EFLG_TXEP (1<<4)
#define MCP_EFLG_RXEP (1<<3)
#define MCP_EFLG_TXWAR (1<<2)
#define MCP_EFLG_RXWAR (1<<1)
#define MCP_EFLG_EWARN (1<<0)
#define MCP_EFLG_ERRORMASK (0xF8) /* 5 MS-Bits */
/*
* Define MCP2515 register addresses
*/
#define MCP_RXF0SIDH 0x00
#define MCP_RXF0SIDL 0x01
#define MCP_RXF0EID8 0x02
#define MCP_RXF0EID0 0x03
#define MCP_RXF1SIDH 0x04
#define MCP_RXF1SIDL 0x05
#define MCP_RXF1EID8 0x06
#define MCP_RXF1EID0 0x07
#define MCP_RXF2SIDH 0x08
#define MCP_RXF2SIDL 0x09
#define MCP_RXF2EID8 0x0A
#define MCP_RXF2EID0 0x0B
#define MCP_CANSTAT 0x0E
#define MCP_CANCTRL 0x0F
#define MCP_RXF3SIDH 0x10
#define MCP_RXF3SIDL 0x11
#define MCP_RXF3EID8 0x12
#define MCP_RXF3EID0 0x13
#define MCP_RXF4SIDH 0x14
#define MCP_RXF4SIDL 0x15
#define MCP_RXF4EID8 0x16
#define MCP_RXF4EID0 0x17
#define MCP_RXF5SIDH 0x18
#define MCP_RXF5SIDL 0x19
#define MCP_RXF5EID8 0x1A
#define MCP_RXF5EID0 0x1B
#define MCP_TEC 0x1C
#define MCP_REC 0x1D
#define MCP_RXM0SIDH 0x20
#define MCP_RXM0SIDL 0x21
#define MCP_RXM0EID8 0x22
#define MCP_RXM0EID0 0x23
#define MCP_RXM1SIDH 0x24
#define MCP_RXM1SIDL 0x25
#define MCP_RXM1EID8 0x26
#define MCP_RXM1EID0 0x27
#define MCP_CNF3 0x28
#define MCP_CNF2 0x29
#define MCP_CNF1 0x2A
#define MCP_CANINTE 0x2B
#define MCP_CANINTF 0x2C
#define MCP_EFLG 0x2D
#define MCP_TXB0CTRL 0x30
#define MCP_TXB1CTRL 0x40
#define MCP_TXB2CTRL 0x50
#define MCP_RXB0CTRL 0x60
#define MCP_RXB0SIDH 0x61
#define MCP_RXB1CTRL 0x70
#define MCP_RXB1SIDH 0x71
#define MCP_TX_INT 0x1C // Enable all transmit interrup ts
#define MCP_TX01_INT 0x0C // Enable TXB0 and TXB1 interru pts
#define MCP_RX_INT 0x03 // Enable receive interrupts
#define MCP_NO_INT 0x00 // Disable all interrupts
#define MCP_TX01_MASK 0x14
#define MCP_TX_MASK 0x54
/*
* Define SPI Instruction Set
*/
#define MCP_WRITE 0x02
#define MCP_READ 0x03
#define MCP_BITMOD 0x05
#define MCP_LOAD_TX0 0x40
#define MCP_LOAD_TX1 0x42
#define MCP_LOAD_TX2 0x44
#define MCP_RTS_TX0 0x81
#define MCP_RTS_TX1 0x82
#define MCP_RTS_TX2 0x84
#define MCP_RTS_ALL 0x87
#define MCP_READ_RX0 0x90
#define MCP_READ_RX1 0x94
#define MCP_READ_STATUS 0xA0
#define MCP_RX_STATUS 0xB0
#define MCP_RESET 0xC0
/*
* CANCTRL Register Values
*/
#define MODE_NORMAL 0x00
#define MODE_SLEEP 0x20
#define MODE_LOOPBACK 0x40
#define MODE_LISTENONLY 0x60
#define MODE_CONFIG 0x80
#define MODE_POWERUP 0xE0
#define MODE_MASK 0xE0
#define ABORT_TX 0x10
#define MODE_ONESHOT 0x08
#define CLKOUT_ENABLE 0x04
#define CLKOUT_DISABLE 0x00
#define CLKOUT_PS1 0x00
#define CLKOUT_PS2 0x01
#define CLKOUT_PS4 0x02
#define CLKOUT_PS8 0x03
/*
* CNF1 Register Values
*/
#define SJW1 0x00
#define SJW2 0x40
#define SJW3 0x80
#define SJW4 0xC0
/*
* CNF2 Register Values
*/
#define BTLMODE 0x80
#define SAMPLE_1X 0x00
#define SAMPLE_3X 0x40
/*
* CNF3 Register Values
*/
#define SOF_ENABLE 0x80
#define SOF_DISABLE 0x00
#define WAKFIL_ENABLE 0x40
#define WAKFIL_DISABLE 0x00
/*
* CANINTF Register Bits
*/
#define MCP_RX0IF 0x01
#define MCP_RX1IF 0x02
#define MCP_TX0IF 0x04
#define MCP_TX1IF 0x08
#define MCP_TX2IF 0x10
#define MCP_ERRIF 0x20
#define MCP_WAKIF 0x40
#define MCP_MERRF 0x80
/*
* speed 16M
*/
#define MCP_16MHz_1000kBPS_CFG1 (0x00)
#define MCP_16MHz_1000kBPS_CFG2 (0xD0)
#define MCP_16MHz_1000kBPS_CFG3 (0x82)
#define MCP_16MHz_500kBPS_CFG1 (0x00)
#define MCP_16MHz_500kBPS_CFG2 (0xF0)
#define MCP_16MHz_500kBPS_CFG3 (0x86)
#define MCP_16MHz_250kBPS_CFG1 (0x41)
#define MCP_16MHz_250kBPS_CFG2 (0xF1)
#define MCP_16MHz_250kBPS_CFG3 (0x85)
#define MCP_16MHz_200kBPS_CFG1 (0x01)
#define MCP_16MHz_200kBPS_CFG2 (0xFA)
#define MCP_16MHz_200kBPS_CFG3 (0x87)
#define MCP_16MHz_125kBPS_CFG1 (0x03)
#define MCP_16MHz_125kBPS_CFG2 (0xF0)
#define MCP_16MHz_125kBPS_CFG3 (0x86)
#define MCP_16MHz_100kBPS_CFG1 (0x03)
#define MCP_16MHz_100kBPS_CFG2 (0xFA)
#define MCP_16MHz_100kBPS_CFG3 (0x87)
#define MCP_16MHz_95kBPS_CFG1 (0x03)
#define MCP_16MHz_95kBPS_CFG2 (0xAD)
#define MCP_16MHz_95kBPS_CFG3 (0x07)
#define MCP_16MHz_83k3BPS_CFG1 (0x03)
#define MCP_16MHz_83k3BPS_CFG2 (0xBE)
#define MCP_16MHz_83k3BPS_CFG3 (0x07)
#define MCP_16MHz_80kBPS_CFG1 (0x03)
#define MCP_16MHz_80kBPS_CFG2 (0xFF)
#define MCP_16MHz_80kBPS_CFG3 (0x87)
#define MCP_16MHz_50kBPS_CFG1 (0x07)
#define MCP_16MHz_50kBPS_CFG2 (0xFA)
#define MCP_16MHz_50kBPS_CFG3 (0x87)
#define MCP_16MHz_40kBPS_CFG1 (0x07)
#define MCP_16MHz_40kBPS_CFG2 (0xFF)
#define MCP_16MHz_40kBPS_CFG3 (0x87)
#define MCP_16MHz_33kBPS_CFG1 (0x09)
#define MCP_16MHz_33kBPS_CFG2 (0xBE)
#define MCP_16MHz_33kBPS_CFG3 (0x07)
#define MCP_16MHz_31k25BPS_CFG1 (0x0F)
#define MCP_16MHz_31k25BPS_CFG2 (0xF1)
#define MCP_16MHz_31k25BPS_CFG3 (0x85)
#define MCP_16MHz_25kBPS_CFG1 (0X0F)
#define MCP_16MHz_25kBPS_CFG2 (0XBA)
#define MCP_16MHz_25kBPS_CFG3 (0X07)
#define MCP_16MHz_20kBPS_CFG1 (0x0F)
#define MCP_16MHz_20kBPS_CFG2 (0xFF)
#define MCP_16MHz_20kBPS_CFG3 (0x87)
#define MCP_16MHz_10kBPS_CFG1 (0x1F)
#define MCP_16MHz_10kBPS_CFG2 (0xFF)
#define MCP_16MHz_10kBPS_CFG3 (0x87)
#define MCP_16MHz_5kBPS_CFG1 (0x3F)
#define MCP_16MHz_5kBPS_CFG2 (0xFF)
#define MCP_16MHz_5kBPS_CFG3 (0x87)
#define MCP_16MHz_666kBPS_CFG1 (0x00)
#define MCP_16MHz_666kBPS_CFG2 (0xA0)
#define MCP_16MHz_666kBPS_CFG3 (0x04)
#define MCPDEBUG (0)
#define MCPDEBUG_TXBUF (0)
#define MCP_N_TXBUFFERS (3)
#define MCP_RXBUF_0 (MCP_RXB0SIDH)
#define MCP_RXBUF_1 (MCP_RXB1SIDH)
//#define SPICS 10
#define MCP2515_SELECT() digitalWrite(SPICS, LOW)
#define MCP2515_UNSELECT() digitalWrite(SPICS, HIGH)
#define MCP2515_OK (0)
#define MCP2515_FAIL (1)
#define MCP_ALLTXBUSY (2)
#define CANDEBUG 1
#define CANUSELOOP 0
#define CANSENDTIMEOUT (200) /* milliseconds */
/*
* initial value of gCANAutoProcess
*/
#define CANAUTOPROCESS (1)
#define CANAUTOON (1)
#define CANAUTOOFF (0)
#define CAN_STDID (0)
#define CAN_EXTID (1)
#define CANDEFAULTIDENT (0x55CC)
#define CANDEFAULTIDENTEXT (CAN_EXTID)
#define CAN_5KBPS 1
#define CAN_10KBPS 2
#define CAN_20KBPS 3
#define CAN_25KBPS 4
#define CAN_31K25BPS 5
#define CAN_33KBPS 6
#define CAN_40KBPS 7
#define CAN_50KBPS 8
#define CAN_80KBPS 9
#define CAN_83K3BPS 10
#define CAN_95KBPS 11
#define CAN_100KBPS 12
#define CAN_125KBPS 13
#define CAN_200KBPS 14
#define CAN_250KBPS 15
#define CAN_500KBPS 16
#define CAN_666KBPS 17
#define CAN_1000KBPS 18
#define CAN_OK (0)
#define CAN_FAILINIT (1)
#define CAN_FAILTX (2)
#define CAN_MSGAVAIL (3)
#define CAN_NOMSG (4)
#define CAN_CTRLERROR (5)
#define CAN_GETTXBFTIMEOUT (6)
#define CAN_SENDMSGTIMEOUT (7)
#define CAN_FAIL (0xff)
#define CAN_MAX_CHAR_IN_MESSAGE (8)
#endif
/*********************************************************************************************************
END FILE
*********************************************************************************************************/
| mit |
HamzaBendidane/tdnold | src/TDN/DocumentBundle/Entity/backup 2/Slider.php | 4670 | <?php
namespace TDN\DocumentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use TDN\ImageBundle\Entity\Image;
/**
* TDN\DocumentBundle\Entity\Slider
*/
class Slider
{
/**
* @var string $pitch
*/
private $pitch;
/**
* @var integer $ordre
*/
private $ordre;
/**
* @var integer $statut
*/
private $statut;
/**
* @var \DateTime $datePublication
*/
private $datePublication;
/**
* @var integer $idSlide
*/
private $idSlide;
/**
* @var TDN\DocumentBundle\Entity\Document
*/
private $lnSource;
/**
* @var TDN\ImageBundle\Entity\Image
*/
private $lnCover;
/**
* Set pitch
*
* @param string $pitch
* @return Slider
*/
public function setPitch($pitch)
{
$this->pitch = $pitch;
return $this;
}
/**
* Get pitch
*
* @return string
*/
public function getPitch()
{
return $this->pitch;
}
/**
* Set ordre
*
* @param integer $ordre
* @return Slider
*/
public function setOrdre($ordre)
{
$this->ordre = $ordre;
return $this;
}
/**
* Get ordre
*
* @return integer
*/
public function getOrdre()
{
return $this->ordre;
}
/**
* Set statut
*
* @param integer $statut
* @return Slider
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* @return integer
*/
public function getStatut()
{
return $this->statut;
}
/**
* Set datePublication
*
* @param \DateTime $datePublication
* @return Slider
*/
public function setDatePublication($datePublication)
{
$this->datePublication = $datePublication;
return $this;
}
/**
* Get datePublication
*
* @return \DateTime
*/
public function getDatePublication()
{
return $this->datePublication;
}
/**
* Get idSlide
*
* @return integer
*/
public function getIdSlide()
{
return $this->idSlide;
}
/**
* Set lnSource
*
* @param TDN\DocumentBundle\Entity\Document $lnSource
* @return Slider
*/
public function setLnSource(\TDN\DocumentBundle\Entity\Document $lnSource = null)
{
$this->lnSource = $lnSource;
return $this;
}
/**
* Get lnSource
*
* @return TDN\DocumentBundle\Entity\Document
*/
public function getLnSource()
{
return $this->lnSource;
}
/**
* Set lnCover
*
* @param TDN\ImageBundle\Entity\Image $lnCover
* @return Slider
*/
public function setLnCover(\TDN\ImageBundle\Entity\Image $lnCover = null)
{
$this->lnCover = $lnCover;
return $this;
}
/**
* Get lnCover
*
* @return TDN\ImageBundle\Entity\Image
*/
public function getLnCover()
{
return $this->lnCover;
}
/**
* Construit un nouveau slide
*
* @return Slider
*/
public function setup ($imageOwner = NULL) {
// Création de l'illustration de l'article en une
$imageSlider = $this->getLnCover();
if ($imageSlider instanceof Image) {
$now = new \DateTime;
$dossier = '/public/'.$now->format('Y').'/'.$now->format('m').'/';
$imageSlider->init($dossier, $imageOwner, $imageOwner);
}
$this->setOrdre(0);
if ($this->getStatut() == 1) {
$this->setDatePublication(new \DateTime);
}
return $this;
}
/**
* Construit un nouveau slide
*
* @return Slider
*/
public function make ($_TDNDocument) {
$imageOwner = $_TDNDocument->getLnAuteur();
// Création de l'illustration de l'article en une
$imageSlider = $this->getLnCover();
if ($imageSlider instanceof Image) {
$now = new \DateTime;
$dossier = '/public/'.$now->format('Y').'/'.$now->format('m').'/';
$imageSlider->init($dossier, $imageOwner, $imageOwner);
}
$this->setLnSource($_TDNDocument)->setDatePublication($_TDNDocument->getDatePublication());
if (is_null($slider->getStatut())) {
$this->setStatut(0);
}
$this->setOrdre(0);
if ($this->getStatut() == 1) {
$this->setDatePublication(new \DateTime);
}
return $this;
}
} | mit |
JuliaStats/MCMC.jl | doc/examples/swiss/MALA/forwarddiff.jl | 1025 | using Klara
covariates, = dataset("swiss", "measurements")
ndata, npars = size(covariates)
covariates = (covariates.-mean(covariates, 1))./repmat(std(covariates, 1), ndata, 1)
outcome, = dataset("swiss", "status")
outcome = vec(outcome)
function ploglikelihood(p::Vector, v::Vector)
Xp = v[2]*p
dot(Xp, v[3])-sum(log.(1+exp.(Xp)))
end
plogprior(p::Vector, v::Vector) = -0.5*(dot(p, p)/v[1]+length(p)*log(2*pi*v[1]))
p = BasicContMuvParameter(:p, loglikelihood=ploglikelihood, logprior=plogprior, nkeys=4, diffopts=DiffOptions(mode=:forward))
model = likelihood_model([Hyperparameter(:λ), Data(:X), Data(:y), p], isindexed=false)
mcsampler = MALA(0.1)
mcrange = BasicMCRange(nsteps=10000, burnin=1000)
v0 = Dict(:λ=>100., :X=>covariates, :y=>outcome, :p=>[5.1, -0.9, 8.2, -4.5])
outopts = Dict{Symbol, Any}(:monitor=>[:value, :logtarget, :gradlogtarget], :diagnostics=>[:accept])
job = BasicMCJob(model, mcsampler, mcrange, v0, outopts=outopts)
run(job)
chain = output(job)
mean(chain)
acceptance(chain)
| mit |
jovial/nim-libclang | examples/tokenize/samples/sample2.cc | 101 | typedef int sampleInt;
class C {
void f();
};
void hoge() {
sampleInt a = 10;
C c;
c.f();
}
| mit |
vertex/website | designs/blog/a-basic-introduction-to-mongodb.md | 17210 | _Using mongodb with [node-mongodb-native][2]
This post was written by [Node Knockout judge][3] and
[node-mongo-db-native][2] author Christian Kvalheim._
# A Basic introduction to Mongo DB
Mongo DB has rapidly grown to become a popular database for web applications and is a perfect fit for Node.JS applications, letting you write Javascript for the client, backend and database layer. Its schemaless nature is a better match to our constantly evolving data structures in web applications, and the integrated support for location queries is a bonus that's hard to ignore. Throw in Replica Sets for scaling, and we're looking at really nice platform to grow your storage needs now and in the future.
Now to shamelessly plug my driver. It can be downloaded via npm, or fetched from the github repository. To install via npm, do the following:
`npm install mongodb`
or go fetch it from github at [https://github.com/christkv/node-mongodb-native](https://github.com/christkv/node-mongodb-native)
Once this business is taken care of, let's move through the types available for the driver and then how to connect to your Mongo DB instance before facing the usage of some CRUD operations.
## Mongo DB data types
So there is an important thing to keep in mind when working with Mongo DB, and that is the slight mapping difference between types Mongo DB supports and native Javascript data types. Let's have a look at the types supported out of the box and then how types are promoted by the driver to fit as close to native Javascript types as possible.
* **Float** is a 8 byte and is directly convertible to the Javascript type Number
* **Double class** a special class representing a float value, this is especially useful when using capped collections where you need to ensure your values are always floats.
* **Integers** is a bit trickier due to the fact that Javascript represents all Numbers as 64 bit floats meaning that the maximum integer value is at a 53 bit. Mongo has two types for integers, a 32 bit and a 64 bit. The driver will try to fit the value into 32 bits if it can and promote it to 64 bits if it has to. Similarly it will deserialize attempting to fit it into 53 bits if it can. If it cannot it will return an instance of **Long** to avoid loosing precession.
* **Long class** a special class that let's you store 64 bit integers and also let's you operate on the 64 bits integers.
* **Date** maps directly to a Javascript Date
* **RegExp** maps directly to a Javascript RegExp
* **String** maps directly to a Javascript String (encoded in utf8)
* **Binary class** a special class that let's you store data in Mongo DB
* **Code class** a special class that let's you store javascript functions in Mongo DB, can also provide a scope to run the method in
* **ObjectID class** a special class that holds a MongoDB document identifier (the equivalent to a Primary key)
* **DbRef class** a special class that let's you include a reference in a document pointing to another object
* **Symbol class** a special class that let's you specify a symbol, not really relevant for javascript but for languages that supports the concept of symbols.
As we see the number type can be a little tricky due to the way integers are implemented in Javascript. The latest driver will do correct conversion up to 53 bit's of complexity. If you need to handle big integers the recommendation is to use the Long class to operate on the numbers.
## Getting that connection to the database
Let's get around to setting up a connection with the Mongo DB database. Jumping straight into the code let's do direct connection and then look at the code.
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
Let's have a quick look at how the connection code works. The **Db.connect**
method let's use use a uri to connect to the Mongo database, where
**localhost:27017** is the server host and port and **exampleDb** the db
we wish to connect to. After the url notice the hash containing the
**auto_reconnect** key. Auto reconnect tells the driver to retry sending
a command to the server if there is a failure during it's execution.
Another useful option you can pass in is
**poolSize**, this allows you to control how many tcp connections are
opened in parallel. The default value for this is 5 but you can set it
as high as you want. The driver will use a round-robin strategy to
dispatch and read from the tcp connection.
We are up and running with a connection to the database. Let's move on
and look at what collections are and how they work.
## Mongo DB and Collections
Collections are the equivalent of tables in traditional databases and contain all your documents. A database can have many collections. So how do we go about defining and using collections. Well there are a couple of methods that we can use. Let's jump straight into code and then look at the code.
**the requires and and other initializing stuff omitted for brevity**
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
db.collection('test', function(err, collection) {});
db.collection('test', {w:1}, function(err, collection) {});
db.createCollection('test', function(err, collection) {});
db.createCollection('test', {w:1}, function(err, collection) {});
});
Three different ways of creating a collection object but slightly different in behavior. Let's go through them and see what they do
db.collection('test', function(err, collection) {});
This function will not actually create a collection on the database until you actually insert the first document.
db.collection('test', {w:1}, function(err, collection) {});
Notice the **{w:1}** option. This option will make the driver check if the collection exists and issue an error if it does not.
db.createCollection('test', function(err, collection) {});
This command will create the collection on the Mongo DB database before returning the collection object. If the collection already exists it will ignore the creation of the collection.
db.createCollection('test', {w:1}, function(err, collection) {});
The **{w:1}** option will make the method return an error if the collection already exists.
With an open db connection and a collection defined we are ready to do some CRUD operation on the data.
## And then there was CRUD
So let's get dirty with the basic operations for Mongo DB. The Mongo DB wire protocol is built around 4 main operations **insert/update/remove/query**. Most operations on the database are actually queries with special json objects defining the operation on the database. But I'm getting ahead of myself. Let's go back and look at insert first and do it with some code.
**the requires and and other initializing stuff omitted for brevity**
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('test');
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];
collection.insert(doc1);
collection.insert(doc2, {w:1}, function(err, result) {});
collection.insert(lotsOfDocs, {w:1}, function(err, result) {});
});
A couple of variations on the theme of inserting a document as we can see. To understand why it's important to understand how Mongo DB works during inserts of documents.
Mongo DB has asynchronous **insert/update/remove** operations. This means that when you issue an **insert** operation its a fire and forget operation where the database does not reply with the status of the insert operation. To retrieve the status of the operation you have to issue a query to retrieve the last error status of the connection. To make it simpler to the developer the driver implements the **{w:1}** options so that this is done automatically when inserting the document. **{w:1}** becomes especially important when you do **update** or **remove** as otherwise it's not possible to determine the amount of documents modified or removed.
Now let's go through the different types of inserts shown in the code above.
collection.insert(doc1);
Taking advantage of the async behavior and not needing confirmation about the persisting of the data to Mongo DB we just fire off the insert (we are doing live analytics, loosing a couple of records does not matter).
collection.insert(doc2, {w:1}, function(err, result) {});
That document needs to stick. Using the **{w:1}** option ensure you get the error back if the document fails to insert correctly.
collection.insert(lotsOfDocs, {w:1}, function(err, result) {});
A batch insert of document with any errors being reported. This is much more efficient if you need to insert large batches of documents as you incur a lot less overhead.
Right that's the basics of insert's ironed out. We got some documents in there but want to update them as we need to change the content of a field. Let's have a look at a simple example and then we will dive into how Mongo DB updates work and how to do them efficiently.
**the requires and and other initializing stuff omitted for brevity**
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('test');
var doc = {mykey:1, fieldtoupdate:1};
collection.insert(doc, {w:1}, function(err, result) {
collection.update({mykey:1}, {$set:{fieldtoupdate:2}}, {w:1}, function(err, result) {});
});
var doc2 = {mykey:2, docs:[{doc1:1}]};
collection.insert(doc2, {w:1}, function(err, result) {
collection.update({mykey:2}, {$push:{docs:{doc2:1}}}, {w:1}, function(err, result) {});
});
});
Alright before we look at the code we want to understand how document updates work and how to do the efficiently. The most basic and less efficient way is to replace the whole document, this is not really the way to go if you want to change just a field in your document. Luckily Mongo DB provides a whole set of operations that let you modify just pieces of the document [Atomic operations documentation](http://www.mongodb.org/display/DOCS/Atomic+Operations). Basically outlined below.
* $inc - increment a particular value by a certain amount
* $set - set a particular value
* $unset - delete a particular field (v1.3+)
* $push - append a value to an array
* $pushAll - append several values to an array
* $addToSet - adds value to the array only if its not in the array already
* $pop - removes the last element in an array
* $pull - remove a value(s) from an existing array
* $pullAll - remove several value(s) from an existing array
* $rename - renames the field
* $bit - bitwise operations
Now that the operations are outline let's dig into the specific cases show in the code example.
collection.update({mykey:1}, {$set:{fieldtoupdate:2}}, {w:1}, function(err, result) {});
Right so this update will look for the document that has a field **mykey** equal to **1** and apply an update to the field **fieldtoupdate** setting the value to **2**. Since we are using the **{w:1}** option the result parameter in the callback will return the value **1** indicating that 1 document was modified by the update statement.
collection.update({mykey:2}, {$push:{docs:{doc2:1}}}, {w:1}, function(err, result) {});
This updates adds another document to the field **docs** in the document identified by **{mykey:2}** using the atomic operation **$push**. This allows you to modify keep such structures as queues in Mongo DB.
Let's have a look at the remove operation for the driver. As before let's start with a piece of code.
**the requires and and other initializing stuff omitted for brevity**
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('test');
var docs = [{mykey:1}, {mykey:2}, {mykey:3}];
collection.insert(docs, {w:1}, function(err, result) {
collection.remove({mykey:1});
collection.remove({mykey:2}, {w:1}, function(err, result) {});
collection.remove();
});
});
Let's examine the 3 remove variants and what they do.
collection.remove({mykey:1});
This leverages the fact that Mongo DB is asynchronous and that it does not return a result for **insert/update/remove** to allow for **synchronous** style execution. This particular remove query will remove the document where **mykey** equals **1**.
collection.remove({mykey:2}, {w:1}, function(err, result) {});
This remove statement removes the document where **mykey** equals **2** but since we are using **{w:1}** it will back to Mongo DB to get the status of the remove operation and return the number of documents removed in the result variable.
collection.remove();
This last one will remove all documents in the collection.
## Time to Query
Queries is of course a fundamental part of interacting with a database and Mongo DB is no exception. Fortunately for us it has a rich query interface with cursors and close to SQL concepts for slicing and dicing your datasets. To build queries we have lots of operators to choose from [Mongo DB advanced queries](http://www.mongodb.org/display/DOCS/Advanced+Queries). There are literarily tons of ways to search and ways to limit the query. Let's look at some simple code for dealing with queries in different ways.
**the requires and and other initializing stuff omitted for brevity**
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('test');
var docs = [{mykey:1}, {mykey:2}, {mykey:3}];
collection.insert(docs, {w:1}, function(err, result) {
collection.find().toArray(function(err, items) {});
var stream = collection.find({mykey:{$ne:2}}).stream();
stream.on("data", function(item) {});
stream.on("end", function() {});
collection.findOne({mykey:1}, function(err, item) {});
});
});
Before we start picking apart the code there is one thing that needs to be understood, the **find** method does not execute the actual query. It builds an instance of **Cursor** that you then use to retrieve the data. This lets you manage how you retrieve the data from Mongo DB and keeps state about your current Cursor state on Mongo DB. Now let's pick apart the queries we have here and look at what they do.
collection.find().toArray(function(err, items) {});
This query will fetch all the document in the collection and return them as an array of items. Be careful with the function **toArray** as it might cause a lot of memory usage as it will instantiate all the document into memory before returning the final array of items. If you have a big resultset you could run into memory issues.
var stream = collection.find({mykey:{$ne:2}}).stream();
stream.on("data", function(item) {});
stream.on("end", function() {});
This is the preferred way if you have to retrieve a lot of data for streaming, as data is deserialized a **data** event is emitted. This keeps the resident memory usage low as the documents are streamed to you. Very useful if you are pushing documents out via websockets or some other streaming socket protocol. Once there is no more document the driver will emit the **end** event to notify the application that it's done.
collection.findOne({mykey:1}, function(err, item) {});
This is special supported function to retrieve just one specific document bypassing the need for a cursor object.
That's pretty much it for the quick intro on how to use the database. I have also included a list of links to where to go to find more information and also a sample crude location application I wrote using express JS and mongo DB.
## Links and stuff
* [The driver examples, good starting point for basic usage](https://github.com/mongodb/node-mongodb-native/tree/master/examples)
* [All the integration tests, they have tons of different usage cases](https://github.com/mongodb/node-mongodb-native/tree/master/test)
* [The Mongo DB wiki pages such as the advanced query link](http://www.mongodb.org/display/DOCS/Advanced+Queries)
* [A silly simple location based application using Express JS and Mongo DB](https://github.com/christkv/mongodb-presentation) | mit |
Mrs-X/PIVX | src/test/skiplist_tests.cpp | 4078 | // Copyright (c) 2014 The Bitcoin Core developers
// Copyright (c) 2017-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "util.h"
#include "test/test_pivx.h"
#include <vector>
#include <boost/test/unit_test.hpp>
#define SKIPLIST_LENGTH 300000
BOOST_FIXTURE_TEST_SUITE(skiplist_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(skiplist_test)
{
std::vector<CBlockIndex> vIndex(SKIPLIST_LENGTH);
for (int i=0; i<SKIPLIST_LENGTH; i++) {
vIndex[i].nHeight = i;
vIndex[i].pprev = (i == 0) ? NULL : &vIndex[i - 1];
vIndex[i].BuildSkip();
}
for (int i=0; i<SKIPLIST_LENGTH; i++) {
if (i > 0) {
BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]);
BOOST_CHECK(vIndex[i].pskip->nHeight < i);
} else {
BOOST_CHECK(vIndex[i].pskip == NULL);
}
}
for (int i=0; i < 1000; i++) {
int from = InsecureRandRange(SKIPLIST_LENGTH - 1);
int to = InsecureRandRange(from + 1);
BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]);
BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]);
BOOST_CHECK(vIndex[from].GetAncestor(0) == &vIndex[0]);
}
}
BOOST_AUTO_TEST_CASE(getlocator_test)
{
// Build a main chain 100000 blocks long.
std::vector<uint256> vHashMain(100000);
std::vector<CBlockIndex> vBlocksMain(100000);
for (unsigned int i=0; i<vBlocksMain.size(); i++) {
vHashMain[i] = i; // Set the hash equal to the height, so we can quickly check the distances.
vBlocksMain[i].nHeight = i;
vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL;
vBlocksMain[i].phashBlock = &vHashMain[i];
vBlocksMain[i].BuildSkip();
BOOST_CHECK_EQUAL((int)vBlocksMain[i].GetBlockHash().GetLow64(), vBlocksMain[i].nHeight);
BOOST_CHECK(vBlocksMain[i].pprev == NULL || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1);
}
// Build a branch that splits off at block 49999, 50000 blocks long.
std::vector<uint256> vHashSide(50000);
std::vector<CBlockIndex> vBlocksSide(50000);
for (unsigned int i=0; i<vBlocksSide.size(); i++) {
vHashSide[i] = i + 50000 + (uint256(1) << 128); // Add 1<<128 to the hashes, so GetLow64() still returns the height.
vBlocksSide[i].nHeight = i + 50000;
vBlocksSide[i].pprev = i ? &vBlocksSide[i - 1] : &vBlocksMain[49999];
vBlocksSide[i].phashBlock = &vHashSide[i];
vBlocksSide[i].BuildSkip();
BOOST_CHECK_EQUAL((int)vBlocksSide[i].GetBlockHash().GetLow64(), vBlocksSide[i].nHeight);
BOOST_CHECK(vBlocksSide[i].pprev == NULL || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1);
}
// Build a CChain for the main branch.
CChain chain;
chain.SetTip(&vBlocksMain.back());
// Test 100 random starting points for locators.
for (int n=0; n<100; n++) {
int r = InsecureRandRange(150000);
CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000];
CBlockLocator locator = chain.GetLocator(tip);
// The first result must be the block itself, the last one must be genesis.
BOOST_CHECK(locator.vHave.front() == tip->GetBlockHash());
BOOST_CHECK(locator.vHave.back() == vBlocksMain[0].GetBlockHash());
// Entries 1 through 11 (inclusive) go back one step each.
for (unsigned int i = 1; i < 12 && i < locator.vHave.size() - 1; i++) {
BOOST_CHECK_EQUAL(locator.vHave[i].GetLow64(), tip->nHeight - i);
}
// The further ones (excluding the last one) go back with exponential steps.
unsigned int dist = 2;
for (unsigned int i = 12; i < locator.vHave.size() - 1; i++) {
BOOST_CHECK_EQUAL(locator.vHave[i - 1].GetLow64() - locator.vHave[i].GetLow64(), dist);
dist *= 2;
}
}
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
mrkeng/redis-sentinel | CHANGELOG.md | 1344 | # CHANGELOG
## 1.5.0
* Subscribe +switch-master again
* Prevents master discovery to get stuck in endless loop if sentinels
are not available
* Always reconnect at least once, even if reconnect timeout is 0
* Catch networking errors which bubble up past redis
## 1.4.4
* Allow client to return list of slaves
* Fix compatibility issues with ruby 1.8.7
## 1.4.3
* Fix for pipelined requests and readonly calls
## 1.4.2
* Fix sentinel reconnection broken
## 1.4.1
* Fix only one sentinel client reconnect issue
## 1.4.0
* Rewrite sentinel client to follow http://redis.io/topics/sentinel
* Parse uri string in sentinels array
## 1.3.0
* Add ability to reconnect all redis sentinel clients
* Avoid the config gets modified
* Reconnect if redis suddenly becones read-only
## 1.2.0
* Add redis synchrony support
* Add redis authentication support
## 1.1.4
* Fix discover_master procedure wich failover_reconnect_wait option
* Add test_wait_for_failover_write example
## 1.1.3
* Cache sentinel connections
* Add option failover_reconnect_timeout
* Add option failover_reconnect_wait
* Add test_wait_for_failover example
## 1.1.2
* Ruby 1.8.7 compatibility
## 1.1.1
* Fix initialize Redis::ConnectionError
## 1.1.0
* Remove background thread, which subscribes switch-master message
* Add example
## 1.0.0
* First version
| mit |
opsb/orbit-firebase | build-support/globalize-orbit.js | 253 | var Orbit = requireModule("orbit");
// Globalize loader properties for use by other Orbit packages
Orbit.__define__ = define;
Orbit.__requireModule__ = requireModule;
Orbit.__require__ = require;
Orbit.__requirejs__ = requirejs;
window.Orbit = Orbit;
| mit |
weppos/hanami-controller | test/unit/cache/directives_test.rb | 3932 | require 'test_helper'
describe 'Directives' do
describe '#directives' do
describe 'non value directives' do
it 'accepts public symbol' do
subject = Lotus::Action::Cache::Directives.new(:public)
subject.values.size.must_equal(1)
end
it 'accepts private symbol' do
subject = Lotus::Action::Cache::Directives.new(:private)
subject.values.size.must_equal(1)
end
it 'accepts no_cache symbol' do
subject = Lotus::Action::Cache::Directives.new(:no_cache)
subject.values.size.must_equal(1)
end
it 'accepts no_store symbol' do
subject = Lotus::Action::Cache::Directives.new(:no_store)
subject.values.size.must_equal(1)
end
it 'accepts no_transform symbol' do
subject = Lotus::Action::Cache::Directives.new(:no_transform)
subject.values.size.must_equal(1)
end
it 'accepts must_revalidate symbol' do
subject = Lotus::Action::Cache::Directives.new(:must_revalidate)
subject.values.size.must_equal(1)
end
it 'accepts proxy_revalidate symbol' do
subject = Lotus::Action::Cache::Directives.new(:proxy_revalidate)
subject.values.size.must_equal(1)
end
it 'does not accept weird symbol' do
subject = Lotus::Action::Cache::Directives.new(:weird)
subject.values.size.must_equal(0)
end
describe 'multiple symbols' do
it 'creates one directive for each valid symbol' do
subject = Lotus::Action::Cache::Directives.new(:private, :proxy_revalidate)
subject.values.size.must_equal(2)
end
end
describe 'private and public at the same time' do
it 'ignores public directive' do
subject = Lotus::Action::Cache::Directives.new(:private, :public)
subject.values.size.must_equal(1)
end
it 'creates one private directive' do
subject = Lotus::Action::Cache::Directives.new(:private, :public)
subject.values.first.name.must_equal(:private)
end
end
end
describe 'value directives' do
it 'accepts max_age symbol' do
subject = Lotus::Action::Cache::Directives.new(max_age: 600)
subject.values.size.must_equal(1)
end
it 'accepts s_maxage symbol' do
subject = Lotus::Action::Cache::Directives.new(s_maxage: 600)
subject.values.size.must_equal(1)
end
it 'accepts min_fresh symbol' do
subject = Lotus::Action::Cache::Directives.new(min_fresh: 600)
subject.values.size.must_equal(1)
end
it 'accepts max_stale symbol' do
subject = Lotus::Action::Cache::Directives.new(max_stale: 600)
subject.values.size.must_equal(1)
end
it 'does not accept weird symbol' do
subject = Lotus::Action::Cache::Directives.new(weird: 600)
subject.values.size.must_equal(0)
end
describe 'multiple symbols' do
it 'creates one directive for each valid symbol' do
subject = Lotus::Action::Cache::Directives.new(max_age: 600, max_stale: 600)
subject.values.size.must_equal(2)
end
end
end
describe 'value and non value directives' do
it 'creates one directive for each valid symbol' do
subject = Lotus::Action::Cache::Directives.new(:public, max_age: 600, max_stale: 600)
subject.values.size.must_equal(3)
end
end
end
end
describe 'ValueDirective' do
describe '#to_str' do
it 'returns as http cache format' do
subject = Lotus::Action::Cache::ValueDirective.new(:max_age, 600)
subject.to_str.must_equal('max-age=600')
end
end
end
describe 'NonValueDirective' do
describe '#to_str' do
it 'returns as http cache format' do
subject = Lotus::Action::Cache::NonValueDirective.new(:no_cache)
subject.to_str.must_equal('no-cache')
end
end
end
| mit |
tmcgee/cmv-wab-widgets | wab/2.15/jimu.js/BaseWidget.js | 12218 | ///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed 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.
///////////////////////////////////////////////////////////////////////////
define([
'dojo/_base/declare',
'dojo/_base/lang',
'dojo/_base/array',
'dojo/_base/html',
'dojo/topic',
'dijit/_WidgetBase',
'jimu/dijit/BindLabelPropsMixin',
'dijit/_TemplatedMixin',
'jimu/utils',
'./PanelManager'
], function(declare, lang, array, html, topic, _WidgetBase, BindLabelPropsMixin, _TemplatedMixin,
utils, PanelManager){
var clazz = declare([_WidgetBase, BindLabelPropsMixin, _TemplatedMixin], {
//type: String
// the value shoulb be widget
type: 'widget',
/****these properties can be configured (be overrided) in app's config.json*****/
//id: String
// the unique id of the widget, if not set in the config file,
// ConfigManager will generate one
id: undefined,
//label: String
// the display name of the widget
label: undefined,
//icon: String
// the uri of the icon, use images/icon.png if not set
icon: undefined,
//uir: String
// used in the config.json to locate where the widget is
uri: undefined,
/*======
//left: int
//top: int
//right: int
//bottom: int
//width: int
//height: int
======*/
// preload widget should config position property if it's not in group.
// the meaning of the property is the same as of the CSS
position: {},
//config: Object|String
// config info in config.json, url or json object
// if url is configured in the config.json, json file is parsed and stored in this property
config: undefined,
//defaultState: Boolean
openAtStart: false,
/***************************************************************/
/*********these properties is set by the framework**************/
//map: esri/Map|esri3d/Map
map: null,
//appConfig: Object
// the app's config.json
appConfig: null,
//folderUrl: String
// the folder url of the widget
folderUrl: null,
//state: String
// the current state of the widget, the available states are:
// opened, closed, active
state: 'closed',
//windowState: String
// the available states are normal, minimized, maximized
windowState: 'normal',
//started: boolean
// whether the widget has started
started: false,
//name: String
// the name is used to identify the widget. The name is the same as the widget folder name
name: '',
/***************************************************************/
/*********these properties is set by the developer**************/
//baseClass: String
// HTML CSS class name
baseClass: null,
//templateString: String
// widget UI part, the content of the file Widget.html will be set to this property
templateString: '<div></div>',
moveTopOnActive: true,
/***************************************************************/
constructor: function(){
//listenWidgetNames: String[]
// builder uses this property to filter widgets. App will not use this property to
// filter messages.
this.listenWidgetNames = [];
//listenWidgetIds: String[]
// app use this property to filter data message, if not set, all message will be received.
// this property can be set in config.json
this.listenWidgetIds = [];
//About the communication between widgets:
// * Two widgets can communicate each other directly, or transferred by DataManager.
// * If you want to share data, please call *publishData*. the published data will
// be stored in DataManager.
// * If you want to read share data, you can override *onReceiveData* method. Whenever
// any widgt publishes data, this method will be invoked. (communication directly)
// * If you want to read the data that published before your widget loaded, you can call
// *fetchData* method and get data in *onReceiveData* method. If the data contains
// history data, it will be availble in *historyData* parameter.
// (transferred by DataManager)
this.own(topic.subscribe('publishData', lang.hitch(this, this._onReceiveData)));
this.own(topic.subscribe('dataFetched', lang.hitch(this, this._onReceiveData)));
this.own(topic.subscribe('noData', lang.hitch(this, this._onNoData)));
this.own(topic.subscribe('dataSourceDataUpdated', lang.hitch(this, this.onDataSourceDataUpdate)));
},
startup: function(){
this.inherited(arguments);
this.started = true;
},
onOpen: function(){
// summary:
// this function will be called when widget is opened everytime.
// description:
// state has been changed to "opened" when call this method.
// this function will be called in two cases:
// 1. after widget's startup
// 2. if widget is closed, use re-open the widget
},
onClose: function(){
// summary:
// this function will be called when widget is closed.
// description:
// state has been changed to "closed" when call this method.
},
onNormalize: function(){
// summary:
// this function will be called when widget window is normalized.
// description:
// windowState has been changed to "normal" when call this method.
},
onMinimize: function(){
// summary:
// this function will be called when widget window is minimized.
// description:
// windowState has been changed to "minimized" when call this method.
},
onMaximize: function(){
// summary:
// this function will be called when widget window is maximized.
// description:
// windowState has been changed to "maximized" when call this method.
},
onActive: function(){
// summary:
// this function will be called when widget is clicked.
},
onDeActive: function(){
// summary:
// this function will be called when another widget is clicked.
},
onSignIn: function(credential){
// summary:
// this function will be called after user sign in.
/*jshint unused: false*/
},
onSignOut: function(){
// summary:
// this function will be called after user sign in.
},
onPositionChange: function(position){
//summary:
// this function will be called when position change,
// widget's position will be changed when layout change
// the position object may contain w/h/t/l/b/r
this.setPosition(position);
},
setPosition: function(position, containerNode){
//For on-screen off-panel widget, layout manager will call this function
//to set widget's position after load widget. If your widget will position by itself,
//please override this function.
this.position = position;
var style = utils.getPositionStyle(this.position);
style.position = 'absolute';
if(!containerNode){
if(position.relativeTo === 'map'){
containerNode = this.map.id;
}else{
containerNode = window.jimuConfig.layoutId;
}
}
html.place(this.domNode, containerNode);
html.setStyle(this.domNode, style);
if(this.started){
this.resize();
}
},
getPosition: function(){
return this.position;
},
getMarginBox: function() {
var box = html.getMarginBox(this.domNode);
return box;
},
setMap: function( /*esri.Map*/ map){
this.map = map;
},
setState: function(state){
this.state = state;
},
setWindowState: function(state){
this.windowState = state;
},
resize: function(){
},
//these three methods are used by builder.
onConfigChanged: function(config){
/*jshint unused: false*/
},
onAppConfigChanged: function(appConfig, reason, changedData){
/*jshint unused: false*/
},
onAction: function(action, data){
/*jshint unused: false*/
},
getPanel: function(){
//get panel of the widget. return null for off-panel widget.
if(this.inPanel === false){
return null;
}
if(this.gid === 'widgetOnScreen' || this.gid === 'widgetPool'){
return PanelManager.getInstance().getPanelById(this.id + '_panel');
}else{
//it's in group
var panel = PanelManager.getInstance().getPanelById(this.gid + '_panel');
if(panel){
//open all widgets in group together
return panel;
}else{
return PanelManager.getInstance().getPanelById(this.id + '_panel');
}
}
},
publishData: function(data, keepHistory){
//if set keepHistory = true, all published data will be stored in datamanager,
//this may cause memory problem.
if(typeof keepHistory === 'undefined'){
//by default, we don't keep the history of the data.
keepHistory = false;
}
topic.publish('publishData', this.name, this.id, data, keepHistory);
},
fetchData: function(widgetId){
//widgetId, the widget id that you want to read data. it is optional.
if(widgetId){
topic.publish('fetchData', widgetId);
}else{
if(this.listenWidgetIds.length !== 0){
array.forEach(this.listenWidgetIds, function(widgetId){
topic.publish('fetchData', widgetId);
}, this);
}else{
topic.publish('fetchData');
}
}
},
fetchDataByName: function(widgetName){
//widgetId, the widget name that you want to read data. it is required.
var widgets = this.widgetManager.getWidgetsByName(widgetName);
array.forEach(widgets, function(widget){
this.fetchData(widget.id);
}, this);
},
openWidgetById: function(widgetId){
return this.widgetManager.triggerWidgetOpen(widgetId);
},
_onReceiveData: function(name, widgetId, data, historyData){
//the data is what I published
if(widgetId === this.id){
return;
}
//I am not interested in the the widget id
if(this.listenWidgetIds.length !== 0 && this.listenWidgetIds.indexOf(widgetId) < 0){
return;
}
this.onReceiveData(name, widgetId, data, historyData);
},
onReceiveData: function(name, widgetId, data, historyData){
/* jshint unused: false */
// console.log('onReceiveData: ' + name + ',' + widgetId + ',data:' + data);
/****************About historyData:
The historyData maybe: undefined, true, object(data)
undefined: means data published without history
true: means data published with history. If this widget want to fetch history data,
Please call fetch data.
object: the history data.
*********************************/
},
updateDataSourceData: function(dsId, data){
topic.publish('updateDataSourceData', 'widget~' + this.id + '~' + dsId, data);
},
onDataSourceDataUpdate: function(dsId, data){
/* jshint unused: false */
},
_onNoData: function(name, widgetId){
/*jshint unused: false*/
if(this.listenWidgetIds.length !== 0 && this.listenWidgetIds.indexOf(widgetId) < 0){
return;
}
this.onNoData(name, widgetId);
},
onNoData: function(name, widgetId){
/*jshint unused: false*/
}
});
return clazz;
}); | mit |
zhouxh1023/nxogre | build/source/NxOgreResourceSystem.h | 4215 | /**
This file is part of NxOgre.
Copyright (c) 2009 Robin Southern, http://www.nxogre.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef NXOGRE_RESOURCESYSTEM_H
#define NXOGRE_RESOURCESYSTEM_H
#include "NxOgreStable.h"
#include "NxOgreCommon.h"
#include "NxOgreResourceProtocol.h"
namespace NxOgre
{
/** \brief
*/
class NxOgrePublicClass ResourceSystem : public ::NxOgre::Singleton<ResourceSystem>, public BigClassAllocatable
{
friend class World;
public: // Functions
NXOGRE_GC_FRIEND_NEW0
NXOGRE_GC_FRIEND_DELETE
typedef map<size_t, ResourceProtocol*> Protocols;
typedef map_iterator<size_t, ResourceProtocol*> ProtocolIterator;
/** \brief Open an resource, using an Path. Archive will be created or opened based of the directories of the file, unless specified
by the protocol.
\usage
<code>
resource_system_ptr->open("file://c:/Program Files/My Game/Game.txt", Enums::ResourceAccess_ReadOnly);
</code>
\note In the event of the resource not existing in the archive, the ResourceProtocol may create one for you.
*/
Resource* open(const Path&, Enums::ResourceAccess = Enums::ResourceAccess_ReadOnly);
/*! function. close
desc.
Close a resource.
*/
void close(Resource*);
/*! function. getProtocols
desc.
Return an iterator to the current protocols loaded.
return.
ProtocolIterator -- The iterator.
*/
ProtocolIterator getProtocols();
/*! constructor. openProtocol
desc.
Open a resource protocol, pointer is owned by the ResourceSystem when passed on.
ResourceProtocols last the entire lifetime of the ResourceSystem, so they can never
be closed.
note.
The Protocol will be deleted according to its destruction policy. (ResourceProtocol::getDestructionPolicy)
*/
void openProtocol(ResourceProtocol*);
protected:
/*! constructor. ResourceSystem
desc.
Private Constructor
see.
World::precreateSingletons() or World::createWorld()
*/
ResourceSystem();
/*! destructor. ResourceSystem
desc.
Private Destructor
see.
World::destroySingletons() or World::destroyWorld()
*/
~ResourceSystem();
/* \internal
mProtocols
Loaded protocols stored in an associative container using a StringHash as the protocol's lowercase
name with the ResourceProtocol stored and owned by the container.
*/
Protocols mProtocols;
}; // class ResourceSystem
} // namespace NxOgre
#endif
| mit |
ryo88c/ChatWorkNotify | var/www/index.php | 102 | <?php
$context = 'prod-hal-api-app';
require dirname(dirname(__DIR__)) . '/bootstrap/bootstrap.php';
| mit |
akarys92/astro_site | vendor/scrollreveal/_vti_cnf/scrollreveal.min.js | 176 | vti_encoding:SR|utf8-nl
vti_timelastmodified:TR|09 Feb 2017 03:34:58 -0000
vti_extenderversion:SR|6.0.2.8161
vti_backlinkinfo:VX|astro_site/mobile.html astro_site/mobile2.html
| mit |
Pvlerick/AutoFixture | Src/AutoFakeItEasy/GlobalSuppressions.cs | 805 | // This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click
// "In Project Suppression File".
// You do not need to add suppressions to this file manually.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes",
Scope = "namespace", Target = "AutoFixture.AutoFakeItEasy",
Justification = "This should be a separate assembly because it provides extensions to AutoFixture that are specific to the use of FakeItEasy.")]
| mit |
scvetkovski/Shortest-Path-Algorithm | snap/glib-core/ds.h | 105284 | /////////////////////////////////////////////////
// Address-Pointer
template <class TRec>
class TAPt{
private:
TRec* Addr;
public:
TAPt(): Addr(NULL){}
TAPt(const TAPt& Pt): Addr(Pt.Addr){}
TAPt(TRec* _Addr): Addr(_Addr){}
TAPt(TSIn&){Fail;}
void Save(TSOut&) const {Fail;}
TAPt& operator=(const TAPt& Pt){Addr=Pt.Addr; return *this;}
TAPt& operator=(TRec* _Addr){Addr=_Addr; return *this;}
bool operator==(const TAPt& Pt) const {return *Addr==*Pt.Addr;}
bool operator!=(const TAPt& Pt) const {return *Addr!=*Pt.Addr;}
bool operator<(const TAPt& Pt) const {return *Addr<*Pt.Addr;}
TRec* operator->() const {Assert(Addr!=NULL); return Addr;}
TRec& operator*() const {Assert(Addr!=NULL); return *Addr;}
TRec& operator[](const int& RecN) const {
Assert(Addr!=NULL); return Addr[RecN];}
TRec* operator()() const {return Addr;}
bool Empty() const {return Addr==NULL;}
};
/////////////////////////////////////////////////
// Pair
template <class TVal1, class TVal2>
class TPair{
public:
TVal1 Val1;
TVal2 Val2;
public:
TPair(): Val1(), Val2(){}
TPair(const TPair& Pair): Val1(Pair.Val1), Val2(Pair.Val2){}
TPair(const TVal1& _Val1, const TVal2& _Val2): Val1(_Val1), Val2(_Val2){}
explicit TPair(TSIn& SIn): Val1(SIn), Val2(SIn){}
void Save(TSOut& SOut) const {
Val1.Save(SOut); Val2.Save(SOut);}
void Load(TSIn& SIn) {Val1.Load(SIn); Val2.Load(SIn);}
void LoadXml(const PXmlTok& XmlTok, const TStr& Nm="");
void SaveXml(TSOut& SOut, const TStr& Nm) const;
TPair& operator=(const TPair& Pair){
if (this!=&Pair){Val1=Pair.Val1; Val2=Pair.Val2;} return *this;}
bool operator==(const TPair& Pair) const {
return (Val1==Pair.Val1)&&(Val2==Pair.Val2);}
bool operator<(const TPair& Pair) const {
return (Val1<Pair.Val1)||((Val1==Pair.Val1)&&(Val2<Pair.Val2));}
int GetMemUsed() const {return Val1.GetMemUsed()+Val2.GetMemUsed();}
int GetPrimHashCd() const {return TPairHashImpl::GetHashCd(Val1.GetPrimHashCd(), Val2.GetPrimHashCd()); }
int GetSecHashCd() const {return TPairHashImpl::GetHashCd(Val2.GetSecHashCd(), Val1.GetSecHashCd()); }
void GetVal(TVal1& _Val1, TVal2& _Val2) const {_Val1=Val1; _Val2=Val2;}
const TVal1& GetVal1() const { return Val1;}
const TVal2& GetVal2() const { return Val2;}
TStr GetStr() const {
return TStr("Pair(")+Val1.GetStr()+", "+Val2.GetStr()+")";}
};
template <class TVal1, class TVal2, class TSizeTy>
void GetSwitchedPrV(const TVec<TPair<TVal1, TVal2>, TSizeTy>& SrcPrV, TVec<TPair<TVal2, TVal1>, TSizeTy>& DstPrV){
const TSizeTy Prs = SrcPrV.Len();
DstPrV.Gen(Prs, 0);
for (TSizeTy PrN=0; PrN<Prs; PrN++){
const TPair<TVal1, TVal2>& SrcPr=SrcPrV[PrN];
DstPrV.Add(TPair<TVal2, TVal1>(SrcPr.Val2, SrcPr.Val1));
}
}
typedef TPair<TBool, TCh> TBoolChPr;
typedef TPair<TBool, TFlt> TBoolFltPr;
typedef TPair<TUCh, TInt> TUChIntPr;
typedef TPair<TUCh, TUInt64> TUChUInt64Pr;
typedef TPair<TUCh, TStr> TUChStrPr;
typedef TPair<TInt, TBool> TIntBoolPr;
typedef TPair<TInt, TCh> TIntChPr;
typedef TPair<TInt, TInt> TIntPr;
typedef TPair<TInt, TUInt64> TIntUInt64Pr;
typedef TPair<TInt, TIntPr> TIntIntPrPr;
typedef TPair<TInt, TVec<TInt, int> > TIntIntVPr;
typedef TPair<TInt, TFlt> TIntFltPr;
typedef TPair<TInt, TStr> TIntStrPr;
typedef TPair<TInt, TStrV> TIntStrVPr;
typedef TPair<TIntPr, TInt> TIntPrIntPr;
typedef TPair<TUInt, TUInt> TUIntUIntPr;
typedef TPair<TUInt, TInt> TUIntIntPr;
typedef TPair<TUInt64, TInt> TUInt64IntPr;
typedef TPair<TUInt64, TUInt64> TUInt64Pr;
typedef TPair<TUInt64, TFlt> TUInt64FltPr;
typedef TPair<TUInt64, TStr> TUInt64StrPr;
typedef TPair<TFlt, TInt> TFltIntPr;
typedef TPair<TFlt, TUInt64> TFltUInt64Pr;
typedef TPair<TFlt, TFlt> TFltPr;
typedef TPair<TFlt, TStr> TFltStrPr;
typedef TPair<TAscFlt, TInt> TAscFltIntPr;
typedef TPair<TAscFlt, TAscFlt> TAscFltPr;
typedef TPair<TFlt, TStr> TFltStrPr;
typedef TPair<TAscFlt, TStr> TAscFltStrPr;
typedef TPair<TStr, TInt> TStrIntPr;
typedef TPair<TStr, TFlt> TStrFltPr;
typedef TPair<TStr, TStr> TStrPr;
typedef TPair<TStr, TStrV> TStrStrVPr;
typedef TPair<TStrV, TInt> TStrVIntPr;
typedef TPair<TInt, TIntPr> TIntIntPrPr;
typedef TPair<TInt, TStrPr> TIntStrPrPr;
typedef TPair<TFlt, TStrPr> TFltStrPrPr;
/// Compares the pair by the second value.
template <class TVal1, class TVal2>
class TCmpPairByVal2 {
private:
bool IsAsc;
public:
TCmpPairByVal2(const bool& AscSort=true) : IsAsc(AscSort) { }
bool operator () (const TPair<TVal1, TVal2>& P1, const TPair<TVal1, TVal2>& P2) const {
if (IsAsc) { return P1.Val2 < P2.Val2; } else { return P2.Val2 < P1.Val2; }
}
};
/////////////////////////////////////////////////
// Triple
template <class TVal1, class TVal2, class TVal3>
class TTriple{
public:
TVal1 Val1;
TVal2 Val2;
TVal3 Val3;
public:
TTriple(): Val1(), Val2(), Val3(){}
TTriple(const TTriple& Triple):
Val1(Triple.Val1), Val2(Triple.Val2), Val3(Triple.Val3){}
TTriple(const TVal1& _Val1, const TVal2& _Val2, const TVal3& _Val3):
Val1(_Val1), Val2(_Val2), Val3(_Val3){}
explicit TTriple(TSIn& SIn): Val1(SIn), Val2(SIn), Val3(SIn){}
void Save(TSOut& SOut) const {
Val1.Save(SOut); Val2.Save(SOut); Val3.Save(SOut);}
void LoadXml(const PXmlTok& XmlTok, const TStr& Nm="");
void SaveXml(TSOut& SOut, const TStr& Nm) const;
TTriple& operator=(const TTriple& Triple){
if (this!=&Triple){Val1=Triple.Val1; Val2=Triple.Val2; Val3=Triple.Val3;}
return *this;}
bool operator==(const TTriple& Triple) const {
return (Val1==Triple.Val1)&&(Val2==Triple.Val2)&&(Val3==Triple.Val3);}
bool operator<(const TTriple& Triple) const {
return (Val1<Triple.Val1)||((Val1==Triple.Val1)&&(Val2<Triple.Val2))||
((Val1==Triple.Val1)&&(Val2==Triple.Val2)&&(Val3<Triple.Val3));}
int GetPrimHashCd() const {return TPairHashImpl::GetHashCd(TPairHashImpl::GetHashCd(Val1.GetPrimHashCd(), Val2.GetPrimHashCd()), Val3.GetPrimHashCd()); }
int GetSecHashCd() const {return TPairHashImpl::GetHashCd(TPairHashImpl::GetHashCd(Val2.GetSecHashCd(), Val3.GetSecHashCd()), Val1.GetSecHashCd()); }
int GetMemUsed() const {return Val1.GetMemUsed()+Val2.GetMemUsed()+Val3.GetMemUsed();}
void GetVal(TVal1& _Val1, TVal2& _Val2, TVal3& _Val3) const {
_Val1=Val1; _Val2=Val2; _Val3=Val3;}
};
typedef TTriple<TCh, TCh, TCh> TChTr;
typedef TTriple<TCh, TInt, TInt> TChIntIntTr;
typedef TTriple<TUCh, TInt, TInt> TUChIntIntTr;
typedef TTriple<TInt, TInt, TInt> TIntTr;
typedef TTriple<TUInt64, TUInt64, TUInt64> TUInt64Tr;
typedef TTriple<TInt, TStr, TInt> TIntStrIntTr;
typedef TTriple<TInt, TInt, TStr> TIntIntStrTr;
typedef TTriple<TInt, TInt, TFlt> TIntIntFltTr;
typedef TTriple<TInt, TFlt, TInt> TIntFltIntTr;
typedef TTriple<TInt, TFlt, TFlt> TIntFltFltTr;
typedef TTriple<TInt, TVec<TInt, int>, TInt> TIntIntVIntTr;
typedef TTriple<TInt, TInt, TVec<TInt, int> > TIntIntIntVTr;
typedef TTriple<TFlt, TFlt, TFlt> TFltTr;
typedef TTriple<TFlt, TInt, TInt> TFltIntIntTr;
typedef TTriple<TFlt, TFlt, TInt> TFltFltIntTr;
typedef TTriple<TFlt, TFlt, TStr> TFltFltStrTr;
typedef TTriple<TChA, TChA, TChA> TChATr;
typedef TTriple<TStr, TStr, TStr> TStrTr;
typedef TTriple<TStr, TInt, TInt> TStrIntIntTr;
typedef TTriple<TStr, TFlt, TFlt> TStrFltFltTr;
typedef TTriple<TStr, TStr, TInt> TStrStrIntTr;
typedef TTriple<TStr, TInt, TStrV> TStrIntStrVTr;
/// Compares the triple by the second value.
template <class TVal1, class TVal2, class TVal3>
class TCmpTripleByVal2 {
private:
bool IsAsc;
public:
TCmpTripleByVal2(const bool& AscSort=true) : IsAsc(AscSort) { }
bool operator () (const TTriple<TVal1, TVal2, TVal3>& T1, const TTriple<TVal1, TVal2, TVal3>& T2) const {
if (IsAsc) { return T1.Val2 < T2.Val2; } else { return T2.Val2 < T1.Val2; }
}
};
/// Compares the triple by the third value.
template <class TVal1, class TVal2, class TVal3>
class TCmpTripleByVal3 {
private:
bool IsAsc;
public:
TCmpTripleByVal3(const bool& AscSort=true) : IsAsc(AscSort) { }
bool operator () (const TTriple<TVal1, TVal2, TVal3>& T1, const TTriple<TVal1, TVal2, TVal3>& T2) const {
if (IsAsc) { return T1.Val3 < T2.Val3; } else { return T2.Val3 < T1.Val3; }
}
};
/////////////////////////////////////////////////
// Quad
template <class TVal1, class TVal2, class TVal3, class TVal4>
class TQuad{
public:
TVal1 Val1;
TVal2 Val2;
TVal3 Val3;
TVal4 Val4;
public:
TQuad():
Val1(), Val2(), Val3(), Val4(){}
TQuad(const TQuad& Quad):
Val1(Quad.Val1), Val2(Quad.Val2), Val3(Quad.Val3), Val4(Quad.Val4){}
TQuad(const TVal1& _Val1, const TVal2& _Val2, const TVal3& _Val3, const TVal4& _Val4):
Val1(_Val1), Val2(_Val2), Val3(_Val3), Val4(_Val4){}
explicit TQuad(TSIn& SIn):
Val1(SIn), Val2(SIn), Val3(SIn), Val4(SIn){}
void Save(TSOut& SOut) const {
Val1.Save(SOut); Val2.Save(SOut); Val3.Save(SOut); Val4.Save(SOut);}
void LoadXml(const PXmlTok& XmlTok, const TStr& Nm="");
void SaveXml(TSOut& SOut, const TStr& Nm) const;
TQuad& operator=(const TQuad& Quad){
if (this!=&Quad){
Val1=Quad.Val1; Val2=Quad.Val2; Val3=Quad.Val3; Val4=Quad.Val4;}
return *this;}
bool operator==(const TQuad& Quad) const {
return (Val1==Quad.Val1)&&(Val2==Quad.Val2)&&(Val3==Quad.Val3)&&(Val4==Quad.Val4);}
bool operator<(const TQuad& Quad) const {
return (Val1<Quad.Val1)||((Val1==Quad.Val1)&&(Val2<Quad.Val2))||
((Val1==Quad.Val1)&&(Val2==Quad.Val2)&&(Val3<Quad.Val3))||
((Val1==Quad.Val1)&&(Val2==Quad.Val2)&&(Val3==Quad.Val3)&&(Val4<Quad.Val4));}
int GetPrimHashCd() const {return TPairHashImpl::GetHashCd(TPairHashImpl::GetHashCd(Val1.GetPrimHashCd(), Val2.GetPrimHashCd()), TPairHashImpl::GetHashCd(Val3.GetPrimHashCd(), Val4.GetPrimHashCd())); }
int GetSecHashCd() const {return TPairHashImpl::GetHashCd(TPairHashImpl::GetHashCd(Val2.GetSecHashCd(), Val3.GetSecHashCd()), TPairHashImpl::GetHashCd(Val4.GetSecHashCd(), Val1.GetSecHashCd())); }
void GetVal(TVal1& _Val1, TVal2& _Val2, TVal3& _Val3, TVal4& _Val4) const {
_Val1=Val1; _Val2=Val2; _Val3=Val3; _Val4=Val4;}
};
typedef TQuad<TStr, TStr, TInt, TInt> TStrStrIntIntQu;
typedef TQuad<TStr, TStr, TStr, TStr> TStrQu;
typedef TQuad<TInt, TInt, TInt, TInt> TIntQu;
typedef TQuad<TFlt, TFlt, TFlt, TFlt> TFltQu;
typedef TQuad<TFlt, TInt, TInt, TInt> TFltIntIntIntQu;
typedef TQuad<TInt, TStr, TInt, TInt> TIntStrIntIntQu;
typedef TQuad<TInt, TInt, TFlt, TFlt> TIntIntFltFltQu;
/////////////////////////////////////////////////
// Tuple
template<class TVal, int NVals>
class TTuple {
private:
TVal ValV [NVals];
public:
TTuple(){}
TTuple(const TVal& InitVal) { for (int i=0; i<Len(); i++) ValV[i]=InitVal; }
TTuple(const TTuple& Tup) { for (int i=0; i<Len(); i++) ValV[i]=Tup[i]; }
TTuple(TSIn& SIn) { for (int i=0; i<Len(); i++) ValV[i].Load(SIn); }
void Save(TSOut& SOut) const { for (int i=0; i<Len(); i++) ValV[i].Save(SOut); }
void Load(TSIn& SIn) { for (int i=0; i<Len(); i++) ValV[i].Load(SIn); }
int Len() const { return NVals; }
TVal& operator[] (const int& ValN) { return ValV[ValN]; }
const TVal& operator[] (const int& ValN) const { return ValV[ValN]; }
TTuple& operator = (const TTuple& Tup) { if (this != & Tup) {
for (int i=0; i<Len(); i++) ValV[i]=Tup[i]; } return *this; }
bool operator == (const TTuple& Tup) const {
if (Len()!=Tup.Len()) { return false; } if (&Tup==this) { return true; }
for (int i=0; i<Len(); i++) if(ValV[i]!=Tup[i]){return false;} return true; }
bool operator < (const TTuple& Tup) const {
if (Len() == Tup.Len()) { for (int i=0; i<Len(); i++) {
if(ValV[i]<Tup[i]){return true;} else if(ValV[i]>Tup[i]){return false;} } return false; }
else { return Len() < Tup.Len(); } }
void Sort(const bool& Asc=true);
int FindMx() const;
int FindMn() const;
int GetPrimHashCd() const { int hc = 0;
for (int i = 0; i < NVals; i++) { hc = TPairHashImpl::GetHashCd(hc, ValV[i].GetPrimHashCd()); }
return hc; }
int GetSecHashCd() const { int hc = 0;
for (int i = 1; i < NVals; i++) { hc = TPairHashImpl::GetHashCd(hc, ValV[i].GetSecHashCd()); }
if (NVals > 0) { hc = TPairHashImpl::GetHashCd(hc, ValV[0].GetSecHashCd()); }
return hc; }
TStr GetStr() const { TChA ValsStr;
for (int i=0; i<Len(); i++) { ValsStr+=" "+ValV[i].GetStr(); }
return TStr::Fmt("Tuple(%d):", Len())+ValsStr; }
};
template<class TVal, int NVals>
void TTuple<TVal, NVals>::Sort(const bool& Asc) {
TVec<TVal, int> V(NVals);
for (int i=0; i<NVals; i++) { V.Add(ValV[i]); }
V.Sort(Asc);
for (int i=0; i<NVals; i++) { ValV[i] = V[i]; }
}
template<class TVal, int NVals>
int TTuple<TVal, NVals>::FindMx() const {
TVal MxVal = ValV[0];
int ValN = 0;
for (int i = 1; i < NVals; i++) {
if (MxVal<ValV[i]) {
MxVal=ValV[i]; ValN=i;
}
}
return ValN;
}
template<class TVal, int NVals>
int TTuple<TVal, NVals>::FindMn() const {
TVal MnVal = ValV[0];
int ValN = 0;
for (int i = 1; i < NVals; i++) {
if (MnVal>ValV[i]) {
MnVal=ValV[i]; ValN=i;
}
}
return ValN;
}
/////////////////////////////////////////////////
// Key-Data
template <class TKey, class TDat>
class TKeyDat{
public:
TKey Key;
TDat Dat;
public:
TKeyDat(): Key(), Dat(){}
TKeyDat(const TKeyDat& KeyDat): Key(KeyDat.Key), Dat(KeyDat.Dat){}
explicit TKeyDat(const TKey& _Key): Key(_Key), Dat(){}
TKeyDat(const TKey& _Key, const TDat& _Dat): Key(_Key), Dat(_Dat){}
explicit TKeyDat(TSIn& SIn): Key(SIn), Dat(SIn){}
void Save(TSOut& SOut) const {Key.Save(SOut); Dat.Save(SOut);}
void LoadXml(const PXmlTok& XmlTok, const TStr& Nm="");
void SaveXml(TSOut& SOut, const TStr& Nm) const;
TKeyDat& operator=(const TKeyDat& KeyDat){
if (this!=&KeyDat){Key=KeyDat.Key; Dat=KeyDat.Dat;} return *this;}
bool operator==(const TKeyDat& KeyDat) const {return Key==KeyDat.Key;}
bool operator<(const TKeyDat& KeyDat) const {return Key<KeyDat.Key;}
int GetPrimHashCd() const {return Key.GetPrimHashCd();}
int GetSecHashCd() const {return Key.GetSecHashCd();}
};
template <class TKey, class TDat>
void GetSwitchedKdV(const TVec<TKeyDat<TKey, TDat>, int>& SrcKdV, TVec<TKeyDat<TDat, TKey>, int>& DstKdV){
const int Kds=SrcKdV.Len();
DstKdV.Gen(Kds, 0);
for (int KdN=0; KdN<Kds; KdN++){
const TKeyDat<TKey, TDat>& SrcKd=SrcKdV[KdN];
DstKdV.Add(TKeyDat<TDat, TKey>(SrcKd.Dat, SrcKd.Key));
}
}
typedef TKeyDat<TInt, TInt> TIntKd;
typedef TKeyDat<TInt, TUInt64> TIntUInt64Kd;
typedef TKeyDat<TInt, TFlt> TIntFltKd;
typedef TKeyDat<TIntPr, TFlt> TIntPrFltKd;
typedef TKeyDat<TInt, TFltPr> TIntFltPrKd;
typedef TKeyDat<TInt, TSFlt> TIntSFltKd;
typedef TKeyDat<TInt, TStr> TIntStrKd;
typedef TKeyDat<TUInt, TInt> TUIntIntKd;
typedef TKeyDat<TUInt, TUInt> TUIntKd;
typedef TKeyDat<TUInt64, TInt> TUInt64IntKd;
typedef TKeyDat<TUInt64, TFlt> TUInt64FltKd;
typedef TKeyDat<TUInt64, TStr> TUInt64StrKd;
typedef TKeyDat<TFlt, TBool> TFltBoolKd;
typedef TKeyDat<TFlt, TInt> TFltIntKd;
typedef TKeyDat<TFlt, TUInt64> TFltUInt64Kd;
typedef TKeyDat<TFlt, TIntPr> TFltIntPrKd;
typedef TKeyDat<TFlt, TUInt> TFltUIntKd;
typedef TKeyDat<TFlt, TFlt> TFltKd;
typedef TKeyDat<TFlt, TStr> TFltStrKd;
typedef TKeyDat<TFlt, TBool> TFltBoolKd;
typedef TKeyDat<TFlt, TIntBoolPr> TFltIntBoolPrKd;
typedef TKeyDat<TAscFlt, TInt> TAscFltIntKd;
typedef TKeyDat<TStr, TBool> TStrBoolKd;
typedef TKeyDat<TStr, TInt> TStrIntKd;
typedef TKeyDat<TStr, TFlt> TStrFltKd;
typedef TKeyDat<TStr, TAscFlt> TStrAscFltKd;
typedef TKeyDat<TStr, TStr> TStrKd;
// Key-Data comparator
template <class TVal1, class TVal2>
class TCmpKeyDatByDat {
private:
bool IsAsc;
public:
TCmpKeyDatByDat(const bool& AscSort=true) : IsAsc(AscSort) { }
bool operator () (const TKeyDat<TVal1, TVal2>& P1, const TKeyDat<TVal1, TVal2>& P2) const {
if (IsAsc) { return P1.Dat < P2.Dat; } else { return P2.Dat < P1.Dat; }
}
};
//#//////////////////////////////////////////////
/// Vector is a sequence \c TVal objects representing an array that can change in size. ##TVec
template <class TVal, class TSizeTy = int>
class TVec{
public:
typedef TVal* TIter; //!< Random access iterator to \c TVal.
protected:
TSizeTy MxVals; //!< Vector capacity. Capacity is the size of allocated storage. If <tt>MxVals==-1</tt>, then \c ValT is not owned by the vector, and it won't free it at destruction.
TSizeTy Vals; //!< Vector length. Length is the number of elements stored in the vector.
TVal* ValT; //!< Pointer to the memory where the elements of the vector are stored.
/// Resizes the vector so that it can store at least \c _MxVals.
void Resize(const TSizeTy& _MxVals=-1);
/// Constructs the out of bounds error message.
TStr GetXOutOfBoundsErrMsg(const TSizeTy& ValN) const;
public:
TVec(): MxVals(0), Vals(0), ValT(NULL){}
TVec(const TVec<TVal, TSizeTy>& Vec);
/// Constructs a vector (an array) of length \c _Vals.
explicit TVec(const TSizeTy& _Vals){
IAssert(0<=_Vals); MxVals=Vals=_Vals;
if (_Vals==0){ValT=NULL;} else {ValT=new TVal[_Vals];}}
/// Constructs a vector (an array) of length \c _Vals, while reserving enough memory to store \c _MxVals elements.
TVec(const TSizeTy& _MxVals, const TSizeTy& _Vals){
IAssert((0<=_Vals)&&(_Vals<=_MxVals)); MxVals=_MxVals; Vals=_Vals;
if (_MxVals==0){ValT=NULL;} else {ValT=new TVal[_MxVals];}}
/// Constructs a vector of \c _Vals elements of memory array \c _ValT. ##TVec::TVec
explicit TVec(TVal *_ValT, const TSizeTy& _Vals):
MxVals(-1), Vals(_Vals), ValT(_ValT){}
~TVec(){if ((ValT!=NULL) && (MxVals!=-1)){delete[] ValT;}}
explicit TVec(TSIn& SIn): MxVals(0), Vals(0), ValT(NULL){Load(SIn);}
void Load(TSIn& SIn);
void Save(TSOut& SOut) const;
void LoadXml(const PXmlTok& XmlTok, const TStr& Nm="");
void SaveXml(TSOut& SOut, const TStr& Nm) const;
/// Assigns new contents to the vector, replacing its current content.
TVec<TVal, TSizeTy>& operator=(const TVec<TVal, TSizeTy>& Vec);
/// Appends value \c Val to the vector.
TVec<TVal, TSizeTy>& operator+(const TVal& Val){Add(Val); return *this;}
/// Checks that the two vectors have the same contents.
bool operator==(const TVec<TVal, TSizeTy>& Vec) const;
/// Lexicographically compares two vectors. ##TVec::Less
bool operator<(const TVec<TVal, TSizeTy>& Vec) const;
/// Returns a reference to the element at position \c ValN in the vector.
const TVal& operator[](const TSizeTy& ValN) const {
AssertR((0<=ValN)&&(ValN<Vals), GetXOutOfBoundsErrMsg(ValN));
return ValT[ValN];}
/// Returns a reference to the element at position \c ValN in the vector.
TVal& operator[](const TSizeTy& ValN){
AssertR((0<=ValN)&&(ValN<Vals), GetXOutOfBoundsErrMsg(ValN));
return ValT[ValN];}
/// Returns the memory footprint (the number of bytes) of the vector.
TSizeTy GetMemUsed() const {
return TSizeTy(2*sizeof(TSizeTy)+sizeof(TVal*)+MxVals*sizeof(TVal));}
/// Returns the memory size (the number of bytes) of a binary representation.
TSizeTy GetMemSize() const {
return TSizeTy(2*sizeof(TVal)+sizeof(TSizeTy)*Vals);}
/// Returns primary hash code of the vector. Used by \c THash.
int GetPrimHashCd() const;
/// Returns secondary hash code of the vector. Used by \c THash.
int GetSecHashCd() const;
/// Constructs a vector (an array) of \c _Vals elements.
void Gen(const TSizeTy& _Vals){ IAssert(0<=_Vals);
if (ValT!=NULL && MxVals!=-1){delete[] ValT;} MxVals=Vals=_Vals;
if (MxVals==0){ValT=NULL;} else {ValT=new TVal[MxVals];}}
/// Constructs a vector (an array) of \c _Vals elements, while reserving enough memory for \c _MxVals elements.
void Gen(const TSizeTy& _MxVals, const TSizeTy& _Vals){ IAssert((0<=_Vals)&&(_Vals<=_MxVals));
if (ValT!=NULL && MxVals!=-1){delete[] ValT;} MxVals=_MxVals; Vals=_Vals;
if (_MxVals==0){ValT=NULL;} else {ValT=new TVal[_MxVals];}}
/// Constructs a vector of \c _Vals elements of memory array \c _ValT. ##TVec::GenExt
void GenExt(TVal *_ValT, const TSizeTy& _Vals){
if (ValT!=NULL && MxVals!=-1){delete[] ValT;}
MxVals=-1; Vals=_Vals; ValT=_ValT;}
/// Returns true if the vector was created using the \c GenExt(). ##TVec::IsExt
bool IsExt() const {return MxVals==-1;}
/// Reserves enough memory for the vector to store \c _MxVals elements.
void Reserve(const TSizeTy& _MxVals){Resize(_MxVals);}
/// Reserves enough memory for the vector to store \c _MxVals elements and sets its length to \c _Vals.
void Reserve(const TSizeTy& _MxVals, const TSizeTy& _Vals){ IAssert((0<=_Vals)&&(_Vals<=_MxVals)); Resize(_MxVals); Vals=_Vals;}
/// Clears the contents of the vector. ##TVec::Clr
void Clr(const bool& DoDel=true, const TSizeTy& NoDelLim=-1);
/// Truncates the vector's length and capacity to \c _Vals elements. ##TVec::Trunc
void Trunc(const TSizeTy& _Vals=-1);
/// The vector reduces its capacity (frees memory) to match its size.
void Pack();
/// Takes over the data and the capacity from \c Vec. ##TVec::MoveFrom
void MoveFrom(TVec<TVal, TSizeTy>& Vec);
/// Swaps the contents of the vector with \c Vec.
void Swap(TVec<TVal, TSizeTy>& Vec);
/// Tests whether the vector is empty. ##TVec::Empty
bool Empty() const {return Vals==0;}
/// Returns the number of elements in the vector. ##TVec::Len
TSizeTy Len() const {return Vals;}
/// Returns the size of allocated storage capacity.
TSizeTy Reserved() const {return MxVals;}
/// Returns a reference to the last element of the vector.
const TVal& Last() const {return GetVal(Len()-1);}
/// Returns a reference to the last element of the vector.
TVal& Last(){return GetVal(Len()-1);}
/// Returns the position of the last element.
TSizeTy LastValN() const {return Len()-1;}
/// Returns a reference to the one before last element of the vector.
const TVal& LastLast() const { AssertR(1<Vals, GetXOutOfBoundsErrMsg(Vals-2)); return ValT[Vals-2];}
/// Returns a reference to the one before last element of the vector.
TVal& LastLast(){ AssertR(1<Vals, GetXOutOfBoundsErrMsg(Vals-2)); return ValT[Vals-2];}
/// Returns an iterator pointing to the first element in the vector.
TIter BegI() const {return ValT;}
/// Returns an iterator referring to the past-the-end element in the vector.
TIter EndI() const {return ValT+Vals;}
/// Returns an iterator an element at position \c ValN.
TIter GetI(const TSizeTy& ValN) const {return ValT+ValN;}
/// Adds a new element at the end of the vector, after its current last element. ##TVec::Add
TSizeTy Add(){ AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
if (Vals==MxVals){Resize();} return Vals++;}
/// Adds a new element at the end of the vector, after its current last element. ##TVec::Add1
TSizeTy Add(const TVal& Val){ AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
if (Vals==MxVals){Resize();} ValT[Vals]=Val; return Vals++;}
TSizeTy Add(TVal& Val){ AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
if (Vals==MxVals){Resize();} ValT[Vals]=Val; return Vals++;}
/// Adds element \c Val at the end of the vector. #TVec::Add2
TSizeTy Add(const TVal& Val, const TSizeTy& ResizeLen){ AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
if (Vals==MxVals){Resize(MxVals+ResizeLen);} ValT[Vals]=Val; return Vals++;}
/// Adds the elements of the vector \c ValV to the to end of the vector.
TSizeTy AddV(const TVec<TVal, TSizeTy>& ValV);
/// Adds element \c Val to a sorted vector. ##TVec::AddSorted
TSizeTy AddSorted(const TVal& Val, const bool& Asc=true, const TSizeTy& _MxVals=-1);
/// Adds element \c Val to a sorted vector. ##TVec::AddBackSorted
TSizeTy AddBackSorted(const TVal& Val, const bool& Asc);
/// Adds element \c Val to a sorted vector only if the element \c Val is not already in the vector. ##TVec::AddMerged
TSizeTy AddMerged(const TVal& Val);
/// Adds elements of \c ValV to a sorted vector only if a particular element is not already in the vector. ##TVec::AddMerged1
TSizeTy AddVMerged(const TVec<TVal, TSizeTy>& ValV);
/// Adds element \c Val to a vector only if the element \c Val is not already in the vector. ##TVec::AddUnique
TSizeTy AddUnique(const TVal& Val);
/// Returns a reference to the element at position \c ValN in the vector.
const TVal& GetVal(const TSizeTy& ValN) const {return operator[](ValN);}
/// Returns a reference to the element at position \c ValN in the vector.
TVal& GetVal(const TSizeTy& ValN){return operator[](ValN);}
/// Sets the value of element at position \c ValN to \c Val.
void SetVal(const TSizeTy& ValN, const TVal& Val){AssertR((0<=ValN)&&(ValN<Vals), GetXOutOfBoundsErrMsg(ValN)); ValT[ValN] = Val;}
/// Returns a vector on elements at positions <tt>BValN...EValN</tt>.
void GetSubValV(const TSizeTy& BValN, const TSizeTy& EValN, TVec<TVal, TSizeTy>& ValV) const;
/// Inserts new element \c Val before the element at position \c ValN.
void Ins(const TSizeTy& ValN, const TVal& Val);
/// Removes the element at position \c ValN.
void Del(const TSizeTy& ValN);
/// Removes the elements at positions <tt>MnValN...MxValN</tt>.
void Del(const TSizeTy& MnValN, const TSizeTy& MxValN);
/// Removes the last element of the vector.
void DelLast(){Del(Len()-1);}
/// Removes the first occurrence of element \c Val.
bool DelIfIn(const TVal& Val);
/// Removes all occurrences of element \c Val.
void DelAll(const TVal& Val);
/// Sets all elements of the vector to value \c Val.
void PutAll(const TVal& Val);
/// Swaps elements at positions \c ValN1 and \c ValN2.
void Swap(const TSizeTy& ValN1, const TSizeTy& ValN2){ const TVal Val=ValT[ValN1]; ValT[ValN1]=ValT[ValN2]; ValT[ValN2]=Val;}
/// Swaps the elements that iterators \c LVal and \c RVal point to.
static void SwapI(TIter LVal, TIter RVal){ const TVal Val=*LVal; *LVal=*RVal; *RVal=Val;}
/// Generates next permutation of the elements in the vector. ##TVec::NextPerm
bool NextPerm();
/// Generates previous permutation of the elements in the vector. ##TVec::PrevPerm
bool PrevPerm();
// Sorting functions
/// Picks three random elements at positions <tt>LValN...RValN</tt> and returns the middle one.
TSizeTy GetPivotValN(const TSizeTy& LValN, const TSizeTy& RValN) const;
/// Bubble sorts the values between positions <tt>MnLValN...MxLValN</tt>. ##TVec::BSort
void BSort(const TSizeTy& MnLValN, const TSizeTy& MxRValN, const bool& Asc);
/// Insertion sorts the values between positions <tt>MnLValN...MxLValN</tt>. ##TVec::ISort
void ISort(const TSizeTy& MnLValN, const TSizeTy& MxRValN, const bool& Asc);
/// Partitions the values between positions <tt>MnLValN...MxLValN</tt>. ##TVec::Partition
TSizeTy Partition(const TSizeTy& MnLValN, const TSizeTy& MxRValN, const bool& Asc);
/// Quick sorts the values between positions <tt>MnLValN...MxLValN</tt>. ##TVec::QSort
void QSort(const TSizeTy& MnLValN, const TSizeTy& MxRValN, const bool& Asc);
/// Sorts the elements of the vector. ##TVec::Sort
void Sort(const bool& Asc=true);
/// Checks whether the vector is sorted in ascending (if \c Asc=true) or descending (if \c Asc=false) order.
bool IsSorted(const bool& Asc=true) const;
/// Randomly shuffles the elements of the vector.
void Shuffle(TRnd& Rnd);
/// Reverses the order of the elements in the vector.
void Reverse();
/// Reverses the order of elements between <tt>LValN...RValN</tt>.
void Reverse(TSizeTy LValN, TSizeTy RValN){ Assert(LValN>=0 && RValN<Len()); while (LValN < RValN){Swap(LValN++, RValN--);} }
/// Sorts the vector and only keeps a single element of each value.
void Merge();
/// Picks three random elements at positions <tt>BI...EI</tt> and returns the middle one under the comparator \c Cmp.
template <class TCmp>
static TIter GetPivotValNCmp(const TIter& BI, const TIter& EI, const TCmp& Cmp) {
TSizeTy SubVals=TSizeTy(EI-BI); if (SubVals > TInt::Mx-1) { SubVals = TInt::Mx-1; }
const TSizeTy ValN1=TInt::GetRnd(SubVals), ValN2=TInt::GetRnd(SubVals), ValN3=TInt::GetRnd(SubVals);
const TVal& Val1 = *(BI+ValN1); const TVal& Val2 = *(BI+ValN2); const TVal& Val3 = *(BI+ValN3);
if (Cmp(Val1, Val2)) {
if (Cmp(Val2, Val3)) return BI+ValN2;
else if (Cmp(Val3, Val1)) return BI+ValN1;
else return BI+ValN3;
} else {
if (Cmp(Val1, Val3)) return BI+ValN1;
else if (Cmp(Val3, Val2)) return BI+ValN2;
else return BI+ValN3; } }
/// Partitions the values between positions <tt>BI...EI</tt> under the comparator \c Cmp.
template <class TCmp>
static TIter PartitionCmp(TIter BI, TIter EI, const TVal Pivot, const TCmp& Cmp) {
forever {
while (Cmp(*BI, Pivot)){++BI;} --EI;
while (Cmp(Pivot, *EI)){--EI;}
if (!(BI<EI)){return BI;} SwapI(BI, EI); ++BI; } }
/// Bubble sorts the values between positions <tt>BI...EI</tt> under the comparator \c Cmp.
template <class TCmp>
static void BSortCmp(TIter BI, TIter EI, const TCmp& Cmp) {
for (TIter i = BI; i != EI; ++i) {
for (TIter j = EI-1; j != i; --j) {
if (Cmp(*j, *(j-1))) { SwapI(j, j-1); } } } }
/// Insertion sorts the values between positions <tt>BI...EI</tt> under the comparator \c Cmp.
template <class TCmp>
static void ISortCmp(TIter BI, TIter EI, const TCmp& Cmp) {
if (BI + 1 < EI) {
for (TIter i = BI, j; i != EI; ++i) { TVal Tmp=*i; j=i;
while (j > BI && Cmp(Tmp, *(j-1))) { *j = *(j-1); --j; } *j=Tmp; } } }
/// Quick sorts the values between positions <tt>BI...EI</tt> under the comparator \c Cmp.
template <class TCmp>
static void QSortCmp(TIter BI, TIter EI, const TCmp& Cmp) {
if (BI + 1 < EI) {
if (EI - BI < 20) { ISortCmp(BI, EI, Cmp); }
else { const TVal Val = *GetPivotValNCmp(BI, EI, Cmp);
TIter Split = PartitionCmp(BI, EI, Val, Cmp);
QSortCmp(BI, Split, Cmp); QSortCmp(Split, EI, Cmp); } } }
/// Sorts the elements of the vector using the comparator \c Cmp.
template <class TCmp>
void SortCmp(const TCmp& Cmp){ QSortCmp(BegI(), EndI(), Cmp);}
/// Checks whether the vector is sorted according to the comparator \c Cmp.
template <class TCmp>
bool IsSortedCmp(const TCmp& Cmp) const {
if (EndI() == BegI()) return true;
for (TIter i = BegI(); i != EndI()-1; ++i) {
if (Cmp(*(i+1), *i)){return false;} } return true; }
/// Result is the intersection of \c this vector with \c ValV. ##TVec::Intrs
void Intrs(const TVec<TVal, TSizeTy>& ValV);
/// Result is the union of \c this vector with \c ValV. ##TVec::Union
void Union(const TVec<TVal, TSizeTy>& ValV);
/// Subtracts \c ValV from \c this vector. ##TVec::Diff
void Diff(const TVec<TVal, TSizeTy>& ValV);
/// \c DstValV is the intersection of vectors \c this and \c ValV. ##TVec::Intrs1
void Intrs(const TVec<TVal, TSizeTy>& ValV, TVec<TVal, TSizeTy>& DstValV) const;
/// \c DstValV is the union of vectors \c this and \c ValV. ##TVec::Union1
void Union(const TVec<TVal, TSizeTy>& ValV, TVec<TVal, TSizeTy>& DstValV) const;
/// \c DstValV is the difference of vectors \c this and \c ValV. ##TVec::Diff1
void Diff(const TVec<TVal, TSizeTy>& ValV, TVec<TVal, TSizeTy>& DstValV) const;
/// Returns the size of the intersection of vectors \c this and \c ValV. ##TVec::IntrsLen
TSizeTy IntrsLen(const TVec<TVal, TSizeTy>& ValV) const;
/// Returns the size of the union of vectors \c this and \c ValV. ##TVec::UnionLen
TSizeTy UnionLen(const TVec<TVal, TSizeTy>& ValV) const;
/// Counts the number of occurrences of \c Val in the vector.
TSizeTy Count(const TVal& Val) const;
/// Returns the position of an element with value \c Val. ##TVec::SearchBin
TSizeTy SearchBin(const TVal& Val) const;
/// Returns the position of an element with value \c Val. ##TVec::SearchBin1
TSizeTy SearchBin(const TVal& Val, TSizeTy& InsValN) const;
/// Returns the position of an element with value \c Val. ##TVec::SearchForw
TSizeTy SearchForw(const TVal& Val, const TSizeTy& BValN=0) const;
/// Returns the position of an element with value \c Val. ##TVec::SearchBack
TSizeTy SearchBack(const TVal& Val) const;
/// Returns the starting position of vector \c ValV. ##TVec::SearchVForw
TSizeTy SearchVForw(const TVec<TVal, TSizeTy>& ValV, const TSizeTy& BValN=0) const;
/// Checks whether element \c Val is a member of the vector.
bool IsIn(const TVal& Val) const {return SearchForw(Val)!=-1;}
/// Checks whether element \c Val is a member of the vector. ##TVec::IsIn
bool IsIn(const TVal& Val, TSizeTy& ValN) const { ValN=SearchForw(Val); return ValN!=-1;}
/// Checks whether element \c Val is a member of the vector. ##TVec::IsInBin
bool IsInBin(const TVal& Val) const {return SearchBin(Val)!=-1;}
/// Returns reference to the first occurrence of element \c Val.
const TVal& GetDat(const TVal& Val) const { return GetVal(SearchForw(Val));}
/// Returns reference to the first occurrence of element \c Val. ##TVec::GetAddDat
TVal& GetAddDat(const TVal& Val){ AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
const TSizeTy ValN=SearchForw(Val); if (ValN==-1){Add(Val); return Last();} else {return GetVal(ValN);}}
/// Returns the position of the largest element in the vector.
TSizeTy GetMxValN() const;
/// Returns a vector on element \c Val1.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1){
TVec<TVal, TSizeTy> V(1, 0); V.Add(Val1); return V;}
/// Returns a vector on elements \c Val1, \c Val2.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1, const TVal& Val2){
TVec<TVal, TSizeTy> V(2, 0); V.Add(Val1); V.Add(Val2); return V;}
/// Returns a vector on elements <tt>Val1...Val3</tt>.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1, const TVal& Val2, const TVal& Val3){
TVec<TVal, TSizeTy> V(3, 0); V.Add(Val1); V.Add(Val2); V.Add(Val3); return V;}
/// Returns a vector on elements <tt>Val1...Val4</tt>.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1, const TVal& Val2, const TVal& Val3, const TVal& Val4){
TVec<TVal, TSizeTy> V(4, 0); V.Add(Val1); V.Add(Val2); V.Add(Val3); V.Add(Val4); return V;}
/// Returns a vector on elements <tt>Val1...Val5</tt>.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1, const TVal& Val2, const TVal& Val3, const TVal& Val4, const TVal& Val5){
TVec<TVal, TSizeTy> V(5, 0); V.Add(Val1); V.Add(Val2); V.Add(Val3); V.Add(Val4); V.Add(Val5); return V;}
/// Returns a vector on elements <tt>Val1...Val6</tt>.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1, const TVal& Val2, const TVal& Val3, const TVal& Val4, const TVal& Val5, const TVal& Val6){
TVec<TVal, TSizeTy> V(6, 0); V.Add(Val1); V.Add(Val2); V.Add(Val3); V.Add(Val4); V.Add(Val5); V.Add(Val6); return V;}
/// Returns a vector on elements <tt>Val1...Val7</tt>.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1, const TVal& Val2, const TVal& Val3, const TVal& Val4, const TVal& Val5, const TVal& Val6, const TVal& Val7){
TVec<TVal, TSizeTy> V(7, 0); V.Add(Val1); V.Add(Val2); V.Add(Val3); V.Add(Val4); V.Add(Val5); V.Add(Val6); V.Add(Val7); return V;}
/// Returns a vector on elements <tt>Val1...Val8</tt>.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1, const TVal& Val2, const TVal& Val3, const TVal& Val4, const TVal& Val5, const TVal& Val6, const TVal& Val7, const TVal& Val8){
TVec<TVal, TSizeTy> V(8, 0); V.Add(Val1); V.Add(Val2); V.Add(Val3); V.Add(Val4); V.Add(Val5); V.Add(Val6); V.Add(Val7); V.Add(Val8); return V;}
/// Returns a vector on elements <tt>Val1...Val9</tt>.
static TVec<TVal, TSizeTy> GetV(const TVal& Val1, const TVal& Val2, const TVal& Val3, const TVal& Val4, const TVal& Val5, const TVal& Val6, const TVal& Val7, const TVal& Val8, const TVal& Val9){
TVec<TVal, TSizeTy> V(9, 0); V.Add(Val1); V.Add(Val2); V.Add(Val3); V.Add(Val4); V.Add(Val5); V.Add(Val6); V.Add(Val7); V.Add(Val8); V.Add(Val9); return V;}
};
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Resize(const TSizeTy& _MxVals){
IAssertR(MxVals!=-1, TStr::Fmt("Can not increase the capacity of the vector. %s. [Program failed to allocate more memory. Solution: Get a bigger machine and a 64-bit compiler.]", GetTypeNm(*this).CStr()).CStr());
IAssertR(MxVals!=(TInt::Mx-1024), TStr::Fmt("Buffer size at maximum. %s. [Program refuses to allocate more memory. Solution-1: Send your test case to developers.]", GetTypeNm(*this).CStr()).CStr());
if (_MxVals==-1){
if (Vals==0){MxVals=16;} else {MxVals*=2;}
} else {
if (_MxVals<=MxVals){return;} else {MxVals=_MxVals;}
}
if (MxVals < 0) {
MxVals = TInt::Mx-1024;
}
if (ValT==NULL){
try {ValT=new TVal[MxVals];}
catch (std::exception Ex){
FailR(TStr::Fmt("TVec::Resize: %s, Length:%s, Capacity:%s, New capacity:%s, Type:%s [Program failed to allocate more memory. Solution: Get a bigger machine and a 64-bit compiler.]",
Ex.what(), TInt::GetStr(Vals).CStr(), TInt::GetStr(MxVals).CStr(), TInt::GetStr(_MxVals).CStr(), GetTypeNm(*this).CStr()).CStr());}
} else {
TVal* NewValT = NULL;
try {
NewValT=new TVal[MxVals];}
catch (std::exception Ex){
FailR(TStr::Fmt("TVec::Resize: %s, Length:%s, Capacity:%s, New capacity:%s, Type:%s [Program failed to allocate more memory. Solution: Get a bigger machine and a 64-bit compiler.]",
Ex.what(), TInt::GetStr(Vals).CStr(), TInt::GetStr(MxVals).CStr(), TInt::GetStr(_MxVals).CStr(), GetTypeNm(*this).CStr()).CStr());}
IAssert(NewValT!=NULL);
for (TSizeTy ValN=0; ValN<Vals; ValN++){NewValT[ValN]=ValT[ValN];}
delete[] ValT; ValT=NewValT;
}
}
template <class TVal, class TSizeTy>
TStr TVec<TVal, TSizeTy>::GetXOutOfBoundsErrMsg(const TSizeTy& ValN) const {
return TStr()+
"Index:"+TInt::GetStr(ValN)+
" Vals:"+TInt::GetStr(Vals)+
" MxVals:"+TInt::GetStr(MxVals)+
" Type:"+GetTypeNm(*this);
}
template <class TVal, class TSizeTy>
TVec<TVal, TSizeTy>::TVec(const TVec<TVal, TSizeTy>& Vec){
MxVals=Vec.MxVals; Vals=Vec.Vals;
if (MxVals==0){ValT=NULL;} else {ValT=new TVal[MxVals];}
for (TSizeTy ValN=0; ValN<Vec.Vals; ValN++){ValT[ValN]=Vec.ValT[ValN];}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Load(TSIn& SIn){
if ((ValT!=NULL)&&(MxVals!=-1)){delete[] ValT;}
SIn.Load(MxVals); SIn.Load(Vals); MxVals=Vals;
if (MxVals==0){ValT=NULL;} else {ValT=new TVal[MxVals];}
for (TSizeTy ValN=0; ValN<Vals; ValN++){ValT[ValN]=TVal(SIn);}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Save(TSOut& SOut) const {
if (MxVals!=-1){SOut.Save(MxVals);} else {SOut.Save(Vals);}
SOut.Save(Vals);
for (TSizeTy ValN=0; ValN<Vals; ValN++){ValT[ValN].Save(SOut);}
}
template <class TVal, class TSizeTy>
TVec<TVal, TSizeTy>& TVec<TVal, TSizeTy>::operator=(const TVec<TVal, TSizeTy>& Vec){
if (this!=&Vec){
if ((ValT!=NULL)&&(MxVals!=-1)){delete[] ValT;}
MxVals=Vals=Vec.Vals;
if (MxVals==0){ValT=NULL;} else {ValT=new TVal[MxVals];}
for (TSizeTy ValN=0; ValN<Vec.Vals; ValN++){ValT[ValN]=Vec.ValT[ValN];}
}
return *this;
}
template <class TVal, class TSizeTy>
bool TVec<TVal, TSizeTy>::operator==(const TVec<TVal, TSizeTy>& Vec) const {
if (this==&Vec){return true;}
if (Len()!=Vec.Len()){return false;}
for (TSizeTy ValN=0; ValN<Vals; ValN++){
if (ValT[ValN]!=Vec.ValT[ValN]){return false;}}
return true;
}
template <class TVal, class TSizeTy>
bool TVec<TVal, TSizeTy>::operator<(const TVec<TVal, TSizeTy>& Vec) const {
if (this==&Vec){return false;}
if (Len()==Vec.Len()){
for (TSizeTy ValN=0; ValN<Vals; ValN++){
if (ValT[ValN]<Vec.ValT[ValN]){return true;}
else if (ValT[ValN]>Vec.ValT[ValN]){return false;}
else {}
}
return false;
} else {
return Len()<Vec.Len();
}
}
// Improved hashing of vectors (Jure Apr 20 2013)
// This change makes binary representation of vectors incompatible with previous code.
// Previous hash functions are available for compatibility in class TVecHashF_OldGLib
template <class TVal, class TSizeTy>
int TVec<TVal, TSizeTy>::GetPrimHashCd() const {
int hc = 0;
for (TSizeTy i=0; i<Vals; i++){
hc = TPairHashImpl::GetHashCd(hc, ValT[i].GetPrimHashCd());
}
return hc;
}
// Improved hashing of vectors (Jure Apr 20 2013)
// This change makes binary representation of vectors incompatible with previous code.
// Previous hash functions are available for compatibility in class TVecHashF_OldGLib
template <class TVal, class TSizeTy>
int TVec<TVal, TSizeTy>::GetSecHashCd() const {
int hc = 0;
for (TSizeTy i=0; i<Vals; i++){
hc = TPairHashImpl::GetHashCd(hc, ValT[i].GetSecHashCd());
}
if (Vals > 0) {
hc = TPairHashImpl::GetHashCd(hc, ValT[0].GetSecHashCd()); }
return hc;
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Clr(const bool& DoDel, const TSizeTy& NoDelLim){
if ((DoDel)||((!DoDel)&&(NoDelLim!=-1)&&(MxVals>NoDelLim))){
if ((ValT!=NULL)&&(MxVals!=-1)){delete[] ValT;}
MxVals=Vals=0; ValT=NULL;
} else {
IAssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
Vals=0;
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Trunc(const TSizeTy& _Vals){
IAssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
IAssert((_Vals==-1)||(_Vals>=0));
if ((_Vals!=-1)&&(_Vals>=Vals)){
return;
} else
if (((_Vals==-1)&&(Vals==0))||(_Vals==0)){
if (ValT!=NULL){delete[] ValT;}
MxVals=Vals=0; ValT=NULL;
} else {
if (_Vals==-1){
if (MxVals==Vals){return;} else {MxVals=Vals;}
} else {
MxVals=Vals=_Vals;
}
TVal* NewValT=new TVal[MxVals];
IAssert(NewValT!=NULL);
for (TSizeTy ValN=0; ValN<Vals; ValN++){NewValT[ValN]=ValT[ValN];}
delete[] ValT; ValT=NewValT;
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Pack(){
IAssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
if (Vals==0){
if (ValT!=NULL){delete[] ValT;} ValT=NULL;
} else
if (Vals<MxVals){
MxVals=Vals;
TVal* NewValT=new TVal[MxVals];
IAssert(NewValT!=NULL);
for (TSizeTy ValN=0; ValN<Vals; ValN++){NewValT[ValN]=ValT[ValN];}
delete[] ValT; ValT=NewValT;
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::MoveFrom(TVec<TVal, TSizeTy>& Vec){
if (this!=&Vec){
if (ValT!=NULL && MxVals!=-1){delete[] ValT;}
MxVals=Vec.MxVals; Vals=Vec.Vals; ValT=Vec.ValT;
Vec.MxVals=0; Vec.Vals=0; Vec.ValT=NULL;
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Swap(TVec<TVal, TSizeTy>& Vec){
if (this!=&Vec){
::Swap(MxVals, Vec.MxVals);
::Swap(Vals, Vec.Vals);
::Swap(ValT, Vec.ValT);
}
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::AddV(const TVec<TVal, TSizeTy>& ValV){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
for (TSizeTy ValN=0; ValN<ValV.Vals; ValN++){Add(ValV[ValN]);}
return Len();
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::AddSorted(const TVal& Val, const bool& Asc, const TSizeTy& _MxVals){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
TSizeTy ValN=Add(Val);
if (Asc){
while ((ValN>0)&&(ValT[ValN]<ValT[ValN-1])){
Swap(ValN, ValN-1); ValN--;}
} else {
while ((ValN>0)&&(ValT[ValN]>ValT[ValN-1])){
Swap(ValN, ValN-1); ValN--;}
}
if ((_MxVals!=-1)&&(Len()>_MxVals)){Del(_MxVals, Len()-1);}
return ValN;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::AddBackSorted(const TVal& Val, const bool& Asc){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
Add();
TSizeTy ValN=Vals-2;
while ((ValN>=0)&&((Asc&&(Val<ValT[ValN]))||(!Asc&&(Val>ValT[ValN])))){
ValT[ValN+1]=ValT[ValN]; ValN--;}
ValT[ValN+1]=Val;
return ValN+1;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::AddMerged(const TVal& Val){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
TSizeTy ValN=SearchBin(Val);
if (ValN==-1){return AddSorted(Val);}
else {GetVal(ValN)=Val; return -1;}
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::AddVMerged(const TVec<TVal, TSizeTy>& ValV){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
for (TSizeTy ValN=0; ValN<ValV.Vals; ValN++){AddMerged(ValV[ValN]);}
return Len();
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::AddUnique(const TVal& Val){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
TSizeTy ValN=SearchForw(Val);
if (ValN==-1){return Add(Val);}
else {GetVal(ValN)=Val; return -1;}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::GetSubValV(const TSizeTy& _BValN, const TSizeTy& _EValN, TVec<TVal, TSizeTy>& SubValV) const {
const TSizeTy BValN=TInt::GetInRng(_BValN, 0, Len()-1);
const TSizeTy EValN=TInt::GetInRng(_EValN, 0, Len()-1);
const TSizeTy SubVals=TInt::GetMx(0, EValN-BValN+1);
SubValV.Gen(SubVals, 0);
for (TSizeTy ValN=BValN; ValN<=EValN; ValN++){
SubValV.Add(GetVal(ValN));}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Ins(const TSizeTy& ValN, const TVal& Val){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
Add(); Assert((0<=ValN)&&(ValN<Vals));
for (TSizeTy MValN=Vals-2; MValN>=ValN; MValN--){ValT[MValN+1]=ValT[MValN];}
ValT[ValN]=Val;
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Del(const TSizeTy& ValN){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
Assert((0<=ValN)&&(ValN<Vals));
for (TSizeTy MValN=ValN+1; MValN<Vals; MValN++){
ValT[MValN-1]=ValT[MValN];}
ValT[--Vals]=TVal();
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Del(const TSizeTy& MnValN, const TSizeTy& MxValN){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
Assert((0<=MnValN)&&(MnValN<Vals)&&(0<=MxValN)&&(MxValN<Vals));
Assert(MnValN<=MxValN);
for (TSizeTy ValN=MxValN+1; ValN<Vals; ValN++){
ValT[MnValN+ValN-MxValN-1]=ValT[ValN];}
for (TSizeTy ValN=Vals-MxValN+MnValN-1; ValN<Vals; ValN++){
ValT[ValN]=TVal();}
Vals-=MxValN-MnValN+1;
}
template <class TVal, class TSizeTy>
bool TVec<TVal, TSizeTy>::DelIfIn(const TVal& Val){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
TSizeTy ValN=SearchForw(Val);
if (ValN!=-1){Del(ValN); return true;}
else {return false;}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::DelAll(const TVal& Val){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
TSizeTy ValN;
while ((ValN=SearchForw(Val))!=-1){Del(ValN);}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::PutAll(const TVal& Val){
for (TSizeTy ValN=0; ValN<Vals; ValN++){ValT[ValN]=Val;}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::BSort(const TSizeTy& MnLValN, const TSizeTy& MxRValN, const bool& Asc){
for (TSizeTy ValN1=MnLValN; ValN1<=MxRValN; ValN1++){
for (TSizeTy ValN2=MxRValN; ValN2>ValN1; ValN2--){
if (Asc){
if (ValT[ValN2]<ValT[ValN2-1]){Swap(ValN2, ValN2-1);}
} else {
if (ValT[ValN2]>ValT[ValN2-1]){Swap(ValN2, ValN2-1);}
}
}
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::ISort(const TSizeTy& MnLValN, const TSizeTy& MxRValN, const bool& Asc){
if (MnLValN<MxRValN){
for (TSizeTy ValN1=MnLValN+1; ValN1<=MxRValN; ValN1++){
TVal Val=ValT[ValN1]; TSizeTy ValN2=ValN1;
if (Asc){
while ((ValN2>MnLValN)&&(ValT[ValN2-1]>Val)){
ValT[ValN2]=ValT[ValN2-1]; ValN2--;}
} else {
while ((ValN2>MnLValN)&&(ValT[ValN2-1]<Val)){
ValT[ValN2]=ValT[ValN2-1]; ValN2--;}
}
ValT[ValN2]=Val;
}
}
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::GetPivotValN(const TSizeTy& LValN, const TSizeTy& RValN) const {
TSizeTy SubVals=RValN-LValN+1;
if (SubVals > TInt::Mx-1) { SubVals = TInt::Mx-1; }
const TSizeTy ValN1=LValN+TInt::GetRnd(int(SubVals));
const TSizeTy ValN2=LValN+TInt::GetRnd(int(SubVals));
const TSizeTy ValN3=LValN+TInt::GetRnd(int(SubVals));
const TVal& Val1=ValT[ValN1];
const TVal& Val2=ValT[ValN2];
const TVal& Val3=ValT[ValN3];
if (Val1<Val2){
if (Val2<Val3){return ValN2;}
else if (Val3<Val1){return ValN1;}
else {return ValN3;}
} else {
if (Val1<Val3){return ValN1;}
else if (Val3<Val2){return ValN2;}
else {return ValN3;}
}
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::Partition(const TSizeTy& MnLValN, const TSizeTy& MxRValN, const bool& Asc){
TSizeTy PivotValN=GetPivotValN(MnLValN, MxRValN);
Swap(PivotValN, MnLValN);
TVal PivotVal=ValT[MnLValN];
TSizeTy LValN=MnLValN-1; TSizeTy RValN=MxRValN+1;
forever {
if (Asc){
do {RValN--;} while (ValT[RValN]>PivotVal);
do {LValN++;} while (ValT[LValN]<PivotVal);
} else {
do {RValN--;} while (ValT[RValN]<PivotVal);
do {LValN++;} while (ValT[LValN]>PivotVal);
}
if (LValN<RValN){Swap(LValN, RValN);}
else {return RValN;}
};
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::QSort(const TSizeTy& MnLValN, const TSizeTy& MxRValN, const bool& Asc){
if (MnLValN<MxRValN){
if (MxRValN-MnLValN<20){
ISort(MnLValN, MxRValN, Asc);
} else {
TSizeTy SplitValN=Partition(MnLValN, MxRValN, Asc);
QSort(MnLValN, SplitValN, Asc);
QSort(SplitValN+1, MxRValN, Asc);
}
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Sort(const bool& Asc){
QSort(0, Len()-1, Asc);
}
template <class TVal, class TSizeTy>
bool TVec<TVal, TSizeTy>::IsSorted(const bool& Asc) const {
if (Asc){
for (TSizeTy ValN=0; ValN<Vals-1; ValN++){
if (ValT[ValN]>ValT[ValN+1]){return false;}}
} else {
for (TSizeTy ValN=0; ValN<Vals-1; ValN++){
if (ValT[ValN]<ValT[ValN+1]){return false;}}
}
return true;
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Shuffle(TRnd& Rnd){
if (Len() < TInt::Mx) {
for (TSizeTy ValN=0; ValN<Vals-1; ValN++){
const int Range = int(Vals-ValN);
Swap(ValN, ValN+Rnd.GetUniDevInt(Range));
}
} else {
for (TSizeTy ValN=0; ValN<Vals-1; ValN++){
const TSizeTy Range = Vals-ValN;
Swap(ValN, TSizeTy(ValN+Rnd.GetUniDevInt64(Range)));
}
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Reverse(){
for (TSizeTy ValN=0; ValN<Vals/2; ValN++){
Swap(ValN, Vals-ValN-1);}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Merge(){
AssertR(MxVals!=-1, "This vector was obtained from TVecPool. Such vectors cannot change its size!");
TVec<TVal, TSizeTy> SortedVec(*this); SortedVec.Sort();
Clr();
for (TSizeTy ValN=0; ValN<SortedVec.Len(); ValN++){
if ((ValN==0)||(SortedVec[ValN-1]!=SortedVec[ValN])){
Add(SortedVec[ValN]);}
}
}
template <class TVal, class TSizeTy>
bool TVec<TVal, TSizeTy>::NextPerm() {
// start with a sorted sequence to obtain all permutations
TSizeTy First = 0, Last = Len(), Next = Len()-1;
if (Last < 2) return false;
for(; ; ) {
// find rightmost element smaller than successor
TSizeTy Next1 = Next;
if (GetVal(--Next) < GetVal(Next1)) { // swap with rightmost element that's smaller, flip suffix
TSizeTy Mid = Last;
for (; GetVal(Next) >= GetVal(--Mid); ) { }
Swap(Next, Mid);
Reverse(Next1, Last-1);
return true;
}
if (Next == First) { // pure descending, flip all
Reverse();
return false;
}
}
}
template <class TVal, class TSizeTy>
bool TVec<TVal, TSizeTy>::PrevPerm() {
TSizeTy First = 0, Last = Len(), Next = Len()-1;
if (Last < 2) return false;
for(; ; ) {
// find rightmost element not smaller than successor
TSizeTy Next1 = Next;
if (GetVal(--Next) >= GetVal(Next1)) { // swap with rightmost element that's not smaller, flip suffix
TSizeTy Mid = Last;
for (; GetVal(Next) < GetVal(--Mid); ) { }
Swap(Next, Mid);
Reverse(Next1, Last);
return true;
}
if (Next == First) { // pure descending, flip all
Reverse();
return false;
}
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Intrs(const TVec<TVal, TSizeTy>& ValV){
TVec<TVal, TSizeTy> IntrsVec;
Intrs(ValV, IntrsVec);
MoveFrom(IntrsVec);
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Union(const TVec<TVal, TSizeTy>& ValV){
TVec<TVal, TSizeTy> UnionVec;
Union(ValV, UnionVec);
MoveFrom(UnionVec);
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Diff(const TVec<TVal, TSizeTy>& ValV){
TVec<TVal, TSizeTy> DiffVec;
Diff(ValV, DiffVec);
MoveFrom(DiffVec);
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Intrs(const TVec<TVal, TSizeTy>& ValV, TVec<TVal, TSizeTy>& DstValV) const {
DstValV.Clr();
TSizeTy ValN1=0, ValN2=0;
while ((ValN1<Len())&&(ValN2<ValV.Len())){
const TVal& Val1=GetVal(ValN1);
while ((ValN2<ValV.Len())&&(Val1>ValV.GetVal(ValN2))){
ValN2++;}
if ((ValN2<ValV.Len())&&(Val1==ValV.GetVal(ValN2))){
DstValV.Add(Val1); ValN2++;}
ValN1++;
}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Union(const TVec<TVal, TSizeTy>& ValV, TVec<TVal, TSizeTy>& DstValV) const {
DstValV.Gen(TInt::GetMx(Len(), ValV.Len()), 0);
TSizeTy ValN1=0, ValN2=0;
while ((ValN1<Len())&&(ValN2<ValV.Len())){
const TVal& Val1=GetVal(ValN1);
const TVal& Val2=ValV.GetVal(ValN2);
if (Val1<Val2){DstValV.Add(Val1); ValN1++;}
else if (Val1>Val2){DstValV.Add(Val2); ValN2++;}
else {DstValV.Add(Val1); ValN1++; ValN2++;}
}
for (TSizeTy RestValN1=ValN1; RestValN1<Len(); RestValN1++){
DstValV.Add(GetVal(RestValN1));}
for (TSizeTy RestValN2=ValN2; RestValN2<ValV.Len(); RestValN2++){
DstValV.Add(ValV.GetVal(RestValN2));}
}
template <class TVal, class TSizeTy>
void TVec<TVal, TSizeTy>::Diff(const TVec<TVal, TSizeTy>& ValV, TVec<TVal, TSizeTy>& DstValV) const {
DstValV.Clr();
TSizeTy ValN1=0, ValN2=0;
while (ValN1<Len() && ValN2<ValV.Len()) {
const TVal& Val1 = GetVal(ValN1);
while (ValN2<ValV.Len() && Val1>ValV.GetVal(ValN2)) ValN2++;
if (ValN2<ValV.Len()) {
if (Val1!=ValV.GetVal(ValN2)) { DstValV.Add(Val1); }
ValN1++;
}
}
for (TSizeTy RestValN1=ValN1; RestValN1<Len(); RestValN1++){
DstValV.Add(GetVal(RestValN1));}
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::IntrsLen(const TVec<TVal, TSizeTy>& ValV) const {
TSizeTy Cnt=0, ValN1=0, ValN2=0;
while ((ValN1<Len())&&(ValN2<ValV.Len())){
const TVal& Val1=GetVal(ValN1);
while ((ValN2<ValV.Len())&&(Val1>ValV.GetVal(ValN2))){
ValN2++;}
if ((ValN2<ValV.Len())&&(Val1==ValV.GetVal(ValN2))){
ValN2++; Cnt++;}
ValN1++;
}
return Cnt;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::UnionLen(const TVec<TVal, TSizeTy>& ValV) const {
TSizeTy Cnt = 0, ValN1 = 0, ValN2 = 0;
while ((ValN1 < Len()) && (ValN2 < ValV.Len())) {
const TVal& Val1 = GetVal(ValN1);
const TVal& Val2 = ValV.GetVal(ValN2);
if (Val1 < Val2) {
Cnt++; ValN1++;
} else if (Val1 > Val2) {
Cnt++; ValN2++;
} else {
Cnt++; ValN1++; ValN2++;
}
}
Cnt += (Len() - ValN1) + (ValV.Len() - ValN2);
return Cnt;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::Count(const TVal& Val) const {
TSizeTy Count = 0;
for (TSizeTy i = 0; i < Len(); i++){
if (Val == ValT[i]){Count++;}}
return Count;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::SearchBin(const TVal& Val) const {
TSizeTy LValN=0, RValN=Len()-1;
while (RValN>=LValN){
TSizeTy ValN=(LValN+RValN)/2;
if (Val==ValT[ValN]){return ValN;}
if (Val<ValT[ValN]){RValN=ValN-1;} else {LValN=ValN+1;}
}
return -1;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::SearchBin(const TVal& Val, TSizeTy& InsValN) const {
TSizeTy LValN=0, RValN=Len()-1;
while (RValN>=LValN){
TSizeTy ValN=(LValN+RValN)/2;
if (Val==ValT[ValN]){InsValN=ValN; return ValN;}
if (Val<ValT[ValN]){RValN=ValN-1;} else {LValN=ValN+1;}
}
InsValN=LValN; return -1;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::SearchForw(const TVal& Val, const TSizeTy& BValN) const {
for (TSizeTy ValN=BValN; ValN<Vals; ValN++){
if (Val==ValT[ValN]){return ValN;}}
return -1;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::SearchBack(const TVal& Val) const {
for (TSizeTy ValN=Vals-1; ValN>=0; ValN--){
if (Val==ValT[ValN]){return ValN;}}
return -1;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::SearchVForw(const TVec<TVal, TSizeTy>& ValV, const TSizeTy& BValN) const {
TSizeTy ValVLen=ValV.Len();
for (TSizeTy ValN=BValN; ValN<Vals-ValVLen+1; ValN++){
bool Found=true;
for (TSizeTy SubValN=0; SubValN<ValVLen; SubValN++){
if (ValV[SubValN]!=GetVal(ValN+SubValN)){Found=false; break;}
}
if (Found){return ValN;}
}
return -1;
}
template <class TVal, class TSizeTy>
TSizeTy TVec<TVal, TSizeTy>::GetMxValN() const {
if (Vals==0){return -1;}
TSizeTy MxValN=0;
for (TSizeTy ValN=1; ValN<Vals; ValN++){
if (ValT[ValN]>ValT[MxValN]){MxValN=ValN;}
}
return MxValN;
}
/////////////////////////////////////////////////
// Common-Vector-Types
typedef TVec<TBool> TBoolV;
typedef TVec<TCh> TChV;
typedef TVec<TUCh> TUChV;
typedef TVec<TUInt> TUIntV;
typedef TVec<TInt> TIntV;
typedef TVec<TUInt64> TUInt64V;
typedef TVec<TFlt> TFltV;
typedef TVec<TSFlt> TSFltV;
typedef TVec<TAscFlt> TAscFltV;
typedef TVec<TStr> TStrV;
typedef TVec<TChA> TChAV;
typedef TVec<TIntPr> TIntPrV;
typedef TVec<TIntTr> TIntTrV;
typedef TVec<TIntQu> TIntQuV;
typedef TVec<TFltPr> TFltPrV;
typedef TVec<TFltTr> TFltTrV;
typedef TVec<TIntKd> TIntKdV;
typedef TVec<TUChIntPr> TUChIntPrV;
typedef TVec<TUChUInt64Pr> TUChUInt64PrV;
typedef TVec<TIntUInt64Pr> TIntUInt64PrV;
typedef TVec<TIntUInt64Kd> TIntUInt64KdV;
typedef TVec<TIntFltPr> TIntFltPrV;
typedef TVec<TIntFltPrKd> TIntFltPrKdV;
typedef TVec<TFltIntPr> TFltIntPrV;
typedef TVec<TFltUInt64Pr> TFltUInt64PrV;
typedef TVec<TFltStrPr> TFltStrPrV;
typedef TVec<TAscFltStrPr> TAscFltStrPrV;
typedef TVec<TIntStrPr> TIntStrPrV;
typedef TVec<TIntIntStrTr> TIntIntStrTrV;
typedef TVec<TIntIntFltTr> TIntIntFltTrV;
typedef TVec<TIntFltIntTr> TIntFltIntTrV;
typedef TVec<TIntStrIntTr> TIntStrIntTrV;
typedef TVec<TIntKd> TIntKdV;
typedef TVec<TUIntIntKd> TUIntIntKdV;
typedef TVec<TIntFltKd> TIntFltKdV;
typedef TVec<TIntPrFltKd> TIntPrFltKdV;
typedef TVec<TIntStrKd> TIntStrKdV;
typedef TVec<TIntStrPrPr> TIntStrPrPrV;
typedef TVec<TIntStrVPr> TIntStrVPrV;
typedef TVec<TIntIntVIntTr> TIntIntVIntTrV;
typedef TVec<TIntIntIntVTr> TIntIntIntVTrV;
typedef TVec<TUInt64IntPr> TUInt64IntPrV;
typedef TVec<TUInt64FltPr> TUInt64FltPrV;
typedef TVec<TUInt64StrPr> TUInt64StrPrV;
typedef TVec<TUInt64IntKd> TUInt64IntKdV;
typedef TVec<TUInt64FltKd> TUInt64FltKdV;
typedef TVec<TUInt64StrKd> TUInt64StrKdV;
typedef TVec<TFltBoolKd> TFltBoolKdV;
typedef TVec<TFltIntKd> TFltIntKdV;
typedef TVec<TFltUInt64Kd> TFltUInt64KdV;
typedef TVec<TFltIntPrKd> TFltIntPrKdV;
typedef TVec<TFltKd> TFltKdV;
typedef TVec<TFltStrKd> TFltStrKdV;
typedef TVec<TFltStrPrPr> TFltStrPrPrV;
typedef TVec<TFltIntIntTr> TFltIntIntTrV;
typedef TVec<TFltFltStrTr> TFltFltStrTrV;
typedef TVec<TAscFltIntPr> TAscFltIntPrV;
typedef TVec<TAscFltIntKd> TAscFltIntKdV;
typedef TVec<TStrPr> TStrPrV;
typedef TVec<TStrIntPr> TStrIntPrV;
typedef TVec<TStrFltPr> TStrFltPrV;
typedef TVec<TStrIntKd> TStrIntKdV;
typedef TVec<TStrFltKd> TStrFltKdV;
typedef TVec<TStrAscFltKd> TStrAscFltKdV;
typedef TVec<TStrTr> TStrTrV;
typedef TVec<TStrQu> TStrQuV;
typedef TVec<TStrFltFltTr> TStrFltFltTrV;
typedef TVec<TStrStrIntTr> TStrStrIntTrV;
typedef TVec<TStrKd> TStrKdV;
typedef TVec<TStrStrVPr> TStrStrVPrV;
typedef TVec<TStrVIntPr> TStrVIntPrV;
typedef TVec<TFltIntIntIntQu> TFltIntIntIntQuV;
typedef TVec<TIntStrIntIntQu> TIntStrIntIntQuV;
typedef TVec<TIntIntPrPr> TIntIntPrPrV;
//#//////////////////////////////////////////////
/// Vector Pool. ##TVecPool
template <class TVal, class TSizeTy=int>
class TVecPool {
public:
typedef TPt<TVecPool<TVal, TSizeTy> > PVecPool;
typedef TVec<TVal, TSizeTy> TValV;
private:
TCRef CRef;
TBool FastCopy;
TSize GrowBy, MxVals, Vals;
TVal EmptyVal; // Empty value/vector
TVal *ValBf; // Buffer for storing all the values
TVec<uint64, int> IdToOffV; // Id to one past last (Vector starts at [id-1]). Vector length is IdToOff[id]-IdToOff[id-1]
private:
void Resize(const TSize& _MxVals);
public:
/// Vector pool constructor. ##TVecPool::TVecPool
TVecPool(const TSize& ExpectVals=0, const TSize& _GrowBy=1000000, const bool& _FastCopy=false, const TVal& _EmptyVal=TVal());
TVecPool(const TVecPool<TVal, TSizeTy>& Pool);
TVecPool(TSIn& SIn);
~TVecPool() { if (ValBf != NULL) { delete [] ValBf; } ValBf=NULL; }
static PVecPool New(const TSize& ExpectVals=0, const TSize& GrowBy=1000000, const bool& FastCopy=false) {
return new TVecPool(ExpectVals, GrowBy, FastCopy); }
static PVecPool Load(TSIn& SIn) { return new TVecPool(SIn); }
static PVecPool Load(const TStr& FNm) { TFIn FIn(FNm); return Load(FIn); }
void Save(TSOut& SOut) const;
TVecPool& operator = (const TVecPool& Pool);
/// Returns the total number of vectors stored in the vector pool.
int GetVecs() const { return IdToOffV.Len(); }
/// Returns the total number of values stored in the vector pool.
TSize GetVals() const { return Vals; }
/// Tests whether vector of id \c VId is in the pool.
bool IsVId(const int& VId) const { return (0 <= VId) && (VId < IdToOffV.Len()); }
/// Returns the total capacity of the pool.
uint64 Reserved() const { return MxVals; }
/// Reserves enough capacity for the pool to store \c MxVals elements.
void Reserve(const TSize& MxVals) { Resize(MxVals); }
/// Returns the reference to an empty value.
const TVal& GetEmptyVal() const { return EmptyVal; }
/// Sets the empty value.
void SetEmptyVal(const TVal& _EmptyVal) { EmptyVal = _EmptyVal; }
/// Returns the total memory footprint (in bytes) of the pool.
uint64 GetMemUsed() const {
return sizeof(TCRef)+sizeof(TBool)+3*sizeof(TSize)+sizeof(TVal*)+MxVals*sizeof(TVal);}
/// Adds vector \c ValV to the pool and returns its id.
int AddV(const TValV& ValV);
/// Adds a vector of length \c ValVLen to the pool and returns its id. ##TVecPool::AddEmptyV
int AddEmptyV(const int& ValVLen);
/// Returns the number of elements in the vector with id \c VId.
int GetVLen(const int& VId) const { if (VId==0){return 0;} else {return int(IdToOffV[VId]-IdToOffV[VId-1]);}}
/// Returns pointer to the first element of the vector with id \c VId.
TVal* GetValVPt(const int& VId) const {
if (GetVLen(VId)==0){return (TVal*)&EmptyVal;}
else {return ValBf+IdToOffV[VId-1];}}
/// Returns \c ValV which is a reference (not a copy) to vector with id \c VId. ##TVecPool::GetV
void GetV(const int& VId, TValV& ValV) const {
if (GetVLen(VId)==0){ValV.Clr();}
else { ValV.GenExt(GetValVPt(VId), GetVLen(VId)); } }
/// Sets the values of vector \c VId with those in \c ValV.
void PutV(const int& VId, const TValV& ValV) {
IAssert(IsVId(VId) && GetVLen(VId) == ValV.Len());
if (FastCopy) {
memcpy(GetValVPt(VId), ValV.BegI(), sizeof(TVal)*ValV.Len()); }
else { TVal* ValPt = GetValVPt(VId);
for (::TSize ValN=0; ValN < ::TSize(ValV.Len()); ValN++, ValPt++) { *ValPt=ValV[ValN]; }
} }
/// Deletes all elements of value \c DelVal from all vectors. ##TVecPool::CompactPool
void CompactPool(const TVal& DelVal);
/// Shuffles the order of all elements in the pool. ##TVecPool::ShuffleAll
void ShuffleAll(TRnd& Rnd=TInt::Rnd);
/// Clears the contents of the pool. ##TVecPool::Clr
void Clr(bool DoDel = true) {
IdToOffV.Clr(DoDel); MxVals=0; Vals=0;
if (DoDel && ValBf!=NULL) { delete [] ValBf; ValBf=NULL;}
if (! DoDel) { PutAll(EmptyVal); } }
/// Sets the values of all elements in the pool to \c Val.
void PutAll(const TVal& Val) {
for (TSize ValN = 0; ValN < MxVals; ValN++) { ValBf[ValN]=Val; } }
friend class TPt<TVecPool<TVal> >;
};
template <class TVal, class TSizeTy>
void TVecPool<TVal, TSizeTy>::Resize(const TSize& _MxVals){
if (_MxVals <= MxVals){ return; } else { MxVals = _MxVals; }
if (ValBf == NULL) {
try { ValBf = new TVal [MxVals]; }
catch (std::exception Ex) {
FailR(TStr::Fmt("TVecPool::Resize 1: %s, MxVals: %s. [Program failed to allocate more memory. Solution: Get a bigger machine and a 64-bit compiler.]", Ex.what(), TInt::GetStr(uint64(_MxVals)).CStr()).CStr()); }
IAssert(ValBf != NULL);
if (EmptyVal != TVal()) { PutAll(EmptyVal); }
} else {
// printf("*** Resize vector pool: %llu -> %llu\n", uint64(Vals), uint64(MxVals));
TVal* NewValBf = NULL;
try { NewValBf = new TVal [MxVals]; }
catch (std::exception Ex) {
FailR(TStr::Fmt("TVecPool::Resize 1: %s, MxVals: %s. [Program failed to allocate more memory. Solution: Get a bigger machine and a 64-bit compiler.]", Ex.what(), TInt::GetStr(uint64(_MxVals)).CStr()).CStr()); }
IAssert(NewValBf != NULL);
if (FastCopy) {
memcpy(NewValBf, ValBf, Vals*sizeof(TVal)); }
else {
for (TSize ValN = 0; ValN < Vals; ValN++){ NewValBf[ValN] = ValBf[ValN]; } }
if (EmptyVal != TVal()) { // init empty values
for (TSize ValN = Vals; ValN < MxVals; ValN++) { NewValBf[ValN] = EmptyVal; }
}
delete [] ValBf;
ValBf = NewValBf;
}
}
template <class TVal, class TSizeTy>
TVecPool<TVal, TSizeTy>::TVecPool(const TSize& ExpectVals, const TSize& _GrowBy, const bool& _FastCopy, const TVal& _EmptyVal) : GrowBy(_GrowBy), MxVals(0), Vals(0), EmptyVal(_EmptyVal), ValBf(NULL) {
IdToOffV.Add(0);
Resize(ExpectVals);
}
template <class TVal, class TSizeTy>
TVecPool<TVal, TSizeTy>::TVecPool(const TVecPool& Pool) : FastCopy(Pool.FastCopy), GrowBy(Pool.GrowBy), MxVals(Pool.MxVals), Vals(Pool.Vals), EmptyVal(Pool.EmptyVal), IdToOffV(Pool.IdToOffV) {
try {
ValBf = new TVal [MxVals]; }
catch (std::exception Ex) {
FailR(TStr::Fmt("TVecPool::TVecPool: %s, MxVals: %s. [Program failed to allocate memory. Solution: Get a bigger machine and a 64-bit compiler.]", Ex.what(), TInt::GetStr(uint64(MxVals)).CStr()).CStr()); }
IAssert(ValBf != NULL);
if (FastCopy) {
memcpy(ValBf, Pool.ValBf, MxVals*sizeof(TVal)); }
else {
for (TSize ValN = 0; ValN < MxVals; ValN++){ ValBf[ValN] = Pool.ValBf[ValN]; } }
}
template <class TVal, class TSizeTy>
TVecPool<TVal, TSizeTy>::TVecPool(TSIn& SIn) : FastCopy(SIn) {
uint64 _GrowBy, _MxVals, _Vals;
SIn.Load(_GrowBy); SIn.Load(_MxVals); SIn.Load(_Vals);
IAssertR(_GrowBy<TSizeMx && _MxVals<TSizeMx && _Vals<TSizeMx, "This is a 64-bit vector pool. Use a 64-bit compiler.");
GrowBy=TSize(_GrowBy); MxVals=TSize(_Vals); Vals=TSize(_Vals); //note MxVals==Vals
EmptyVal = TVal(SIn);
if (MxVals==0) { ValBf = NULL; } else { ValBf = new TVal [MxVals]; }
for (TSize ValN = 0; ValN < Vals; ValN++) { ValBf[ValN] = TVal(SIn); }
{ TInt MxVals(SIn), Vals(SIn);
IdToOffV.Gen(Vals);
for (int ValN = 0; ValN < Vals; ValN++) {
uint64 Offset; SIn.Load(Offset); IAssert(Offset < TSizeMx);
IdToOffV[ValN]=TSize(Offset);
} }
}
template <class TVal, class TSizeTy>
void TVecPool<TVal, TSizeTy>::Save(TSOut& SOut) const {
SOut.Save(FastCopy);
uint64 _GrowBy=GrowBy, _MxVals=MxVals, _Vals=Vals;
SOut.Save(_GrowBy); SOut.Save(_MxVals); SOut.Save(_Vals);
SOut.Save(EmptyVal);
for (TSize ValN = 0; ValN < Vals; ValN++) { ValBf[ValN].Save(SOut); }
{ SOut.Save(IdToOffV.Len()); SOut.Save(IdToOffV.Len());
for (int ValN = 0; ValN < IdToOffV.Len(); ValN++) {
const uint64 Offset=IdToOffV[ValN]; SOut.Save(Offset);
} }
}
template <class TVal, class TSizeTy>
TVecPool<TVal, TSizeTy>& TVecPool<TVal, TSizeTy>::operator = (const TVecPool& Pool) {
if (this!=&Pool) {
FastCopy = Pool.FastCopy;
GrowBy = Pool.GrowBy;
MxVals = Pool.MxVals;
Vals = Pool.Vals;
EmptyVal = Pool.EmptyVal;
IdToOffV=Pool.IdToOffV;
try {
ValBf = new TVal [MxVals]; }
catch (std::exception Ex) {
FailR(TStr::Fmt("TVecPool::operator=: %s, MxVals: %s. [Program failed to allocate memory. Solution: Get a bigger machine and a 64-bit compiler.]", Ex.what(), TInt::GetStr(uint64(MxVals)).CStr()).CStr()); }
IAssert(ValBf != NULL);
if (FastCopy) {
memcpy(ValBf, Pool.ValBf, Vals*sizeof(TVal)); }
else {
for (TSize ValN = 0; ValN < Vals; ValN++){ ValBf[ValN] = Pool.ValBf[ValN]; } }
}
return *this;
}
template <class TVal, class TSizeTy>
int TVecPool<TVal, TSizeTy>::AddV(const TValV& ValV) {
const TSizeTy ValVLen = ValV.Len();
if (ValVLen == 0) { return 0; }
if (MxVals < Vals+ValVLen) { Resize(Vals+max(ValVLen, GrowBy)); }
if (FastCopy) { memcpy(ValBf+Vals, ValV.BegI(), sizeof(TVal)*ValV.Len()); }
else { for (uint ValN=0; ValN < ValVLen; ValN++) { ValBf[Vals+ValN]=ValV[ValN]; } }
Vals+=ValVLen; IdToOffV.Add(Vals);
return IdToOffV.Len()-1;
}
template <class TVal, class TSizeTy>
int TVecPool<TVal, TSizeTy>::AddEmptyV(const int& ValVLen) {
if (ValVLen==0){return 0;}
if (MxVals < Vals+ValVLen){Resize(Vals+max(TSize(ValVLen), GrowBy)); }
Vals+=ValVLen; IdToOffV.Add(Vals);
return IdToOffV.Len()-1;
}
// Delete all elements of value DelVal from all vectors. Empty space is left at the end of the pool.
template <class TVal, class TSizeTy>
void TVecPool<TVal, TSizeTy>::CompactPool(const TVal& DelVal) {
::TSize TotalDel=0, NDel=0;
// printf("Compacting %d vectors\n", IdToOffV.Len());
for (int vid = 1; vid < IdToOffV.Len(); vid++) {
// if (vid % 10000000 == 0) { printf(" %dm", vid/1000000); fflush(stdout); }
const uint Len = GetVLen(vid);
TVal* ValV = GetValVPt(vid);
if (TotalDel > 0) { IdToOffV[vid-1] -= TotalDel; } // update end of vector
if (Len == 0) { continue; }
NDel = 0;
for (TVal* v = ValV; v < ValV+Len-NDel; v++) {
if (*v == DelVal) {
TVal* Beg = v;
while (*v == DelVal && v < ValV+Len) { v++; NDel++; }
memcpy(Beg, v, sizeof(TVal)*int(Len - ::TSize(v - ValV)));
v -= NDel;
}
}
memcpy(ValV-TotalDel, ValV, sizeof(TVal)*Len); // move data
TotalDel += NDel;
}
IdToOffV.Last() -= TotalDel;
for (::TSize i = Vals-TotalDel; i < Vals; i++) { ValBf[i] = EmptyVal; }
Vals -= TotalDel;
// printf(" deleted %llu elements from the pool\n", TotalDel);
}
// shuffles all the order of elements in the pool (does not respect vector boundaries)
template <class TVal, class TSizeTy>
void TVecPool<TVal, TSizeTy>::ShuffleAll(TRnd& Rnd) {
for (::TSize n = Vals-1; n > 0; n--) {
const ::TSize k = ::TSize(((uint64(Rnd.GetUniDevInt())<<32) | uint64(Rnd.GetUniDevInt())) % (n+1));
const TVal Tmp = ValBf[n];
ValBf[n] = ValBf[k];
ValBf[k] = Tmp;
}
}
/////////////////////////////////////////////////
// Below are old 32-bit implementations of TVec and other classes.
// Old TVec takes at most 2G elements.
// The new vector class supports 64-bits for the number of elements,
// but also allows 32-bits for backward compatibility.
// by Jure (Jan 2013)
namespace TGLib_OLD {
/////////////////////////////////////////////////
// Vector Pool
template<class TVal>
class TVecPool {
public:
typedef TPt<TVecPool<TVal> > PVecPool;
typedef TVec<TVal> TValV;
private:
TCRef CRef;
TBool FastCopy;
::TSize GrowBy, MxVals, Vals;
TVal EmptyVal; // empty vector
TVal *ValBf; // buffer storing all the values
TVec< ::TSize> IdToOffV; // id to one past last (vector starts at [id-1])
private:
void Resize(const ::TSize& _MxVals);
public:
TVecPool(const ::TSize& ExpectVals=0, const ::TSize& _GrowBy=1000000, const bool& _FastCopy=false, const TVal& _EmptyVal=TVal());
TVecPool(const TVecPool& Pool);
TVecPool(TSIn& SIn);
~TVecPool() { if (ValBf != NULL) { delete [] ValBf; } ValBf=NULL; }
static PVecPool New(const ::TSize& ExpectVals=0, const ::TSize& GrowBy=1000000, const bool& FastCopy=false) {
return new TVecPool(ExpectVals, GrowBy, FastCopy); }
static PVecPool Load(TSIn& SIn) { return new TVecPool(SIn); }
static PVecPool Load(const TStr& FNm) { TFIn FIn(FNm); return Load(FIn); }
void Save(TSOut& SOut) const;
TVecPool& operator = (const TVecPool& Pool);
::TSize GetVals() const { return Vals; }
::TSize GetVecs() const { return IdToOffV.Len(); }
bool IsVId(const int& VId) const { return (0 <= VId) && (VId < IdToOffV.Len()); }
::TSize Reserved() const { return MxVals; }
void Reserve(const ::TSize& MxVals) { Resize(MxVals); }
const TVal& GetEmptyVal() const { return EmptyVal; }
void SetEmptyVal(const TVal& _EmptyVal) { EmptyVal = _EmptyVal; }
::TSize GetMemUsed() const {
return sizeof(TCRef)+sizeof(TBool)+3*sizeof(TSize)+sizeof(TVal*)+MxVals*sizeof(TVal);}
int AddV(const TValV& ValV);
int AddEmptyV(const int& ValVLen);
uint GetVLen(const int& VId) const {
if (VId==0){return 0;}
else {return uint(IdToOffV[VId]-IdToOffV[VId-1]);}}
TVal* GetValVPt(const int& VId) const {
if (GetVLen(VId)==0){return (TVal*)&EmptyVal;}
else {return ValBf+IdToOffV[VId-1];}}
void GetV(const int& VId, TValV& ValV) const {
if (GetVLen(VId)==0){ValV.Clr();}
else { ValV.GenExt(GetValVPt(VId), GetVLen(VId)); } }
void PutV(const int& VId, const TValV& ValV) {
IAssert(IsVId(VId) && GetVLen(VId) == ValV.Len());
if (FastCopy) {
memcpy(GetValVPt(VId), ValV.BegI(), sizeof(TVal)*ValV.Len()); }
else { TVal* ValPt = GetValVPt(VId);
for (uint ValN=0; ValN < uint(ValV.Len()); ValN++, ValPt++) { *ValPt=ValV[ValN]; }
}
}
void CompactPool(const TVal& DelVal); // delete all elements of value DelVal from all vectors
void ShuffleAll(TRnd& Rnd=TInt::Rnd); // shuffles all the order of elements in the Pool (does not respect vector boundaries)
//bool HasIdMap() const { return ! IdToOffV.Empty(); }
//void ClrIdMap() { IdToOffV.Clr(true); }
void Clr(bool DoDel = true) {
IdToOffV.Clr(DoDel); MxVals=0; Vals=0;
if (DoDel && ValBf!=NULL) { delete [] ValBf; ValBf=NULL;}
if (! DoDel) { PutAll(EmptyVal); }
}
void PutAll(const TVal& Val) {
for (TSize ValN = 0; ValN < MxVals; ValN++) { ValBf[ValN]=Val; } }
friend class TPt<TVecPool<TVal> >;
};
template <class TVal>
void TVecPool<TVal>::Resize(const ::TSize& _MxVals){
if (_MxVals <= MxVals){ return; } else { MxVals = _MxVals; }
if (ValBf == NULL) {
try { ValBf = new TVal [MxVals]; }
catch (std::exception Ex) {
FailR(TStr::Fmt("TVecPool::Resize 1: %s, MxVals: %d. [Program failed to allocate more memory. Solution: Get a bigger machine and a 64-bit compiler.]", Ex.what(), _MxVals).CStr()); }
IAssert(ValBf != NULL);
if (EmptyVal != TVal()) { PutAll(EmptyVal); }
} else {
// printf("*** Resize vector pool: %llu -> %llu\n", uint64(Vals), uint64(MxVals));
TVal* NewValBf = NULL;
try { NewValBf = new TVal [MxVals]; }
catch (std::exception Ex) { FailR(TStr::Fmt("TVecPool::Resize 2: %s, MxVals: %d. [Program failed to allocate more memory. Solution: Get a bigger machine and a 64-bit compiler.]", Ex.what(), _MxVals).CStr()); }
IAssert(NewValBf != NULL);
if (FastCopy) {
memcpy(NewValBf, ValBf, Vals*sizeof(TVal)); }
else {
for (TSize ValN = 0; ValN < Vals; ValN++){ NewValBf[ValN] = ValBf[ValN]; } }
if (EmptyVal != TVal()) { // init empty values
for (TSize ValN = Vals; ValN < MxVals; ValN++) { NewValBf[ValN] = EmptyVal; }
}
delete [] ValBf;
ValBf = NewValBf;
}
}
template <class TVal>
TVecPool<TVal>::TVecPool(const ::TSize& ExpectVals, const ::TSize& _GrowBy, const bool& _FastCopy, const TVal& _EmptyVal) :
GrowBy(_GrowBy), MxVals(0), Vals(0), EmptyVal(_EmptyVal), ValBf(NULL) {
IdToOffV.Add(0);
Resize(ExpectVals);
}
template <class TVal>
TVecPool<TVal>::TVecPool(const TVecPool& Pool):
FastCopy(Pool.FastCopy), GrowBy(Pool.GrowBy),
MxVals(Pool.MxVals), Vals(Pool.Vals), EmptyVal(Pool.EmptyVal), IdToOffV(Pool.IdToOffV) {
try { ValBf = new TVal [MxVals]; }
catch (std::exception Ex) { FailR(TStr::Fmt("TVecPool::TVecPool: %s, MxVals: %d", Ex.what(), MxVals).CStr()); }
IAssert(ValBf != NULL);
if (FastCopy) {
memcpy(ValBf, Pool.ValBf, MxVals*sizeof(TVal)); }
else {
for (TSize ValN = 0; ValN < MxVals; ValN++){ ValBf[ValN] = Pool.ValBf[ValN]; } }
}
template <class TVal>
TVecPool<TVal>::TVecPool(TSIn& SIn):
FastCopy(SIn) {
uint64 _GrowBy, _MxVals, _Vals;
SIn.Load(_GrowBy); SIn.Load(_MxVals); SIn.Load(_Vals);
IAssert(_GrowBy<TSizeMx && _MxVals<TSizeMx && _Vals<TSizeMx);
GrowBy=TSize(_GrowBy); MxVals=TSize(_Vals); Vals=TSize(_Vals); //note MxVals==Vals
EmptyVal = TVal(SIn);
if (MxVals==0) { ValBf = NULL; } else { ValBf = new TVal [MxVals]; }
for (TSize ValN = 0; ValN < Vals; ValN++) { ValBf[ValN] = TVal(SIn); }
{ TInt MxVals(SIn), Vals(SIn);
IdToOffV.Gen(Vals);
for (int ValN = 0; ValN < Vals; ValN++) {
uint64 Offset; SIn.Load(Offset); IAssert(Offset < TSizeMx);
IdToOffV[ValN]=TSize(Offset);
} }
}
template <class TVal>
void TVecPool<TVal>::Save(TSOut& SOut) const {
SOut.Save(FastCopy);
uint64 _GrowBy=GrowBy, _MxVals=MxVals, _Vals=Vals;
SOut.Save(_GrowBy); SOut.Save(_MxVals); SOut.Save(_Vals);
SOut.Save(EmptyVal);
for (TSize ValN = 0; ValN < Vals; ValN++) { ValBf[ValN].Save(SOut); }
{ SOut.Save(IdToOffV.Len()); SOut.Save(IdToOffV.Len());
for (int ValN = 0; ValN < IdToOffV.Len(); ValN++) {
const uint64 Offset=IdToOffV[ValN]; SOut.Save(Offset);
} }
}
template <class TVal>
TVecPool<TVal>& TVecPool<TVal>::operator = (const TVecPool& Pool) {
if (this!=&Pool) {
FastCopy = Pool.FastCopy;
GrowBy = Pool.GrowBy;
MxVals = Pool.MxVals;
Vals = Pool.Vals;
EmptyVal = Pool.EmptyVal;
IdToOffV=Pool.IdToOffV;
try { ValBf = new TVal [MxVals]; }
catch (std::exception Ex) { FailR(TStr::Fmt("TVec::operator= : %s, MxVals: %d", Ex.what(), MxVals).CStr()); }
IAssert(ValBf != NULL);
if (FastCopy) {
memcpy(ValBf, Pool.ValBf, Vals*sizeof(TVal)); }
else {
for (uint64 ValN = 0; ValN < Vals; ValN++){ ValBf[ValN] = Pool.ValBf[ValN]; } }
}
return *this;
}
template<class TVal>
int TVecPool<TVal>::AddV(const TValV& ValV) {
const ::TSize ValVLen = ValV.Len();
if (ValVLen == 0) { return 0; }
if (MxVals < Vals+ValVLen) { Resize(Vals+max(ValVLen, GrowBy)); }
if (FastCopy) { memcpy(ValBf+Vals, ValV.BegI(), sizeof(TVal)*ValV.Len()); }
else { for (uint ValN=0; ValN < ValVLen; ValN++) { ValBf[Vals+ValN]=ValV[ValN]; } }
Vals+=ValVLen; IdToOffV.Add(Vals);
return IdToOffV.Len()-1;
}
template<class TVal>
int TVecPool<TVal>::AddEmptyV(const int& ValVLen) {
if (ValVLen==0){return 0;}
if (MxVals < Vals+ValVLen){Resize(Vals+max(TSize(ValVLen), GrowBy)); }
Vals+=ValVLen; IdToOffV.Add(Vals);
return IdToOffV.Len()-1;
}
// delete all elements of value DelVal from all vectors
// empty space is left at the end of the pool
template<class TVal>
void TVecPool<TVal>::CompactPool(const TVal& DelVal) {
::TSize TotalDel=0, NDel=0;
// printf("Compacting %d vectors\n", IdToOffV.Len());
for (int vid = 1; vid < IdToOffV.Len(); vid++) {
// if (vid % 10000000 == 0) { printf(" %dm", vid/1000000); fflush(stdout); }
const uint Len = GetVLen(vid);
TVal* ValV = GetValVPt(vid);
if (TotalDel > 0) { IdToOffV[vid-1] -= TotalDel; } // update end of vector
if (Len == 0) { continue; }
NDel = 0;
for (TVal* v = ValV; v < ValV+Len-NDel; v++) {
if (*v == DelVal) {
TVal* Beg = v;
while (*v == DelVal && v < ValV+Len) { v++; NDel++; }
memcpy(Beg, v, sizeof(TVal)*int(Len - ::TSize(v - ValV)));
v -= NDel;
}
}
memcpy(ValV-TotalDel, ValV, sizeof(TVal)*Len); // move data
TotalDel += NDel;
}
IdToOffV.Last() -= TotalDel;
for (::TSize i = Vals-TotalDel; i < Vals; i++) { ValBf[i] = EmptyVal; }
Vals -= TotalDel;
// printf(" deleted %llu elements from the pool\n", TotalDel);
}
// shuffles all the order of elements in the pool (does not respect vector boundaries)
template<class TVal>
void TVecPool<TVal>::ShuffleAll(TRnd& Rnd) {
for (::TSize n = Vals-1; n > 0; n--) {
const ::TSize k = ::TSize(((uint64(Rnd.GetUniDevInt())<<32) | uint64(Rnd.GetUniDevInt())) % (n+1));
const TVal Tmp = ValBf[n];
ValBf[n] = ValBf[k];
ValBf[k] = Tmp;
}
}
}; // namespace TGLib_OLD
typedef TVecPool<TInt> TIntVecPool;
typedef TPt<TIntVecPool> PIntVecPool;
/////////////////////////////////////////////////
// Vector-Pointer
template <class TVal>
class PVec{
private:
TCRef CRef;
public:
TVec<TVal> V;
public:
PVec<TVal>(): V(){}
PVec<TVal>(const PVec<TVal>& Vec): V(Vec.V){}
static TPt<PVec<TVal> > New(){
return new PVec<TVal>();}
PVec<TVal>(const int& MxVals, const int& Vals): V(MxVals, Vals){}
static TPt<PVec<TVal> > New(const int& MxVals, const int& Vals){
return new PVec<TVal>(MxVals, Vals);}
PVec<TVal>(const TVec<TVal>& _V): V(_V){}
static TPt<PVec<TVal> > New(const TVec<TVal>& V){
return new PVec<TVal>(V);}
explicit PVec<TVal>(TSIn& SIn): V(SIn){}
static TPt<PVec<TVal> > Load(TSIn& SIn){return new PVec<TVal>(SIn);}
void Save(TSOut& SOut) const {V.Save(SOut);}
PVec<TVal>& operator=(const PVec<TVal>& Vec){
if (this!=&Vec){V=Vec.V;} return *this;}
bool operator==(const PVec<TVal>& Vec) const {return V==Vec.V;}
bool operator<(const PVec<TVal>& Vec) const {return V<Vec.V;}
TVal& operator[](const int& ValN) const {return V[ValN];}
bool Empty() const {return V.Empty();}
int Len() const {return V.Len();}
TVal GetVal(const int& ValN) const {return V[ValN];}
int Add(const TVal& Val){return V.Add(Val);}
friend class TPt<PVec<TVal> >;
};
/////////////////////////////////////////////////
// Common-Vector-Pointer-Types
typedef PVec<TFlt> TFltVP;
typedef TPt<TFltVP> PFltV;
typedef PVec<TAscFlt> TAscFltVP;
typedef TPt<TAscFltVP> PAscFltV;
typedef PVec<TStr> TStrVP;
typedef TPt<TStrVP> PStrV;
/////////////////////////////////////////////////
// 2D-Vector
template <class TVal>
class TVVec{
private:
TInt XDim, YDim;
TVec<TVal> ValV;
public:
TVVec(): XDim(), YDim(), ValV(){}
TVVec(const TVVec& Vec):
XDim(Vec.XDim), YDim(Vec.YDim), ValV(Vec.ValV){}
TVVec(const int& _XDim, const int& _YDim):
XDim(), YDim(), ValV(){Gen(_XDim, _YDim);}
explicit TVVec(const TVec<TVal>& _ValV, const int& _XDim, const int& _YDim):
XDim(_XDim), YDim(_YDim), ValV(_ValV){ IAssert(ValV.Len()==XDim*YDim); }
explicit TVVec(TSIn& SIn) {Load(SIn);}
void Load(TSIn& SIn){XDim.Load(SIn); YDim.Load(SIn); ValV.Load(SIn);}
void Save(TSOut& SOut) const {
XDim.Save(SOut); YDim.Save(SOut); ValV.Save(SOut);}
TVVec<TVal>& operator=(const TVVec<TVal>& Vec){
if (this!=&Vec){XDim=Vec.XDim; YDim=Vec.YDim; ValV=Vec.ValV;} return *this;}
bool operator==(const TVVec& Vec) const {
return (XDim==Vec.XDim)&&(YDim==Vec.YDim)&&(ValV==Vec.ValV);}
bool Empty() const {return ValV.Len()==0;}
void Clr(){XDim=0; YDim=0; ValV.Clr();}
void Gen(const int& _XDim, const int& _YDim){
Assert((_XDim>=0)&&(_YDim>=0));
XDim=_XDim; YDim=_YDim; ValV.Gen(XDim*YDim);}
int GetXDim() const {return XDim;}
int GetYDim() const {return YDim;}
int GetRows() const {return XDim;}
int GetCols() const {return YDim;}
TVec<TVal>& Get1DVec(){return ValV;}
const TVal& At(const int& X, const int& Y) const {
Assert((0<=X)&&(X<int(XDim))&&(0<=Y)&&(Y<int(YDim)));
return ValV[X*YDim+Y];}
TVal& At(const int& X, const int& Y){
Assert((0<=X)&&(X<int(XDim))&&(0<=Y)&&(Y<int(YDim)));
return ValV[X*YDim+Y];}
TVal& operator()(const int& X, const int& Y){
return At(X, Y);}
const TVal& operator()(const int& X, const int& Y) const {
return At(X, Y);}
void PutXY(const int& X, const int& Y, const TVal& Val){At(X, Y)=Val;}
void PutAll(const TVal& Val){ValV.PutAll(Val);}
void PutX(const int& X, const TVal& Val){
for (int Y=0; Y<int(YDim); Y++){At(X, Y)=Val;}}
void PutY(const int& Y, const TVal& Val){
for (int X=0; X<int(XDim); X++){At(X, Y)=Val;}}
TVal GetXY(const int& X, const int& Y) const {
Assert((0<=X)&&(X<int(XDim))&&(0<=Y)&&(Y<int(YDim)));
return ValV[X*YDim+Y];}
void GetRow(const int& RowN, TVec<TVal>& Vec) const;
void GetCol(const int& ColN, TVec<TVal>& Vec) const;
void SwapX(const int& X1, const int& X2);
void SwapY(const int& Y1, const int& Y2);
void Swap(TVVec<TVal>& Vec);
void ShuffleX(TRnd& Rnd);
void ShuffleY(TRnd& Rnd);
void GetMxValXY(int& X, int& Y) const;
void CopyFrom(const TVVec<TVal>& VVec);
void AddXDim();
void AddYDim();
void DelX(const int& X);
void DelY(const int& Y);
};
template <class TVal>
void TVVec<TVal>::SwapX(const int& X1, const int& X2){
for (int Y=0; Y<int(YDim); Y++){
TVal Val=At(X1, Y); At(X1, Y)=At(X2, Y); At(X2, Y)=Val;}
}
template <class TVal>
void TVVec<TVal>::SwapY(const int& Y1, const int& Y2){
for (int X=0; X<int(XDim); X++){
TVal Val=At(X, Y1); At(X, Y1)=At(X, Y2); At(X, Y2)=Val;}
}
template <class TVal>
void TVVec<TVal>::Swap(TVVec<TVal>& Vec){ //J:
if (this!=&Vec){
::Swap(XDim, Vec.XDim);
::Swap(YDim, Vec.YDim);
ValV.Swap(Vec.ValV);
}
}
template <class TVal>
void TVVec<TVal>::ShuffleX(TRnd& Rnd){
for (int X=0; X<XDim-1; X++){SwapX(X, X+Rnd.GetUniDevInt(XDim-X));}
}
template <class TVal>
void TVVec<TVal>::ShuffleY(TRnd& Rnd){
for (int Y=0; Y<YDim-1; Y++){SwapY(Y, Y+Rnd.GetUniDevInt(YDim-Y));}
}
template <class TVal>
void TVVec<TVal>::GetMxValXY(int& X, int& Y) const {
int MxValN=ValV.GetMxValN();
Y=MxValN%YDim;
X=MxValN/YDim;
}
template <class TVal>
void TVVec<TVal>::CopyFrom(const TVVec<TVal>& VVec){
int CopyXDim=TInt::GetMn(GetXDim(), VVec.GetXDim());
int CopyYDim=TInt::GetMn(GetYDim(), VVec.GetYDim());
for (int X=0; X<CopyXDim; X++){
for (int Y=0; Y<CopyYDim; Y++){
At(X, Y)=VVec.At(X, Y);
}
}
}
template <class TVal>
void TVVec<TVal>::AddXDim(){
TVVec<TVal> NewVVec(XDim+1, YDim);
NewVVec.CopyFrom(*this);
*this=NewVVec;
}
template <class TVal>
void TVVec<TVal>::AddYDim(){
TVVec<TVal> NewVVec(XDim, YDim+1);
NewVVec.CopyFrom(*this);
*this=NewVVec;
}
template <class TVal>
void TVVec<TVal>::DelX(const int& X){
TVVec<TVal> NewVVec(XDim-1, YDim);
for (int Y=0; Y<YDim; Y++){
for (int LX=0; LX<X; LX++){
NewVVec.At(LX, Y)=At(LX, Y);}
for (int RX=X+1; RX<XDim; RX++){
NewVVec.At(RX-1, Y)=At(RX, Y);}
}
*this=NewVVec;
}
template <class TVal>
void TVVec<TVal>::DelY(const int& Y){
TVVec<TVal> NewVVec(XDim, YDim-1);
for (int X=0; X<XDim; X++){
for (int LY=0; LY<Y; LY++){
NewVVec.At(X, LY)=At(X, LY);}
for (int RY=Y+1; RY<YDim; RY++){
NewVVec.At(X, RY-1)=At(X, RY);}
}
*this=NewVVec;
}
template <class TVal>
void TVVec<TVal>::GetRow(const int& RowN, TVec<TVal>& Vec) const {
Vec.Gen(GetCols(), 0);
for (int col = 0; col < GetCols(); col++) {
Vec.Add(At(RowN, col));
}
}
template <class TVal>
void TVVec<TVal>::GetCol(const int& ColN, TVec<TVal>& Vec) const {
Vec.Gen(GetRows(), 0);
for (int row = 0; row < GetRows(); row++) {
Vec.Add(At(row, ColN));
}
}
/////////////////////////////////////////////////
// Common-2D-Vector-Types
typedef TVVec<TBool> TBoolVV;
typedef TVVec<TCh> TChVV;
typedef TVVec<TInt> TIntVV;
typedef TVVec<TSFlt> TSFltVV;
typedef TVVec<TFlt> TFltVV;
typedef TVVec<TStr> TStrVV;
typedef TVVec<TIntPr> TIntPrVV;
/////////////////////////////////////////////////
// 3D-Vector
template <class TVal>
class TVVVec{
private:
TInt XDim, YDim, ZDim;
TVec<TVal> ValV;
public:
TVVVec(): XDim(), YDim(), ZDim(), ValV(){}
TVVVec(const TVVVec& Vec):
XDim(Vec.XDim), YDim(Vec.YDim), ZDim(Vec.ZDim), ValV(Vec.ValV){}
TVVVec(const int& _XDim, const int& _YDim, const int& _ZDim):
XDim(), YDim(), ZDim(), ValV(){Gen(_XDim, _YDim, _ZDim);}
explicit TVVVec(TSIn& SIn):
XDim(SIn), YDim(SIn), ZDim(SIn), ValV(SIn){}
void Save(TSOut& SOut) const {
XDim.Save(SOut); YDim.Save(SOut); ZDim.Save(SOut); ValV.Save(SOut);}
TVVVec<TVal>& operator=(const TVVVec<TVal>& Vec){
XDim=Vec.XDim; YDim=Vec.YDim; ZDim=Vec.ZDim; ValV=Vec.ValV;
return *this;
}
bool operator==(const TVVVec& Vec) const {
return (XDim==Vec.XDim)&&(YDim==Vec.YDim)&&(ZDim==Vec.ZDim)&&
(ValV==Vec.ValV);}
bool Empty() const {return ValV.Len()==0;}
void Clr(){XDim=0; YDim=0; ZDim=0; ValV.Clr();}
void Gen(const int& _XDim, const int& _YDim, const int& _ZDim){
Assert((_XDim>=0)&&(_YDim>=0)&&(_ZDim>=0));
XDim=_XDim; YDim=_YDim; ZDim=_ZDim; ValV.Gen(XDim*YDim*ZDim);}
TVal& At(const int& X, const int& Y, const int& Z){
Assert((0<=X)&&(X<int(XDim))&&(0<=Y)&&(Y<int(YDim))&&(0<=Z)&&(Z<int(ZDim)));
return ValV[X*YDim*ZDim+Y*ZDim+Z];}
const TVal& At(const int& X, const int& Y, const int& Z) const {
Assert((0<=X)&&(X<int(XDim))&&(0<=Y)&&(Y<int(YDim))&&(0<=Z)&&(Z<int(ZDim)));
return ValV[X*YDim*ZDim+Y*ZDim+Z];}
TVal& operator()(const int& X, const int& Y, const int& Z){
return At(X, Y, Z);}
const TVal& operator()(const int& X, const int& Y, const int& Z) const {
return At(X, Y, Z);}
int GetXDim() const {return XDim;}
int GetYDim() const {return YDim;}
int GetZDim() const {return ZDim;}
};
/////////////////////////////////////////////////
// Common-3D-Vector-Types
typedef TVVVec<TInt> TIntVVV;
typedef TVVVec<TFlt> TFltVVV;
/////////////////////////////////////////////////
// Tree
template <class TVal>
class TTree{
private:
TVec<TTriple<TInt, TIntV, TVal> > NodeV; // (ParentNodeId, ChildNodeIdV, NodeVal)
public:
TTree(): NodeV(){}
TTree(const TTree& Tree): NodeV(Tree.NodeV){}
explicit TTree(TSIn& SIn): NodeV(SIn){}
void Save(TSOut& SOut) const {NodeV.Save(SOut);}
void LoadXml(const PXmlTok& XmlTok, const TStr& Nm="");
void SaveXml(TSOut& SOut, const TStr& Nm) const;
TTree& operator=(const TTree& Tree){if (this!=&Tree){NodeV=Tree.NodeV;} return *this;}
bool operator==(const TTree& Tree) const {return NodeV==Tree.NodeV;}
bool operator<(const TTree& Tree) const {return false;}
int GetPrimHashCd() const {return NodeV.GetPrimHashCd();}
int GetSecHashCd() const {return NodeV.GetSecHashCd();}
int GetMemUsed() const {return NodeV.GetMemUsed();}
void Clr(){NodeV.Clr();}
int AddNode(const int& ParentNodeId, const TVal& NodeVal=TVal()){
IAssert(((ParentNodeId==-1)&&(NodeV.Len()==0))||(NodeV.Len()>0));
if (ParentNodeId!=-1){NodeV[ParentNodeId].Val2.Add(NodeV.Len());}
return NodeV.Add(TTriple<TInt, TIntV, TVal>(ParentNodeId, TIntV(), NodeVal));}
int AddRoot(const TVal& NodeVal=TVal()){
return AddNode(-1, NodeVal);}
int GetNodes() const {return NodeV.Len();}
void GetNodeIdV(TIntV& NodeIdV, const int& NodeId=0);
int GetParentNodeId(const int& NodeId) const {return NodeV[NodeId].Val1;}
int GetChildren(const int& NodeId) const {return NodeV[NodeId].Val2.Len();}
int GetChildNodeId(const int& NodeId, const int& ChildN) const {return NodeV[NodeId].Val2[ChildN];}
TVal& GetNodeVal(const int& NodeId){return NodeV[NodeId].Val3;}
void GenRandomTree(const int& Nodes, TRnd& Rnd);
void DelNode(const int& NodeId);
void CopyTree(const int& SrcNodeId, TTree& DstTree, const int& DstParentNodeId=-1);
void WrTree(const int& NodeId=0, const int& Lev=0);
};
template <class TVal>
void TTree<TVal>::GetNodeIdV(TIntV& NodeIdV, const int& NodeId){
if (NodeId==0){NodeIdV.Clr(); if (GetNodes()==0){return;}}
else if (GetParentNodeId(NodeId)==-1){return;}
NodeIdV.Add(NodeId);
for (int ChildN=0; ChildN<GetChildren(NodeId); ChildN++){
int ChildNodeId=GetChildNodeId(NodeId, ChildN);
if (ChildNodeId!=-1){
GetNodeIdV(NodeIdV, ChildNodeId);
}
}
}
template <class TVal>
void TTree<TVal>::GenRandomTree(const int& Nodes, TRnd& Rnd){
Clr();
if (Nodes>0){
AddRoot(TVal());
for (int NodeN=1; NodeN<Nodes; NodeN++){
int ParentNodeId=Rnd.GetUniDevInt(0, GetNodes()-1);
AddNode(ParentNodeId, TVal());
}
}
}
template <class TVal>
void TTree<TVal>::DelNode(const int& NodeId){
if (NodeId==0){
Clr();
} else {
TIntV& ChildNodeIdV=NodeV[GetParentNodeId(NodeId)].Val2;
int ChildNodeIdN=ChildNodeIdV.SearchForw(NodeId);
ChildNodeIdV[ChildNodeIdN]=-1;
}
}
template <class TVal>
void TTree<TVal>::CopyTree(const int& SrcNodeId, TTree& DstTree, const int& DstParentNodeId){
int DstNodeId=DstTree.AddNode(DstParentNodeId, GetNodeVal(SrcNodeId));
for (int ChildN=0; ChildN<GetChildren(SrcNodeId); ChildN++){
int ChildNodeId=GetChildNodeId(SrcNodeId, ChildN);
if (ChildNodeId!=-1){
CopyTree(ChildNodeId, DstTree, DstNodeId);
}
}
}
template <class TVal>
void TTree<TVal>::WrTree(const int& NodeId, const int& Lev){
for (int LevN=0; LevN<Lev; LevN++){printf("| ");}
printf("%d (%d)\n", NodeId, GetChildren(NodeId));
for (int ChildN=0; ChildN<GetChildren(NodeId); ChildN++){
int ChildNodeId=GetChildNodeId(NodeId, ChildN);
if (ChildNodeId!=-1){
WrTree(ChildNodeId, Lev+1);
}
}
}
/////////////////////////////////////////////////
// Common-Tree-Types
typedef TTree<TInt> TIntTree;
typedef TTree<TFlt> TFltTree;
typedef TTree<TStr> TStrTree;
typedef TTree<TStrIntPr> TStrIntPrTree;
typedef TTree<TStrIntStrVTr> TStrIntStrVTrTree;
/////////////////////////////////////////////////
// Stack
template <class TVal>
class TSStack{
private:
TVec<TVal> ValV;
public:
TSStack(): ValV(){}
TSStack(const int& MxVals): ValV(MxVals, 0){}
TSStack(const TSStack& Stack): ValV(Stack.ValV){}
explicit TSStack(TSIn& SIn): ValV(SIn){}
void Save(TSOut& SOut) const {ValV.Save(SOut);}
TSStack& operator=(const TSStack& Stack){
if (this!=&Stack){ValV=Stack.ValV;} return *this;}
bool operator==(const TSStack& Stack) const {return this==&Stack;}
const TVal& operator[](const int& ValN) const {return ValV[ValV.Len()-ValN-1];}
TVal& operator[](const int& ValN) {return ValV[ValV.Len()-ValN-1];}
bool Empty(){return ValV.Len()==0;}
void Clr(const bool& DoDel=false) {ValV.Clr(DoDel);}
bool IsIn(const TVal& Val) const {return ValV.IsIn(Val);}
int Len(){return ValV.Len();}
TVal& Top(){Assert(0<ValV.Len()); return ValV.Last();}
const TVal& Top() const {Assert(0<ValV.Len()); return ValV.Last();}
void Push(){ValV.Add();}
void Push(const TVal& Val){ValV.Add(Val);}
void Pop(){Assert(0<ValV.Len()); ValV.DelLast();}
};
/////////////////////////////////////////////////
// Common-Stack-Types
typedef TSStack<TInt> TIntS;
typedef TSStack<TBoolChPr> TBoolChS;
/////////////////////////////////////////////////
// Queue
template <class TVal>
class TQQueue{
private:
TInt MxLast, MxLen;
TInt First, Last;
TVec<TVal> ValV;
public:
TQQueue(const int& _MxLast=64, const int& _MxLen=-1):
MxLast(_MxLast), MxLen(_MxLen), First(0), Last(0), ValV(){
Assert(int(MxLast)>0); Assert((MxLen==-1)||(int(MxLen)>0));}
TQQueue(const TQQueue& Queue):
MxLast(Queue.MxLast), MxLen(Queue.MxLen),
First(Queue.First), Last(Queue.Last), ValV(Queue.ValV){}
explicit TQQueue(TSIn& SIn):
MxLast(SIn), MxLen(SIn), First(SIn), Last(SIn), ValV(SIn){}
void Save(TSOut& SOut) const {
MxLast.Save(SOut); MxLen.Save(SOut);
First.Save(SOut); Last.Save(SOut); ValV.Save(SOut);}
TQQueue& operator=(const TQQueue& Queue){
if (this!=&Queue){MxLast=Queue.MxLast; MxLen=Queue.MxLen;
First=Queue.First; Last=Queue.Last; ValV=Queue.ValV;}
return *this;}
const TVal& operator[](const int& ValN) const {Assert((0<=ValN)&&(ValN<Len()));
return ValV[Last+ValN];}
void Clr(const bool& DoDel=true){ValV.Clr(DoDel); First=Last=0;}
void Gen(const int& _MxLast=64, const int& _MxLen=-1){
MxLast=_MxLast; MxLen=_MxLen; First=0; Last=0; ValV.Clr();}
void GetSubValV(const int& _BValN, const int& _EValN, TVec<TVal>& SubValV) const {
int BValN=TInt::GetMx(0, _BValN);
int EValN=TInt::GetMn(Len()-1, _EValN);
SubValV.Gen(EValN-BValN+1);
for (int ValN=BValN; ValN<=EValN; ValN++){
SubValV[ValN-BValN]=ValV[Last+ValN];}
}
bool Empty() const {return First==Last;}
int Len() const {return First-Last;}
const TVal& Top() const {
Assert(First!=Last); return ValV[Last];}
void Pop(){
IAssert(First!=Last); Last++;
if (First==Last){ValV.Clr(); First=Last=0;}}
void Push(const TVal& Val){
if (Last>MxLast){ValV.Del(0, Last-1); First-=Last; Last=0;}
if ((MxLen!=-1)&&(MxLen==Len())){Pop();}
First++; ValV.Add(Val);}
void Shuffle(TRnd& Rnd){
TVec<TVal> ValV(Len(), 0); while (!Empty()){ValV.Add(Top()); Pop();}
ValV.Shuffle(Rnd); Clr();
for (int ValN=0; ValN<ValV.Len(); ValN++){Push(ValV[ValN]);}}
};
/////////////////////////////////////////////////
// Common-Queue-Types
typedef TQQueue<TInt> TIntQ;
typedef TQQueue<TFlt> TFltQ;
typedef TQQueue<TStr> TStrQ;
typedef TQQueue<TIntPr> TIntPrQ;
typedef TQQueue<TIntStrPr> TIntStrPrQ;
typedef TQQueue<TFltV> TFltVQ;
typedef TQQueue<TAscFltV> TAscFltVQ;
typedef TVec<TQQueue<TInt> > TIntQV;
/////////////////////////////////////////////////
// List-Node
template <class TVal>
class TLstNd{
public:
TLstNd* PrevNd;
TLstNd* NextNd;
TVal Val;
public:
TLstNd(): PrevNd(NULL), NextNd(NULL), Val(){}
TLstNd(const TLstNd&);
TLstNd(TLstNd* _PrevNd, TLstNd* _NextNd, const TVal& _Val):
PrevNd(_PrevNd), NextNd(_NextNd), Val(_Val){}
TLstNd& operator=(const TLstNd&);
bool IsPrev() const {return (PrevNd != NULL); }
bool IsNext() const {return (NextNd != NULL); }
TLstNd* Prev() const {Assert(this!=NULL); return PrevNd;}
TLstNd* Next() const {Assert(this!=NULL); return NextNd;}
TVal& GetVal(){Assert(this!=NULL); return Val;}
const TVal& GetVal() const {Assert(this!=NULL); return Val;}
};
/////////////////////////////////////////////////
// List
template <class TVal>
class TLst{
public:
typedef TLstNd<TVal>* PLstNd;
private:
int Nds;
PLstNd FirstNd;
PLstNd LastNd;
public:
TLst(): Nds(0), FirstNd(NULL), LastNd(NULL){}
TLst(const TLst&);
~TLst(){Clr();}
explicit TLst(TSIn& SIn);
void Save(TSOut& SOut) const;
TLst& operator=(const TLst&);
void Clr(){
PLstNd Nd=FirstNd;
while (Nd!=NULL){PLstNd NextNd=Nd->NextNd; delete Nd; Nd=NextNd;}
Nds=0; FirstNd=NULL; LastNd=NULL;}
bool Empty() const {return Nds==0;}
int Len() const {return Nds;}
PLstNd First() const {return FirstNd;}
PLstNd Last() const {return LastNd;}
TVal& FirstVal() const {return FirstNd->GetVal();}
TVal& LastVal() const {return LastNd->GetVal();}
PLstNd AddFront(const TVal& Val);
PLstNd AddBack(const TVal& Val);
PLstNd AddFrontSorted(const TVal& Val, const bool& Asc=true);
PLstNd AddBackSorted(const TVal& Val, const bool& Asc=true);
void PutFront(const PLstNd& Nd);
void PutBack(const PLstNd& Nd);
PLstNd Ins(const PLstNd& Nd, const TVal& Val);
void Del(const TVal& Val);
void Del(const PLstNd& Nd);
void DelFirst() { PLstNd DelNd = FirstNd; Del(DelNd); }
void DelLast() { PLstNd DelNd = LastNd; Del(DelNd); }
PLstNd SearchForw(const TVal& Val);
PLstNd SearchBack(const TVal& Val);
friend class TLstNd<TVal>;
};
template <class TVal>
TLst<TVal>::TLst(TSIn& SIn):
Nds(0), FirstNd(NULL), LastNd(NULL){
int CheckNds=0; SIn.Load(CheckNds);
for (int NdN=0; NdN<CheckNds; NdN++){AddBack(TVal(SIn));}
Assert(Nds==CheckNds);
}
template <class TVal>
void TLst<TVal>::Save(TSOut& SOut) const {
SOut.Save(Nds);
PLstNd Nd=FirstNd; int CheckNds=0;
while (Nd!=NULL){
Nd->Val.Save(SOut); Nd=Nd->NextNd; CheckNds++;}
IAssert(Nds==CheckNds);
}
template <class TVal>
TLstNd<TVal>* TLst<TVal>::AddFront(const TVal& Val){
PLstNd Nd=new TLstNd<TVal>(NULL, FirstNd, Val);
if (FirstNd!=NULL){FirstNd->PrevNd=Nd; FirstNd=Nd;}
else {FirstNd=Nd; LastNd=Nd;}
Nds++; return Nd;
}
template <class TVal>
TLstNd<TVal>* TLst<TVal>::AddBack(const TVal& Val){
PLstNd Nd=new TLstNd<TVal>(LastNd, NULL, Val);
if (LastNd!=NULL){LastNd->NextNd=Nd; LastNd=Nd;}
else {FirstNd=Nd; LastNd=Nd;}
Nds++; return Nd;
}
template <class TVal>
TLstNd<TVal>* TLst<TVal>::AddFrontSorted(const TVal& Val, const bool& Asc){
PLstNd Nd=First();
if (Nd==NULL){
return Ins(Nd, Val);
} else {
while ((Nd!=NULL)&&((Asc&&(Val>Nd()))||(!Asc&&(Val<Nd())))){
Nd=Nd->Next();}
if (Nd==NULL){return Ins(Nd->Last(), Val);}
else {return Ins(Nd->Prev(), Val);}
}
}
template <class TVal>
TLstNd<TVal>* TLst<TVal>::AddBackSorted(const TVal& Val, const bool& Asc){
PLstNd Nd=Last();
while ((Nd!=NULL)&&((Asc&&(Val<Nd->Val))||(!Asc&&(Val>Nd->Val)))){
Nd=Nd->Prev();}
return Ins(Nd, Val);
}
template <class TVal>
void TLst<TVal>::PutFront(const PLstNd& Nd){
Assert(Nd!=NULL);
// unchain
if (Nd->PrevNd==NULL){FirstNd=Nd->NextNd;}
else {Nd->PrevNd->NextNd=Nd->NextNd;}
if (Nd->NextNd==NULL){LastNd=Nd->PrevNd;}
else {Nd->NextNd->PrevNd=Nd->PrevNd;}
// add to front
Nd->PrevNd=NULL; Nd->NextNd=FirstNd;
if (FirstNd!=NULL){FirstNd->PrevNd=Nd; FirstNd=Nd;}
else {FirstNd=Nd; LastNd=Nd;}
}
template <class TVal>
void TLst<TVal>::PutBack(const PLstNd& Nd){
Assert(Nd!=NULL);
// unchain
if (Nd->PrevNd==NULL){FirstNd=Nd->NextNd;}
else {Nd->PrevNd->NextNd=Nd->NextNd;}
if (Nd->NextNd==NULL){LastNd=Nd->PrevNd;}
else {Nd->NextNd->PrevNd=Nd->PrevNd;}
// add to back
Nd->PrevNd=LastNd; Nd->NextNd=NULL;
if (LastNd!=NULL){LastNd->NextNd=Nd; LastNd=Nd;}
else {FirstNd=Nd; LastNd=Nd;}
}
template <class TVal>
TLstNd<TVal>* TLst<TVal>::Ins(const PLstNd& Nd, const TVal& Val){
if (Nd==NULL){return AddFront(Val);}
else if (Nd->NextNd==NULL){return AddBack(Val);}
else {
PLstNd NewNd=new TLstNd<TVal>(Nd, Nd->NextNd, Val);
Nd->NextNd=NewNd; NewNd->NextNd->PrevNd=Nd;
Nds++; return Nd;
}
}
template <class TVal>
void TLst<TVal>::Del(const TVal& Val){
PLstNd Nd=SearchForw(Val);
if (Nd!=NULL){Del(Nd);}
}
template <class TVal>
void TLst<TVal>::Del(const PLstNd& Nd){
Assert(Nd!=NULL);
if (Nd->PrevNd==NULL){FirstNd=Nd->NextNd;}
else {Nd->PrevNd->NextNd=Nd->NextNd;}
if (Nd->NextNd==NULL){LastNd=Nd->PrevNd;}
else {Nd->NextNd->PrevNd=Nd->PrevNd;}
Nds--; delete Nd;
}
template <class TVal>
TLstNd<TVal>* TLst<TVal>::SearchForw(const TVal& Val){
PLstNd Nd=First();
while (Nd!=NULL){
if (Nd->GetVal()==Val){return Nd;}
Nd=Nd->Next();
}
return NULL;
}
template <class TVal>
TLstNd<TVal>* TLst<TVal>::SearchBack(const TVal& Val){
PLstNd Nd=Last();
while (Nd!=NULL){
if (Nd->GetVal()==Val){return Nd;}
Nd=Nd->Prev();
}
return NULL;
}
/////////////////////////////////////////////////
// Common-List-Types
typedef TLst<TInt> TIntL;
typedef TLstNd<TInt>* PIntLN;
typedef TLst<TIntKd> TIntKdL;
typedef TLstNd<TIntKd>* PIntKdLN;
typedef TLst<TFlt> TFltL;
typedef TLstNd<TFlt>* PFltLN;
typedef TLst<TFltIntKd> TFltIntKdL;
typedef TLstNd<TFltIntKd>* PFltIntKdLN;
typedef TLst<TAscFltIntKd> TAscFltIntKdL;
typedef TLstNd<TAscFltIntKd>* PAscFltIntKdLN;
typedef TLst<TStr> TStrL;
typedef TLstNd<TStr>* PStrLN;
/////////////////////////////////////////////////
// Record-File
template <class THd, class TRec>
class TFRec{
private:
PFRnd FRnd;
public:
TFRec(const TStr& FNm, const TFAccess& FAccess, const bool& CreateIfNo):
FRnd(PFRnd(new TFRnd(FNm, FAccess, CreateIfNo, sizeof(THd), sizeof(TRec)))){}
TFRec(const TFRec&);
TFRec& operator=(const TFRec&);
void SetRecN(const int& RecN){FRnd->SetRecN(RecN);}
int GetRecN(){return FRnd->GetRecN();}
int GetRecs(){return FRnd->GetRecs();}
void GetHd(THd& Hd){FRnd->GetHd(&Hd);}
void PutHd(const THd& Hd){FRnd->PutHd(&Hd);}
void GetRec(TRec& Rec, const int& RecN=-1){FRnd->GetRec(&Rec, RecN);}
void PutRec(const TRec& Rec, const int& RecN=-1){FRnd->PutRec(&Rec, RecN);}
};
/////////////////////////////////////////////////
// Function
template <class TFuncPt>
class TFunc{
private:
TFuncPt FuncPt;
public:
TFunc(): FuncPt(NULL){}
TFunc(const TFunc& Func): FuncPt(Func.FuncPt){}
TFunc(const TFuncPt& _FuncPt): FuncPt(_FuncPt){}
TFunc(TSIn&){Fail;}
void Save(TSOut&) const {Fail;}
TFunc& operator=(const TFunc& Func){
if (this!=&Func){FuncPt=Func.FuncPt;} return *this;}
bool operator==(const TFunc& Func) const {
return FuncPt==Func.FuncPt;}
bool operator<(const TFunc&) const {
Fail; return false;}
TFuncPt operator()() const {return FuncPt;}
};
| mit |
hpicgs/glbinding | source/glbinding/source/Binding_objects_e.cpp | 4797 |
#include "Binding_pch.h"
using namespace gl;
namespace glbinding
{
Function<void, GLboolean> Binding::EdgeFlag("glEdgeFlag");
Function<void, GLsizei> Binding::EdgeFlagFormatNV("glEdgeFlagFormatNV");
Function<void, GLsizei, const void *> Binding::EdgeFlagPointer("glEdgeFlagPointer");
Function<void, GLsizei, GLsizei, const GLboolean *> Binding::EdgeFlagPointerEXT("glEdgeFlagPointerEXT");
Function<void, GLint, const GLboolean **, GLint> Binding::EdgeFlagPointerListIBM("glEdgeFlagPointerListIBM");
Function<void, const GLboolean *> Binding::EdgeFlagv("glEdgeFlagv");
Function<void, GLenum, GLeglImageOES, const GLint*> Binding::EGLImageTargetTexStorageEXT("glEGLImageTargetTexStorageEXT");
Function<void, GLuint, GLeglImageOES, const GLint*> Binding::EGLImageTargetTextureStorageEXT("glEGLImageTargetTextureStorageEXT");
Function<void, GLenum, const void *> Binding::ElementPointerAPPLE("glElementPointerAPPLE");
Function<void, GLenum, const void *> Binding::ElementPointerATI("glElementPointerATI");
Function<void, GLenum> Binding::Enable("glEnable");
Function<void, GLenum> Binding::EnableClientState("glEnableClientState");
Function<void, GLenum, GLuint> Binding::EnableClientStateiEXT("glEnableClientStateiEXT");
Function<void, GLenum, GLuint> Binding::EnableClientStateIndexedEXT("glEnableClientStateIndexedEXT");
Function<void, GLenum, GLuint> Binding::Enablei("glEnablei");
Function<void, GLenum, GLuint> Binding::EnableIndexedEXT("glEnableIndexedEXT");
Function<void, GLuint> Binding::EnableVariantClientStateEXT("glEnableVariantClientStateEXT");
Function<void, GLuint, GLuint> Binding::EnableVertexArrayAttrib("glEnableVertexArrayAttrib");
Function<void, GLuint, GLuint> Binding::EnableVertexArrayAttribEXT("glEnableVertexArrayAttribEXT");
Function<void, GLuint, GLenum> Binding::EnableVertexArrayEXT("glEnableVertexArrayEXT");
Function<void, GLuint, GLenum> Binding::EnableVertexAttribAPPLE("glEnableVertexAttribAPPLE");
Function<void, GLuint> Binding::EnableVertexAttribArray("glEnableVertexAttribArray");
Function<void, GLuint> Binding::EnableVertexAttribArrayARB("glEnableVertexAttribArrayARB");
Function<void> Binding::End("glEnd");
Function<void> Binding::EndConditionalRender("glEndConditionalRender");
Function<void> Binding::EndConditionalRenderNV("glEndConditionalRenderNV");
Function<void> Binding::EndConditionalRenderNVX("glEndConditionalRenderNVX");
Function<void> Binding::EndFragmentShaderATI("glEndFragmentShaderATI");
Function<void> Binding::EndList("glEndList");
Function<void> Binding::EndOcclusionQueryNV("glEndOcclusionQueryNV");
Function<void, GLuint> Binding::EndPerfMonitorAMD("glEndPerfMonitorAMD");
Function<void, GLuint> Binding::EndPerfQueryINTEL("glEndPerfQueryINTEL");
Function<void, GLenum> Binding::EndQuery("glEndQuery");
Function<void, GLenum> Binding::EndQueryARB("glEndQueryARB");
Function<void, GLenum, GLuint> Binding::EndQueryIndexed("glEndQueryIndexed");
Function<void> Binding::EndTransformFeedback("glEndTransformFeedback");
Function<void> Binding::EndTransformFeedbackEXT("glEndTransformFeedbackEXT");
Function<void> Binding::EndTransformFeedbackNV("glEndTransformFeedbackNV");
Function<void> Binding::EndVertexShaderEXT("glEndVertexShaderEXT");
Function<void, GLuint> Binding::EndVideoCaptureNV("glEndVideoCaptureNV");
Function<void, GLdouble> Binding::EvalCoord1d("glEvalCoord1d");
Function<void, const GLdouble *> Binding::EvalCoord1dv("glEvalCoord1dv");
Function<void, GLfloat> Binding::EvalCoord1f("glEvalCoord1f");
Function<void, const GLfloat *> Binding::EvalCoord1fv("glEvalCoord1fv");
Function<void, GLfixed> Binding::EvalCoord1xOES("glEvalCoord1xOES");
Function<void, const GLfixed *> Binding::EvalCoord1xvOES("glEvalCoord1xvOES");
Function<void, GLdouble, GLdouble> Binding::EvalCoord2d("glEvalCoord2d");
Function<void, const GLdouble *> Binding::EvalCoord2dv("glEvalCoord2dv");
Function<void, GLfloat, GLfloat> Binding::EvalCoord2f("glEvalCoord2f");
Function<void, const GLfloat *> Binding::EvalCoord2fv("glEvalCoord2fv");
Function<void, GLfixed, GLfixed> Binding::EvalCoord2xOES("glEvalCoord2xOES");
Function<void, const GLfixed *> Binding::EvalCoord2xvOES("glEvalCoord2xvOES");
Function<void, GLenum, GLenum> Binding::EvalMapsNV("glEvalMapsNV");
Function<void, GLenum, GLint, GLint> Binding::EvalMesh1("glEvalMesh1");
Function<void, GLenum, GLint, GLint, GLint, GLint> Binding::EvalMesh2("glEvalMesh2");
Function<void, GLint> Binding::EvalPoint1("glEvalPoint1");
Function<void, GLint, GLint> Binding::EvalPoint2("glEvalPoint2");
Function<void> Binding::EvaluateDepthValuesARB("glEvaluateDepthValuesARB");
Function<void, GLenum, GLuint, const GLfloat *> Binding::ExecuteProgramNV("glExecuteProgramNV");
Function<void, GLuint, GLuint, GLuint> Binding::ExtractComponentEXT("glExtractComponentEXT");
} // namespace glbinding | mit |
bhlzlx/ogre | Components/Terrain/src/OgreTerrain.cpp | 145401 | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreTerrain.h"
#include "OgreTerrainQuadTreeNode.h"
#include "OgreStreamSerialiser.h"
#include "OgreMath.h"
#include "OgreImage.h"
#include "OgrePixelFormat.h"
#include "OgreSceneManager.h"
#include "OgreSceneNode.h"
#include "OgreException.h"
#include "OgreBitwise.h"
#include "OgreStringConverter.h"
#include "OgreViewport.h"
#include "OgreLogManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreTextureManager.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreRay.h"
#include "OgrePlane.h"
#include "OgreTerrainMaterialGeneratorA.h"
#include "OgreMaterialManager.h"
#include "OgreHardwareBufferManager.h"
#include "OgreDeflate.h"
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
// we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing
# pragma warning (disable : 4244)
#endif
namespace Ogre
{
//---------------------------------------------------------------------
const uint32 Terrain::TERRAIN_CHUNK_ID = StreamSerialiser::makeIdentifier("TERR");
const uint16 Terrain::TERRAIN_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINLAYERDECLARATION_CHUNK_ID = StreamSerialiser::makeIdentifier("TDCL");
const uint16 Terrain::TERRAINLAYERDECLARATION_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINLAYERSAMPLER_CHUNK_ID = StreamSerialiser::makeIdentifier("TSAM");;
const uint16 Terrain::TERRAINLAYERSAMPLER_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINLAYERSAMPLERELEMENT_CHUNK_ID = StreamSerialiser::makeIdentifier("TSEL");;
const uint16 Terrain::TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINLAYERINSTANCE_CHUNK_ID = StreamSerialiser::makeIdentifier("TLIN");;
const uint16 Terrain::TERRAINLAYERINSTANCE_CHUNK_VERSION = 1;
const uint32 Terrain::TERRAINDERIVEDDATA_CHUNK_ID = StreamSerialiser::makeIdentifier("TDDA");;
const uint16 Terrain::TERRAINDERIVEDDATA_CHUNK_VERSION = 1;
// since 129^2 is the greatest power we can address in 16-bit index
const uint16 Terrain::TERRAIN_MAX_BATCH_SIZE = 129;
const uint16 Terrain::WORKQUEUE_DERIVED_DATA_REQUEST = 1;
const size_t Terrain::LOD_MORPH_CUSTOM_PARAM = 1001;
const uint8 Terrain::DERIVED_DATA_DELTAS = 1;
const uint8 Terrain::DERIVED_DATA_NORMALS = 2;
const uint8 Terrain::DERIVED_DATA_LIGHTMAP = 4;
// This MUST match the bitwise OR of all the types above with no extra bits!
const uint8 Terrain::DERIVED_DATA_ALL = 7;
//-----------------------------------------------------------------------
template<> TerrainGlobalOptions* Singleton<TerrainGlobalOptions>::msSingleton = 0;
TerrainGlobalOptions* TerrainGlobalOptions::getSingletonPtr(void)
{
return msSingleton;
}
TerrainGlobalOptions& TerrainGlobalOptions::getSingleton(void)
{
assert( msSingleton ); return ( *msSingleton );
}
//---------------------------------------------------------------------
TerrainGlobalOptions::TerrainGlobalOptions()
: mSkirtSize(30)
, mLightMapDir(Vector3(1, -1, 0).normalisedCopy())
, mCastsShadows(false)
, mMaxPixelError(3.0)
, mRenderQueueGroup(RENDER_QUEUE_MAIN)
, mVisibilityFlags(0xFFFFFFFF)
, mQueryFlags(0xFFFFFFFF)
, mUseRayBoxDistanceCalculation(false)
, mLayerBlendMapSize(1024)
, mDefaultLayerTextureWorldSize(10)
, mDefaultGlobalColourMapSize(1024)
, mLightmapSize(1024)
, mCompositeMapSize(1024)
, mCompositeMapAmbient(ColourValue::White)
, mCompositeMapDiffuse(ColourValue::White)
, mCompositeMapDistance(4000)
, mResourceGroup(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)
, mUseVertexCompressionWhenAvailable(true)
{
}
//---------------------------------------------------------------------
void TerrainGlobalOptions::setDefaultMaterialGenerator(TerrainMaterialGeneratorPtr gen)
{
mDefaultMaterialGenerator = gen;
}
//---------------------------------------------------------------------
TerrainMaterialGeneratorPtr TerrainGlobalOptions::getDefaultMaterialGenerator()
{
if (mDefaultMaterialGenerator.isNull())
{
// default
mDefaultMaterialGenerator.bind(OGRE_NEW TerrainMaterialGeneratorA());
}
return mDefaultMaterialGenerator;
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
NameGenerator Terrain::msBlendTextureGenerator = NameGenerator("TerrBlend");
//---------------------------------------------------------------------
Terrain::Terrain(SceneManager* sm)
: mSceneMgr(sm)
, mResourceGroup(StringUtil::BLANK)
, mIsLoaded(false)
, mModified(false)
, mHeightDataModified(false)
, mHeightData(0)
, mDeltaData(0)
, mPos(Vector3::ZERO)
, mQuadTree(0)
, mNumLodLevels(0)
, mNumLodLevelsPerLeafNode(0)
, mTreeDepth(0)
, mDirtyGeometryRect(0, 0, 0, 0)
, mDirtyDerivedDataRect(0, 0, 0, 0)
, mDirtyGeometryRectForNeighbours(0, 0, 0, 0)
, mDirtyLightmapFromNeighboursRect(0, 0, 0, 0)
, mDerivedDataUpdateInProgress(false)
, mDerivedUpdatePendingMask(0)
, mMaterialGenerationCount(0)
, mMaterialDirty(false)
, mMaterialParamsDirty(false)
, mGlobalColourMapSize(0)
, mGlobalColourMapEnabled(false)
, mCpuColourMapStorage(0)
, mCpuLightmapStorage(0)
, mCpuCompositeMapStorage(0)
, mCompositeMapDirtyRect(0, 0, 0, 0)
, mCompositeMapUpdateCountdown(0)
, mLastMillis(0)
, mCompositeMapDirtyRectLightmapUpdate(false)
, mLodMorphRequired(false)
, mNormalMapRequired(false)
, mLightMapRequired(false)
, mLightMapShadowsOnly(true)
, mCompositeMapRequired(false)
, mCpuTerrainNormalMap(0)
, mLastLODCamera(0)
, mLastLODFrame(0)
, mLastViewportHeight(0)
, mCustomGpuBufferAllocator(0)
{
mRootNode = sm->getRootSceneNode()->createChildSceneNode();
sm->addListener(this);
WorkQueue* wq = Root::getSingleton().getWorkQueue();
mWorkQueueChannel = wq->getChannel("Ogre/Terrain");
wq->addRequestHandler(mWorkQueueChannel, this);
wq->addResponseHandler(mWorkQueueChannel, this);
// generate a material name, it's important for the terrain material
// name to be consistent & unique no matter what generator is being used
// so use our own pointer as identifier, use FashHash rather than just casting
// the pointer to a long so we support 64-bit pointers
Terrain* pTerrain = this;
mMaterialName = "OgreTerrain/" + StringConverter::toString(FastHash((const char*)&pTerrain, sizeof(Terrain*)));
memset(mNeighbours, 0, sizeof(Terrain*) * NEIGHBOUR_COUNT);
}
//---------------------------------------------------------------------
Terrain::~Terrain()
{
mDerivedUpdatePendingMask = 0;
waitForDerivedProcesses();
WorkQueue* wq = Root::getSingleton().getWorkQueue();
wq->removeRequestHandler(mWorkQueueChannel, this);
wq->removeResponseHandler(mWorkQueueChannel, this);
freeTemporaryResources();
freeGPUResources();
freeCPUResources();
if (mSceneMgr)
{
mSceneMgr->destroySceneNode(mRootNode);
mSceneMgr->removeListener(this);
}
}
//---------------------------------------------------------------------
const AxisAlignedBox& Terrain::getAABB() const
{
if (!mQuadTree)
return AxisAlignedBox::BOX_NULL;
else
return mQuadTree->getAABB();
}
//---------------------------------------------------------------------
AxisAlignedBox Terrain::getWorldAABB() const
{
Matrix4 m = Matrix4::IDENTITY;
m.setTrans(getPosition());
AxisAlignedBox ret = getAABB();
ret.transformAffine(m);
return ret;
}
//---------------------------------------------------------------------
Real Terrain::getMinHeight() const
{
if (!mQuadTree)
return 0;
else
return mQuadTree->getMinHeight();
}
//---------------------------------------------------------------------
Real Terrain::getMaxHeight() const
{
if (!mQuadTree)
return 0;
else
return mQuadTree->getMaxHeight();
}
//---------------------------------------------------------------------
Real Terrain::getBoundingRadius() const
{
if (!mQuadTree)
return 0;
else
return mQuadTree->getBoundingRadius();
}
//---------------------------------------------------------------------
void Terrain::save(const String& filename)
{
DataStreamPtr stream = Root::getSingleton().createFileStream(filename, _getDerivedResourceGroup(), true);
// Compress
DataStreamPtr compressStream(OGRE_NEW DeflateStream(filename, stream));
StreamSerialiser ser(compressStream);
save(ser);
}
//---------------------------------------------------------------------
void Terrain::save(StreamSerialiser& stream)
{
// wait for any queued processes to finish
waitForDerivedProcesses();
if (mHeightDataModified)
{
// When modifying, for efficiency we only increase the max deltas at each LOD,
// we never reduce them (since that would require re-examining more samples)
// Since we now save this data in the file though, we need to make sure we've
// calculated the optimal
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
calculateHeightDeltas(rect);
finaliseHeightDeltas(rect, false);
}
stream.writeChunkBegin(TERRAIN_CHUNK_ID, TERRAIN_CHUNK_VERSION);
uint8 align = (uint8)mAlign;
stream.write(&align);
stream.write(&mSize);
stream.write(&mWorldSize);
stream.write(&mMaxBatchSize);
stream.write(&mMinBatchSize);
stream.write(&mPos);
stream.write(mHeightData, mSize * mSize);
writeLayerDeclaration(mLayerDecl, stream);
// Layers
checkLayers(false);
uint8 numLayers = (uint8)mLayers.size();
writeLayerInstanceList(mLayers, stream);
// Packed layer blend data
if(!mCpuBlendMapStorage.empty())
{
// save from CPU data if it's there, it means GPU data was never created
stream.write(&mLayerBlendMapSize);
// load packed CPU data
int numBlendTex = getBlendTextureCount(numLayers);
for (int i = 0; i < numBlendTex; ++i)
{
PixelFormat fmt = getBlendTextureFormat(i, numLayers);
size_t channels = PixelUtil::getNumElemBytes(fmt);
size_t dataSz = channels * mLayerBlendMapSize * mLayerBlendMapSize;
uint8* pData = mCpuBlendMapStorage[i];
stream.write(pData, dataSz);
}
}
else
{
if (mLayerBlendMapSize != mLayerBlendMapSizeActual)
{
LogManager::getSingleton().stream() <<
"WARNING: blend maps were requested at a size larger than was supported "
"on this hardware, which means the quality has been degraded";
}
stream.write(&mLayerBlendMapSizeActual);
uint8* tmpData = (uint8*)OGRE_MALLOC(mLayerBlendMapSizeActual * mLayerBlendMapSizeActual * 4, MEMCATEGORY_GENERAL);
uint8 texIndex = 0;
for (TexturePtrList::iterator i = mBlendTextureList.begin(); i != mBlendTextureList.end(); ++i, ++texIndex)
{
// Must blit back in CPU format!
PixelFormat cpuFormat = getBlendTextureFormat(texIndex, getLayerCount());
PixelBox dst(mLayerBlendMapSizeActual, mLayerBlendMapSizeActual, 1, cpuFormat, tmpData);
(*i)->getBuffer()->blitToMemory(dst);
size_t dataSz = PixelUtil::getNumElemBytes((*i)->getFormat()) *
mLayerBlendMapSizeActual * mLayerBlendMapSizeActual;
stream.write(tmpData, dataSz);
}
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
// other data
// normals
stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
String normalDataType("normalmap");
stream.write(&normalDataType);
stream.write(&mSize);
if (mCpuTerrainNormalMap)
{
// save from CPU data if it's there, it means GPU data was never created
stream.write((uint8*)mCpuTerrainNormalMap->data, mSize * mSize * 3);
}
else
{
uint8* tmpData = (uint8*)OGRE_MALLOC(mSize * mSize * 3, MEMCATEGORY_GENERAL);
PixelBox dst(mSize, mSize, 1, PF_BYTE_RGB, tmpData);
mTerrainNormalMap->getBuffer()->blitToMemory(dst);
stream.write(tmpData, mSize * mSize * 3);
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
// colourmap
if (mGlobalColourMapEnabled)
{
stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
String colourDataType("colourmap");
stream.write(&colourDataType);
stream.write(&mGlobalColourMapSize);
if (mCpuColourMapStorage)
{
// save from CPU data if it's there, it means GPU data was never created
stream.write(mCpuColourMapStorage, mGlobalColourMapSize * mGlobalColourMapSize * 3);
}
else
{
uint8* tmpData = (uint8*)OGRE_MALLOC(mGlobalColourMapSize * mGlobalColourMapSize * 3, MEMCATEGORY_GENERAL);
PixelBox dst(mGlobalColourMapSize, mGlobalColourMapSize, 1, PF_BYTE_RGB, tmpData);
mColourMap->getBuffer()->blitToMemory(dst);
stream.write(tmpData, mGlobalColourMapSize * mGlobalColourMapSize * 3);
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
}
// lightmap
if (mLightMapRequired)
{
stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
String lightmapDataType("lightmap");
stream.write(&lightmapDataType);
stream.write(&mLightmapSize);
if (mCpuLightmapStorage)
{
// save from CPU data if it's there, it means GPU data was never created
stream.write(mCpuLightmapStorage, mLightmapSize * mLightmapSize);
}
else
{
uint8* tmpData = (uint8*)OGRE_MALLOC(mLightmapSize * mLightmapSize, MEMCATEGORY_GENERAL);
PixelBox dst(mLightmapSize, mLightmapSize, 1, PF_L8, tmpData);
mLightmap->getBuffer()->blitToMemory(dst);
stream.write(tmpData, mLightmapSize * mLightmapSize);
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
}
// composite map
if (mCompositeMapRequired)
{
stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
String compositeMapDataType("compositemap");
stream.write(&compositeMapDataType);
stream.write(&mCompositeMapSize);
if (mCpuCompositeMapStorage)
{
// save from CPU data if it's there, it means GPU data was never created
stream.write(mCpuCompositeMapStorage, mCompositeMapSize * mCompositeMapSize * 4);
}
else
{
// composite map is 4 channel, 3x diffuse, 1x specular mask
uint8* tmpData = (uint8*)OGRE_MALLOC(mCompositeMapSize * mCompositeMapSize * 4, MEMCATEGORY_GENERAL);
PixelBox dst(mCompositeMapSize, mCompositeMapSize, 1, PF_BYTE_RGBA, tmpData);
mCompositeMap->getBuffer()->blitToMemory(dst);
stream.write(tmpData, mCompositeMapSize * mCompositeMapSize * 4);
OGRE_FREE(tmpData, MEMCATEGORY_GENERAL);
}
stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
}
// write deltas
stream.write(mDeltaData, mSize * mSize);
// write the quadtree
mQuadTree->save(stream);
stream.writeChunkEnd(TERRAIN_CHUNK_ID);
mModified = false;
mHeightDataModified = false;
}
//---------------------------------------------------------------------
void Terrain::writeLayerDeclaration(const TerrainLayerDeclaration& decl, StreamSerialiser& stream)
{
// Layer declaration
stream.writeChunkBegin(TERRAINLAYERDECLARATION_CHUNK_ID, TERRAINLAYERDECLARATION_CHUNK_VERSION);
// samplers
uint8 numSamplers = (uint8)decl.samplers.size();
stream.write(&numSamplers);
for (TerrainLayerSamplerList::const_iterator i = decl.samplers.begin();
i != decl.samplers.end(); ++i)
{
const TerrainLayerSampler& sampler = *i;
stream.writeChunkBegin(TERRAINLAYERSAMPLER_CHUNK_ID, TERRAINLAYERSAMPLER_CHUNK_VERSION);
stream.write(&sampler.alias);
uint8 pixFmt = (uint8)sampler.format;
stream.write(&pixFmt);
stream.writeChunkEnd(TERRAINLAYERSAMPLER_CHUNK_ID);
}
// elements
uint8 numElems = (uint8)decl.elements.size();
stream.write(&numElems);
for (TerrainLayerSamplerElementList::const_iterator i = decl.elements.begin();
i != decl.elements.end(); ++i)
{
const TerrainLayerSamplerElement& elem= *i;
stream.writeChunkBegin(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID, TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION);
stream.write(&elem.source);
uint8 sem = (uint8)elem.semantic;
stream.write(&sem);
stream.write(&elem.elementStart);
stream.write(&elem.elementCount);
stream.writeChunkEnd(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID);
}
stream.writeChunkEnd(TERRAINLAYERDECLARATION_CHUNK_ID);
}
//---------------------------------------------------------------------
bool Terrain::readLayerDeclaration(StreamSerialiser& stream, TerrainLayerDeclaration& targetdecl)
{
if (!stream.readChunkBegin(TERRAINLAYERDECLARATION_CHUNK_ID, TERRAINLAYERDECLARATION_CHUNK_VERSION))
return false;
// samplers
uint8 numSamplers;
stream.read(&numSamplers);
targetdecl.samplers.resize(numSamplers);
for (uint8 s = 0; s < numSamplers; ++s)
{
if (!stream.readChunkBegin(TERRAINLAYERSAMPLER_CHUNK_ID, TERRAINLAYERSAMPLER_CHUNK_VERSION))
return false;
stream.read(&(targetdecl.samplers[s].alias));
uint8 pixFmt;
stream.read(&pixFmt);
targetdecl.samplers[s].format = (PixelFormat)pixFmt;
stream.readChunkEnd(TERRAINLAYERSAMPLER_CHUNK_ID);
}
// elements
uint8 numElems;
stream.read(&numElems);
targetdecl.elements.resize(numElems);
for (uint8 e = 0; e < numElems; ++e)
{
if (!stream.readChunkBegin(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID, TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION))
return false;
stream.read(&(targetdecl.elements[e].source));
uint8 sem;
stream.read(&sem);
targetdecl.elements[e].semantic = (TerrainLayerSamplerSemantic)sem;
stream.read(&(targetdecl.elements[e].elementStart));
stream.read(&(targetdecl.elements[e].elementCount));
stream.readChunkEnd(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID);
}
stream.readChunkEnd(TERRAINLAYERDECLARATION_CHUNK_ID);
return true;
}
//---------------------------------------------------------------------
void Terrain::writeLayerInstanceList(const Terrain::LayerInstanceList& layers, StreamSerialiser& stream)
{
uint8 numLayers = (uint8)layers.size();
stream.write(&numLayers);
for (LayerInstanceList::const_iterator i = layers.begin(); i != layers.end(); ++i)
{
const LayerInstance& inst = *i;
stream.writeChunkBegin(TERRAINLAYERINSTANCE_CHUNK_ID, TERRAINLAYERINSTANCE_CHUNK_VERSION);
stream.write(&inst.worldSize);
for (StringVector::const_iterator t = inst.textureNames.begin();
t != inst.textureNames.end(); ++t)
{
stream.write(&(*t));
}
stream.writeChunkEnd(TERRAINLAYERINSTANCE_CHUNK_ID);
}
}
//---------------------------------------------------------------------
bool Terrain::readLayerInstanceList(StreamSerialiser& stream, size_t numSamplers, Terrain::LayerInstanceList& targetlayers)
{
uint8 numLayers;
stream.read(&numLayers);
targetlayers.resize(numLayers);
for (uint8 l = 0; l < numLayers; ++l)
{
if (!stream.readChunkBegin(TERRAINLAYERINSTANCE_CHUNK_ID, TERRAINLAYERINSTANCE_CHUNK_VERSION))
return false;
stream.read(&targetlayers[l].worldSize);
targetlayers[l].textureNames.resize(numSamplers);
for (size_t t = 0; t < numSamplers; ++t)
{
stream.read(&(targetlayers[l].textureNames[t]));
}
stream.readChunkEnd(TERRAINLAYERINSTANCE_CHUNK_ID);
}
return true;
}
//---------------------------------------------------------------------
const String& Terrain::_getDerivedResourceGroup() const
{
if (mResourceGroup.empty())
return TerrainGlobalOptions::getSingleton().getDefaultResourceGroup();
else
return mResourceGroup;
}
//---------------------------------------------------------------------
bool Terrain::prepare(const String& filename)
{
DataStreamPtr stream = Root::getSingleton().openFileStream(filename,
_getDerivedResourceGroup());
// uncompress
// Note DeflateStream automatically falls back on reading the underlying
// stream direct if it's not actually compressed so this will still work
// with uncompressed streams
DataStreamPtr uncompressStream(OGRE_NEW DeflateStream(filename, stream));
StreamSerialiser ser(uncompressStream);
return prepare(ser);
}
//---------------------------------------------------------------------
bool Terrain::prepare(StreamSerialiser& stream)
{
freeTemporaryResources();
freeCPUResources();
copyGlobalOptions();
if (!stream.readChunkBegin(TERRAIN_CHUNK_ID, TERRAIN_CHUNK_VERSION))
return false;
uint8 align;
stream.read(&align);
mAlign = (Alignment)align;
stream.read(&mSize);
stream.read(&mWorldSize);
stream.read(&mMaxBatchSize);
stream.read(&mMinBatchSize);
stream.read(&mPos);
mRootNode->setPosition(mPos);
updateBaseScale();
determineLodLevels();
size_t numVertices = mSize * mSize;
mHeightData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
stream.read(mHeightData, numVertices);
// Layer declaration
if (!readLayerDeclaration(stream, mLayerDecl))
return false;
checkDeclaration();
// Layers
if (!readLayerInstanceList(stream, mLayerDecl.samplers.size(), mLayers))
return false;
deriveUVMultipliers();
// Packed layer blend data
uint8 numLayers = (uint8)mLayers.size();
stream.read(&mLayerBlendMapSize);
mLayerBlendMapSizeActual = mLayerBlendMapSize; // for now, until we check
// load packed CPU data
int numBlendTex = getBlendTextureCount(numLayers);
for (int i = 0; i < numBlendTex; ++i)
{
PixelFormat fmt = getBlendTextureFormat(i, numLayers);
size_t channels = PixelUtil::getNumElemBytes(fmt);
size_t dataSz = channels * mLayerBlendMapSize * mLayerBlendMapSize;
uint8* pData = (uint8*)OGRE_MALLOC(dataSz, MEMCATEGORY_RESOURCE);
stream.read(pData, dataSz);
mCpuBlendMapStorage.push_back(pData);
}
// derived data
while (!stream.isEndOfChunk(TERRAIN_CHUNK_ID) &&
stream.peekNextChunkID() == TERRAINDERIVEDDATA_CHUNK_ID)
{
stream.readChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION);
// name
String name;
stream.read(&name);
uint16 sz;
stream.read(&sz);
if (name == "normalmap")
{
mNormalMapRequired = true;
uint8* pData = static_cast<uint8*>(OGRE_MALLOC(sz * sz * 3, MEMCATEGORY_GENERAL));
mCpuTerrainNormalMap = OGRE_NEW PixelBox(sz, sz, 1, PF_BYTE_RGB, pData);
stream.read(pData, sz * sz * 3);
}
else if (name == "colourmap")
{
mGlobalColourMapEnabled = true;
mGlobalColourMapSize = sz;
mCpuColourMapStorage = static_cast<uint8*>(OGRE_MALLOC(sz * sz * 3, MEMCATEGORY_GENERAL));
stream.read(mCpuColourMapStorage, sz * sz * 3);
}
else if (name == "lightmap")
{
mLightMapRequired = true;
mLightmapSize = sz;
mCpuLightmapStorage = static_cast<uint8*>(OGRE_MALLOC(sz * sz, MEMCATEGORY_GENERAL));
stream.read(mCpuLightmapStorage, sz * sz);
}
else if (name == "compositemap")
{
mCompositeMapRequired = true;
mCompositeMapSize = sz;
mCpuCompositeMapStorage = static_cast<uint8*>(OGRE_MALLOC(sz * sz * 4, MEMCATEGORY_GENERAL));
stream.read(mCpuCompositeMapStorage, sz * sz * 4);
}
stream.readChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID);
}
// Load delta data
mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
stream.read(mDeltaData, numVertices);
// Create & load quadtree
mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0, 0);
mQuadTree->prepare(stream);
stream.readChunkEnd(TERRAIN_CHUNK_ID);
distributeVertexData();
mModified = false;
mHeightDataModified = false;
return true;
}
//---------------------------------------------------------------------
bool Terrain::prepare(const ImportData& importData)
{
freeTemporaryResources();
freeCPUResources();
copyGlobalOptions();
// validate
if (!(Bitwise::isPO2(importData.terrainSize - 1) && Bitwise::isPO2(importData.minBatchSize - 1)
&& Bitwise::isPO2(importData.maxBatchSize - 1)))
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"terrainSize, minBatchSize and maxBatchSize must all be 2^n + 1",
"Terrain::prepare");
}
if (importData.minBatchSize > importData.maxBatchSize)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"minBatchSize must be less than or equal to maxBatchSize",
"Terrain::prepare");
}
if (importData.maxBatchSize > TERRAIN_MAX_BATCH_SIZE)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"maxBatchSize must be no larger than " +
StringConverter::toString(TERRAIN_MAX_BATCH_SIZE),
"Terrain::prepare");
}
mAlign = importData.terrainAlign;
mSize = importData.terrainSize;
mWorldSize = importData.worldSize;
mLayerDecl = importData.layerDeclaration;
checkDeclaration();
mLayers = importData.layerList;
checkLayers(false);
deriveUVMultipliers();
mMaxBatchSize = importData.maxBatchSize;
mMinBatchSize = importData.minBatchSize;
setPosition(importData.pos);
updateBaseScale();
determineLodLevels();
size_t numVertices = mSize * mSize;
mHeightData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
if (importData.inputFloat)
{
if (Math::RealEqual(importData.inputBias, 0.0) && Math::RealEqual(importData.inputScale, 1.0))
{
// straight copy
memcpy(mHeightData, importData.inputFloat, sizeof(float) * numVertices);
}
else
{
// scale & bias
float* src = importData.inputFloat;
float* dst = mHeightData;
for (size_t i = 0; i < numVertices; ++i)
*dst++ = (*src++ * importData.inputScale) + importData.inputBias;
}
}
else if (importData.inputImage)
{
Image* img = importData.inputImage;
if (img->getWidth() != mSize || img->getHeight() != mSize)
img->resize(mSize, mSize);
// convert image data to floats
// Do this on a row-by-row basis, because we describe the terrain in
// a bottom-up fashion (ie ascending world coords), while Image is top-down
unsigned char* pSrcBase = img->getData();
for (size_t i = 0; i < mSize; ++i)
{
size_t srcy = mSize - i - 1;
unsigned char* pSrc = pSrcBase + srcy * img->getRowSpan();
float* pDst = mHeightData + i * mSize;
PixelUtil::bulkPixelConversion(pSrc, img->getFormat(),
pDst, PF_FLOAT32_R, mSize);
}
if (!Math::RealEqual(importData.inputBias, 0.0) || !Math::RealEqual(importData.inputScale, 1.0))
{
float* pAdj = mHeightData;
for (size_t i = 0; i < numVertices; ++i)
{
*pAdj = (*pAdj * importData.inputScale) + importData.inputBias;
++pAdj;
}
}
}
else
{
// start with flat terrain
if (importData.constantHeight == 0)
memset(mHeightData, 0, sizeof(float) * mSize * mSize);
else
{
float* pFloat = mHeightData;
for (long i = 0 ; i < mSize * mSize; ++i)
*pFloat++ = importData.constantHeight;
}
}
mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
memset(mDeltaData, 0, sizeof(float) * numVertices);
mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0, 0);
mQuadTree->prepare();
// calculate entire terrain
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
calculateHeightDeltas(rect);
finaliseHeightDeltas(rect, true);
distributeVertexData();
// Imported data is treated as modified because it's not saved
mModified = true;
mHeightDataModified = true;
return true;
}
//---------------------------------------------------------------------
void Terrain::copyGlobalOptions()
{
TerrainGlobalOptions& opts = TerrainGlobalOptions::getSingleton();
mSkirtSize = opts.getSkirtSize();
mRenderQueueGroup = opts.getRenderQueueGroup();
mVisibilityFlags = opts.getVisibilityFlags();
mQueryFlags = opts.getQueryFlags();
mLayerBlendMapSize = opts.getLayerBlendMapSize();
mLayerBlendMapSizeActual = mLayerBlendMapSize; // for now, until we check
mLightmapSize = opts.getLightMapSize();
mLightmapSizeActual = mLightmapSize; // for now, until we check
mCompositeMapSize = opts.getCompositeMapSize();
mCompositeMapSizeActual = mCompositeMapSize; // for now, until we check
}
//---------------------------------------------------------------------
void Terrain::determineLodLevels()
{
/* On a leaf-node basis, LOD can vary from maxBatch to minBatch in
number of vertices. After that, nodes will be gathered into parent
nodes with the same number of vertices, but they are combined with
3 of their siblings. In practice, the number of LOD levels overall
is:
LODlevels = log2(size - 1) - log2(minBatch - 1) + 1
TreeDepth = log2((size - 1) / (maxBatch - 1)) + 1
.. it's just that at the max LOD, the terrain is divided into
(size - 1) / (maxBatch - 1) tiles each of maxBatch vertices, and
at the lowest LOD the terrain is made up of one single tile of
minBatch vertices.
Example: size = 257, minBatch = 17, maxBatch = 33
LODlevels = log2(257 - 1) - log2(17 - 1) + 1 = 8 - 4 + 1 = 5
TreeDepth = log2((size - 1) / (maxBatch - 1)) + 1 = 4
LOD list - this assumes everything changes at once, which rarely happens of course
in fact except where groupings must occur, tiles can change independently
LOD 0: 257 vertices, 8 x 33 vertex tiles (tree depth 3)
LOD 1: 129 vertices, 8 x 17 vertex tiles (tree depth 3)
LOD 2: 65 vertices, 4 x 17 vertex tiles (tree depth 2)
LOD 3: 33 vertices, 2 x 17 vertex tiles (tree depth 1)
LOD 4: 17 vertices, 1 x 17 vertex tiles (tree depth 0)
Notice how we only have 2 sizes of index buffer to be concerned about,
17 vertices (per side) or 33. This makes buffer re-use much easier while
still giving the full range of LODs.
*/
mNumLodLevelsPerLeafNode = (uint16) (Math::Log2(mMaxBatchSize - 1.0f) - Math::Log2(mMinBatchSize - 1.0f) + 1.0f);
mNumLodLevels = (uint16) (Math::Log2(mSize - 1.0f) - Math::Log2(mMinBatchSize - 1.0f) + 1.0f);
//mTreeDepth = Math::Log2(mMaxBatchSize - 1) - Math::Log2(mMinBatchSize - 1) + 2;
mTreeDepth = mNumLodLevels - mNumLodLevelsPerLeafNode + 1;
LogManager::getSingleton().stream() << "Terrain created; size=" << mSize
<< " minBatch=" << mMinBatchSize << " maxBatch=" << mMaxBatchSize
<< " treeDepth=" << mTreeDepth << " lodLevels=" << mNumLodLevels
<< " leafLods=" << mNumLodLevelsPerLeafNode;
}
//---------------------------------------------------------------------
void Terrain::distributeVertexData()
{
/* Now we need to figure out how to distribute vertex data. We want to
use 16-bit indexes for compatibility, which means that the maximum patch
size that we can address (even sparsely for lower LODs) is 129x129
(the next one up, 257x257 is too big).
So we need to split the vertex data into chunks of 129. The number of
primary tiles this creates also indicates the point above which in
the node tree that we can no longer merge tiles at lower LODs without
using different vertex data. For example, using the 257x257 input example
above, the vertex data would have to be split in 2 (in each dimension)
in order to fit within the 129x129 range. This data could be shared by
all tree depths from 1 onwards, it's just that LODs 3-1 would sample
the 129x129 data sparsely. LOD 0 would sample all of the vertices.
LOD 4 however, the lowest LOD, could not work with the same vertex data
because it needs to cover the entire terrain. There are 2 choices here:
create another set of vertex data at 17x17 which is only used by LOD 4,
or make LOD 4 occur at tree depth 1 instead (ie still split up, and
rendered as 2x9 along each edge instead.
Since rendering very small batches is not desirable, and the vertex counts
are inherently not going to be large, creating a separate vertex set is
preferable. This will also be more efficient on the vertex cache with
distant terrains.
We probably need a larger example, because in this case only 1 level (LOD 0)
needs to use this separate vertex data. Higher detail terrains will need
it for multiple levels, here's a 2049x2049 example with 65 / 33 batch settings:
LODlevels = log2(2049 - 1) - log2(33 - 1) + 1 = 11 - 5 + 1 = 7
TreeDepth = log2((2049 - 1) / (65 - 1)) + 1 = 6
Number of vertex data splits at most detailed level:
(size - 1) / (TERRAIN_MAX_BATCH_SIZE - 1) = 2048 / 128 = 16
LOD 0: 2049 vertices, 32 x 65 vertex tiles (tree depth 5) vdata 0-15 [129x16]
LOD 1: 1025 vertices, 32 x 33 vertex tiles (tree depth 5) vdata 0-15 [129x16]
LOD 2: 513 vertices, 16 x 33 vertex tiles (tree depth 4) vdata 0-15 [129x16]
LOD 3: 257 vertices, 8 x 33 vertex tiles (tree depth 3) vdata 16-17 [129x2]
LOD 4: 129 vertices, 4 x 33 vertex tiles (tree depth 2) vdata 16-17 [129x2]
LOD 5: 65 vertices, 2 x 33 vertex tiles (tree depth 1) vdata 16-17 [129x2]
LOD 6: 33 vertices, 1 x 33 vertex tiles (tree depth 0) vdata 18 [33]
All the vertex counts are to be squared, they are just along one edge.
So as you can see, we need to have 3 levels of vertex data to satisy this
(admittedly quite extreme) case, and a total of 19 sets of vertex data.
The full detail geometry, which is 16(x16) sets of 129(x129), used by
LODs 0-2. LOD 3 can't use this set because it needs to group across them,
because it has only 8 tiles, so we make another set which satisfies this
at a maximum of 129 vertices per vertex data section. In this case LOD
3 needs 257(x257) total vertices so we still split into 2(x2) sets of 129.
This set is good up to and including LOD 5, but LOD 6 needs a single
contiguous set of vertices, so we make a 33x33 vertex set for it.
In terms of vertex data stored, this means that while our primary data is:
2049^2 = 4198401 vertices
our final stored vertex data is
(16 * 129)^2 + (2 * 129)^2 + 33^2 = 4327749 vertices
That equals a 3% premium, but it's both necessary and worth it for the
reduction in batch count resulting from the grouping. In addition, at
LODs 3 and 6 (or rather tree depth 3 and 0) there is the opportunity
to free up the vertex data used by more detailed LODs, which is
important when dealing with large terrains. For example, if we
freed the (GPU) vertex data for LOD 0-2 in the medium distance,
we would save 98% of the memory overhead for this terrain.
*/
LogManager& logMgr = LogManager::getSingleton();
logMgr.stream(LML_TRIVIAL) << "Terrain::distributeVertexData processing source "
"terrain size of " << mSize;
uint16 depth = mTreeDepth;
uint16 prevdepth = depth;
uint16 currresolution = mSize;
uint16 bakedresolution = mSize;
uint16 targetSplits = (bakedresolution - 1) / (TERRAIN_MAX_BATCH_SIZE - 1);
while(depth-- && targetSplits)
{
uint splits = 1 << depth;
if (splits == targetSplits)
{
logMgr.stream(LML_TRIVIAL) << " Assigning vertex data, resolution="
<< bakedresolution << " startDepth=" << depth << " endDepth=" << prevdepth
<< " splits=" << splits;
// vertex data goes at this level, at bakedresolution
// applies to all lower levels (except those with a closer vertex data)
// determine physical size (as opposed to resolution)
size_t sz = ((bakedresolution-1) / splits) + 1;
mQuadTree->assignVertexData(depth, prevdepth, bakedresolution, sz);
// next set to look for
bakedresolution = ((currresolution - 1) >> 1) + 1;
targetSplits = (bakedresolution - 1) / (TERRAIN_MAX_BATCH_SIZE - 1);
prevdepth = depth;
}
currresolution = ((currresolution - 1) >> 1) + 1;
}
// Always assign vertex data to the top of the tree
if (prevdepth > 0)
{
mQuadTree->assignVertexData(0, 1, bakedresolution, bakedresolution);
logMgr.stream(LML_TRIVIAL) << " Assigning vertex data, resolution: "
<< bakedresolution << " startDepth=0 endDepth=1 splits=1";
}
logMgr.stream(LML_TRIVIAL) << "Terrain::distributeVertexData finished";
}
//---------------------------------------------------------------------
void Terrain::load(const String& filename)
{
if (prepare(filename))
load();
else
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Error while preparing " + filename + ", see log for details",
__FUNCTION__);
}
//---------------------------------------------------------------------
void Terrain::load(StreamSerialiser& stream)
{
if (prepare(stream))
load();
else
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
"Error while preparing from stream, see log for details",
__FUNCTION__);
}
//---------------------------------------------------------------------
void Terrain::load()
{
if (mIsLoaded)
return;
if (mQuadTree)
mQuadTree->load();
checkLayers(true);
createOrDestroyGPUColourMap();
createOrDestroyGPUNormalMap();
createOrDestroyGPULightmap();
createOrDestroyGPUCompositeMap();
mMaterialGenerator->requestOptions(this);
mIsLoaded = true;
}
//---------------------------------------------------------------------
void Terrain::unload()
{
if (!mIsLoaded)
return;
if (mQuadTree)
mQuadTree->unload();
// free own buffers if used, but not custom
mDefaultGpuBufferAllocator.freeAllBuffers();
mIsLoaded = false;
mModified = false;
mHeightDataModified = false;
}
//---------------------------------------------------------------------
void Terrain::unprepare()
{
if (mQuadTree)
mQuadTree->unprepare();
}
//---------------------------------------------------------------------
float* Terrain::getHeightData() const
{
return mHeightData;
}
//---------------------------------------------------------------------
float* Terrain::getHeightData(long x, long y) const
{
assert (x >= 0 && x < mSize && y >= 0 && y < mSize);
return &mHeightData[y * mSize + x];
}
//---------------------------------------------------------------------
float Terrain::getHeightAtPoint(long x, long y) const
{
// clamp
x = std::min(x, (long)mSize - 1L);
x = std::max(x, 0L);
y = std::min(y, (long)mSize - 1L);
y = std::max(y, 0L);
return *getHeightData(x, y);
}
//---------------------------------------------------------------------
void Terrain::setHeightAtPoint(long x, long y, float h)
{
// clamp
x = std::min(x, (long)mSize - 1L);
x = std::max(x, 0L);
y = std::min(y, (long)mSize - 1L);
y = std::max(y, 0L);
*getHeightData(x, y) = h;
Rect rect;
rect.left = x;
rect.right = x+1;
rect.top = y;
rect.bottom = y+1;
dirtyRect(rect);
}
//---------------------------------------------------------------------
float Terrain::getHeightAtTerrainPosition(Real x, Real y)
{
// get left / bottom points (rounded down)
Real factor = (Real)mSize - 1.0f;
Real invFactor = 1.0f / factor;
long startX = static_cast<long>(x * factor);
long startY = static_cast<long>(y * factor);
long endX = startX + 1;
long endY = startY + 1;
// now get points in terrain space (effectively rounding them to boundaries)
// note that we do not clamp! We need a valid plane
Real startXTS = startX * invFactor;
Real startYTS = startY * invFactor;
Real endXTS = endX * invFactor;
Real endYTS = endY * invFactor;
// now clamp
endX = std::min(endX, (long)mSize-1);
endY = std::min(endY, (long)mSize-1);
// get parametric from start coord to next point
Real xParam = (x - startXTS) / invFactor;
Real yParam = (y - startYTS) / invFactor;
/* For even / odd tri strip rows, triangles are this shape:
even odd
3---2 3---2
| / | | \ |
0---1 0---1
*/
// Build all 4 positions in terrain space, using point-sampled height
Vector3 v0 (startXTS, startYTS, getHeightAtPoint(startX, startY));
Vector3 v1 (endXTS, startYTS, getHeightAtPoint(endX, startY));
Vector3 v2 (endXTS, endYTS, getHeightAtPoint(endX, endY));
Vector3 v3 (startXTS, endYTS, getHeightAtPoint(startX, endY));
// define this plane in terrain space
Plane plane;
if (startY % 2)
{
// odd row
bool secondTri = ((1.0 - yParam) > xParam);
if (secondTri)
plane.redefine(v0, v1, v3);
else
plane.redefine(v1, v2, v3);
}
else
{
// even row
bool secondTri = (yParam > xParam);
if (secondTri)
plane.redefine(v0, v2, v3);
else
plane.redefine(v0, v1, v2);
}
// Solve plane equation for z
return (-plane.normal.x * x
-plane.normal.y * y
- plane.d) / plane.normal.z;
}
//---------------------------------------------------------------------
float Terrain::getHeightAtWorldPosition(Real x, Real y, Real z)
{
Vector3 terrPos;
getTerrainPosition(x, y, z, &terrPos);
return getHeightAtTerrainPosition(terrPos.x, terrPos.y);
}
//---------------------------------------------------------------------
float Terrain::getHeightAtWorldPosition(const Vector3& pos)
{
return getHeightAtWorldPosition(pos.x, pos.y, pos.z);
}
//---------------------------------------------------------------------
const float* Terrain::getDeltaData()
{
return mDeltaData;
}
//---------------------------------------------------------------------
const float* Terrain::getDeltaData(long x, long y)
{
assert (x >= 0 && x < mSize && y >= 0 && y < mSize);
return &mDeltaData[y * mSize + x];
}
//---------------------------------------------------------------------
Vector3 Terrain::convertPosition(Space inSpace, const Vector3& inPos, Space outSpace) const
{
Vector3 ret;
convertPosition(inSpace, inPos, outSpace, ret);
return ret;
}
//---------------------------------------------------------------------
Vector3 Terrain::convertDirection(Space inSpace, const Vector3& inDir, Space outSpace) const
{
Vector3 ret;
convertDirection(inSpace, inDir, outSpace, ret);
return ret;
}
//---------------------------------------------------------------------
void Terrain::convertPosition(Space inSpace, const Vector3& inPos, Space outSpace, Vector3& outPos) const
{
convertSpace(inSpace, inPos, outSpace, outPos, true);
}
//---------------------------------------------------------------------
void Terrain::convertDirection(Space inSpace, const Vector3& inDir, Space outSpace, Vector3& outDir) const
{
convertSpace(inSpace, inDir, outSpace, outDir, false);
}
//---------------------------------------------------------------------
void Terrain::convertSpace(Space inSpace, const Vector3& inVec, Space outSpace, Vector3& outVec, bool translation) const
{
Space currSpace = inSpace;
outVec = inVec;
while (currSpace != outSpace)
{
switch(currSpace)
{
case WORLD_SPACE:
// In all cases, transition to local space
if (translation)
outVec -= mPos;
currSpace = LOCAL_SPACE;
break;
case LOCAL_SPACE:
switch(outSpace)
{
case WORLD_SPACE:
if (translation)
outVec += mPos;
currSpace = WORLD_SPACE;
break;
case POINT_SPACE:
case TERRAIN_SPACE:
// go via terrain space
outVec = convertWorldToTerrainAxes(outVec);
if (translation)
{
outVec.x -= mBase; outVec.y -= mBase;
outVec.x /= (mSize - 1) * mScale; outVec.y /= (mSize - 1) * mScale;
}
currSpace = TERRAIN_SPACE;
break;
case LOCAL_SPACE:
default:
break;
};
break;
case TERRAIN_SPACE:
switch(outSpace)
{
case WORLD_SPACE:
case LOCAL_SPACE:
// go via local space
if (translation)
{
outVec.x *= (mSize - 1) * mScale; outVec.y *= (mSize - 1) * mScale;
outVec.x += mBase; outVec.y += mBase;
}
outVec = convertTerrainToWorldAxes(outVec);
currSpace = LOCAL_SPACE;
break;
case POINT_SPACE:
if (translation)
{
outVec.x *= (mSize - 1); outVec.y *= (mSize - 1);
// rounding up/down
// this is why POINT_SPACE is the last on the list, because it loses data
outVec.x = static_cast<Real>(static_cast<int>(outVec.x + 0.5));
outVec.y = static_cast<Real>(static_cast<int>(outVec.y + 0.5));
}
currSpace = POINT_SPACE;
break;
case TERRAIN_SPACE:
default:
break;
};
break;
case POINT_SPACE:
// always go via terrain space
if (translation)
outVec.x /= (mSize - 1); outVec.y /= (mSize - 1);
currSpace = TERRAIN_SPACE;
break;
};
}
}
//---------------------------------------------------------------------
void Terrain::convertWorldToTerrainAxes(Alignment align, const Vector3& worldVec, Vector3* terrainVec)
{
switch (align)
{
case ALIGN_X_Z:
terrainVec->z = worldVec.y;
terrainVec->x = worldVec.x;
terrainVec->y = -worldVec.z;
break;
case ALIGN_Y_Z:
terrainVec->z = worldVec.x;
terrainVec->x = -worldVec.z;
terrainVec->y = worldVec.y;
break;
case ALIGN_X_Y:
*terrainVec = worldVec;
break;
};
}
//---------------------------------------------------------------------
void Terrain::convertTerrainToWorldAxes(Alignment align, const Vector3& terrainVec, Vector3* worldVec)
{
switch (align)
{
case ALIGN_X_Z:
worldVec->x = terrainVec.x;
worldVec->y = terrainVec.z;
worldVec->z = -terrainVec.y;
break;
case ALIGN_Y_Z:
worldVec->x = terrainVec.z;
worldVec->y = terrainVec.y;
worldVec->z = -terrainVec.x;
break;
case ALIGN_X_Y:
*worldVec = terrainVec;
break;
};
}
//---------------------------------------------------------------------
Vector3 Terrain::convertWorldToTerrainAxes(const Vector3& inVec) const
{
Vector3 ret;
convertWorldToTerrainAxes(mAlign, inVec, &ret);
return ret;
}
//---------------------------------------------------------------------
Vector3 Terrain::convertTerrainToWorldAxes(const Vector3& inVec) const
{
Vector3 ret;
convertTerrainToWorldAxes(mAlign, inVec, &ret);
return ret;
}
//---------------------------------------------------------------------
void Terrain::getPoint(long x, long y, Vector3* outpos)
{
getPointAlign(x, y, mAlign, outpos);
}
//---------------------------------------------------------------------
void Terrain::getPoint(long x, long y, float height, Vector3* outpos)
{
getPointAlign(x, y, height, mAlign, outpos);
}
//---------------------------------------------------------------------
void Terrain::getPointAlign(long x, long y, Alignment align, Vector3* outpos)
{
getPointAlign(x, y, *getHeightData(x, y), align, outpos);
}
//---------------------------------------------------------------------
void Terrain::getPointAlign(long x, long y, float height, Alignment align, Vector3* outpos)
{
switch(align)
{
case ALIGN_X_Z:
outpos->y = height;
outpos->x = x * mScale + mBase;
outpos->z = y * -mScale - mBase;
break;
case ALIGN_Y_Z:
outpos->x = height;
outpos->z = x * -mScale - mBase;
outpos->y = y * mScale + mBase;
break;
case ALIGN_X_Y:
outpos->z = height;
outpos->x = x * mScale + mBase;
outpos->y = y * mScale + mBase;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getPointTransform(Matrix4* outXform) const
{
*outXform = Matrix4::ZERO;
switch(mAlign)
{
case ALIGN_X_Z:
//outpos->y = height (z)
(*outXform)[1][2] = 1.0f;
//outpos->x = x * mScale + mBase;
(*outXform)[0][0] = mScale;
(*outXform)[0][3] = mBase;
//outpos->z = y * -mScale - mBase;
(*outXform)[2][1] = -mScale;
(*outXform)[2][3] = -mBase;
break;
case ALIGN_Y_Z:
//outpos->x = height;
(*outXform)[0][2] = 1.0f;
//outpos->z = x * -mScale - mBase;
(*outXform)[2][0] = -mScale;
(*outXform)[2][3] = -mBase;
//outpos->y = y * mScale + mBase;
(*outXform)[1][1] = mScale;
(*outXform)[1][3] = mBase;
break;
case ALIGN_X_Y:
//outpos->z = height;
(*outXform)[2][2] = 1.0f; // strictly already the case, but..
//outpos->x = x * mScale + mBase;
(*outXform)[0][0] = mScale;
(*outXform)[0][3] = mBase;
//outpos->y = y * mScale + mBase;
(*outXform)[1][1] = mScale;
(*outXform)[1][3] = mBase;
break;
};
(*outXform)[3][3] = 1.0f;
}
//---------------------------------------------------------------------
void Terrain::getVector(const Vector3& inVec, Vector3* outVec)
{
getVectorAlign(inVec.x, inVec.y, inVec.z, mAlign, outVec);
}
//---------------------------------------------------------------------
void Terrain::getVector(Real x, Real y, Real z, Vector3* outVec)
{
getVectorAlign(x, y, z, mAlign, outVec);
}
//---------------------------------------------------------------------
void Terrain::getVectorAlign(const Vector3& inVec, Alignment align, Vector3* outVec)
{
getVectorAlign(inVec.x, inVec.y, inVec.z, align, outVec);
}
//---------------------------------------------------------------------
void Terrain::getVectorAlign(Real x, Real y, Real z, Alignment align, Vector3* outVec)
{
switch(align)
{
case ALIGN_X_Z:
outVec->y = z;
outVec->x = x;
outVec->z = -y;
break;
case ALIGN_Y_Z:
outVec->x = z;
outVec->y = y;
outVec->z = -x;
break;
case ALIGN_X_Y:
outVec->x = x;
outVec->y = y;
outVec->z = z;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getPosition(const Vector3& TSpos, Vector3* outWSpos)
{
getPositionAlign(TSpos, mAlign, outWSpos);
}
//---------------------------------------------------------------------
void Terrain::getPosition(Real x, Real y, Real z, Vector3* outWSpos)
{
getPositionAlign(x, y, z, mAlign, outWSpos);
}
//---------------------------------------------------------------------
void Terrain::getTerrainPosition(const Vector3& WSpos, Vector3* outTSpos)
{
getTerrainPositionAlign(WSpos, mAlign, outTSpos);
}
//---------------------------------------------------------------------
void Terrain::getTerrainPosition(Real x, Real y, Real z, Vector3* outTSpos)
{
getTerrainPositionAlign(x, y, z, mAlign, outTSpos);
}
//---------------------------------------------------------------------
void Terrain::getPositionAlign(const Vector3& TSpos, Alignment align, Vector3* outWSpos)
{
getPositionAlign(TSpos.x, TSpos.y, TSpos.z, align, outWSpos);
}
//---------------------------------------------------------------------
void Terrain::getPositionAlign(Real x, Real y, Real z, Alignment align, Vector3* outWSpos)
{
switch(align)
{
case ALIGN_X_Z:
outWSpos->y = z;
outWSpos->x = x * (mSize - 1) * mScale + mBase;
outWSpos->z = y * (mSize - 1) * -mScale - mBase;
break;
case ALIGN_Y_Z:
outWSpos->x = z;
outWSpos->y = y * (mSize - 1) * mScale + mBase;
outWSpos->z = x * (mSize - 1) * -mScale - mBase;
break;
case ALIGN_X_Y:
outWSpos->z = z;
outWSpos->x = x * (mSize - 1) * mScale + mBase;
outWSpos->y = y * (mSize - 1) * mScale + mBase;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getTerrainPositionAlign(const Vector3& WSpos, Alignment align, Vector3* outTSpos)
{
getTerrainPositionAlign(WSpos.x, WSpos.y, WSpos.z, align, outTSpos);
}
//---------------------------------------------------------------------
void Terrain::getTerrainPositionAlign(Real x, Real y, Real z, Alignment align, Vector3* outTSpos)
{
switch(align)
{
case ALIGN_X_Z:
outTSpos->x = (x - mBase - mPos.x) / ((mSize - 1) * mScale);
outTSpos->y = (z + mBase - mPos.z) / ((mSize - 1) * -mScale);
outTSpos->z = y;
break;
case ALIGN_Y_Z:
outTSpos->x = (z - mBase - mPos.z) / ((mSize - 1) * -mScale);
outTSpos->y = (y + mBase - mPos.y) / ((mSize - 1) * mScale);
outTSpos->z = x;
break;
case ALIGN_X_Y:
outTSpos->x = (x - mBase - mPos.x) / ((mSize - 1) * mScale);
outTSpos->y = (y - mBase - mPos.y) / ((mSize - 1) * mScale);
outTSpos->z = z;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getTerrainVector(const Vector3& inVec, Vector3* outVec)
{
getTerrainVectorAlign(inVec.x, inVec.y, inVec.z, mAlign, outVec);
}
//---------------------------------------------------------------------
void Terrain::getTerrainVector(Real x, Real y, Real z, Vector3* outVec)
{
getTerrainVectorAlign(x, y, z, mAlign, outVec);
}
//---------------------------------------------------------------------
void Terrain::getTerrainVectorAlign(const Vector3& inVec, Alignment align, Vector3* outVec)
{
getTerrainVectorAlign(inVec.x, inVec.y, inVec.z, align, outVec);
}
//---------------------------------------------------------------------
void Terrain::getTerrainVectorAlign(Real x, Real y, Real z, Alignment align, Vector3* outVec)
{
switch(align)
{
case ALIGN_X_Z:
outVec->z = y;
outVec->x = x;
outVec->y = -z;
break;
case ALIGN_Y_Z:
outVec->z = x;
outVec->y = y;
outVec->x = -z;
break;
case ALIGN_X_Y:
outVec->x = x;
outVec->y = y;
outVec->z = z;
break;
};
}
//---------------------------------------------------------------------
Terrain::Alignment Terrain::getAlignment() const
{
return mAlign;
}
//---------------------------------------------------------------------
uint16 Terrain::getSize() const
{
return mSize;
}
//---------------------------------------------------------------------
uint16 Terrain::getMaxBatchSize() const
{
return mMaxBatchSize;
}
//---------------------------------------------------------------------
uint16 Terrain::getMinBatchSize() const
{
return mMinBatchSize;
}
//---------------------------------------------------------------------
Real Terrain::getWorldSize() const
{
return mWorldSize;
}
//---------------------------------------------------------------------
Real Terrain::getLayerWorldSize(uint8 index) const
{
if (index < mLayers.size())
{
return mLayers[index].worldSize;
}
else if (!mLayers.empty())
{
return mLayers[0].worldSize;
}
else
{
return TerrainGlobalOptions::getSingleton().getDefaultLayerTextureWorldSize();
}
}
//---------------------------------------------------------------------
void Terrain::setLayerWorldSize(uint8 index, Real size)
{
if (index < mLayers.size())
{
if (index >= mLayerUVMultiplier.size())
mLayerUVMultiplier.resize(index + 1);
mLayers[index].worldSize = size;
mLayerUVMultiplier[index] = mWorldSize / size;
mMaterialParamsDirty = true;
mModified = true;
}
}
//---------------------------------------------------------------------
Real Terrain::getLayerUVMultiplier(uint8 index) const
{
if (index < mLayerUVMultiplier.size())
{
return mLayerUVMultiplier[index];
}
else if (!mLayerUVMultiplier.empty())
{
return mLayerUVMultiplier[0];
}
else
{
// default to tile 100 times
return 100;
}
}
//---------------------------------------------------------------------
void Terrain::deriveUVMultipliers()
{
mLayerUVMultiplier.resize(mLayers.size());
for (size_t i = 0; i < mLayers.size(); ++i)
{
const LayerInstance& inst = mLayers[i];
mLayerUVMultiplier[i] = mWorldSize / inst.worldSize;
}
}
//---------------------------------------------------------------------
const String& Terrain::getLayerTextureName(uint8 layerIndex, uint8 samplerIndex) const
{
if (layerIndex < mLayers.size() && samplerIndex < mLayerDecl.samplers.size())
{
return mLayers[layerIndex].textureNames[samplerIndex];
}
else
{
return StringUtil::BLANK;
}
}
//---------------------------------------------------------------------
void Terrain::setLayerTextureName(uint8 layerIndex, uint8 samplerIndex, const String& textureName)
{
if (layerIndex < mLayers.size() && samplerIndex < mLayerDecl.samplers.size())
{
if (mLayers[layerIndex].textureNames[samplerIndex] != textureName)
{
mLayers[layerIndex].textureNames[samplerIndex] = textureName;
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
}
}
//---------------------------------------------------------------------
void Terrain::setPosition(const Vector3& pos)
{
if (pos != mPos)
{
mPos = pos;
mRootNode->setPosition(pos);
updateBaseScale();
mModified = true;
}
}
//---------------------------------------------------------------------
SceneNode* Terrain::_getRootSceneNode() const
{
return mRootNode;
}
//---------------------------------------------------------------------
void Terrain::updateBaseScale()
{
// centre the terrain on local origin
mBase = -mWorldSize * 0.5;
// scale determines what 1 unit on the grid becomes in world space
mScale = mWorldSize / (Real)(mSize-1);
}
//---------------------------------------------------------------------
void Terrain::dirty()
{
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
dirtyRect(rect);
}
//---------------------------------------------------------------------
void Terrain::dirtyRect(const Rect& rect)
{
mDirtyGeometryRect.merge(rect);
mDirtyGeometryRectForNeighbours.merge(rect);
mDirtyDerivedDataRect.merge(rect);
mCompositeMapDirtyRect.merge(rect);
mModified = true;
mHeightDataModified = true;
}
//---------------------------------------------------------------------
void Terrain::_dirtyCompositeMapRect(const Rect& rect)
{
mCompositeMapDirtyRect.merge(rect);
mModified = true;
}
//---------------------------------------------------------------------
void Terrain::dirtyLightmapRect(const Rect& rect)
{
mDirtyDerivedDataRect.merge(rect);
mModified = true;
}
//---------------------------------------------------------------------
void Terrain::dirtyLightmap()
{
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
dirtyLightmapRect(rect);
}
//---------------------------------------------------------------------
void Terrain::update(bool synchronous)
{
updateGeometry();
updateDerivedData(synchronous);
}
//---------------------------------------------------------------------
void Terrain::updateGeometry()
{
if (!mDirtyGeometryRect.isNull())
{
mQuadTree->updateVertexData(true, false, mDirtyGeometryRect, false);
mDirtyGeometryRect.setNull();
}
// propagate changes
notifyNeighbours();
}
//---------------------------------------------------------------------
void Terrain::updateDerivedData(bool synchronous, uint8 typeMask)
{
if (!mDirtyDerivedDataRect.isNull() || !mDirtyLightmapFromNeighboursRect.isNull())
{
mModified = true;
if (mDerivedDataUpdateInProgress)
{
// Don't launch many updates, instead wait for the other one
// to finish and issue another afterwards.
mDerivedUpdatePendingMask |= typeMask;
}
else
{
updateDerivedDataImpl(mDirtyDerivedDataRect, mDirtyLightmapFromNeighboursRect,
synchronous, typeMask);
mDirtyDerivedDataRect.setNull();
mDirtyLightmapFromNeighboursRect.setNull();
}
}
else
{
// Usually the composite map is updated after the other background
// data is updated (no point doing it beforehand), but if there's
// nothing to update, then we'll do it right now.
updateCompositeMap();
}
}
//---------------------------------------------------------------------
void Terrain::updateDerivedDataImpl(const Rect& rect, const Rect& lightmapExtraRect,
bool synchronous, uint8 typeMask)
{
mDerivedDataUpdateInProgress = true;
mDerivedUpdatePendingMask = 0;
DerivedDataRequest req;
req.terrain = this;
req.dirtyRect = rect;
req.lightmapExtraDirtyRect = lightmapExtraRect;
req.typeMask = typeMask;
if (!mNormalMapRequired)
req.typeMask = req.typeMask & ~DERIVED_DATA_NORMALS;
if (!mLightMapRequired)
req.typeMask = req.typeMask & ~DERIVED_DATA_LIGHTMAP;
Root::getSingleton().getWorkQueue()->addRequest(
mWorkQueueChannel, WORKQUEUE_DERIVED_DATA_REQUEST,
Any(req), 0, synchronous);
}
//---------------------------------------------------------------------
void Terrain::waitForDerivedProcesses()
{
while (mDerivedDataUpdateInProgress)
{
// we need to wait for this to finish
OGRE_THREAD_SLEEP(50);
Root::getSingleton().getWorkQueue()->processResponses();
}
}
//---------------------------------------------------------------------
void Terrain::freeCPUResources()
{
OGRE_FREE(mHeightData, MEMCATEGORY_GEOMETRY);
mHeightData = 0;
OGRE_FREE(mDeltaData, MEMCATEGORY_GEOMETRY);
mDeltaData = 0;
OGRE_DELETE mQuadTree;
mQuadTree = 0;
if (mCpuTerrainNormalMap)
{
OGRE_FREE(mCpuTerrainNormalMap->data, MEMCATEGORY_GENERAL);
OGRE_DELETE mCpuTerrainNormalMap;
mCpuTerrainNormalMap = 0;
}
OGRE_FREE(mCpuColourMapStorage, MEMCATEGORY_GENERAL);
mCpuColourMapStorage = 0;
OGRE_FREE(mCpuLightmapStorage, MEMCATEGORY_GENERAL);
mCpuLightmapStorage = 0;
OGRE_FREE(mCpuCompositeMapStorage, MEMCATEGORY_GENERAL);
mCpuCompositeMapStorage = 0;
}
//---------------------------------------------------------------------
void Terrain::freeGPUResources()
{
// remove textures
TextureManager* tmgr = TextureManager::getSingletonPtr();
if (tmgr)
{
for (TexturePtrList::iterator i = mBlendTextureList.begin(); i != mBlendTextureList.end(); ++i)
{
tmgr->remove((*i)->getHandle());
}
mBlendTextureList.clear();
}
if (!mTerrainNormalMap.isNull())
{
tmgr->remove(mTerrainNormalMap->getHandle());
mTerrainNormalMap.setNull();
}
if (!mColourMap.isNull())
{
tmgr->remove(mColourMap->getHandle());
mColourMap.setNull();
}
if (!mLightmap.isNull())
{
tmgr->remove(mLightmap->getHandle());
mLightmap.setNull();
}
if (!mCompositeMap.isNull())
{
tmgr->remove(mCompositeMap->getHandle());
mCompositeMap.setNull();
}
if (!mMaterial.isNull())
{
MaterialManager::getSingleton().remove(mMaterial->getHandle());
mMaterial.setNull();
}
if (!mCompositeMapMaterial.isNull())
{
MaterialManager::getSingleton().remove(mCompositeMapMaterial->getHandle());
mCompositeMapMaterial.setNull();
}
}
//---------------------------------------------------------------------
Rect Terrain::calculateHeightDeltas(const Rect& rect)
{
Rect clampedRect(rect);
clampedRect.left = std::max(0L, clampedRect.left);
clampedRect.top = std::max(0L, clampedRect.top);
clampedRect.right = std::min((long)mSize, clampedRect.right);
clampedRect.bottom = std::min((long)mSize, clampedRect.bottom);
Rect finalRect(clampedRect);
mQuadTree->preDeltaCalculation(clampedRect);
/// Iterate over target levels,
for (int targetLevel = 1; targetLevel < mNumLodLevels; ++targetLevel)
{
int sourceLevel = targetLevel - 1;
int step = 1 << targetLevel;
// The step of the next higher LOD
// int higherstep = step >> 1;
// need to widen the dirty rectangle since change will affect surrounding
// vertices at lower LOD
Rect widenedRect(rect);
widenedRect.left = std::max(0L, widenedRect.left - step);
widenedRect.top = std::max(0L, widenedRect.top - step);
widenedRect.right = std::min((long)mSize, widenedRect.right + step);
widenedRect.bottom = std::min((long)mSize, widenedRect.bottom + step);
// keep a merge of the widest
finalRect.merge(widenedRect);
// now round the rectangle at this level so that it starts & ends on
// the step boundaries
Rect lodRect(widenedRect);
lodRect.left -= lodRect.left % step;
lodRect.top -= lodRect.top % step;
if (lodRect.right % step)
lodRect.right += step - (lodRect.right % step);
if (lodRect.bottom % step)
lodRect.bottom += step - (lodRect.bottom % step);
for (int j = lodRect.top; j < lodRect.bottom - step; j += step )
{
for (int i = lodRect.left; i < lodRect.right - step; i += step )
{
// Form planes relating to the lower detail tris to be produced
// For even tri strip rows, they are this shape:
// 2---3
// | / |
// 0---1
// For odd tri strip rows, they are this shape:
// 2---3
// | \ |
// 0---1
Vector3 v0, v1, v2, v3;
getPointAlign(i, j, ALIGN_X_Y, &v0);
getPointAlign(i + step, j, ALIGN_X_Y, &v1);
getPointAlign(i, j + step, ALIGN_X_Y, &v2);
getPointAlign(i + step, j + step, ALIGN_X_Y, &v3);
Plane t1, t2;
bool backwardTri = false;
// Odd or even in terms of target level
if ((j / step) % 2 == 0)
{
t1.redefine(v0, v1, v3);
t2.redefine(v0, v3, v2);
}
else
{
t1.redefine(v1, v3, v2);
t2.redefine(v0, v1, v2);
backwardTri = true;
}
// include the bottommost row of vertices if this is the last row
int yubound = (j == (mSize - step)? step : step - 1);
for ( int y = 0; y <= yubound; y++ )
{
// include the rightmost col of vertices if this is the last col
int xubound = (i == (mSize - step)? step : step - 1);
for ( int x = 0; x <= xubound; x++ )
{
int fulldetailx = i + x;
int fulldetaily = j + y;
if ( fulldetailx % step == 0 &&
fulldetaily % step == 0 )
{
// Skip, this one is a vertex at this level
continue;
}
Real ypct = (Real)y / (Real)step;
Real xpct = (Real)x / (Real)step;
//interpolated height
Vector3 actualPos;
getPointAlign(fulldetailx, fulldetaily, ALIGN_X_Y, &actualPos);
Real interp_h;
// Determine which tri we're on
if ((xpct > ypct && !backwardTri) ||
(xpct > (1-ypct) && backwardTri))
{
// Solve for x/z
interp_h =
(-t1.normal.x * actualPos.x
- t1.normal.y * actualPos.y
- t1.d) / t1.normal.z;
}
else
{
// Second tri
interp_h =
(-t2.normal.x * actualPos.x
- t2.normal.y * actualPos.y
- t2.d) / t2.normal.z;
}
Real actual_h = actualPos.z;
Real delta = interp_h - actual_h;
// max(delta) is the worst case scenario at this LOD
// compared to the original heightmap
// tell the quadtree about this
mQuadTree->notifyDelta(fulldetailx, fulldetaily, sourceLevel, delta);
// If this vertex is being removed at this LOD,
// then save the height difference since that's the move
// it will need to make. Vertices to be removed at this LOD
// are halfway between the steps, but exclude those that
// would have been eliminated at earlier levels
int halfStep = step / 2;
if (
((fulldetailx % step) == halfStep && (fulldetaily % halfStep) == 0) ||
((fulldetaily % step) == halfStep && (fulldetailx % halfStep) == 0))
{
// Save height difference
mDeltaData[fulldetailx + (fulldetaily * mSize)] = delta;
}
}
}
} // i
} // j
} // targetLevel
mQuadTree->postDeltaCalculation(clampedRect);
return finalRect;
}
//---------------------------------------------------------------------
void Terrain::finaliseHeightDeltas(const Rect& rect, bool cpuData)
{
Rect clampedRect(rect);
clampedRect.left = std::max(0L, clampedRect.left);
clampedRect.top = std::max(0L, clampedRect.top);
clampedRect.right = std::min((long)mSize, clampedRect.right);
clampedRect.bottom = std::min((long)mSize, clampedRect.bottom);
// min/max information
mQuadTree->finaliseDeltaValues(clampedRect);
// delta vertex data
mQuadTree->updateVertexData(false, true, clampedRect, cpuData);
}
//---------------------------------------------------------------------
uint16 Terrain::getResolutionAtLod(uint16 lodLevel)
{
return ((mSize - 1) >> lodLevel) + 1;
}
//---------------------------------------------------------------------
void Terrain::preFindVisibleObjects(SceneManager* source,
SceneManager::IlluminationRenderStage irs, Viewport* v)
{
// Early-out
if (!mIsLoaded)
return;
// check deferred updates
unsigned long currMillis = Root::getSingleton().getTimer()->getMilliseconds();
unsigned long elapsedMillis = currMillis - mLastMillis;
if (mCompositeMapUpdateCountdown > 0 && elapsedMillis)
{
if (elapsedMillis > mCompositeMapUpdateCountdown)
mCompositeMapUpdateCountdown = 0;
else
mCompositeMapUpdateCountdown -= elapsedMillis;
if (!mCompositeMapUpdateCountdown)
updateCompositeMap();
}
mLastMillis = currMillis;
// only calculate LOD once per LOD camera, per frame, per viewport height
const Camera* lodCamera = v->getCamera()->getLodCamera();
unsigned long frameNum = Root::getSingleton().getNextFrameNumber();
int vpHeight = v->getActualHeight();
if (mLastLODCamera != lodCamera || frameNum != mLastLODFrame
|| mLastViewportHeight != vpHeight)
{
mLastLODCamera = lodCamera;
mLastLODFrame = frameNum;
mLastViewportHeight = vpHeight;
calculateCurrentLod(v);
}
}
//---------------------------------------------------------------------
void Terrain::sceneManagerDestroyed(SceneManager* source)
{
unload();
unprepare();
if (source == mSceneMgr)
mSceneMgr = 0;
}
//---------------------------------------------------------------------
void Terrain::calculateCurrentLod(Viewport* vp)
{
if (mQuadTree)
{
// calculate error terms
const Camera* cam = vp->getCamera()->getLodCamera();
// W. de Boer 2000 calculation
// A = vp_near / abs(vp_top)
// A = 1 / tan(fovy*0.5) (== 1 for fovy=45*2)
Real A = 1.0f / Math::Tan(cam->getFOVy() * 0.5f);
// T = 2 * maxPixelError / vertRes
Real maxPixelError = TerrainGlobalOptions::getSingleton().getMaxPixelError() * cam->_getLodBiasInverse();
Real T = 2.0f * maxPixelError / (Real)vp->getActualHeight();
// CFactor = A / T
Real cFactor = A / T;
mQuadTree->calculateCurrentLod(cam, cFactor);
}
}
//---------------------------------------------------------------------
std::pair<bool, Vector3> Terrain::rayIntersects(const Ray& ray,
bool cascadeToNeighbours /* = false */, Real distanceLimit /* = 0 */)
{
typedef std::pair<bool, Vector3> Result;
// first step: convert the ray to a local vertex space
// we assume terrain to be in the x-z plane, with the [0,0] vertex
// at origin and a plane distance of 1 between vertices.
// This makes calculations easier.
Vector3 rayOrigin = ray.getOrigin() - getPosition();
Vector3 rayDirection = ray.getDirection();
// change alignment
Vector3 tmp;
switch (getAlignment())
{
case ALIGN_X_Y:
std::swap(rayOrigin.y, rayOrigin.z);
std::swap(rayDirection.y, rayDirection.z);
break;
case ALIGN_Y_Z:
// x = z, z = y, y = -x
tmp.x = rayOrigin.z;
tmp.z = rayOrigin.y;
tmp.y = -rayOrigin.x;
rayOrigin = tmp;
tmp.x = rayDirection.z;
tmp.z = rayDirection.y;
tmp.y = -rayDirection.x;
rayDirection = tmp;
break;
case ALIGN_X_Z:
// already in X/Z but values increase in -Z
rayOrigin.z = -rayOrigin.z;
rayDirection.z = -rayDirection.z;
break;
}
// readjust coordinate origin
rayOrigin.x += mWorldSize/2;
rayOrigin.z += mWorldSize/2;
// scale down to vertex level
rayOrigin.x /= mScale;
rayOrigin.z /= mScale;
rayDirection.x /= mScale;
rayDirection.z /= mScale;
rayDirection.normalise();
Ray localRay (rayOrigin, rayDirection);
// test if the ray actually hits the terrain's bounds
Real maxHeight = getMaxHeight();
Real minHeight = getMinHeight();
AxisAlignedBox aabb (Vector3(0, minHeight, 0), Vector3(mSize, maxHeight, mSize));
std::pair<bool, Real> aabbTest = localRay.intersects(aabb);
if (!aabbTest.first)
{
if (cascadeToNeighbours)
{
Terrain* neighbour = raySelectNeighbour(ray, distanceLimit);
if (neighbour)
return neighbour->rayIntersects(ray, cascadeToNeighbours, distanceLimit);
}
return Result(false, Vector3());
}
// get intersection point and move inside
Vector3 cur = localRay.getPoint(aabbTest.second);
// now check every quad the ray touches
int quadX = std::min(std::max(static_cast<int>(cur.x), 0), (int)mSize-2);
int quadZ = std::min(std::max(static_cast<int>(cur.z), 0), (int)mSize-2);
int flipX = (rayDirection.x < 0 ? 0 : 1);
int flipZ = (rayDirection.z < 0 ? 0 : 1);
int xDir = (rayDirection.x < 0 ? -1 : 1);
int zDir = (rayDirection.z < 0 ? -1 : 1);
Result result(true, Vector3::ZERO);
Real dummyHighValue = (Real)mSize * 10000.0f;
while (cur.y >= (minHeight - 1e-3) && cur.y <= (maxHeight + 1e-3))
{
if (quadX < 0 || quadX >= (int)mSize-1 || quadZ < 0 || quadZ >= (int)mSize-1)
break;
result = checkQuadIntersection(quadX, quadZ, localRay);
if (result.first)
break;
// determine next quad to test
Real xDist = Math::RealEqual(rayDirection.x, 0.0) ? dummyHighValue :
(quadX - cur.x + flipX) / rayDirection.x;
Real zDist = Math::RealEqual(rayDirection.z, 0.0) ? dummyHighValue :
(quadZ - cur.z + flipZ) / rayDirection.z;
if (xDist < zDist)
{
quadX += xDir;
cur += rayDirection * xDist;
}
else
{
quadZ += zDir;
cur += rayDirection * zDist;
}
}
if (result.first)
{
// transform the point of intersection back to world space
result.second.x *= mScale;
result.second.z *= mScale;
result.second.x -= mWorldSize/2;
result.second.z -= mWorldSize/2;
switch (getAlignment())
{
case ALIGN_X_Y:
std::swap(result.second.y, result.second.z);
break;
case ALIGN_Y_Z:
// z = x, y = z, x = -y
tmp.x = -rayOrigin.y;
tmp.y = rayOrigin.z;
tmp.z = rayOrigin.x;
rayOrigin = tmp;
break;
case ALIGN_X_Z:
result.second.z = -result.second.z;
break;
}
result.second += getPosition();
}
else if (cascadeToNeighbours)
{
Terrain* neighbour = raySelectNeighbour(ray, distanceLimit);
if (neighbour)
result = neighbour->rayIntersects(ray, cascadeToNeighbours, distanceLimit);
}
return result;
}
//---------------------------------------------------------------------
std::pair<bool, Vector3> Terrain::checkQuadIntersection(int x, int z, const Ray& ray)
{
// build the two planes belonging to the quad's triangles
Vector3 v1 ((Real)x, *getHeightData(x,z), (Real)z);
Vector3 v2 ((Real)x+1, *getHeightData(x+1,z), (Real)z);
Vector3 v3 ((Real)x, *getHeightData(x,z+1), (Real)z+1);
Vector3 v4 ((Real)x+1, *getHeightData(x+1,z+1), (Real)z+1);
Plane p1, p2;
bool oddRow = false;
if (z % 2)
{
/* odd
3---4
| \ |
1---2
*/
p1.redefine(v2, v4, v3);
p2.redefine(v1, v2, v3);
oddRow = true;
}
else
{
/* even
3---4
| / |
1---2
*/
p1.redefine(v1, v2, v4);
p2.redefine(v1, v4, v3);
}
// Test for intersection with the two planes.
// Then test that the intersection points are actually
// still inside the triangle (with a small error margin)
// Also check which triangle it is in
std::pair<bool, Real> planeInt = ray.intersects(p1);
if (planeInt.first)
{
Vector3 where = ray.getPoint(planeInt.second);
Vector3 rel = where - v1;
if (rel.x >= -0.01 && rel.x <= 1.01 && rel.z >= -0.01 && rel.z <= 1.01 // quad bounds
&& ((rel.x >= rel.z && !oddRow) || (rel.x >= (1 - rel.z) && oddRow))) // triangle bounds
return std::pair<bool, Vector3>(true, where);
}
planeInt = ray.intersects(p2);
if (planeInt.first)
{
Vector3 where = ray.getPoint(planeInt.second);
Vector3 rel = where - v1;
if (rel.x >= -0.01 && rel.x <= 1.01 && rel.z >= -0.01 && rel.z <= 1.01 // quad bounds
&& ((rel.x <= rel.z && !oddRow) || (rel.x <= (1 - rel.z) && oddRow))) // triangle bounds
return std::pair<bool, Vector3>(true, where);
}
return std::pair<bool, Vector3>(false, Vector3());
}
//---------------------------------------------------------------------
const MaterialPtr& Terrain::getMaterial() const
{
if (mMaterial.isNull() ||
mMaterialGenerator->getChangeCount() != mMaterialGenerationCount ||
mMaterialDirty)
{
mMaterial = mMaterialGenerator->generate(this);
mMaterial->load();
if (mCompositeMapRequired)
{
mCompositeMapMaterial = mMaterialGenerator->generateForCompositeMap(this);
mCompositeMapMaterial->load();
}
mMaterialGenerationCount = mMaterialGenerator->getChangeCount();
mMaterialDirty = false;
}
if (mMaterialParamsDirty)
{
mMaterialGenerator->updateParams(mMaterial, this);
if(mCompositeMapRequired)
mMaterialGenerator->updateParamsForCompositeMap(mCompositeMapMaterial, this);
mMaterialParamsDirty = false;
}
return mMaterial;
}
//---------------------------------------------------------------------
const MaterialPtr& Terrain::getCompositeMapMaterial() const
{
// both materials updated together since they change at the same time
getMaterial();
return mCompositeMapMaterial;
}
//---------------------------------------------------------------------
void Terrain::checkLayers(bool includeGPUResources)
{
for (LayerInstanceList::iterator it = mLayers.begin(); it != mLayers.end(); ++it)
{
LayerInstance& layer = *it;
// If we're missing sampler entries compared to the declaration, initialise them
for (size_t i = layer.textureNames.size(); i < mLayerDecl.samplers.size(); ++i)
{
layer.textureNames.push_back(StringUtil::BLANK);
}
// if we have too many layers for the declaration, trim them
if (layer.textureNames.size() > mLayerDecl.samplers.size())
{
layer.textureNames.resize(mLayerDecl.samplers.size());
}
}
if (includeGPUResources)
{
createGPUBlendTextures();
createLayerBlendMaps();
}
}
//---------------------------------------------------------------------
void Terrain::checkDeclaration()
{
if (mMaterialGenerator.isNull())
{
mMaterialGenerator = TerrainGlobalOptions::getSingleton().getDefaultMaterialGenerator();
}
if (mLayerDecl.elements.empty())
{
// default the declaration
mLayerDecl = mMaterialGenerator->getLayerDeclaration();
}
}
//---------------------------------------------------------------------
void Terrain::replaceLayer(uint8 index, bool keepBlends, Real worldSize, const StringVector* textureNames)
{
if (getLayerCount() > 0)
{
if (index >= getLayerCount())
index = getLayerCount() - 1;
LayerInstanceList::iterator i = mLayers.begin();
std::advance(i, index);
if (textureNames)
{
(*i).textureNames = *textureNames;
}
// use utility method to update UV scaling
setLayerWorldSize(index, worldSize);
// Delete the blend map if its not the base
if ( !keepBlends && index > 0 )
{
if (mLayerBlendMapList[index-1])
{
delete mLayerBlendMapList[index-1];
mLayerBlendMapList[index-1] = 0;
}
// Reset the layer to black
std::pair<uint8,uint8> layerPair = getLayerBlendTextureIndex(index);
clearGPUBlendChannel( layerPair.first, layerPair.second );
}
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
}
//---------------------------------------------------------------------
void Terrain::addLayer(Real worldSize, const StringVector* textureNames)
{
addLayer(getLayerCount(), worldSize, textureNames);
}
//---------------------------------------------------------------------
void Terrain::addLayer(uint8 index, Real worldSize, const StringVector* textureNames)
{
if (!worldSize)
worldSize = TerrainGlobalOptions::getSingleton().getDefaultLayerTextureWorldSize();
uint8 blendIndex = std::max(index-1,0);
if (index >= getLayerCount())
{
mLayers.push_back(LayerInstance());
index = getLayerCount() - 1;
}
else
{
LayerInstanceList::iterator i = mLayers.begin();
std::advance(i, index);
mLayers.insert(i, LayerInstance());
RealVector::iterator uvi = mLayerUVMultiplier.begin();
std::advance(uvi, index);
mLayerUVMultiplier.insert(uvi, 0.0f);
TerrainLayerBlendMapList::iterator bi = mLayerBlendMapList.begin();
std::advance(bi, blendIndex);
mLayerBlendMapList.insert(bi, static_cast<TerrainLayerBlendMap*>(0));
}
if (textureNames)
{
LayerInstance& inst = mLayers[index];
inst.textureNames = *textureNames;
}
// use utility method to update UV scaling
setLayerWorldSize(index, worldSize);
checkLayers(true);
// Is this an insert into the middle of the layer list?
if (index < getLayerCount() - 1)
{
// Shift all GPU texture channels up one
shiftUpGPUBlendChannels(blendIndex);
// All blend maps above this layer index will need to be recreated since their buffers/channels have changed
deleteBlendMaps(index);
}
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
//---------------------------------------------------------------------
void Terrain::removeLayer(uint8 index)
{
if (index < mLayers.size())
{
uint8 blendIndex = std::max(index-1,0);
// Shift all GPU texture channels down one
shiftDownGPUBlendChannels(blendIndex);
LayerInstanceList::iterator i = mLayers.begin();
std::advance(i, index);
mLayers.erase(i);
RealVector::iterator uvi = mLayerUVMultiplier.begin();
std::advance(uvi, index);
mLayerUVMultiplier.erase(uvi);
if (mLayerBlendMapList.size() > 0)
{
// If they removed the base OR the first layer, we need to erase the first blend map
TerrainLayerBlendMapList::iterator bi = mLayerBlendMapList.begin();
std::advance(bi, blendIndex);
OGRE_DELETE *bi;
mLayerBlendMapList.erase(bi);
// Check to see if a GPU textures can be released
checkLayers(true);
// All blend maps for layers above the erased will need to be recreated since their buffers/channels have changed
deleteBlendMaps(blendIndex);
}
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
}
//---------------------------------------------------------------------
uint8 Terrain::getMaxLayers() const
{
return mMaterialGenerator->getMaxLayers(this);
}
//---------------------------------------------------------------------
TerrainLayerBlendMap* Terrain::getLayerBlendMap(uint8 layerIndex)
{
if (layerIndex == 0 || layerIndex-1 >= (uint8)mLayerBlendMapList.size())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Invalid layer index", "Terrain::getLayerBlendMap");
uint8 idx = layerIndex - 1;
if (!mLayerBlendMapList[idx])
{
if (mBlendTextureList.size() < static_cast<size_t>(idx / 4))
checkLayers(true);
const TexturePtr& tex = mBlendTextureList[idx / 4];
mLayerBlendMapList[idx] = OGRE_NEW TerrainLayerBlendMap(this, layerIndex, tex->getBuffer().getPointer());
}
return mLayerBlendMapList[idx];
}
//---------------------------------------------------------------------
uint8 Terrain::getBlendTextureCount(uint8 numLayers) const
{
return ((numLayers - 1) / 4) + 1;
}
//---------------------------------------------------------------------
uint8 Terrain::getBlendTextureCount() const
{
return (uint8)mBlendTextureList.size();
}
//---------------------------------------------------------------------
PixelFormat Terrain::getBlendTextureFormat(uint8 textureIndex, uint8 numLayers)
{
/*
if (numLayers - 1 - (textureIndex * 4) > 3)
return PF_BYTE_RGBA;
else
return PF_BYTE_RGB;
*/
// Always create RGBA; no point trying to create RGB since all cards pad to 32-bit (XRGB)
// and it makes it harder to expand layer count dynamically if format has to change
return PF_BYTE_RGBA;
}
//---------------------------------------------------------------------
void Terrain::shiftUpGPUBlendChannels(uint8 index)
{
// checkLayers() has been called to make sure the blend textures have been created
assert( mBlendTextureList.size() == getBlendTextureCount(getLayerCount()) );
// Shift all blend channels > index UP one slot, possibly into the next texture
// Example: index = 2
// Before: [1 2 3 4] [5]
// After: [1 2 0 3] [4 5]
uint8 layerIndex = index + 1;
for (uint8 i=getLayerCount()-1; i > layerIndex; --i )
{
std::pair<uint8,uint8> destPair = getLayerBlendTextureIndex(i);
std::pair<uint8,uint8> srcPair = getLayerBlendTextureIndex(i - 1);
copyBlendTextureChannel( srcPair.first, srcPair.second, destPair.first, destPair.second );
}
// Reset the layer to black
std::pair<uint8,uint8> layerPair = getLayerBlendTextureIndex(layerIndex);
clearGPUBlendChannel( layerPair.first, layerPair.second );
}
//---------------------------------------------------------------------
void Terrain::shiftDownGPUBlendChannels(uint8 index)
{
// checkLayers() has been called to make sure the blend textures have been created
assert( mBlendTextureList.size() == getBlendTextureCount(getLayerCount()) );
// Shift all blend channels above layerIndex DOWN one slot, possibly into the previous texture
// Example: index = 2
// Before: [1 2 3 4] [5]
// After: [1 2 4 5] [0]
uint8 layerIndex = index + 1;
for (uint8 i=layerIndex; i < getLayerCount() - 1; ++i )
{
std::pair<uint8,uint8> destPair = getLayerBlendTextureIndex(i);
std::pair<uint8,uint8> srcPair = getLayerBlendTextureIndex(i + 1);
copyBlendTextureChannel( srcPair.first, srcPair.second, destPair.first, destPair.second );
}
// Reset the layer to black
if ( getLayerCount() > 1 )
{
std::pair<uint8,uint8> layerPair = getLayerBlendTextureIndex(getLayerCount() - 1);
clearGPUBlendChannel( layerPair.first, layerPair.second );
}
}
//---------------------------------------------------------------------
void Terrain::copyBlendTextureChannel(uint8 srcIndex, uint8 srcChannel, uint8 destIndex, uint8 destChannel )
{
HardwarePixelBufferSharedPtr srcBuffer = getLayerBlendTexture(srcIndex)->getBuffer();
HardwarePixelBufferSharedPtr destBuffer = getLayerBlendTexture(destIndex)->getBuffer();
unsigned char rgbaShift[4];
Image::Box box(0, 0, destBuffer->getWidth(), destBuffer->getHeight());
uint8* pDestBase = static_cast<uint8*>(destBuffer->lock(box, HardwareBuffer::HBL_NORMAL).data);
PixelUtil::getBitShifts(destBuffer->getFormat(), rgbaShift);
uint8* pDest = pDestBase + rgbaShift[destChannel] / 8;
size_t destInc = PixelUtil::getNumElemBytes(destBuffer->getFormat());
size_t srcInc;
uint8* pSrc;
if ( destBuffer == srcBuffer )
{
pSrc = pDestBase + rgbaShift[srcChannel] / 8;
srcInc = destInc;
}
else
{
pSrc = static_cast<uint8*>(srcBuffer->lock(box, HardwareBuffer::HBL_READ_ONLY).data);
PixelUtil::getBitShifts(srcBuffer->getFormat(), rgbaShift);
pSrc += rgbaShift[srcChannel] / 8;
srcInc = PixelUtil::getNumElemBytes(srcBuffer->getFormat());
}
for (size_t y = box.top; y < box.bottom; ++y)
{
for (size_t x = box.left; x < box.right; ++x)
{
*pDest = *pSrc;
pSrc += srcInc;
pDest += destInc;
}
}
destBuffer->unlock();
if ( destBuffer != srcBuffer )
srcBuffer->unlock();
}
//---------------------------------------------------------------------
void Terrain::clearGPUBlendChannel(uint8 index, uint channel)
{
HardwarePixelBufferSharedPtr buffer = getLayerBlendTexture(index)->getBuffer();
unsigned char rgbaShift[4];
Image::Box box(0, 0, buffer->getWidth(), buffer->getHeight());
uint8* pData = static_cast<uint8*>(buffer->lock(box, HardwareBuffer::HBL_NORMAL).data);
PixelUtil::getBitShifts(buffer->getFormat(), rgbaShift);
pData += rgbaShift[channel] / 8;
size_t inc = PixelUtil::getNumElemBytes(buffer->getFormat());
for (size_t y = box.top; y < box.bottom; ++y)
{
for (size_t x = box.left; x < box.right; ++x)
{
*pData = 0;
pData += inc;
}
}
buffer->unlock();
}
//---------------------------------------------------------------------
void Terrain::createGPUBlendTextures()
{
// Create enough RGBA/RGB textures to cope with blend layers
uint8 numTex = getBlendTextureCount(getLayerCount());
// delete extras
TextureManager* tmgr = TextureManager::getSingletonPtr();
if (!tmgr)
return;
while (mBlendTextureList.size() > numTex)
{
tmgr->remove(mBlendTextureList.back()->getHandle());
mBlendTextureList.pop_back();
}
uint8 currentTex = (uint8)mBlendTextureList.size();
mBlendTextureList.resize(numTex);
// create new textures
for (uint8 i = currentTex; i < numTex; ++i)
{
PixelFormat fmt = getBlendTextureFormat(i, getLayerCount());
// Use TU_STATIC because although we will update this, we won't do it every frame
// in normal circumstances, so we don't want TU_DYNAMIC. Also we will
// read it (if we've cleared local temp areas) so no WRITE_ONLY
mBlendTextureList[i] = TextureManager::getSingleton().createManual(
msBlendTextureGenerator.generate(), _getDerivedResourceGroup(),
TEX_TYPE_2D, mLayerBlendMapSize, mLayerBlendMapSize, 1, 0, fmt, TU_STATIC);
mLayerBlendMapSizeActual = mBlendTextureList[i]->getWidth();
if (mCpuBlendMapStorage.size() > i)
{
// Load blend data
PixelBox src(mLayerBlendMapSize, mLayerBlendMapSize, 1, fmt, mCpuBlendMapStorage[i]);
mBlendTextureList[i]->getBuffer()->blitFromMemory(src);
// release CPU copy, don't need it anymore
OGRE_FREE(mCpuBlendMapStorage[i], MEMCATEGORY_RESOURCE);
}
else
{
// initialise black
Box box(0, 0, mLayerBlendMapSize, mLayerBlendMapSize);
HardwarePixelBufferSharedPtr buf = mBlendTextureList[i]->getBuffer();
uint8* pInit = static_cast<uint8*>(buf->lock(box, HardwarePixelBuffer::HBL_DISCARD).data);
memset(pInit, 0, PixelUtil::getNumElemBytes(fmt) * mLayerBlendMapSize * mLayerBlendMapSize);
buf->unlock();
}
}
mCpuBlendMapStorage.clear();
}
//---------------------------------------------------------------------
void Terrain::createLayerBlendMaps()
{
// delete extra blend layers (affects GPU)
while (mLayerBlendMapList.size() > mLayers.size() - 1)
{
OGRE_DELETE mLayerBlendMapList.back();
mLayerBlendMapList.pop_back();
}
// resize up (initialises to 0, populate as necessary)
if ( mLayers.size() > 1 )
mLayerBlendMapList.resize(mLayers.size() - 1, 0);
}
//---------------------------------------------------------------------
void Terrain::createOrDestroyGPUNormalMap()
{
if (mNormalMapRequired && mTerrainNormalMap.isNull())
{
// create
mTerrainNormalMap = TextureManager::getSingleton().createManual(
mMaterialName + "/nm", _getDerivedResourceGroup(),
TEX_TYPE_2D, mSize, mSize, 1, 0, PF_BYTE_RGB, TU_STATIC);
// Upload loaded normal data if present
if (mCpuTerrainNormalMap)
{
mTerrainNormalMap->getBuffer()->blitFromMemory(*mCpuTerrainNormalMap);
OGRE_FREE(mCpuTerrainNormalMap->data, MEMCATEGORY_GENERAL);
OGRE_DELETE mCpuTerrainNormalMap;
mCpuTerrainNormalMap = 0;
}
}
else if (!mNormalMapRequired && !mTerrainNormalMap.isNull())
{
// destroy
TextureManager::getSingleton().remove(mTerrainNormalMap->getHandle());
mTerrainNormalMap.setNull();
}
}
//---------------------------------------------------------------------
void Terrain::freeTemporaryResources()
{
// CPU blend maps
for (BytePointerList::iterator i = mCpuBlendMapStorage.begin();
i != mCpuBlendMapStorage.end(); ++i)
{
OGRE_FREE(*i, MEMCATEGORY_RESOURCE);
}
mCpuBlendMapStorage.clear();
// Editable structures for blend layers (not needed at runtime, only blend textures are)
deleteBlendMaps(0);
}
//---------------------------------------------------------------------
void Terrain::deleteBlendMaps(uint8 lowIndex)
{
TerrainLayerBlendMapList::iterator i = mLayerBlendMapList.begin();
std::advance(i, lowIndex);
for (; i != mLayerBlendMapList.end(); ++i )
{
OGRE_DELETE *i;
*i = 0;
}
}
//---------------------------------------------------------------------
const TexturePtr& Terrain::getLayerBlendTexture(uint8 index)
{
assert(index < mBlendTextureList.size());
return mBlendTextureList[index];
}
//---------------------------------------------------------------------
std::pair<uint8,uint8> Terrain::getLayerBlendTextureIndex(uint8 layerIndex)
{
assert(layerIndex > 0 && layerIndex < mLayers.size());
uint8 idx = layerIndex - 1;
return std::pair<uint8, uint8>(idx / 4, idx % 4);
}
//---------------------------------------------------------------------
void Terrain::_setNormalMapRequired(bool normalMap)
{
if (normalMap != mNormalMapRequired)
{
mNormalMapRequired = normalMap;
// Check NPOT textures supported. We have to use NPOT textures to map
// texels to vertices directly!
if (!mNormalMapRequired && Root::getSingleton().getRenderSystem()
->getCapabilities()->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))
{
mNormalMapRequired = false;
LogManager::getSingleton().stream(LML_CRITICAL) <<
"Terrain: Ignoring request for normal map generation since "
"non-power-of-two texture support is required.";
}
createOrDestroyGPUNormalMap();
// if we enabled, generate normal maps
if (mNormalMapRequired)
{
// update derived data for whole terrain, but just normals
mDirtyDerivedDataRect.left = mDirtyDerivedDataRect.top = 0;
mDirtyDerivedDataRect.right = mDirtyDerivedDataRect.bottom = mSize;
updateDerivedData(false, DERIVED_DATA_NORMALS);
}
}
}
//---------------------------------------------------------------------
void Terrain::_setLightMapRequired(bool lightMap, bool shadowsOnly)
{
if (lightMap != mLightMapRequired || shadowsOnly != mLightMapShadowsOnly)
{
mLightMapRequired = lightMap;
mLightMapShadowsOnly = shadowsOnly;
createOrDestroyGPULightmap();
// if we enabled, generate light maps
if (mLightMapRequired)
{
// update derived data for whole terrain, but just lightmap
mDirtyDerivedDataRect.left = mDirtyDerivedDataRect.top = 0;
mDirtyDerivedDataRect.right = mDirtyDerivedDataRect.bottom = mSize;
updateDerivedData(false, DERIVED_DATA_LIGHTMAP);
}
}
}
//---------------------------------------------------------------------
void Terrain::_setCompositeMapRequired(bool compositeMap)
{
if (compositeMap != mCompositeMapRequired)
{
mCompositeMapRequired = compositeMap;
createOrDestroyGPUCompositeMap();
// if we enabled, generate composite maps
if (mCompositeMapRequired)
{
mCompositeMapDirtyRect.left = mCompositeMapDirtyRect.top = 0;
mCompositeMapDirtyRect.right = mCompositeMapDirtyRect.bottom = mSize;
updateCompositeMap();
}
}
}
//---------------------------------------------------------------------
bool Terrain::_getUseVertexCompression() const
{
return mMaterialGenerator->isVertexCompressionSupported() &&
TerrainGlobalOptions::getSingleton().getUseVertexCompressionWhenAvailable();
}
//---------------------------------------------------------------------
bool Terrain::canHandleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
{
DerivedDataRequest ddr = any_cast<DerivedDataRequest>(req->getData());
// only deal with own requests
// we do this because if we delete a terrain we want any pending tasks to be discarded
if (ddr.terrain != this)
return false;
else
return RequestHandler::canHandleRequest(req, srcQ);
}
//---------------------------------------------------------------------
bool Terrain::canHandleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
DerivedDataRequest ddreq = any_cast<DerivedDataRequest>(res->getRequest()->getData());
// only deal with own requests
// we do this because if we delete a terrain we want any pending tasks to be discarded
if (ddreq.terrain != this)
return false;
else
return true;
}
//---------------------------------------------------------------------
WorkQueue::Response* Terrain::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
{
// Background thread (maybe)
DerivedDataRequest ddr = any_cast<DerivedDataRequest>(req->getData());
// only deal with own requests; we shouldn't ever get here though
if (ddr.terrain != this)
return 0;
DerivedDataResponse ddres;
ddres.remainingTypeMask = ddr.typeMask & DERIVED_DATA_ALL;
// Do only ONE type of task per background iteration, in order of priority
// this means we return faster, can abort faster and we repeat less redundant calcs
// we don't do this as separate requests, because we only want one background
// task per Terrain instance in flight at once
if (ddr.typeMask & DERIVED_DATA_DELTAS)
{
ddres.deltaUpdateRect = calculateHeightDeltas(ddr.dirtyRect);
ddres.remainingTypeMask &= ~ DERIVED_DATA_DELTAS;
}
else if (ddr.typeMask & DERIVED_DATA_NORMALS)
{
ddres.normalMapBox = calculateNormals(ddr.dirtyRect, ddres.normalUpdateRect);
ddres.remainingTypeMask &= ~ DERIVED_DATA_NORMALS;
}
else if (ddr.typeMask & DERIVED_DATA_LIGHTMAP)
{
ddres.lightMapBox = calculateLightmap(ddr.dirtyRect, ddr.lightmapExtraDirtyRect, ddres.lightmapUpdateRect);
ddres.remainingTypeMask &= ~ DERIVED_DATA_LIGHTMAP;
}
ddres.terrain = ddr.terrain;
WorkQueue::Response* response = OGRE_NEW WorkQueue::Response(req, true, Any(ddres));
return response;
}
//---------------------------------------------------------------------
void Terrain::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
// Main thread
DerivedDataResponse ddres = any_cast<DerivedDataResponse>(res->getData());
DerivedDataRequest ddreq = any_cast<DerivedDataRequest>(res->getRequest()->getData());
// only deal with own requests
if (ddreq.terrain != this)
return;
if ((ddreq.typeMask & DERIVED_DATA_DELTAS) &&
!(ddres.remainingTypeMask & DERIVED_DATA_DELTAS))
finaliseHeightDeltas(ddres.deltaUpdateRect, false);
if ((ddreq.typeMask & DERIVED_DATA_NORMALS) &&
!(ddres.remainingTypeMask & DERIVED_DATA_NORMALS))
{
finaliseNormals(ddres.normalUpdateRect, ddres.normalMapBox);
mCompositeMapDirtyRect.merge(ddreq.dirtyRect);
}
if ((ddreq.typeMask & DERIVED_DATA_LIGHTMAP) &&
!(ddres.remainingTypeMask & DERIVED_DATA_LIGHTMAP))
{
finaliseLightmap(ddres.lightmapUpdateRect, ddres.lightMapBox);
mCompositeMapDirtyRect.merge(ddreq.dirtyRect);
mCompositeMapDirtyRectLightmapUpdate = true;
}
mDerivedDataUpdateInProgress = false;
// Re-trigger another request if there are still things to do, or if
// we had a new request since this one
Rect newRect(0,0,0,0);
if (ddres.remainingTypeMask)
newRect.merge(ddreq.dirtyRect);
if (mDerivedUpdatePendingMask)
{
newRect.merge(mDirtyDerivedDataRect);
mDirtyDerivedDataRect.setNull();
}
Rect newLightmapExtraRect(0,0,0,0);
if (ddres.remainingTypeMask)
newLightmapExtraRect.merge(ddreq.lightmapExtraDirtyRect);
if (mDerivedUpdatePendingMask)
{
newLightmapExtraRect.merge(mDirtyLightmapFromNeighboursRect);
mDirtyLightmapFromNeighboursRect.setNull();
}
uint8 newMask = ddres.remainingTypeMask | mDerivedUpdatePendingMask;
if (newMask)
{
// trigger again
updateDerivedDataImpl(newRect, newLightmapExtraRect, false, newMask);
}
else
{
// we've finished all the background processes
// update the composite map if enabled
if (mCompositeMapRequired)
updateCompositeMap();
}
}
//---------------------------------------------------------------------
uint16 Terrain::getLODLevelWhenVertexEliminated(long x, long y)
{
// gets eliminated by either row or column first
return std::min(getLODLevelWhenVertexEliminated(x), getLODLevelWhenVertexEliminated(y));
}
//---------------------------------------------------------------------
uint16 Terrain::getLODLevelWhenVertexEliminated(long rowOrColulmn)
{
// LOD levels bisect the domain.
// start at the lowest detail
uint16 currentElim = (mSize - 1) / (mMinBatchSize - 1);
// start at a non-exitant LOD index, this applies to the min batch vertices
// which are never eliminated
uint16 currentLod = mNumLodLevels;
while (rowOrColulmn % currentElim)
{
// not on this boundary, look finer
currentElim = currentElim / 2;
--currentLod;
// This will always terminate since (anything % 1 == 0)
}
return currentLod;
}
//---------------------------------------------------------------------
PixelBox* Terrain::calculateNormals(const Rect &rect, Rect& finalRect)
{
// Widen the rectangle by 1 element in all directions since height
// changes affect neighbours normals
Rect widenedRect(
std::max(0L, rect.left - 1L),
std::max(0L, rect.top - 1L),
std::min((long)mSize, rect.right + 1L),
std::min((long)mSize, rect.bottom + 1L)
);
// allocate memory for RGB
uint8* pData = static_cast<uint8*>(
OGRE_MALLOC(widenedRect.width() * widenedRect.height() * 3, MEMCATEGORY_GENERAL));
PixelBox* pixbox = OGRE_NEW PixelBox(widenedRect.width(), widenedRect.height(), 1, PF_BYTE_RGB, pData);
// Evaluate normal like this
// 3---2---1
// | \ | / |
// 4---P---0
// | / | \ |
// 5---6---7
Plane plane;
for (long y = widenedRect.top; y < widenedRect.bottom; ++y)
{
for (long x = widenedRect.left; x < widenedRect.right; ++x)
{
Vector3 cumulativeNormal = Vector3::ZERO;
// Build points to sample
Vector3 centrePoint;
Vector3 adjacentPoints[8];
getPointFromSelfOrNeighbour(x , y, ¢rePoint);
getPointFromSelfOrNeighbour(x+1, y, &adjacentPoints[0]);
getPointFromSelfOrNeighbour(x+1, y+1, &adjacentPoints[1]);
getPointFromSelfOrNeighbour(x, y+1, &adjacentPoints[2]);
getPointFromSelfOrNeighbour(x-1, y+1, &adjacentPoints[3]);
getPointFromSelfOrNeighbour(x-1, y, &adjacentPoints[4]);
getPointFromSelfOrNeighbour(x-1, y-1, &adjacentPoints[5]);
getPointFromSelfOrNeighbour(x, y-1, &adjacentPoints[6]);
getPointFromSelfOrNeighbour(x+1, y-1, &adjacentPoints[7]);
for (int i = 0; i < 8; ++i)
{
plane.redefine(centrePoint, adjacentPoints[i], adjacentPoints[(i+1)%8]);
cumulativeNormal += plane.normal;
}
// normalise & store normal
cumulativeNormal.normalise();
// encode as RGB, object space
// invert the Y to deal with image space
long storeX = x - widenedRect.left;
long storeY = widenedRect.bottom - y - 1;
uint8* pStore = pData + ((storeY * widenedRect.width()) + storeX) * 3;
*pStore++ = static_cast<uint8>((cumulativeNormal.x + 1.0f) * 0.5f * 255.0f);
*pStore++ = static_cast<uint8>((cumulativeNormal.y + 1.0f) * 0.5f * 255.0f);
*pStore++ = static_cast<uint8>((cumulativeNormal.z + 1.0f) * 0.5f * 255.0f);
}
}
finalRect = widenedRect;
return pixbox;
}
//---------------------------------------------------------------------
void Terrain::finaliseNormals(const Ogre::Rect &rect, Ogre::PixelBox *normalsBox)
{
createOrDestroyGPUNormalMap();
// deal with race condition where nm has been disabled while we were working!
if (!mTerrainNormalMap.isNull())
{
// blit the normals into the texture
if (rect.left == 0 && rect.top == 0 && rect.bottom == mSize && rect.right == mSize)
{
mTerrainNormalMap->getBuffer()->blitFromMemory(*normalsBox);
}
else
{
// content of normalsBox is already inverted in Y, but rect is still
// in terrain space for dealing with sub-rect, so invert
Image::Box dstBox;
dstBox.left = rect.left;
dstBox.right = rect.right;
dstBox.top = mSize - rect.bottom;
dstBox.bottom = mSize - rect.top;
mTerrainNormalMap->getBuffer()->blitFromMemory(*normalsBox, dstBox);
}
}
// delete memory
OGRE_FREE(normalsBox->data, MEMCATEGORY_GENERAL);
OGRE_DELETE(normalsBox);
}
//---------------------------------------------------------------------
void Terrain::widenRectByVector(const Vector3& vec, const Rect& inRect, Rect& outRect)
{
widenRectByVector(vec, inRect, getMinHeight(), getMaxHeight(), outRect);
}
//---------------------------------------------------------------------
void Terrain::widenRectByVector(const Vector3& vec, const Rect& inRect,
Real minHeight, Real maxHeight, Rect& outRect)
{
outRect = inRect;
Plane p;
switch(getAlignment())
{
case ALIGN_X_Y:
p.redefine(Vector3::UNIT_Z, Vector3(0, 0, vec.z < 0.0 ? minHeight : maxHeight));
break;
case ALIGN_X_Z:
p.redefine(Vector3::UNIT_Y, Vector3(0, vec.y < 0.0 ? minHeight : maxHeight, 0));
break;
case ALIGN_Y_Z:
p.redefine(Vector3::UNIT_X, Vector3(vec.x < 0.0 ? minHeight : maxHeight, 0, 0));
break;
}
float verticalVal = vec.dotProduct(p.normal);
if (Math::RealEqual(verticalVal, 0.0))
return;
Vector3 corners[4];
Real startHeight = verticalVal < 0.0 ? maxHeight : minHeight;
getPoint(inRect.left, inRect.top, startHeight, &corners[0]);
getPoint(inRect.right-1, inRect.top, startHeight, &corners[1]);
getPoint(inRect.left, inRect.bottom-1, startHeight, &corners[2]);
getPoint(inRect.right-1, inRect.bottom-1, startHeight, &corners[3]);
for (int i = 0; i < 4; ++i)
{
Ray ray(corners[i] + mPos, vec);
std::pair<bool, Real> rayHit = ray.intersects(p);
if(rayHit.first)
{
Vector3 pt = ray.getPoint(rayHit.second);
// convert back to terrain point
Vector3 terrainHitPos;
getTerrainPosition(pt, &terrainHitPos);
// build rectangle which has rounded down & rounded up values
// remember right & bottom are exclusive
Rect mergeRect(
(long)(terrainHitPos.x * (mSize - 1)),
(long)(terrainHitPos.y * (mSize - 1)),
(long)(terrainHitPos.x * (float)(mSize - 1) + 0.5) + 1,
(long)(terrainHitPos.y * (float)(mSize - 1) + 0.5) + 1
);
outRect.merge(mergeRect);
}
}
}
//---------------------------------------------------------------------
PixelBox* Terrain::calculateLightmap(const Rect& rect, const Rect& extraTargetRect, Rect& outFinalRect)
{
// as well as calculating the lighting changes for the area that is
// dirty, we also need to calculate the effect on casting shadow on
// other areas. To do this, we project the dirt rect by the light direction
// onto the minimum height
const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection();
Ogre::Rect widenedRect;
widenRectByVector(lightVec, rect, widenedRect);
// merge in the extra area (e.g. from neighbours)
widenedRect.merge(extraTargetRect);
// widenedRect now contains terrain point space version of the area we
// need to calculate. However, we need to calculate in lightmap image space
float terrainToLightmapScale = (float)mLightmapSizeActual / (float)mSize;
widenedRect.left = (long)(widenedRect.left * terrainToLightmapScale);
widenedRect.right = (long)(widenedRect.right * terrainToLightmapScale);
widenedRect.top = (long)(widenedRect.top * terrainToLightmapScale);
widenedRect.bottom = (long)(widenedRect.bottom * terrainToLightmapScale);
// clamp
widenedRect.left = std::max(0L, widenedRect.left);
widenedRect.top = std::max(0L, widenedRect.top);
widenedRect.right = std::min((long)mLightmapSizeActual, widenedRect.right);
widenedRect.bottom = std::min((long)mLightmapSizeActual, widenedRect.bottom);
outFinalRect = widenedRect;
// allocate memory (L8)
uint8* pData = static_cast<uint8*>(
OGRE_MALLOC(widenedRect.width() * widenedRect.height(), MEMCATEGORY_GENERAL));
PixelBox* pixbox = OGRE_NEW PixelBox(widenedRect.width(), widenedRect.height(), 1, PF_L8, pData);
Real heightPad = (getMaxHeight() - getMinHeight()) * 1.0e-3f;
for (long y = widenedRect.top; y < widenedRect.bottom; ++y)
{
for (long x = widenedRect.left; x < widenedRect.right; ++x)
{
float litVal = 1.0f;
// convert to terrain space (not points, allow this to go between points)
float Tx = (float)x / (float)(mLightmapSizeActual-1);
float Ty = (float)y / (float)(mLightmapSizeActual-1);
// get world space point
// add a little height padding to stop shadowing self
Vector3 wpos = Vector3::ZERO;
getPosition(Tx, Ty, getHeightAtTerrainPosition(Tx, Ty) + heightPad, &wpos);
wpos += getPosition();
// build ray, cast backwards along light direction
Ray ray(wpos, -lightVec);
// Cascade into neighbours when casting, but don't travel further
// than world size
std::pair<bool, Vector3> rayHit = rayIntersects(ray, true, mWorldSize);
if (rayHit.first)
litVal = 0.0f;
// encode as L8
// invert the Y to deal with image space
long storeX = x - widenedRect.left;
long storeY = widenedRect.bottom - y - 1;
uint8* pStore = pData + ((storeY * widenedRect.width()) + storeX);
*pStore = (unsigned char)(litVal * 255.0);
}
}
return pixbox;
}
//---------------------------------------------------------------------
void Terrain::finaliseLightmap(const Rect& rect, PixelBox* lightmapBox)
{
createOrDestroyGPULightmap();
// deal with race condition where lm has been disabled while we were working!
if (!mLightmap.isNull())
{
// blit the normals into the texture
if (rect.left == 0 && rect.top == 0 && rect.bottom == mLightmapSizeActual && rect.right == mLightmapSizeActual)
{
mLightmap->getBuffer()->blitFromMemory(*lightmapBox);
}
else
{
// content of PixelBox is already inverted in Y, but rect is still
// in terrain space for dealing with sub-rect, so invert
Image::Box dstBox;
dstBox.left = rect.left;
dstBox.right = rect.right;
dstBox.top = mLightmapSizeActual - rect.bottom;
dstBox.bottom = mLightmapSizeActual - rect.top;
mLightmap->getBuffer()->blitFromMemory(*lightmapBox, dstBox);
}
}
// delete memory
OGRE_FREE(lightmapBox->data, MEMCATEGORY_GENERAL);
OGRE_DELETE(lightmapBox);
}
//---------------------------------------------------------------------
void Terrain::updateCompositeMap()
{
// All done in the render thread
if (mCompositeMapRequired && !mCompositeMapDirtyRect.isNull())
{
mModified = true;
createOrDestroyGPUCompositeMap();
if (mCompositeMapDirtyRectLightmapUpdate &&
(mCompositeMapDirtyRect.width() < mSize || mCompositeMapDirtyRect.height() < mSize))
{
// widen the dirty rectangle since lighting makes it wider
Rect widenedRect;
widenRectByVector(TerrainGlobalOptions::getSingleton().getLightMapDirection(), mCompositeMapDirtyRect, widenedRect);
// clamp
widenedRect.left = std::max(widenedRect.left, 0L);
widenedRect.top = std::max(widenedRect.top, 0L);
widenedRect.right = std::min(widenedRect.right, (long)mSize);
widenedRect.bottom = std::min(widenedRect.bottom, (long)mSize);
mMaterialGenerator->updateCompositeMap(this, widenedRect);
}
else
mMaterialGenerator->updateCompositeMap(this, mCompositeMapDirtyRect);
mCompositeMapDirtyRectLightmapUpdate = false;
mCompositeMapDirtyRect.setNull();
}
}
//---------------------------------------------------------------------
void Terrain::updateCompositeMapWithDelay(Real delay)
{
mCompositeMapUpdateCountdown = (long)(delay * 1000);
}
//---------------------------------------------------------------------
uint8 Terrain::getBlendTextureIndex(uint8 layerIndex) const
{
if (layerIndex == 0 || layerIndex-1 >= (uint8)mLayerBlendMapList.size())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Invalid layer index", "Terrain::getBlendTextureIndex");
return (layerIndex - 1) % 4;
}
//---------------------------------------------------------------------
const String& Terrain::getBlendTextureName(uint8 textureIndex) const
{
if (textureIndex >= (uint8)mBlendTextureList.size())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Invalid texture index", "Terrain::getBlendTextureName");
return mBlendTextureList[textureIndex]->getName();
}
//---------------------------------------------------------------------
void Terrain::setGlobalColourMapEnabled(bool enabled, uint16 sz)
{
if (!sz)
sz = TerrainGlobalOptions::getSingleton().getDefaultGlobalColourMapSize();
if (enabled != mGlobalColourMapEnabled ||
(enabled && mGlobalColourMapSize != sz))
{
mGlobalColourMapEnabled = enabled;
mGlobalColourMapSize = sz;
createOrDestroyGPUColourMap();
mMaterialDirty = true;
mMaterialParamsDirty = true;
mModified = true;
}
}
//---------------------------------------------------------------------
void Terrain::createOrDestroyGPUColourMap()
{
if (mGlobalColourMapEnabled && mColourMap.isNull())
{
// create
mColourMap = TextureManager::getSingleton().createManual(
mMaterialName + "/cm", _getDerivedResourceGroup(),
TEX_TYPE_2D, mGlobalColourMapSize, mGlobalColourMapSize, MIP_DEFAULT,
PF_BYTE_RGB, TU_STATIC);
if (mCpuColourMapStorage)
{
// Load cached data
PixelBox src(mGlobalColourMapSize, mGlobalColourMapSize, 1, PF_BYTE_RGB, mCpuColourMapStorage);
mColourMap->getBuffer()->blitFromMemory(src);
// release CPU copy, don't need it anymore
OGRE_FREE(mCpuColourMapStorage, MEMCATEGORY_RESOURCE);
mCpuColourMapStorage = 0;
}
}
else if (!mGlobalColourMapEnabled && !mColourMap.isNull())
{
// destroy
TextureManager::getSingleton().remove(mColourMap->getHandle());
mColourMap.setNull();
}
}
//---------------------------------------------------------------------
void Terrain::createOrDestroyGPULightmap()
{
if (mLightMapRequired && mLightmap.isNull())
{
// create
mLightmap = TextureManager::getSingleton().createManual(
mMaterialName + "/lm", _getDerivedResourceGroup(),
TEX_TYPE_2D, mLightmapSize, mLightmapSize, 0, PF_L8, TU_STATIC);
mLightmapSizeActual = mLightmap->getWidth();
if (mCpuLightmapStorage)
{
// Load cached data
PixelBox src(mLightmapSize, mLightmapSize, 1, PF_L8, mCpuLightmapStorage);
mLightmap->getBuffer()->blitFromMemory(src);
// release CPU copy, don't need it anymore
OGRE_FREE(mCpuLightmapStorage, MEMCATEGORY_RESOURCE);
mCpuLightmapStorage = 0;
}
else
{
// initialise to full-bright
Box box(0, 0, mLightmapSizeActual, mLightmapSizeActual);
HardwarePixelBufferSharedPtr buf = mLightmap->getBuffer();
uint8* pInit = static_cast<uint8*>(buf->lock(box, HardwarePixelBuffer::HBL_DISCARD).data);
memset(pInit, 255, mLightmapSizeActual * mLightmapSizeActual);
buf->unlock();
}
}
else if (!mLightMapRequired && !mLightmap.isNull())
{
// destroy
TextureManager::getSingleton().remove(mLightmap->getHandle());
mLightmap.setNull();
}
}
//---------------------------------------------------------------------
void Terrain::createOrDestroyGPUCompositeMap()
{
if (mCompositeMapRequired && mCompositeMap.isNull())
{
// create
mCompositeMap = TextureManager::getSingleton().createManual(
mMaterialName + "/comp", _getDerivedResourceGroup(),
TEX_TYPE_2D, mCompositeMapSize, mCompositeMapSize, 0, PF_BYTE_RGBA, TU_STATIC);
mCompositeMapSizeActual = mCompositeMap->getWidth();
if (mCpuCompositeMapStorage)
{
// Load cached data
PixelBox src(mCompositeMapSize, mCompositeMapSize, 1, PF_BYTE_RGBA, mCpuCompositeMapStorage);
mCompositeMap->getBuffer()->blitFromMemory(src);
// release CPU copy, don't need it anymore
OGRE_FREE(mCpuCompositeMapStorage, MEMCATEGORY_RESOURCE);
mCpuCompositeMapStorage = 0;
}
else
{
// initialise to black
Box box(0, 0, mCompositeMapSizeActual, mCompositeMapSizeActual);
HardwarePixelBufferSharedPtr buf = mCompositeMap->getBuffer();
uint8* pInit = static_cast<uint8*>(buf->lock(box, HardwarePixelBuffer::HBL_DISCARD).data);
memset(pInit, 0, mCompositeMapSizeActual * mCompositeMapSizeActual * 4);
buf->unlock();
}
}
else if (!mCompositeMapRequired && !mCompositeMap.isNull())
{
// destroy
TextureManager::getSingleton().remove(mCompositeMap->getHandle());
mCompositeMap.setNull();
}
}
//---------------------------------------------------------------------
Terrain* Terrain::getNeighbour(NeighbourIndex index)
{
return mNeighbours[index];
}
//---------------------------------------------------------------------
void Terrain::setNeighbour(NeighbourIndex index, Terrain* neighbour,
bool recalculate /*= false*/, bool notifyOther /* = true */)
{
if (mNeighbours[index] != neighbour)
{
assert(neighbour != this && "Can't set self as own neighbour!");
// detach existing
if (mNeighbours[index] && notifyOther)
mNeighbours[index]->setNeighbour(getOppositeNeighbour(index), 0, false, false);
mNeighbours[index] = neighbour;
if (neighbour && notifyOther)
mNeighbours[index]->setNeighbour(getOppositeNeighbour(index), this, recalculate, false);
if (recalculate)
{
// Recalculate, pass OUR edge rect
Rect edgerect;
getEdgeRect(index, 2, &edgerect);
neighbourModified(index, edgerect, edgerect);
}
}
}
//---------------------------------------------------------------------
Terrain::NeighbourIndex Terrain::getOppositeNeighbour(NeighbourIndex index)
{
int intindex = static_cast<int>(index);
intindex += NEIGHBOUR_COUNT / 2;
intindex = intindex % NEIGHBOUR_COUNT;
return static_cast<NeighbourIndex>(intindex);
}
//---------------------------------------------------------------------
Terrain::NeighbourIndex Terrain::getNeighbourIndex(long x, long y)
{
if (x < 0)
{
if (y < 0)
return NEIGHBOUR_SOUTHWEST;
else if (y > 0)
return NEIGHBOUR_NORTHWEST;
else
return NEIGHBOUR_WEST;
}
else if (x > 0)
{
if (y < 0)
return NEIGHBOUR_SOUTHEAST;
else if (y > 0)
return NEIGHBOUR_NORTHEAST;
else
return NEIGHBOUR_EAST;
}
if (y < 0)
{
if (x == 0)
return NEIGHBOUR_SOUTH;
}
else if (y > 0)
{
if (x == 0)
return NEIGHBOUR_NORTH;
}
return NEIGHBOUR_NORTH;
}
//---------------------------------------------------------------------
void Terrain::notifyNeighbours()
{
// There are 3 things that can need updating:
// Height at edge - match to neighbour (first one to update 'loses' to other since read-only)
// Normal at edge - use heights from across boundary too
// Shadows across edge
// The extent to which these can affect the current tile vary:
// Height at edge - only affected by a change at the adjoining edge / corner
// Normal at edge - only affected by a change to the 2 rows adjoining the edge / corner
// Shadows across edge - possible effect extends based on the projection of the
// neighbour AABB along the light direction (worst case scenario)
if (!mDirtyGeometryRectForNeighbours.isNull())
{
Rect dirtyRectForNeighbours(mDirtyGeometryRectForNeighbours);
mDirtyGeometryRectForNeighbours.setNull();
// calculate light update rectangle
const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection();
Rect lightmapRect;
widenRectByVector(lightVec, dirtyRectForNeighbours, getMinHeight(), getMaxHeight(), lightmapRect);
for (int i = 0; i < (int)NEIGHBOUR_COUNT; ++i)
{
NeighbourIndex ni = static_cast<NeighbourIndex>(i);
Terrain* neighbour = getNeighbour(ni);
if (!neighbour)
continue;
// Intersect the incoming rectangles with the edge regions related to this neighbour
Rect edgeRect;
getEdgeRect(ni, 2, &edgeRect);
Rect heightEdgeRect = edgeRect.intersect(dirtyRectForNeighbours);
Rect lightmapEdgeRect = edgeRect.intersect(lightmapRect);
if (!heightEdgeRect.isNull() || !lightmapRect.isNull())
{
// ok, we have something valid to pass on
Rect neighbourHeightEdgeRect, neighbourLightmapEdgeRect;
if (!heightEdgeRect.isNull())
getNeighbourEdgeRect(ni, heightEdgeRect, &neighbourHeightEdgeRect);
if (!lightmapRect.isNull())
getNeighbourEdgeRect(ni, lightmapEdgeRect, &neighbourLightmapEdgeRect);
neighbour->neighbourModified(getOppositeNeighbour(ni),
neighbourHeightEdgeRect, neighbourLightmapEdgeRect);
}
}
}
}
//---------------------------------------------------------------------
void Terrain::neighbourModified(NeighbourIndex index, const Rect& edgerect, const Rect& shadowrect)
{
// We can safely assume that we would not have been contacted if it wasn't
// important
const Terrain* neighbour = getNeighbour(index);
if (!neighbour)
return; // bogus request
bool updateGeom = false;
uint8 updateDerived = 0;
if (!edgerect.isNull())
{
// update edges; match heights first, then recalculate normals
// reduce to just single line / corner
Rect heightMatchRect;
getEdgeRect(index, 1, &heightMatchRect);
heightMatchRect = heightMatchRect.intersect(edgerect);
for (long y = heightMatchRect.top; y < heightMatchRect.bottom; ++y)
{
for (long x = heightMatchRect.left; x < heightMatchRect.right; ++x)
{
long nx, ny;
getNeighbourPoint(index, x, y, &nx, &ny);
float neighbourHeight = neighbour->getHeightAtPoint(nx, ny);
if (!Math::RealEqual(neighbourHeight, getHeightAtPoint(x, y), 1e-3f))
{
setHeightAtPoint(x, y, neighbourHeight);
if (!updateGeom)
{
updateGeom = true;
updateDerived |= DERIVED_DATA_ALL;
}
}
}
}
// if we didn't need to update heights, we still need to update normals
// because this was called only if neighbor changed
if (!updateGeom)
{
// ideally we would deal with normal dirty rect separately (as we do with
// lightmaps) because a dirty geom rectangle will actually grow by one
// element in each direction for normals recalculation. However for
// the sake of one row/column it's really not worth it.
mDirtyDerivedDataRect.merge(edgerect);
updateDerived |= DERIVED_DATA_NORMALS;
}
}
if (!shadowrect.isNull())
{
// update shadows
// here we need to widen the rect passed in based on the min/max height
// of the *neighbour*
const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection();
Rect widenedRect;
widenRectByVector(lightVec, shadowrect, neighbour->getMinHeight(), neighbour->getMaxHeight(), widenedRect);
// set the special-case lightmap dirty rectangle
mDirtyLightmapFromNeighboursRect.merge(widenedRect);
updateDerived |= DERIVED_DATA_LIGHTMAP;
}
if (updateGeom)
updateGeometry();
if (updateDerived)
updateDerivedData(false, updateDerived);
}
//---------------------------------------------------------------------
void Terrain::getEdgeRect(NeighbourIndex index, long range, Rect* outRect)
{
// We make the edge rectangle 2 rows / columns at the edge of the tile
// 2 because this copes with normal changes and potentially filtered
// shadows.
// all right / bottom values are exclusive
// terrain origin is bottom-left remember so north is highest value
// set left/right
switch(index)
{
case NEIGHBOUR_EAST:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_SOUTHEAST:
outRect->left = mSize - range;
outRect->right = mSize;
break;
case NEIGHBOUR_WEST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTHWEST:
outRect->left = 0;
outRect->right = range;
break;
case NEIGHBOUR_NORTH:
case NEIGHBOUR_SOUTH:
outRect->left = 0;
outRect->right = mSize;
break;
case NEIGHBOUR_COUNT:
default:
break;
};
// set top / bottom
switch(index)
{
case NEIGHBOUR_NORTH:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_NORTHWEST:
outRect->top = mSize - range;
outRect->bottom = mSize;
break;
case NEIGHBOUR_SOUTH:
case NEIGHBOUR_SOUTHWEST:
case NEIGHBOUR_SOUTHEAST:
outRect->top = 0;
outRect->bottom = range;
break;
case NEIGHBOUR_EAST:
case NEIGHBOUR_WEST:
outRect->top = 0;
outRect->bottom = mSize;
break;
case NEIGHBOUR_COUNT:
default:
break;
};
}
//---------------------------------------------------------------------
void Terrain::getNeighbourEdgeRect(NeighbourIndex index, const Rect& inRect, Rect* outRect)
{
assert (mSize == getNeighbour(index)->getSize());
// Basically just reflect the rect
// remember index is neighbour relationship from OUR perspective so
// arrangement is backwards to getEdgeRect
// left/right
switch(index)
{
case NEIGHBOUR_EAST:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_SOUTHEAST:
case NEIGHBOUR_WEST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTHWEST:
outRect->left = mSize - inRect.right;
outRect->right = mSize - inRect.left;
break;
default:
outRect->left = inRect.left;
outRect->right = inRect.right;
break;
};
// top / bottom
switch(index)
{
case NEIGHBOUR_NORTH:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTH:
case NEIGHBOUR_SOUTHWEST:
case NEIGHBOUR_SOUTHEAST:
outRect->top = mSize - inRect.bottom;
outRect->bottom = mSize - inRect.top;
break;
default:
outRect->top = inRect.top;
outRect->bottom = inRect.bottom;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getNeighbourPoint(NeighbourIndex index, long x, long y, long *outx, long *outy)
{
// Get the index of the point we should be looking at on a neighbour
// in order to match up points
assert (mSize == getNeighbour(index)->getSize());
// left/right
switch(index)
{
case NEIGHBOUR_EAST:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_SOUTHEAST:
case NEIGHBOUR_WEST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTHWEST:
*outx = mSize - x - 1;
break;
default:
*outx = x;
break;
};
// top / bottom
switch(index)
{
case NEIGHBOUR_NORTH:
case NEIGHBOUR_NORTHEAST:
case NEIGHBOUR_NORTHWEST:
case NEIGHBOUR_SOUTH:
case NEIGHBOUR_SOUTHWEST:
case NEIGHBOUR_SOUTHEAST:
*outy = mSize - y - 1;
break;
default:
*outy = y;
break;
};
}
//---------------------------------------------------------------------
void Terrain::getPointFromSelfOrNeighbour(long x, long y, Vector3* outpos)
{
if (x >= 0 && y >=0 && x < mSize && y < mSize)
getPoint(x, y, outpos);
else
{
long nx, ny;
NeighbourIndex ni = NEIGHBOUR_EAST;
getNeighbourPointOverflow(x, y, &ni, &nx, &ny);
Terrain* neighbour = getNeighbour(ni);
if (neighbour)
{
Vector3 neighbourPos = Vector3::ZERO;
neighbour->getPoint(nx, ny, &neighbourPos);
// adjust to make it relative to our position
*outpos = neighbourPos + neighbour->getPosition() - getPosition();
}
else
{
// use our getPoint() after all, just clamp
x = std::min(x, mSize - 1L);
y = std::min(y, mSize - 1L);
x = std::max(x, 0L);
y = std::max(y, 0L);
getPoint(x, y, outpos);
}
}
}
//---------------------------------------------------------------------
void Terrain::getNeighbourPointOverflow(long x, long y, NeighbourIndex *outindex, long *outx, long *outy)
{
if (x < 0)
{
*outx = x + mSize - 1;
if (y < 0)
*outindex = NEIGHBOUR_SOUTHWEST;
else if (y >= mSize)
*outindex = NEIGHBOUR_NORTHWEST;
else
*outindex = NEIGHBOUR_WEST;
}
else if (x >= mSize)
{
*outx = x - mSize + 1;
if (y < 0)
*outindex = NEIGHBOUR_SOUTHEAST;
else if (y >= mSize)
*outindex = NEIGHBOUR_NORTHEAST;
else
*outindex = NEIGHBOUR_EAST;
}
else
*outx = x;
if (y < 0)
{
*outy = y + mSize - 1;
if (x >= 0 && x < mSize)
*outindex = NEIGHBOUR_SOUTH;
}
else if (y >= mSize)
{
*outy = y - mSize + 1;
if (x >= 0 && x < mSize)
*outindex = NEIGHBOUR_NORTH;
}
else
*outy = y;
}
//---------------------------------------------------------------------
Terrain* Terrain::raySelectNeighbour(const Ray& ray, Real distanceLimit /* = 0 */)
{
Ray modifiedRay(ray.getOrigin(), ray.getDirection());
// Move back half a square - if we're on the edge of the AABB we might
// miss the intersection otherwise; it's ok for everywhere else since
// we want the far intersection anyway
modifiedRay.setOrigin(modifiedRay.getPoint(-mWorldSize/mSize * 0.5f));
// transform into terrain space
Vector3 tPos, tDir;
convertPosition(WORLD_SPACE, modifiedRay.getOrigin(), TERRAIN_SPACE, tPos);
convertDirection(WORLD_SPACE, modifiedRay.getDirection(), TERRAIN_SPACE, tDir);
// Discard rays with no lateral component
if (Math::RealEqual(tDir.x, 0.0f, 1e-4) && Math::RealEqual(tDir.y, 0.0f, 1e-4))
return 0;
Ray terrainRay(tPos, tDir);
// Intersect with boundary planes
// Only collide with the positive (exit) side of the plane, because we may be
// querying from a point outside ourselves if we've cascaded more than once
Real dist = std::numeric_limits<Real>::max();
std::pair<bool, Real> intersectResult;
if (tDir.x < 0.0f)
{
intersectResult = Math::intersects(terrainRay, Plane(Vector3::UNIT_X, Vector3::ZERO));
if (intersectResult.first && intersectResult.second < dist)
dist = intersectResult.second;
}
else if (tDir.x > 0.0f)
{
intersectResult = Math::intersects(terrainRay, Plane(Vector3::NEGATIVE_UNIT_X, Vector3(1,0,0)));
if (intersectResult.first && intersectResult.second < dist)
dist = intersectResult.second;
}
if (tDir.y < 0.0f)
{
intersectResult = Math::intersects(terrainRay, Plane(Vector3::UNIT_Y, Vector3::ZERO));
if (intersectResult.first && intersectResult.second < dist)
dist = intersectResult.second;
}
else if (tDir.y > 0.0f)
{
intersectResult = Math::intersects(terrainRay, Plane(Vector3::NEGATIVE_UNIT_Y, Vector3(0,1,0)));
if (intersectResult.first && intersectResult.second < dist)
dist = intersectResult.second;
}
// discard out of range
if (dist * mWorldSize > distanceLimit)
return 0;
Vector3 terrainIntersectPos = terrainRay.getPoint(dist);
Real x = terrainIntersectPos.x;
Real y = terrainIntersectPos.y;
Real dx = tDir.x;
Real dy = tDir.y;
// Never return diagonal directions, we will navigate those recursively anyway
if (Math::RealEqual(x, 1.0f, 1e-4f) && dx > 0)
return getNeighbour(NEIGHBOUR_EAST);
else if (Math::RealEqual(x, 0.0f, 1e-4f) && dx < 0)
return getNeighbour(NEIGHBOUR_WEST);
else if (Math::RealEqual(y, 1.0f, 1e-4f) && dy > 0)
return getNeighbour(NEIGHBOUR_NORTH);
else if (Math::RealEqual(y, 0.0f, 1e-4f) && dy < 0)
return getNeighbour(NEIGHBOUR_SOUTH);
return 0;
}
//---------------------------------------------------------------------
void Terrain::_dumpTextures(const String& prefix, const String& suffix)
{
if (!mTerrainNormalMap.isNull())
{
Image img;
mTerrainNormalMap->convertToImage(img);
img.save(prefix + "_normalmap" + suffix);
}
if (!mColourMap.isNull())
{
Image img;
mColourMap->convertToImage(img);
img.save(prefix + "_colourmap" + suffix);
}
if (!mLightmap.isNull())
{
Image img;
mLightmap->convertToImage(img);
img.save(prefix + "_lightmap" + suffix);
}
if (!mCompositeMap.isNull())
{
Image img;
mCompositeMap->convertToImage(img);
img.save(prefix + "_compositemap" + suffix);
}
int blendTexture = 0;
for (TexturePtrList::iterator i = mBlendTextureList.begin(); i != mBlendTextureList.end(); ++i, ++blendTexture)
{
if (!i->isNull())
{
Image img;
(*i)->convertToImage(img);
img.save(prefix + "_blendtexture" + StringConverter::toString(blendTexture) + suffix);
}
}
}
//---------------------------------------------------------------------
void Terrain::setGpuBufferAllocator(GpuBufferAllocator* alloc)
{
if (alloc != getGpuBufferAllocator())
{
if (isLoaded())
OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
"Cannot alter the allocator when loaded!", __FUNCTION__);
mCustomGpuBufferAllocator = alloc;
}
}
//---------------------------------------------------------------------
Terrain::GpuBufferAllocator* Terrain::getGpuBufferAllocator()
{
if (mCustomGpuBufferAllocator)
return mCustomGpuBufferAllocator;
else
return &mDefaultGpuBufferAllocator;
}
//---------------------------------------------------------------------
size_t Terrain::getPositionBufVertexSize() const
{
size_t sz = 0;
if (_getUseVertexCompression())
{
// short2 position
sz += sizeof(short) * 2;
// float1 height
sz += sizeof(float);
}
else
{
// float3 position
sz += sizeof(float) * 3;
// float2 uv
sz += sizeof(float) * 2;
}
return sz;
}
//---------------------------------------------------------------------
size_t Terrain::getDeltaBufVertexSize() const
{
// float2(delta, deltaLODthreshold)
return sizeof(float) * 2;
}
//---------------------------------------------------------------------
size_t Terrain::_getNumIndexesForBatchSize(uint16 batchSize)
{
size_t mainIndexesPerRow = batchSize * 2 + 1;
size_t numRows = batchSize - 1;
size_t mainIndexCount = mainIndexesPerRow * numRows;
// skirts share edges, so they take 1 less row per side than batchSize,
// but with 2 extra at the end (repeated) to finish the strip
// * 2 for the vertical line, * 4 for the sides, +2 to finish
size_t skirtIndexCount = (batchSize - 1) * 2 * 4 + 2;
return mainIndexCount + skirtIndexCount;
}
//---------------------------------------------------------------------
void Terrain::_populateIndexBuffer(uint16* pI, uint16 batchSize,
uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols,
uint16 skirtRowColSkip)
{
/* For even / odd tri strip rows, triangles are this shape:
6---7---8
| \ | \ |
3---4---5
| / | / |
0---1---2
Note how vertex rows count upwards. In order to match up the anti-clockwise
winding and this upward transitioning list, we need to start from the
right hand side. So we get (2,5,1,4,0,3) etc on even lines (right-left)
and (3,6,4,7,5,8) etc on odd lines (left-right). At the turn, we emit the end index
twice, this forms a degenerate triangle, which lets us turn without any artefacts.
So the full list in this simple case is (2,5,1,4,0,3,3,6,4,7,5,8)
Skirts are part of the same strip, so after finishing on 8, where sX is
the skirt vertex corresponding to main vertex X, we go
anticlockwise around the edge, (s8,7,s7,6,s6) to do the top skirt,
then (3,s3,0,s0),(1,s1,2,s2),(5,s5,8,s8) to finish the left, bottom, and
right skirts respectively.
*/
// to issue a complete row, it takes issuing the upper and lower row
// and one extra index, which is the degenerate triangle and also turning
// around the winding
size_t rowSize = vdatasize * vertexIncrement;
size_t numRows = batchSize - 1;
// Start on the right
uint16 currentVertex = (batchSize - 1) * vertexIncrement;
// but, our quad area might not start at 0 in this vertex data
// offsets are at main terrain resolution, remember
uint16 columnStart = xoffset;
uint16 rowStart = yoffset;
currentVertex += rowStart * vdatasize + columnStart;
bool rightToLeft = true;
for (uint16 r = 0; r < numRows; ++r)
{
for (uint16 c = 0; c < batchSize; ++c)
{
*pI++ = currentVertex;
*pI++ = currentVertex + rowSize;
// don't increment / decrement at a border, keep this vertex for next
// row as we 'snake' across the tile
if (c+1 < batchSize)
{
currentVertex = rightToLeft ?
currentVertex - vertexIncrement : currentVertex + vertexIncrement;
}
}
rightToLeft = !rightToLeft;
currentVertex += rowSize;
// issue one extra index to turn winding around
*pI++ = currentVertex;
}
// Skirts
for (uint16 s = 0; s < 4; ++s)
{
// edgeIncrement is the index offset from one original edge vertex to the next
// in this row or column. Columns skip based on a row size here
// skirtIncrement is the index offset from one skirt vertex to the next,
// because skirts are packed in rows/cols then there is no row multiplier for
// processing columns
int edgeIncrement = 0, skirtIncrement = 0;
switch(s)
{
case 0: // top
edgeIncrement = -static_cast<int>(vertexIncrement);
skirtIncrement = -static_cast<int>(vertexIncrement);
break;
case 1: // left
edgeIncrement = -static_cast<int>(rowSize);
skirtIncrement = -static_cast<int>(vertexIncrement);
break;
case 2: // bottom
edgeIncrement = static_cast<int>(vertexIncrement);
skirtIncrement = static_cast<int>(vertexIncrement);
break;
case 3: // right
edgeIncrement = static_cast<int>(rowSize);
skirtIncrement = static_cast<int>(vertexIncrement);
break;
}
// Skirts are stored in contiguous rows / columns (rows 0/2, cols 1/3)
uint16 skirtIndex = _calcSkirtVertexIndex(currentVertex, vdatasize,
(s % 2) != 0, numSkirtRowsCols, skirtRowColSkip);
for (uint16 c = 0; c < batchSize - 1; ++c)
{
*pI++ = currentVertex;
*pI++ = skirtIndex;
currentVertex += edgeIncrement;
skirtIndex += skirtIncrement;
}
if (s == 3)
{
// we issue an extra 2 indices to finish the skirt off
*pI++ = currentVertex;
*pI++ = skirtIndex;
currentVertex += edgeIncrement;
}
}
}
//---------------------------------------------------------------------
uint16 Terrain::_calcSkirtVertexIndex(uint16 mainIndex, uint16 vdatasize, bool isCol,
uint16 numSkirtRowsCols, uint16 skirtRowColSkip)
{
// row / col in main vertex resolution
uint16 row = mainIndex / vdatasize;
uint16 col = mainIndex % vdatasize;
// skrits are after main vertices, so skip them
uint16 base = vdatasize * vdatasize;
// The layout in vertex data is:
// 1. row skirts
// numSkirtRowsCols rows of resolution vertices each
// 2. column skirts
// numSkirtRowsCols cols of resolution vertices each
// No offsets used here, this is an index into the current vertex data,
// which is already relative
if (isCol)
{
uint16 skirtNum = col / skirtRowColSkip;
uint16 colbase = numSkirtRowsCols * vdatasize;
return base + colbase + vdatasize * skirtNum + row;
}
else
{
uint16 skirtNum = row / skirtRowColSkip;
return base + vdatasize * skirtNum + col;
}
}
//---------------------------------------------------------------------
void Terrain::setWorldSize(Real newWorldSize)
{
if(mWorldSize != newWorldSize)
{
waitForDerivedProcesses();
mWorldSize = newWorldSize;
updateBaseScale();
deriveUVMultipliers();
mMaterialParamsDirty = true;
if(mIsLoaded)
{
Rect dRect(0, 0, mSize, mSize);
dirtyRect(dRect);
update();
}
mModified = true;
}
}
//---------------------------------------------------------------------
void Terrain::setSize(uint16 newSize)
{
if(mSize != newSize)
{
waitForDerivedProcesses();
size_t numVertices = newSize * newSize;
PixelBox src(mSize, mSize, 1, Ogre::PF_FLOAT32_R, (void*)getHeightData());
float* tmpData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GENERAL);
PixelBox dst(newSize, newSize, 1, Ogre::PF_FLOAT32_R, tmpData);
Image::scale(src, dst, Image::FILTER_BILINEAR);
freeCPUResources();
mSize = newSize;
determineLodLevels();
updateBaseScale();
deriveUVMultipliers();
mMaterialParamsDirty = true;
mHeightData = tmpData;
mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY);
memset(mDeltaData, 0, sizeof(float) * numVertices);
mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0, 0);
mQuadTree->prepare();
// calculate entire terrain
Rect rect;
rect.top = 0; rect.bottom = mSize;
rect.left = 0; rect.right = mSize;
calculateHeightDeltas(rect);
finaliseHeightDeltas(rect, true);
distributeVertexData();
if(mIsLoaded)
{
if (mQuadTree)
mQuadTree->load();
}
mModified = true;
}
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
Terrain::DefaultGpuBufferAllocator::DefaultGpuBufferAllocator()
{
}
//---------------------------------------------------------------------
Terrain::DefaultGpuBufferAllocator::~DefaultGpuBufferAllocator()
{
freeAllBuffers();
}
//---------------------------------------------------------------------
void Terrain::DefaultGpuBufferAllocator::allocateVertexBuffers(Terrain* forTerrain,
size_t numVertices, HardwareVertexBufferSharedPtr& destPos, HardwareVertexBufferSharedPtr& destDelta)
{
destPos = getVertexBuffer(mFreePosBufList, forTerrain->getPositionBufVertexSize(), numVertices);
destDelta = getVertexBuffer(mFreeDeltaBufList, forTerrain->getDeltaBufVertexSize(), numVertices);
}
//---------------------------------------------------------------------
HardwareVertexBufferSharedPtr Terrain::DefaultGpuBufferAllocator::getVertexBuffer(
VBufList& list, size_t vertexSize, size_t numVertices)
{
size_t sz = vertexSize * numVertices;
for (VBufList::iterator i = list.begin(); i != list.end(); ++i)
{
if ((*i)->getSizeInBytes() == sz)
{
HardwareVertexBufferSharedPtr ret = *i;
list.erase(i);
return ret;
}
}
// Didn't find one?
return HardwareBufferManager::getSingleton()
.createVertexBuffer(vertexSize, numVertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
}
//---------------------------------------------------------------------
void Terrain::DefaultGpuBufferAllocator::freeVertexBuffers(
const HardwareVertexBufferSharedPtr& posbuf, const HardwareVertexBufferSharedPtr& deltabuf)
{
mFreePosBufList.push_back(posbuf);
mFreeDeltaBufList.push_back(deltabuf);
}
//---------------------------------------------------------------------
HardwareIndexBufferSharedPtr Terrain::DefaultGpuBufferAllocator::getSharedIndexBuffer(uint16 batchSize,
uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols,
uint16 skirtRowColSkip)
{
uint32 hsh = hashIndexBuffer(batchSize, vdatasize, vertexIncrement, xoffset, yoffset,
numSkirtRowsCols, skirtRowColSkip);
IBufMap::iterator i = mSharedIBufMap.find(hsh);
if (i == mSharedIBufMap.end())
{
// create new
size_t indexCount = Terrain::_getNumIndexesForBatchSize(batchSize);
HardwareIndexBufferSharedPtr ret = HardwareBufferManager::getSingleton()
.createIndexBuffer(HardwareIndexBuffer::IT_16BIT, indexCount,
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
uint16* pI = static_cast<uint16*>(ret->lock(HardwareBuffer::HBL_DISCARD));
Terrain::_populateIndexBuffer(pI, batchSize, vdatasize, vertexIncrement, xoffset, yoffset, numSkirtRowsCols, skirtRowColSkip);
ret->unlock();
mSharedIBufMap[hsh] = ret;
return ret;
}
else
return i->second;
}
//---------------------------------------------------------------------
void Terrain::DefaultGpuBufferAllocator::freeAllBuffers()
{
mFreePosBufList.clear();
mFreeDeltaBufList.clear();
mSharedIBufMap.clear();
}
//---------------------------------------------------------------------
void Terrain::DefaultGpuBufferAllocator::warmStart(size_t numInstances, uint16 terrainSize, uint16 maxBatchSize,
uint16 mMinBatchSize)
{
// TODO
}
//---------------------------------------------------------------------
uint32 Terrain::DefaultGpuBufferAllocator::hashIndexBuffer(uint16 batchSize,
uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols,
uint16 skirtRowColSkip)
{
uint32 ret = 0;
ret = HashCombine(ret, batchSize);
ret = HashCombine(ret, vdatasize);
ret = HashCombine(ret, vertexIncrement);
ret = HashCombine(ret, xoffset);
ret = HashCombine(ret, yoffset);
ret = HashCombine(ret, numSkirtRowsCols);
ret = HashCombine(ret, skirtRowColSkip);
return ret;
}
}
| mit |
luanlv/lila | modules/security/src/main/Firewall.scala | 1384 | package lila.security
import org.joda.time.DateTime
import play.api.mvc.RequestHeader
import scala.concurrent.duration._
import reactivemongo.api.ReadPreference
import lila.common.IpAddress
import lila.db.BSON.BSONJodaDateTimeHandler
import lila.db.dsl._
final class Firewall(
coll: Coll,
scheduler: akka.actor.Scheduler
)(implicit ec: scala.concurrent.ExecutionContext) {
private var current: Set[String] = Set.empty
scheduler.scheduleOnce(10 minutes)(loadFromDb.unit)
def blocksIp(ip: IpAddress): Boolean = current contains ip.value
def blocks(req: RequestHeader): Boolean = {
val v = blocksIp {
lila.common.HTTPRequest ipAddress req
}
if (v) lila.mon.security.firewall.block.increment()
v
}
def accepts(req: RequestHeader): Boolean = !blocks(req)
def blockIps(ips: Iterable[IpAddress]): Funit =
ips.map { ip =>
coll.update
.one(
$id(ip),
$doc("_id" -> ip, "date" -> DateTime.now),
upsert = true
)
.void
}.sequenceFu >> loadFromDb
def unblockIps(ips: Iterable[IpAddress]): Funit =
coll.delete.one($inIds(ips)).void >>- loadFromDb.unit
private def loadFromDb: Funit =
coll.distinctEasy[String, Set]("_id", $empty, ReadPreference.secondaryPreferred).map { ips =>
current = ips
lila.mon.security.firewall.ip.update(ips.size).unit
}
}
| mit |
dkackman/HockeySDK-Windows | Src/Kit.WP81/Universal/LocalizedStrings.cs | 2406 | using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Resources;
namespace Microsoft.HockeyApp
{
public class LocalizedStrings
{
private static ResourceWrapper _localizedResources = null;
public static dynamic LocalizedResources {
get {
if (_localizedResources == null)
{
_localizedResources = new ResourceWrapper();
}
return _localizedResources;
}
}
}
public class ResourceWrapper : DynamicObject
{
private ResourceLoader _customResLoader;
internal ResourceLoader CustomResourceLoader
{
get { return _customResLoader; }
set { _customResLoader = value; }
}
private ResourceLoader _internalResLoader;
internal ResourceLoader InternalResourceLoader
{
get { return _internalResLoader; }
set { _internalResLoader = value; }
}
internal ResourceWrapper()
{
InternalResourceLoader = ResourceLoader.GetForViewIndependentUse(Tools.WebBrowserHelper.AssemblyNameWithoutExtension + "/Resources");
try
{ //try to load .resw if available in project!
CustomResourceLoader = ResourceLoader.GetForViewIndependentUse(Tools.WebBrowserHelper.AssemblyNameWithoutExtension);
}
catch (Exception) { }
}
public object this[string index]
{
get
{
string value = null;
if (_customResLoader != null)
{
value = _customResLoader.GetString(index);
}
if (String.IsNullOrEmpty(value))
{
value = _internalResLoader.GetString(index);
}
if (String.IsNullOrEmpty(value))
{
value = index + "_i18n";
}
return value;
}
}
//For dynamic use in code
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this[binder.Name];
return result != null;
}
}
}
| mit |
tenpoku1000/UEFI_Ver_CPUID | src/lib/external/MIT/musl/src/thread/pthread_rwlock_timedwrlock.c | 610 | #include "pthread_impl.h"
int pthread_rwlock_timedwrlock(pthread_rwlock_t *restrict rw, const struct timespec *restrict at)
{
int r, t;
r = pthread_rwlock_trywrlock(rw);
if (r != EBUSY) return r;
int spins = 100;
while (spins-- && rw->_rw_lock && !rw->_rw_waiters) a_spin();
while ((r=pthread_rwlock_trywrlock(rw))==EBUSY) {
if (!(r=rw->_rw_lock)) continue;
t = r | 0x80000000;
a_inc(&rw->_rw_waiters);
a_cas(&rw->_rw_lock, r, t);
r = __timedwait(&rw->_rw_lock, t, CLOCK_REALTIME, at, 0, 0, rw->_rw_shared^128);
a_dec(&rw->_rw_waiters);
if (r && r != EINTR) return r;
}
return r;
}
| mit |
grvcoelho/webhulk | vendor/gopkg.in/kataras/iris.v8/vendor/github.com/ryanuber/columnize/columnize.go | 4658 | package columnize
import (
"bytes"
"fmt"
"strings"
)
// Config can be used to tune certain parameters which affect the way
// in which Columnize will format output text.
type Config struct {
// The string by which the lines of input will be split.
Delim string
// The string by which columns of output will be separated.
Glue string
// The string by which columns of output will be prefixed.
Prefix string
// A replacement string to replace empty fields.
Empty string
// NoTrim disables automatic trimming of inputs.
NoTrim bool
}
// DefaultConfig returns a *Config with default values.
func DefaultConfig() *Config {
return &Config{
Delim: "|",
Glue: " ",
Prefix: "",
Empty: "",
NoTrim: false,
}
}
// MergeConfig merges two config objects together and returns the resulting
// configuration. Values from the right take precedence over the left side.
func MergeConfig(a, b *Config) *Config {
// Return quickly if either side was nil
if a == nil {
return b
}
if b == nil {
return a
}
var result Config = *a
if b.Delim != "" {
result.Delim = b.Delim
}
if b.Glue != "" {
result.Glue = b.Glue
}
if b.Prefix != "" {
result.Prefix = b.Prefix
}
if b.Empty != "" {
result.Empty = b.Empty
}
if b.NoTrim {
result.NoTrim = true
}
return &result
}
// stringFormat, given a set of column widths and the number of columns in
// the current line, returns a sprintf-style format string which can be used
// to print output aligned properly with other lines using the same widths set.
func stringFormat(c *Config, widths []int, columns int) string {
// Create the buffer with an estimate of the length
buf := bytes.NewBuffer(make([]byte, 0, (6+len(c.Glue))*columns))
// Start with the prefix, if any was given. The buffer will not return an
// error so it does not need to be handled
buf.WriteString(c.Prefix)
// Create the format string from the discovered widths
for i := 0; i < columns && i < len(widths); i++ {
if i == columns-1 {
buf.WriteString("%s\n")
} else {
fmt.Fprintf(buf, "%%-%ds%s", widths[i], c.Glue)
}
}
return buf.String()
}
// elementsFromLine returns a list of elements, each representing a single
// item which will belong to a column of output.
func elementsFromLine(config *Config, line string) []interface{} {
separated := strings.Split(line, config.Delim)
elements := make([]interface{}, len(separated))
for i, field := range separated {
value := field
if !config.NoTrim {
value = strings.TrimSpace(field)
}
// Apply the empty value, if configured.
if value == "" && config.Empty != "" {
value = config.Empty
}
elements[i] = value
}
return elements
}
// runeLen calculates the number of visible "characters" in a string
func runeLen(s string) int {
l := 0
for range s {
l++
}
return l
}
// widthsFromLines examines a list of strings and determines how wide each
// column should be considering all of the elements that need to be printed
// within it.
func widthsFromLines(config *Config, lines []string) []int {
widths := make([]int, 0, 8)
for _, line := range lines {
elems := elementsFromLine(config, line)
for i := 0; i < len(elems); i++ {
l := runeLen(elems[i].(string))
if len(widths) <= i {
widths = append(widths, l)
} else if widths[i] < l {
widths[i] = l
}
}
}
return widths
}
// Format is the public-facing interface that takes a list of strings and
// returns nicely aligned column-formatted text.
func Format(lines []string, config *Config) string {
conf := MergeConfig(DefaultConfig(), config)
widths := widthsFromLines(conf, lines)
// Estimate the buffer size
glueSize := len(conf.Glue)
var size int
for _, w := range widths {
size += w + glueSize
}
size *= len(lines)
// Create the buffer
buf := bytes.NewBuffer(make([]byte, 0, size))
// Create a cache for the string formats
fmtCache := make(map[int]string, 16)
// Create the formatted output using the format string
for _, line := range lines {
elems := elementsFromLine(conf, line)
// Get the string format using cache
numElems := len(elems)
stringfmt, ok := fmtCache[numElems]
if !ok {
stringfmt = stringFormat(conf, widths, numElems)
fmtCache[numElems] = stringfmt
}
fmt.Fprintf(buf, stringfmt, elems...)
}
// Get the string result
result := buf.String()
// Remove trailing newline without removing leading/trailing space
if n := len(result); n > 0 && result[n-1] == '\n' {
result = result[:n-1]
}
return result
}
// SimpleFormat is a convenience function to format text with the defaults.
func SimpleFormat(lines []string) string {
return Format(lines, nil)
}
| mit |
LuaDist2/lua_cliargs | spec/features/splatarg_spec.lua | 3343 | local helpers = require("spec_helper")
describe("cliargs - splat arguments", function()
local cli
before_each(function()
cli = require("cliargs.core")()
end)
describe('defining the splat arg', function()
it('works', function()
assert.has_no_error(function()
cli:splat('SPLAT', 'some repeatable arg')
end)
end)
it('requires a key', function()
assert.error_matches(function()
cli:splat()
end, 'Key and description are mandatory arguments')
end)
it('requires a description', function()
assert.error_matches(function()
cli:splat('SPLAT')
end, 'Key and description are mandatory arguments')
end)
it('rejects multiple definitions', function()
cli:splat('SPLAT', 'some repeatable arg')
assert.error_matches(function()
cli:splat('SOME_SPLAT', 'some repeatable arg')
end, 'Only one splat')
end)
end)
describe('default value', function()
it('allows me to define a default value', function()
cli:splat('SPLAT', 'some repeatable arg', 'foo')
end)
context('when only 1 occurrence is allowed', function()
before_each(function()
cli:splat('SPLAT', 'some repeatable arg', 'foo')
end)
it('uses the default value when nothing is passed in', function()
assert.equal(helpers.parse(cli, '').SPLAT, 'foo')
end)
end)
context('when more than 1 occurrence is allowed', function()
before_each(function()
cli:splat('SPLAT', 'some repeatable arg', 'foo', 3)
end)
it('uses the default value only once when nothing is passed in', function()
assert.same(helpers.parse(cli, '').SPLAT, { 'foo' })
end)
it('does not use the default value if something was passed in at least once', function()
assert.same(helpers.parse(cli, 'asdf').SPLAT, { 'asdf' })
end)
end)
end)
describe('repetition count', function()
it('accepts a repetition count', function()
assert.has_no_error(function()
cli:splat('SPLAT', 'some repeatable arg', nil, 2)
end)
end)
it('appends the values to a list', function()
cli:splat('SPLAT', 'some repeatable arg', nil, 2)
local args = helpers.parse(cli, 'a b')
assert.equal(#args.SPLAT, 2)
assert.equal(args.SPLAT[1], 'a')
assert.equal(args.SPLAT[2], 'b')
end)
it('bails if more values were passed than acceptable', function()
cli:splat('SPLAT', 'foobar', nil, 2)
local _, err = helpers.parse(cli, 'a b c')
assert.matches("bad number of arguments", err)
end)
end)
context("given a splatarg as the only argument/option", function()
it("works", function()
cli:splat('SPLAT', 'foobar', nil, 1)
local args = helpers.parse(cli, 'asdf')
assert.equal(type(args.SPLAT), "string")
assert.equal(args.SPLAT, "asdf")
end)
end)
describe('@callback', function()
it('invokes the callback every time a value for the splat arg is parsed', function()
local call_args = {}
cli:splat('SPLAT', 'foobar', nil, 2, function(_, value)
table.insert(call_args, value)
end)
helpers.parse(cli, 'a b')
assert.equal(#call_args, 2)
assert.equal(call_args[1], 'a')
assert.equal(call_args[2], 'b')
end)
end)
end) | mit |
jpaoletti/java-presentation-manager-2 | modules/jpm2-web-bs5/src/main/webapp/static/js/locale/select2/et.js | 775 | /*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */
(function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/et",[],function(){return{inputTooLong:function(e){var t=e.input.length-e.maximum,n="Sisesta "+t+" täht";return t!=1&&(n+="e"),n+=" vähem",n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="Sisesta "+t+" täht";return t!=1&&(n+="e"),n+=" rohkem",n},loadingMore:function(){return"Laen tulemusi..."},maximumSelected:function(e){var t="Saad vaid "+e.maximum+" tulemus";return e.maximum==1?t+="e":t+="t",t+=" valida",t},noResults:function(){return"Tulemused puuduvad"},searching:function(){return"Otsin..."}}}),{define:e.define,require:e.require}})(); | mit |
diversantvlz/WellCommerce | src/WellCommerce/Bundle/AppBundle/Controller/Admin/ClientController.php | 2342 | <?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <[email protected]>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\AppBundle\Controller\Admin;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use WellCommerce\Bundle\AppBundle\Entity\Client;
use WellCommerce\Bundle\CoreBundle\Controller\Admin\AbstractAdminController;
/**
* Class ClientController
*
* @author Adam Piotrowski <[email protected]>
*/
class ClientController extends AbstractAdminController
{
public function addAction(Request $request): Response
{
/** @var Client $resource */
$resource = $this->getManager()->initResource();
$form = $this->formBuilder->createForm($resource, [
'validation_groups' => ['client_admin_registration']
]);
if ($form->handleRequest()->isSubmitted()) {
if ($form->isValid()) {
$this->getManager()->createResource($resource);
$password = $form->getValue()['required_data']['clientDetails']['clientDetails.hashedPassword'];
$this->getMailerHelper()->sendEmail([
'recipient' => $resource->getContactDetails()->getEmail(),
'subject' => $this->getTranslatorHelper()->trans('client.email.heading.register'),
'template' => 'WellCommerceAppBundle:Email:register_admin.html.twig',
'parameters' => [
'client' => $resource,
'password' => $password,
],
'configuration' => $resource->getShop()->getMailerConfiguration(),
]);
}
return $this->createFormDefaultJsonResponse($form);
}
return $this->displayTemplate('add', [
'form' => $form,
]);
}
public function detailsAction(Client $client): Response
{
$data = $this->get('serializer')->serialize($client, 'json', ['group' => 'client']);
return new Response($data);
}
}
| mit |
samsel/Gander | tasks/copyto.js | 436 | 'use strict';
module.exports = function copyto(grunt) {
// Load task
grunt.loadNpmTasks('grunt-copy-to');
// Options
return {
build: {
files: [{
cwd: 'src',
src: ['**/*.json'],
dest: '.dist/'
},{
cwd: 'src',
src: ['public/css/**/*.less'],
dest: '.dist/'
}]
}
};
};
| mit |
tlan16/sushi-co | web/protected/controls/iframeResizer/doc/spec/parentIFrameMethodsSpec.js | 1024 | /*
define(['iframeResizerContent'], function() {
describe('ParentIFrame methods: ', function() {
var id = 'parentIFrame';
var log = LOG;
it('Get ID of iFrame is same as iFrame', function() {
mockInitFromParent(id,log);
expect(window.parentIFrame.getId()).toBe(id);
closeChild();
});
it('call methods', function() {
var count = 0;
mockInitFromParent(id,false,function(msg){
switch(++count){
case 2:
expect(msg.split('#')[1]).toBe('foo');
break;
case 3:
expect(strEnd(msg,5)).toBe('reset');
break;
case 4:
expect(msg).toBe('foo');
break;
case 5:
expect(msg).toBe('foo');
break;
case 6:
expect(msg).toBe('foo');
break;
case 7:
expect(msg).toBe('foo');
break;
case 8:
expect(msg).toBe('foo');
break;
}
});
expect(window.parentIFrame.getId()).toBe(id);
window.parentIFrame.moveToAnchor('foo');
//window.parentIFrame.reset();
//setTimeout(closeChild,1);
});
});
});
*/ | mit |
jonnybee/csla | Source/Csla.test/DataPortalChild/DataPortalChildTests.cs | 6826 | //-----------------------------------------------------------------------
// <copyright file="DataPortalChildTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif
namespace Csla.Test.DataPortalChild
{
[TestClass()]
public class DataPortalChildTests
{
[TestMethod]
public void CreateAndSaveChild()
{
Root root = new Root();
root.Data = "a";
root.Child.Data = "b";
Assert.IsTrue(root.IsDirty, "Root should be dirty");
Assert.IsTrue(root.Child.IsNew, "Child should be new");
Assert.IsTrue(root.Child.IsDirty, "Child should be dirty");
Assert.AreEqual("Created", root.Child.Status, "Child status incorrect after create");
root = root.Save();
Assert.IsFalse(root.IsDirty, "Root should not be dirty");
Assert.IsFalse(root.IsNew, "Root should not be new");
Assert.IsFalse(root.Child.IsDirty, "Child should not be dirty");
Assert.IsFalse(root.Child.IsNew, "Child should not be new");
Assert.AreEqual("Inserted", root.Child.Status, "Child status incorrect after Save");
}
[TestMethod]
public void CreateAndDeleteChild()
{
Root root = new Root();
root.Child.DeleteChild();
Assert.IsTrue(root.Child.IsDeleted, "Child should be marked for deletion");
Assert.IsTrue(root.Child.IsDirty, "Child should be dirty");
root = root.Save();
Assert.IsTrue(root.IsDirty, "Root should be dirty after Save");
Assert.IsFalse(root.IsNew, "Root should not be new");
Assert.IsTrue(root.Child.IsDirty, "Child should be dirty");
Assert.IsTrue(root.Child.IsNew, "Child should be new");
Assert.AreEqual("Created", root.Child.Status, "Child status incorrect");
}
[TestMethod]
public void FetchAndSaveChild()
{
Root root = new Root();
root.FetchChild();
Assert.IsFalse(root.Child.IsNew, "Child should not be new");
Assert.IsFalse(root.Child.IsDirty, "Child should not be dirty");
Assert.AreEqual("Fetched", root.Child.Status, "Child status incorrect after fetch");
root.Child.Data = "b";
Assert.IsTrue(root.Child.IsDirty, "Child should be dirty");
root = root.Save();
Assert.IsFalse(root.IsDirty, "Root should not be dirty");
Assert.IsFalse(root.IsNew, "Root should not be new");
Assert.IsFalse(root.Child.IsDirty, "Child should not be dirty");
Assert.IsFalse(root.Child.IsNew, "Child should not be new");
Assert.AreEqual("Updated", root.Child.Status, "Child status incorrect after Save");
}
[TestMethod]
public void FetchAndDeleteChild()
{
Root root = new Root();
root.FetchChild();
Assert.IsFalse(root.Child.IsNew, "Child should not be new");
Assert.IsFalse(root.Child.IsDirty, "Child should not be dirty");
Assert.AreEqual("Fetched", root.Child.Status, "Child status incorrect after fetch");
root.Child.DeleteChild();
Assert.IsTrue(root.Child.IsDeleted, "Child should be marked for deletion");
Assert.IsTrue(root.Child.IsDirty, "Child should be dirty");
root = root.Save();
Assert.IsTrue(root.IsDirty, "Root should be dirty after Save");
Assert.IsFalse(root.IsNew, "Root should not be new");
Assert.IsTrue(root.Child.IsDirty, "Child should be dirty after Save");
Assert.IsTrue(root.Child.IsNew, "Child should be new after Save");
Assert.AreEqual("Deleted", root.Child.Status, "Child status incorrect after Save");
}
[TestMethod]
public void FetchAndSaveChildList()
{
Root root = new Root();
var list = root.ChildList;
Assert.IsFalse(root.ChildList.IsDirty, "Child list should not be dirty");
Assert.AreEqual("Fetched", root.ChildList.Status, "Child list status incorrect after fetch");
list.Add(Child.NewChild());
Assert.IsTrue(root.ChildList.IsDirty, "Child list should be dirty after add");
Assert.IsTrue(root.ChildList[0].IsDirty, "Child should be dirty after add");
Assert.IsTrue(root.ChildList[0].IsNew, "Child should be new after add");
root = root.Save();
Assert.IsFalse(root.IsDirty, "Root should not be dirty after Save");
Assert.IsFalse(root.IsNew, "Root should not be new");
Assert.IsFalse(root.ChildList.IsDirty, "Child should not be dirty after Save");
Assert.AreEqual("Updated", root.ChildList.Status, "Child list status incorrect after Save");
Assert.IsFalse(root.ChildList[0].IsDirty, "Child should not be dirty after Save");
Assert.IsFalse(root.ChildList[0].IsNew, "Child should not be new after Save");
Assert.AreEqual("Inserted", root.ChildList[0].Status, "Child status incorrect after Save");
}
[TestMethod]
public void FetchAndSaveChildListVerifyParent()
{
Root root = new Root();
root.Data = "root";
var oneChild = root.Child;
oneChild.Data = "random";
var list = root.ChildList;
Assert.IsFalse(root.ChildList.IsDirty, "Child list should not be dirty");
Assert.AreEqual("Fetched", root.ChildList.Status, "Child list status incorrect after fetch");
list.Add(Child.NewChild());
Assert.IsTrue(root.ChildList.IsDirty, "Child list should be dirty after add");
Assert.IsTrue(root.ChildList[0].IsDirty, "Child should be dirty after add");
Assert.IsTrue(root.ChildList[0].IsNew, "Child should be new after add");
root = root.Save();
Assert.IsFalse(root.IsDirty, "Root should not be dirty after Save");
Assert.IsFalse(root.IsNew, "Root should not be new");
Assert.IsFalse(root.ChildList.IsDirty, "Child should not be dirty after Save");
Assert.AreEqual("Updated", root.ChildList.Status, "Child list status incorrect after Save");
Assert.IsFalse(root.ChildList[0].IsDirty, "Child should not be dirty after Save");
Assert.IsFalse(root.ChildList[0].IsNew, "Child should not be new after Save");
Assert.AreEqual("Inserted", root.ChildList[0].Status, "Child status incorrect after Save");
Assert.AreEqual("root", root.ChildList[0].RootData, "Parent data is not correct after Save in the list");
Assert.AreEqual("root", root.Child.RootData, "Parent data is not correct after Save in one child");
}
}
} | mit |
bitovi/canjs | docs/can-guides/introduction/who-uses.md | 2955 | @page guides/who-uses-canjs Who Uses CanJS?
@parent about 2
@body
<div class="screenshots">
## Apple Store
Discovered via [Reddit](https://www.reddit.com/r/javascript/comments/1kffau/apple_store_use_canjs_javascript_framework_not/)
<a href="http://www.apple.com/shop/buy-iphone/iphone-7"><span>http://www.apple.com/shop/buy-iphone/iphone-7</span><img src="../../docs/can-guides/images/apps/screenshots-aos.jpg"></a>
## Chase
<a href="http://payments.chase.com"><span>http://payments.chase.com</span><img src="../../docs/can-guides/images/apps/screenshots-chase.jpg">
## HP
<a href="http://store.hp.com"><span>http://store.hp.com</span><img src="../../docs/can-guides/images/apps/screenshots-hp.jpg"></a>
## USGA
<a href="http://www.usga.org/"><span>http://www.usga.org</span><img src="../../docs/can-guides/images/apps/screenshots-usga.jpg"></a>
## Yahoo
Yahoo uses CanJS in its [Brightroll Console](https://www.bitovi.com/blog/canjs-case-study-brightroll), a tool used to purchase ads and explore analytics.
<img src="../../docs/can-guides/images/apps/screenshots-brightroll.jpg">
## PlutoTV
<a href="http://pluto.tv/watch"><span>http://pluto.tv/watch</span><img src="../../docs/can-guides/images/apps/screenshots-plutotv.jpg"></a>
## FedEx
FedEx uses CanJS in its package tracker.
<a href="https://www.fedex.com/apps/fedextrack/?action=track&cntry_code=us"><span>https://www.fedex.com/apps/fedextrack</span><img src="../../docs/can-guides/images/apps/screenshots-fedex.jpg"></a>
## Sam’s Club
<a href="https://m.samsclub.com/locator?xid=hdr_locator"><span>https://m.samsclub.com</span><img src="../../docs/can-guides/images/apps/screenshots-sams.jpg"></a>
## Delta SkyMiles
Delta uses CanJS in its rewards program, SkyMiles.
<a href="http://www.skymilesshopping.com/"><span>http://www.skymilesshopping.com</span><img src="../../docs/can-guides/images/apps/screenshots-skymiles.jpg"></a>
## Fidelity
Fidelity uses JavaScriptMVC (the previous name for CanJS) in its Mutual Fund comparison tool.
<a href="https://www.fidelity.com/fund-screener/research.shtml"><span>https://www.fidelity.com/fund-screener/research.shtml</span><img src="../../docs/can-guides/images/apps/screenshots-fidelity.jpg"></a>
## Apple ID Data & Privacy
<a href="https://privacy.apple.com/"><span>https://privacy.apple.com/</span><img src="../../docs/can-guides/images/apps/screenshots-apple-id-data-and-privacy.png"></a>
## Cars.com
<a href="http://www.cars.com"><span>http://www.cars.com</span><img src="../../docs/can-guides/images/apps/screenshots-cars.jpg"></a>
</div>
## Submit other apps
Did you work on an app that uses CanJS? Please add it to the list [here](https://github.com/canjs/canjs/blob/master/docs/can-guides/introduction/who-uses.md) and create a PR, or email it [here](mailto:[email protected]) and we’d be happy to submit it for you!
[//]: # (Volkswagon)
[//]: # (Wells Fargo)
[//]: # (Walmart)
[//]: # (T-Mobile)
| mit |
linpengxuan/blog_backup | untitled folder/2007-04-28-我去越南了。。。有事电话我-86-13902979771-估计是没人打了.html | 293 | ---
layout: post
title: 我去越南了。。。有事电话我 86 13902979771 估计是没人打了。。。。
categories: []
tags: []
published: true
comments: true
---
<p><div id="msgcns!3725CC0EE38B1F6!1658" class="bvMsg"><br /><br />-- <br />Sincerely,<br /><br />Lin Pengxuan</div></p>
| mit |
ExtraCells/ExtraCells1 | src/api/java/appeng/api/me/util/ICraftRequest.java | 121 | package appeng.api.me.util;
/**
* Pretty much just a place holder right now
*
*/
public interface ICraftRequest {
}
| mit |
rohitsuratekar/PersonalWebsite | src/app/components/about-me/about-me.component.spec.ts | 636 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AboutMeComponent } from './about-me.component';
describe('AboutMeComponent', () => {
let component: AboutMeComponent;
let fixture: ComponentFixture<AboutMeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AboutMeComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AboutMeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| mit |
iGusev/phalcon-boilerplate | app/library/Services/Util.php | 3314 | <?php
namespace Lib\Services;
/**
* Internal utility component
*
* @depends service session
* @depends service profiler
*/
class Util extends \Base\Service
{
protected $messages = [];
protected $memory = [
'start' => 0,
'end' => 0 ];
protected $time = [
'start' => 0,
'end' => 0 ];
public function addMessage( $message, $type = SUCCESS )
{
if ( is_array( $message ) )
{
foreach ( $message as $m )
{
$this->messages[] = [ $type => $m ];
}
}
else
{
$this->messages[] = [ $type => $message ];
}
}
public function getMessages()
{
return $this->messages;
}
public function setFlash( $messages )
{
$session = $this->getService( 'session' );
$flash = $session->get( 'flash' );
if ( ! is_array( $flash ) )
{
$flash = [];
}
$flash = array_merge( $flash, $messages );
$session->set( 'flash', $flash );
}
public function getFlash()
{
$session = $this->getService( 'session' );
$flash = $session->get( 'flash' );
$session->remove( 'flash' );
return $flash;
}
public function clearMessages()
{
$this->messages = [];
}
public function startBenchmark()
{
$this->memory[ 'start' ] = memory_get_usage();
$this->time[ 'start' ] = microtime( TRUE );
}
public function stopBenchmark()
{
$this->memory[ 'end' ] = memory_get_usage();
$this->time[ 'end' ] = microtime( TRUE );
}
public function resetBenchmarks()
{
$this->memory = [
'start' => 0,
'end' => 0 ];
$this->time = [
'start' => 0,
'end' => 0 ];
}
public function getMemoryUsage()
{
return $this->memory[ 'end' ] - $this->memory[ 'start' ];
}
public function getPeakMemoryUsage()
{
return memory_get_peak_usage();
}
public function getExecutionTime()
{
return $this->time[ 'end' ] - $this->time[ 'start' ];
}
public function getQueryProfiles()
{
$profiler = $this->getService( 'profiler' );
$profiles = $profiler->getProfiles();
$return = [];
foreach ( (array) $profiles as $profile )
{
$return[] = [
'statement' => $profile->getSQLStatement(),
'start_time' => $profile->getInitialTime(),
'end_time' => $profile->getFinalTime(),
'elapsed_time' => $profile->getTotalElapsedSeconds() ];
}
return $return;
}
public function getDebugInfo()
{
return [
'session_id' => $this->getService( 'session' )->getId(),
'memory' => $this->getMemoryUsage(),
'memory_human' => human_bytes( $this->getMemoryUsage() ),
'peak_memory' => self::getPeakMemoryUsage(),
'peak_memory_human' => human_bytes( $this->getPeakMemoryUsage() ),
'time' => $this->getExecutionTime(),
'time_human' => round( $this->getExecutionTime() * 1000, 2 ) .' ms',
'query_profiles' => $this->getQueryProfiles() ];
}
} | mit |
sourcegraph/srclib-ruby | yard/lib/yard/templates/helpers/markup_helper.rb | 6420 | require 'rubygems'
module YARD
module Templates::Helpers
# Helper methods for loading and managing markup types.
module MarkupHelper
class << self
# Clears the markup provider cache information. Mainly used for testing.
# @return [void]
def clear_markup_cache
self.markup_cache = {}
end
# @return [Hash{Symbol=>{(:provider,:class)=>Object}}] the cached markup providers
# @private
# @since 0.6.4
attr_accessor :markup_cache
end
MarkupHelper.clear_markup_cache
# The default list of markup providers for each markup type
MARKUP_PROVIDERS = {
:markdown => [
{:lib => :redcarpet, :const => 'RedcarpetCompat'},
{:lib => :rdiscount, :const => 'RDiscount'},
{:lib => :kramdown, :const => 'Kramdown::Document'},
{:lib => :bluecloth, :const => 'BlueCloth'},
{:lib => :maruku, :const => 'Maruku'},
{:lib => :'rpeg-markdown', :const => 'PEGMarkdown'},
{:lib => :rdoc, :const => 'YARD::Templates::Helpers::Markup::RDocMarkdown'},
],
:textile => [
{:lib => :redcloth, :const => 'RedCloth'},
],
:textile_strict => [
{:lib => :redcloth, :const => 'RedCloth'},
],
:rdoc => [
{:lib => nil, :const => 'YARD::Templates::Helpers::Markup::RDocMarkup'},
],
:asciidoc => [
{:lib => :asciidoctor, :const => 'Asciidoctor'}
],
:ruby => [],
:text => [],
:pre => [],
:html => [],
:none => [],
}
# Returns a list of extensions for various markup types. To register
# extensions for a type, add them to the array of extensions for the
# type.
# @since 0.6.0
MARKUP_EXTENSIONS = {
:html => ['htm', 'html', 'shtml'],
:text => ['txt'],
:textile => ['textile', 'txtile'],
:asciidoc => ['asciidoc'],
:markdown => ['markdown', 'md', 'mdown', 'mkd'],
:rdoc => ['rdoc'],
:ruby => ['rb', 'ru']
}
# Contains the Regexp object that matches the shebang line of extra
# files to detect the markup type.
MARKUP_FILE_SHEBANG = /\A#!(\S+)\s*$/
# Attempts to load the first valid markup provider in {MARKUP_PROVIDERS}.
# If a provider is specified, immediately try to load it.
#
# On success this sets `@markup_provider` and `@markup_class` to
# the provider name and library constant class/module respectively for
# the loaded provider.
#
# On failure this method will inform the user that no provider could be
# found and exit the program.
#
# @return [Boolean] whether the markup provider was successfully loaded.
def load_markup_provider(type = options.markup)
return true if MarkupHelper.markup_cache[type]
MarkupHelper.markup_cache[type] ||= {}
providers = MARKUP_PROVIDERS[type.to_sym]
return true if providers && providers.empty?
if providers && options.markup_provider
providers = providers.select {|p| p[:lib] == options.markup_provider }
end
if providers == nil || providers.empty?
log.error "Invalid markup type '#{type}' or markup provider " +
"(#{options.markup_provider}) is not registered."
return false
end
# Search for provider, return the library class name as const if found
providers.each do |provider|
begin require provider[:lib].to_s; rescue LoadError; next end if provider[:lib]
begin klass = eval("::" + provider[:const]); rescue NameError; next end
MarkupHelper.markup_cache[type][:provider] = provider[:lib] # Cache the provider
MarkupHelper.markup_cache[type][:class] = klass
return true
end
# Show error message telling user to install first potential provider
name, lib = *[providers.first[:const], providers.first[:lib] || type]
log.error "Missing '#{lib}' gem for #{type.to_s.capitalize} formatting. Install it with `gem install #{lib}`"
false
end
# Checks for a shebang or looks at the file extension to determine
# the markup type for the file contents. File extensions are registered
# for a markup type in {MARKUP_EXTENSIONS}.
#
# A shebang should be on the first line of a file and be in the form:
#
# #!markup_type
#
# Standard markup types are text, html, rdoc, markdown, textile
#
# @param [String] contents Unused. Was necessary prior to 0.7.0.
# Newer versions of YARD use {CodeObjects::ExtraFileObject#contents}
# @return [Symbol] the markup type recognized for the file
# @see MARKUP_EXTENSIONS
# @since 0.6.0
def markup_for_file(contents, filename)
if contents && contents =~ MARKUP_FILE_SHEBANG # Shebang support
return $1.to_sym
end
ext = (File.extname(filename)[1..-1] || '').downcase
MARKUP_EXTENSIONS.each do |type, exts|
return type if exts.include?(ext)
end
options.markup
end
# Strips any shebang lines on the file contents that pertain to
# markup or preprocessing data.
#
# @deprecated Use {CodeObjects::ExtraFileObject#contents} instead
# @return [String] the file contents minus any preprocessing tags
# @since 0.6.0
def markup_file_contents(contents)
contents =~ MARKUP_FILE_SHEBANG ? $' : contents
end
# Gets the markup provider class/module constant for a markup type
# Call {#load_markup_provider} before using this method.
#
# @param [Symbol] type the markup type (:rdoc, :markdown, etc.)
# @return [Class] the markup class
def markup_class(type = options.markup)
load_markup_provider(type)
MarkupHelper.markup_cache[type][:class]
end
# Gets the markup provider name for a markup type
# Call {#load_markup_provider} before using this method.
#
# @param [Symbol] type the markup type (:rdoc, :markdown, etc.)
# @return [Symbol] the markup provider name (usually the gem name of the library)
def markup_provider(type = options.markup)
MarkupHelper.markup_cache[type][:provider]
end
end
end
end
| mit |
angelozerr/typescript.java | eclipse/jsdt/ts.eclipse.ide.jsdt.ui/src/ts/eclipse/ide/jsdt/internal/ui/ITypeScriptThemeConstants.java | 1914 | /**
* Copyright (c) 2015-2016 Angelo ZERR.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Angelo Zerr <[email protected]> - initial API and implementation
*/
package ts.eclipse.ide.jsdt.internal.ui;
import ts.eclipse.ide.jsdt.ui.PreferenceConstants;
/**
* Defines the constants used in the <code>org.eclipse.ui.themes</code>
* extension contributed by this plug-in.
*
*
*/
public interface ITypeScriptThemeConstants {
String ID_PREFIX = JSDTTypeScriptUIPlugin.PLUGIN_ID + "."; //$NON-NLS-1$
/**
* A theme constant that holds the color used to render JSX tag border
* constants.
*/
public final String EDITOR_TYPESCRIPT_DECORATOR_COLOR = ID_PREFIX
+ PreferenceConstants.EDITOR_TYPESCRIPT_DECORATOR_COLOR;
/**
* A theme constant that holds the color used to render JSX tag border
* constants.
*/
public final String EDITOR_JSX_TAG_BORDER_COLOR = ID_PREFIX + PreferenceConstants.EDITOR_JSX_TAG_BORDER_COLOR;
/**
* A theme constant that holds the color used to render JSX tag name
* constants.
*/
public final String EDITOR_JSX_TAG_NAME_COLOR = ID_PREFIX + PreferenceConstants.EDITOR_JSX_TAG_NAME_COLOR;
/**
* A theme constant that holds the color used to render JSX tag attribute
* name constants.
*/
public final String EDITOR_JSX_TAG_ATTRIBUTE_NAME_COLOR = ID_PREFIX
+ PreferenceConstants.EDITOR_JSX_TAG_ATTRIBUTE_NAME_COLOR;
/**
* A theme constant that holds the color used to render JSX tag attribute
* value constants.
*/
public final String EDITOR_JSX_TAG_ATTRIBUTE_VALUE_COLOR = ID_PREFIX
+ PreferenceConstants.EDITOR_JSX_TAG_ATTRIBUTE_VALUE_COLOR;
}
| mit |
glenjamin/react-bootstrap | types/components/ModalTitle.d.ts | 207 | import * as React from 'react';
import { BsPrefixComponent } from './helpers';
declare class ModalTitle<
As extends React.ReactType = 'div'
> extends BsPrefixComponent<As> {}
export default ModalTitle;
| mit |
christinagyles-ea/water | app/v6/views/v25/eo/returns/returns-report-flagged.html | 13147 | {% extends "../head-signedin.html" %}
<!-- page title -->
{% block page_title %}
Licence return for {{ pData.LicenceNumber }} - GOV.UK
{% endblock %}
{% block content %}
<main id="content" role="main">
{% from "custom_inc/waterdata.html" import permits %}
{% for pNumber, pData in permits %}
{% if pNumber==chosenPermitID %}
<!-- beta banner block -->
{% include "../../partials/beta-banner.html" %}
<!-- navigation block -->
{% include "../../partials/nav-eo-manage.html" %}
<div class="grid-row">
<div class="column-two-thirds small-space">
<div class="panel panel-border-wide alert-warning big-space">
You must check this return for compliance
</div>
<!-- page heading -->
{% if pData.LicenceName %}
<h1 class="sub-head">
<a href="returns">Abstraction return for {{ pData.LicenceSerialNo }}</a>
</h1>
<h2 class="heading-large spaceless">
{{ pData.LicenceName }}
</h2>
{% else %}
<h2 class="sub-head">
<a href="returns">Abstraction return</a>
</h2>
<h1 class="heading-large spaceless">
Licence number {{pData.LicenceSerialNo}}
</h1>
{% endif %}
</div>
</div>
<div class="small-space">
<dl>
<dt class="meta-label">
Return reference
</dt>
<dd class="meta-description">
65432123
</dd>
<dt class="meta-label">
Region
</dt>
<dd class="meta-description">
Anglia
</dd>
<dt class="meta-label">
Site description
</dt>
<dd class="meta-description">
Great Ouse at Bedford College (Heat pump - cooling only)
</dd>
<dt class="meta-label">
Purpose
</dt>
<dd class="meta-description">
{{ pData.Purpose1 }}
</dd>
<dt class="meta-label">
Return period
</dt>
<dd class="meta-description">
April 2018 to September 2018
</dd>
</dl>
</div>
<div class="grid-row medium-space">
<div class="column-two-thirds">
<p>
<a href="../online-licence?wid={{ query.wid }}">View this licence</a>
</p>
</div>
</div>
<!-- detect nill return -->
{% if pData.NilReturn %}
<div class="grid-row">
<div class="column-two-thirds">
<h3 class="heading-xlarge">
Nil return
</h3>
<div class="big-space">
<a href="returns-route-return?wid={{ query.wid }}" class="button">Edit return</a>
</div>
</div>
</div>
{% else %}
<div class="grid-row">
<div class="column-two-thirds">
<h3 class="heading-medium small-space">
Abstraction amounts
</h3>
<div class="big-space">
<a href="returns-form?wid={{ query.wid }}" class="button">Edit return</a>
</div>
</div>
</div>
<!-- table starts -->
<div class="table medium-space"> <!-- a table -->
<div class="table-row table-head"> <!-- the table head -->
<div class="table-cell bold-small column-33">
Month
</div>
<div class="table-cell bold-small column-33 numbers">
Litres
</div>
<div class="table-cell bold-small column-33 numbers">
Cubic metres
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
April
</h4>
<h5 class="context">
Month
</h5>
April
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
12,340
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
12.340
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
May
</h4>
<h5 class="context">
Month
</h5>
May
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
9,720
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
9.720
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
June
</h4>
<h5 class="context">
Month
</h5>
June
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
10,040
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
10.040
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
July
</h4>
<h5 class="context">
Month
</h5>
July
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
17,120
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
17.120
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
August
</h4>
<h5 class="context">
Month
</h5>
August
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
2,007
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
2.007
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
September
</h4>
<h5 class="context">
Month
</h5>
September
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
0
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
0
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
October
</h4>
<h5 class="context">
Month
</h5>
October
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
0
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
0
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
November
</h4>
<h5 class="context">
Month
</h5>
November
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
0
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
0
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
December
</h4>
<h5 class="context">
Month
</h5>
December
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
0
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
0
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
January
</h4>
<h5 class="context">
Month
</h5>
January
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
0
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
0
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
February
</h4>
<h5 class="context">
Month
</h5>
February
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
0
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
0
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
March
</h4>
<h5 class="context">
Month
</h5>
March
</div>
<div class="table-cell numbers">
<h5 class="context">
Litres
</h5>
0
</div>
<div class="table-cell numbers">
<h5 class="context">
Cubic metres
</h5>
0
</div>
</div>
<div class="table-row medium-space"> <!-- a data row starts -->
<div class="table-cell">
<h4 class="sr-only">
Total row
</h4>
<h5 class="bold-small">
Total
</h5>
</div>
<div class="table-cell">
<h5 class="context">
Litres
</h5>
<span class="bold-small numbers">
51,227
</span>
</div>
<div class="table-cell numbers">
<h5 class="context">
Total
</h5>
<span class="bold-small">
51.227
</span>
</div>
</div>
</div>
<div class="grid-row medium-space">
<div class="column-two-thirds versions">
<h3 class="heading-medium">
Comments
</h3>
<div class="panel panel-border-wide">
<p>
Last year abstraction was around 30% use. This year use is up to 90%. We should flag this for EOs.
</p>
</div>
</div>
</div>
{% endif %}
<div class="grid-row">
<div class="column-two-thirds versions">
<h3 class="heading-medium">
Submitted by
</h3>
<div class="panel panel-border-wide this-version version">
<p class="version spaceless selected">
<span class="sr-only">This version</span>
[email protected]<br>
<a href="returns-report?wid={{ query.wid }}">11 September 2018</a><br>
</p>
</div>
<div class="version">
<p class="spaceless">
[email protected]<br>
<a href="returns-report-version?wid={{ query.wid }}">02 September 2018</a><br>
</p>
</div>
<div class="version">
<p class="spaceless">
[email protected]<br>
<a href="returns-report-version?wid={{ query.wid }}">30 August 2018</a><br>
</p>
</div>
</div>
</div>
{% endif %}
{% endfor %}
</main>
<script src="/public/v6/javascripts/underscore.min.js"></script>
<script src="/public/v6/javascripts/jquery-1.11.3.js"></script>
<script src="/public/v6/javascripts/license_results.js"></script>
<script>
$(function() {
$('a').parents('.version').addClass('clickable');
// Click on licence list clicks inner link
$('.version').on('click', function (ev) {
window.location.href = $(this).find('a:first').attr('href');
$(this).addClass('active');
ev.preventDefault();
});
});
</script>
{% endblock %}
| mit |
erikcaineolson/HARE | db/seeds/test.rb | 383 | # This file should contain all the record creation to seed the
# TEST database with its default values.
# The data can then be loaded with `$ bundle exec rake db:seed`.
# To create and seed a new database, use `$ bundle exec rake db:setup`.
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
| mit |
githubmoros/myclinicsoft | vendor/google/apiclient-services/src/Google/Service/DeploymentManager/Resource/Deployments.php | 14180 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed 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.
*/
/**
* The "deployments" collection of methods.
* Typical usage is:
* <code>
* $deploymentmanagerService = new Google_Service_DeploymentManager(...);
* $deployments = $deploymentmanagerService->deployments;
* </code>
*/
class Google_Service_DeploymentManager_Resource_Deployments extends Google_Service_Resource
{
/**
* Cancels and removes the preview currently associated with the deployment.
* (deployments.cancelPreview)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param Google_Service_DeploymentManager_DeploymentsCancelPreviewRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Operation
*/
public function cancelPreview($project, $deployment, Google_Service_DeploymentManager_DeploymentsCancelPreviewRequest $postBody, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('cancelPreview', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Deletes a deployment and all of the resources in the deployment.
* (deployments.delete)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param array $optParams Optional parameters.
*
* @opt_param string deletePolicy Sets the policy to use for deleting resources.
* @return Google_Service_DeploymentManager_Operation
*/
public function delete($project, $deployment, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Gets information about a specific deployment. (deployments.get)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Deployment
*/
public function get($project, $deployment, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_DeploymentManager_Deployment");
}
/**
* Gets the access control policy for a resource. May be empty if no such policy
* or resource exists. (deployments.getIamPolicy)
*
* @param string $project Project ID for this request.
* @param string $resource Name of the resource for this request.
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Policy
*/
public function getIamPolicy($project, $resource, $optParams = array())
{
$params = array('project' => $project, 'resource' => $resource);
$params = array_merge($params, $optParams);
return $this->call('getIamPolicy', array($params), "Google_Service_DeploymentManager_Policy");
}
/**
* Creates a deployment and all of the resources described by the deployment
* manifest. (deployments.insert)
*
* @param string $project The project ID for this request.
* @param Google_Service_DeploymentManager_Deployment $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string createPolicy Sets the policy to use for creating new
* resources.
* @opt_param bool preview If set to true, creates a deployment and creates
* "shell" resources but does not actually instantiate these resources. This
* allows you to preview what your deployment looks like. After previewing a
* deployment, you can deploy your resources by making a request with the
* update() method or you can use the cancelPreview() method to cancel the
* preview altogether. Note that the deployment will still exist after you
* cancel the preview and you must separately delete this deployment if you want
* to remove it.
* @return Google_Service_DeploymentManager_Operation
*/
public function insert($project, Google_Service_DeploymentManager_Deployment $postBody, $optParams = array())
{
$params = array('project' => $project, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Lists all deployments for a given project. (deployments.listDeployments)
*
* @param string $project The project ID for this request.
* @param array $optParams Optional parameters.
*
* @opt_param string filter A filter expression that filters resources listed in
* the response. The expression must specify the field name, a comparison
* operator, and the value that you want to use for filtering. The value must be
* a string, a number, or a boolean. The comparison operator must be either =,
* !=, >, or <.
*
* For example, if you are filtering Compute Engine instances, you can exclude
* instances named example-instance by specifying name != example-instance.
*
* You can also filter nested fields. For example, you could specify
* scheduling.automaticRestart = false to include instances only if they are not
* scheduled for automatic restarts. You can use filtering on nested fields to
* filter based on resource labels.
*
* To filter on multiple expressions, provide each separate expression within
* parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform =
* "Intel Skylake"). By default, each expression is an AND expression. However,
* you can include AND and OR expressions explicitly. For example, (cpuPlatform
* = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND
* (scheduling.automaticRestart = true).
* @opt_param string maxResults The maximum number of results per page that
* should be returned. If the number of available results is larger than
* maxResults, Compute Engine returns a nextPageToken that can be used to get
* the next page of results in subsequent list requests. Acceptable values are 0
* to 500, inclusive. (Default: 500)
* @opt_param string orderBy Sorts list results by a certain order. By default,
* results are returned in alphanumerical order based on the resource name.
*
* You can also sort results in descending order based on the creation timestamp
* using orderBy="creationTimestamp desc". This sorts results based on the
* creationTimestamp field in reverse chronological order (newest result first).
* Use this to sort resources like operations so that the newest operation is
* returned first.
*
* Currently, only sorting by name or creationTimestamp desc is supported.
* @opt_param string pageToken Specifies a page token to use. Set pageToken to
* the nextPageToken returned by a previous list request to get the next page of
* results.
* @return Google_Service_DeploymentManager_DeploymentsListResponse
*/
public function listDeployments($project, $optParams = array())
{
$params = array('project' => $project);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_DeploymentManager_DeploymentsListResponse");
}
/**
* Updates a deployment and all of the resources described by the deployment
* manifest. This method supports patch semantics. (deployments.patch)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param Google_Service_DeploymentManager_Deployment $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string createPolicy Sets the policy to use for creating new
* resources.
* @opt_param string deletePolicy Sets the policy to use for deleting resources.
* @opt_param bool preview If set to true, updates the deployment and creates
* and updates the "shell" resources but does not actually alter or instantiate
* these resources. This allows you to preview what your deployment will look
* like. You can use this intent to preview how an update would affect your
* deployment. You must provide a target.config with a configuration if this is
* set to true. After previewing a deployment, you can deploy your resources by
* making a request with the update() or you can cancelPreview() to remove the
* preview altogether. Note that the deployment will still exist after you
* cancel the preview and you must separately delete this deployment if you want
* to remove it.
* @return Google_Service_DeploymentManager_Operation
*/
public function patch($project, $deployment, Google_Service_DeploymentManager_Deployment $postBody, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Sets the access control policy on the specified resource. Replaces any
* existing policy. (deployments.setIamPolicy)
*
* @param string $project Project ID for this request.
* @param string $resource Name of the resource for this request.
* @param Google_Service_DeploymentManager_Policy $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Policy
*/
public function setIamPolicy($project, $resource, Google_Service_DeploymentManager_Policy $postBody, $optParams = array())
{
$params = array('project' => $project, 'resource' => $resource, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('setIamPolicy', array($params), "Google_Service_DeploymentManager_Policy");
}
/**
* Stops an ongoing operation. This does not roll back any work that has already
* been completed, but prevents any new work from being started.
* (deployments.stop)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param Google_Service_DeploymentManager_DeploymentsStopRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_Operation
*/
public function stop($project, $deployment, Google_Service_DeploymentManager_DeploymentsStopRequest $postBody, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('stop', array($params), "Google_Service_DeploymentManager_Operation");
}
/**
* Returns permissions that a caller has on the specified resource.
* (deployments.testIamPermissions)
*
* @param string $project Project ID for this request.
* @param string $resource Name of the resource for this request.
* @param Google_Service_DeploymentManager_TestPermissionsRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_DeploymentManager_TestPermissionsResponse
*/
public function testIamPermissions($project, $resource, Google_Service_DeploymentManager_TestPermissionsRequest $postBody, $optParams = array())
{
$params = array('project' => $project, 'resource' => $resource, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('testIamPermissions', array($params), "Google_Service_DeploymentManager_TestPermissionsResponse");
}
/**
* Updates a deployment and all of the resources described by the deployment
* manifest. (deployments.update)
*
* @param string $project The project ID for this request.
* @param string $deployment The name of the deployment for this request.
* @param Google_Service_DeploymentManager_Deployment $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string createPolicy Sets the policy to use for creating new
* resources.
* @opt_param string deletePolicy Sets the policy to use for deleting resources.
* @opt_param bool preview If set to true, updates the deployment and creates
* and updates the "shell" resources but does not actually alter or instantiate
* these resources. This allows you to preview what your deployment will look
* like. You can use this intent to preview how an update would affect your
* deployment. You must provide a target.config with a configuration if this is
* set to true. After previewing a deployment, you can deploy your resources by
* making a request with the update() or you can cancelPreview() to remove the
* preview altogether. Note that the deployment will still exist after you
* cancel the preview and you must separately delete this deployment if you want
* to remove it.
* @return Google_Service_DeploymentManager_Operation
*/
public function update($project, $deployment, Google_Service_DeploymentManager_Deployment $postBody, $optParams = array())
{
$params = array('project' => $project, 'deployment' => $deployment, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_DeploymentManager_Operation");
}
}
| mit |
tmcgee/cmv-wab-widgets | wab/2.15/widgets/BasemapGallery/setting/nls/pt-br/strings.js | 1850 | define({
"showArcgisBasemaps": "Incluir mapas base do Portal",
"add": "Clique para adicionar um novo mapa base",
"edit": "Propriedades",
"titlePH": "Título do mapa base",
"thumbnailHint": "Clique na imagem para atualizar",
"urlPH": "URL da Camada",
"addlayer": "Adicionar mapa base",
"warning": "Entrada incorreta",
"save": "Voltar e salvar",
"back": "Voltar e cancelar",
"addUrl": "Adicionar URL",
"autoCheck": "Verificação automática",
"checking": "Verificando...",
"result": "Salvo com sucesso",
"spError": "Todo os mapas base adicionados na galeria precisam ter a mesma referência espacial.",
"invalidTitle1": "Um mapa base '",
"invalidTitle2": "‘ já existe. Escolha outro título.",
"invalidBasemapUrl1": "Este tipo de camada não pode ser utilizada como um mapa base.",
"invalidBasemapUrl2": "O mapa base que você está adicionando tem uma referência espacial diferente do mapa atual.",
"addBaselayer": "Adicionar camada de mapa base",
"repectOnline": "Sempre sincronizar com a configuração da Galeria de Mapa Base da organização",
"customBasemap": "Configurar mapas base personalizados",
"basemapTips": "Clique em \"${import}\" ou \"${createNew}\" para adicionar maps base.",
"importBasemap": "Importar",
"createBasemap": "Criar novo",
"importTitle": "Importar mapas base",
"createTitle": "Novo mapa base",
"selectGroupTip": "Seleciona um grupo cujo mapas da web podem ser utilizados como mapas base.",
"noBasemaps": "Nenhum mapa base.",
"defaultGroup": "Padrão Esri",
"defaultOrgGroup": "Organização padrão",
"warningTitle": "Aviso",
"confirmDelete": "Deseja excluir os mapas base selecionados?",
"noBasemapAvailable": "Não há mapas base disponíveis, pois todos os mapas base têm referência espacial ou esquema de mosaico diferente do mapa atual."
}); | mit |
vgno/roc-config | test/validation/validators/isFunction.js | 1209 | import expect from 'expect';
import isFunction from '../../../src/validation/validators/isFunction';
describe('validators', () => {
describe('toFunction', () => {
it('should return infoObject if requested', () => {
expect(isFunction(null, true))
.toEqual({
type: 'Function',
required: false,
canBeEmpty: null,
converter: undefined,
unmanagedObject: false,
});
});
it('should validate a function correctly', () => {
expect(isFunction(() => {}))
.toBe(true);
});
it('should validate a function correctly when undefined', () => {
expect(isFunction(undefined))
.toBe(true);
});
it('should return error if value is not a function', () => {
expect(isFunction(1))
.toInclude('not a function');
});
it('should allow undefined and null', () => {
expect(isFunction(null))
.toBe(true);
expect(isFunction(undefined))
.toBe(true);
});
});
});
| mit |
Anvesh-Reddy/Pinger | PingerAPI/PingerAPI/Controllers/TaskController.cs | 2814 | using DomainModel.DTO;
using DomainModel.Enum;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Web.Http;
namespace PingerAPI.Controllers
{
public class TaskController : ApiController
{
[HttpPost]
public async Task<List<TaskDTO>> CheckTaskStatus(List<TaskDTO> list)
{
foreach (var item in list)
{
switch (item.TaskType)
{
case (int)TaskTypeEnum.WebSite:
await CheckWebsiteStatus(item);
break;
case (int)TaskTypeEnum.Server:
await CheckServerNDBStatus(item);
break;
case (int)TaskTypeEnum.Database:
await CheckServerNDBStatus(item);
break;
default:
break;
}
}
return list;
}
private async Task<bool> CheckWebsiteStatus(TaskDTO obj)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create((obj.Entity.IndexOf("://") == -1) ?
"http://" + obj.Entity : obj.Entity);
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
if (obj.PreviousState != (int)TaskStatusEnum.Alive)
{
obj.UpdatedState = (int)TaskStatusEnum.Alive;
}
}
}
return true;
}
catch
{
}
if (obj.PreviousState != (int)TaskStatusEnum.Dead)
{
obj.UpdatedState = (int)TaskStatusEnum.Dead;
}
return true;
}
private async Task<bool> CheckServerNDBStatus(TaskDTO obj)
{
try
{
string[] list = obj.Entity.Split(':');
TcpClient client = new TcpClient();
await client.ConnectAsync(list[0], Convert.ToInt32(list[1]));
if (obj.PreviousState != (int)TaskStatusEnum.Alive)
{
obj.UpdatedState = (int)TaskStatusEnum.Alive;
}
return true;
}
catch
{
}
if (obj.PreviousState != (int)TaskStatusEnum.Dead)
{
obj.UpdatedState = (int)TaskStatusEnum.Dead;
}
return true;
}
}
} | mit |
kardeiz/fop_wrapper | vendor/fop-1.1/javadocs/org/apache/fop/pdf/NullFilter.html | 14026 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 16 22:49:44 ICT 2012 -->
<TITLE>
NullFilter (Apache FOP 1.1 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-16">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="NullFilter (Apache FOP 1.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NullFilter.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/apache/fop/pdf/InMemoryStreamCache.html" title="class in org.apache.fop.pdf"><B>PREV CLASS</B></A>
<A HREF="../../../../org/apache/fop/pdf/ObjectStream.html" title="class in org.apache.fop.pdf"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/apache/fop/pdf/NullFilter.html" target="_top"><B>FRAMES</B></A>
<A HREF="NullFilter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.apache.fop.pdf</FONT>
<BR>
Class NullFilter</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../org/apache/fop/pdf/PDFFilter.html" title="class in org.apache.fop.pdf">org.apache.fop.pdf.PDFFilter</A>
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.fop.pdf.NullFilter</B>
</PRE>
<DL>
<DT><B>Direct Known Subclasses:</B> <DD><A HREF="../../../../org/apache/fop/pdf/CCFFilter.html" title="class in org.apache.fop.pdf">CCFFilter</A>, <A HREF="../../../../org/apache/fop/pdf/DCTFilter.html" title="class in org.apache.fop.pdf">DCTFilter</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>NullFilter</B><DT>extends <A HREF="../../../../org/apache/fop/pdf/PDFFilter.html" title="class in org.apache.fop.pdf">PDFFilter</A></DL>
</PRE>
<P>
Null Filter class. The content is just passed through. The class is used to
override the default Flate filter for debugging purposes.
<P>
<P>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/NullFilter.html#NullFilter()">NullFilter</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.io.OutputStream</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/NullFilter.html#applyFilter(java.io.OutputStream)">applyFilter</A></B>(java.io.OutputStream out)</CODE>
<BR>
Applies a filter to an OutputStream.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../org/apache/fop/pdf/PDFObject.html" title="class in org.apache.fop.pdf">PDFObject</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/NullFilter.html#getDecodeParms()">getDecodeParms</A></B>()</CODE>
<BR>
return a parameter dictionary for this filter, or null</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/fop/pdf/NullFilter.html#getName()">getName</A></B>()</CODE>
<BR>
return a PDF string representation of the filter, e.g.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_org.apache.fop.pdf.PDFFilter"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class org.apache.fop.pdf.<A HREF="../../../../org/apache/fop/pdf/PDFFilter.html" title="class in org.apache.fop.pdf">PDFFilter</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../org/apache/fop/pdf/PDFFilter.html#isApplied()">isApplied</A>, <A HREF="../../../../org/apache/fop/pdf/PDFFilter.html#isASCIIFilter()">isASCIIFilter</A>, <A HREF="../../../../org/apache/fop/pdf/PDFFilter.html#setApplied(boolean)">setApplied</A></CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="NullFilter()"><!-- --></A><H3>
NullFilter</H3>
<PRE>
public <B>NullFilter</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getName()"><!-- --></A><H3>
getName</H3>
<PRE>
public java.lang.String <B>getName</B>()</PRE>
<DL>
<DD>return a PDF string representation of the filter, e.g. /FlateDecode
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../org/apache/fop/pdf/PDFFilter.html#getName()">getName</A></CODE> in class <CODE><A HREF="../../../../org/apache/fop/pdf/PDFFilter.html" title="class in org.apache.fop.pdf">PDFFilter</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the filter PDF name</DL>
</DD>
</DL>
<HR>
<A NAME="getDecodeParms()"><!-- --></A><H3>
getDecodeParms</H3>
<PRE>
public <A HREF="../../../../org/apache/fop/pdf/PDFObject.html" title="class in org.apache.fop.pdf">PDFObject</A> <B>getDecodeParms</B>()</PRE>
<DL>
<DD>return a parameter dictionary for this filter, or null
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../org/apache/fop/pdf/PDFFilter.html#getDecodeParms()">getDecodeParms</A></CODE> in class <CODE><A HREF="../../../../org/apache/fop/pdf/PDFFilter.html" title="class in org.apache.fop.pdf">PDFFilter</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the decode params for the filter</DL>
</DD>
</DL>
<HR>
<A NAME="applyFilter(java.io.OutputStream)"><!-- --></A><H3>
applyFilter</H3>
<PRE>
public java.io.OutputStream <B>applyFilter</B>(java.io.OutputStream out)
throws java.io.IOException</PRE>
<DL>
<DD>Applies a filter to an OutputStream.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../org/apache/fop/pdf/PDFFilter.html#applyFilter(java.io.OutputStream)">applyFilter</A></CODE> in class <CODE><A HREF="../../../../org/apache/fop/pdf/PDFFilter.html" title="class in org.apache.fop.pdf">PDFFilter</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>out</CODE> - contents to be filtered
<DT><B>Returns:</B><DD>OutputStream filtered contents
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE> - In case of an I/O problem</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NullFilter.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/apache/fop/pdf/InMemoryStreamCache.html" title="class in org.apache.fop.pdf"><B>PREV CLASS</B></A>
<A HREF="../../../../org/apache/fop/pdf/ObjectStream.html" title="class in org.apache.fop.pdf"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/apache/fop/pdf/NullFilter.html" target="_top"><B>FRAMES</B></A>
<A HREF="NullFilter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| mit |
MSylvia/feeds | Website/js/jquery.activity-indicator-1.0.1.js | 6993 | /*!
* NETEYE Activity Indicator jQuery Plugin
*
* Copyright (c) 2010 NETEYE GmbH
* Licensed under the MIT license
*
* Author: Felix Gnass [fgnass at neteye dot de]
* Version: 1.0.0
*/
/**
* Plugin that renders a customisable activity indicator (spinner) using SVG or VML.
*/
(function($) {
$.fn.activity = function(opts) {
this.each(function() {
var $this = $(this);
var el = $this.data('activity');
if (el) {
clearInterval(el.data('interval'));
el.remove();
$this.removeData('activity');
}
if (opts !== false) {
opts = $.extend({color: $this.css('color')}, $.fn.activity.defaults, opts);
el = render($this, opts).css('position', 'absolute').prependTo(opts.outside ? 'body' : $this);
var h = $this.outerHeight() - el.height();
var w = $this.outerWidth() - el.width();
var margin = {
top: opts.valign == 'top' ? opts.padding : opts.valign == 'bottom' ? h - opts.padding : Math.floor(h / 2),
left: opts.align == 'left' ? opts.padding : opts.align == 'right' ? w - opts.padding : Math.floor(w / 2)
};
var offset = $this.offset();
if (opts.outside) {
el.css({top: offset.top + 'px', left: offset.left + 'px'});
}
else {
margin.top -= el.offset().top - offset.top;
margin.left -= el.offset().left - offset.left;
}
el.css({marginTop: margin.top + 'px', marginLeft: margin.left + 'px'});
animate(el, opts.segments, Math.round(10 / opts.speed) / 10);
$this.data('activity', el);
}
});
return this;
};
$.fn.activity.defaults = {
segments: 12,
space: 3,
length: 7,
width: 4,
speed: 1.2,
align: 'center',
valign: 'center',
padding: 4
};
$.fn.activity.getOpacity = function(opts, i) {
var steps = opts.steps || opts.segments-1;
var end = opts.opacity !== undefined ? opts.opacity : 1/steps;
return 1 - Math.min(i, steps) * (1 - end) / steps;
};
/**
* Default rendering strategy. If neither SVG nor VML is available, a div with class-name 'busy'
* is inserted, that can be styled with CSS to display an animated gif as fallback.
*/
var render = function() {
return $('<div>').addClass('busy');
};
/**
* The default animation strategy does nothing as we expect an animated gif as fallback.
*/
var animate = function() {
};
/**
* Utility function to create elements in the SVG namespace.
*/
function svg(tag, attr) {
var el = document.createElementNS("http://www.w3.org/2000/svg", tag || 'svg');
if (attr) {
$.each(attr, function(k, v) {
el.setAttributeNS(null, k, v);
});
}
return $(el);
}
if (document.createElementNS && document.createElementNS( "http://www.w3.org/2000/svg", "svg").createSVGRect) {
// =======================================================================================
// SVG Rendering
// =======================================================================================
/**
* Rendering strategy that creates a SVG tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var el = svg().width(r*2).height(r*2);
var g = svg('g', {
'stroke-width': d.width,
'stroke-linecap': 'round',
stroke: d.color
}).appendTo(svg('g', {transform: 'translate('+ r +','+ r +')'}).appendTo(el));
for (var i = 0; i < d.segments; i++) {
g.append(svg('line', {
x1: 0,
y1: innerRadius,
x2: 0,
y2: innerRadius + d.length,
transform: 'rotate(' + (360 / d.segments * i) + ', 0, 0)',
opacity: $.fn.activity.getOpacity(d, i)
}));
}
return $('<div>').append(el).width(2*r).height(2*r);
};
// Check if Webkit CSS animations are available, as they work much better on the iPad
// than setTimeout() based animations.
if (document.createElement('div').style.WebkitAnimationName !== undefined) {
var animations = {};
/**
* Animation strategy that uses dynamically created CSS animation rules.
*/
animate = function(el, steps, duration) {
if (!animations[steps]) {
var name = 'spin' + steps;
var rule = '@-webkit-keyframes '+ name +' {';
for (var i=0; i < steps; i++) {
var p1 = Math.round(100000 / steps * i) / 1000;
var p2 = Math.round(100000 / steps * (i+1) - 1) / 1000;
var value = '% { -webkit-transform:rotate(' + Math.round(360 / steps * i) + 'deg); }\n';
rule += p1 + value + p2 + value;
}
rule += '100% { -webkit-transform:rotate(100deg); }\n}';
document.styleSheets[0].insertRule(rule,document.styleSheets[0].cssRules.length-1);
animations[steps] = name;
}
el.css('-webkit-animation', animations[steps] + ' ' + duration +'s linear infinite');
};
}
else {
/**
* Animation strategy that transforms a SVG element using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.find('g g').get(0);
el.data('interval', setInterval(function() {
g.setAttributeNS(null, 'transform', 'rotate(' + (++rotation % steps * (360 / steps)) + ')');
}, duration * 1000 / steps));
};
}
}
else {
// =======================================================================================
// VML Rendering
// =======================================================================================
var s = $('<shape>').css('behavior', 'url(#default#VML)').appendTo('body');
if (s.get(0).adj) {
// VML support detected. Insert CSS rules for group, shape and stroke.
var sheet = document.createStyleSheet();
$.each(['group', 'shape', 'stroke'], function() {
sheet.addRule(this, "behavior:url(#default#VML);");
});
/**
* Rendering strategy that creates a VML tree.
*/
render = function(target, d) {
var innerRadius = d.width*2 + d.space;
var r = (innerRadius + d.length + Math.ceil(d.width / 2) + 1);
var s = r*2;
var o = -Math.ceil(s/2);
var el = $('<group>', {coordsize: s + ' ' + s, coordorigin: o + ' ' + o}).css({top: o, left: o, width: s, height: s});
for (var i = 0; i < d.segments; i++) {
el.append($('<shape>', {path: 'm ' + innerRadius + ',0 l ' + (innerRadius + d.length) + ',0'}).css({
width: s,
height: s,
rotation: (360 / d.segments * i) + 'deg'
}).append($('<stroke>', {color: d.color, weight: d.width + 'px', endcap: 'round', opacity: $.fn.activity.getOpacity(d, i)})));
}
return $('<group>', {coordsize: s + ' ' + s}).css({width: s, height: s, overflow: 'hidden'}).append(el);
};
/**
* Animation strategy that modifies the VML rotation property using setInterval().
*/
animate = function(el, steps, duration) {
var rotation = 0;
var g = el.get(0);
el.data('interval', setInterval(function() {
g.style.rotation = ++rotation % steps * (360 / steps);
}, duration * 1000 / steps));
};
}
$(s).remove();
}
})(jQuery);
| mit |
minhnguyen-balance/oro_platform | web/bundles/oroaddress/js/mapservice/googlemaps.js | 5828 | /* jshint browser:true */
/* global define, google */
define(['underscore', 'backbone', 'oro/translator'],
function(_, Backbone, __) {
'use strict';
var $ = Backbone.$;
/**
* @export oro/mapservice/googlemaps
* @class oro.mapservice.Googlemaps
* @extends Backbone.View
*/
return Backbone.View.extend({
options: {
mapOptions: {
zoom: 17,
mapTypeControl: true,
panControl: false,
zoomControl: true
},
apiVersion: '3.exp',
sensor: false,
apiKey: null,
showWeather: true
},
mapLocationCache: {},
mapsLoadExecuted: false,
initialize: function() {
this.$mapContainer = $('<div class="map-visual"/>')
.appendTo(this.$el);
this.$unknownAddress = $('<div class="map-unknown">' + __('map.unknown.location') + '</div>')
.appendTo(this.$el);
this.mapLocationUnknown();
},
_initMapOptions: function() {
if (_.isUndefined(this.options.mapOptions.mapTypeControlOptions)) {
this.options.mapOptions.mapTypeControlOptions = {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
};
}
if (_.isUndefined(this.options.mapOptions.zoomControlOptions)) {
this.options.mapOptions.zoomControlOptions = {
style: google.maps.ZoomControlStyle.SMALL
};
}
if (_.isUndefined(this.options.mapOptions.mapTypeId)) {
this.options.mapOptions.mapTypeId = google.maps.MapTypeId.ROADMAP;
}
},
_initMap: function(location) {
this._initMapOptions();
this.map = new google.maps.Map(
this.$mapContainer[0],
_.extend({}, this.options.mapOptions, {center: location})
);
this.mapLocationMarker = new google.maps.Marker({
draggable: false,
map: this.map,
position: location
});
if (this.options.showWeather) {
var weatherLayer = new google.maps.weather.WeatherLayer();
weatherLayer.setMap(this.map);
var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(this.map);
}
},
loadGoogleMaps: function() {
var googleMapsSettings = 'sensor=' + (this.options.sensor ? 'true' : 'false');
if (this.options.showWeather) {
googleMapsSettings += '&libraries=weather';
}
if (this.options.apiKey) {
googleMapsSettings += '&key=' + this.options.apiKey;
}
$.ajax({
url: window.location.protocol + "//www.google.com/jsapi",
dataType: "script",
cache: true,
success: _.bind(function() {
google.load('maps', this.options.apiVersion, {
other_params: googleMapsSettings,
callback: _.bind(this.onGoogleMapsInit, this)
});
}, this)
});
},
updateMap: function(address, label) {
// Load google maps js
if (!this.hasGoogleMaps() && !this.mapsLoadExecuted) {
this.mapsLoadExecuted = true;
this.requestedLocation = {
'address': address,
'label': label
};
this.loadGoogleMaps();
return;
}
if (this.mapLocationCache.hasOwnProperty(address)) {
this.updateMapLocation(this.mapLocationCache[address], label);
} else {
this.getGeocoder().geocode({'address': address}, _.bind(function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
this.mapLocationCache[address] = results[0].geometry.location;
//Move location marker and map center to new coordinates
this.updateMapLocation(results[0].geometry.location, label);
} else {
this.mapLocationUnknown();
}
}, this));
}
},
onGoogleMapsInit: function() {
if (!_.isUndefined(this.requestedLocation)) {
this.updateMap(this.requestedLocation.address, this.requestedLocation.label);
delete this.requestedLocation;
}
},
hasGoogleMaps: function() {
return !_.isUndefined(window.google) && google.hasOwnProperty('maps');
},
mapLocationUnknown: function() {
this.$mapContainer.hide();
this.$unknownAddress.show();
},
mapLocationKnown: function() {
this.$mapContainer.show();
this.$unknownAddress.hide();
},
updateMapLocation: function(location, label) {
this.mapLocationKnown();
if (location && (!this.location || location.toString() !== this.location.toString())) {
this._initMap(location);
this.map.setCenter(location);
this.mapLocationMarker.setPosition(location);
this.mapLocationMarker.setTitle(label);
this.location = location;
}
},
getGeocoder: function() {
if (_.isUndefined(this.geocoder)) {
this.geocoder = new google.maps.Geocoder();
}
return this.geocoder;
}
});
});
| mit |
georgemarshall/DefinitelyTyped | types/temp/index.d.ts | 1426 | // Type definitions for temp 0.9
// Project: https://github.com/bruce/node-temp
// Definitions by: Daniel Rosenwasser <https://github.com/DanielRosenwasser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import * as fs from "fs";
declare namespace temp {
interface OpenFile {
path: string;
fd: number;
}
interface Stats {
files: number;
dirs: number;
}
interface AffixOptions {
prefix?: string;
suffix?: string;
dir?: string;
}
let dir: string;
function track(value?: boolean): typeof temp;
function mkdir(affixes: string | AffixOptions | undefined, callback: (err: any, dirPath: string) => void): void;
function mkdir(affixes?: string | AffixOptions): Promise<string>;
function mkdirSync(affixes?: string | AffixOptions): string;
function open(affixes: string | AffixOptions | undefined, callback: (err: any, result: OpenFile) => void): void;
function open(affixes?: string | AffixOptions): Promise<OpenFile>;
function openSync(affixes?: string | AffixOptions): OpenFile;
function path(affixes?: string | AffixOptions, defaultPrefix?: string): string;
function cleanup(callback: (err: any, result: Stats) => void): void;
function cleanup(): Promise<Stats>;
function cleanupSync(): boolean | Stats;
function createWriteStream(affixes?: string | AffixOptions): fs.WriteStream;
}
export = temp;
| mit |
yinchunlong/abelkhan-1 | ext/c++/thirdpart/c++/boost/libs/asio/doc/html/boost_asio/reference/basic_io_object/basic_io_object.html | 4724 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_io_object::basic_io_object</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_io_object.html" title="basic_io_object">
<link rel="prev" href="../basic_io_object.html" title="basic_io_object">
<link rel="next" href="basic_io_object/overload1.html" title="basic_io_object::basic_io_object (1 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../basic_io_object.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_io_object.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="basic_io_object/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_io_object.basic_io_object"></a><a class="link" href="basic_io_object.html" title="basic_io_object::basic_io_object">basic_io_object::basic_io_object</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idp30317520"></a>
Construct a <a class="link" href="../basic_io_object.html" title="basic_io_object"><code class="computeroutput"><span class="identifier">basic_io_object</span></code></a>.
</p>
<pre class="programlisting"><span class="keyword">explicit</span> <a class="link" href="basic_io_object/overload1.html" title="basic_io_object::basic_io_object (1 of 2 overloads)">basic_io_object</a><span class="special">(</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span> <span class="special">&</span> <span class="identifier">io_service</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="basic_io_object/overload1.html" title="basic_io_object::basic_io_object (1 of 2 overloads)">more...</a></em></span>
</pre>
<p>
Move-construct a <a class="link" href="../basic_io_object.html" title="basic_io_object"><code class="computeroutput"><span class="identifier">basic_io_object</span></code></a>.
</p>
<pre class="programlisting"><a class="link" href="basic_io_object/overload2.html" title="basic_io_object::basic_io_object (2 of 2 overloads)">basic_io_object</a><span class="special">(</span>
<span class="identifier">basic_io_object</span> <span class="special">&&</span> <span class="identifier">other</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="basic_io_object/overload2.html" title="basic_io_object::basic_io_object (2 of 2 overloads)">more...</a></em></span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../basic_io_object.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_io_object.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="basic_io_object/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
okfn/product-browser-android | src/org/okfn/pod/IntentIntegrator.java | 16341 | /*
* Copyright 2009 ZXing authors
*
* Licensed 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.okfn.pod;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
/**
* <p>A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple
* way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the
* project's source code.</p>
*
* <h2>Initiating a barcode scan</h2>
*
* <p>To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()} and wait
* for the result in your app.</p>
*
* <p>It does require that the Barcode Scanner (or work-alike) application is installed. The
* {@link #initiateScan()} method will prompt the user to download the application, if needed.</p>
*
* <p>There are a few steps to using this integration. First, your {@link Activity} must implement
* the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:</p>
*
* <pre>{@code
* public void onActivityResult(int requestCode, int resultCode, Intent intent) {
* IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
* if (scanResult != null) {
* // handle scan result
* }
* // else continue with any other code you need in the method
* ...
* }
* }</pre>
*
* <p>This is where you will handle a scan result.</p>
*
* <p>Second, just call this in response to a user action somewhere to begin the scan process:</p>
*
* <pre>{@code
* IntentIntegrator integrator = new IntentIntegrator(yourActivity);
* integrator.initiateScan();
* }</pre>
*
* <p>Note that {@link #initiateScan()} returns an {@link AlertDialog} which is non-null if the
* user was prompted to download the application. This lets the calling app potentially manage the dialog.
* In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()}
* method.</p>
*
* <p>You can use {@link #setTitle(String)} to customize the title of this download prompt dialog (or, use
* {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message, and
* yes/no button labels can be changed.</p>
*
* <p>Finally, you can use {@link #addExtra(String, Object)} to add more parameters to the Intent used
* to invoke the scanner. This can be used to set additional options not directly exposed by this
* simplified API.</p>
*
* <p>By default, this will only allow applications that are known to respond to this intent correctly
* do so. The apps that are allowed to response can be set with {@link #setTargetApplications(List)}.
* For example, set to {@link #TARGET_BARCODE_SCANNER_ONLY} to only target the Barcode Scanner app itself.</p>
*
* <h2>Sharing text via barcode</h2>
*
* <p>To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(CharSequence)}.</p>
*
* <p>Some code, particularly download integration, was contributed from the Anobiit application.</p>
*
* <h2>Enabling experimental barcode formats</h2>
*
* <p>Some formats are not enabled by default even when scanning with {@link #ALL_CODE_TYPES}, such as
* PDF417. Use {@link #initiateScan(java.util.Collection)} with
* a collection containing the names of formats to scan for explicitly, like "PDF_417", to use such
* formats.</p>
*
* @author Sean Owen
* @author Fred Lin
* @author Isaac Potoczny-Jones
* @author Brad Drehmer
* @author gcstang
*/
public class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE =
"This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
// private static final String BS_PACKAGE = "com.google.zxing.client.android";
// private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
private static final String BSPLUS_PACKAGE = "com.google.zxing.client.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES =
list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE);
public static final List<String> TARGET_ALL_KNOWN = list(
BSPLUS_PACKAGE, // Barcode Scanner+
BSPLUS_PACKAGE + ".simple", // Barcode Scanner+ Simple
BS_PACKAGE // Barcode Scanner
// What else supports this intent?
);
private final Activity activity;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private List<String> targetApplications;
private final Map<String,Object> moreExtras;
public IntentIntegrator(Activity activity) {
this.activity = activity;
title = DEFAULT_TITLE;
message = DEFAULT_MESSAGE;
buttonYes = DEFAULT_YES;
buttonNo = DEFAULT_NO;
targetApplications = TARGET_ALL_KNOWN;
moreExtras = new HashMap<String,Object>(3);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleByID(int titleID) {
title = activity.getString(titleID);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessageByID(int messageID) {
message = activity.getString(messageID);
}
public String getButtonYes() {
return buttonYes;
}
public void setButtonYes(String buttonYes) {
this.buttonYes = buttonYes;
}
public void setButtonYesByID(int buttonYesID) {
buttonYes = activity.getString(buttonYesID);
}
public String getButtonNo() {
return buttonNo;
}
public void setButtonNo(String buttonNo) {
this.buttonNo = buttonNo;
}
public void setButtonNoByID(int buttonNoID) {
buttonNo = activity.getString(buttonNoID);
}
public Collection<String> getTargetApplications() {
return targetApplications;
}
public final void setTargetApplications(List<String> targetApplications) {
if (targetApplications.isEmpty()) {
throw new IllegalArgumentException("No target applications");
}
this.targetApplications = targetApplications;
}
public void setSingleTargetApplication(String targetApplication) {
this.targetApplications = Collections.singletonList(targetApplication);
}
public Map<String,?> getMoreExtras() {
return moreExtras;
}
public final void addExtra(String key, Object value) {
moreExtras.put(key, value);
}
/**
* Initiates a scan for all known barcode types.
*/
public final AlertDialog initiateScan() {
return initiateScan(ALL_CODE_TYPES);
}
/**
* Initiates a scan only for a certain set of barcode types, given as strings corresponding
* to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
* like {@link #PRODUCT_CODE_TYPES} for example.
*
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
* if a prompt was needed, or null otherwise
*/
public final AlertDialog initiateScan(Collection<String> desiredBarcodeFormats) {
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// check which types of codes to scan for
if (desiredBarcodeFormats != null) {
// set the desired barcode types
StringBuilder joinedByComma = new StringBuilder();
for (String format : desiredBarcodeFormats) {
if (joinedByComma.length() > 0) {
joinedByComma.append(',');
}
joinedByComma.append(format);
}
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
}
String targetAppPackage = findTargetAppPackage(intentScan);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intentScan);
startActivityForResult(intentScan, REQUEST_CODE);
return null;
}
/**
* Start an activity. This method is defined to allow different methods of activity starting for
* newer versions of Android and for compatibility library.
*
* @param intent Intent to start.
* @param code Request code for the activity
* @see android.app.Activity#startActivityForResult(Intent, int)
* @see android.app.Fragment#startActivityForResult(Intent, int)
*/
protected void startActivityForResult(Intent intent, int code) {
activity.startActivityForResult(intent, code);
}
private String findTargetAppPackage(Intent intent) {
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (availableApps != null) {
for (String targetApp : targetApplications) {
if (contains(availableApps, targetApp)) {
return targetApp;
}
}
}
return null;
}
private static boolean contains(Iterable<ResolveInfo> availableApps, String targetApp) {
for (ResolveInfo availableApp : availableApps) {
String packageName = availableApp.activityInfo.packageName;
if (targetApp.equals(packageName)) {
return true;
}
}
return false;
}
private AlertDialog showDownloadDialog() {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String packageName = targetApplications.get(0);
Uri uri = Uri.parse("market://details?id=" + packageName);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
// Hmm, market is not installed
Log.w(TAG, "Google Play is not installed; cannot install " + packageName);
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
});
return downloadDialog.show();
}
/**
* <p>Call this from your {@link Activity}'s
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
*
* @return null if the event handled here was not related to this class, or
* else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
* the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
/**
* Defaults to type "TEXT_TYPE".
* @see #shareText(CharSequence, CharSequence)
*/
public final AlertDialog shareText(CharSequence text) {
return shareText(text, "TEXT_TYPE");
}
/**
* Shares the given text by encoding it as a barcode, such that another user can
* scan the text off the screen of the device.
*
* @param text the text string to encode as a barcode
* @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
* if a prompt was needed, or null otherwise
*/
public final AlertDialog shareText(CharSequence text, CharSequence type) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", type);
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intent);
activity.startActivity(intent);
return null;
}
private static List<String> list(String... values) {
return Collections.unmodifiableList(Arrays.asList(values));
}
private void attachMoreExtras(Intent intent) {
for (Map.Entry<String,Object> entry : moreExtras.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// Kind of hacky
if (value instanceof Integer) {
intent.putExtra(key, (Integer) value);
} else if (value instanceof Long) {
intent.putExtra(key, (Long) value);
} else if (value instanceof Boolean) {
intent.putExtra(key, (Boolean) value);
} else if (value instanceof Double) {
intent.putExtra(key, (Double) value);
} else if (value instanceof Float) {
intent.putExtra(key, (Float) value);
} else if (value instanceof Bundle) {
intent.putExtra(key, (Bundle) value);
} else {
intent.putExtra(key, value.toString());
}
}
}
}
| mit |
yinchunlong/abelkhan-1 | ext/c++/thirdpart/c++/boost/libs/intrusive/doc/html/boost/intrusive/unordered_set.html | 126310 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class template unordered_set</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Intrusive">
<link rel="up" href="../../intrusive/reference.html#header.boost.intrusive.unordered_set_hpp" title="Header <boost/intrusive/unordered_set.hpp>">
<link rel="prev" href="trivial_value_traits.html" title="Struct template trivial_value_traits">
<link rel="next" href="make_unordered_set.html" title="Struct template make_unordered_set">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="trivial_value_traits.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../intrusive/reference.html#header.boost.intrusive.unordered_set_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="make_unordered_set.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.intrusive.unordered_set"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Class template unordered_set</span></h2>
<p>boost::intrusive::unordered_set</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../intrusive/reference.html#header.boost.intrusive.unordered_set_hpp" title="Header <boost/intrusive/unordered_set.hpp>">boost/intrusive/unordered_set.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> T<span class="special">,</span> <span class="keyword">class</span><span class="special">...</span> Options<span class="special">></span>
<span class="keyword">class</span> <a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">:</span> <span class="keyword">public</span> boost::intrusive::hashtable< ValueTraits, VoidOrKeyOfValue, VoidOrKeyHash, VoidOrKeyEqual, BucketTraits, SizeType, BoolFlags|hash_bool_flags::unique_keys_pos >
<span class="special">{</span>
<span class="keyword">public</span><span class="special">:</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">value_type</span> <a name="boost.intrusive.unordered_set.value_type"></a><span class="identifier">value_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">key_type</span> <a name="boost.intrusive.unordered_set.key_type"></a><span class="identifier">key_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">key_of_value</span> <a name="boost.intrusive.unordered_set.key_of_value"></a><span class="identifier">key_of_value</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">value_traits</span> <a name="boost.intrusive.unordered_set.value_traits"></a><span class="identifier">value_traits</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">bucket_traits</span> <a name="boost.intrusive.unordered_set.bucket_traits"></a><span class="identifier">bucket_traits</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">pointer</span> <a name="boost.intrusive.unordered_set.pointer"></a><span class="identifier">pointer</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">const_pointer</span> <a name="boost.intrusive.unordered_set.const_pointer"></a><span class="identifier">const_pointer</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">reference</span> <a name="boost.intrusive.unordered_set.reference"></a><span class="identifier">reference</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">const_reference</span> <a name="boost.intrusive.unordered_set.const_reference"></a><span class="identifier">const_reference</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">difference_type</span> <a name="boost.intrusive.unordered_set.difference_type"></a><span class="identifier">difference_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">size_type</span> <a name="boost.intrusive.unordered_set.size_type"></a><span class="identifier">size_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">key_equal</span> <a name="boost.intrusive.unordered_set.key_equal"></a><span class="identifier">key_equal</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">hasher</span> <a name="boost.intrusive.unordered_set.hasher"></a><span class="identifier">hasher</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">bucket_type</span> <a name="boost.intrusive.unordered_set.bucket_type"></a><span class="identifier">bucket_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">bucket_ptr</span> <a name="boost.intrusive.unordered_set.bucket_ptr"></a><span class="identifier">bucket_ptr</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">iterator</span> <a name="boost.intrusive.unordered_set.iterator"></a><span class="identifier">iterator</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">const_iterator</span> <a name="boost.intrusive.unordered_set.const_iterator"></a><span class="identifier">const_iterator</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">insert_commit_data</span> <a name="boost.intrusive.unordered_set.insert_commit_data"></a><span class="identifier">insert_commit_data</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">local_iterator</span> <a name="boost.intrusive.unordered_set.local_iterator"></a><span class="identifier">local_iterator</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">const_local_iterator</span> <a name="boost.intrusive.unordered_set.const_local_iterator"></a><span class="identifier">const_local_iterator</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">node_traits</span> <a name="boost.intrusive.unordered_set.node_traits"></a><span class="identifier">node_traits</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">node</span> <a name="boost.intrusive.unordered_set.node"></a><span class="identifier">node</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">node_ptr</span> <a name="boost.intrusive.unordered_set.node_ptr"></a><span class="identifier">node_ptr</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">const_node_ptr</span> <a name="boost.intrusive.unordered_set.const_node_ptr"></a><span class="identifier">const_node_ptr</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span><span class="special">::</span><span class="identifier">node_algorithms</span> <a name="boost.intrusive.unordered_set.node_algorithms"></a><span class="identifier">node_algorithms</span><span class="special">;</span>
<span class="comment">// <a class="link" href="unordered_set.html#boost.intrusive.unordered_setconstruct-copy-destruct">construct/copy/destruct</a></span>
<span class="keyword">explicit</span> <a class="link" href="unordered_set.html#idp48255024-bb"><span class="identifier">unordered_set</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">bucket_traits</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">hasher</span> <span class="special">&</span> <span class="special">=</span> <span class="identifier">hasher</span><span class="special">(</span><span class="special">)</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">key_equal</span> <span class="special">&</span> <span class="special">=</span> <span class="identifier">key_equal</span><span class="special">(</span><span class="special">)</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">value_traits</span> <span class="special">&</span> <span class="special">=</span> <span class="identifier">value_traits</span><span class="special">(</span><span class="special">)</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Iterator<span class="special">></span>
<a class="link" href="unordered_set.html#idp48264928-bb"><span class="identifier">unordered_set</span></a><span class="special">(</span><span class="identifier">Iterator</span><span class="special">,</span> <span class="identifier">Iterator</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">bucket_traits</span> <span class="special">&</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">hasher</span> <span class="special">&</span> <span class="special">=</span> <span class="identifier">hasher</span><span class="special">(</span><span class="special">)</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">key_equal</span> <span class="special">&</span> <span class="special">=</span> <span class="identifier">key_equal</span><span class="special">(</span><span class="special">)</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">value_traits</span> <span class="special">&</span> <span class="special">=</span> <span class="identifier">value_traits</span><span class="special">(</span><span class="special">)</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="unordered_set.html#idp48276192-bb"><span class="identifier">unordered_set</span></a><span class="special">(</span><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&&</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&</span> <a class="link" href="unordered_set.html#idp48278720-bb"><span class="keyword">operator</span><span class="special">=</span></a><span class="special">(</span><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&&</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="unordered_set.html#idp48281824-bb"><span class="special">~</span><span class="identifier">unordered_set</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="unordered_set.html#idp47845824-bb">public member functions</a></span>
<span class="identifier">iterator</span> <a class="link" href="unordered_set.html#idp47846384-bb"><span class="identifier">begin</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">const_iterator</span> <a class="link" href="unordered_set.html#idp47851744-bb"><span class="identifier">begin</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">const_iterator</span> <a class="link" href="unordered_set.html#idp47857392-bb"><span class="identifier">cbegin</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">iterator</span> <a class="link" href="unordered_set.html#idp47863040-bb"><span class="identifier">end</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">const_iterator</span> <a class="link" href="unordered_set.html#idp47867616-bb"><span class="identifier">end</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">const_iterator</span> <a class="link" href="unordered_set.html#idp47872464-bb"><span class="identifier">cend</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">hasher</span> <a class="link" href="unordered_set.html#idp47877312-bb"><span class="identifier">hash_function</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">key_equal</span> <a class="link" href="unordered_set.html#idp47882176-bb"><span class="identifier">key_eq</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="unordered_set.html#idp47887056-bb"><span class="identifier">empty</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp47892032-bb"><span class="identifier">size</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">void</span> <a class="link" href="unordered_set.html#idp47897664-bb"><span class="identifier">swap</span></a><span class="special">(</span><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Cloner<span class="special">,</span> <span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="unordered_set.html#idp47905216-bb"><span class="identifier">clone_from</span></a><span class="special">(</span><span class="keyword">const</span> <a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&</span><span class="special">,</span> <span class="identifier">Cloner</span><span class="special">,</span> <span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Cloner<span class="special">,</span> <span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="unordered_set.html#idp47915728-bb"><span class="identifier">clone_from</span></a><span class="special">(</span><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&&</span><span class="special">,</span> <span class="identifier">Cloner</span><span class="special">,</span> <span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span> <a class="link" href="unordered_set.html#idp47926064-bb"><span class="identifier">insert</span></a><span class="special">(</span><span class="identifier">reference</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Iterator<span class="special">></span> <span class="keyword">void</span> <a class="link" href="unordered_set.html#idp47934272-bb"><span class="identifier">insert</span></a><span class="special">(</span><span class="identifier">Iterator</span><span class="special">,</span> <span class="identifier">Iterator</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span>
<a class="link" href="unordered_set.html#idp47942304-bb"><span class="identifier">insert_check</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span>
<a class="link" href="unordered_set.html#idp47952576-bb"><span class="identifier">insert_check</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">,</span> <span class="identifier">KeyEqual</span><span class="special">,</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">iterator</span> <a class="link" href="unordered_set.html#idp47967648-bb"><span class="identifier">insert_commit</span></a><span class="special">(</span><span class="identifier">reference</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">void</span> <a class="link" href="unordered_set.html#idp47977728-bb"><span class="identifier">erase</span></a><span class="special">(</span><span class="identifier">const_iterator</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">void</span> <a class="link" href="unordered_set.html#idp47983200-bb"><span class="identifier">erase</span></a><span class="special">(</span><span class="identifier">const_iterator</span><span class="special">,</span> <span class="identifier">const_iterator</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp47989408-bb"><span class="identifier">erase</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp47995856-bb"><span class="identifier">erase</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">,</span> <span class="identifier">KeyEqual</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span> <span class="keyword">void</span> <a class="link" href="unordered_set.html#idp48007104-bb"><span class="identifier">erase_and_dispose</span></a><span class="special">(</span><span class="identifier">const_iterator</span><span class="special">,</span> <span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="unordered_set.html#idp48015008-bb"><span class="identifier">erase_and_dispose</span></a><span class="special">(</span><span class="identifier">const_iterator</span><span class="special">,</span> <span class="identifier">const_iterator</span><span class="special">,</span> <span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48023632-bb"><span class="identifier">erase_and_dispose</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">,</span>
<span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48032560-bb"><span class="identifier">erase_and_dispose</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">,</span> <span class="identifier">KeyEqual</span><span class="special">,</span>
<span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">void</span> <a class="link" href="unordered_set.html#idp48044496-bb"><span class="identifier">clear</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span> <span class="keyword">void</span> <a class="link" href="unordered_set.html#idp48049376-bb"><span class="identifier">clear_and_dispose</span></a><span class="special">(</span><span class="identifier">Disposer</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48056656-bb"><span class="identifier">count</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48061552-bb"><span class="identifier">count</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">,</span> <span class="identifier">KeyEqual</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">iterator</span> <a class="link" href="unordered_set.html#idp48071216-bb"><span class="identifier">find</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">iterator</span> <a class="link" href="unordered_set.html#idp48075872-bb"><span class="identifier">find</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">,</span> <span class="identifier">KeyEqual</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">const_iterator</span> <a class="link" href="unordered_set.html#idp48086352-bb"><span class="identifier">find</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">const_iterator</span> <a class="link" href="unordered_set.html#idp48091248-bb"><span class="identifier">find</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">,</span> <span class="identifier">KeyEqual</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="identifier">iterator</span> <span class="special">></span> <a class="link" href="unordered_set.html#idp48102000-bb"><span class="identifier">equal_range</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="identifier">iterator</span> <span class="special">></span>
<a class="link" href="unordered_set.html#idp48106736-bb"><span class="identifier">equal_range</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">,</span> <span class="identifier">KeyEqual</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">const_iterator</span><span class="special">,</span> <span class="identifier">const_iterator</span> <span class="special">></span>
<a class="link" href="unordered_set.html#idp48117264-bb"><span class="identifier">equal_range</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">const_iterator</span><span class="special">,</span> <span class="identifier">const_iterator</span> <span class="special">></span>
<a class="link" href="unordered_set.html#idp48122288-bb"><span class="identifier">equal_range</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">,</span> <span class="identifier">KeyEqual</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">iterator</span> <a class="link" href="unordered_set.html#idp48133104-bb"><span class="identifier">iterator_to</span></a><span class="special">(</span><span class="identifier">reference</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">const_iterator</span> <a class="link" href="unordered_set.html#idp48140080-bb"><span class="identifier">iterator_to</span></a><span class="special">(</span><span class="identifier">const_reference</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">local_iterator</span> <a class="link" href="unordered_set.html#idp48147328-bb"><span class="identifier">local_iterator_to</span></a><span class="special">(</span><span class="identifier">reference</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">const_local_iterator</span> <a class="link" href="unordered_set.html#idp48154272-bb"><span class="identifier">local_iterator_to</span></a><span class="special">(</span><span class="identifier">const_reference</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48161488-bb"><span class="identifier">bucket_count</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48165632-bb"><span class="identifier">bucket_size</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48171312-bb"><span class="identifier">bucket</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">></span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48177104-bb"><span class="identifier">bucket</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">KeyHasher</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">bucket_ptr</span> <a class="link" href="unordered_set.html#idp48185984-bb"><span class="identifier">bucket_pointer</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">local_iterator</span> <a class="link" href="unordered_set.html#idp48190144-bb"><span class="identifier">begin</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">const_local_iterator</span> <a class="link" href="unordered_set.html#idp48196528-bb"><span class="identifier">begin</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">const_local_iterator</span> <a class="link" href="unordered_set.html#idp48203184-bb"><span class="identifier">cbegin</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">local_iterator</span> <a class="link" href="unordered_set.html#idp48209840-bb"><span class="identifier">end</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">const_local_iterator</span> <a class="link" href="unordered_set.html#idp48216208-bb"><span class="identifier">end</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">const_local_iterator</span> <a class="link" href="unordered_set.html#idp48222864-bb"><span class="identifier">cend</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">void</span> <a class="link" href="unordered_set.html#idp48229520-bb"><span class="identifier">rehash</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">bucket_traits</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="unordered_set.html#idp48236656-bb"><span class="identifier">incremental_rehash</span></a><span class="special">(</span><span class="keyword">bool</span> <span class="special">=</span> <span class="keyword">true</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">bool</span> <a class="link" href="unordered_set.html#idp48243200-bb"><span class="identifier">incremental_rehash</span></a><span class="special">(</span><span class="keyword">const</span> <span class="identifier">bucket_traits</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48249904-bb"><span class="identifier">split_count</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="comment">// <a class="link" href="unordered_set.html#idp48286688-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="identifier">local_iterator</span> <a class="link" href="unordered_set.html#idp48287248-bb"><span class="identifier">s_local_iterator_to</span></a><span class="special">(</span><span class="identifier">reference</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">const_local_iterator</span> <a class="link" href="unordered_set.html#idp48295792-bb"><span class="identifier">s_local_iterator_to</span></a><span class="special">(</span><span class="identifier">const_reference</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48304336-bb"><span class="identifier">suggested_upper_bucket_count</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="identifier">size_type</span> <a class="link" href="unordered_set.html#idp48309408-bb"><span class="identifier">suggested_lower_bucket_count</span></a><span class="special">(</span><span class="identifier">size_type</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp125904368"></a><h2>Description</h2>
<p>The class template <a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> is an intrusive container, that mimics most of the interface of std::tr1::unordered_set as described in the C++ TR1.</p>
<p><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> is a semi-intrusive container: each object to be stored in the container must contain a proper hook, but the container also needs additional auxiliary memory to work: <a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> needs a pointer to an array of type `bucket_type` to be passed in the constructor. This bucket array must have at least the same lifetime as the container. This makes the use of <a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> more complicated than purely intrusive containers. `bucket_type` is default-constructible, copyable and assignable</p>
<p>The template parameter <code class="computeroutput">T</code> is the type to be managed by the container. The user can specify additional options and if no options are provided default options are used.</p>
<p>The container supports the following options: <code class="computeroutput">base_hook<>/member_hook<>/value_traits<></code>, <code class="computeroutput">constant_time_size<></code>, <code class="computeroutput">size_type<></code>, <code class="computeroutput">hash<></code> and <code class="computeroutput">equal<></code> <code class="computeroutput">bucket_traits<></code>, <code class="computeroutput">power_2_buckets<></code> and <code class="computeroutput">cache_begin<></code>.</p>
<p><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> only provides forward iterators but it provides 4 iterator types: iterator and const_iterator to navigate through the whole container and local_iterator and const_local_iterator to navigate through the values stored in a single bucket. Local iterators are faster and smaller.</p>
<p>It's not recommended to use non constant-time size unordered_sets because several key functions, like "empty()", become non-constant time functions. Non constant-time size unordered_sets are mainly provided to support auto-unlink hooks.</p>
<p><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a>, unlike std::unordered_set, does not make automatic rehashings nor offers functions related to a load factor. Rehashing can be explicitly requested and the user must provide a new bucket array that will be used from that moment.</p>
<p>Since no automatic rehashing is done, iterators are never invalidated when inserting or erasing elements. Iterators are only invalidated when rehasing. </p>
<div class="refsect2">
<a name="idp125919712"></a><h3>
<a name="boost.intrusive.unordered_setconstruct-copy-destruct"></a><code class="computeroutput">unordered_set</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><span class="keyword">explicit</span> <a name="idp48255024-bb"></a><span class="identifier">unordered_set</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">bucket_traits</span> <span class="special">&</span> b_traits<span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">hasher</span> <span class="special">&</span> hash_func <span class="special">=</span> <span class="identifier">hasher</span><span class="special">(</span><span class="special">)</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">key_equal</span> <span class="special">&</span> equal_func <span class="special">=</span> <span class="identifier">key_equal</span><span class="special">(</span><span class="special">)</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">value_traits</span> <span class="special">&</span> v_traits <span class="special">=</span> <span class="identifier">value_traits</span><span class="special">(</span><span class="special">)</span><span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: buckets must not be being used by any other resource.</p>
<p><span class="bold"><strong>Effects</strong></span>: Constructs an empty <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>, storing a reference to the bucket array and copies of the key_hasher and equal_func functors.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: If value_traits::node_traits::node constructor throws (this does not happen with predefined Boost.Intrusive hooks) or the copy constructor or invocation of hash_func or equal_func throws.</p>
<p><span class="bold"><strong>Notes</strong></span>: buckets array must be disposed only after this is disposed. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Iterator<span class="special">></span>
<a name="idp48264928-bb"></a><span class="identifier">unordered_set</span><span class="special">(</span><span class="identifier">Iterator</span> b<span class="special">,</span> <span class="identifier">Iterator</span> e<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">bucket_traits</span> <span class="special">&</span> b_traits<span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">hasher</span> <span class="special">&</span> hash_func <span class="special">=</span> <span class="identifier">hasher</span><span class="special">(</span><span class="special">)</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">key_equal</span> <span class="special">&</span> equal_func <span class="special">=</span> <span class="identifier">key_equal</span><span class="special">(</span><span class="special">)</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">value_traits</span> <span class="special">&</span> v_traits <span class="special">=</span> <span class="identifier">value_traits</span><span class="special">(</span><span class="special">)</span><span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: buckets must not be being used by any other resource and dereferencing iterator must yield an lvalue of type value_type.</p>
<p><span class="bold"><strong>Effects</strong></span>: Constructs an empty container and inserts elements from [b, e).</p>
<p><span class="bold"><strong>Complexity</strong></span>: If N is distance(b, e): Average case is O(N) (with a good hash function and with buckets_len >= N),worst case O(N^2).</p>
<p><span class="bold"><strong>Throws</strong></span>: If value_traits::node_traits::node constructor throws (this does not happen with predefined Boost.Intrusive hooks) or the copy constructor or invocation of hasher or key_equal throws.</p>
<p><span class="bold"><strong>Notes</strong></span>: buckets array must be disposed only after this is disposed. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><a name="idp48276192-bb"></a><span class="identifier">unordered_set</span><span class="special">(</span><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&&</span> x<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: to-do </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&</span> <a name="idp48278720-bb"></a><span class="keyword">operator</span><span class="special">=</span><span class="special">(</span><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&&</span> x<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: to-do </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><a name="idp48281824-bb"></a><span class="special">~</span><span class="identifier">unordered_set</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Detaches all elements from this. The objects in the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> are not deleted (i.e. no destructors are called).</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to the number of elements in the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>, if it's a safe-mode or auto-unlink value. Otherwise constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
</ol></div>
</div>
<div class="refsect2">
<a name="idp126004816"></a><h3>
<a name="idp47845824-bb"></a><code class="computeroutput">unordered_set</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><span class="identifier">iterator</span> <a name="idp47846384-bb"></a><span class="identifier">begin</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns an iterator pointing to the beginning of the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Amortized constant time. Worst case (empty <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>): O(this->bucket_count())</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_iterator</span> <a name="idp47851744-bb"></a><span class="identifier">begin</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns a const_iterator pointing to the beginning of the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Amortized constant time. Worst case (empty <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>): O(this->bucket_count())</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_iterator</span> <a name="idp47857392-bb"></a><span class="identifier">cbegin</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns a const_iterator pointing to the beginning of the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Amortized constant time. Worst case (empty <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>): O(this->bucket_count())</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">iterator</span> <a name="idp47863040-bb"></a><span class="identifier">end</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns an iterator pointing to the end of the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_iterator</span> <a name="idp47867616-bb"></a><span class="identifier">end</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns a const_iterator pointing to the end of the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_iterator</span> <a name="idp47872464-bb"></a><span class="identifier">cend</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns a const_iterator pointing to the end of the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">hasher</span> <a name="idp47877312-bb"></a><span class="identifier">hash_function</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the hasher object used by the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: If hasher copy-constructor throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">key_equal</span> <a name="idp47882176-bb"></a><span class="identifier">key_eq</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the key_equal object used by the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: If key_equal copy-constructor throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">bool</span> <a name="idp47887056-bb"></a><span class="identifier">empty</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns true if the container is empty.</p>
<p><span class="bold"><strong>Complexity</strong></span>: if constant-time size and <code class="computeroutput"><a class="link" href="cache_begin.html" title="Struct template cache_begin">cache_begin</a></code> options are disabled, average constant time (worst case, with empty() == true: O(this->bucket_count()). Otherwise constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">size_type</span> <a name="idp47892032-bb"></a><span class="identifier">size</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the number of elements stored in the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to elements contained in *this if <code class="computeroutput"><a class="link" href="constant_time_size.html" title="Struct template constant_time_size">constant_time_size</a></code> is false. Constant-time otherwise.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">void</span> <a name="idp47897664-bb"></a><span class="identifier">swap</span><span class="special">(</span><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&</span> other<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: buckets must not be being used by any other resource.</p>
<p><span class="bold"><strong>Effects</strong></span>: Constructs an empty <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>, storing a reference to the bucket array and copies of the key_hasher and equal_func functors.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: If value_traits::node_traits::node constructor throws (this does not happen with predefined Boost.Intrusive hooks) or the copy constructor or invocation of hash_func or equal_func throws.</p>
<p><span class="bold"><strong>Notes</strong></span>: buckets array must be disposed only after this is disposed. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Cloner<span class="special">,</span> <span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">void</span> <a name="idp47905216-bb"></a><span class="identifier">clone_from</span><span class="special">(</span><span class="keyword">const</span> <a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&</span> src<span class="special">,</span> <span class="identifier">Cloner</span> cloner<span class="special">,</span> <span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: Disposer::operator()(pointer) shouldn't throw Cloner should yield to nodes that compare equal and produce the same hash than the original node.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases all the elements from *this calling Disposer::operator()(pointer), clones all the elements from src calling Cloner::operator()(const_reference ) and inserts them on *this. The hash function and the equality predicate are copied from the source.</p>
<p>If <code class="computeroutput"><a class="link" href="store_hash.html" title="Struct template store_hash">store_hash</a></code> option is true, this method does not use the hash function.</p>
<p>If any operation throws, all cloned elements are unlinked and disposed calling Disposer::operator()(pointer).</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to erased plus inserted elements.</p>
<p><span class="bold"><strong>Throws</strong></span>: If cloner or hasher throw or hash or equality predicate copying throws. Basic guarantee. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Cloner<span class="special">,</span> <span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">void</span> <a name="idp47915728-bb"></a><span class="identifier">clone_from</span><span class="special">(</span><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a> <span class="special">&&</span> src<span class="special">,</span> <span class="identifier">Cloner</span> cloner<span class="special">,</span> <span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: Disposer::operator()(pointer) shouldn't throw Cloner should yield to nodes that compare equal and produce the same hash than the original node.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases all the elements from *this calling Disposer::operator()(pointer), clones all the elements from src calling Cloner::operator()(reference) and inserts them on *this. The hash function and the equality predicate are copied from the source.</p>
<p>If <code class="computeroutput"><a class="link" href="store_hash.html" title="Struct template store_hash">store_hash</a></code> option is true, this method does not use the hash function.</p>
<p>If any operation throws, all cloned elements are unlinked and disposed calling Disposer::operator()(pointer).</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to erased plus inserted elements.</p>
<p><span class="bold"><strong>Throws</strong></span>: If cloner or hasher throw or hash or equality predicate copying throws. Basic guarantee. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span> <a name="idp47926064-bb"></a><span class="identifier">insert</span><span class="special">(</span><span class="identifier">reference</span> value<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: value must be an lvalue</p>
<p><span class="bold"><strong>Effects</strong></span>: Tries to inserts value into the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p><span class="bold"><strong>Returns</strong></span>: If the value is not already present inserts it and returns a pair containing the iterator to the new value and true. If there is an equivalent value returns a pair containing an iterator to the already present value and false.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. Strong guarantee.</p>
<p><span class="bold"><strong>Note</strong></span>: Does not affect the validity of iterators and references. No copy-constructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Iterator<span class="special">></span> <span class="keyword">void</span> <a name="idp47934272-bb"></a><span class="identifier">insert</span><span class="special">(</span><span class="identifier">Iterator</span> b<span class="special">,</span> <span class="identifier">Iterator</span> e<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: Dereferencing iterator must yield an lvalue of type value_type.</p>
<p><span class="bold"><strong>Effects</strong></span>: Equivalent to this->insert_unique(t) for each element in [b, e).</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(N), where N is distance(b, e). Worst case O(N*this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. Basic guarantee.</p>
<p><span class="bold"><strong>Note</strong></span>: Does not affect the validity of iterators and references. No copy-constructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span>
<a name="idp47942304-bb"></a><span class="identifier">insert_check</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span> commit_data<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Checks if a value can be inserted in the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>, using a user provided key instead of the value itself.</p>
<p><span class="bold"><strong>Returns</strong></span>: If there is an equivalent value returns a pair containing an iterator to the already present value and false. If the value can be inserted returns true in the returned pair boolean and fills "commit_data" that is meant to be used with the "insert_commit" function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If hasher or key_compare throw. Strong guarantee.</p>
<p><span class="bold"><strong>Notes</strong></span>: This function is used to improve performance when constructing a value_type is expensive: if there is an equivalent value the constructed object must be discarded. Many times, the part of the node that is used to impose the hash or the equality is much cheaper to construct than the value_type and this function offers the possibility to use that the part to check if the insertion will be successful.</p>
<p>If the check is successful, the user can construct the value_type and use "insert_commit" to insert the object in constant-time.</p>
<p>"commit_data" remains valid for a subsequent "insert_commit" only if no more objects are inserted or erased from the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p>After a successful rehashing insert_commit_data remains valid. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="keyword">bool</span> <span class="special">></span>
<a name="idp47952576-bb"></a><span class="identifier">insert_check</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyHasher</span> hasher<span class="special">,</span>
<span class="identifier">KeyEqual</span> key_value_equal<span class="special">,</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span> commit_data<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "hash_func" must be a hash function that induces the same hash values as the stored hasher. The difference is that "hash_func" hashes the given key instead of the value_type.</p>
<p>"equal_func" must be a equality function that induces the same equality as key_equal. The difference is that "equal_func" compares an arbitrary key with the contained values.</p>
<p><span class="bold"><strong>Effects</strong></span>: Checks if a value can be inserted in the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>, using a user provided key instead of the value itself.</p>
<p><span class="bold"><strong>Returns</strong></span>: If there is an equivalent value returns a pair containing an iterator to the already present value and false. If the value can be inserted returns true in the returned pair boolean and fills "commit_data" that is meant to be used with the "insert_commit" function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If hash_func or equal_func throw. Strong guarantee.</p>
<p><span class="bold"><strong>Notes</strong></span>: This function is used to improve performance when constructing a value_type is expensive: if there is an equivalent value the constructed object must be discarded. Many times, the part of the node that is used to impose the hash or the equality is much cheaper to construct than the value_type and this function offers the possibility to use that the part to check if the insertion will be successful.</p>
<p>If the check is successful, the user can construct the value_type and use "insert_commit" to insert the object in constant-time.</p>
<p>"commit_data" remains valid for a subsequent "insert_commit" only if no more objects are inserted or erased from the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code>.</p>
<p>After a successful rehashing insert_commit_data remains valid. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">iterator</span> <a name="idp47967648-bb"></a><span class="identifier">insert_commit</span><span class="special">(</span><span class="identifier">reference</span> value<span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">insert_commit_data</span> <span class="special">&</span> commit_data<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: value must be an lvalue of type value_type. commit_data must have been obtained from a previous call to "insert_check". No objects should have been inserted or erased from the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> between the "insert_check" that filled "commit_data" and the call to "insert_commit".</p>
<p><span class="bold"><strong>Effects</strong></span>: Inserts the value in the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> using the information obtained from the "commit_data" that a previous "insert_check" filled.</p>
<p><span class="bold"><strong>Returns</strong></span>: An iterator to the newly inserted object.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Notes</strong></span>: This function has only sense if a "insert_check" has been previously executed to fill "commit_data". No value should be inserted or erased between the "insert_check" and "insert_commit" calls.</p>
<p>After a successful rehashing insert_commit_data remains valid. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">void</span> <a name="idp47977728-bb"></a><span class="identifier">erase</span><span class="special">(</span><span class="identifier">const_iterator</span> i<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Erases the element pointed to by i.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators (but not the references) to the erased element. No destructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">void</span> <a name="idp47983200-bb"></a><span class="identifier">erase</span><span class="special">(</span><span class="identifier">const_iterator</span> b<span class="special">,</span> <span class="identifier">const_iterator</span> e<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Erases the range pointed to by b end e.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(distance(b, e)), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators (but not the references) to the erased elements. No destructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">size_type</span> <a name="idp47989408-bb"></a><span class="identifier">erase</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> key<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Erases all the elements with the given value.</p>
<p><span class="bold"><strong>Returns</strong></span>: The number of erased elements.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(this->count(value)). Worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. Basic guarantee.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators (but not the references) to the erased elements. No destructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">size_type</span> <a name="idp47995856-bb"></a><span class="identifier">erase</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyHasher</span> hash_func<span class="special">,</span>
<span class="identifier">KeyEqual</span> equal_func<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "hash_func" must be a hash function that induces the same hash values as the stored hasher. The difference is that "hash_func" hashes the given key instead of the value_type.</p>
<p>"equal_func" must be a equality function that induces the same equality as key_equal. The difference is that "equal_func" compares an arbitrary key with the contained values.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases all the elements that have the same hash and compare equal with the given key.</p>
<p><span class="bold"><strong>Returns</strong></span>: The number of erased elements.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(this->count(value)). Worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If hash_func or equal_func throw. Basic guarantee.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators (but not the references) to the erased elements. No destructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">void</span> <a name="idp48007104-bb"></a><span class="identifier">erase_and_dispose</span><span class="special">(</span><span class="identifier">const_iterator</span> i<span class="special">,</span> <span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: Disposer::operator()(pointer) shouldn't throw.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases the element pointed to by i. Disposer::operator()(pointer) is called for the removed element.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators to the erased elements. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="keyword">void</span> <a name="idp48015008-bb"></a><span class="identifier">erase_and_dispose</span><span class="special">(</span><span class="identifier">const_iterator</span> b<span class="special">,</span> <span class="identifier">const_iterator</span> e<span class="special">,</span>
<span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: Disposer::operator()(pointer) shouldn't throw.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases the range pointed to by b end e. Disposer::operator()(pointer) is called for the removed elements.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(distance(b, e)), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators to the erased elements. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="identifier">size_type</span> <a name="idp48023632-bb"></a><span class="identifier">erase_and_dispose</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: Disposer::operator()(pointer) shouldn't throw.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases all the elements with the given value. Disposer::operator()(pointer) is called for the removed elements.</p>
<p><span class="bold"><strong>Returns</strong></span>: The number of erased elements.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(this->count(value)). Worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. Basic guarantee.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators (but not the references) to the erased elements. No destructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">,</span>
<span class="keyword">typename</span> Disposer<span class="special">></span>
<span class="identifier">size_type</span> <a name="idp48032560-bb"></a><span class="identifier">erase_and_dispose</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyHasher</span> hash_func<span class="special">,</span>
<span class="identifier">KeyEqual</span> equal_func<span class="special">,</span> <span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: Disposer::operator()(pointer) shouldn't throw.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases all the elements with the given key. according to the comparison functor "equal_func". Disposer::operator()(pointer) is called for the removed elements.</p>
<p><span class="bold"><strong>Returns</strong></span>: The number of erased elements.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(this->count(value)). Worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If hash_func or equal_func throw. Basic guarantee.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators to the erased elements. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">void</span> <a name="idp48044496-bb"></a><span class="identifier">clear</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Erases all of the elements.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to the number of elements on the container. if it's a safe-mode or auto-unlink value_type. Constant time otherwise.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators (but not the references) to the erased elements. No destructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Disposer<span class="special">></span> <span class="keyword">void</span> <a name="idp48049376-bb"></a><span class="identifier">clear_and_dispose</span><span class="special">(</span><span class="identifier">Disposer</span> disposer<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: Disposer::operator()(pointer) shouldn't throw.</p>
<p><span class="bold"><strong>Effects</strong></span>: Erases all of the elements.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to the number of elements on the container. Disposer::operator()(pointer) is called for the removed elements.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: Invalidates the iterators (but not the references) to the erased elements. No destructors are called. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">size_type</span> <a name="idp48056656-bb"></a><span class="identifier">count</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> key<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the number of contained elements with the given value</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">size_type</span> <a name="idp48061552-bb"></a><span class="identifier">count</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyHasher</span> hash_func<span class="special">,</span>
<span class="identifier">KeyEqual</span> equal_func<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "hash_func" must be a hash function that induces the same hash values as the stored hasher. The difference is that "hash_func" hashes the given key instead of the value_type.</p>
<p>"equal_func" must be a equality function that induces the same equality as key_equal. The difference is that "equal_func" compares an arbitrary key with the contained values.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the number of contained elements with the given key</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If hash_func or equal throw. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">iterator</span> <a name="idp48071216-bb"></a><span class="identifier">find</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> key<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Finds an iterator to the first element is equal to "value" or end() if that element does not exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">iterator</span> <a name="idp48075872-bb"></a><span class="identifier">find</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyHasher</span> hash_func<span class="special">,</span> <span class="identifier">KeyEqual</span> equal_func<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "hash_func" must be a hash function that induces the same hash values as the stored hasher. The difference is that "hash_func" hashes the given key instead of the value_type.</p>
<p>"equal_func" must be a equality function that induces the same equality as key_equal. The difference is that "equal_func" compares an arbitrary key with the contained values.</p>
<p><span class="bold"><strong>Effects</strong></span>: Finds an iterator to the first element whose key is "key" according to the given hash and equality functor or end() if that element does not exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If hash_func or equal_func throw.</p>
<p><span class="bold"><strong>Note</strong></span>: This function is used when constructing a value_type is expensive and the value_type can be compared with a cheaper key type. Usually this key is part of the value_type. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_iterator</span> <a name="idp48086352-bb"></a><span class="identifier">find</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> key<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the number of contained elements with the given value</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">const_iterator</span>
<a name="idp48091248-bb"></a><span class="identifier">find</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyHasher</span> hash_func<span class="special">,</span> <span class="identifier">KeyEqual</span> equal_func<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "hash_func" must be a hash function that induces the same hash values as the stored hasher. The difference is that "hash_func" hashes the given key instead of the value_type.</p>
<p>"equal_func" must be a equality function that induces the same equality as key_equal. The difference is that "equal_func" compares an arbitrary key with the contained values.</p>
<p><span class="bold"><strong>Effects</strong></span>: Finds an iterator to the first element whose key is "key" according to the given hasher and equality functor or end() if that element does not exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(1), worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If hash_func or equal_func throw.</p>
<p><span class="bold"><strong>Note</strong></span>: This function is used when constructing a value_type is expensive and the value_type can be compared with a cheaper key type. Usually this key is part of the value_type. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="identifier">iterator</span> <span class="special">></span> <a name="idp48102000-bb"></a><span class="identifier">equal_range</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> key<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns a range containing all elements with values equivalent to value. Returns std::make_pair(this->end(), this->end()) if no such elements exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(this->count(value)). Worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">iterator</span><span class="special">,</span> <span class="identifier">iterator</span> <span class="special">></span>
<a name="idp48106736-bb"></a><span class="identifier">equal_range</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyHasher</span> hash_func<span class="special">,</span> <span class="identifier">KeyEqual</span> equal_func<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "hash_func" must be a hash function that induces the same hash values as the stored hasher. The difference is that "hash_func" hashes the given key instead of the value_type.</p>
<p>"equal_func" must be a equality function that induces the same equality as key_equal. The difference is that "equal_func" compares an arbitrary key with the contained values.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a range containing all elements with equivalent keys. Returns std::make_pair(this->end(), this->end()) if no such elements exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(this->count(key, hash_func, equal_func)). Worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If hash_func or the equal_func throw.</p>
<p><span class="bold"><strong>Note</strong></span>: This function is used when constructing a value_type is expensive and the value_type can be compared with a cheaper key type. Usually this key is part of the value_type. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">const_iterator</span><span class="special">,</span> <span class="identifier">const_iterator</span> <span class="special">></span>
<a name="idp48117264-bb"></a><span class="identifier">equal_range</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> key<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns a range containing all elements with values equivalent to value. Returns std::make_pair(this->end(), this->end()) if no such elements exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(this->count(value)). Worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hasher or the equality functor throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">,</span> <span class="keyword">typename</span> KeyEqual<span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span> <span class="identifier">const_iterator</span><span class="special">,</span> <span class="identifier">const_iterator</span> <span class="special">></span>
<a name="idp48122288-bb"></a><span class="identifier">equal_range</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> key<span class="special">,</span> <span class="identifier">KeyHasher</span> hash_func<span class="special">,</span> <span class="identifier">KeyEqual</span> equal_func<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "hash_func" must be a hash function that induces the same hash values as the stored hasher. The difference is that "hash_func" hashes the given key instead of the value_type.</p>
<p>"equal_func" must be a equality function that induces the same equality as key_equal. The difference is that "equal_func" compares an arbitrary key with the contained values.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a range containing all elements with equivalent keys. Returns std::make_pair(this->end(), this->end()) if no such elements exist.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case O(this->count(key, hash_func, equal_func)). Worst case O(this->size()).</p>
<p><span class="bold"><strong>Throws</strong></span>: If the hasher or equal_func throw.</p>
<p><span class="bold"><strong>Note</strong></span>: This function is used when constructing a value_type is expensive and the value_type can be compared with a cheaper key type. Usually this key is part of the value_type. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">iterator</span> <a name="idp48133104-bb"></a><span class="identifier">iterator_to</span><span class="special">(</span><span class="identifier">reference</span> value<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: value must be an lvalue and shall be in a <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> of appropriate type. Otherwise the behavior is undefined.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns: a valid iterator belonging to the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> that points to the value</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hash function throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_iterator</span> <a name="idp48140080-bb"></a><span class="identifier">iterator_to</span><span class="special">(</span><span class="identifier">const_reference</span> value<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: value must be an lvalue and shall be in a <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> of appropriate type. Otherwise the behavior is undefined.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns: a valid const_iterator belonging to the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> that points to the value</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: If the internal hash function throws. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">local_iterator</span> <a name="idp48147328-bb"></a><span class="identifier">local_iterator_to</span><span class="special">(</span><span class="identifier">reference</span> value<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: value must be an lvalue and shall be in a <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> of appropriate type. Otherwise the behavior is undefined.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns: a valid local_iterator belonging to the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> that points to the value</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_local_iterator</span> <a name="idp48154272-bb"></a><span class="identifier">local_iterator_to</span><span class="special">(</span><span class="identifier">const_reference</span> value<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: value must be an lvalue and shall be in a <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> of appropriate type. Otherwise the behavior is undefined.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns: a valid local_iterator belonging to the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> that points to the value</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">size_type</span> <a name="idp48161488-bb"></a><span class="identifier">bucket_count</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the number of buckets passed in the constructor or the last rehash function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">size_type</span> <a name="idp48165632-bb"></a><span class="identifier">bucket_size</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: n is in the range [0, this->bucket_count()).</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the number of elements in the nth bucket.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">size_type</span> <a name="idp48171312-bb"></a><span class="identifier">bucket</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">key_type</span> <span class="special">&</span> k<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the index of the bucket in which elements with keys equivalent to k would be found, if any such element existed.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: If the hash functor throws.</p>
<p><span class="bold"><strong>Note</strong></span>: the return value is in the range [0, this->bucket_count()). </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> KeyType<span class="special">,</span> <span class="keyword">typename</span> KeyHasher<span class="special">></span>
<span class="identifier">size_type</span> <a name="idp48177104-bb"></a><span class="identifier">bucket</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">KeyType</span> <span class="special">&</span> k<span class="special">,</span> <span class="identifier">KeyHasher</span> hash_func<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: "hash_func" must be a hash function that induces the same hash values as the stored hasher. The difference is that "hash_func" hashes the given key instead of the value_type.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns the index of the bucket in which elements with keys equivalent to k would be found, if any such element existed.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: If hash_func throws.</p>
<p><span class="bold"><strong>Note</strong></span>: the return value is in the range [0, this->bucket_count()). </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">bucket_ptr</span> <a name="idp48185984-bb"></a><span class="identifier">bucket_pointer</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the bucket array pointer passed in the constructor or the last rehash function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">local_iterator</span> <a name="idp48190144-bb"></a><span class="identifier">begin</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: n is in the range [0, this->bucket_count()).</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a local_iterator pointing to the beginning of the sequence stored in the bucket n.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: [this->begin(n), this->end(n)) is a valid range containing all of the elements in the nth bucket. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_local_iterator</span> <a name="idp48196528-bb"></a><span class="identifier">begin</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: n is in the range [0, this->bucket_count()).</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a const_local_iterator pointing to the beginning of the sequence stored in the bucket n.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: [this->begin(n), this->end(n)) is a valid range containing all of the elements in the nth bucket. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_local_iterator</span> <a name="idp48203184-bb"></a><span class="identifier">cbegin</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: n is in the range [0, this->bucket_count()).</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a const_local_iterator pointing to the beginning of the sequence stored in the bucket n.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: [this->begin(n), this->end(n)) is a valid range containing all of the elements in the nth bucket. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">local_iterator</span> <a name="idp48209840-bb"></a><span class="identifier">end</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: n is in the range [0, this->bucket_count()).</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a local_iterator pointing to the end of the sequence stored in the bucket n.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: [this->begin(n), this->end(n)) is a valid range containing all of the elements in the nth bucket. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_local_iterator</span> <a name="idp48216208-bb"></a><span class="identifier">end</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: n is in the range [0, this->bucket_count()).</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a const_local_iterator pointing to the end of the sequence stored in the bucket n.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: [this->begin(n), this->end(n)) is a valid range containing all of the elements in the nth bucket. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">const_local_iterator</span> <a name="idp48222864-bb"></a><span class="identifier">cend</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: n is in the range [0, this->bucket_count()).</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns a const_local_iterator pointing to the end of the sequence stored in the bucket n.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: [this->begin(n), this->end(n)) is a valid range containing all of the elements in the nth bucket. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">void</span> <a name="idp48229520-bb"></a><span class="identifier">rehash</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">bucket_traits</span> <span class="special">&</span> new_bucket_traits<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: new_bucket_traits can hold a pointer to a new bucket array or the same as the old bucket array with a different length. new_size is the length of the the array pointed by new_buckets. If new_bucket_traits.bucket_begin() == this->bucket_pointer() new_bucket_traits.bucket_count() can be bigger or smaller than this->bucket_count(). 'new_bucket_traits' copy constructor should not throw.</p>
<p><span class="bold"><strong>Effects</strong></span>: Updates the internal reference with the new bucket, erases the values from the old bucket and inserts then in the new one. Bucket traits hold by *this is assigned from new_bucket_traits. If the container is configured as incremental<>, the split bucket is set to the new bucket_count().</p>
<p>If <code class="computeroutput"><a class="link" href="store_hash.html" title="Struct template store_hash">store_hash</a></code> option is true, this method does not use the hash function.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Average case linear in this->size(), worst case quadratic.</p>
<p><span class="bold"><strong>Throws</strong></span>: If the hasher functor throws. Basic guarantee. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">bool</span> <a name="idp48236656-bb"></a><span class="identifier">incremental_rehash</span><span class="special">(</span><span class="keyword">bool</span> grow <span class="special">=</span> <span class="keyword">true</span><span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>:</p>
<p><span class="bold"><strong>Effects</strong></span>:</p>
<p><span class="bold"><strong>Complexity</strong></span>:</p>
<p><span class="bold"><strong>Throws</strong></span>:</p>
<p><span class="bold"><strong>Note</strong></span>: this method is only available if incremental<true> option is activated. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">bool</span> <a name="idp48243200-bb"></a><span class="identifier">incremental_rehash</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">bucket_traits</span> <span class="special">&</span> new_bucket_traits<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: If new_bucket_traits.bucket_count() is not this->bucket_count()/2 or this->bucket_count()*2, or this->split_bucket() != new_bucket_traits.bucket_count() returns false and does nothing.</p>
<p>Otherwise, copy assigns new_bucket_traits to the internal <code class="computeroutput"><a class="link" href="bucket_traits.html" title="Struct template bucket_traits">bucket_traits</a></code> and transfers all the objects from old buckets to the new ones.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Linear to size().</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing</p>
<p><span class="bold"><strong>Note</strong></span>: this method is only available if incremental<true> option is activated. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">size_type</span> <a name="idp48249904-bb"></a><span class="identifier">split_count</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: incremental<> option must be set</p>
<p><span class="bold"><strong>Effects</strong></span>: returns the current split count</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing </p>
<p>
</p>
</li>
</ol></div>
</div>
<div class="refsect2">
<a name="idp126763360"></a><h3>
<a name="idp48286688-bb"></a><code class="computeroutput">unordered_set</code> public static functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">local_iterator</span> <a name="idp48287248-bb"></a><span class="identifier">s_local_iterator_to</span><span class="special">(</span><span class="identifier">reference</span> value<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: value must be an lvalue and shall be in a <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> of appropriate type. Otherwise the behavior is undefined.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns: a valid local_iterator belonging to the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> that points to the value</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: This static function is available only if the <span class="emphasis"><em>value traits</em></span> is stateless. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">const_local_iterator</span> <a name="idp48295792-bb"></a><span class="identifier">s_local_iterator_to</span><span class="special">(</span><span class="identifier">const_reference</span> value<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Requires</strong></span>: value must be an lvalue and shall be in a <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> of appropriate type. Otherwise the behavior is undefined.</p>
<p><span class="bold"><strong>Effects</strong></span>: Returns: a valid local_iterator belonging to the <code class="computeroutput"><a class="link" href="unordered_set.html" title="Class template unordered_set">unordered_set</a></code> that points to the value</p>
<p><span class="bold"><strong>Complexity</strong></span>: Constant.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing.</p>
<p><span class="bold"><strong>Note</strong></span>: This static function is available only if the <span class="emphasis"><em>value traits</em></span> is stateless. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">size_type</span> <a name="idp48304336-bb"></a><span class="identifier">suggested_upper_bucket_count</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the nearest new bucket count optimized for the container that is bigger or equal than n. This suggestion can be used to create bucket arrays with a size that will usually improve container's performance. If such value does not exist, the higher possible value is returned.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Amortized constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">static</span> <span class="identifier">size_type</span> <a name="idp48309408-bb"></a><span class="identifier">suggested_lower_bucket_count</span><span class="special">(</span><span class="identifier">size_type</span> n<span class="special">)</span><span class="special">;</span></pre>
<p><span class="bold"><strong>Effects</strong></span>: Returns the nearest new bucket count optimized for the container that is smaller or equal than n. This suggestion can be used to create bucket arrays with a size that will usually improve container's performance. If such value does not exist, the lowest possible value is returned.</p>
<p><span class="bold"><strong>Complexity</strong></span>: Amortized constant time.</p>
<p><span class="bold"><strong>Throws</strong></span>: Nothing. </p>
<p>
</p>
</li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005 Olaf Krzikalla<br>Copyright © 2006-2015 Ion Gaztanaga<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="trivial_value_traits.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../intrusive/reference.html#header.boost.intrusive.unordered_set_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="make_unordered_set.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
imasaru/sabbath-school-lessons | src/es/2019-01-jo/04/06.md | 2401 | ---
title: La maravilla de todo esto
date: 24/01/2019
---
**Opinión**: Apocalipsis 4
"Recuerda que la vida no se mide por la cantidad de veces que respiras, sino por aquellos momentos que te dejan sin aliento". Este dicho, que ha sido atribuido a muchos au-tores, resuena en mi corazón de una manera poderosa. Esos momentos -momentos de asombro, maravilla y gozo exultante- son experiencias que, a menudo, nos toman por sorpresa y dejan una marca permanente en nuestros recuerdos.
Viajar es una manera genial de explorar el mundo y las diferentes personas que viven en él, y muchas veces me dejó maravillada. He estado en grandes salas de conciertos, catedrales, museos, edificios gubernamentales y estructuras eclécticas en varios países. En el mundo natural, las montañas y las cascadas llaman mi atención de manera especial. Las personas y las culturas también me fascinan, y muchas veces estoy ansiosa por inter-actuar y aprender de ellas.
¡Hay tanta belleza en este mundo! Y aun así, he aprendido que es solo una muestra de la verdadera belleza del universo.
Cuando pienso en la sala del trono de Dios según se describe en Apocalipsis 4, me quedo verdaderamente sin palabras. No hay nada en este mundo, natural o artificial, que se compare con la majestad, la gloria y la maravilla de este espacio magnífico en algún lugar del universo.
Un trono de piedras preciosas, un arcoíris de esmeralda, individuos vestidos de manera suntuosa, seres alucinantes, música celestial y, por supuesto, la maravillosa presencia de Dios el Padre.
Este Padre, lleno de poder y gracia, ha probado por su Palabra que nos considera a nosotros, los seres humanos, su máxima creación. Dios nos ama, y ha hecho todo lo que estaba en su poder para restaurar su preciosa creación a su imagen al darle a la humanidad su Hijo: Jesús.
Gracias a Jesús, a su sacrificio y su victoria, yo y todos los que lo consideran su Señor tenemos la seguridad de que, un día, podremos unirnos a él y al Padre en el cielo. Vere-mos la naturaleza de la forma en que Dios la Ideó, y exploraremos el universo de maneras que no podemos comenzar a Imaginar.
Pero, lo más importante: tendremos una relación de amor eterno con nuestro Creador, Redentor y Amigo. Cuando me siento y pienso en eso y en lo que significa, simplemente me deja sin aliento.
_Juliana Balono, Rockville, Maryland, EE. UU._ | mit |
kodemunki/devcenter | source/docs/best-practices.html.md | 317 | ---
title: Best Practices
---
# Include your dependencies in your repository
Include all your dependencies if possible (for example your
CocoaPods).
This will make your build more reliable (the exact dependencies checked
into your repository will be used) and
faster (no additional dependency fetching required).
| mit |
coryshaw1/DubPlus | src/js/utils/notify.js | 2082 | /* global Dubtrack */
const modal = require('../utils/modal.js');
var isActiveTab = true;
window.onfocus = function () {
isActiveTab = true;
};
window.onblur = function () {
isActiveTab = false;
};
var onDenyDismiss = function() {
modal.create({
title: 'Desktop Notifications',
content: "You have dismissed or chosen to deny the request to allow desktop notifications. Reset this choice by clearing your cache for the site."
});
};
export function notifyCheckPermission(cb){
var _cb = typeof cb === 'function' ? cb : function(){};
// first check if browser supports it
if (!("Notification" in window)) {
modal.create({
title: 'Desktop Notifications',
content: "Sorry this browser does not support desktop notifications. Please use the latest version of Chrome or FireFox"
});
return _cb(false);
}
// no request needed, good to go
if (Notification.permission === "granted") {
return _cb(true);
}
if (Notification.permission !== 'denied') {
Notification.requestPermission().then(function(result) {
if (result === 'denied' || result === 'default') {
onDenyDismiss();
_cb(false);
return;
}
_cb(true);
});
} else {
onDenyDismiss();
return _cb(false);
}
}
export function showNotification (opts){
var defaults = {
title : 'New Message',
content : '',
ignoreActiveTab : false,
callback : null,
wait : 5000
};
var options = Object.assign({}, defaults, opts);
// don't show a notification if tab is active
if (isActiveTab === true && !options.ignoreActiveTab) { return; }
var notificationOptions = {
body: options.content,
icon: "https://res.cloudinary.com/hhberclba/image/upload/c_lpad,h_100,w_100/v1400351432/dubtrack_new_logo_fvpxa6.png"
};
var n = new Notification(options.title, notificationOptions);
n.onclick = function() {
window.focus();
if (typeof options.callback === "function") { options.callback(); }
n.close();
};
setTimeout(n.close.bind(n), options.wait);
}
| mit |
PrJared/sabbath-school-lessons | src/fj/2019-04/13/01.md | 1804 | ---
title: O Ira Na Dauveiliutaki E Isireli
date: 21/12/2019
---
### Vulica Na Vuli Ni Macawa Oqo
1 Tui 12:1–16; Cakacaka 15:7–11; Joni 11:46–53; Niemaia 4:7–23; Esera 8:21–23, 31, 32.
> <p>Wiligusu</p>
> “A ra sa lako yani ko ira kecega na tamata me ra kana, ka gunu, ka me ra vakauta nai votavota, ka me ra marau vakalevu, ni ra sa kila na vosa sa tukuni vei ira.” (Niemaia 8:12).
Koi rau ko Esera kei Neimaia erau ivakaraitaki ni liuliu vinaka ni rau yalo dina vakaoti ki Vua na Kalou ka rau vakayacora talega na ka e vakaitavitaki rau kina na Kalou. Na nodrau lomana na Kalou e laki uqeta me rau sa dauveiqaravi yalodina vakaoti ki Vua. Na nodrau yalo dina sa uto tiko ni noda vuli oqo.
Ena macawa oqo eda na raica tiko kina eso nai vakaraitaki ni veiliutaki era kunei enai Vola Tabu, mevakataki rau ko Esera kei Neimaia. Oqo e sega ni ka ni vuli taucoko, ka ni levu sara na ka ena rawa ni veivosakitaki kina. Ia, na lesoni e digitaki ena yaga ki vua nai liuliu cava ga e vulica. Ena sega beka ni ko okati iko mo iliuliu ena gauna ni nomu bula oqo, ia, eda na rawa ni vurevure ni vakatulewa vei ira eso na tamata, sai koya oya na vuna e yaga kina na lesoni oqo veikeda kece.
E uto tiko ni talanoa me baleti ira nai liuliu oqo na Vosa ni Kalou. Na Vosa e veisautaka na nodra vakasama kei na bula ka laki vakavuna na tuvatuvaka me baleta na veivakabulabulataki kei na veivakavoui. Era solia taucoko na nodra vakavinavinaka ki na Vosa ni Kalou kei na Nona ivakasala era kune kina. Ena sala vata ga oya, veitalia ga se o cei oikeda se cava na nodai tavi, sa dodonu meda maroroya na Vosa ni Kalou me uto ni vakarau ni noda bula mevaka e dua na lewe ni lotu ni Kavitu ni Lesu Vakarua mai Lotu Vakarisito.
_*Vulica na lesoni ni Macawa oqo me Vakarautaki iko ena Siga Tabu, Tiseba 28._ | mit |
diversantvlz/WellCommerce | src/WellCommerce/Bundle/AppBundle/Tests/DataSet/Admin/ShopDataSetTest.php | 1062 | <?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <[email protected]>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\AppBundle\Tests\DataSet\Admin;
use WellCommerce\Bundle\CoreBundle\Test\DataSet\AbstractDataSetTestCase;
/**
* Class ShopDataSetTest
*
* @author Adam Piotrowski <[email protected]>
*/
class ShopDataSetTest extends AbstractDataSetTestCase
{
protected function get()
{
return $this->container->get('shop.dataset.admin');
}
protected function getColumns()
{
return [
'id' => 'shop.id',
'name' => 'shop.name',
'url' => 'shop.url',
'theme' => 'shop_theme.name',
'company' => 'shop_company.name',
'currency' => 'shop.defaultCurrency',
'country' => 'shop.defaultCountry',
];
}
}
| mit |
tf/pageflow-dependabot-test | app/assets/javascripts/pageflow/video_player/buffer_underrun_waiting.js | 1736 | pageflow.VideoPlayer.bufferUnderrunWaiting = function(player) {
var originalPause = player.pause;
player.pause = function() {
cancelWaiting();
originalPause.apply(this, arguments);
};
function pauseAndPreloadOnUnderrun() {
if (bufferUnderrun()) {
pauseAndPreload();
}
}
function bufferUnderrun() {
return !player.isBufferedAhead(0.1, true) && !player.waitingOnUnderrun && !ignoringUnderruns();
}
function pauseAndPreload() {
pageflow.log('Buffer underrun');
player.trigger('bufferunderrun');
player.pause();
player.waitingOnUnderrun = true;
player.prebuffer({secondsToBuffer: 5, secondsToWait: 5}).then(function() {
// do nothing if user aborted waiting by clicking pause
if (player.waitingOnUnderrun) {
player.waitingOnUnderrun = false;
player.trigger('bufferunderruncontinue');
player.play();
}
});
}
function cancelWaiting() {
if (player.waitingOnUnderrun) {
player.ignoreUnderrunsUntil = new Date().getTime() + 5 * 1000;
player.waitingOnUnderrun = false;
player.trigger('bufferunderruncontinue');
}
}
function ignoringUnderruns() {
var r = player.ignoreUnderrunsUntil && new Date().getTime() < player.ignoreUnderrunsUntil;
if (r) {
pageflow.log('ignoring underrun');
}
return r;
}
function stopListeningForProgress() {
player.off('progress', pauseAndPreloadOnUnderrun);
}
if (pageflow.browser.has('buffer underrun waiting support')) {
player.on('play', function() {
player.on('progress', pauseAndPreloadOnUnderrun);
});
player.on('pause', stopListeningForProgress);
player.on('ended', stopListeningForProgress);
}
}; | mit |
slowbrain/node-julia | src/dispatch.h | 122 | #ifndef __nj_dispatch
#define __nj_dispatch
namespace nj
{
void async_dispatch();
void dispatch_init();
};
#endif
| mit |
craftworkgames/MonoGame.Extended | src/cs/Tests/MonoGame.Extended.Entities.Tests/ComponentManagerTests.cs | 1586 | using MonoGame.Extended.Sprites;
using Xunit;
namespace MonoGame.Extended.Entities.Tests
{
public class ComponentManagerTests
{
[Fact]
public void GetMapperForType()
{
var componentManager = new ComponentManager();
var transformMapper = componentManager.GetMapper<Transform2>();
var spriteMapper = componentManager.GetMapper<Sprite>();
Assert.IsType<ComponentMapper<Transform2>>(transformMapper);
Assert.IsType<ComponentMapper<Sprite>>(spriteMapper);
Assert.Equal(0, transformMapper.Id);
Assert.Equal(1, spriteMapper.Id);
Assert.Same(spriteMapper, componentManager.GetMapper<Sprite>());
}
[Fact]
public void GetComponentTypeId()
{
var componentManager = new ComponentManager();
Assert.Equal(0, componentManager.GetComponentTypeId(typeof(Transform2)));
Assert.Equal(1, componentManager.GetComponentTypeId(typeof(Sprite)));
Assert.Equal(0, componentManager.GetComponentTypeId(typeof(Transform2)));
}
//[Fact]
//public void GetCompositionIdentity()
//{
// var compositionBits = new BitArray(3)
// {
// [0] = true,
// [1] = false,
// [2] = true
// };
// var componentManager = new ComponentManager();
// var identity = componentManager.GetCompositionIdentity(compositionBits);
// Assert.Equal(0b101, identity);
//}
}
} | mit |
KellyChan/python-examples | web/gae/python/b_words_replaced.py | 581 | # User Instructions
#
# Write a function 'sub1' that, given a
# string, embeds that string in
# the string:
# "I think X is a perfectly normal thing to do in public."
# where X is replaced by the given
# string.
#
given_string = "I think %s is a perfectly normal thing to do in public."
def sub1(s):
return given_string.replace("%s", s)
def sub2(s):
return given_string % s
print sub1("running")
# => "I think running is a perfectly normal thing to do in public."
print sub1("sleeping")
# => "I think sleeping is a perfectly normal thing to do in public."
| mit |
wilsonmar/oss-testing | alerts.md | 1117 | Alerts
Use product Watcher licensed from elastic.io
https://www.elastic.co/webinars/watcher-practical-alerting-for-elasticsearch-deutsch
It creates watchers.
Watcher is a plugin for Elasticsearch that provides alerting and notification based on changes in your data.
Watcher periodically issues a Elasticsearch query.
It checks results from the query against a condition.
If the condition is met an action is taken, such as sendingg an email,
a 3rd party system is notified, or the query results are stored.
* Open a helpdesk ticket when any servers are likely to run out of free space in the next few days.
* When the number of tweets and posts in an area exceeds a threshold of significance, notify a service technician.
* Track application response times and if page-load time exceeds SLAs for more than 5 minutes, open a helpdesk ticket. If SLAs are exceeded for an hour, page the administrator on duty.
https://www.elastic.co/guide/en/watcher/current/getting-started.html
Alerts need to be prioritized so that humans are not inuundated.
Pull in cases filed in Salesforce customer service app.
| mit |
kardeiz/fop_wrapper | vendor/fop-1.1/javadocs/org/apache/fop/fo/extensions/class-use/ExtensionAttachment.html | 41318 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 16 22:49:48 ICT 2012 -->
<TITLE>
Uses of Interface org.apache.fop.fo.extensions.ExtensionAttachment (Apache FOP 1.1 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-16">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.apache.fop.fo.extensions.ExtensionAttachment (Apache FOP 1.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/fo/extensions//class-useExtensionAttachment.html" target="_top"><B>FRAMES</B></A>
<A HREF="ExtensionAttachment.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>org.apache.fop.fo.extensions.ExtensionAttachment</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.area"><B>org.apache.fop.area</B></A></TD>
<TD>FOP's area tree. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.fo"><B>org.apache.fop.fo</B></A></TD>
<TD>Classes, constants and basic infrastructure for the FO tree. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.fo.extensions.xmp"><B>org.apache.fop.fo.extensions.xmp</B></A></TD>
<TD>Extension classes which handles <a href="http://www.adobe.com/products/xmp/">XMP metadata</a>. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.afp.extensions"><B>org.apache.fop.render.afp.extensions</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.pdf.extensions"><B>org.apache.fop.render.pdf.extensions</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.render.ps.extensions"><B>org.apache.fop.render.ps.extensions</B></A></TD>
<TD>Extensions specific to the PostScript Renderer. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.area"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A> in <A HREF="../../../../../../org/apache/fop/area/package-summary.html">org.apache.fop.area</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../org/apache/fop/area/package-summary.html">org.apache.fop.area</A> with type parameters of type <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.util.List<<A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A>></CODE></FONT></TD>
<TD><CODE><B>AreaTreeObject.</B><B><A HREF="../../../../../../org/apache/fop/area/AreaTreeObject.html#extensionAttachments">extensionAttachments</A></B></CODE>
<BR>
Extension attachments</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/fop/area/package-summary.html">org.apache.fop.area</A> that return <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>OffDocumentExtensionAttachment.</B><B><A HREF="../../../../../../org/apache/fop/area/OffDocumentExtensionAttachment.html#getAttachment()">getAttachment</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/fop/area/package-summary.html">org.apache.fop.area</A> that return types with arguments of type <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List<<A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A>></CODE></FONT></TD>
<TD><CODE><B>AreaTreeObject.</B><B><A HREF="../../../../../../org/apache/fop/area/AreaTreeObject.html#getExtensionAttachments()">getExtensionAttachments</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/fop/area/package-summary.html">org.apache.fop.area</A> with parameters of type <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>AreaTreeObject.</B><B><A HREF="../../../../../../org/apache/fop/area/AreaTreeObject.html#addExtensionAttachment(org.apache.fop.fo.extensions.ExtensionAttachment)">addExtensionAttachment</A></B>(<A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A> attachment)</CODE>
<BR>
Adds a new ExtensionAttachment instance to this page.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Method parameters in <A HREF="../../../../../../org/apache/fop/area/package-summary.html">org.apache.fop.area</A> with type arguments of type <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>AreaTreeObject.</B><B><A HREF="../../../../../../org/apache/fop/area/AreaTreeObject.html#setExtensionAttachments(java.util.List)">setExtensionAttachments</A></B>(java.util.List<<A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A>> extensionAttachments)</CODE>
<BR>
Set extension attachments from a List</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../../org/apache/fop/area/package-summary.html">org.apache.fop.area</A> with parameters of type <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/area/OffDocumentExtensionAttachment.html#OffDocumentExtensionAttachment(org.apache.fop.fo.extensions.ExtensionAttachment)">OffDocumentExtensionAttachment</A></B>(<A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A> attachment)</CODE>
<BR>
Main constructor</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.fo"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A> in <A HREF="../../../../../../org/apache/fop/fo/package-summary.html">org.apache.fop.fo</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/fop/fo/package-summary.html">org.apache.fop.fo</A> that return <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>FONode.</B><B><A HREF="../../../../../../org/apache/fop/fo/FONode.html#getExtensionAttachment()">getExtensionAttachment</A></B>()</CODE>
<BR>
This method is overridden by extension elements and allows the extension element
to return a pass-through attachment which the parent formatting objects should simply
carry with them but otherwise ignore.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.fo.extensions.xmp"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A> in <A HREF="../../../../../../org/apache/fop/fo/extensions/xmp/package-summary.html">org.apache.fop.fo.extensions.xmp</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../org/apache/fop/fo/extensions/xmp/package-summary.html">org.apache.fop.fo.extensions.xmp</A> that implement <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/fo/extensions/xmp/XMPMetadata.html" title="class in org.apache.fop.fo.extensions.xmp">XMPMetadata</A></B></CODE>
<BR>
This is the pass-through value object for the XMP metadata extension.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/fop/fo/extensions/xmp/package-summary.html">org.apache.fop.fo.extensions.xmp</A> that return <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AbstractMetadataElement.</B><B><A HREF="../../../../../../org/apache/fop/fo/extensions/xmp/AbstractMetadataElement.html#getExtensionAttachment()">getExtensionAttachment</A></B>()</CODE>
<BR>
This method is overridden by extension elements and allows the extension element
to return a pass-through attachment which the parent formatting objects should simply
carry with them but otherwise ignore.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.afp.extensions"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A> in <A HREF="../../../../../../org/apache/fop/render/afp/extensions/package-summary.html">org.apache.fop.render.afp.extensions</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../org/apache/fop/render/afp/extensions/package-summary.html">org.apache.fop.render.afp.extensions</A> that implement <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPExtensionAttachment.html" title="class in org.apache.fop.render.afp.extensions">AFPExtensionAttachment</A></B></CODE>
<BR>
This is the pass-through value object for the AFP extension.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPIncludeFormMap.html" title="class in org.apache.fop.render.afp.extensions">AFPIncludeFormMap</A></B></CODE>
<BR>
This extension allows to include an AFP form map resource.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPInvokeMediumMap.html" title="class in org.apache.fop.render.afp.extensions">AFPInvokeMediumMap</A></B></CODE>
<BR>
This is the pass-through value object for the AFP extension.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPPageOverlay.html" title="class in org.apache.fop.render.afp.extensions">AFPPageOverlay</A></B></CODE>
<BR>
This extension allows to include an AFP Page Overlay resource.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPPageSegmentElement.AFPPageSegmentSetup.html" title="class in org.apache.fop.render.afp.extensions">AFPPageSegmentElement.AFPPageSegmentSetup</A></B></CODE>
<BR>
This is the pass-through value object for the AFP extension.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPPageSetup.html" title="class in org.apache.fop.render.afp.extensions">AFPPageSetup</A></B></CODE>
<BR>
This is the pass-through value object for the AFP extension.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/fop/render/afp/extensions/package-summary.html">org.apache.fop.render.afp.extensions</A> that return <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AbstractAFPExtensionObject.</B><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.html#getExtensionAttachment()">getExtensionAttachment</A></B>()</CODE>
<BR>
This method is overridden by extension elements and allows the extension element
to return a pass-through attachment which the parent formatting objects should simply
carry with them but otherwise ignore.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AFPPageSetupElement.</B><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPPageSetupElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AFPPageSegmentElement.</B><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPPageSegmentElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AFPPageOverlayElement.</B><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPPageOverlayElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AFPInvokeMediumMapElement.</B><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPInvokeMediumMapElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AFPIncludeFormMapElement.</B><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AbstractAFPExtensionObject.</B><B><A HREF="../../../../../../org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.pdf.extensions"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A> in <A HREF="../../../../../../org/apache/fop/render/pdf/extensions/package-summary.html">org.apache.fop.render.pdf.extensions</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../org/apache/fop/render/pdf/extensions/package-summary.html">org.apache.fop.render.pdf.extensions</A> that implement <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/pdf/extensions/PDFEmbeddedFileExtensionAttachment.html" title="class in org.apache.fop.render.pdf.extensions">PDFEmbeddedFileExtensionAttachment</A></B></CODE>
<BR>
This is the pass-through value object for the PDF extension.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/pdf/extensions/PDFExtensionAttachment.html" title="class in org.apache.fop.render.pdf.extensions">PDFExtensionAttachment</A></B></CODE>
<BR>
This is the pass-through value object for the PDF extension.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/fop/render/pdf/extensions/package-summary.html">org.apache.fop.render.pdf.extensions</A> that return <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPDFExtensionElement.</B><B><A HREF="../../../../../../org/apache/fop/render/pdf/extensions/AbstractPDFExtensionElement.html#getExtensionAttachment()">getExtensionAttachment</A></B>()</CODE>
<BR>
Returns the extension attachment.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>PDFEmbeddedFileElement.</B><B><A HREF="../../../../../../org/apache/fop/render/pdf/extensions/PDFEmbeddedFileElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPDFExtensionElement.</B><B><A HREF="../../../../../../org/apache/fop/render/pdf/extensions/AbstractPDFExtensionElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.render.ps.extensions"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A> in <A HREF="../../../../../../org/apache/fop/render/ps/extensions/package-summary.html">org.apache.fop.render.ps.extensions</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../org/apache/fop/render/ps/extensions/package-summary.html">org.apache.fop.render.ps.extensions</A> that implement <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSCommentAfter.html" title="class in org.apache.fop.render.ps.extensions">PSCommentAfter</A></B></CODE>
<BR>
Custom postscript comment after class</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSCommentBefore.html" title="class in org.apache.fop.render.ps.extensions">PSCommentBefore</A></B></CODE>
<BR>
Custom postscript comment before class</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSExtensionAttachment.html" title="class in org.apache.fop.render.ps.extensions">PSExtensionAttachment</A></B></CODE>
<BR>
This is the pass-through value object for the PostScript extension.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSPageTrailerCodeBefore.html" title="class in org.apache.fop.render.ps.extensions">PSPageTrailerCodeBefore</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSSetPageDevice.html" title="class in org.apache.fop.render.ps.extensions">PSSetPageDevice</A></B></CODE>
<BR>
Element for postscript setpagedevice instruction
This is a an extension which provides a pass-through value
dictionary object for the postscript setpagedevice instruction.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSSetupCode.html" title="class in org.apache.fop.render.ps.extensions">PSSetupCode</A></B></CODE>
<BR>
This is the pass-through value object for the PostScript extension.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/fop/render/ps/extensions/package-summary.html">org.apache.fop.render.ps.extensions</A> that return <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPSExtensionObject.</B><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/AbstractPSExtensionObject.html#getExtensionAttachment()">getExtensionAttachment</A></B>()</CODE>
<BR>
This method is overridden by extension elements and allows the extension element
to return a pass-through attachment which the parent formatting objects should simply
carry with them but otherwise ignore.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPSExtensionElement.</B><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/AbstractPSExtensionElement.html#getExtensionAttachment()">getExtensionAttachment</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>PSSetPageDeviceElement.</B><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSSetPageDeviceElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>PSPageTrailerCodeBeforeElement.</B><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSPageTrailerCodeBeforeElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>PSCommentBeforeElement.</B><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSCommentBeforeElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>PSCommentAfterElement.</B><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/PSCommentAfterElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions">ExtensionAttachment</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPSExtensionElement.</B><B><A HREF="../../../../../../org/apache/fop/render/ps/extensions/AbstractPSExtensionElement.html#instantiateExtensionAttachment()">instantiateExtensionAttachment</A></B>()</CODE>
<BR>
Instantiates extension attachment object</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/fop/fo/extensions/ExtensionAttachment.html" title="interface in org.apache.fop.fo.extensions"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 1.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/fo/extensions//class-useExtensionAttachment.html" target="_top"><B>FRAMES</B></A>
<A HREF="ExtensionAttachment.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| mit |
LighthouseHPC/lighthouse | src/lighthouseProject/lighthouseProject/static/Doxygen/docs/html/cgtrfs_8f.html | 13130 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Lighthouse: lapack/cgtrfs.f File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="tabs.css" rel="stylesheet" type="text/css" />
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!--<div id="titlearea">
</div>-->
<!-- end header part -->
<!-- Generated by Doxygen 1.8.2 -->
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_42b7da8b2ebcfce3aea4b69198a0a9ad.html">lapack</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#func-members">Functions/Subroutines</a> </div>
<div class="headertitle">
<div class="title">cgtrfs.f File Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions/Subroutines</h2></td></tr>
<tr class="memitem:a92eec53c6ac6c6285a10e7d05d9c00d5"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="cgtrfs_8f.html#a92eec53c6ac6c6285a10e7d05d9c00d5">cgtrfs</a> (TRANS, N, NRHS, DL, D, DU, DLF, DF, DUF, DU2, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)</td></tr>
<tr class="memdesc:a92eec53c6ac6c6285a10e7d05d9c00d5"><td class="mdescLeft"> </td><td class="mdescRight"><b>CGTRFS</b> <a href="#a92eec53c6ac6c6285a10e7d05d9c00d5"></a><br/></td></tr>
<tr class="separator:a92eec53c6ac6c6285a10e7d05d9c00d5"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Function/Subroutine Documentation</h2>
<a class="anchor" id="a92eec53c6ac6c6285a10e7d05d9c00d5"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine cgtrfs </td>
<td>(</td>
<td class="paramtype">character </td>
<td class="paramname"><em>TRANS</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>N</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>NRHS</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( * ) </td>
<td class="paramname"><em>DL</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( * ) </td>
<td class="paramname"><em>D</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( * ) </td>
<td class="paramname"><em>DU</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( * ) </td>
<td class="paramname"><em>DLF</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( * ) </td>
<td class="paramname"><em>DF</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( * ) </td>
<td class="paramname"><em>DUF</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( * ) </td>
<td class="paramname"><em>DU2</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer, dimension( * ) </td>
<td class="paramname"><em>IPIV</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( ldb, * ) </td>
<td class="paramname"><em>B</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>LDB</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( ldx, * ) </td>
<td class="paramname"><em>X</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>LDX</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">real, dimension( * ) </td>
<td class="paramname"><em>FERR</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">real, dimension( * ) </td>
<td class="paramname"><em>BERR</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">complex, dimension( * ) </td>
<td class="paramname"><em>WORK</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">real, dimension( * ) </td>
<td class="paramname"><em>RWORK</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>INFO</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p><b>CGTRFS</b> </p>
Download CGTRFS + dependencies
<a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cgtrfs.f">
[TGZ]</a>
<a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cgtrfs.f">
[ZIP]</a>
<a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cgtrfs.f">
[TXT]</a>
<dl class="section user"><dt>Purpose: </dt><dd><pre class="fragment"> CGTRFS improves the computed solution to a system of linear
equations when the coefficient matrix is tridiagonal, and provides
error bounds and backward error estimates for the solution.</pre> </dd></dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramdir">[in]</td><td class="paramname">TRANS</td><td><pre class="fragment"> TRANS is CHARACTER*1
Specifies the form of the system of equations:
= 'N': A * X = B (No transpose)
= 'T': A**T * X = B (Transpose)
= 'C': A**H * X = B (Conjugate transpose)</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">N</td><td><pre class="fragment"> N is INTEGER
The order of the matrix A. N >= 0.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">NRHS</td><td><pre class="fragment"> NRHS is INTEGER
The number of right hand sides, i.e., the number of columns
of the matrix B. NRHS >= 0.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">DL</td><td><pre class="fragment"> DL is COMPLEX array, dimension (N-1)
The (n-1) subdiagonal elements of A.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">D</td><td><pre class="fragment"> D is COMPLEX array, dimension (N)
The diagonal elements of A.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">DU</td><td><pre class="fragment"> DU is COMPLEX array, dimension (N-1)
The (n-1) superdiagonal elements of A.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">DLF</td><td><pre class="fragment"> DLF is COMPLEX array, dimension (N-1)
The (n-1) multipliers that define the matrix L from the
LU factorization of A as computed by CGTTRF.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">DF</td><td><pre class="fragment"> DF is COMPLEX array, dimension (N)
The n diagonal elements of the upper triangular matrix U from
the LU factorization of A.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">DUF</td><td><pre class="fragment"> DUF is COMPLEX array, dimension (N-1)
The (n-1) elements of the first superdiagonal of U.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">DU2</td><td><pre class="fragment"> DU2 is COMPLEX array, dimension (N-2)
The (n-2) elements of the second superdiagonal of U.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">IPIV</td><td><pre class="fragment"> IPIV is INTEGER array, dimension (N)
The pivot indices; for 1 <= i <= n, row i of the matrix was
interchanged with row IPIV(i). IPIV(i) will always be either
i or i+1; IPIV(i) = i indicates a row interchange was not
required.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">B</td><td><pre class="fragment"> B is COMPLEX array, dimension (LDB,NRHS)
The right hand side matrix B.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">LDB</td><td><pre class="fragment"> LDB is INTEGER
The leading dimension of the array B. LDB >= max(1,N).</pre></td></tr>
<tr><td class="paramdir">[in,out]</td><td class="paramname">X</td><td><pre class="fragment"> X is COMPLEX array, dimension (LDX,NRHS)
On entry, the solution matrix X, as computed by CGTTRS.
On exit, the improved solution matrix X.</pre></td></tr>
<tr><td class="paramdir">[in]</td><td class="paramname">LDX</td><td><pre class="fragment"> LDX is INTEGER
The leading dimension of the array X. LDX >= max(1,N).</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">FERR</td><td><pre class="fragment"> FERR is REAL array, dimension (NRHS)
The estimated forward error bound for each solution vector
X(j) (the j-th column of the solution matrix X).
If XTRUE is the true solution corresponding to X(j), FERR(j)
is an estimated upper bound for the magnitude of the largest
element in (X(j) - XTRUE) divided by the magnitude of the
largest element in X(j). The estimate is as reliable as
the estimate for RCOND, and is almost always a slight
overestimate of the true error.</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">BERR</td><td><pre class="fragment"> BERR is REAL array, dimension (NRHS)
The componentwise relative backward error of each solution
vector X(j) (i.e., the smallest relative change in
any element of A or B that makes X(j) an exact solution).</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">WORK</td><td><pre class="fragment"> WORK is COMPLEX array, dimension (2*N)</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">RWORK</td><td><pre class="fragment"> RWORK is REAL array, dimension (N)</pre></td></tr>
<tr><td class="paramdir">[out]</td><td class="paramname">INFO</td><td><pre class="fragment"> INFO is INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value</pre> </td></tr>
</table>
</dd>
</dl>
<dl class="section user"><dt>Internal Parameters: </dt><dd><pre class="fragment"> ITMAX is the maximum number of steps of iterative refinement.</pre> </dd></dl>
<dl class="section author"><dt>Author</dt><dd>Univ. of Tennessee </dd>
<dd>
Univ. of California Berkeley </dd>
<dd>
Univ. of Colorado Denver </dd>
<dd>
NAG Ltd. </dd></dl>
<dl class="section date"><dt>Date</dt><dd>November 2011 </dd></dl>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Mon Jul 14 2014 18:28:48 for Lighthouse by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.2
</small></address>
</body>
</html>
| mit |
PrJared/sabbath-school-lessons | src/ja/2019-02/02/02.md | 2753 | ---
title: 自由意志、自由選択
date: 07/04/2019
---
神は、人間が生まれる前ですら、その人が救われるか否かをすでに選択しておられる、と信じるクリスチャンがいます。つまり、最終的に永遠に滅びる人たちは、神が御自分の知恵によって、そうなるように選択されたからだと、この神学は主張するのです。ということはつまり、その人が罪に定められるのは、彼/彼女の選択にかかわらないということです。
幸いなことに、私たちアドベンチストはそのような神学を認めません。そうではなく、神は、私たち全員が救われるように選択してくださり、この世が始まる前ですら、私たちは神において永遠の命を持つように選ばれたと、アドベンチストは信じます。
`問1: エフェソ 1:1 ~ 4、テトス 1:1、2、Ⅱテモテ 1:8、9 を読んでください。これらの聖句は、神によって選ばれることや、私たちがいつ選ばれたのかということについて、何と教えていますか。`
この知らせがいかに良いものであろうと、ある人たちはそれでも滅びます(マタ25:41)。なぜなら神が、私たち全員をお選びくださったものの、自由意志という最も聖なる賜物を人間にお与えになったからです。
`問2: マタイ 22:35 ~ 37 は、自由意志についてどのようなことを教えていますか。`
「主を愛しなさい」と、主は私たちを強制なさいません。愛が愛であるために、愛は進んで与えられねばならないのです。いろいろな意味で、聖書は、さまよえる人間に手を差し伸べ、強いることなく、彼らの心を獲得しようとする神の物語だ、と言うことができます。この事実が最もよくわかるのは、イエスの御生涯と働き、そして人々が(自由意志を用いて)いかに彼に応じたかということの中においてです。彼に魅了された人もいれば、彼を殺したいと思った人もいました。
確かに神は、私たちが救われるように選んでくださいましたが、最終的に、その救いを受け入れる選択は、私たちがしなければなりません。私たちが行わなければならないあらゆる選択の中で、主に仕えるという選択は、群を抜いて、私たちと、私たちの人生やその中での選択によって影響を受ける人たち(身近な家族など)にとって最も重大です。そのことは、疑いの余地がありません。
`ノート` | mit |
m1nuz/ironforge | lib/GLcore/include/glcore_es2.h | 26563 | /* Generated by glcoregen v2 */
#pragma once
#include <GLES2/gl2.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Core GL API */
int glLoadFunctions(void);
void *nativeGetProcAddress(const char *proc);
/* OpenGL function prototypes */
#define APIENTRYP *
typedef void ( APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
typedef void ( APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
typedef void ( APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name);
typedef void ( APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
typedef void ( APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer);
typedef void ( APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer);
typedef void ( APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
typedef void ( APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
typedef void ( APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
typedef void ( APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
typedef void ( APIENTRYP PFNGLBLENDFUNCPROC) (GLenum sfactor, GLenum dfactor);
typedef void ( APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
typedef void ( APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
typedef void ( APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
typedef GLenum ( APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target);
typedef void ( APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
typedef void ( APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
typedef void ( APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d);
typedef void ( APIENTRYP PFNGLCLEARSTENCILPROC) (GLint s);
typedef void ( APIENTRYP PFNGLCOLORMASKPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
typedef void ( APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
typedef void ( APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data);
typedef void ( APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data);
typedef void ( APIENTRYP PFNGLCOPYTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
typedef void ( APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
typedef GLuint ( APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
typedef GLuint ( APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
typedef void ( APIENTRYP PFNGLCULLFACEPROC) (GLenum mode);
typedef void ( APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
typedef void ( APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers);
typedef void ( APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
typedef void ( APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers);
typedef void ( APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
typedef void ( APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
typedef void ( APIENTRYP PFNGLDEPTHFUNCPROC) (GLenum func);
typedef void ( APIENTRYP PFNGLDEPTHMASKPROC) (GLboolean flag);
typedef void ( APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f);
typedef void ( APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
typedef void ( APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
typedef void ( APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef void ( APIENTRYP PFNGLDRAWARRAYSPROC) (GLenum mode, GLint first, GLsizei count);
typedef void ( APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
typedef void ( APIENTRYP PFNGLENABLEPROC) (GLenum cap);
typedef void ( APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef void ( APIENTRYP PFNGLFINISHPROC) (void);
typedef void ( APIENTRYP PFNGLFLUSHPROC) (void);
typedef void ( APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
typedef void ( APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
typedef void ( APIENTRYP PFNGLFRONTFACEPROC) (GLenum mode);
typedef void ( APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
typedef void ( APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target);
typedef void ( APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers);
typedef void ( APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers);
typedef void ( APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
typedef void ( APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
typedef void ( APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
typedef void ( APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders);
typedef GLint ( APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void ( APIENTRYP PFNGLGETBOOLEANVPROC) (GLenum pname, GLboolean *data);
typedef void ( APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
typedef GLenum ( APIENTRYP PFNGLGETERRORPROC) (void);
typedef void ( APIENTRYP PFNGLGETFLOATVPROC) (GLenum pname, GLfloat *data);
typedef void ( APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);
typedef void ( APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
typedef void ( APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
typedef void ( APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef void ( APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
typedef void ( APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
typedef void ( APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef void ( APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision);
typedef void ( APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);
typedef const GLubyte *( APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
typedef void ( APIENTRYP PFNGLGETTEXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
typedef void ( APIENTRYP PFNGLGETTEXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
typedef void ( APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params);
typedef void ( APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params);
typedef GLint ( APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void ( APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params);
typedef void ( APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
typedef void ( APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);
typedef void ( APIENTRYP PFNGLHINTPROC) (GLenum target, GLenum mode);
typedef GLboolean ( APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer);
typedef GLboolean ( APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
typedef GLboolean ( APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer);
typedef GLboolean ( APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
typedef GLboolean ( APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer);
typedef GLboolean ( APIENTRYP PFNGLISSHADERPROC) (GLuint shader);
typedef GLboolean ( APIENTRYP PFNGLISTEXTUREPROC) (GLuint texture);
typedef void ( APIENTRYP PFNGLLINEWIDTHPROC) (GLfloat width);
typedef void ( APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
typedef void ( APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
typedef void ( APIENTRYP PFNGLPOLYGONOFFSETPROC) (GLfloat factor, GLfloat units);
typedef void ( APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
typedef void ( APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void);
typedef void ( APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
typedef void ( APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert);
typedef void ( APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
typedef void ( APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length);
typedef void ( APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
typedef void ( APIENTRYP PFNGLSTENCILFUNCPROC) (GLenum func, GLint ref, GLuint mask);
typedef void ( APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask);
typedef void ( APIENTRYP PFNGLSTENCILMASKPROC) (GLuint mask);
typedef void ( APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask);
typedef void ( APIENTRYP PFNGLSTENCILOPPROC) (GLenum fail, GLenum zfail, GLenum zpass);
typedef void ( APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
typedef void ( APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
typedef void ( APIENTRYP PFNGLTEXPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat param);
typedef void ( APIENTRYP PFNGLTEXPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
typedef void ( APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
typedef void ( APIENTRYP PFNGLTEXPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
typedef void ( APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
typedef void ( APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0);
typedef void ( APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value);
typedef void ( APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
typedef void ( APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value);
typedef void ( APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1);
typedef void ( APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value);
typedef void ( APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1);
typedef void ( APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value);
typedef void ( APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
typedef void ( APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value);
typedef void ( APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2);
typedef void ( APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value);
typedef void ( APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
typedef void ( APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value);
typedef void ( APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
typedef void ( APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value);
typedef void ( APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void ( APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void ( APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void ( APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
typedef void ( APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program);
typedef void ( APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x);
typedef void ( APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v);
typedef void ( APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y);
typedef void ( APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v);
typedef void ( APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
typedef void ( APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v);
typedef void ( APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
typedef void ( APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v);
typedef void ( APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
typedef void ( APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
/* OpenGL functions*/
extern PFNGLACTIVETEXTUREPROC _glActiveTexture;
extern PFNGLATTACHSHADERPROC _glAttachShader;
extern PFNGLBINDATTRIBLOCATIONPROC _glBindAttribLocation;
extern PFNGLBINDBUFFERPROC _glBindBuffer;
extern PFNGLBINDFRAMEBUFFERPROC _glBindFramebuffer;
extern PFNGLBINDRENDERBUFFERPROC _glBindRenderbuffer;
extern PFNGLBINDTEXTUREPROC _glBindTexture;
extern PFNGLBLENDCOLORPROC _glBlendColor;
extern PFNGLBLENDEQUATIONPROC _glBlendEquation;
extern PFNGLBLENDEQUATIONSEPARATEPROC _glBlendEquationSeparate;
extern PFNGLBLENDFUNCPROC _glBlendFunc;
extern PFNGLBLENDFUNCSEPARATEPROC _glBlendFuncSeparate;
extern PFNGLBUFFERDATAPROC _glBufferData;
extern PFNGLBUFFERSUBDATAPROC _glBufferSubData;
extern PFNGLCHECKFRAMEBUFFERSTATUSPROC _glCheckFramebufferStatus;
extern PFNGLCLEARPROC _glClear;
extern PFNGLCLEARCOLORPROC _glClearColor;
extern PFNGLCLEARDEPTHFPROC _glClearDepthf;
extern PFNGLCLEARSTENCILPROC _glClearStencil;
extern PFNGLCOLORMASKPROC _glColorMask;
extern PFNGLCOMPILESHADERPROC _glCompileShader;
extern PFNGLCOMPRESSEDTEXIMAGE2DPROC _glCompressedTexImage2D;
extern PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC _glCompressedTexSubImage2D;
extern PFNGLCOPYTEXIMAGE2DPROC _glCopyTexImage2D;
extern PFNGLCOPYTEXSUBIMAGE2DPROC _glCopyTexSubImage2D;
extern PFNGLCREATEPROGRAMPROC _glCreateProgram;
extern PFNGLCREATESHADERPROC _glCreateShader;
extern PFNGLCULLFACEPROC _glCullFace;
extern PFNGLDELETEBUFFERSPROC _glDeleteBuffers;
extern PFNGLDELETEFRAMEBUFFERSPROC _glDeleteFramebuffers;
extern PFNGLDELETEPROGRAMPROC _glDeleteProgram;
extern PFNGLDELETERENDERBUFFERSPROC _glDeleteRenderbuffers;
extern PFNGLDELETESHADERPROC _glDeleteShader;
extern PFNGLDELETETEXTURESPROC _glDeleteTextures;
extern PFNGLDEPTHFUNCPROC _glDepthFunc;
extern PFNGLDEPTHMASKPROC _glDepthMask;
extern PFNGLDEPTHRANGEFPROC _glDepthRangef;
extern PFNGLDETACHSHADERPROC _glDetachShader;
extern PFNGLDISABLEPROC _glDisable;
extern PFNGLDISABLEVERTEXATTRIBARRAYPROC _glDisableVertexAttribArray;
extern PFNGLDRAWARRAYSPROC _glDrawArrays;
extern PFNGLDRAWELEMENTSPROC _glDrawElements;
extern PFNGLENABLEPROC _glEnable;
extern PFNGLENABLEVERTEXATTRIBARRAYPROC _glEnableVertexAttribArray;
extern PFNGLFINISHPROC _glFinish;
extern PFNGLFLUSHPROC _glFlush;
extern PFNGLFRAMEBUFFERRENDERBUFFERPROC _glFramebufferRenderbuffer;
extern PFNGLFRAMEBUFFERTEXTURE2DPROC _glFramebufferTexture2D;
extern PFNGLFRONTFACEPROC _glFrontFace;
extern PFNGLGENBUFFERSPROC _glGenBuffers;
extern PFNGLGENERATEMIPMAPPROC _glGenerateMipmap;
extern PFNGLGENFRAMEBUFFERSPROC _glGenFramebuffers;
extern PFNGLGENRENDERBUFFERSPROC _glGenRenderbuffers;
extern PFNGLGENTEXTURESPROC _glGenTextures;
extern PFNGLGETACTIVEATTRIBPROC _glGetActiveAttrib;
extern PFNGLGETACTIVEUNIFORMPROC _glGetActiveUniform;
extern PFNGLGETATTACHEDSHADERSPROC _glGetAttachedShaders;
extern PFNGLGETATTRIBLOCATIONPROC _glGetAttribLocation;
extern PFNGLGETBOOLEANVPROC _glGetBooleanv;
extern PFNGLGETBUFFERPARAMETERIVPROC _glGetBufferParameteriv;
extern PFNGLGETERRORPROC _glGetError;
extern PFNGLGETFLOATVPROC _glGetFloatv;
extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC _glGetFramebufferAttachmentParameteriv;
extern PFNGLGETINTEGERVPROC _glGetIntegerv;
extern PFNGLGETPROGRAMIVPROC _glGetProgramiv;
extern PFNGLGETPROGRAMINFOLOGPROC _glGetProgramInfoLog;
extern PFNGLGETRENDERBUFFERPARAMETERIVPROC _glGetRenderbufferParameteriv;
extern PFNGLGETSHADERIVPROC _glGetShaderiv;
extern PFNGLGETSHADERINFOLOGPROC _glGetShaderInfoLog;
extern PFNGLGETSHADERPRECISIONFORMATPROC _glGetShaderPrecisionFormat;
extern PFNGLGETSHADERSOURCEPROC _glGetShaderSource;
extern PFNGLGETSTRINGPROC _glGetString;
extern PFNGLGETTEXPARAMETERFVPROC _glGetTexParameterfv;
extern PFNGLGETTEXPARAMETERIVPROC _glGetTexParameteriv;
extern PFNGLGETUNIFORMFVPROC _glGetUniformfv;
extern PFNGLGETUNIFORMIVPROC _glGetUniformiv;
extern PFNGLGETUNIFORMLOCATIONPROC _glGetUniformLocation;
extern PFNGLGETVERTEXATTRIBFVPROC _glGetVertexAttribfv;
extern PFNGLGETVERTEXATTRIBIVPROC _glGetVertexAttribiv;
extern PFNGLGETVERTEXATTRIBPOINTERVPROC _glGetVertexAttribPointerv;
extern PFNGLHINTPROC _glHint;
extern PFNGLISBUFFERPROC _glIsBuffer;
extern PFNGLISENABLEDPROC _glIsEnabled;
extern PFNGLISFRAMEBUFFERPROC _glIsFramebuffer;
extern PFNGLISPROGRAMPROC _glIsProgram;
extern PFNGLISRENDERBUFFERPROC _glIsRenderbuffer;
extern PFNGLISSHADERPROC _glIsShader;
extern PFNGLISTEXTUREPROC _glIsTexture;
extern PFNGLLINEWIDTHPROC _glLineWidth;
extern PFNGLLINKPROGRAMPROC _glLinkProgram;
extern PFNGLPIXELSTOREIPROC _glPixelStorei;
extern PFNGLPOLYGONOFFSETPROC _glPolygonOffset;
extern PFNGLREADPIXELSPROC _glReadPixels;
extern PFNGLRELEASESHADERCOMPILERPROC _glReleaseShaderCompiler;
extern PFNGLRENDERBUFFERSTORAGEPROC _glRenderbufferStorage;
extern PFNGLSAMPLECOVERAGEPROC _glSampleCoverage;
extern PFNGLSCISSORPROC _glScissor;
extern PFNGLSHADERBINARYPROC _glShaderBinary;
extern PFNGLSHADERSOURCEPROC _glShaderSource;
extern PFNGLSTENCILFUNCPROC _glStencilFunc;
extern PFNGLSTENCILFUNCSEPARATEPROC _glStencilFuncSeparate;
extern PFNGLSTENCILMASKPROC _glStencilMask;
extern PFNGLSTENCILMASKSEPARATEPROC _glStencilMaskSeparate;
extern PFNGLSTENCILOPPROC _glStencilOp;
extern PFNGLSTENCILOPSEPARATEPROC _glStencilOpSeparate;
extern PFNGLTEXIMAGE2DPROC _glTexImage2D;
extern PFNGLTEXPARAMETERFPROC _glTexParameterf;
extern PFNGLTEXPARAMETERFVPROC _glTexParameterfv;
extern PFNGLTEXPARAMETERIPROC _glTexParameteri;
extern PFNGLTEXPARAMETERIVPROC _glTexParameteriv;
extern PFNGLTEXSUBIMAGE2DPROC _glTexSubImage2D;
extern PFNGLUNIFORM1FPROC _glUniform1f;
extern PFNGLUNIFORM1FVPROC _glUniform1fv;
extern PFNGLUNIFORM1IPROC _glUniform1i;
extern PFNGLUNIFORM1IVPROC _glUniform1iv;
extern PFNGLUNIFORM2FPROC _glUniform2f;
extern PFNGLUNIFORM2FVPROC _glUniform2fv;
extern PFNGLUNIFORM2IPROC _glUniform2i;
extern PFNGLUNIFORM2IVPROC _glUniform2iv;
extern PFNGLUNIFORM3FPROC _glUniform3f;
extern PFNGLUNIFORM3FVPROC _glUniform3fv;
extern PFNGLUNIFORM3IPROC _glUniform3i;
extern PFNGLUNIFORM3IVPROC _glUniform3iv;
extern PFNGLUNIFORM4FPROC _glUniform4f;
extern PFNGLUNIFORM4FVPROC _glUniform4fv;
extern PFNGLUNIFORM4IPROC _glUniform4i;
extern PFNGLUNIFORM4IVPROC _glUniform4iv;
extern PFNGLUNIFORMMATRIX2FVPROC _glUniformMatrix2fv;
extern PFNGLUNIFORMMATRIX3FVPROC _glUniformMatrix3fv;
extern PFNGLUNIFORMMATRIX4FVPROC _glUniformMatrix4fv;
extern PFNGLUSEPROGRAMPROC _glUseProgram;
extern PFNGLVALIDATEPROGRAMPROC _glValidateProgram;
extern PFNGLVERTEXATTRIB1FPROC _glVertexAttrib1f;
extern PFNGLVERTEXATTRIB1FVPROC _glVertexAttrib1fv;
extern PFNGLVERTEXATTRIB2FPROC _glVertexAttrib2f;
extern PFNGLVERTEXATTRIB2FVPROC _glVertexAttrib2fv;
extern PFNGLVERTEXATTRIB3FPROC _glVertexAttrib3f;
extern PFNGLVERTEXATTRIB3FVPROC _glVertexAttrib3fv;
extern PFNGLVERTEXATTRIB4FPROC _glVertexAttrib4f;
extern PFNGLVERTEXATTRIB4FVPROC _glVertexAttrib4fv;
extern PFNGLVERTEXATTRIBPOINTERPROC _glVertexAttribPointer;
extern PFNGLVIEWPORTPROC _glViewport;
#define glActiveTexture _glActiveTexture
#define glAttachShader _glAttachShader
#define glBindAttribLocation _glBindAttribLocation
#define glBindBuffer _glBindBuffer
#define glBindFramebuffer _glBindFramebuffer
#define glBindRenderbuffer _glBindRenderbuffer
#define glBindTexture _glBindTexture
#define glBlendColor _glBlendColor
#define glBlendEquation _glBlendEquation
#define glBlendEquationSeparate _glBlendEquationSeparate
#define glBlendFunc _glBlendFunc
#define glBlendFuncSeparate _glBlendFuncSeparate
#define glBufferData _glBufferData
#define glBufferSubData _glBufferSubData
#define glCheckFramebufferStatus _glCheckFramebufferStatus
#define glClear _glClear
#define glClearColor _glClearColor
#define glClearDepthf _glClearDepthf
#define glClearStencil _glClearStencil
#define glColorMask _glColorMask
#define glCompileShader _glCompileShader
#define glCompressedTexImage2D _glCompressedTexImage2D
#define glCompressedTexSubImage2D _glCompressedTexSubImage2D
#define glCopyTexImage2D _glCopyTexImage2D
#define glCopyTexSubImage2D _glCopyTexSubImage2D
#define glCreateProgram _glCreateProgram
#define glCreateShader _glCreateShader
#define glCullFace _glCullFace
#define glDeleteBuffers _glDeleteBuffers
#define glDeleteFramebuffers _glDeleteFramebuffers
#define glDeleteProgram _glDeleteProgram
#define glDeleteRenderbuffers _glDeleteRenderbuffers
#define glDeleteShader _glDeleteShader
#define glDeleteTextures _glDeleteTextures
#define glDepthFunc _glDepthFunc
#define glDepthMask _glDepthMask
#define glDepthRangef _glDepthRangef
#define glDetachShader _glDetachShader
#define glDisable _glDisable
#define glDisableVertexAttribArray _glDisableVertexAttribArray
#define glDrawArrays _glDrawArrays
#define glDrawElements _glDrawElements
#define glEnable _glEnable
#define glEnableVertexAttribArray _glEnableVertexAttribArray
#define glFinish _glFinish
#define glFlush _glFlush
#define glFramebufferRenderbuffer _glFramebufferRenderbuffer
#define glFramebufferTexture2D _glFramebufferTexture2D
#define glFrontFace _glFrontFace
#define glGenBuffers _glGenBuffers
#define glGenerateMipmap _glGenerateMipmap
#define glGenFramebuffers _glGenFramebuffers
#define glGenRenderbuffers _glGenRenderbuffers
#define glGenTextures _glGenTextures
#define glGetActiveAttrib _glGetActiveAttrib
#define glGetActiveUniform _glGetActiveUniform
#define glGetAttachedShaders _glGetAttachedShaders
#define glGetAttribLocation _glGetAttribLocation
#define glGetBooleanv _glGetBooleanv
#define glGetBufferParameteriv _glGetBufferParameteriv
#define glGetError _glGetError
#define glGetFloatv _glGetFloatv
#define glGetFramebufferAttachmentParameteriv _glGetFramebufferAttachmentParameteriv
#define glGetIntegerv _glGetIntegerv
#define glGetProgramiv _glGetProgramiv
#define glGetProgramInfoLog _glGetProgramInfoLog
#define glGetRenderbufferParameteriv _glGetRenderbufferParameteriv
#define glGetShaderiv _glGetShaderiv
#define glGetShaderInfoLog _glGetShaderInfoLog
#define glGetShaderPrecisionFormat _glGetShaderPrecisionFormat
#define glGetShaderSource _glGetShaderSource
#define glGetString _glGetString
#define glGetTexParameterfv _glGetTexParameterfv
#define glGetTexParameteriv _glGetTexParameteriv
#define glGetUniformfv _glGetUniformfv
#define glGetUniformiv _glGetUniformiv
#define glGetUniformLocation _glGetUniformLocation
#define glGetVertexAttribfv _glGetVertexAttribfv
#define glGetVertexAttribiv _glGetVertexAttribiv
#define glGetVertexAttribPointerv _glGetVertexAttribPointerv
#define glHint _glHint
#define glIsBuffer _glIsBuffer
#define glIsEnabled _glIsEnabled
#define glIsFramebuffer _glIsFramebuffer
#define glIsProgram _glIsProgram
#define glIsRenderbuffer _glIsRenderbuffer
#define glIsShader _glIsShader
#define glIsTexture _glIsTexture
#define glLineWidth _glLineWidth
#define glLinkProgram _glLinkProgram
#define glPixelStorei _glPixelStorei
#define glPolygonOffset _glPolygonOffset
#define glReadPixels _glReadPixels
#define glReleaseShaderCompiler _glReleaseShaderCompiler
#define glRenderbufferStorage _glRenderbufferStorage
#define glSampleCoverage _glSampleCoverage
#define glScissor _glScissor
#define glShaderBinary _glShaderBinary
#define glShaderSource _glShaderSource
#define glStencilFunc _glStencilFunc
#define glStencilFuncSeparate _glStencilFuncSeparate
#define glStencilMask _glStencilMask
#define glStencilMaskSeparate _glStencilMaskSeparate
#define glStencilOp _glStencilOp
#define glStencilOpSeparate _glStencilOpSeparate
#define glTexImage2D _glTexImage2D
#define glTexParameterf _glTexParameterf
#define glTexParameterfv _glTexParameterfv
#define glTexParameteri _glTexParameteri
#define glTexParameteriv _glTexParameteriv
#define glTexSubImage2D _glTexSubImage2D
#define glUniform1f _glUniform1f
#define glUniform1fv _glUniform1fv
#define glUniform1i _glUniform1i
#define glUniform1iv _glUniform1iv
#define glUniform2f _glUniform2f
#define glUniform2fv _glUniform2fv
#define glUniform2i _glUniform2i
#define glUniform2iv _glUniform2iv
#define glUniform3f _glUniform3f
#define glUniform3fv _glUniform3fv
#define glUniform3i _glUniform3i
#define glUniform3iv _glUniform3iv
#define glUniform4f _glUniform4f
#define glUniform4fv _glUniform4fv
#define glUniform4i _glUniform4i
#define glUniform4iv _glUniform4iv
#define glUniformMatrix2fv _glUniformMatrix2fv
#define glUniformMatrix3fv _glUniformMatrix3fv
#define glUniformMatrix4fv _glUniformMatrix4fv
#define glUseProgram _glUseProgram
#define glValidateProgram _glValidateProgram
#define glVertexAttrib1f _glVertexAttrib1f
#define glVertexAttrib1fv _glVertexAttrib1fv
#define glVertexAttrib2f _glVertexAttrib2f
#define glVertexAttrib2fv _glVertexAttrib2fv
#define glVertexAttrib3f _glVertexAttrib3f
#define glVertexAttrib3fv _glVertexAttrib3fv
#define glVertexAttrib4f _glVertexAttrib4f
#define glVertexAttrib4fv _glVertexAttrib4fv
#define glVertexAttribPointer _glVertexAttribPointer
#define glViewport _glViewport
#ifdef __cplusplus
}
#endif
| mit |
ebberly/johnny-five-tutorial | node_modules/johnny-five/Gruntfile.js | 5627 | var inspect = require("util").inspect,
fs = require("fs");
module.exports = function(grunt) {
var task = grunt.task;
var file = grunt.file;
var log = grunt.log;
var verbose = grunt.verbose;
var fail = grunt.fail;
var option = grunt.option;
var config = grunt.config;
var template = grunt.template;
var _ = grunt.util._;
var templates = {
doc: _.template( file.read("tpl/.docs.md") ),
img: _.template( file.read("tpl/.img.md") ),
fritzing: _.template( file.read("tpl/.fritzing.md") ),
doclink: _.template( file.read("tpl/.readme.doclink.md") ),
readme: _.template( file.read("tpl/.readme.md") )
};
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
docs: {
files: ["programs.json"]
},
nodeunit: {
tests: [
"test/board.js",
"test/button.js",
"test/options.js",
"test/pins.js",
"test/capabilities.js",
"test/led.js",
"test/pin.js",
"test/pir.js",
"test/sensor.js",
"test/ping.js",
"test/shiftregister.js"
]
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
node: true,
strict: false,
globals: {
exports: true,
document: true,
$: true,
Radar: true,
WeakMap: true,
window: true
}
},
files: {
src: ["Gruntfile.js", "lib/**/!(johnny-five)*.js", "test/**/*.js", "eg/**/*.js"]
}
},
jsbeautifier: {
files: ["lib/**/*.js"],
options: {
js: {
braceStyle: "collapse",
breakChainedMethods: false,
e4x: false,
evalCode: false,
indentChar: " ",
indentLevel: 0,
indentSize: 2,
indentWithTabs: false,
jslintHappy: false,
keepArrayIndentation: false,
keepFunctionIndentation: false,
maxPreserveNewlines: 10,
preserveNewlines: true,
spaceBeforeConditional: true,
spaceInParen: false,
unescapeStrings: false,
wrapLineLength: 0
}
}
}
});
// Default tasks are contrib plugins
grunt.loadNpmTasks("grunt-contrib-nodeunit");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-jsbeautifier");
// Default task.
grunt.registerTask("default", ["jshint", "nodeunit"]);
grunt.registerMultiTask("docs", "generate simple docs from examples", function() {
// Concat specified files.
var entries, readme;
entries = JSON.parse(file.read(file.expand( this.data )));
readme = [];
entries.forEach(function( entry ) {
var values, markdown, eg, md, png, fzz, title,
hasPng, hasFzz, inMarkdown, filepath, fritzfile, fritzpath;
if ( Array.isArray(entry) ) {
// Produces:
// "### Heading\n"
readme.push( "\n### " + entry[0] + "\n" );
// TODO: figure out a way to have tiered subheadings
// readme.push(
// entry.reduce(function( prev, val, k ) {
// // Produces:
// // "### Board\n"
// return prev + (Array(k + 4).join("#")) + " " + val + "\n";
// }, "")
// );
}
else {
filepath = "eg/" + entry;
eg = file.read( filepath );
md = "docs/" + entry.replace(".js", ".md");
png = "docs/breadboard/" + entry.replace(".js", ".png");
fzz = "docs/breadboard/" + entry.replace(".js", ".fzz");
title = entry;
markdown = [];
// Generate a title string from the file name
[ [ /^.+\//, "" ],
[ /\.js/, "" ],
[ /\-/g, " " ]
].forEach(function( args ) {
title = "".replace.apply( title, args );
});
fritzpath = fzz.split("/");
fritzfile = fritzpath[ fritzpath.length - 1 ];
inMarkdown = false;
// Modify code in example to appear as it would if installed via npm
eg = eg.replace("../lib/johnny-five.js", "johnny-five")
.split("\n").filter(function( line ) {
if ( /@markdown/.test(line) ) {
inMarkdown = !inMarkdown;
return false;
}
if ( inMarkdown ) {
line = line.trim();
if ( line ) {
markdown.push(
line.replace(/^\/\//, "").trim()
);
}
// Filter out the markdown lines
// from the main content.
return false;
}
return true;
}).join("\n");
hasPng = fs.existsSync(png);
hasFzz = fs.existsSync(fzz);
// console.log( markdown );
values = {
title: _.titleize(title),
command: "node " + filepath,
example: eg,
file: md,
markdown: markdown.join("\n"),
breadboard: hasPng ? templates.img({ png: png }) : "",
fritzing: hasFzz ? templates.fritzing({ fzz: fzz }) : ""
};
// Write the file to /docs/*
file.write( md, templates.doc(values) );
// Push a rendered markdown link into the readme "index"
readme.push( templates.doclink(values) );
}
});
// Write the readme with doc link index
file.write( "README.md", templates.readme({ doclinks: readme.join("") }) );
log.writeln("Docs created.");
});
};
| mit |
svrc-pivotal/Calavera | cookbooks/base/recipes/_hosts.rb | 881 | # Cookbook Name:: shared
# Recipe:: _hosts - run on base node - copies and sets permissions on host file
#
# Copyright (c) 2015 Charles T Betz, All Rights Reserved.
# Recipe for all nodes within Calavera
# from files directory
#ssh and network setup
# from files directory
file_map = {
"calaverahosts" => "/home/vagrant/calaverahosts", # there is now a recipe for managing hosts
}
# download each file and place it in right directory
file_map.each do | fileName, pathName |
cookbook_file fileName do
path pathName
mode 0755
#user "xx"
#group "xx"
action :create
end
end
# convert next 2 commands to the hostsfile cookbook?
execute 'configure host file' do
command 'cat /home/vagrant/calaverahosts >> /etc/hosts' # REALLY not idempotent. just put a touch x guard
end
execute 'remove host file' do
command 'rm /home/vagrant/calaverahosts'
end
| mit |
alphagov/spotlight | app/common/collections/grouped_timeseries.js | 2654 | define([
'extensions/collections/collection'
],
function (Collection) {
return Collection.extend({
initialize: function (models, options) {
if(options !== undefined){
options.flattenEverything = false;
}
return Collection.prototype.initialize.apply(this, arguments);
},
parse: function () {
var data = Collection.prototype.parse.apply(this, arguments);
var lines = this.options.axes.y;
var hasOther = _.findWhere(lines, { groupId: 'other' });
if (this.options.groupMapping) {
_.each(this.options.groupMapping, function (to, from) {
from = new RegExp(from + ':' + this.valueAttr);
_.each(data, function (model) {
var toAttr = to + ':' + this.valueAttr;
var sum = 0;
_.each(model, function (val, key) {
if (key.match(from)) {
if (val) {
sum += val;
}
delete model[key];
}
});
if (model[toAttr] === undefined) {
model[toAttr] = 0;
}
model[toAttr] += sum;
}, this);
}, this);
}
_.each(data, function (model) {
var total = null,
other = null;
_.each(model, function (val, key) {
var index = key.indexOf(this.valueAttr);
if (index > 1 && model[key]) {
// get the prefix value
var group = key.replace(':' + this.valueAttr, '');
var axis = _.findWhere(lines, { groupId: group });
if (axis || hasOther) {
total += model[key];
}
if (!axis) {
other += model[key];
delete model[key];
}
}
}, this);
model['other:' + this.valueAttr] = other;
model['total:' + this.valueAttr] = total;
_.each(lines, function (line) {
var prop = (line.key || line.groupId) + ':' + this.valueAttr;
var value = model[prop];
if (value === undefined) {
value = model[prop] = null;
}
if (model['total:' + this.valueAttr]) {
model[prop + ':percent'] = value / model['total:' + this.valueAttr];
} else {
model[prop + ':percent'] = null;
}
}, this);
}, this);
return data;
},
getYAxes: function () {
var axes = Collection.prototype.getYAxes.apply(this, arguments);
_.each(this.options.groupMapping, function (to, from) {
axes.push({ groupId: from });
});
return axes;
}
});
});
| mit |
zhitko/speech-apps | utills/SPTK/mc2b/mc2b.c | 6890 | /* ----------------------------------------------------------------- */
/* The Speech Signal Processing Toolkit (SPTK) */
/* developed by SPTK Working Group */
/* http://sp-tk.sourceforge.net/ */
/* ----------------------------------------------------------------- */
/* */
/* Copyright (c) 1984-2007 Tokyo Institute of Technology */
/* Interdisciplinary Graduate School of */
/* Science and Engineering */
/* */
/* 1996-2013 Nagoya Institute of Technology */
/* Department of Computer Science */
/* */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* - Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials provided */
/* with the distribution. */
/* - Neither the name of the SPTK working group nor the names of its */
/* contributors may be used to endorse or promote products derived */
/* from this software without specific prior written permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND */
/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */
/* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */
/* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY */
/* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
/* ----------------------------------------------------------------- */
/************************************************************************
* *
* Transform Mel Cepstrum to MLSA Digital Filter Coefficients *
* *
* 1995.12 K.Koishida *
* *
* usage: *
* mc2b [ options ] [ infile ] > stdout *
* options: *
* -a a : all-pass constant [0.35] *
* -m m : order of mel cepstrum [25] *
* infile: *
* mel cepstral coefficients *
* , c~(0), c~(1), ..., c~(M), *
* stdout: *
* MLSA filter coefficients *
* , b(0), b(1), ..., b(M), *
* require: *
* mc2b() *
* *
************************************************************************/
static char *rcs_id = "$Id:";
/* Standard C Libraries */
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_STRING_H
# include <string.h>
#else
# include <strings.h>
# ifndef HAVE_STRRCHR
# define strrchr rindex
# endif
#endif
#if defined(WIN32)
# include "SPTK.h"
#else
# include <SPTK.h>
#endif
/* Default Values */
#define ALPHA 0.35
#define ORDER 25
/* Command Name */
char *cmnd;
void usage(int status)
{
fprintf(stderr, "\n");
fprintf(stderr, " %s - transform mel cepstrum \n", cmnd);
fprintf(stderr, " to MLSA digital filter coefficients\n");
fprintf(stderr, "\n");
fprintf(stderr, " usage:\n");
fprintf(stderr, " %s [ options ] [ infile ] > stdout\n", cmnd);
fprintf(stderr, " options:\n");
fprintf(stderr, " -a a : all-pass constant [%g]\n", ALPHA);
fprintf(stderr, " -m m : order of mel-cepstrum [%d]\n", ORDER);
fprintf(stderr, " -h : print this message\n");
fprintf(stderr, " infile:\n");
fprintf(stderr, " mel-cepstrum (%s) [stdin]\n", FORMAT);
fprintf(stderr, " stdout:\n");
fprintf(stderr, " MLSA filter coefficients (%s)\n", FORMAT);
#ifdef PACKAGE_VERSION
fprintf(stderr, "\n");
fprintf(stderr, " SPTK: version %s\n", PACKAGE_VERSION);
fprintf(stderr, " CVS Info: %s", rcs_id);
#endif
fprintf(stderr, "\n");
exit(status);
}
int main(int argc, char **argv)
{
int m = ORDER, m1;
FILE *fp = stdin;
double a = ALPHA, *x;
if ((cmnd = strrchr(argv[0], '/')) == NULL)
cmnd = argv[0];
else
cmnd++;
while (--argc)
if (**++argv == '-') {
switch (*(*argv + 1)) {
case 'a':
a = atof(*++argv);
--argc;
break;
case 'm':
m = atoi(*++argv);
--argc;
break;
case 'h':
usage(0);
default:
fprintf(stderr, "%s : Invalid option '%c'!\n", cmnd, *(*argv + 1));
usage(1);
}
} else
fp = getfp(*argv, "rb");
m1 = m + 1;
x = dgetmem(m1);
while (freadf(x, sizeof(*x), m1, fp) == m1) {
mc2b(x, x, m, a);
fwritef(x, sizeof(*x), m1, stdout);
}
return (0);
}
| mit |
PrJared/sabbath-school-lessons | src/en/2019-03-cq/08/03.md | 5018 | ---
title: Recovered Connection
date: 19/08/2019
---
**Logos**: Heb. 10:24, 25
**Fellowship Is Imperative (1 Thess. 4:17; Heb. 10:24, 25)**
Being part of any community takes a lot of work. The temptation is to stay away from the community to avoid the drama. But, especially as the second coming of Christ approaches, it is imperative that we come together in fellowship. “And let us consider one another to provoke unto love and to good works: Not forsaking the assembling of ourselves together, as the manner of some is; but exhorting one another: and so much the more, as ye see the day approaching” (Heb. 10:24, 25). According to this passage, Paul understands the necessity of banding together here on earth as a prerequisite to being “caught up together . . . to meet the Lord in the air” (1 Thess. 4:17).
This necessity for humanity to connect can be found throughout the Bible, as part of God’s original design. It is sin that has caused separation from God and division from each other. As God brings spiritual healing into our lives, we will draw closer together in relationship with one another. We might rightly ask, if we are not drawing closer to one another, are we truly being transformed by God?
**Fellowship Is Inevitable (John 13:34, 35; 15:9, 12)**
Drawing closer to others as we draw closer to God is not just a function of obedience to God’s injunction to assemble together. Rather, it is a natural outflow of the love that God places in our hearts. As we experience God’s unfathomable love and forgiveness, it inspires love and forgiveness in our hearts toward others. Beholding the love of Jesus, we are transformed into His likeness, and we become loving Christians ourselves (2 Cor. 3:18).
Moreover, we were originally designed to live in community. When God created humanity, He created two beings who could relate to each other but were altogether different from each other. Together, Adam and Eve were the image of God, who Himself exists as the Godhead, three Beings yet one God.
Made from the image of God, three and one, it is unnatural for humans to live divided. At the foundation of this division can be found the deteriorating influence of fear. Examining the lives of Adam and Eve, we can see that through indulged disobedience, they ran from the sound of God’s voice and, sadly, from each other. Instead of taking responsibility for their actions, they looked to cast blame elsewhere, abandoning the foundation of their relationship— cleaving to become one. However, their fears are relieved by the promised defeat of the serpent, the very source that instigated their separation.
Jesus being the fulfillment of this promise, crushing the head of the serpent, comforts His followers, “Let not your heart be troubled. . . . Where I am, there ye may be also” (John 14:1–3). This brings hope to the hearts of those who follow Him and opens the doors for proper connection to exist among one another.
Hope is the single most powerful weapon against fear!
**Fellowship Is Intuitive (Acts 2:1)**
After Christ’s ascension, the disciples gathered in the upper room to wait for the promise of the Holy Spirit. As they focused their minds on Christ’s teachings, the walls of jealousy and evil surmising began to break down, and they joined together in unity. Being in the same room together, they had the opportunity to resolve their differences right there and then. While they may very well have realized their need for reconciliation even if they were praying in separate locations, being in the same location gave them the opportunity to act on their conviction immediately.
Banding together is essential to facilitate proper relationships among one another. We need to come together physically to see the needs of others and meet those needs right away. Even if we are individually convicted on the importance of ministering to the downtrodden, we may not act on that conviction unless we come into physical contact with said people. For anyone who wants to minister as Christ ministered, physically coming into contact with other people is intuitive.
The disciples, in Acts 2, are together in one place, in one accord, ready to receive the power that will enable them to preach the gospel to the world. They understood that connection with each other and God was key in fulfilling the command Jesus gave in Matthew 28:19: go to all the world.
Going back to Hebrews 10:24, 25, Paul exhorts the people of God not to forsake the assembling of themselves as they see the day approaching. What day? The second coming of Christ! The blessed hope is that one day you and I, together, will be able to enjoy the presence of the Lord for all eternity. Nonetheless, before that day comes, we must enjoy the sweet fellowship that comes with banding together. As we grow in wisdom and stature, let us never forget to grow in favor with both God and those whom we come in contact with every day!
---
_Rayshaun Williams, Berrien Springs, Michigan, USA_ | mit |
zhelezko/made-mistakes-jekyll | _posts/paperfaces/2013-09-25-sakkaden-portrait.md | 1867 | ---
layout: article
title: "Look at this view!"
excerpt: "PaperFaces portrait of @sakkaden drawn with Paper by 53 on an iPad."
image:
feature: paperfaces-sakkaden-twitter-lg.jpg
thumb: paperfaces-sakkaden-twitter-150.jpg
category: paperfaces
tags: [portrait, illustration, paper by 53]
---
PaperFaces portrait commissioned by <a href="http://twitter.com/sakkaden">@sakkaden</a>.
{% include paperfaces-boilerplate-2.html %}
<figure>
<a href="{{ site.url }}/images/paperfaces-sakkaden-process-1-lg.jpg"><img src="{{ site.url }}/images/paperfaces-sakkaden-process-1-750.jpg" alt="Work in process screenshot"></a>
<figcaption>Sketching with the pencil.</figcaption>
</figure>
<figure class="half">
<a href="{{ site.url }}/images/paperfaces-sakkaden-process-2-lg.jpg"><img src="{{ site.url }}/images/paperfaces-sakkaden-process-2-600.jpg" alt="Work in process screenshot"></a>
<a href="{{ site.url }}/images/paperfaces-sakkaden-process-3-lg.jpg"><img src="{{ site.url }}/images/paperfaces-sakkaden-process-3-600.jpg" alt="Work in process screenshot"></a>
<a href="{{ site.url }}/images/paperfaces-sakkaden-process-4-lg.jpg"><img src="{{ site.url }}/images/paperfaces-sakkaden-process-4-600.jpg" alt="Work in process screenshot"></a>
<a href="{{ site.url }}/images/paperfaces-sakkaden-process-5-lg.jpg"><img src="{{ site.url }}/images/paperfaces-sakkaden-process-5-600.jpg" alt="Work in process screenshot"></a>
<a href="{{ site.url }}/images/paperfaces-sakkaden-process-6-lg.jpg"><img src="{{ site.url }}/images/paperfaces-sakkaden-process-6-600.jpg" alt="Work in process screenshot"></a>
<a href="{{ site.url }}/images/paperfaces-sakkaden-process-7-lg.jpg"><img src="{{ site.url }}/images/paperfaces-sakkaden-process-7-600.jpg" alt="Work in process screenshot"></a>
<figcaption>Work in progress screenshots (Paper by 53).</figcaption>
</figure> | mit |
mockingbirdnest/Principia | rebuild_release.ps1 | 303 | $ErrorActionPreference = "Stop"
$msbuild = &".\find_msbuild.ps1"
&$msbuild `
"/t:Clean;Build" `
/m `
/property:Configuration=Release `
/property:Platform=x64 `
Principia.sln
if (!$?) {
exit 1
}
| mit |
garymabin/YGOMobile | irrlicht/source/Irrlicht/CImageLoaderDDS.h | 3603 | // Copyright (C) 2002-2012 Thomas Alten
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_IMAGE_LOADER_DDS_H_INCLUDED__
#define __C_IMAGE_LOADER_DDS_H_INCLUDED__
#include "IrrCompileConfig.h"
#if defined(_IRR_COMPILE_WITH_DDS_LOADER_) || defined(_IRR_COMPILE_WITH_DDS_DECODER_LOADER_)
#include "IImageLoader.h"
namespace irr
{
namespace video
{
/* dds pixel format types */
enum eDDSPixelFormat
{
DDS_PF_ARGB8888,
DDS_PF_DXT1,
DDS_PF_DXT2,
DDS_PF_DXT3,
DDS_PF_DXT4,
DDS_PF_DXT5,
DDS_PF_UNKNOWN
};
// byte-align structures
#include "irrpack.h"
/* structures */
struct ddsPixelFormat
{
u32 Size;
u32 Flags;
u32 FourCC;
u32 RGBBitCount;
u32 RBitMask;
u32 GBitMask;
u32 BBitMask;
u32 ABitMask;
} PACK_STRUCT;
struct ddsCaps
{
u32 caps1;
u32 caps2;
u32 caps3;
u32 caps4;
} PACK_STRUCT;
struct ddsHeader
{
c8 Magic[4];
u32 Size;
u32 Flags;
u32 Height;
u32 Width;
u32 PitchOrLinearSize;
u32 Depth;
u32 MipMapCount;
u32 Reserved1[11];
ddsPixelFormat PixelFormat;
ddsCaps Caps;
u32 Reserved2;
} PACK_STRUCT;
#ifdef _IRR_COMPILE_WITH_DDS_DECODER_LOADER_
struct ddsColorBlock
{
u16 colors[ 2 ];
u8 row[ 4 ];
} PACK_STRUCT;
struct ddsAlphaBlockExplicit
{
u16 row[ 4 ];
} PACK_STRUCT;
struct ddsAlphaBlock3BitLinear
{
u8 alpha0;
u8 alpha1;
u8 stuff[ 6 ];
} PACK_STRUCT;
struct ddsColor
{
u8 r, g, b, a;
} PACK_STRUCT;
#endif
// Default alignment
#include "irrunpack.h"
/* endian tomfoolery */
typedef union
{
f32 f;
c8 c[ 4 ];
}
floatSwapUnion;
#ifndef __BIG_ENDIAN__
#ifdef _SGI_SOURCE
#define __BIG_ENDIAN__
#endif
#endif
#ifdef __BIG_ENDIAN__
s32 DDSBigLong( s32 src ) { return src; }
s16 DDSBigShort( s16 src ) { return src; }
f32 DDSBigFloat( f32 src ) { return src; }
s32 DDSLittleLong( s32 src )
{
return ((src & 0xFF000000) >> 24) |
((src & 0x00FF0000) >> 8) |
((src & 0x0000FF00) << 8) |
((src & 0x000000FF) << 24);
}
s16 DDSLittleShort( s16 src )
{
return ((src & 0xFF00) >> 8) |
((src & 0x00FF) << 8);
}
f32 DDSLittleFloat( f32 src )
{
floatSwapUnion in,out;
in.f = src;
out.c[ 0 ] = in.c[ 3 ];
out.c[ 1 ] = in.c[ 2 ];
out.c[ 2 ] = in.c[ 1 ];
out.c[ 3 ] = in.c[ 0 ];
return out.f;
}
#else /*__BIG_ENDIAN__*/
s32 DDSLittleLong( s32 src ) { return src; }
s16 DDSLittleShort( s16 src ) { return src; }
f32 DDSLittleFloat( f32 src ) { return src; }
s32 DDSBigLong( s32 src )
{
return ((src & 0xFF000000) >> 24) |
((src & 0x00FF0000) >> 8) |
((src & 0x0000FF00) << 8) |
((src & 0x000000FF) << 24);
}
s16 DDSBigShort( s16 src )
{
return ((src & 0xFF00) >> 8) |
((src & 0x00FF) << 8);
}
f32 DDSBigFloat( f32 src )
{
floatSwapUnion in,out;
in.f = src;
out.c[ 0 ] = in.c[ 3 ];
out.c[ 1 ] = in.c[ 2 ];
out.c[ 2 ] = in.c[ 1 ];
out.c[ 3 ] = in.c[ 0 ];
return out.f;
}
#endif /*__BIG_ENDIAN__*/
/*!
Surface Loader for DDS images
*/
class CImageLoaderDDS : public IImageLoader
{
public:
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".tga")
virtual bool isALoadableFileExtension(const io::path& filename) const _IRR_OVERRIDE_;
//! returns true if the file maybe is able to be loaded by this class
virtual bool isALoadableFileFormat(io::IReadFile* file) const _IRR_OVERRIDE_;
//! creates a surface from the file
virtual IImage* loadImage(io::IReadFile* file) const _IRR_OVERRIDE_;
};
} // end namespace video
} // end namespace irr
#endif // compiled with DDS loader
#endif
| mit |
colemickens/autorest | AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/autoRestComplexTestService.js | 1993 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
var util = require('util');
var msRest = require('ms-rest');
var ServiceClient = msRest.ServiceClient;
var WebResource = msRest.WebResource;
var models = require('./models');
var operations = require('./operations');
/**
* @class
* Initializes a new instance of the AutoRestComplexTestService class.
* @constructor
*
* @param {string} [baseUri] - The base URI of the service.
*
* @param {object} [options] - The parameter options
*
* @param {Array} [options.filters] - Filters to be added to the request pipeline
*
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@link https://github.com/request/request#requestoptions-callback Options doc}
*
* @param {bool} [options.noRetryPolicy] - If set to true, turn off default retry policy
*/
function AutoRestComplexTestService(baseUri, options) {
if (!options) options = {};
AutoRestComplexTestService['super_'].call(this, null, options);
this.baseUri = baseUri;
if (!this.baseUri) {
this.baseUri = 'http://localhost';
}
this.basicOperations = new operations.BasicOperations(this);
this.primitive = new operations.Primitive(this);
this.arrayModel = new operations.ArrayModel(this);
this.dictionary = new operations.Dictionary(this);
this.inheritance = new operations.Inheritance(this);
this.polymorphism = new operations.Polymorphism(this);
this.polymorphicrecursive = new operations.Polymorphicrecursive(this);
this._models = models;
}
util.inherits(AutoRestComplexTestService, ServiceClient);
module.exports = AutoRestComplexTestService;
| mit |
ryantheleach/SpongeCommon | src/main/java/org/spongepowered/common/command/SpongeCommandManager.java | 13967 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.command;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.spongepowered.api.command.CommandMessageFormatting.error;
import static org.spongepowered.api.util.SpongeApiTranslationHelper.t;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandCallable;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandManager;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.command.CommandPermissionException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.InvocationCommandException;
import org.spongepowered.api.command.dispatcher.Disambiguator;
import org.spongepowered.api.command.dispatcher.SimpleDispatcher;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.event.command.SendCommandEvent;
import org.spongepowered.api.event.command.TabCompleteEvent;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.api.util.TextMessageException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nullable;
import javax.inject.Inject;
/**
* A simple implementation of {@link CommandManager}.
* This service calls the appropriate events for a command.
*/
public class SpongeCommandManager implements CommandManager {
private final Logger log;
private final SimpleDispatcher dispatcher;
private final Multimap<PluginContainer, CommandMapping> owners = HashMultimap.create();
private final Object lock = new Object();
/**
* Construct a simple {@link CommandManager}.
*
* @param logger The logger to log error messages to
*/
@Inject
public SpongeCommandManager(Logger logger) {
this(logger, SimpleDispatcher.FIRST_DISAMBIGUATOR);
}
/**
* Construct a simple {@link CommandManager}.
*
* @param logger The logger to log error messages to
* @param disambiguator The function to resolve a single command when multiple options are available
*/
public SpongeCommandManager(Logger logger, Disambiguator disambiguator) {
this.log = logger;
this.dispatcher = new SimpleDispatcher(disambiguator);
}
@Override
public Optional<CommandMapping> register(Object plugin, CommandCallable callable, String... alias) {
return register(plugin, callable, Arrays.asList(alias));
}
@Override
public Optional<CommandMapping> register(Object plugin, CommandCallable callable, List<String> aliases) {
return register(plugin, callable, aliases, Function.identity());
}
@Override
public Optional<CommandMapping> register(Object plugin, CommandCallable callable, List<String> aliases,
Function<List<String>, List<String>> callback) {
checkNotNull(plugin, "plugin");
Optional<PluginContainer> containerOptional = Sponge.getGame().getPluginManager().fromInstance(plugin);
if (!containerOptional.isPresent()) {
throw new IllegalArgumentException(
"The provided plugin object does not have an associated plugin container "
+ "(in other words, is 'plugin' actually your plugin object?");
}
PluginContainer container = containerOptional.get();
synchronized (this.lock) {
// <namespace>:<alias> for all commands
List<String> aliasesWithPrefix = new ArrayList<>(aliases.size() * 3);
for (String alias : aliases) {
final Collection<CommandMapping> ownedCommands = this.owners.get(container);
for (CommandMapping mapping : this.dispatcher.getAll(alias)) {
if (ownedCommands.contains(mapping)) {
throw new IllegalArgumentException("A plugin may not register multiple commands for the same alias ('" + alias + "')!");
}
}
aliasesWithPrefix.add(alias);
// Alias commands with unqualified ID and qualified ID
String unqualifiedId = container.getUnqualifiedId();
aliasesWithPrefix.add(unqualifiedId + ':' + alias);
if (!container.getId().equals(unqualifiedId)) {
aliasesWithPrefix.add(container.getId() + ':' + alias);
}
}
Optional<CommandMapping> mapping = this.dispatcher.register(callable, aliasesWithPrefix, callback);
if (mapping.isPresent()) {
this.owners.put(container, mapping.get());
}
return mapping;
}
}
@Override
public Optional<CommandMapping> removeMapping(CommandMapping mapping) {
synchronized (this.lock) {
Optional<CommandMapping> removed = this.dispatcher.removeMapping(mapping);
if (removed.isPresent()) {
forgetMapping(removed.get());
}
return removed;
}
}
private void forgetMapping(CommandMapping mapping) {
Iterator<CommandMapping> it = this.owners.values().iterator();
while (it.hasNext()) {
if (it.next().equals(mapping)) {
it.remove();
break;
}
}
}
@Override
public Set<PluginContainer> getPluginContainers() {
synchronized (this.lock) {
return ImmutableSet.copyOf(this.owners.keySet());
}
}
@Override
public Set<CommandMapping> getCommands() {
return this.dispatcher.getCommands();
}
@Override
public Set<CommandMapping> getOwnedBy(Object instance) {
Optional<PluginContainer> container = Sponge.getGame().getPluginManager().fromInstance(instance);
if (!container.isPresent()) {
throw new IllegalArgumentException("The provided plugin object does not have an associated plugin container "
+ "(in other words, is 'plugin' actually your plugin object?)");
}
synchronized (this.lock) {
return ImmutableSet.copyOf(this.owners.get(container.get()));
}
}
@Override
public Set<String> getPrimaryAliases() {
return this.dispatcher.getPrimaryAliases();
}
@Override
public Set<String> getAliases() {
return this.dispatcher.getAliases();
}
@Override
public Optional<CommandMapping> get(String alias) {
return this.dispatcher.get(alias);
}
@Override
public Optional<? extends CommandMapping> get(String alias, @Nullable CommandSource source) {
return this.dispatcher.get(alias, source);
}
@Override
public Set<? extends CommandMapping> getAll(String alias) {
return this.dispatcher.getAll(alias);
}
@Override
public Multimap<String, CommandMapping> getAll() {
return this.dispatcher.getAll();
}
@Override
public boolean containsAlias(String alias) {
return this.dispatcher.containsAlias(alias);
}
@Override
public boolean containsMapping(CommandMapping mapping) {
return this.dispatcher.containsMapping(mapping);
}
@Override
public CommandResult process(CommandSource source, String commandLine) {
final String[] argSplit = commandLine.split(" ", 2);
final SendCommandEvent event = SpongeEventFactory.createSendCommandEvent(Cause.of(NamedCause.source(source)),
argSplit.length > 1 ? argSplit[1] : "", argSplit[0], CommandResult.empty());
Sponge.getGame().getEventManager().post(event);
if (event.isCancelled()) {
return event.getResult();
}
// Only the first part of argSplit is used at the moment, do the other in the future if needed.
argSplit[0] = event.getCommand();
commandLine = event.getCommand();
if (!event.getArguments().isEmpty()) {
commandLine = commandLine + ' ' + event.getArguments();
}
try {
try {
return this.dispatcher.process(source, commandLine);
} catch (InvocationCommandException ex) {
if (ex.getCause() != null) {
throw ex.getCause();
}
} catch (CommandPermissionException ex) {
Text text = ex.getText();
if (text != null) {
source.sendMessage(error(text));
}
} catch (CommandException ex) {
Text text = ex.getText();
if (text != null) {
source.sendMessage(error(text));
}
if (ex.shouldIncludeUsage()) {
final Optional<CommandMapping> mapping = this.dispatcher.get(argSplit[0], source);
if (mapping.isPresent()) {
source.sendMessage(error(t("Usage: /%s %s", argSplit[0], mapping.get().getCallable().getUsage(source))));
}
}
}
} catch (Throwable thr) {
Text.Builder excBuilder;
if (thr instanceof TextMessageException) {
Text text = ((TextMessageException) thr).getText();
excBuilder = text == null ? Text.builder("null") : Text.builder();
} else {
excBuilder = Text.builder(String.valueOf(thr.getMessage()));
}
if (source.hasPermission("sponge.debug.hover-stacktrace")) {
final StringWriter writer = new StringWriter();
thr.printStackTrace(new PrintWriter(writer));
excBuilder.onHover(TextActions.showText(Text.of(writer.toString()
.replace("\t", " ")
.replace("\r\n", "\n")
.replace("\r", "\n")))); // I mean I guess somebody could be running this on like OS 9?
}
source.sendMessage(error(t("Error occurred while executing command: %s", excBuilder.build())));
this.log.error(TextSerializers.PLAIN.serialize(t("Error occurred while executing command '%s' for source %s: %s", commandLine, source.toString(), String
.valueOf(thr.getMessage()))), thr);
}
return CommandResult.empty();
}
@Override
public List<String> getSuggestions(CommandSource src, String arguments) {
try {
final String[] argSplit = arguments.split(" ", 2);
List<String> suggestions = new ArrayList<>(this.dispatcher.getSuggestions(src, arguments));
final TabCompleteEvent.Command event = SpongeEventFactory.createTabCompleteEventCommand(Cause.source(src).build(),
ImmutableList.copyOf(suggestions), suggestions, argSplit.length > 1 ? argSplit[1] : "", argSplit[0], arguments);
Sponge.getGame().getEventManager().post(event);
if (event.isCancelled()) {
return ImmutableList.of();
} else {
return ImmutableList.copyOf(event.getTabCompletions());
}
} catch (CommandException e) {
src.sendMessage(error(t("Error getting suggestions: %s", e.getText())));
return Collections.emptyList();
}
}
@Override
public boolean testPermission(CommandSource source) {
return this.dispatcher.testPermission(source);
}
@Override
public Optional<Text> getShortDescription(CommandSource source) {
return this.dispatcher.getShortDescription(source);
}
@Override
public Optional<Text> getHelp(CommandSource source) {
return this.dispatcher.getHelp(source);
}
@Override
public Text getUsage(CommandSource source) {
return this.dispatcher.getUsage(source);
}
@Override
public int size() {
return this.dispatcher.size();
}
}
| mit |
Colorsublime/Colorsublime-Plugin | colorsublime/http/downloaders/external.py | 843 | from .downloader_base import DownloaderBase
from ... import logger
log = logger.get(__name__)
import traceback
import subprocess
import shutil
from ... import settings
class ExternalDownloader(DownloaderBase):
"""Abstract Base class for downloading through an external utility"""
program = None
args = []
@classmethod
def is_available(cls):
return not settings.is_windows() and shutil.which(cls.program)
def get(self, url):
try:
log.debug('%s downloader getting url %s', self.program, url)
call = [self.program] + self.args + [url]
result = subprocess.check_output(call)
except subprocess.CalledProcessError:
log.error('%s downloader failed.', self.program)
traceback.print_exc()
result = False
return result
| mit |
ekg/vg | src/io/register_loader_saver_odgi.cpp | 1329 | /**
* \file register_loader_saver_odgi.cpp
* Defines IO for a PackedGraph from stream files.
*/
#include <arpa/inet.h>
#include <vg/io/registry.hpp>
#include "register_loader_saver_odgi.hpp"
#include "handle.hpp"
#include "bdsg/odgi.hpp"
namespace vg {
namespace io {
using namespace std;
using namespace vg::io;
void register_loader_saver_odgi() {
// Convert the ODGI SerializableHandleGraph magic number to a string
bdsg::ODGI empty;
// Make sure it is in network byte order
uint32_t new_magic_number = htonl(empty.get_magic_number());
// Load all 4 characters of it into a string
string new_magic((char*)&new_magic_number, 4);
Registry::register_bare_loader_saver_with_magic<bdsg::ODGI, MutablePathDeletableHandleGraph, MutablePathMutableHandleGraph, MutableHandleGraph, PathHandleGraph, HandleGraph>("ODGI", new_magic, [](istream& input) -> void* {
// Allocate an ODGI graph
bdsg::ODGI* odgi = new bdsg::ODGI();
// Load it
odgi->deserialize(input);
// Return it so the caller owns it.
return (void*) odgi;
}, [](const void* odgi_void, ostream& output) {
// Cast to ODGI and serialize to the stream.
assert(odgi_void != nullptr);
((bdsg::ODGI*) odgi_void)->serialize(output);
});
}
}
}
| mit |
erdidoqan/znframework | System/Libraries/Helpers/Filter.php | 3266 | <?php
class __USE_STATIC_ACCESS__Filter
{
/***********************************************************************************/
/* FILTER LIBRARY */
/***********************************************************************************/
/* Yazar: Ozan UYKUN <[email protected]> | <[email protected]>
/* Site: www.zntr.net
/* Lisans: The MIT License
/* Telif Hakkı: Copyright (c) 2012-2015, zntr.net
/*
/* Sınıf Adı: Filter
/* Versiyon: 1.4
/* Tanımlanma: Statik
/* Dahil Edilme: Gerektirmez
/* Erişim: Filter::, $this->Filter, zn::$use->Filter, uselib('Filter')
/* Not: Büyük-küçük harf duyarlılığı yoktur.
/***********************************************************************************/
/******************************************************************************************
* CALL *
*******************************************************************************************
| Genel Kullanım: Geçersiz fonksiyon girildiğinde çağrılması için. |
| |
******************************************************************************************/
public function __call($method = '', $param = '')
{
die(getErrorMessage('Error', 'undefinedFunction', "Filter::$method()"));
}
/******************************************************************************************
* WORD *
*******************************************************************************************
| Genel Kullanım: Metin içinde istenilmeyen kelimelerin izole edilmesi için kullanılır. |
| |
******************************************************************************************/
public function word($string = '', $badWords = '', $changeChar = '[badwords]')
{
if( ! isValue($string) )
{
return Error::set(lang('Error', 'valueParameter', 'string'));
}
if( ! is_array($badWords) )
{
if( empty($badWords) )
{
return $string;
}
return $string = Regex::replace($badWords, $changeChar, $string, 'xi');
}
$ch = '';
$i = 0;
if( ! empty($badWords) ) foreach( $badWords as $value )
{
if( ! is_array($changeChar) )
{
$ch = $changeChar;
}
else
{
if( isset($changeChar[$i]) )
{
$ch = $changeChar[$i];
$i++;
}
}
$string = Regex::replace($value, $ch, $string, 'xi');
}
return $string;
}
/******************************************************************************************
* DATA *
*******************************************************************************************
| Genel Kullanım: Filter::word() yöntemi ile aynı işlevi görür. |
| |
******************************************************************************************/
public function data($string = '', $badWords = '', $changeChar = '[badwords]')
{
return self::word($string, $badWords, $changeChar);
}
} | mit |
hibbitts-design/grav-theme-course-hub-bones | _demo/single-course/accordionpage/04.how-to-understand-and-communicate-peoples-needs-and-behaviors/personas/topic.md | 949 | ---
title: 'Personas'
---
Personas
_Fictional persons, based on research, where each one represents a specific type of user._
* [An introduction to personas and how to create them](http://www.steptwo.com.au/papers/kmc_personas/index.html)
* [Describing Personas](https://medium.com/@indiyoung/describing-personas-af992e3fc527#.uqj6h6mb2)
* [Five Factors for Successful Persona Projects](http://www.uie.com/articles/successful_persona_projects)
* [Persona Grata - Welcoming users into the interaction design process](http://uxmag.com/articles/persona-grata)
* [A Closer Look At Personas: What They Are And How They Work (Part 1)](http://www.smashingmagazine.com/2014/08/06/a-closer-look-at-personas-part-1/)
* [Personas: Setting the Stage for Building Usable Information Sites](http://www.infotoday.com/online/jul03/head.shtml)
* [Three Important Benefits of Personas](http://www.uie.com/articles/benefits_of_personas/)
| mit |
tipunch74/MaterialDesignInXamlToolkit | paket-files/samueldjack/VirtualCollection/VirtualCollection/VirtualCollection/VirtualizingWrapPanel.cs | 15915 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace VirtualCollection.VirtualCollection
{
public class VirtualizingWrapPanel : VirtualizingPanel, IScrollInfo
{
private const double ScrollLineAmount = 16.0;
private Size _extentSize;
private Size _viewportSize;
private Point _offset;
private ItemsControl _itemsControl;
private readonly Dictionary<UIElement, Rect> _childLayouts = new Dictionary<UIElement, Rect>();
public static readonly DependencyProperty ItemWidthProperty =
DependencyProperty.Register(nameof(ItemWidth), typeof(double), typeof(VirtualizingWrapPanel), new PropertyMetadata(1.0, HandleItemDimensionChanged));
public static readonly DependencyProperty ItemHeightProperty =
DependencyProperty.Register(nameof(ItemHeight), typeof(double), typeof(VirtualizingWrapPanel), new PropertyMetadata(1.0, HandleItemDimensionChanged));
private static readonly DependencyProperty VirtualItemIndexProperty =
DependencyProperty.RegisterAttached("VirtualItemIndex", typeof(int), typeof(VirtualizingWrapPanel), new PropertyMetadata(-1));
private IRecyclingItemContainerGenerator _itemsGenerator;
private bool _isInMeasure;
private static int GetVirtualItemIndex(DependencyObject obj)
{
return (int)obj.GetValue(VirtualItemIndexProperty);
}
private static void SetVirtualItemIndex(DependencyObject obj, int value)
{
obj.SetValue(VirtualItemIndexProperty, value);
}
public double ItemHeight
{
get { return (double)GetValue(ItemHeightProperty); }
set { SetValue(ItemHeightProperty, value); }
}
public double ItemWidth
{
get { return (double)GetValue(ItemWidthProperty); }
set { SetValue(ItemWidthProperty, value); }
}
public VirtualizingWrapPanel()
{
if (!DesignerProperties.GetIsInDesignMode(this))
{
Dispatcher.BeginInvoke(new Action(Initialize));
}
}
private void Initialize()
{
_itemsControl = ItemsControl.GetItemsOwner(this);
_itemsGenerator = (IRecyclingItemContainerGenerator)ItemContainerGenerator;
InvalidateMeasure();
}
protected override void OnItemsChanged(object sender, ItemsChangedEventArgs args)
{
base.OnItemsChanged(sender, args);
InvalidateMeasure();
}
protected override Size MeasureOverride(Size availableSize)
{
if (_itemsControl == null)
{
return new Size(double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width,
double.IsInfinity(availableSize.Height) ? 0 : availableSize.Height);
}
_isInMeasure = true;
_childLayouts.Clear();
var extentInfo = GetExtentInfo(availableSize, ItemHeight);
EnsureScrollOffsetIsWithinConstrains(extentInfo);
var layoutInfo = GetLayoutInfo(availableSize, ItemHeight, extentInfo);
RecycleItems(layoutInfo);
// Determine where the first item is in relation to previously realized items
var generatorStartPosition = _itemsGenerator.GeneratorPositionFromIndex(layoutInfo.FirstRealizedItemIndex);
var visualIndex = 0;
var currentX = layoutInfo.FirstRealizedItemLeft;
var currentY = layoutInfo.FirstRealizedLineTop;
using (_itemsGenerator.StartAt(generatorStartPosition, GeneratorDirection.Forward, true))
{
for (var itemIndex = layoutInfo.FirstRealizedItemIndex; itemIndex <= layoutInfo.LastRealizedItemIndex; itemIndex++, visualIndex++)
{
bool newlyRealized;
var child = (UIElement)_itemsGenerator.GenerateNext(out newlyRealized);
SetVirtualItemIndex(child, itemIndex);
if (newlyRealized)
{
InsertInternalChild(visualIndex, child);
}
else
{
// check if item needs to be moved into a new position in the Children collection
if (visualIndex < Children.Count)
{
if (Children[visualIndex] != child)
{
var childCurrentIndex = Children.IndexOf(child);
if (childCurrentIndex >= 0)
{
RemoveInternalChildRange(childCurrentIndex, 1);
}
InsertInternalChild(visualIndex, child);
}
}
else
{
// we know that the child can't already be in the children collection
// because we've been inserting children in correct visualIndex order,
// and this child has a visualIndex greater than the Children.Count
AddInternalChild(child);
}
}
// only prepare the item once it has been added to the visual tree
_itemsGenerator.PrepareItemContainer(child);
child.Measure(new Size(ItemWidth, ItemHeight));
_childLayouts.Add(child, new Rect(currentX, currentY, ItemWidth, ItemHeight));
if (currentX + ItemWidth * 2 >= availableSize.Width)
{
// wrap to a new line
currentY += ItemHeight;
currentX = 0;
}
else
{
currentX += ItemWidth;
}
}
}
RemoveRedundantChildren();
UpdateScrollInfo(availableSize, extentInfo);
var desiredSize = new Size(double.IsInfinity(availableSize.Width) ? 0 : availableSize.Width,
double.IsInfinity(availableSize.Height) ? 0 : availableSize.Height);
_isInMeasure = false;
return desiredSize;
}
private void EnsureScrollOffsetIsWithinConstrains(ExtentInfo extentInfo)
{
_offset.Y = Clamp(_offset.Y, 0, extentInfo.MaxVerticalOffset);
}
private void RecycleItems(ItemLayoutInfo layoutInfo)
{
foreach (var child in Children.OfType<UIElement>())
{
var virtualItemIndex = GetVirtualItemIndex(child);
if (virtualItemIndex < layoutInfo.FirstRealizedItemIndex || virtualItemIndex > layoutInfo.LastRealizedItemIndex)
{
var generatorPosition = _itemsGenerator.GeneratorPositionFromIndex(virtualItemIndex);
if (generatorPosition.Index >= 0)
{
_itemsGenerator.Recycle(generatorPosition, 1);
}
}
SetVirtualItemIndex(child, -1);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
foreach (var child in Children.OfType<UIElement>())
{
child.Arrange(_childLayouts[child]);
}
return finalSize;
}
private void UpdateScrollInfo(Size availableSize, ExtentInfo extentInfo)
{
_viewportSize = availableSize;
_extentSize = new Size(availableSize.Width, extentInfo.ExtentHeight);
InvalidateScrollInfo();
}
private void RemoveRedundantChildren()
{
// iterate backwards through the child collection because we're going to be
// removing items from it
for (var i = Children.Count - 1; i >= 0; i--)
{
var child = Children[i];
// if the virtual item index is -1, this indicates
// it is a recycled item that hasn't been reused this time round
if (GetVirtualItemIndex(child) == -1)
{
RemoveInternalChildRange(i, 1);
}
}
}
private ItemLayoutInfo GetLayoutInfo(Size availableSize, double itemHeight, ExtentInfo extentInfo)
{
if (_itemsControl == null)
{
return new ItemLayoutInfo();
}
// we need to ensure that there is one realized item prior to the first visible item, and one after the last visible item,
// so that keyboard navigation works properly. For example, when focus is on the first visible item, and the user
// navigates up, the ListBox selects the previous item, and the scrolls that into view - and this triggers the loading of the rest of the items
// in that row
var firstVisibleLine = (int)Math.Floor(VerticalOffset / itemHeight);
var firstRealizedIndex = Math.Max(extentInfo.ItemsPerLine * firstVisibleLine - 1, 0);
var firstRealizedItemLeft = firstRealizedIndex % extentInfo.ItemsPerLine * ItemWidth - HorizontalOffset;
var firstRealizedItemTop = (firstRealizedIndex / extentInfo.ItemsPerLine) * itemHeight - VerticalOffset;
var firstCompleteLineTop = (firstVisibleLine == 0 ? firstRealizedItemTop : firstRealizedItemTop + ItemHeight);
var completeRealizedLines = (int)Math.Ceiling((availableSize.Height - firstCompleteLineTop) / itemHeight);
var lastRealizedIndex = Math.Min(firstRealizedIndex + completeRealizedLines * extentInfo.ItemsPerLine + 2, _itemsControl.Items.Count - 1);
return new ItemLayoutInfo
{
FirstRealizedItemIndex = firstRealizedIndex,
FirstRealizedItemLeft = firstRealizedItemLeft,
FirstRealizedLineTop = firstRealizedItemTop,
LastRealizedItemIndex = lastRealizedIndex,
};
}
private ExtentInfo GetExtentInfo(Size viewPortSize, double itemHeight)
{
if (_itemsControl == null)
{
return new ExtentInfo();
}
var itemsPerLine = Math.Max((int)Math.Floor(viewPortSize.Width / ItemWidth), 1);
var totalLines = (int)Math.Ceiling((double)_itemsControl.Items.Count / itemsPerLine);
var extentHeight = Math.Max(totalLines * ItemHeight, viewPortSize.Height);
return new ExtentInfo()
{
ItemsPerLine = itemsPerLine,
TotalLines = totalLines,
ExtentHeight = extentHeight,
MaxVerticalOffset = extentHeight - viewPortSize.Height,
};
}
public void LineUp()
{
SetVerticalOffset(VerticalOffset - ScrollLineAmount);
}
public void LineDown()
{
SetVerticalOffset(VerticalOffset + ScrollLineAmount);
}
public void LineLeft()
{
SetHorizontalOffset(HorizontalOffset + ScrollLineAmount);
}
public void LineRight()
{
SetHorizontalOffset(HorizontalOffset - ScrollLineAmount);
}
public void PageUp()
{
SetVerticalOffset(VerticalOffset - ViewportHeight);
}
public void PageDown()
{
SetVerticalOffset(VerticalOffset + ViewportHeight);
}
public void PageLeft()
{
SetHorizontalOffset(HorizontalOffset + ItemWidth);
}
public void PageRight()
{
SetHorizontalOffset(HorizontalOffset - ItemWidth);
}
public void MouseWheelUp()
{
SetVerticalOffset(VerticalOffset - ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void MouseWheelDown()
{
SetVerticalOffset(VerticalOffset + ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void MouseWheelLeft()
{
SetHorizontalOffset(HorizontalOffset - ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void MouseWheelRight()
{
SetHorizontalOffset(HorizontalOffset + ScrollLineAmount * SystemParameters.WheelScrollLines);
}
public void SetHorizontalOffset(double offset)
{
if (_isInMeasure)
{
return;
}
offset = Clamp(offset, 0, ExtentWidth - ViewportWidth);
_offset = new Point(offset, _offset.Y);
InvalidateScrollInfo();
InvalidateMeasure();
}
public void SetVerticalOffset(double offset)
{
if (_isInMeasure)
{
return;
}
offset = Clamp(offset, 0, ExtentHeight - ViewportHeight);
_offset = new Point(_offset.X, offset);
InvalidateScrollInfo();
InvalidateMeasure();
}
public Rect MakeVisible(Visual visual, Rect rectangle)
{
return new Rect();
}
public Rect MakeVisible(UIElement visual, Rect rectangle)
{
return new Rect();
}
public ItemLayoutInfo GetVisibleItemsRange()
{
return GetLayoutInfo(_viewportSize, ItemHeight, GetExtentInfo(_viewportSize, ItemHeight));
}
public bool CanVerticallyScroll
{
get;
set;
}
public bool CanHorizontallyScroll
{
get;
set;
}
public double ExtentWidth
{
get { return _extentSize.Width; }
}
public double ExtentHeight
{
get { return _extentSize.Height; }
}
public double ViewportWidth
{
get { return _viewportSize.Width; }
}
public double ViewportHeight
{
get { return _viewportSize.Height; }
}
public double HorizontalOffset
{
get { return _offset.X; }
}
public double VerticalOffset
{
get { return _offset.Y; }
}
public ScrollViewer ScrollOwner
{
get;
set;
}
private void InvalidateScrollInfo()
{
if (ScrollOwner != null)
{
ScrollOwner.InvalidateScrollInfo();
}
}
private static void HandleItemDimensionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var wrapPanel = (d as VirtualizingWrapPanel);
wrapPanel.InvalidateMeasure();
}
private double Clamp(double value, double min, double max)
{
return Math.Min(Math.Max(value, min), max);
}
internal class ExtentInfo
{
public int ItemsPerLine;
public int TotalLines;
public double ExtentHeight;
public double MaxVerticalOffset;
}
}
public class ItemLayoutInfo
{
public int FirstRealizedItemIndex;
public double FirstRealizedLineTop;
public double FirstRealizedItemLeft;
public int LastRealizedItemIndex;
}
}
| mit |
MSOpenTech/connectthedots | Devices/DirectlyConnectedDevices/XamarinSimulatedSensors/XamarinSimulatedSensors/XamarinSimulatedSensors.iOS/AppDelegate.cs | 2158 | using Foundation;
using UIKit;
namespace XamarinSimulatedSensors.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to application events from iOS.
[Register ("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
// class-level declarations
public override UIWindow Window {
get;
set;
}
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
// Override point for customization after application launch.
// If not required for your application you can safely delete this method
return true;
}
public override void OnResignActivation (UIApplication application)
{
// Invoked when the application is about to move from active to inactive state.
// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message)
// or when the user quits the application and it begins the transition to the background state.
// Games should use this method to pause the game.
}
public override void DidEnterBackground (UIApplication application)
{
// Use this method to release shared resources, save user data, invalidate timers and store the application state.
// If your application supports background exection this method is called instead of WillTerminate when the user quits.
}
public override void WillEnterForeground (UIApplication application)
{
// Called as part of the transiton from background to active state.
// Here you can undo many of the changes made on entering the background.
}
public override void OnActivated (UIApplication application)
{
// Restart any tasks that were paused (or not yet started) while the application was inactive.
// If the application was previously in the background, optionally refresh the user interface.
}
public override void WillTerminate (UIApplication application)
{
// Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground.
}
}
}
| mit |
appearhere/bloom | packages/core/src/components/Cards/SpaceListingCard/SpaceListingCard.css | 898 | .placeLink {
composes: fontSmallI from '../../../globals/typography.css';
padding: var(--size-small);
background-color: var(--color-black);
background-color: var(--color-transparent-black-i);
color: var(--color-white);
border-radius: 2px;
font-weight: normal;
position: absolute;
top: var(--size-small);
right: var(--size-small);
z-index: 2;
line-height: 1;
transition: background-color 100ms;
max-width: 80%;
text-transform: initial;
}
.placeLink:hover {
color: white;
background-color: var(--color-black);
}
.placeLinkBody {
overflow: hidden;
word-wrap: break-word;
text-overflow: ellipsis;
white-space: nowrap;
width: 100%;
padding-right: 1rem;
display: inline-block;
vertical-align: bottom;
box-sizing: border-box;
letter-spacing: var(--letter-spacing-large-ii);
}
.placeLinkIcon {
position: absolute;
top: 0.4rem;
right: 0.5rem;
} | mit |
lancetw/react-isomorphic-bundle | views/users/index.html | 11 | HTTP BASIC
| mit |
joaopedronardari/COO-EACHUSP | Listas/Lista 1/4/src/math/geometry/Shape.java | 63 | package math.geometry;
interface Shape {
double calcArea();
} | mit |
yangjinecho/licode | erizo/src/third_party/webrtc/src/webrtc/modules/bitrate_controller/send_side_bandwidth_estimation.h | 3428 | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*
* FEC and NACK added bitrate is handled outside class
*/
#ifndef WEBRTC_MODULES_BITRATE_CONTROLLER_SEND_SIDE_BANDWIDTH_ESTIMATION_H_
#define WEBRTC_MODULES_BITRATE_CONTROLLER_SEND_SIDE_BANDWIDTH_ESTIMATION_H_
#include <deque>
#include <utility>
#include <vector>
#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
namespace webrtc {
class SendSideBandwidthEstimation {
public:
SendSideBandwidthEstimation();
virtual ~SendSideBandwidthEstimation();
void CurrentEstimate(int* bitrate, uint8_t* loss, int64_t* rtt) const;
// Call periodically to update estimate.
void UpdateEstimate(int64_t now_ms);
// Call when we receive a RTCP message with TMMBR or REMB.
void UpdateReceiverEstimate(int64_t now_ms, uint32_t bandwidth);
// Call when a new delay-based estimate is available.
void UpdateDelayBasedEstimate(int64_t now_ms, uint32_t bitrate_bps);
// Call when we receive a RTCP message with a ReceiveBlock.
void UpdateReceiverBlock(uint8_t fraction_loss,
int64_t rtt,
int number_of_packets,
int64_t now_ms);
void SetBitrates(int send_bitrate,
int min_bitrate,
int max_bitrate);
void SetSendBitrate(int bitrate);
void SetMinMaxBitrate(int min_bitrate, int max_bitrate);
int GetMinBitrate() const;
private:
enum UmaState { kNoUpdate, kFirstDone, kDone };
bool IsInStartPhase(int64_t now_ms) const;
void UpdateUmaStats(int64_t now_ms, int64_t rtt, int lost_packets);
// Returns the input bitrate capped to the thresholds defined by the max,
// min and incoming bandwidth.
uint32_t CapBitrateToThresholds(int64_t now_ms, uint32_t bitrate);
// Updates history of min bitrates.
// After this method returns min_bitrate_history_.front().second contains the
// min bitrate used during last kBweIncreaseIntervalMs.
void UpdateMinHistory(int64_t now_ms);
std::deque<std::pair<int64_t, uint32_t> > min_bitrate_history_;
// incoming filters
int lost_packets_since_last_loss_update_Q8_;
int expected_packets_since_last_loss_update_;
uint32_t bitrate_;
uint32_t min_bitrate_configured_;
uint32_t max_bitrate_configured_;
int64_t last_low_bitrate_log_ms_;
bool has_decreased_since_last_fraction_loss_;
int64_t last_feedback_ms_;
int64_t last_packet_report_ms_;
int64_t last_timeout_ms_;
uint8_t last_fraction_loss_;
uint8_t last_logged_fraction_loss_;
int64_t last_round_trip_time_ms_;
uint32_t bwe_incoming_;
uint32_t delay_based_bitrate_bps_;
int64_t time_last_decrease_ms_;
int64_t first_report_time_ms_;
int initially_lost_packets_;
int bitrate_at_2_seconds_kbps_;
UmaState uma_update_state_;
std::vector<bool> rampup_uma_stats_updated_;
int64_t last_rtc_event_log_ms_;
bool in_timeout_experiment_;
};
} // namespace webrtc
#endif // WEBRTC_MODULES_BITRATE_CONTROLLER_SEND_SIDE_BANDWIDTH_ESTIMATION_H_
| mit |
yinchunlong/abelkhan-1 | ext/c++/thirdpart/c++/boost/libs/compute/doc/html/boost/compute/transform_if.html | 5371 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template transform_if</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Compute">
<link rel="up" href="../../boost_compute/reference.html#header.boost.compute.algorithm.transform_if_hpp" title="Header <boost/compute/algorithm/transform_if.hpp>">
<link rel="prev" href="transform.html" title="Function transform">
<link rel="next" href="transform_reduce.html" title="Function transform_reduce">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="transform.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_compute/reference.html#header.boost.compute.algorithm.transform_if_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="transform_reduce.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.compute.transform_if"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function template transform_if</span></h2>
<p>boost::compute::transform_if</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../boost_compute/reference.html#header.boost.compute.algorithm.transform_if_hpp" title="Header <boost/compute/algorithm/transform_if.hpp>">boost/compute/algorithm/transform_if.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> InputIterator<span class="special">,</span> <span class="keyword">typename</span> OutputIterator<span class="special">,</span>
<span class="keyword">typename</span> UnaryFunction<span class="special">,</span> <span class="keyword">typename</span> Predicate<span class="special">></span>
<span class="identifier">OutputIterator</span>
<span class="identifier">transform_if</span><span class="special">(</span><span class="identifier">InputIterator</span> first<span class="special">,</span> <span class="identifier">InputIterator</span> last<span class="special">,</span> <span class="identifier">OutputIterator</span> result<span class="special">,</span>
<span class="identifier">UnaryFunction</span> function<span class="special">,</span> <span class="identifier">Predicate</span> predicate<span class="special">,</span>
<span class="identifier">command_queue</span> <span class="special">&</span> queue <span class="special">=</span> <span class="identifier">system</span><span class="special">::</span><span class="identifier">default_queue</span><span class="special">(</span><span class="special">)</span><span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp69423216"></a><h2>Description</h2>
<p>Copies each element in the range [<code class="computeroutput">first</code>, <code class="computeroutput">last</code>) for which <code class="computeroutput">predicate</code> returns <code class="computeroutput">true</code> to the range beginning at <code class="computeroutput">result</code>. </p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2013, 2014 Kyle Lutz<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="transform.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_compute/reference.html#header.boost.compute.algorithm.transform_if_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="transform_reduce.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
josguil/corefx | src/Common/src/Interop/Unix/System.Native/Interop.GetPeerName.cs | 495 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Sys
{
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPeerName")]
internal static extern unsafe Error GetPeerName(int socket, byte* socketAddress, int* socketAddressLen);
}
}
| mit |
MarcosToledo/java-design-patterns | FactoryMethod/src/com/ibanheiz/model/Erdinger.java | 169 | package com.ibanheiz.model;
public class Erdinger extends Cerveja {
@Override
public void info() {
System.out.println("Sou uma breja alemã boa e modinha");
}
}
| mit |
mheggeseth/allReady | AllReadyApp/Web-App/AllReady.UnitTest/Areas/Admin/Features/Itineraries/AddTeamMemberCommandHandlerAsyncTests.cs | 4697 | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Features.Itineraries;
using AllReady.Features.Notifications;
using AllReady.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc.Rendering;
using Moq;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Features.Itineraries
{
public class AddTeamMemberCommandHandlerAsyncTests : InMemoryContextTest
{
protected override void LoadTestData()
{
var htb = new Organization
{
Name = "Humanitarian Toolbox",
LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png",
WebUrl = "http://www.htbox.org",
Campaigns = new List<Campaign>()
};
var firePrev = new Campaign
{
Name = "Neighborhood Fire Prevention Days",
ManagingOrganization = htb
};
htb.Campaigns.Add(firePrev);
var queenAnne = new Event
{
Id = 1,
Name = "Queen Anne Fire Prevention Day",
Campaign = firePrev,
CampaignId = firePrev.Id,
StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
Location = new Location { Id = 1 },
RequiredSkills = new List<EventSkill>(),
EventType = EventType.Itinerary
};
var itinerary = new Itinerary
{
Event = queenAnne,
Name = "1st Itinerary",
Id = 1,
Date = new DateTime(2016, 07, 01)
};
Context.Organizations.Add(htb);
Context.Campaigns.Add(firePrev);
Context.Events.Add(queenAnne);
Context.Itineraries.Add(itinerary);
Context.SaveChanges();
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncReturnsFalseWhenItineraryDoesNotExist()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 0,
TaskSignupId = 1
};
var handler = new AddTeamMemberCommandHandlerAsync(Context, null);
var result = await handler.Handle(query);
Assert.Equal(false, result);
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncReturnsTrueWhenItineraryExists()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var handler = new AddTeamMemberCommandHandlerAsync(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Equal(true, result);
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncSendsPotentialItineraryTeamMemberQueryWithCorrectEventId()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var mockMediator = new Mock<IMediator>();
var handler = new AddTeamMemberCommandHandlerAsync(Context, mockMediator.Object);
await handler.Handle(query);
mockMediator.Verify(x => x.SendAsync(It.Is<PotentialItineraryTeamMembersQuery>(y => y.EventId == 1)), Times.Once);
}
[Fact(Skip = "RTM Broken Tests")]
public async Task AddTeamMemberCommandHandlerAsyncPublishesItineraryVolunteerListUpdatedWhenMatchedOnTaskSignupId()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var potentialTaskSignups = new List<SelectListItem>
{
new SelectListItem
{
Text = "[email protected] : Test TaskName",
Value = query.TaskSignupId.ToString()
}
};
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.SendAsync(It.IsAny<PotentialItineraryTeamMembersQuery>())).ReturnsAsync(potentialTaskSignups);
var handler = new AddTeamMemberCommandHandlerAsync(Context, mockMediator.Object);
await handler.Handle(query);
mockMediator.Verify(x => x.PublishAsync(It.Is<IntineraryVolunteerListUpdated>(y => y.TaskSignupId == query.TaskSignupId && y.ItineraryId == query.ItineraryId && y.UpdateType == UpdateType.VolunteerAssigned)), Times.Once);
}
}
} | mit |
yindaz/pbrs | mitsuba-af602c6fd98a/doc/section_phase.tex | 935 | \newpage
\subsection{Phase functions}
\label{sec:phase}
This section contains a description of all implemented medium scattering models, which
are also known as \emph{phase functions}. These are very similar in principle to surface
scattering models (or \emph{BSDF}s), and essentially describe where light travels after
hitting a particle within the medium.
The most commonly used models for smoke, fog, and other homogeneous media
are isotropic scattering (\pluginref{isotropic}) and the Henyey-Greenstein
phase function (\pluginref{hg}). Mitsuba also supports \emph{anisotropic}
media, where the behavior of the medium changes depending on the direction
of light propagation (e.g. in volumetric representations of fabric). These
are the Kajiya-Kay (\pluginref{kkay}) and Micro-flake (\pluginref{microflake})
models.
Finally, there is also a phase function for simulating scattering in
planetary atmospheres (\pluginref{rayleigh}).
| mit |
mjmostachetti/grasshopper-core-nodejs | release_notes/0.15.6_2014-08-18.md | 27 | ## 0.15.6
* Fixing Casing. | mit |
bitstadium/HockeySDK-Windows | Src/Kit.WP81/Universal/Tools/BooleanToVisibilityConverter.cs | 2258 | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace Microsoft.HockeyApp.Tools
{
/// <summary>
/// xaml converter boolean to visibility
/// </summary>
public class BooleanToVisibilityConverter : IValueConverter
{
/// <summary>
/// Modifies the source data before passing it to the target for display in the UI.
/// </summary>
/// <param name="value">The source data being passed to the target.</param>
/// <param name="targetType">The type of the target property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).</param>
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>
/// The value to be passed to the target dependency property.
/// </returns>
public object Convert(object value, Type targetType, object parameter, string language)
{
return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
/// <summary>
/// Modifies the target data before passing it to the source object. This method is called only in TwoWay bindings.
/// </summary>
/// <param name="value">The target data being passed to the source.</param>
/// <param name="targetType">The type of the target property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).</param>
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>
/// The value to be passed to the source object.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return ((Visibility)value) == Visibility.Visible;
}
}
}
| mit |
SNAS/website | site/content/visualize.md | 563 | ---
title: "Visualize"
date: 2017-01-04T15:04:10.000Z
---
<p>View BGP peers with geo-tags-<p>
<img src="/img/peer_view_for_website.png" alt="" class="left db mb1" style="width: 740px">
<p>View historical data about prefixes-<p>
<img src="/img/tops_view_for_website.png" alt="" class="left db mb1" style="width: 740px">
<p>View network data from public looking glass servers with search filters-<p>
<img src="/img/looking_glass_view_for_website.png" alt="" class="left db mb1" style="width: 740px">
<p>See many more <a href="/docs/examples">examples.</a></p>
| mit |
DigitalCurationCentre/roadmap | app/javascript/src/answers/rdaMetadata.js | 16053 | import { isUndefined, isObject } from '../utils/isType';
$(() => {
// url for the api we will be querying
let url = '';
// key/value lookup for standards
const descriptions = {};
// cleaned up structure of the API results
const minTree = {};
// keeps track of how many waiting api-requests still need to run
let noWaiting = 0;
// prune the min_tree where there are no standards
// opporates on the principal that no two subjects have the same name
function removeUnused(name) {
const num = Object.keys(minTree).find((x) => minTree[x].name === name);
// if not top level standard
if (isUndefined(num)) {
// for each top level standard
Object.keys(minTree).forEach((knum) => {
const child = Object.keys(minTree[knum].children)
.find((x) => minTree[knum].children[x].name === name);
if (isObject(child)) {
delete minTree[knum].children[child];
$(`.rda_metadata .sub-subject select option[value="${name}"]`).remove();
}
});
} else {
delete minTree[num];
// remove min_tree[num] from top-level dropdowns
$(`.rda_metadata .subject select option[value="${name}"]`).remove();
}
}
function getDescription(id) {
$.ajax({
url: url + id.slice(4),
type: 'GET',
crossDomain: true,
dataType: 'json',
}).done((results) => {
descriptions[id] = {};
descriptions[id].title = results.title;
descriptions[id].description = results.description;
noWaiting -= 1;
});
}
// init descriptions lookup table based on passed ids
function initDescriptions(ids) {
ids.forEach((id) => {
if (!(id in descriptions)) {
noWaiting += 1;
getDescription(id);
}
});
}
// takes in a subset of the min_tree which has name and standards properties
// initializes the standards property to the result of an AJAX POST
function getStandards(name, num, child) {
// slice -4 from url to remove '/api/'
noWaiting += 1;
$.ajax({
url: `${url.slice(0, -4)}query/schemes`,
type: 'POST',
crossDomain: true,
data: `keyword=${name}`,
dataType: 'json',
}).done((result) => {
if (isUndefined(child)) {
minTree[num].standards = result.ids;
} else {
minTree[num].children[child].standards = result.ids;
}
if (result.ids.length < 1) {
removeUnused(name);
}
noWaiting -= 1;
initDescriptions(result.ids);
});
}
// clean up the data initially returned from the API
function cleanTree(apiTree) {
// iterate over api_tree
Object.keys(apiTree).forEach((num) => {
minTree[num] = {};
minTree[num].name = apiTree[num].name;
minTree[num].children = [];
if (apiTree[num].children !== undefined) {
Object.keys(apiTree[num].children).forEach((child) => {
minTree[num].children[child] = {};
minTree[num].children[child].name = apiTree[num].children[child].name;
minTree[num].children[child].standards = [];
getStandards(minTree[num].children[child].name, num, child);
});
}
// init a standards on top level
minTree[num].standards = [];
getStandards(minTree[num].name, num, undefined);
});
}
// create object for typeahead
function initTypeahead() {
const data = [];
const simpdat = [];
Object.keys(descriptions).forEach((id) => {
data.push({ value: descriptions[id].title, id });
simpdat.push(descriptions[id].title);
});
const typ = $('.standards-typeahead');
typ.typeahead({ source: simpdat });
}
function initStandards() {
// for each metadata question, init selected standards according to html
$('.rda_metadata').each(function () { // eslint-disable-line func-names
// list of selected standards
const selectedStandards = $(this).find('.selected_standards .list');
// form listing of standards
const formStandards = $(this).next('form').find('#standards');
// need to pull in the value from frm_stds
const standardsArray = JSON.parse(formStandards.val());
// init the data value
formStandards.data('standard', standardsArray);
Object.keys(standardsArray).forEach((key) => {
// add the standard to list
if (key === standardsArray[key]) {
selectedStandards.append(`<li class="${key}">${key}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li`);
} else {
selectedStandards.append(`<li class="${key}">${descriptions[key].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
}
});
});
}
function waitAndUpdate() {
if (noWaiting > 0) {
// if we are waiting on api responces, call this function in 1 seccond
setTimeout(waitAndUpdate, 1000);
} else {
// update all the dropdowns/ standards explore box (calling on subject
// will suffice since it will necisarily update sub-subject)
$('.rda_metadata .subject select').change();
initStandards();
initTypeahead();
}
}
// given a subject name, returns the portion of the min_tree applicable
function getSubject(subjectText) {
const num = Object.keys(minTree).find((x) => minTree[x].name === subjectText);
return minTree[num];
}
// given a subsubject name and an array of children, data, return the
// applicable child
function getSubSubject(subsubjectText, data) {
const child = Object.keys(data).find((x) => data[x].name === subsubjectText);
return data[child];
}
function updateSaveStatus(group) {
// update save/autosave status
group.next('form').find('fieldset input').change();
}
// change sub-subjects and standards based on selected subject
$('.rda_metadata').on('change', '.subject select', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const subSubject = group.find('.sub-subject select');
const subjectText = target.find(':selected').text();
// find subject in min_tree
const subject = getSubject(subjectText);
// check to see if this object has no children(and thus it's own standards)
if (subject.children.length === 0) {
// hide sub-subject since there's no data for it
subSubject.closest('div').hide();
// update the standards display selector
$('.rda_metadata .sub-subject select').change();
} else {
// show the sub-subject incase it was previously hidden
subSubject.closest('div').show();
// update the sub-subject display selector
subSubject.find('option').remove();
subject.children.forEach((child) => {
$('<option />', { value: child.name, text: child.name }).appendTo(subSubject);
});
// once we have updated the sub-standards, ensure the standards displayed
// get updated as well
$('.rda_metadata .sub-subject select').change();
}
});
// change standards based on selected sub-subject
$('.rda_metadata').on('change', '.sub-subject select', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const subject = group.find('.subject select');
const subSubject = group.find('.sub-subject select');
const subjectText = subject.find(':selected').text();
const subjectData = getSubject(subjectText);
const standards = group.find('.browse-standards-border');
let standardsData;
if (subjectData.children.length === 0) {
// update based on subject's standards
standardsData = subjectData.standards;
} else {
// update based on sub-subject's standards
const subsubjectText = subSubject.find(':selected').text();
standardsData = getSubSubject(subsubjectText, subjectData.children).standards;
}
// clear list of standards
standards.empty();
// update list of standards
Object.keys(standardsData).forEach((num) => {
const standard = descriptions[standardsData[num]];
standards.append(`<div style="background-color:#EAEAEA;border-radius:3px"><strong>${standard.title}</strong><div style="float:right"><button class="btn btn-primary select_standard" data-standard="${standardsData[num]}">Add Standard</button></br></div><p>${standard.description}</p></div>`);
});
});
// when 'Add Standard' button next to the search is clicked, we need to add
// this to the user's selected list of standards.
// update the data and val of hidden standards field in form
$('.rda_metadata').on('click', '.select_standard_typeahead', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selected = group.find('ul.typeahead li.active');
const selectedStandards = group.find('.selected_standards .list');
// the title of the standard
const standardTitle = selected.data('value');
// need to find the standard
let standard;
Object.keys(descriptions).forEach((standardId) => {
if (descriptions[standardId].title === standardTitle) {
standard = standardId;
}
});
selectedStandards.append(`<li class="${standard}">${descriptions[standard].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (typeof frmStdsDat === 'undefined') {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
// NOTE: is there any point in storing the title or description here?
// storing the title could make export easier as we wolnt need to query api
// but queries to the api would be 1 per-standard if we dont store these
frmStdsDat[standard] = descriptions[standard].title;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// when a 'Add standard' button is clicked, we need to add this to the user's
// selected list of standards
// update the data and val of hidden standards field in form
$('.rda_metadata').on('click', '.select_standard', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selectedStandards = group.find('.selected_standards .list');
// the identifier for the standard which was selected
const standard = target.data('standard');
// append the standard to the displayed list of selected standards
selectedStandards.append(`<li class="${standard}">${descriptions[standard].title}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (isUndefined(frmStdsDat)) {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
frmStdsDat[standard] = descriptions[standard].title;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// when a 'Remove Standard' button is clicked, we need to remove this from the
// user's selected list of standards. Additionally, we need to remove the
// standard from the data/val fields of standards in hidden form
$('.rda_metadata').on('click', '.remove-standard', (e) => {
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const listedStandard = target.closest('li');
const standardId = listedStandard.attr('class');
// remove the standard from the list
listedStandard.remove();
// update the data for the form
const formStandards = group.next('form').find('#standards');
const frmStdsDat = formStandards.data('standard');
delete frmStdsDat[standardId];
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
// show the add custom standard div when standard not listed clicked
$('.rda_metadata').on('click', '.custom-standard', (e) => {
e.preventDefault();
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const addStandardDiv = $(group.find('.add-custom-standard'));
addStandardDiv.show();
});
// when this button is clicked, we add the typed standard to the list of
// selected standards
$('.rda_metadata').on('click', '.submit_custom_standard', (e) => {
e.preventDefault();
const target = $(e.currentTarget);
const group = target.closest('.rda_metadata');
const selectedStandards = group.find('.selected_standards .list');
const standardName = group.find('.custom-standard-name').val();
selectedStandards.append(`<li class="${standardName}">${standardName}<button class="remove-standard"><i class="fas fa-times-circle"></i></button></li>`);
const formStandards = group.next('form').find('#standards');
// get the data for selected standards from the data attribute 'standard'
// of the hidden field #standards within the answer form
let frmStdsDat = formStandards.data('standard');
// need to init data object for first time
if (typeof frmStdsDat === 'undefined') {
frmStdsDat = {};
}
// init the key to standard id and value to standard.
frmStdsDat[standardName] = standardName;
// update data value
formStandards.data('standard', frmStdsDat);
// update input value
formStandards.val(JSON.stringify(frmStdsDat));
updateSaveStatus(group);
});
function initMetadataQuestions() {
// find all elements with rda_metadata div
$('.rda_metadata').each((idx, el) => {
// $(this) is the element
const sub = $(el).find('.subject select');
// var sub_subject = $(this).find(".sub-subject select");
Object.keys(minTree).forEach((num) => {
$('<option />', { value: minTree[num].name, text: minTree[num].name }).appendTo(sub);
});
});
waitAndUpdate();// $(".rda_metadata .subject select").change();
}
// callback from url+subject-index
// define api_tree and call to initMetadataQuestions
function subjectCallback(data) {
// remove unused standards/substandards
cleanTree(data);
// initialize the dropdowns/selected standards for the page
initMetadataQuestions();
}
// callback from get request to rda_api_address
// define url and make a call to url+subject-index
function urlCallback(data) {
// init url
({ url } = data);
// get api_tree structure from api
$.ajax({
url: `${url}subject-index`,
type: 'GET',
crossDomain: true,
dataType: 'json',
}).done((result) => {
subjectCallback(result);
});
}
// get the url we will be using for the api
// only do this if page has an rda_metadata div
if ($('.rda_metadata').length) {
$.getJSON('/question_formats/rda_api_address', urlCallback);
}
// when the autosave or save action occurs, this clears out both the list of
// selected standards, and the selectors for new standards, as it re-renders
// the partial. This "autosave" event is triggered by that JS in order to
// allow us to know when the save has happened and re-init the question
$('.rda_metadata').on('autosave', (e) => {
e.preventDefault();
// re-initialize the metadata question
initMetadataQuestions();
});
});
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.