text
stringlengths
5
1.04M
/*========================================================================= * * Copyright NumFOCUS * * 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 * * https://www.apache.org/licenses/LICENSE-2.0.txt * * 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. * *=========================================================================*/ // Software Guide : BeginLatex // // It is often valuable to be able to query the entries from the header of a // DICOM file. This can be used for consistency checking, or simply for // verifying that we have the correct dataset in our hands. This example // illustrates how to read a DICOM file and then print out most of the DICOM // header information. The binary fields of the DICOM header are skipped. // // \index{DICOM!Header} // \index{DICOM!Tags} // \index{DICOM!Printing Tags} // \index{DICOM!Dictionary} // \index{DICOM!GDCM} // \index{GDCM!Dictionary} // // Software Guide : EndLatex // Software Guide : BeginLatex // // The headers of the main classes involved in this example are specified // below. They include the image file reader, the GDCMImageIO object, the // MetaDataDictionary and its entry element, the MetaDataObject. // // \index{MetaDataDictionary!header} // \index{MetaDataObject!header} // \index{GDCMImageIO!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageFileReader.h" #include "itkGDCMImageIO.h" #include "itkMetaDataObject.h" // Software Guide : EndCodeSnippet #include "gdcmGlobal.h" // Software Guide : BeginLatex // Software Guide : EndLatex int main(int argc, char * argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " DicomFile [user defined dict]" << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // We instantiate the type to be used for storing the image once it is read // into memory. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet using PixelType = short; constexpr unsigned int Dimension = 2; using ImageType = itk::Image<PixelType, Dimension>; // Software Guide : EndCodeSnippet if (argc == 3) { // Specify a path where XML dicts can be found (Part 3/4 & 6) gdcm::Global::GetInstance().Prepend( itksys::SystemTools::GetFilenamePath(argv[2]).c_str()); // Load them ! gdcm::Global::GetInstance().LoadResourcesFiles(); } // Software Guide : BeginLatex // // Using the image type as a template parameter we instantiate the type of // the image file reader and construct one instance of it. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet using ReaderType = itk::ImageFileReader<ImageType>; auto reader = ReaderType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The GDCM image IO type is declared and used for constructing one image IO // object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet using ImageIOType = itk::GDCMImageIO; auto dicomIO = ImageIOType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We pass to the reader the filename of the image to be read and connect // the ImageIO object to it too. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet reader->SetFileName(argv[1]); reader->SetImageIO(dicomIO); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The reading process is triggered with a call to the \code{Update()} // method. This call should be placed inside a \code{try/catch} block // because its execution may result in exceptions being thrown. // // Software Guide : EndLatex try { // Software Guide : BeginCodeSnippet reader->Update(); // Software Guide : EndCodeSnippet } catch (const itk::ExceptionObject & ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // Now that the image has been read, we obtain the MetaDataDictionary from // the ImageIO object using the \code{GetMetaDataDictionary()} method. // // \index{MetaDataDictionary} // \index{GetMetaDataDictionary()!ImageIOBase} // \index{ImageIOBase!GetMetaDataDictionary()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet using DictionaryType = itk::MetaDataDictionary; const DictionaryType & dictionary = dicomIO->GetMetaDataDictionary(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Since we are interested only in the DICOM tags that can be expressed in // strings, we declare a MetaDataObject suitable for managing strings. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet using MetaDataStringType = itk::MetaDataObject<std::string>; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We instantiate the iterators that will make possible to walk through all // the entries of the MetaDataDictionary. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet auto itr = dictionary.Begin(); auto end = dictionary.End(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // For each one of the entries in the dictionary, we check first if its // element can be converted to a string, a \code{dynamic\_cast} is used for // this purpose. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet while (itr != end) { itk::MetaDataObjectBase::Pointer entry = itr->second; MetaDataStringType::Pointer entryvalue = dynamic_cast<MetaDataStringType *>(entry.GetPointer()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // For those entries that can be converted, we take their DICOM tag and // pass it to the \code{GetLabelFromTag()} method of the GDCMImageIO // class. This method checks the DICOM dictionary and returns the string // label associated with the tag that we are providing in the // \code{tagkey} variable. If the label is found, it is returned in // \code{labelId} variable. The method itself returns false if the tagkey // is not found in the dictionary. For example "$0010|0010$" in // \code{tagkey} becomes "Patient's Name" in \code{labelId}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet if (entryvalue) { std::string tagkey = itr->first; std::string labelId; bool found = itk::GDCMImageIO::GetLabelFromTag(tagkey, labelId); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The actual value of the dictionary entry is obtained as a string with // the \code{GetMetaDataObjectValue()} method. // // \index{MetaDataObject!GetMetaDataObjectValue()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::string tagvalue = entryvalue->GetMetaDataObjectValue(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // At this point we can print out an entry by concatenating the DICOM // Name or label, the numeric tag and its actual value. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet if (found) { std::cout << "(" << tagkey << ") " << labelId; std::cout << " = " << tagvalue.c_str() << std::endl; } // Software Guide : EndCodeSnippet else { std::cout << "(" << tagkey << ") " << "Unknown"; std::cout << " = " << tagvalue.c_str() << std::endl; } } // Software Guide : BeginLatex // // Finally we just close the loop that will walk through all the // Dictionary entries. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ++itr; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // It is also possible to read a specific tag. In that case the string of // the entry can be used for querying the MetaDataDictionary. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::string entryId = "0010|0010"; auto tagItr = dictionary.Find(entryId); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // If the entry is actually found in the Dictionary, then we can attempt to // convert it to a string entry by using a \code{dynamic\_cast}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet if (tagItr != end) { MetaDataStringType::ConstPointer entryvalue = dynamic_cast<const MetaDataStringType *>(tagItr->second.GetPointer()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // If the dynamic cast succeeds, then we can print out the values of the // label, the tag and the actual value. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet if (entryvalue) { std::string tagvalue = entryvalue->GetMetaDataObjectValue(); std::cout << "Patient's Name (" << entryId << ") "; std::cout << " is: " << tagvalue.c_str() << std::endl; } // Software Guide : EndCodeSnippet } // Software Guide : BeginLatex // // Another way to read a specific tag is to use the encapsulation above // MetaDataDictionary. Note that this is stricly equivalent to the above // code. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::string tagkey = "0008|1050"; std::string labelId; if (itk::GDCMImageIO::GetLabelFromTag(tagkey, labelId)) { std::string value; std::cout << labelId << " (" << tagkey << "): "; if (dicomIO->GetValueFromTag(tagkey, value)) { std::cout << value; } else { std::cout << "(No Value Found in File)"; } std::cout << std::endl; } else { std::cerr << "Trying to access inexistant DICOM tag." << std::endl; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // For a full description of the DICOM dictionary please look at the file. // // \code{Insight/Utilities/gdcm/Dicts/dicomV3.dic} // // Software Guide : EndLatex // Software Guide : BeginLatex // // The following piece of code will print out the proper pixel type / // component for instantiating an \doxygen{ImageFileReader} that can // properly import the printed DICOM file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet itk::IOPixelEnum pixelType = reader->GetImageIO()->GetPixelType(); itk::IOComponentEnum componentType = reader->GetImageIO()->GetComponentType(); std::cout << "PixelType: " << reader->GetImageIO()->GetPixelTypeAsString(pixelType) << std::endl; std::cout << "Component Type: " << reader->GetImageIO()->GetComponentTypeAsString(componentType) << std::endl; // Software Guide : EndCodeSnippet return EXIT_SUCCESS; }
// Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "chainparams.h" #include "coincontrol.h" #include "denomination_functions.h" #include "main.h" #include "txdb.h" #include "wallet/wallet.h" #include "wallet/walletdb.h" #include "test/test_unitedworldmoney.h" #include <boost/test/unit_test.hpp> #include <iostream> using namespace libzerocoin; BOOST_FIXTURE_TEST_SUITE(zerocoin_denom_tests, BasicTestingSetup) //translation from unitedworldmoney quantity to zerocoin denomination BOOST_AUTO_TEST_CASE(amount_to_denomination_test) { cout << "Running amount_to_denomination_test...\n"; //valid amount (min edge) CAmount amount = 1 * COIN; BOOST_CHECK_MESSAGE(AmountToZerocoinDenomination(amount) == ZQ_ONE, "For COIN denomination should be ZQ_ONE"); //valid amount (max edge) CAmount amount1 = 5000 * COIN; BOOST_CHECK_MESSAGE(AmountToZerocoinDenomination(amount1) == ZQ_FIVE_THOUSAND, "For 5000*COIN denomination should be ZQ_ONE"); //invalid amount (too much) CAmount amount2 = 7000 * COIN; BOOST_CHECK_MESSAGE(AmountToZerocoinDenomination(amount2) == ZQ_ERROR, "For 7000*COIN denomination should be Invalid -> ZQ_ERROR"); //invalid amount (not enough) CAmount amount3 = 1; BOOST_CHECK_MESSAGE(AmountToZerocoinDenomination(amount3) == ZQ_ERROR, "For 1 denomination should be Invalid -> ZQ_ERROR"); } BOOST_AUTO_TEST_CASE(denomination_to_value_test) { cout << "Running ZerocoinDenominationToValue_test...\n"; int64_t Value = 1 * COIN; CoinDenomination denomination = ZQ_ONE; BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 1"); Value = 10 * COIN; denomination = ZQ_TEN; BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 10"); Value = 50 * COIN; denomination = ZQ_FIFTY; BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 50"); Value = 500 * COIN; denomination = ZQ_FIVE_HUNDRED; BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 500"); Value = 100 * COIN; denomination = ZQ_ONE_HUNDRED; BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 100"); Value = 0 * COIN; denomination = ZQ_ERROR; BOOST_CHECK_MESSAGE(ZerocoinDenominationToAmount(denomination) == Value, "Wrong Value - should be 0"); } BOOST_AUTO_TEST_CASE(zerocoin_spend_test241) { const int nMaxNumberOfSpends = 4; const bool fMinimizeChange = false; const int DenomAmounts[] = {1, 2, 3, 4, 0, 0, 0, 0}; CAmount nSelectedValue; std::list<CMintMeta> listMints; std::map<CoinDenomination, CAmount> mapDenom; int j = 0; CAmount nTotalAmount = 0; int CoinsHeld = 0; // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available for (const auto& denom : zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { CAmount currentAmount = ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; CBigNum serial = CBigNum::randKBitBignum(256); bool isUsed = false; CMintMeta meta; meta.denom = denom; meta.hashPubcoin = GetPubCoinHash(value); meta.hashSerial = GetSerialHash(serial); meta.isUsed = isUsed; meta.nVersion = 1; listMints.push_back(meta); } mapDenom.insert(std::pair<CoinDenomination, CAmount>(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; std::cout << "Curremt Amount held = " << CoinsHeld << ": "; // Show what we have j = 0; for (const auto& denom : zerocoinDenomList) std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; // For DenomAmounts[] = {1,2,3,4,0,0,0,0}; we can spend up to 200 without requiring more than 4 Spends // Amounts above this can not be met CAmount MaxLimit = 200; CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); CAmount nValueTarget = OneCoinAmount; int nCoinsReturned; int nNeededSpends = 0; // Number of spends which would be needed if selection failed bool fDebug = 0; // Go through all possible spend between 1 and 241 and see if it's possible or not for (int i = 0; i < CoinsHeld; i++) { std::vector<CMintMeta> vSpends = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, fMinimizeChange, nCoinsReturned, listMints, mapDenom, nNeededSpends); if (fDebug) { if (vSpends.size() > 0) { std::cout << "SUCCESS : Coins = " << nValueTarget / COIN << " # spends used = " << vSpends.size() << " # of coins returned = " << nCoinsReturned << " Spend Amount = " << nSelectedValue / COIN << " Held = " << CoinsHeld << "\n"; } else { std::cout << "FAILED : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; } } if (i < MaxLimit) { BOOST_CHECK_MESSAGE(vSpends.size() < 5, "Too many spends"); BOOST_CHECK_MESSAGE(vSpends.size() > 0, "No spends"); } else { bool spends_not_ok = ((vSpends.size() >= 4) || (vSpends.size() == 0)); BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); } nValueTarget += OneCoinAmount; } //std::cout << "241 Test done!\n"; } BOOST_AUTO_TEST_CASE(zerocoin_spend_test115) { const int nMaxNumberOfSpends = 4; const bool fMinimizeChange = false; const int DenomAmounts[] = {0, 1, 1, 2, 0, 0, 0, 0}; CAmount nSelectedValue; std::list<CMintMeta> listMints; std::map<CoinDenomination, CAmount> mapDenom; int j = 0; CAmount nTotalAmount = 0; int CoinsHeld = 0; // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available for (const auto& denom : zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { CAmount currentAmount = ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; CBigNum serial = CBigNum::randKBitBignum(256); bool isUsed = false; CMintMeta meta; meta.denom = denom; meta.hashPubcoin = GetPubCoinHash(value); meta.hashSerial = GetSerialHash(serial); meta.isUsed = isUsed; meta.nVersion = 1; listMints.push_back(meta); } mapDenom.insert(std::pair<CoinDenomination, CAmount>(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; std::cout << "Curremt Amount held = " << CoinsHeld << ": "; // Show what we have j = 0; for (const auto& denom : zerocoinDenomList) std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); CAmount nValueTarget = OneCoinAmount; //bool fDebug = 0; int nCoinsReturned; int nNeededSpends = 0; // Number of spends which would be needed if selection failed std::vector<CMintMeta> vSpends = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, fMinimizeChange, nCoinsReturned, listMints, mapDenom, nNeededSpends); // if (fDebug) { // if (vSpends.size() > 0) { // std::cout << "SUCCESS : Coins = " << nValueTarget / COIN << " # spends used = " << vSpends.size() // << " # of coins returned = " << nCoinsReturned // << " Spend Amount = " << nSelectedValue / COIN << " Held = " << CoinsHeld << "\n"; // } else { // std::cout << "FAILED : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } BOOST_CHECK_MESSAGE(vSpends.size() < 5, "Too many spends"); BOOST_CHECK_MESSAGE(vSpends.size() > 0, "No spends"); nValueTarget += OneCoinAmount; } BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_245) { const int nMaxNumberOfSpends = 5; // For 36: // const int nSpendValue = 36; // Here have a 50 so use for 36 since can't meet exact amount // const int DenomAmounts[] = {0,1,4,1,0,0,0,0}; // Here have 45 so use 4*10 for 36 since can't meet exact amount // const int DenomAmounts[] = {0, 1, 4, 0, 0, 0, 0, 0}; // For 51 //const int nSpendValue = 51; // CoinsHeld = 245 const int DenomAmounts[] = {0, 1, 4, 2, 1, 0, 0, 0}; // We can spend up to this amount for above set for less 6 spends // Otherwise, 6 spends are required const int nMaxSpendAmount = 220; CAmount nSelectedValue; std::list<CMintMeta> listMints; std::map<CoinDenomination, CAmount> mapOfDenomsHeld; int j = 0; CAmount nTotalAmount = 0; int CoinsHeld = 0; // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available for (const auto& denom : zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { CAmount currentAmount = ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; CBigNum serial = CBigNum::randKBitBignum(256); bool isUsed = false; CMintMeta meta; meta.denom = denom; meta.hashPubcoin = GetPubCoinHash(value); meta.hashSerial = GetSerialHash(serial); meta.isUsed = isUsed; meta.nVersion = 1; listMints.push_back(meta); } mapOfDenomsHeld.insert(std::pair<CoinDenomination, CAmount>(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; std::cout << "Curremt Amount held = " << CoinsHeld << ": "; // Show what we have j = 0; for (const auto& denom : zerocoinDenomList) std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); CAmount nValueTarget = OneCoinAmount; // bool fDebug = 0; int nCoinsReturned; int nNeededSpends = 0; // Number of spends which would be needed if selection failed // Go through all possible spend between 1 and 241 and see if it's possible or not for (int i = 0; i < CoinsHeld; i++) { std::vector<CMintMeta> vSpends = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, false, nCoinsReturned, listMints, mapOfDenomsHeld, nNeededSpends); // if (fDebug) { // if (vSpends.size() > 0) { // std::cout << "SUCCESS : Coins = " << nValueTarget / COIN << " # spends = " << vSpends.size() // << " # coins returned = " << nCoinsReturned // << " Amount = " << nSelectedValue / COIN << " Held = " << CoinsHeld << " "; // } else { // std::cout << "UNABLE TO SPEND : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } bool spends_not_ok = ((vSpends.size() > nMaxNumberOfSpends) || (vSpends.size() == 0)); if (i < nMaxSpendAmount) BOOST_CHECK_MESSAGE(!spends_not_ok, "Too many spends"); else BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); std::vector<CMintMeta> vSpendsAlt = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, true, nCoinsReturned, listMints, mapOfDenomsHeld, nNeededSpends); // if (fDebug) { // if (vSpendsAlt.size() > 0) { // std::cout << "# spends = " << vSpendsAlt.size() // << " # coins returned = " << nCoinsReturned // << " Amount = " << nSelectedValue / COIN << "\n"; // } else { // std::cout << "UNABLE TO SPEND : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } spends_not_ok = ((vSpendsAlt.size() > nMaxNumberOfSpends) || (vSpendsAlt.size() == 0)); if (i < nMaxSpendAmount) BOOST_CHECK_MESSAGE(!spends_not_ok, "Too many spends"); else BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); nValueTarget += OneCoinAmount; } } BOOST_AUTO_TEST_CASE(zerocoin_spend_test_from_145) { const int nMaxNumberOfSpends = 5; // CoinsHeld = 145 const int DenomAmounts[] = {0, 1, 4, 2, 0, 0, 0, 0}; CAmount nSelectedValue; std::list<CMintMeta> listMints; std::map<CoinDenomination, CAmount> mapOfDenomsHeld; int j = 0; CAmount nTotalAmount = 0; int CoinsHeld = 0; // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available for (const auto& denom : zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { CAmount currentAmount = ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; CBigNum serial = CBigNum::randKBitBignum(256); bool isUsed = false; CMintMeta meta; meta.denom = denom; meta.hashPubcoin = GetPubCoinHash(value); meta.hashSerial = GetSerialHash(serial); meta.isUsed = isUsed; meta.nVersion = 1; listMints.push_back(meta); } mapOfDenomsHeld.insert(std::pair<CoinDenomination, CAmount>(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; std::cout << "Curremt Amount held = " << CoinsHeld << ": "; // We can spend up to this amount for above set for less 6 spends // Otherwise, 6 spends are required const int nMaxSpendAmount = 130; // Show what we have j = 0; for (const auto& denom : zerocoinDenomList) std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); CAmount nValueTarget = OneCoinAmount; //bool fDebug = 0; int nCoinsReturned; int nNeededSpends = 0; // Number of spends which would be needed if selection failed // Go through all possible spend between 1 and 241 and see if it's possible or not for (int i = 0; i < CoinsHeld; i++) { std::vector<CMintMeta> vSpends = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, false, nCoinsReturned, listMints, mapOfDenomsHeld, nNeededSpends); // if (fDebug) { // if (vSpends.size() > 0) { // std::cout << "SUCCESS : Coins = " << nValueTarget / COIN << " # spends = " << vSpends.size() // << " # coins returned = " << nCoinsReturned // << " Amount = " << nSelectedValue / COIN << " Held = " << CoinsHeld << " "; // } else { // std::cout << "UNABLE TO SPEND : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } bool spends_not_ok = ((vSpends.size() > nMaxNumberOfSpends) || (vSpends.size() == 0)); if (i < nMaxSpendAmount) BOOST_CHECK_MESSAGE(!spends_not_ok, "Too many spends"); else BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); std::vector<CMintMeta> vSpendsAlt = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, true, nCoinsReturned, listMints, mapOfDenomsHeld, nNeededSpends); // if (fDebug) { // if (vSpendsAlt.size() > 0) { // std::cout << "# spends = " << vSpendsAlt.size() // << " # coins returned = " << nCoinsReturned // << " Amount = " << nSelectedValue / COIN << "\n"; // } else { // std::cout << "UNABLE TO SPEND : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } spends_not_ok = ((vSpendsAlt.size() > nMaxNumberOfSpends) || (vSpendsAlt.size() == 0)); if (i < nMaxSpendAmount) BOOST_CHECK_MESSAGE(!spends_not_ok, "Too many spends"); else BOOST_CHECK_MESSAGE(spends_not_ok, "Expected to fail but didn't"); nValueTarget += OneCoinAmount; } } BOOST_AUTO_TEST_CASE(zerocoin_spend_test99) { const int nMaxNumberOfSpends = 4; const bool fMinimizeChange = false; const int DenomAmounts[] = {0, 1, 4, 2, 1, 0, 0, 0}; CAmount nSelectedValue; std::list<CMintMeta> listMints; std::map<CoinDenomination, CAmount> mapOfDenomsHeld; int j = 0; CAmount nTotalAmount = 0; int CoinsHeld = 0; // Create a set of Minted coins that fits profile given by DenomAmounts // Also setup Map array corresponding to DenomAmount which is the current set of coins available for (const auto& denom : zerocoinDenomList) { for (int i = 0; i < DenomAmounts[j]; i++) { CAmount currentAmount = ZerocoinDenominationToAmount(denom); nTotalAmount += currentAmount; CBigNum value; CBigNum rand; CBigNum serial = CBigNum::randKBitBignum(256); bool isUsed = false; CMintMeta meta; meta.denom = denom; meta.hashPubcoin = GetPubCoinHash(value); meta.hashSerial = GetSerialHash(serial); meta.isUsed = isUsed; meta.nVersion = 1; listMints.push_back(meta); } mapOfDenomsHeld.insert(std::pair<CoinDenomination, CAmount>(denom, DenomAmounts[j])); j++; } CoinsHeld = nTotalAmount / COIN; std::cout << "Curremt Amount held = " << CoinsHeld << ": "; // Show what we have j = 0; for (const auto& denom : zerocoinDenomList) std::cout << DenomAmounts[j++] << "*" << ZerocoinDenominationToAmount(denom) / COIN << " + "; std::cout << "\n"; CAmount OneCoinAmount = ZerocoinDenominationToAmount(ZQ_ONE); CAmount nValueTarget = 99 * OneCoinAmount; // bool fDebug = 0; int nCoinsReturned; int nNeededSpends = 0; // Number of spends which would be needed if selection failed std::vector<CMintMeta> vSpends = SelectMintsFromList(nValueTarget, nSelectedValue, nMaxNumberOfSpends, fMinimizeChange, nCoinsReturned, listMints, mapOfDenomsHeld, nNeededSpends); // if (fDebug) { // if (vSpends.size() > 0) { // std::cout << "SUCCESS : Coins = " << nValueTarget / COIN << " # spends used = " << vSpends.size() // << " # of coins returned = " << nCoinsReturned // << " Spend Amount = " << nSelectedValue / COIN << " Held = " << CoinsHeld << "\n"; // } else { // std::cout << "FAILED : Coins = " << nValueTarget / COIN << " Held = " << CoinsHeld << "\n"; // } // } BOOST_CHECK_MESSAGE(vSpends.size() < 5, "Too many spends"); BOOST_CHECK_MESSAGE(vSpends.size() > 0, "No spends"); nValueTarget += OneCoinAmount; } BOOST_AUTO_TEST_SUITE_END()
// This file is automatically generated at compile-time to include some subset of the user-created cpp files. #include "C:/!Unreal/!Assignment/basic5_Teacher/Plugins/AGRPRO/Source/AGRPRO/Private/AGRPRO.cpp" #include "C:/!Unreal/!Assignment/basic5_Teacher/Plugins/AGRPRO/Source/AGRPRO/Private/Animation/AGRCoreAnimInstance.cpp" #include "C:/!Unreal/!Assignment/basic5_Teacher/Plugins/AGRPRO/Source/AGRPRO/Private/Characters/AGRCharacter.cpp" #include "C:/!Unreal/!Assignment/basic5_Teacher/Plugins/AGRPRO/Source/AGRPRO/Private/Components/AGRAnimMasterComponent.cpp" #include "C:/!Unreal/!Assignment/basic5_Teacher/Plugins/AGRPRO/Source/AGRPRO/Private/Components/AGR_SoundMaster.cpp" #include "C:/!Unreal/!Assignment/basic5_Teacher/Plugins/AGRPRO/Source/AGRPRO/Private/Data/AGR_Footstep_Notify.cpp" #include "C:/!Unreal/!Assignment/basic5_Teacher/Plugins/AGRPRO/Source/AGRPRO/Private/Data/DA_AGR_FootstepConfig.cpp" #include "C:/!Unreal/!Assignment/basic5_Teacher/Plugins/AGRPRO/Source/AGRPRO/Private/Data/DA_FootstepConfig.cpp"
#ifndef __CREATURE_H_ #define __CREATURE_H_ #include <algorithm> #include <thread> #include <liblog/liblog.hpp> #include "EventBus.hpp" #include "lss/game/content/traits.hpp" #include "lss/game/damage.hpp" #include "lss/game/effect.hpp" #include "lss/game/equipment.hpp" #include "lss/game/item.hpp" #include "lss/game/object.hpp" #include "lss/game/trait.hpp" #include <lss/game/ai.hpp> #include <lss/game/damageSpec.hpp> #include <lss/game/location.hpp> class Creature : public Object { LibLog::Logger &log = LibLog::Logger::getInstance(); public: Creature(); std::string getId() {return name;} std::vector<std::shared_ptr<Cell>> viewField; std::shared_ptr<Location> currentLocation; std::vector<Trait> traits; Effects activeEffects; std::thread bgThread; bool move(Direction, bool autoAction = false); bool attack(Direction); bool canSee(std::shared_ptr<Cell> c) { return canSee(c, viewField); }; bool canSee(std::shared_ptr<Cell> c, std::vector<std::shared_ptr<Cell>> vf) { for (auto t : utils::castObjects<Terrain>( currentLocation->getObjects(currentCell))) { if (t->type == TerrainType::DARKNESS) { return false; } } return std::find(vf.begin(), vf.end(), c) != vf.end() || hasTrait(Traits::MIND_SIGHT); }; std::vector<std::shared_ptr<Cell>> calcViewField(bool force = false); bool interact(std::shared_ptr<Object>); std::shared_ptr<Damage> getDamage(std::shared_ptr<Object>); std::string getDmgDesc(); std::string name = "Unnamed"; std::vector<std::string> knownItems; void identify(std::shared_ptr<Item> item) { item->identified = true; knownItems.push_back(item->getTitle()); std::for_each(inventory.begin(), inventory.end(), [&](auto i) { if (!i->identified && i->getTitle(true) == item->getTitle(true)) { identify(i); } }); } bool isIdentified(std::shared_ptr<Item> item) { return item->identified || std::find(knownItems.begin(), knownItems.end(), item->getTitle(true)) != knownItems.end(); } Items inventory; std::shared_ptr<Equipment> equipment; bool pick(std::shared_ptr<Item>); bool drop(std::shared_ptr<Item>); bool throwItem(std::shared_ptr<Item>, std::shared_ptr<Cell>); int hp; int hp_max; DamageSpec dmgSpec = DamageSpec(0, 0, 0, DamageType::BASIC); float speed = 1.f; float visibility_distance = 0; float default_visibility = 3.2f; float crit_chance = 0.1; int defense = 0; int level = 0; int throw_distance = 7; int mp = 0; int mp_max = 0; int actionPoints = 0; std::optional<AiAction> execAction() { log.warn("call execAction on creature"); log.info(fmt::format("creature [{}@{}.{}]", lu::magenta(name), currentCell->x, currentCell->y)); return std::nullopt; } std::optional<std::tuple<std::shared_ptr<Slot>, DamageSpec>> getPrimaryDmg(); std::optional<std::tuple<std::shared_ptr<Slot>, DamageSpec>> getSecondaryDmg(std::shared_ptr<Slot>); std::vector<Trait> getTraits() { auto allTraits = traits; for (auto s : equipment->slots) { if (s->item == nullptr || std::find(s->acceptTypes.begin(), s->acceptTypes.end(), s->item->type.wearableType) == s->acceptTypes.end()) { continue; } for (auto e : s->item->effects) { if (auto et = std::dynamic_pointer_cast<TraitEffect>(e)) { allTraits.push_back(et->trait); } } } for (auto e : activeEffects) { if (auto le = std::dynamic_pointer_cast<LastingEffect>(e)) { if (auto et = std::dynamic_pointer_cast<TraitEffect>(le->effect)) { allTraits.push_back(et->trait); } } } return allTraits; } bool hasTrait(Trait t) { auto allTraits = getTraits(); return std::find(allTraits.begin(), allTraits.end(), t) != allTraits.end(); } bool hasLight(); std::shared_ptr<Damage> updateDamage(std::shared_ptr<Damage>, DamageSpec); std::vector<std::shared_ptr<Cell>> getInRadius(float distance); void applyDamage(std::shared_ptr<Object> attacker, std::shared_ptr<Damage>); virtual void onDamage(std::shared_ptr<Creature>, std::shared_ptr<Damage>) = 0; virtual void onDie() = 0; std::shared_ptr<Slot> getSlot(WearableType type); std::optional<std::shared_ptr<Slot>> getSlot(WearableType type, bool); bool hasResist(DamageType dt) { auto trait = RESISTS.at(dt); return hasTrait(trait); } bool hasImmunity(DamageType dt) { auto trait = IMMUNITIES.at(dt); return hasTrait(trait); } bool hasVulnerable(DamageType dt) { auto trait = VULNERABLES.at(dt); return hasTrait(trait); } std::optional<std::shared_ptr<Creature>> getNearestTarget(float distance) { std::optional<std::shared_ptr<Creature>> target = std::nullopt; auto cells = getInRadius(distance); std::vector<std::shared_ptr<Creature>> targets; for (auto c : cells) { auto objects = currentLocation->getObjects(c); auto enemies = utils::castObjects<Creature>(objects); if (enemies.size() != 0) { targets.push_back(enemies.front()); } } auto d = distance; auto cc = currentCell; for (auto e : targets) { if (e->currentCell == nullptr) { throw std::runtime_error( fmt::format("{} -> nullptr current cell again", e->name)); } auto td = sqrt(pow(cc->x - e->currentCell->x, 2) + pow(cc->y - e->currentCell->y, 2)); if (td <= d) { target = std::make_optional<std::shared_ptr<Creature>>(e); d = td; } } return target; } std::optional<LightSpec> getGlow() override { std::optional<LightSpec> result = std::nullopt; auto effects = getEffects(AttributeType::VISIBILITY_DISTANCE); for (auto e : effects) { if (auto vm = std::dynamic_pointer_cast<VisibilityModifier>(e); vm && vm->glow) { if (!result || vm->light.distance > (*result).distance) { result = vm->light; } } } return result; } Effects getEffects(AttributeType type) { Effects effects; effects.insert(effects.end(), activeEffects.begin(), activeEffects.end()); for (auto s : equipment->slots) { if (s->item == nullptr || std::find(s->acceptTypes.begin(), s->acceptTypes.end(), s->item->type.wearableType) == s->acceptTypes.end()) { continue; } for (auto e : s->item->effects) { if (e->type != type) continue; effects.push_back(e); } } return effects; } void prepareAiState(); float intelligence = 1.f; float strength = 1.f; Attribute HP = Attribute(AttributeType::HP); Attribute HP_MAX = Attribute(AttributeType::HP_MAX); Attribute MP = Attribute(AttributeType::MP); Attribute MP_MAX = Attribute(AttributeType::MP_MAX); Attribute SPEED = Attribute(AttributeType::SPEED); Attribute VISIBILITY_DISTANCE = Attribute(AttributeType::VISIBILITY_DISTANCE); Attribute DMG = Attribute(AttributeType::DAMAGE); Attribute DEF = Attribute(AttributeType::DEFENSE); Attribute CRIT = Attribute(AttributeType::CRIT_CHANCE); Attribute INTELLIGENCE = Attribute(AttributeType::INTELLIGENCE); Attribute STRENGTH = Attribute(AttributeType::STRENGTH); float getThrowRange() { return STRENGTH(this) * throw_distance; } void applyEoT(EoT, int); std::vector<std::shared_ptr<Cell>> path; micropather::MicroPather *pather = nullptr; std::shared_ptr<Creature> lastTarget; std::shared_ptr<Cell> lastTargetCell; std::vector<std::shared_ptr<Cell>> findPath(std::shared_ptr<Cell>); AiState getAiState(std::shared_ptr<Object>); AiState lastAiState; void commit(std::string reason, int ap, bool s = false); int waitedAP = 0; void heal(int min, int max) { auto heal = R::Z(HP_MAX(this) / 100 * min, HP_MAX(this) / 100 * max); hp += heal; if (HP(this) > HP_MAX(this)) { hp = HP_MAX(this); } commit("heal", 0); auto a = std::make_shared<ColorAnimation>(shared_from_this(), Color::fromHexString("#2222ff"), 8, true); AnimationEvent ae(a); eb::EventBus::FireEvent(ae); } void restoreMana(int min, int max) { auto heal = R::Z(MP_MAX(this) / 100 * min, MP_MAX(this) / 100 * max); mp += heal; if (MP(this) > MP_MAX(this)) { mp = MP_MAX(this); } commit("manaRestore", 0); auto a = std::make_shared<ColorAnimation>(shared_from_this(), Color::fromHexString("#2222ff"), 8, true); AnimationEvent ae(a); eb::EventBus::FireEvent(ae); } private: std::shared_ptr<Cell> cachedCell; }; #endif // __CREATURE_H_
// ver_test_1.cc -- a test case for gold // Copyright (C) 2007-2017 Free Software Foundation, Inc. // Written by Cary Coutant <ccoutant@google.com>. // This file is part of gold. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, // MA 02110-1301, USA. #include "ver_test.h" // Calls an unversioned function in file1 that overrides // a versioned function in file2. bool t1() { TRACE return t1_2() == 11; }
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/exec/arg/FetchTagArrayDirectOut.h> #include <vtkm/exec/arg/testing/ThreadIndicesTesting.h> #include <vtkm/testing/Testing.h> namespace { static constexpr vtkm::Id ARRAY_SIZE = 10; static vtkm::Id g_NumSets; template <typename T> struct TestPortal { using ValueType = T; VTKM_EXEC_CONT vtkm::Id GetNumberOfValues() const { return ARRAY_SIZE; } VTKM_EXEC_CONT void Set(vtkm::Id index, const ValueType& value) const { VTKM_TEST_ASSERT(index >= 0, "Bad portal index."); VTKM_TEST_ASSERT(index < this->GetNumberOfValues(), "Bad portal index."); VTKM_TEST_ASSERT(test_equal(value, TestValue(index, ValueType())), "Tried to set invalid value."); g_NumSets++; } }; template <typename T> struct FetchArrayDirectOutTests { void operator()() { TestPortal<T> execObject; using FetchType = vtkm::exec::arg::Fetch<vtkm::exec::arg::FetchTagArrayDirectOut, vtkm::exec::arg::AspectTagDefault, vtkm::exec::arg::ThreadIndicesTesting, TestPortal<T>>; FetchType fetch; g_NumSets = 0; for (vtkm::Id index = 0; index < ARRAY_SIZE; index++) { vtkm::exec::arg::ThreadIndicesTesting indices(index); // This is a no-op, but should be callable. T value = fetch.Load(indices, execObject); value = TestValue(index, T()); // The portal will check to make sure we are setting a good value. fetch.Store(indices, execObject, value); } VTKM_TEST_ASSERT(g_NumSets == ARRAY_SIZE, "Array portal's set not called correct number of times." "Store method must be wrong."); } }; struct TryType { template <typename T> void operator()(T) const { FetchArrayDirectOutTests<T>()(); } }; void TestExecObjectFetch() { vtkm::testing::Testing::TryTypes(TryType()); } } // anonymous namespace int UnitTestFetchArrayDirectOut(int argc, char* argv[]) { return vtkm::testing::Testing::Run(TestExecObjectFetch, argc, argv); }
#include <rudiments/sharedmemory.h> #include <rudiments/charstring.h> #include <rudiments/permissions.h> #include <rudiments/file.h> #include <rudiments/error.h> #include <rudiments/snooze.h> #include <rudiments/process.h> #include <rudiments/stdio.h> int main(int argc, const char **argv) { // create a file called "shm" file::createFile("shm",permissions::evalPermString("rw-------")); // create a 128 byte shared memory segment, keyed to the file "shm" sharedmemory shm; if (!shm.create(file::generateKey("shm",1),128, permissions::evalPermString("rw-------"))) { stdoutput.printf("error: %s\n",error::getErrorString()); process::exit(1); } // write a string into the shared memory char *shmptr=(char *)shm.getPointer(); charstring::copy(shmptr,"This string is in shared memory."); // sleep for 10 seconds, giving another process some time to access // the shared memory... snooze::macrosnooze(10); // remove the file "shm" file::remove("shm"); }
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: CompilableIRFunction.tcc (emitters) // Authors: Chuck Jacobs // //////////////////////////////////////////////////////////////////////////////////////////////////// namespace ell { namespace emitters { template <typename ValueType> ValueType IRAddFunction<ValueType>::Compute(ValueType x, ValueType y) const { return x + y; } template <typename ValueType> llvm::Value* IRAddFunction<ValueType>::Compile(IRFunctionEmitter& function, llvm::Value* x, llvm::Value* y) const { llvm::Value* sum = function.Operator(emitters::GetAddForValueType<ValueType>(), x, y); return sum; } } }
/* * Copyright (C) 2020 Yaron Gvili and Gvili Tech Ltd. * * See the accompanying LICENSE.txt file for licensing information. */ /*! \file include/libswifft/swifft_iset.inl * \brief LibSWIFFT public C API expansion for instruction-sets */ #include "libswifft/swifft_common.h" #undef SWIFFT_ISET_NAME #ifndef SWIFFT_ISET #error "SWIFFT_ISET() must be defined as AVX, AVX2, or AVX512" #endif #define SWIFFT_ISET_NAME(name) LIBSWIFFT_CONCAT(name,SWIFFT_ISET()) ///< Adds a suffix SWIFFT_ISET, a macro which must be defined prior to including LIBSWIFFT_BEGIN_EXTERN_C //! \brief Computes the FFT phase of SWIFFT. //! //! \param[in] input the blocks of input, each of 256 bytes (2048 bits). //! \param[in] sign the blocks of sign bits corresponding to blocks of input of 256 bytes (2048 bits). //! \param[in] m number of 8-elements in the input. //! \param[out] fftout the blocks of FFT-output elements, totaling N*m. void SWIFFT_ISET_NAME(SWIFFT_fft_)(const BitSequence * LIBSWIFFT_RESTRICT input, const BitSequence * LIBSWIFFT_RESTRICT sign, int m, int16_t *fftout); //! \brief Computes the FFT-sum phase of SWIFFT. //! //! \param[in] ikey the SWIFFT key. //! \param[in] ifftout the blocks of FFT-output elements, totaling N*m //! \param[in] m number of 8-elements in the input. //! \param[out] iout the blocks of output elements, each of 64 double-bytes (1024 bits). void SWIFFT_ISET_NAME(SWIFFT_fftsum_)(const int16_t * LIBSWIFFT_RESTRICT ikey, const int16_t * LIBSWIFFT_RESTRICT ifftout, int m, int16_t * LIBSWIFFT_RESTRICT iout); //! \brief Sets a constant value at each SWIFFT hash value element. //! //! \param[out] output the hash value of SWIFFT to modify. //! \param[in] operand the constant value to set. void SWIFFT_ISET_NAME(SWIFFT_ConstSet_)(BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE], const int16_t operand); //! \brief Adds a constant value to each SWIFFT hash value element. //! //! \param[in,out] output the hash value of SWIFFT to modify. //! \param[in] operand the constant value to add. void SWIFFT_ISET_NAME(SWIFFT_ConstAdd_)(BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE], const int16_t operand); //! \brief Subtracts a constant value from each SWIFFT hash value element. //! //! \param[in,out] output the hash value of SWIFFT to modify. //! \param[in] operand the constant value to subtract. void SWIFFT_ISET_NAME(SWIFFT_ConstSub_)(BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE], const int16_t operand); //! \brief Multiply a constant value into each SWIFFT hash value element. //! //! \param[in,out] output the hash value of SWIFFT to modify. //! \param[in] operand the constant value to multiply by. void SWIFFT_ISET_NAME(SWIFFT_ConstMul_)(BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE], const int16_t operand); //! \brief Sets a SWIFFT hash value to another, element-wise. //! //! \param[in,out] output the hash value of SWIFFT to modify. //! \param[in] operand the hash value to set to. void SWIFFT_ISET_NAME(SWIFFT_Set_)(BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE], const BitSequence operand[SWIFFT_OUTPUT_BLOCK_SIZE]); //! \brief Adds a SWIFFT hash value to another, element-wise. //! //! \param[in,out] output the hash value of SWIFFT to modify. //! \param[in] operand the hash value to add. void SWIFFT_ISET_NAME(SWIFFT_Add_)(BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE], const BitSequence operand[SWIFFT_OUTPUT_BLOCK_SIZE]); //! \brief Subtracts a SWIFFT hash value from another, element-wise. //! //! \param[in,out] output the hash value of SWIFFT to modify. //! \param[in] operand the hash value to subtract. void SWIFFT_ISET_NAME(SWIFFT_Sub_)(BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE], const BitSequence operand[SWIFFT_OUTPUT_BLOCK_SIZE]); //! \brief Multiplies a SWIFFT hash value from another, element-wise. //! //! \param[in,out] output the hash value of SWIFFT to modify. //! \param[in] operand the hash value to multiply by. void SWIFFT_ISET_NAME(SWIFFT_Mul_)(BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE], const BitSequence operand[SWIFFT_OUTPUT_BLOCK_SIZE]); //! \brief Computes the result of a SWIFFT operation. //! The result is composable with other hash values. //! //! \param[in] input the input of 256 bytes (2048 bit). //! \param[out] output the resulting hash value of SWIFFT, of size 128 bytes (1024 bit). void SWIFFT_ISET_NAME(SWIFFT_Compute_)(const BitSequence input[SWIFFT_INPUT_BLOCK_SIZE], BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE]); //! \brief Computes the result of a SWIFFT operation. //! The result is composable with other hash values. //! //! \param[in] input the input of 256 bytes (2048 bit). //! \param[in] sign the sign bits corresponding to the input of 256 bytes (2048 bit). //! \param[out] output the resulting hash value of SWIFFT, of size 128 bytes (1024 bit). void SWIFFT_ISET_NAME(SWIFFT_ComputeSigned_)(const BitSequence input[SWIFFT_INPUT_BLOCK_SIZE], const BitSequence sign[SWIFFT_INPUT_BLOCK_SIZE], BitSequence output[SWIFFT_OUTPUT_BLOCK_SIZE]); //! \brief Computes the FFT phase of SWIFFT for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in] input the blocks of input, each of 256 bytes (2048 bits). //! \param[in] sign the blocks of sign bits corresponding to blocks of input of 256 bytes (2048 bits). //! \param[in] m number of 8-elements in the input. //! \param[out] fftout the blocks of FFT-output elements, totaling nblocks*N*m. void SWIFFT_ISET_NAME(SWIFFT_fftMultiple_)(int nblocks, const BitSequence * LIBSWIFFT_RESTRICT input, const BitSequence * LIBSWIFFT_RESTRICT sign, int m, int16_t * LIBSWIFFT_RESTRICT fftout); //! \brief Computes the FFT-sum phase of SWIFFT for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in] ikey the SWIFFT key. //! \param[in] ifftout the blocks of FFT-output elements, totaling N*m //! \param[in] m number of 8-elements in the input. //! \param[out] iout the blocks of output elements, each of 64 double-bytes (1024 bits). void SWIFFT_ISET_NAME(SWIFFT_fftsumMultiple_)(int nblocks, const int16_t * LIBSWIFFT_RESTRICT ikey, const int16_t * LIBSWIFFT_RESTRICT ifftout, int m, int16_t * LIBSWIFFT_RESTRICT iout); //! \brief Compacts a hash value of SWIFFT for multiple blocks. //! The result is not composable with other compacted hash values. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in] output the hash value of SWIFFT, of size 128 bytes (1024 bit) per block. //! \param[out] compact the compacted hash value of SWIFFT, of size 64 bytes (512 bit) per block. void SWIFFT_ISET_NAME(SWIFFT_CompactMultiple_)(int nblocks, const BitSequence * output, BitSequence * compact); //! \brief Sets a constant value at each SWIFFT hash value element for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[out] output the hash value of SWIFFT to modify, per block. //! \param[in] operand the constant value to set, per block. void SWIFFT_ISET_NAME(SWIFFT_ConstSetMultiple_)(int nblocks, BitSequence * output, const int16_t * operand); //! \brief Adds a constant value to each SWIFFT hash value element for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in,out] output the hash value of SWIFFT to modify, per block. //! \param[in] operand the constant value to add, per block. void SWIFFT_ISET_NAME(SWIFFT_ConstAddMultiple_)(int nblocks, BitSequence * output, const int16_t * operand); //! \brief Subtracts a constant value from each SWIFFT hash value element for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in,out] output the hash value of SWIFFT to modify, per block.. //! \param[in] operand the constant value to subtract, per block. void SWIFFT_ISET_NAME(SWIFFT_ConstSubMultiple_)(int nblocks, BitSequence * output, const int16_t * operand); //! \brief Multiply a constant value into each SWIFFT hash value element for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in,out] output the hash value of SWIFFT to modify, per block.. //! \param[in] operand the constant value to multiply by, per block. void SWIFFT_ISET_NAME(SWIFFT_ConstMulMultiple_)(int nblocks, BitSequence * output, const int16_t * operand); //! \brief Sets a SWIFFT hash value to another, element-wise, for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in,out] output the hash value of SWIFFT to modify, per block.. //! \param[in] operand the hash value to set to, per block. void SWIFFT_ISET_NAME(SWIFFT_SetMultiple_)(int nblocks, BitSequence * output, const BitSequence * operand); //! \brief Adds a SWIFFT hash value to another, element-wise, for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in,out] output the hash value of SWIFFT to modify, per block.. //! \param[in] operand the hash value to add, per block. void SWIFFT_ISET_NAME(SWIFFT_AddMultiple_)(int nblocks, BitSequence * output, const BitSequence * operand); //! \brief Subtracts a SWIFFT hash value from another, element-wise, for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in,out] output the hash value of SWIFFT to modify, per block.. //! \param[in] operand the hash value to subtract, per block. void SWIFFT_ISET_NAME(SWIFFT_SubMultiple_)(int nblocks, BitSequence * output, const BitSequence * operand); //! \brief Multiplies a SWIFFT hash value from another, element-wise, for multiple blocks. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in,out] output the hash value of SWIFFT to modify, per block.. //! \param[in] operand the hash value to multiply by, per block. void SWIFFT_ISET_NAME(SWIFFT_MulMultiple_)(int nblocks, BitSequence * output, const BitSequence * operand); //! \brief Computes the result of multiple SWIFFT operations. //! The result is composable with other hash values. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in] input the blocks of input, each of 256 bytes (2048 bit). //! \param[out] output the resulting blocks of hash values of SWIFFT, each of size 128 bytes (1024 bit). void SWIFFT_ISET_NAME(SWIFFT_ComputeMultiple_)(int nblocks, const BitSequence * input, BitSequence * output); //! \brief Computes the result of multiple SWIFFT operations. //! The result is composable with other hash values. //! //! \param[in] nblocks the number of blocks to operate on. //! \param[in] input the blocks of input, each of 256 bytes (2048 bit). //! \param[in] sign the blocks of sign bits corresponding to blocks of input of 256 bytes (2048 bit). //! \param[out] output the resulting blocks of hash values of SWIFFT, each of size 128 bytes (1024 bit). void SWIFFT_ISET_NAME(SWIFFT_ComputeMultipleSigned_)(int nblocks, const BitSequence * input, const BitSequence * sign, BitSequence * output); LIBSWIFFT_END_EXTERN_C
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #include <aws/sms-voice/model/EventType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace PinpointSMSVoice { namespace Model { namespace EventTypeMapper { static const int INITIATED_CALL_HASH = HashingUtils::HashString("INITIATED_CALL"); static const int RINGING_HASH = HashingUtils::HashString("RINGING"); static const int ANSWERED_HASH = HashingUtils::HashString("ANSWERED"); static const int COMPLETED_CALL_HASH = HashingUtils::HashString("COMPLETED_CALL"); static const int BUSY_HASH = HashingUtils::HashString("BUSY"); static const int FAILED_HASH = HashingUtils::HashString("FAILED"); static const int NO_ANSWER_HASH = HashingUtils::HashString("NO_ANSWER"); EventType GetEventTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == INITIATED_CALL_HASH) { return EventType::INITIATED_CALL; } else if (hashCode == RINGING_HASH) { return EventType::RINGING; } else if (hashCode == ANSWERED_HASH) { return EventType::ANSWERED; } else if (hashCode == COMPLETED_CALL_HASH) { return EventType::COMPLETED_CALL; } else if (hashCode == BUSY_HASH) { return EventType::BUSY; } else if (hashCode == FAILED_HASH) { return EventType::FAILED; } else if (hashCode == NO_ANSWER_HASH) { return EventType::NO_ANSWER; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<EventType>(hashCode); } return EventType::NOT_SET; } Aws::String GetNameForEventType(EventType enumValue) { switch(enumValue) { case EventType::INITIATED_CALL: return "INITIATED_CALL"; case EventType::RINGING: return "RINGING"; case EventType::ANSWERED: return "ANSWERED"; case EventType::COMPLETED_CALL: return "COMPLETED_CALL"; case EventType::BUSY: return "BUSY"; case EventType::FAILED: return "FAILED"; case EventType::NO_ANSWER: return "NO_ANSWER"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace EventTypeMapper } // namespace Model } // namespace PinpointSMSVoice } // namespace Aws
#include "Common.h" struct PerEyeArg { FramebufferWrapperPtr framebuffer; glm::mat4 projection; }; class CubeScene_RiftSensors : public RiftGlfwApp { PerEyeArg eyes[2]; ovrTexture eyeTextures[2]; ovrVector3f eyeOffsets[2]; float ipd, eyeHeight; public: CubeScene_RiftSensors() { eyeHeight = ovrHmd_GetFloat(hmd, OVR_KEY_EYE_HEIGHT, eyeHeight); ipd = ovrHmd_GetFloat(hmd, OVR_KEY_IPD, ipd); Stacks::modelview().top() = glm::lookAt( vec3(0, eyeHeight, 0.5f), vec3(0, eyeHeight, 0), Vectors::UP); if (!ovrHmd_ConfigureTracking(hmd, ovrTrackingCap_Orientation | ovrTrackingCap_Position, 0)) { SAY("Warning: Unable to locate Rift sensor device. This demo is boring now."); } } virtual void initGl() { RiftGlfwApp::initGl(); ovrRenderAPIConfig cfg; memset(&cfg, 0, sizeof(cfg)); cfg.Header.API = ovrRenderAPI_OpenGL; cfg.Header.BackBufferSize = ovr::fromGlm(getSize()); cfg.Header.Multisample = 1; int distortionCaps = ovrDistortionCap_Vignette; ovrEyeRenderDesc eyeRenderDescs[2]; int configResult = ovrHmd_ConfigureRendering(hmd, &cfg, distortionCaps, hmd->DefaultEyeFov, eyeRenderDescs); for_each_eye([&](ovrEyeType eye) { PerEyeArg & eyeArgs = eyes[eye]; ovrFovPort fov = hmd->DefaultEyeFov[eye]; ovrSizei texSize = ovrHmd_GetFovTextureSize(hmd, eye, fov, 1.0f); eyeArgs.framebuffer = FramebufferWrapperPtr(new FramebufferWrapper()); eyeArgs.framebuffer->init(ovr::toGlm(texSize)); ovrTextureHeader & textureHeader = eyeTextures[eye].Header; textureHeader.API = ovrRenderAPI_OpenGL; textureHeader.TextureSize = texSize; textureHeader.RenderViewport.Size = texSize; textureHeader.RenderViewport.Pos.x = 0; textureHeader.RenderViewport.Pos.y = 0; ((ovrGLTextureData&)eyeTextures[eye]).TexId = oglplus::GetName(eyeArgs.framebuffer->color); eyeOffsets[eye] = eyeRenderDescs[eye].HmdToEyeViewOffset; ovrMatrix4f projection = ovrMatrix4f_Projection(fov, 0.01f, 100, true); eyeArgs.projection = ovr::toGlm(projection); }); } virtual void finishFrame() { } virtual void draw() { ovrPosef eyePoses[2]; ovrHmd_GetEyePoses(hmd, getFrame(), eyeOffsets, eyePoses, nullptr); ovrHmd_BeginFrame(hmd, getFrame()); MatrixStack & mv = Stacks::modelview(); for (int i = 0; i < ovrEye_Count; ++i) { ovrEyeType eye = hmd->EyeRenderOrder[i]; PerEyeArg & eyeArgs = eyes[eye]; Stacks::projection().top() = eyeArgs.projection; eyeArgs.framebuffer->Bind(); oglplus::Context::Clear().DepthBuffer(); Stacks::withPush(mv, [&]{ mv.preMultiply(glm::inverse(ovr::toGlm(eyePoses[eye]))); oria::renderExampleScene(ipd, eyeHeight); }); } ovrHmd_EndFrame(hmd, eyePoses, eyeTextures); } }; RUN_OVR_APP(CubeScene_RiftSensors);
// Derived from VTK/Examples/Cxx/Medical2.cxx // This example reads a volume dataset, extracts two isosurfaces that // represent the skin and bone, and then displays them. // #include <vtkActor.h> #include <vtkCamera.h> #include <vtkMarchingCubes.h> #include <vtkMetaImageReader.h> #include <vtkNamedColors.h> #include <vtkOutlineFilter.h> #include <vtkPolyDataMapper.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkSmartPointer.h> #include <vtkStripper.h> #include <array> int main (int argc, char *argv[]) { if (argc < 2) { cout << "Usage: " << argv[0] << " file.mhd" << endl; return EXIT_FAILURE; } vtkSmartPointer<vtkNamedColors> colors = vtkSmartPointer<vtkNamedColors>::New(); // Set the colors. std::array<unsigned char , 4> skinColor{{255, 125, 64}}; colors->SetColor("SkinColor", skinColor.data()); std::array<unsigned char , 4> bkg{{51, 77, 102, 255}}; colors->SetColor("BkgColor", bkg.data()); // Create the renderer, the render window, and the interactor. The renderer // draws into the render window, the interactor enables mouse- and // keyboard-based interaction with the data within the render window. // vtkSmartPointer<vtkRenderer> aRenderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->AddRenderer(aRenderer); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow(renWin); // The following reader is used to read a series of 2D slices (images) // that compose the volume. The slice dimensions are set, and the // pixel spacing. The data Endianness must also be specified. The reader // uses the FilePrefix in combination with the slice number to construct // filenames using the format FilePrefix.%d. (In this case the FilePrefix // is the root name of the file: quarter.) vtkSmartPointer<vtkMetaImageReader> reader = vtkSmartPointer<vtkMetaImageReader>::New(); reader->SetFileName (argv[1]); // An isosurface, or contour value of 500 is known to correspond to the // skin of the patient. // The triangle stripper is used to create triangle strips from the // isosurface; these render much faster on many systems. vtkSmartPointer<vtkMarchingCubes> skinExtractor = vtkSmartPointer<vtkMarchingCubes>::New(); skinExtractor->SetInputConnection(reader->GetOutputPort()); skinExtractor->SetValue(0, 500); vtkSmartPointer<vtkStripper> skinStripper = vtkSmartPointer<vtkStripper>::New(); skinStripper->SetInputConnection(skinExtractor->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> skinMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); skinMapper->SetInputConnection(skinStripper->GetOutputPort()); skinMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> skin = vtkSmartPointer<vtkActor>::New(); skin->SetMapper(skinMapper); skin->GetProperty()->SetDiffuseColor(colors->GetColor3d("SkinColor").GetData()); skin->GetProperty()->SetSpecular(.3); skin->GetProperty()->SetSpecularPower(20); skin->GetProperty()->SetOpacity(.5); // An isosurface, or contour value of 1150 is known to correspond to the // bone of the patient. // The triangle stripper is used to create triangle strips from the // isosurface; these render much faster on may systems. vtkSmartPointer<vtkMarchingCubes> boneExtractor = vtkSmartPointer<vtkMarchingCubes>::New(); boneExtractor->SetInputConnection(reader->GetOutputPort()); boneExtractor->SetValue(0, 1150); vtkSmartPointer<vtkStripper> boneStripper = vtkSmartPointer<vtkStripper>::New(); boneStripper->SetInputConnection(boneExtractor->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> boneMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); boneMapper->SetInputConnection(boneStripper->GetOutputPort()); boneMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> bone = vtkSmartPointer<vtkActor>::New(); bone->SetMapper(boneMapper); bone->GetProperty()->SetDiffuseColor(colors->GetColor3d("Ivory").GetData()); // An outline provides context around the data. // vtkSmartPointer<vtkOutlineFilter> outlineData = vtkSmartPointer<vtkOutlineFilter>::New(); outlineData->SetInputConnection(reader->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> mapOutline = vtkSmartPointer<vtkPolyDataMapper>::New(); mapOutline->SetInputConnection(outlineData->GetOutputPort()); vtkSmartPointer<vtkActor> outline = vtkSmartPointer<vtkActor>::New(); outline->SetMapper(mapOutline); outline->GetProperty()->SetColor(colors->GetColor3d("Black").GetData()); // It is convenient to create an initial view of the data. The FocalPoint // and Position form a vector direction. Later on (ResetCamera() method) // this vector is used to position the camera to look at the data in // this direction. vtkSmartPointer<vtkCamera> aCamera = vtkSmartPointer<vtkCamera>::New(); aCamera->SetViewUp (0, 0, -1); aCamera->SetPosition (0, -1, 0); aCamera->SetFocalPoint (0, 0, 0); aCamera->ComputeViewPlaneNormal(); aCamera->Azimuth(30.0); aCamera->Elevation(30.0); // Actors are added to the renderer. An initial camera view is created. // The Dolly() method moves the camera towards the FocalPoint, // thereby enlarging the image. aRenderer->AddActor(outline); aRenderer->AddActor(skin); aRenderer->AddActor(bone); aRenderer->SetActiveCamera(aCamera); aRenderer->ResetCamera (); aCamera->Dolly(1.5); // Set a background color for the renderer and set the size of the // render window (expressed in pixels). aRenderer->SetBackground(colors->GetColor3d("BkgColor").GetData()); renWin->SetSize(640, 480); // Note that when camera movement occurs (as it does in the Dolly() // method), the clipping planes often need adjusting. Clipping planes // consist of two planes: near and far along the view direction. The // near plane clips out objects in front of the plane; the far plane // clips out objects behind the plane. This way only what is drawn // between the planes is actually rendered. aRenderer->ResetCameraClippingRange (); // Initialize the event loop and then start it. iren->Initialize(); iren->Start(); return EXIT_SUCCESS; }
/****************************************************************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #include "qwt_point_mapper.h" #include "qwt_scale_map.h" #include "qwt_pixel_matrix.h" #include "qwt_series_data.h" #include "qwt_math.h" #include <qpolygon.h> #include <qimage.h> #include <qpen.h> #include <qpainter.h> #include <qthread.h> #include <qfuture.h> #include <qtconcurrentrun.h> #if !defined( QT_NO_QFUTURE ) #define QWT_USE_THREADS 1 #endif static QRectF qwtInvalidRect( 0.0, 0.0, -1.0, -1.0 ); static inline int qwtRoundValue( double value ) { return qRound( value ); } static inline double qwtRoundValueF( double value ) { #if 1 // MS Windows and at least IRIX does not have C99's nearbyint() function return ( value >= 0.0 ) ? std::floor( value + 0.5 ) : std::ceil( value - 0.5 ); #else return nearbyint( value ); #endif } static Qt::Orientation qwtProbeOrientation( const QwtSeriesData< QPointF >* series, int from, int to ) { if ( to - from < 20 ) { // not enough points to "have an orientation" return Qt::Horizontal; } const double x0 = series->sample( from ).x(); const double xn = series->sample( to ).x(); if ( x0 == xn ) return Qt::Vertical; const int step = ( to - from ) / 10; const bool isIncreasing = xn > x0; double x1 = x0; for ( int i = from + step; i < to; i += step ) { const double x2 = series->sample( i ).x(); if ( x2 != x1 ) { if ( ( x2 > x1 ) != isIncreasing ) return Qt::Vertical; } x1 = x2; } return Qt::Horizontal; } namespace { template< class Polygon, class Point > class QwtPolygonQuadrupelX { public: inline void start( int x, int y ) { x0 = x; y1 = yMin = yMax = y2 = y; } inline bool append( int x, int y ) { if ( x0 != x ) return false; if ( y < yMin ) yMin = y; else if ( y > yMax ) yMax = y; y2 = y; return true; } inline void flush( Polygon& polyline ) { appendTo( y1, polyline ); if ( y2 > y1 ) qSwap( yMin, yMax ); if ( yMax != y1 ) appendTo( yMax, polyline ); if ( yMin != yMax ) appendTo( yMin, polyline ); if ( y2 != yMin ) appendTo( y2, polyline ); } private: inline void appendTo( int y, Polygon& polyline ) { polyline += Point( x0, y ); } private: int x0, y1, yMin, yMax, y2; }; template< class Polygon, class Point > class QwtPolygonQuadrupelY { public: inline void start( int x, int y ) { y0 = y; x1 = xMin = xMax = x2 = x; } inline bool append( int x, int y ) { if ( y0 != y ) return false; if ( x < xMin ) xMin = x; else if ( x > xMax ) xMax = x; x2 = x; return true; } inline void flush( Polygon& polyline ) { appendTo( x1, polyline ); if ( x2 > x1 ) qSwap( xMin, xMax ); if ( xMax != x1 ) appendTo( xMax, polyline ); if ( xMin != xMax ) appendTo( xMin, polyline ); if ( x2 != xMin ) appendTo( x2, polyline ); } private: inline void appendTo( int x, Polygon& polyline ) { polyline += Point( x, y0 ); } int y0, x1, xMin, xMax, x2; }; } template< class Polygon, class Point, class PolygonQuadrupel > static Polygon qwtMapPointsQuad( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) { const QPointF sample0 = series->sample( from ); PolygonQuadrupel q; q.start( qwtRoundValue( xMap.transform( sample0.x() ) ), qwtRoundValue( yMap.transform( sample0.y() ) ) ); Polygon polyline; for ( int i = from; i <= to; i++ ) { const QPointF sample = series->sample( i ); const int x = qwtRoundValue( xMap.transform( sample.x() ) ); const int y = qwtRoundValue( yMap.transform( sample.y() ) ); if ( !q.append( x, y ) ) { q.flush( polyline ); q.start( x, y ); } } q.flush( polyline ); return polyline; } template< class Polygon, class Point, class PolygonQuadrupel > static Polygon qwtMapPointsQuad( const Polygon& polyline ) { const int numPoints = polyline.size(); if ( numPoints < 3 ) return polyline; const Point* points = polyline.constData(); Polygon polylineXY; PolygonQuadrupel q; q.start( points[0].x(), points[0].y() ); for ( int i = 0; i < numPoints; i++ ) { const int x = points[i].x(); const int y = points[i].y(); if ( !q.append( x, y ) ) { q.flush( polylineXY ); q.start( x, y ); } } q.flush( polylineXY ); return polylineXY; } template< class Polygon, class Point > static Polygon qwtMapPointsQuad( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) { Polygon polyline; if ( from > to ) return polyline; /* probing some values, to decide if it is better to start with x or y coordinates */ const Qt::Orientation orientation = qwtProbeOrientation( series, from, to ); if ( orientation == Qt::Horizontal ) { polyline = qwtMapPointsQuad< Polygon, Point, QwtPolygonQuadrupelY< Polygon, Point > >( xMap, yMap, series, from, to ); polyline = qwtMapPointsQuad< Polygon, Point, QwtPolygonQuadrupelX< Polygon, Point > >( polyline ); } else { polyline = qwtMapPointsQuad< Polygon, Point, QwtPolygonQuadrupelX< Polygon, Point > >( xMap, yMap, series, from, to ); polyline = qwtMapPointsQuad< Polygon, Point, QwtPolygonQuadrupelY< Polygon, Point > >( polyline ); } return polyline; } // Helper class to work around the 5 parameters // limitation of QtConcurrent::run() class QwtDotsCommand { public: const QwtSeriesData< QPointF >* series; int from; int to; QRgb rgb; }; static void qwtRenderDots( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtDotsCommand& command, const QPoint& pos, QImage* image ) { const QRgb rgb = command.rgb; QRgb* bits = reinterpret_cast< QRgb* >( image->bits() ); const int w = image->width(); const int h = image->height(); const int x0 = pos.x(); const int y0 = pos.y(); for ( int i = command.from; i <= command.to; i++ ) { const QPointF sample = command.series->sample( i ); const int x = static_cast< int >( xMap.transform( sample.x() ) + 0.5 ) - x0; const int y = static_cast< int >( yMap.transform( sample.y() ) + 0.5 ) - y0; if ( x >= 0 && x < w && y >= 0 && y < h ) bits[ y * w + x ] = rgb; } } // some functors, so that the compile can inline struct QwtRoundI { inline int operator()( double value ) const { return qwtRoundValue( value ); } }; struct QwtRoundF { inline double operator()( double value ) const { return qwtRoundValueF( value ); } }; struct QwtNoRoundF { inline double operator()( double value ) const { return value; } }; // mapping points without any filtering - beside checking // the bounding rectangle template< class Polygon, class Point, class Round > static inline Polygon qwtToPoints( const QRectF& boundingRect, const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to, Round round ) { Polygon polyline( to - from + 1 ); Point* points = polyline.data(); int numPoints = 0; if ( boundingRect.isValid() ) { // iterating over all values // filtering out all points outside of // the bounding rectangle for ( int i = from; i <= to; i++ ) { const QPointF sample = series->sample( i ); const double x = xMap.transform( sample.x() ); const double y = yMap.transform( sample.y() ); if ( boundingRect.contains( x, y ) ) { points[ numPoints ].rx() = round( x ); points[ numPoints ].ry() = round( y ); numPoints++; } } polyline.resize( numPoints ); } else { // simply iterating over all values // without any filtering for ( int i = from; i <= to; i++ ) { const QPointF sample = series->sample( i ); const double x = xMap.transform( sample.x() ); const double y = yMap.transform( sample.y() ); points[ numPoints ].rx() = round( x ); points[ numPoints ].ry() = round( y ); numPoints++; } } return polyline; } static inline QPolygon qwtToPointsI( const QRectF& boundingRect, const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) { return qwtToPoints< QPolygon, QPoint >( boundingRect, xMap, yMap, series, from, to, QwtRoundI() ); } template< class Round > static inline QPolygonF qwtToPointsF( const QRectF& boundingRect, const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to, Round round ) { return qwtToPoints< QPolygonF, QPointF >( boundingRect, xMap, yMap, series, from, to, round ); } // Mapping points with filtering out consecutive // points mapped to the same position template< class Polygon, class Point, class Round > static inline Polygon qwtToPolylineFiltered( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to, Round round ) { // in curves with many points consecutive points // are often mapped to the same position. As this might // result in empty lines ( or symbols hidden by others ) // we try to filter them out Polygon polyline( to - from + 1 ); Point* points = polyline.data(); const QPointF sample0 = series->sample( from ); points[0].rx() = round( xMap.transform( sample0.x() ) ); points[0].ry() = round( yMap.transform( sample0.y() ) ); int pos = 0; for ( int i = from + 1; i <= to; i++ ) { const QPointF sample = series->sample( i ); const Point p( round( xMap.transform( sample.x() ) ), round( yMap.transform( sample.y() ) ) ); if ( points[pos] != p ) points[++pos] = p; } polyline.resize( pos + 1 ); return polyline; } static inline QPolygon qwtToPolylineFilteredI( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) { return qwtToPolylineFiltered< QPolygon, QPoint >( xMap, yMap, series, from, to, QwtRoundI() ); } template< class Round > static inline QPolygonF qwtToPolylineFilteredF( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to, Round round ) { return qwtToPolylineFiltered< QPolygonF, QPointF >( xMap, yMap, series, from, to, round ); } template< class Polygon, class Point > static inline Polygon qwtToPointsFiltered( const QRectF& boundingRect, const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) { // F.e. in scatter plots ( no connecting lines ) we // can sort out all duplicates ( not only consecutive points ) Polygon polygon( to - from + 1 ); Point* points = polygon.data(); QwtPixelMatrix pixelMatrix( boundingRect.toAlignedRect() ); int numPoints = 0; for ( int i = from; i <= to; i++ ) { const QPointF sample = series->sample( i ); const int x = qwtRoundValue( xMap.transform( sample.x() ) ); const int y = qwtRoundValue( yMap.transform( sample.y() ) ); if ( pixelMatrix.testAndSetPixel( x, y, true ) == false ) { points[ numPoints ].rx() = x; points[ numPoints ].ry() = y; numPoints++; } } polygon.resize( numPoints ); return polygon; } static inline QPolygon qwtToPointsFilteredI( const QRectF& boundingRect, const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) { return qwtToPointsFiltered< QPolygon, QPoint >( boundingRect, xMap, yMap, series, from, to ); } static inline QPolygonF qwtToPointsFilteredF( const QRectF& boundingRect, const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) { return qwtToPointsFiltered< QPolygonF, QPointF >( boundingRect, xMap, yMap, series, from, to ); } class QwtPointMapper::PrivateData { public: PrivateData() : boundingRect( qwtInvalidRect ) { } QRectF boundingRect; QwtPointMapper::TransformationFlags flags; }; //! Constructor QwtPointMapper::QwtPointMapper() { m_data = new PrivateData(); } //! Destructor QwtPointMapper::~QwtPointMapper() { delete m_data; } /*! Set the flags affecting the transformation process \param flags Flags \sa flags(), setFlag() */ void QwtPointMapper::setFlags( TransformationFlags flags ) { m_data->flags = flags; } /*! \return Flags affecting the transformation process \sa setFlags(), setFlag() */ QwtPointMapper::TransformationFlags QwtPointMapper::flags() const { return m_data->flags; } /*! Modify a flag affecting the transformation process \param flag Flag type \param on Value \sa flag(), setFlags() */ void QwtPointMapper::setFlag( TransformationFlag flag, bool on ) { if ( on ) m_data->flags |= flag; else m_data->flags &= ~flag; } /*! \return True, when the flag is set \param flag Flag type \sa setFlag(), setFlags() */ bool QwtPointMapper::testFlag( TransformationFlag flag ) const { return m_data->flags & flag; } /*! Set a bounding rectangle for the point mapping algorithm A valid bounding rectangle can be used for optimizations \param rect Bounding rectangle \sa boundingRect() */ void QwtPointMapper::setBoundingRect( const QRectF& rect ) { m_data->boundingRect = rect; } /*! \return Bounding rectangle \sa setBoundingRect() */ QRectF QwtPointMapper::boundingRect() const { return m_data->boundingRect; } /*! \brief Translate a series of points into a QPolygonF When the WeedOutPoints flag is enabled consecutive points, that are mapped to the same position will be one point. When RoundPoints is set all points are rounded to integers but returned as PolygonF - what only makes sense when the further processing of the values need a QPolygonF. When RoundPoints & WeedOutIntermediatePoints is enabled an even more aggressive weeding algorithm is enabled. \param xMap x map \param yMap y map \param series Series of points to be mapped \param from Index of the first point to be painted \param to Index of the last point to be painted \return Translated polygon */ QPolygonF QwtPointMapper::toPolygonF( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) const { QPolygonF polyline; if ( m_data->flags & RoundPoints ) { if ( m_data->flags & WeedOutIntermediatePoints ) { polyline = qwtMapPointsQuad< QPolygonF, QPointF >( xMap, yMap, series, from, to ); } else if ( m_data->flags & WeedOutPoints ) { polyline = qwtToPolylineFilteredF( xMap, yMap, series, from, to, QwtRoundF() ); } else { polyline = qwtToPointsF( qwtInvalidRect, xMap, yMap, series, from, to, QwtRoundF() ); } } else { if ( m_data->flags & WeedOutPoints ) { polyline = qwtToPolylineFilteredF( xMap, yMap, series, from, to, QwtNoRoundF() ); } else { polyline = qwtToPointsF( qwtInvalidRect, xMap, yMap, series, from, to, QwtNoRoundF() ); } } return polyline; } /*! \brief Translate a series of points into a QPolygon When the WeedOutPoints flag is enabled consecutive points, that are mapped to the same position will be one point. \param xMap x map \param yMap y map \param series Series of points to be mapped \param from Index of the first point to be painted \param to Index of the last point to be painted \return Translated polygon */ QPolygon QwtPointMapper::toPolygon( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) const { QPolygon polyline; if ( m_data->flags & WeedOutIntermediatePoints ) { // TODO WeedOutIntermediatePointsY ... polyline = qwtMapPointsQuad< QPolygon, QPoint >( xMap, yMap, series, from, to ); } else if ( m_data->flags & WeedOutPoints ) { polyline = qwtToPolylineFilteredI( xMap, yMap, series, from, to ); } else { polyline = qwtToPointsI( qwtInvalidRect, xMap, yMap, series, from, to ); } return polyline; } /*! \brief Translate a series into a QPolygonF - WeedOutPoints & RoundPoints & boundingRect().isValid() All points that are mapped to the same position will be one point. Points outside of the bounding rectangle are ignored. - WeedOutPoints & RoundPoints & !boundingRect().isValid() All consecutive points that are mapped to the same position will one point - WeedOutPoints & !RoundPoints All consecutive points that are mapped to the same position will one point - !WeedOutPoints & boundingRect().isValid() Points outside of the bounding rectangle are ignored. When RoundPoints is set all points are rounded to integers but returned as PolygonF - what only makes sense when the further processing of the values need a QPolygonF. \param xMap x map \param yMap y map \param series Series of points to be mapped \param from Index of the first point to be painted \param to Index of the last point to be painted \return Translated polygon */ QPolygonF QwtPointMapper::toPointsF( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) const { QPolygonF points; if ( m_data->flags & WeedOutPoints ) { if ( m_data->flags & RoundPoints ) { if ( m_data->boundingRect.isValid() ) { points = qwtToPointsFilteredF( m_data->boundingRect, xMap, yMap, series, from, to ); } else { // without a bounding rectangle all we can // do is to filter out duplicates of // consecutive points points = qwtToPolylineFilteredF( xMap, yMap, series, from, to, QwtRoundF() ); } } else { // when rounding is not allowed we can't use // qwtToPointsFilteredF points = qwtToPolylineFilteredF( xMap, yMap, series, from, to, QwtNoRoundF() ); } } else { if ( m_data->flags & RoundPoints ) { points = qwtToPointsF( m_data->boundingRect, xMap, yMap, series, from, to, QwtRoundF() ); } else { points = qwtToPointsF( m_data->boundingRect, xMap, yMap, series, from, to, QwtNoRoundF() ); } } return points; } /*! \brief Translate a series of points into a QPolygon - WeedOutPoints & boundingRect().isValid() All points that are mapped to the same position will be one point. Points outside of the bounding rectangle are ignored. - WeedOutPoints & !boundingRect().isValid() All consecutive points that are mapped to the same position will one point - !WeedOutPoints & boundingRect().isValid() Points outside of the bounding rectangle are ignored. \param xMap x map \param yMap y map \param series Series of points to be mapped \param from Index of the first point to be painted \param to Index of the last point to be painted \return Translated polygon */ QPolygon QwtPointMapper::toPoints( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to ) const { QPolygon points; if ( m_data->flags & WeedOutPoints ) { if ( m_data->boundingRect.isValid() ) { points = qwtToPointsFilteredI( m_data->boundingRect, xMap, yMap, series, from, to ); } else { // when we don't have the bounding rectangle all // we can do is to filter out consecutive duplicates points = qwtToPolylineFilteredI( xMap, yMap, series, from, to ); } } else { points = qwtToPointsI( m_data->boundingRect, xMap, yMap, series, from, to ); } return points; } /*! \brief Translate a series into a QImage \param xMap x map \param yMap y map \param series Series of points to be mapped \param from Index of the first point to be painted \param to Index of the last point to be painted \param pen Pen used for drawing a point of the image, where a point is mapped to \param antialiased True, when the dots should be displayed antialiased \param numThreads Number of threads to be used for rendering. If numThreads is set to 0, the system specific ideal thread count is used. \return Image displaying the series */ QImage QwtPointMapper::toImage( const QwtScaleMap& xMap, const QwtScaleMap& yMap, const QwtSeriesData< QPointF >* series, int from, int to, const QPen& pen, bool antialiased, uint numThreads ) const { Q_UNUSED( antialiased ) #if QWT_USE_THREADS if ( numThreads == 0 ) numThreads = QThread::idealThreadCount(); if ( numThreads <= 0 ) numThreads = 1; #else Q_UNUSED( numThreads ) #endif // a very special optimization for scatter plots // where every sample is mapped to one pixel only. const QRect rect = m_data->boundingRect.toAlignedRect(); QImage image( rect.size(), QImage::Format_ARGB32 ); image.fill( Qt::transparent ); if ( pen.width() <= 1 && pen.color().alpha() == 255 ) { QwtDotsCommand command; command.series = series; command.rgb = pen.color().rgba(); #if QWT_USE_THREADS const int numPoints = ( to - from + 1 ) / numThreads; QList< QFuture< void > > futures; for ( uint i = 0; i < numThreads; i++ ) { const QPoint pos = rect.topLeft(); const int index0 = from + i * numPoints; if ( i == numThreads - 1 ) { command.from = index0; command.to = to; qwtRenderDots( xMap, yMap, command, pos, &image ); } else { command.from = index0; command.to = index0 + numPoints - 1; futures += QtConcurrent::run( &qwtRenderDots, xMap, yMap, command, pos, &image ); } } for ( int i = 0; i < futures.size(); i++ ) futures[i].waitForFinished(); #else command.from = from; command.to = to; qwtRenderDots( xMap, yMap, command, rect.topLeft(), &image ); #endif } else { // fallback implementation: to be replaced later by // setting the pixels of the image like above, TODO ... QPainter painter( &image ); painter.setPen( pen ); painter.setRenderHint( QPainter::Antialiasing, antialiased ); const int chunkSize = 1000; for ( int i = from; i <= to; i += chunkSize ) { const int indexTo = qMin( i + chunkSize - 1, to ); const QPolygon points = toPoints( xMap, yMap, series, i, indexTo ); painter.drawPoints( points ); } } return image; }
// Copyright (c) 2018-2021, The DeroGold Developers // Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // Copyright (c) 2018-2019, The TurtleCoin Developers // // Please see the included LICENSE file for more information. #include "ErrorMessage.h" #include <cerrno> #include <cstring> namespace System { std::string lastErrorMessage() { return errorMessage(errno); } std::string errorMessage(int err) { return "result=" + std::to_string(err) + ", " + std::strerror(err); } } // namespace System
#include "httprpc.h" #include "base58.h" #include "chainparams.h" #include "httpserver.h" #include "rpc/protocol.h" #include "rpc/server.h" #include "random.h" #include "sync.h" #include "util.h" #include "utilstrencodings.h" #include "ui_interface.h" #include <boost/algorithm/string.hpp> // boost::trim /** Simple one-shot callback timer to be used by the RPC mechanism to e.g. * re-lock the wellet. */ class HTTPRPCTimer : public RPCTimerBase { public: HTTPRPCTimer(struct event_base* eventBase, boost::function<void(void)>& func, int64_t millis) : ev(eventBase, false, func) { struct timeval tv; tv.tv_sec = millis/1000; tv.tv_usec = (millis%1000)*1000; ev.trigger(&tv); } private: HTTPEvent ev; }; class HTTPRPCTimerInterface : public RPCTimerInterface { public: HTTPRPCTimerInterface(struct event_base* base) : base(base) { } const char* Name() { return "HTTP"; } RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis) { return new HTTPRPCTimer(base, func, millis); } private: struct event_base* base; }; /* Pre-base64-encoded authentication token */ static std::string strRPCUserColonPass; /* Stored RPC timer interface (for unregistration) */ static HTTPRPCTimerInterface* httpRPCTimerInterface = 0; static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; std::string strReply = JSONRPCReply(NullUniValue, objError, id); req->WriteHeader("Content-Type", "application/json"); req->WriteReply(nStatus, strReply); } static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut) { if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called return false; if (strAuth.substr(0, 6) != "Basic ") return false; std::string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); std::string strUserPass = DecodeBase64(strUserPass64); if (strUserPass.find(":") != std::string::npos) strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(":")); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &) { // JSONRPC handles only POST if (req->GetRequestMethod() != HTTPRequest::POST) { req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests"); return false; } // Check authorization std::pair<bool, std::string> authHeader = req->GetHeader("authorization"); if (!authHeader.first) { req->WriteReply(HTTP_UNAUTHORIZED); return false; } JSONRPCRequest jreq; if (!RPCAuthorized(authHeader.second, jreq.authUser)) { LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", req->GetPeer().ToString()); /* Deter brute-forcing If this results in a DoS the user really shouldn't have their RPC port exposed. */ MilliSleep(250); req->WriteReply(HTTP_UNAUTHORIZED); return false; } try { // Parse request UniValue valRequest; if (!valRequest.read(req->ReadBody())) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); // Set the URI jreq.URI = req->GetURI(); std::string strReply; // singleton request if (valRequest.isObject()) { jreq.parse(valRequest); UniValue result = tableRPC.execute(jreq); // Send reply strReply = JSONRPCReply(result, NullUniValue, jreq.id); // array of requests } else if (valRequest.isArray()) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); req->WriteHeader("Content-Type", "application/json"); req->WriteReply(HTTP_OK, strReply); } catch (const UniValue& objError) { JSONErrorReply(req, objError, jreq.id); return false; } catch (const std::exception& e) { JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); return false; } return true; } static bool InitRPCAuthentication() { if (mapArgs["-rpcpassword"] == "") { LogPrintf("Error: No rpcpassword set"); uiInterface.ThreadSafeMessageBox(_("Error: No rpcpassword set"), "", CClientUIInterface::MSG_ERROR); return false; } else { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; } return true; } bool StartHTTPRPC() { LogPrint(Log::RPC, "Starting HTTP RPC server\n"); if (!InitRPCAuthentication()) return false; RegisterHTTPHandler("/", true, HTTPReq_JSONRPC); assert(EventBase()); httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase()); RPCSetTimerInterface(httpRPCTimerInterface); return true; } void InterruptHTTPRPC() { LogPrint(Log::RPC, "Interrupting HTTP RPC server\n"); } void StopHTTPRPC() { LogPrint(Log::RPC, "Stopping HTTP RPC server\n"); UnregisterHTTPHandler("/", true); if (httpRPCTimerInterface) { RPCUnsetTimerInterface(httpRPCTimerInterface); delete httpRPCTimerInterface; httpRPCTimerInterface = 0; } }
#include <efsw/WatcherWin32.hpp> #include <efsw/String.hpp> #if EFSW_PLATFORM == EFSW_PLATFORM_WIN32 namespace efsw { /// Unpacks events and passes them to a user defined callback. void CALLBACK WatchCallback(DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped) { if (dwNumberOfBytesTransfered == 0 || NULL == lpOverlapped) { return; } char szFile[MAX_PATH]; PFILE_NOTIFY_INFORMATION pNotify; WatcherStructWin32 * tWatch = (WatcherStructWin32*) lpOverlapped; WatcherWin32 * pWatch = tWatch->Watch; size_t offset = 0; if (pWatch) { do { bool skip = false; pNotify = (PFILE_NOTIFY_INFORMATION)&pWatch->Buffer[offset]; if (!pNotify) return; offset += pNotify->NextEntryOffset; int count = WideCharToMultiByte(CP_UTF8, 0, pNotify->FileName, pNotify->FileNameLength / sizeof(WCHAR), szFile, MAX_PATH - 1, NULL, NULL); szFile[count] = TEXT('\0'); std::string nfile(szFile); if (FILE_ACTION_MODIFIED == pNotify->Action) { FileInfo fifile(std::string(pWatch->DirName) + nfile); if (pWatch->LastModifiedEvent.file.ModificationTime == fifile.ModificationTime && pWatch->LastModifiedEvent.file.Size == fifile.Size && pWatch->LastModifiedEvent.fileName == nfile) { skip = true; } pWatch->LastModifiedEvent.fileName = nfile; pWatch->LastModifiedEvent.file = fifile; } if (!skip) { pWatch->Watch->handleAction(pWatch, nfile, pNotify->Action); } } while (pNotify->NextEntryOffset != 0); if (!pWatch->StopNow) { RefreshWatch(tWatch); } } } /// Refreshes the directory monitoring. bool RefreshWatch(WatcherStructWin32* pWatch) { return ReadDirectoryChangesW( pWatch->Watch->DirHandle, pWatch->Watch->Buffer, sizeof(pWatch->Watch->Buffer), pWatch->Watch->Recursive, pWatch->Watch->NotifyFilter, NULL, &pWatch->Overlapped, NULL ) != 0; } /// Stops monitoring a directory. void DestroyWatch(WatcherStructWin32* pWatch) { if (pWatch) { WatcherWin32 * tWatch = pWatch->Watch; tWatch->StopNow = true; CancelIoEx(pWatch->Watch->DirHandle, &pWatch->Overlapped); CloseHandle(pWatch->Watch->DirHandle); efSAFE_DELETE_ARRAY( pWatch->Watch->DirName ); efSAFE_DELETE( pWatch->Watch ); } } /// Starts monitoring a directory. WatcherStructWin32* CreateWatch(LPCWSTR szDirectory, bool recursive, DWORD NotifyFilter, HANDLE iocp) { WatcherStructWin32 * tWatch; size_t ptrsize = sizeof(*tWatch); tWatch = static_cast<WatcherStructWin32*>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ptrsize)); WatcherWin32 * pWatch = new WatcherWin32(); tWatch->Watch = pWatch; pWatch->DirHandle = CreateFileW( szDirectory, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL ); if (pWatch->DirHandle != INVALID_HANDLE_VALUE && CreateIoCompletionPort(pWatch->DirHandle, iocp, 0, 1)) { pWatch->NotifyFilter = NotifyFilter; pWatch->Recursive = recursive; if (RefreshWatch(tWatch)) { return tWatch; } } CloseHandle(pWatch->DirHandle); efSAFE_DELETE( pWatch->Watch ); HeapFree(GetProcessHeap(), 0, tWatch); return NULL; } } #endif
/* * * Copyright (c) 1998-2002 * John Maddock * * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ /* * LOCATION: see http://www.boost.org for most recent version. * FILE regex_match_example.cpp * VERSION see <boost/version.hpp> * DESCRIPTION: ftp based regex_match example. */ #include <cstdlib> #include <stdlib.h> #include <boost/regex.hpp> #include <string> #include <iostream> using namespace std; using namespace boost; regex expression("^([0-9]+)(\\-| |$)(.*)$"); // process_ftp: // on success returns the ftp response code, and fills // msg with the ftp response message. int process_ftp(const char* response, std::string* msg) { cmatch what; if(regex_match(response, what, expression)) { // what[0] contains the whole string // what[1] contains the response code // what[2] contains the separator character // what[3] contains the text message. if(msg) msg->assign(what[3].first, what[3].second); return ::atoi(what[1].first); } // failure did not match if(msg) msg->erase(); return -1; } #if defined(BOOST_MSVC) || (defined(__BORLANDC__) && (__BORLANDC__ == 0x550)) // // problem with std::getline under MSVC6sp3 istream& getline(istream& is, std::string& s) { s.erase(); char c = static_cast<char>(is.get()); while(c != '\n') { s.append(1, c); c = static_cast<char>(is.get()); } return is; } #endif int main(int argc, const char*[]) { std::string in, out; do { if(argc == 1) { cout << "enter test string" << endl; getline(cin, in); if(in == "quit") break; } else in = "100 this is an ftp message text"; int result; result = process_ftp(in.c_str(), &out); if(result != -1) { cout << "Match found:" << endl; cout << "Response code: " << result << endl; cout << "Message text: " << out << endl; } else { cout << "Match not found" << endl; } cout << endl; } while(argc == 1); return 0; }
#include <iostream> using namespace std; int main() { int a,b; while(cin>>a>>b) { cout<<a+b<<endl; } return 0; }
#include "method_call.h" #include "borders.h" namespace DesktopWindowMethodCall { MethodCall::MethodCall(const flutter::MethodCall<flutter::EncodableValue> &Cmethod_call, std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> Cresult): method_call(Cmethod_call) { result = std::move(Cresult); } void MethodCall::setFullscreen() { const auto *arguments = std::get_if<flutter::EncodableMap>(method_call.arguments()); bool fullscreen = false; if (arguments) { auto fs_it = arguments->find(flutter::EncodableValue("fullscreen")); if (fs_it != arguments->end()) { fullscreen = std::get<bool>(fs_it->second); } } HWND handle = GetActiveWindow(); WINDOWPLACEMENT placement; GetWindowPlacement(handle, &placement); if (fullscreen) { placement.showCmd = SW_MAXIMIZE; SetWindowPlacement(handle, &placement); } else { placement.showCmd = SW_NORMAL; SetWindowPlacement(handle, &placement); } result->Success(flutter::EncodableValue(true)); } void MethodCall::getFullscreen() { HWND handle = GetActiveWindow(); WINDOWPLACEMENT placement; GetWindowPlacement(handle, &placement); result->Success(flutter::EncodableValue(placement.showCmd == SW_MAXIMIZE)); } void MethodCall::toggleFullscreen() { HWND handle = GetActiveWindow(); WINDOWPLACEMENT placement; GetWindowPlacement(handle, &placement); if (placement.showCmd == SW_MAXIMIZE) { placement.showCmd = SW_NORMAL; SetWindowPlacement(handle, &placement); } else { placement.showCmd = SW_MAXIMIZE; SetWindowPlacement(handle, &placement); } result->Success(flutter::EncodableValue(true)); } void MethodCall::setBorders() { const auto *arguments = std::get_if<flutter::EncodableMap>(method_call.arguments()); bool border = false; if (arguments) { auto fs_it = arguments->find(flutter::EncodableValue("border")); if (fs_it != arguments->end()) { border = std::get<bool>(fs_it->second); } } HWND hWnd = GetActiveWindow(); Borders::setBorders(&hWnd, border, true); result->Success(flutter::EncodableValue(true)); } void MethodCall::hasBorders() { HWND hWnd = GetActiveWindow(); result->Success(flutter::EncodableValue(Borders::hasBorders(&hWnd))); } void MethodCall::toggleBorders() { HWND hWnd = GetActiveWindow(); Borders::toggleBorders(&hWnd, true); result->Success(flutter::EncodableValue(true)); } void MethodCall::stayOnTop() { const auto *arguments = std::get_if<flutter::EncodableMap>(method_call.arguments()); bool stayOnTop = true; if (arguments) { auto fs_it = arguments->find(flutter::EncodableValue("stayOnTop")); if (fs_it != arguments->end()) { stayOnTop = std::get<bool>(fs_it->second); } } HWND hWnd = GetActiveWindow(); RECT rect; GetWindowRect(hWnd, &rect); SetWindowPos(hWnd, stayOnTop? HWND_TOPMOST: HWND_NOTOPMOST, rect.left, rect.top, rect.right-rect.left, rect.bottom -rect.top, SWP_SHOWWINDOW); result->Success(flutter::EncodableValue(true)); } void MethodCall::focus() { HWND hwnd=FindWindowA(NULL, "Deliver"); SetForegroundWindow(hwnd); ShowWindow(hwnd, 3); result->Success(flutter::EncodableValue(true)); } }
// Copyright (C) 2009 Anthony Williams // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #define BOOST_THREAD_USES_MOVE #define BOOST_TEST_MODULE Boost.Threads: thread move return test suite #include <boost/thread/thread_only.hpp> #include <boost/test/unit_test.hpp> void do_nothing(boost::thread::id* my_id) { *my_id=boost::this_thread::get_id(); } boost::thread make_thread_move_return(boost::thread::id* the_id) { boost::thread t(do_nothing,the_id); return boost::move(t); } BOOST_AUTO_TEST_CASE(test_move_from_function_move_return) { boost::thread::id the_id; boost::thread x=make_thread_move_return(&the_id); boost::thread::id x_id=x.get_id(); x.join(); BOOST_CHECK_EQUAL(the_id,x_id); }
#include <iostream> #include <windows.h> #include <string.h> #include "./src/queue.hpp" #define MAXTAM 50 typedef struct Student { int RA; char name[30]; } Student; Queue<Student> *queue = createQ<Student>(MAXTAM); void register_student(); void serve_student(); void display_queue(); void menu(); using namespace std; void printStudent(Student s) { cout << "\nNome: " << s.name << "\nRA: " << s.RA << endl; } int main() { UINT CPAGE_UTF8 = 65001; UINT CPAGE_DEFAULT = GetConsoleOutputCP(); SetConsoleOutputCP(CPAGE_UTF8); menu(); return 0; } void register_student() { Student s; char choose; if (!isFull(queue)) { do { cout << "██████████████████████████████████████████████\n"; cout << "██ INCLUSÃO DE ALUNO ██\n"; cout << "██████████████████████████████████████████████\n\n"; cin.ignore(); cout << "Nome do aluno: "; gets(s.name); cout << "Número do RA: "; cin >> s.RA; enqueue(queue, s); cout << "Aluno incluso na fila com sucesso!\n\n"; cout << "\nDeseja cadastrar outro aluno?[s/n] "; cin >> choose; } while (choose == 's' || choose == 'S'); } else { cout << "A fila já está cheia, impossível adicionar mais alunos."; } cout << "\nVoltando ao menu pricipal, aguarde"; for (int i = 0; i < 7; i++) { Sleep(300); cout << ". "; } system("cls"); } void serve_student() { Student s; char choose; if (!isEmpty(queue)) { do { cout << "██████████████████████████████████████████████\n"; cout << "██ ATENDER ALUNO ██\n"; cout << "██████████████████████████████████████████████\n\n"; dequeue(queue, &s); cout << "Aluno atendido com sucesso!\n\n"; cout << "\nDeseja atender outro aluno?[s/n] "; cin >> choose; if ((choose == 's' || choose == 'S') && isEmpty(queue)) { cout << "Desculpe, mas a fila está vazia."; break; } } while (choose == 's' || choose == 'S'); } else { cout << "A fila está vazia, impossível atender mais alunos."; } cout << "\nVoltando ao menu principal, aguarde"; for (int i = 0; i < 7; i++) { Sleep(300); cout << ". "; } system("cls"); } void display_queue() { printQueue(queue, printStudent); } void menu() { int option; do { system("cls"); cout << " \n ████████████████████████████████████████████████████████████\n"; cout << " FILA DE ESTUDANTES "; cout << " \n ██ ██"; cout << " \n ████████████████████████████████████████████████████████████\n"; cout << " \n ██ 1 - Incluir um novo aluno ██"; cout << " \n ██ 2 - Atender aluno ██"; cout << " \n ██ 3 - Exibir fila ██"; cout << " \n ██ 4 - Sair ██"; cout << " \n ████████████████████████████████████████████████████████████\n"; while ((cout << "\n Digite o numero referente a sua opçao: ") && !(cin >> option)) { cout << " \n Digite uma opção válida."; cin.clear(); cin.ignore(); Sleep(1000); system("cls"); } switch (option) { case 1: register_student(); break; case 2: serve_student(); break; case 3: display_queue(); break; default: break; } system("pause"); } while (option != 4); }
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # include <qsboost/preprocessor/slot/detail/shared.hpp> # # undef QSBOOST_PP_SLOT_1 # # undef QSBOOST_PP_SLOT_1_DIGIT_1 # undef QSBOOST_PP_SLOT_1_DIGIT_2 # undef QSBOOST_PP_SLOT_1_DIGIT_3 # undef QSBOOST_PP_SLOT_1_DIGIT_4 # undef QSBOOST_PP_SLOT_1_DIGIT_5 # undef QSBOOST_PP_SLOT_1_DIGIT_6 # undef QSBOOST_PP_SLOT_1_DIGIT_7 # undef QSBOOST_PP_SLOT_1_DIGIT_8 # undef QSBOOST_PP_SLOT_1_DIGIT_9 # undef QSBOOST_PP_SLOT_1_DIGIT_10 # # if QSBOOST_PP_SLOT_TEMP_10 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_10 0 # elif QSBOOST_PP_SLOT_TEMP_10 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_10 1 # elif QSBOOST_PP_SLOT_TEMP_10 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_10 2 # elif QSBOOST_PP_SLOT_TEMP_10 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_10 3 # elif QSBOOST_PP_SLOT_TEMP_10 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_10 4 # elif QSBOOST_PP_SLOT_TEMP_10 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_10 5 # elif QSBOOST_PP_SLOT_TEMP_10 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_10 6 # elif QSBOOST_PP_SLOT_TEMP_10 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_10 7 # elif QSBOOST_PP_SLOT_TEMP_10 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_10 8 # elif QSBOOST_PP_SLOT_TEMP_10 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_10 9 # endif # # if QSBOOST_PP_SLOT_TEMP_9 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_9 0 # elif QSBOOST_PP_SLOT_TEMP_9 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_9 1 # elif QSBOOST_PP_SLOT_TEMP_9 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_9 2 # elif QSBOOST_PP_SLOT_TEMP_9 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_9 3 # elif QSBOOST_PP_SLOT_TEMP_9 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_9 4 # elif QSBOOST_PP_SLOT_TEMP_9 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_9 5 # elif QSBOOST_PP_SLOT_TEMP_9 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_9 6 # elif QSBOOST_PP_SLOT_TEMP_9 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_9 7 # elif QSBOOST_PP_SLOT_TEMP_9 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_9 8 # elif QSBOOST_PP_SLOT_TEMP_9 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_9 9 # endif # # if QSBOOST_PP_SLOT_TEMP_8 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_8 0 # elif QSBOOST_PP_SLOT_TEMP_8 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_8 1 # elif QSBOOST_PP_SLOT_TEMP_8 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_8 2 # elif QSBOOST_PP_SLOT_TEMP_8 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_8 3 # elif QSBOOST_PP_SLOT_TEMP_8 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_8 4 # elif QSBOOST_PP_SLOT_TEMP_8 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_8 5 # elif QSBOOST_PP_SLOT_TEMP_8 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_8 6 # elif QSBOOST_PP_SLOT_TEMP_8 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_8 7 # elif QSBOOST_PP_SLOT_TEMP_8 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_8 8 # elif QSBOOST_PP_SLOT_TEMP_8 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_8 9 # endif # # if QSBOOST_PP_SLOT_TEMP_7 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_7 0 # elif QSBOOST_PP_SLOT_TEMP_7 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_7 1 # elif QSBOOST_PP_SLOT_TEMP_7 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_7 2 # elif QSBOOST_PP_SLOT_TEMP_7 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_7 3 # elif QSBOOST_PP_SLOT_TEMP_7 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_7 4 # elif QSBOOST_PP_SLOT_TEMP_7 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_7 5 # elif QSBOOST_PP_SLOT_TEMP_7 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_7 6 # elif QSBOOST_PP_SLOT_TEMP_7 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_7 7 # elif QSBOOST_PP_SLOT_TEMP_7 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_7 8 # elif QSBOOST_PP_SLOT_TEMP_7 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_7 9 # endif # # if QSBOOST_PP_SLOT_TEMP_6 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_6 0 # elif QSBOOST_PP_SLOT_TEMP_6 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_6 1 # elif QSBOOST_PP_SLOT_TEMP_6 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_6 2 # elif QSBOOST_PP_SLOT_TEMP_6 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_6 3 # elif QSBOOST_PP_SLOT_TEMP_6 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_6 4 # elif QSBOOST_PP_SLOT_TEMP_6 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_6 5 # elif QSBOOST_PP_SLOT_TEMP_6 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_6 6 # elif QSBOOST_PP_SLOT_TEMP_6 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_6 7 # elif QSBOOST_PP_SLOT_TEMP_6 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_6 8 # elif QSBOOST_PP_SLOT_TEMP_6 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_6 9 # endif # # if QSBOOST_PP_SLOT_TEMP_5 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_5 0 # elif QSBOOST_PP_SLOT_TEMP_5 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_5 1 # elif QSBOOST_PP_SLOT_TEMP_5 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_5 2 # elif QSBOOST_PP_SLOT_TEMP_5 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_5 3 # elif QSBOOST_PP_SLOT_TEMP_5 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_5 4 # elif QSBOOST_PP_SLOT_TEMP_5 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_5 5 # elif QSBOOST_PP_SLOT_TEMP_5 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_5 6 # elif QSBOOST_PP_SLOT_TEMP_5 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_5 7 # elif QSBOOST_PP_SLOT_TEMP_5 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_5 8 # elif QSBOOST_PP_SLOT_TEMP_5 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_5 9 # endif # # if QSBOOST_PP_SLOT_TEMP_4 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_4 0 # elif QSBOOST_PP_SLOT_TEMP_4 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_4 1 # elif QSBOOST_PP_SLOT_TEMP_4 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_4 2 # elif QSBOOST_PP_SLOT_TEMP_4 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_4 3 # elif QSBOOST_PP_SLOT_TEMP_4 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_4 4 # elif QSBOOST_PP_SLOT_TEMP_4 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_4 5 # elif QSBOOST_PP_SLOT_TEMP_4 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_4 6 # elif QSBOOST_PP_SLOT_TEMP_4 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_4 7 # elif QSBOOST_PP_SLOT_TEMP_4 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_4 8 # elif QSBOOST_PP_SLOT_TEMP_4 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_4 9 # endif # # if QSBOOST_PP_SLOT_TEMP_3 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_3 0 # elif QSBOOST_PP_SLOT_TEMP_3 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_3 1 # elif QSBOOST_PP_SLOT_TEMP_3 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_3 2 # elif QSBOOST_PP_SLOT_TEMP_3 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_3 3 # elif QSBOOST_PP_SLOT_TEMP_3 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_3 4 # elif QSBOOST_PP_SLOT_TEMP_3 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_3 5 # elif QSBOOST_PP_SLOT_TEMP_3 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_3 6 # elif QSBOOST_PP_SLOT_TEMP_3 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_3 7 # elif QSBOOST_PP_SLOT_TEMP_3 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_3 8 # elif QSBOOST_PP_SLOT_TEMP_3 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_3 9 # endif # # if QSBOOST_PP_SLOT_TEMP_2 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_2 0 # elif QSBOOST_PP_SLOT_TEMP_2 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_2 1 # elif QSBOOST_PP_SLOT_TEMP_2 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_2 2 # elif QSBOOST_PP_SLOT_TEMP_2 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_2 3 # elif QSBOOST_PP_SLOT_TEMP_2 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_2 4 # elif QSBOOST_PP_SLOT_TEMP_2 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_2 5 # elif QSBOOST_PP_SLOT_TEMP_2 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_2 6 # elif QSBOOST_PP_SLOT_TEMP_2 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_2 7 # elif QSBOOST_PP_SLOT_TEMP_2 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_2 8 # elif QSBOOST_PP_SLOT_TEMP_2 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_2 9 # endif # # if QSBOOST_PP_SLOT_TEMP_1 == 0 # define QSBOOST_PP_SLOT_1_DIGIT_1 0 # elif QSBOOST_PP_SLOT_TEMP_1 == 1 # define QSBOOST_PP_SLOT_1_DIGIT_1 1 # elif QSBOOST_PP_SLOT_TEMP_1 == 2 # define QSBOOST_PP_SLOT_1_DIGIT_1 2 # elif QSBOOST_PP_SLOT_TEMP_1 == 3 # define QSBOOST_PP_SLOT_1_DIGIT_1 3 # elif QSBOOST_PP_SLOT_TEMP_1 == 4 # define QSBOOST_PP_SLOT_1_DIGIT_1 4 # elif QSBOOST_PP_SLOT_TEMP_1 == 5 # define QSBOOST_PP_SLOT_1_DIGIT_1 5 # elif QSBOOST_PP_SLOT_TEMP_1 == 6 # define QSBOOST_PP_SLOT_1_DIGIT_1 6 # elif QSBOOST_PP_SLOT_TEMP_1 == 7 # define QSBOOST_PP_SLOT_1_DIGIT_1 7 # elif QSBOOST_PP_SLOT_TEMP_1 == 8 # define QSBOOST_PP_SLOT_1_DIGIT_1 8 # elif QSBOOST_PP_SLOT_TEMP_1 == 9 # define QSBOOST_PP_SLOT_1_DIGIT_1 9 # endif # # if QSBOOST_PP_SLOT_1_DIGIT_10 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_10(QSBOOST_PP_SLOT_1_DIGIT_10, QSBOOST_PP_SLOT_1_DIGIT_9, QSBOOST_PP_SLOT_1_DIGIT_8, QSBOOST_PP_SLOT_1_DIGIT_7, QSBOOST_PP_SLOT_1_DIGIT_6, QSBOOST_PP_SLOT_1_DIGIT_5, QSBOOST_PP_SLOT_1_DIGIT_4, QSBOOST_PP_SLOT_1_DIGIT_3, QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # elif QSBOOST_PP_SLOT_1_DIGIT_9 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_9(QSBOOST_PP_SLOT_1_DIGIT_9, QSBOOST_PP_SLOT_1_DIGIT_8, QSBOOST_PP_SLOT_1_DIGIT_7, QSBOOST_PP_SLOT_1_DIGIT_6, QSBOOST_PP_SLOT_1_DIGIT_5, QSBOOST_PP_SLOT_1_DIGIT_4, QSBOOST_PP_SLOT_1_DIGIT_3, QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # elif QSBOOST_PP_SLOT_1_DIGIT_8 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_8(QSBOOST_PP_SLOT_1_DIGIT_8, QSBOOST_PP_SLOT_1_DIGIT_7, QSBOOST_PP_SLOT_1_DIGIT_6, QSBOOST_PP_SLOT_1_DIGIT_5, QSBOOST_PP_SLOT_1_DIGIT_4, QSBOOST_PP_SLOT_1_DIGIT_3, QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # elif QSBOOST_PP_SLOT_1_DIGIT_7 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_7(QSBOOST_PP_SLOT_1_DIGIT_7, QSBOOST_PP_SLOT_1_DIGIT_6, QSBOOST_PP_SLOT_1_DIGIT_5, QSBOOST_PP_SLOT_1_DIGIT_4, QSBOOST_PP_SLOT_1_DIGIT_3, QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # elif QSBOOST_PP_SLOT_1_DIGIT_6 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_6(QSBOOST_PP_SLOT_1_DIGIT_6, QSBOOST_PP_SLOT_1_DIGIT_5, QSBOOST_PP_SLOT_1_DIGIT_4, QSBOOST_PP_SLOT_1_DIGIT_3, QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # elif QSBOOST_PP_SLOT_1_DIGIT_5 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_5(QSBOOST_PP_SLOT_1_DIGIT_5, QSBOOST_PP_SLOT_1_DIGIT_4, QSBOOST_PP_SLOT_1_DIGIT_3, QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # elif QSBOOST_PP_SLOT_1_DIGIT_4 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_4(QSBOOST_PP_SLOT_1_DIGIT_4, QSBOOST_PP_SLOT_1_DIGIT_3, QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # elif QSBOOST_PP_SLOT_1_DIGIT_3 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_3(QSBOOST_PP_SLOT_1_DIGIT_3, QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # elif QSBOOST_PP_SLOT_1_DIGIT_2 # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_CC_2(QSBOOST_PP_SLOT_1_DIGIT_2, QSBOOST_PP_SLOT_1_DIGIT_1) # else # define QSBOOST_PP_SLOT_1() QSBOOST_PP_SLOT_1_DIGIT_1 # endif
// sol3 // The MIT License (MIT) // Copyright (c) 2013-2019 Rapptz, ThePhD and 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. #include "sol_defines.hpp" #include <sol/in_place.hpp>
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "dna.h" TEST_CASE("Verify Test Configuration", "verification") { REQUIRE(true == true); } TEST_CASE("Verify get_gc_content of dna") { REQUIRE( get_gc_content("AGCTATAG") == .375); REQUIRE( get_gc_content("CGCTATAG") == .50); }
/* * Vulkan * * Copyright (C) 2015 Valve, Inc. * Copyright (C) 2016 Google, 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. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unordered_map> #include <list> #include "vk_loader_platform.h" #include "vulkan/vk_layer.h" #include "vk_layer_config.h" #include "vk_layer_extension_utils.h" #include "vk_layer_utils.h" #include "vk_enum_validate_helper.h" #include "vk_struct_validate_helper.h" #include "vk_layer_table.h" #include "vk_layer_logging.h" #include "threading.h" #include "vk_dispatch_table_helper.h" #include "vk_struct_string_helper_cpp.h" #include "vk_layer_data.h" #include "thread_check.h" static void initThreading(layer_data *my_data, const VkAllocationCallbacks *pAllocator) { uint32_t report_flags = 0; uint32_t debug_action = 0; FILE *log_output = NULL; const char *strOpt; VkDebugReportCallbackEXT callback; // initialize threading options report_flags = getLayerOptionFlags("google_threading.report_flags", 0); getLayerOptionEnum("google_threading.debug_action", (uint32_t *)&debug_action); if (debug_action & VK_DBG_LAYER_ACTION_LOG_MSG) { strOpt = getLayerOption("google_threading.log_filename"); log_output = getLayerLogOutput(strOpt, "google_threading"); VkDebugReportCallbackCreateInfoEXT dbgCreateInfo; memset(&dbgCreateInfo, 0, sizeof(dbgCreateInfo)); dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; dbgCreateInfo.flags = report_flags; dbgCreateInfo.pfnCallback = log_callback; dbgCreateInfo.pUserData = (void *)log_output; layer_create_msg_callback(my_data->report_data, &dbgCreateInfo, pAllocator, &callback); my_data->logging_callback.push_back(callback); } if (debug_action & VK_DBG_LAYER_ACTION_DEBUG_OUTPUT) { VkDebugReportCallbackCreateInfoEXT dbgCreateInfo; memset(&dbgCreateInfo, 0, sizeof(dbgCreateInfo)); dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; dbgCreateInfo.flags = report_flags; dbgCreateInfo.pfnCallback = win32_debug_output_msg; dbgCreateInfo.pUserData = NULL; layer_create_msg_callback(my_data->report_data, &dbgCreateInfo, pAllocator, &callback); my_data->logging_callback.push_back(callback); } if (!threadingLockInitialized) { loader_platform_thread_create_mutex(&threadingLock); loader_platform_thread_init_cond(&threadingCond); threadingLockInitialized = 1; } } VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateInstance(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkInstance *pInstance) { VkLayerInstanceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO); assert(chain_info->u.pLayerInfo); PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; PFN_vkCreateInstance fpCreateInstance = (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance"); if (fpCreateInstance == NULL) { return VK_ERROR_INITIALIZATION_FAILED; } // Advance the link info for the next element on the chain chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance); if (result != VK_SUCCESS) return result; layer_data *my_data = get_my_data_ptr(get_dispatch_key(*pInstance), layer_data_map); my_data->instance_dispatch_table = new VkLayerInstanceDispatchTable; layer_init_instance_dispatch_table(*pInstance, my_data->instance_dispatch_table, fpGetInstanceProcAddr); my_data->report_data = debug_report_create_instance(my_data->instance_dispatch_table, *pInstance, pCreateInfo->enabledExtensionCount, pCreateInfo->ppEnabledExtensionNames); initThreading(my_data, pAllocator); return result; } VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) { dispatch_key key = get_dispatch_key(instance); layer_data *my_data = get_my_data_ptr(key, layer_data_map); VkLayerInstanceDispatchTable *pTable = my_data->instance_dispatch_table; startWriteObject(my_data, instance); pTable->DestroyInstance(instance, pAllocator); finishWriteObject(my_data, instance); // Clean up logging callback, if any while (my_data->logging_callback.size() > 0) { VkDebugReportCallbackEXT callback = my_data->logging_callback.back(); layer_destroy_msg_callback(my_data->report_data, callback, pAllocator); my_data->logging_callback.pop_back(); } layer_debug_report_destroy_instance(my_data->report_data); delete my_data->instance_dispatch_table; layer_data_map.erase(key); if (layer_data_map.empty()) { // Release mutex when destroying last instance. loader_platform_thread_delete_mutex(&threadingLock); threadingLockInitialized = 0; } } VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) { VkLayerDeviceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO); assert(chain_info->u.pLayerInfo); PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr; PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice"); if (fpCreateDevice == NULL) { return VK_ERROR_INITIALIZATION_FAILED; } // Advance the link info for the next element on the chain chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; VkResult result = fpCreateDevice(gpu, pCreateInfo, pAllocator, pDevice); if (result != VK_SUCCESS) { return result; } layer_data *my_instance_data = get_my_data_ptr(get_dispatch_key(gpu), layer_data_map); layer_data *my_device_data = get_my_data_ptr(get_dispatch_key(*pDevice), layer_data_map); // Setup device dispatch table my_device_data->device_dispatch_table = new VkLayerDispatchTable; layer_init_device_dispatch_table(*pDevice, my_device_data->device_dispatch_table, fpGetDeviceProcAddr); my_device_data->report_data = layer_debug_report_create_device(my_instance_data->report_data, *pDevice); return result; } VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) { dispatch_key key = get_dispatch_key(device); layer_data *dev_data = get_my_data_ptr(key, layer_data_map); startWriteObject(dev_data, device); dev_data->device_dispatch_table->DestroyDevice(device, pAllocator); finishWriteObject(dev_data, device); layer_data_map.erase(key); } static const VkExtensionProperties threading_extensions[] = { {VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_EXT_DEBUG_REPORT_SPEC_VERSION}}; VK_LAYER_EXPORT VkResult VKAPI_CALL vkEnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pCount, VkExtensionProperties *pProperties) { return util_GetExtensionProperties(ARRAY_SIZE(threading_extensions), threading_extensions, pCount, pProperties); } static const VkLayerProperties globalLayerProps[] = {{ "VK_LAYER_GOOGLE_threading", VK_API_VERSION, // specVersion 1, "Google Validation Layer", }}; VK_LAYER_EXPORT VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties(uint32_t *pCount, VkLayerProperties *pProperties) { return util_GetLayerProperties(ARRAY_SIZE(globalLayerProps), globalLayerProps, pCount, pProperties); } static const VkLayerProperties deviceLayerProps[] = {{ "VK_LAYER_GOOGLE_threading", VK_API_VERSION, // specVersion 1, "Google Validation Layer", }}; VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice, const char *pLayerName, uint32_t *pCount, VkExtensionProperties *pProperties) { if (pLayerName == NULL) { dispatch_key key = get_dispatch_key(physicalDevice); layer_data *my_data = get_my_data_ptr(key, layer_data_map); return my_data->instance_dispatch_table->EnumerateDeviceExtensionProperties(physicalDevice, NULL, pCount, pProperties); } else { // Threading layer does not have any device extensions return util_GetExtensionProperties(0, nullptr, pCount, pProperties); } } VK_LAYER_EXPORT VkResult VKAPI_CALL vkEnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice, uint32_t *pCount, VkLayerProperties *pProperties) { return util_GetLayerProperties(ARRAY_SIZE(deviceLayerProps), deviceLayerProps, pCount, pProperties); } static inline PFN_vkVoidFunction layer_intercept_proc(const char *name) { for (int i = 0; i < sizeof(procmap) / sizeof(procmap[0]); i++) { if (!strcmp(name, procmap[i].name)) return procmap[i].pFunc; } return NULL; } static inline PFN_vkVoidFunction layer_intercept_instance_proc(const char *name) { if (!name || name[0] != 'v' || name[1] != 'k') return NULL; name += 2; if (!strcmp(name, "CreateInstance")) return (PFN_vkVoidFunction)vkCreateInstance; if (!strcmp(name, "DestroyInstance")) return (PFN_vkVoidFunction)vkDestroyInstance; if (!strcmp(name, "EnumerateInstanceExtensionProperties")) return (PFN_vkVoidFunction)vkEnumerateInstanceExtensionProperties; if (!strcmp(name, "EnumerateInstanceLayerProperties")) return (PFN_vkVoidFunction)vkEnumerateInstanceLayerProperties; if (!strcmp(name, "EnumerateDeviceExtensionProperties")) return (PFN_vkVoidFunction)vkEnumerateDeviceExtensionProperties; if (!strcmp(name, "EnumerateDeviceLayerProperties")) return (PFN_vkVoidFunction)vkEnumerateDeviceLayerProperties; if (!strcmp(name, "CreateDevice")) return (PFN_vkVoidFunction)vkCreateDevice; if (!strcmp(name, "GetInstanceProcAddr")) return (PFN_vkVoidFunction)vkGetInstanceProcAddr; return NULL; } VK_LAYER_EXPORT PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device, const char *funcName) { PFN_vkVoidFunction addr; layer_data *dev_data; if (device == VK_NULL_HANDLE) { return NULL; } addr = layer_intercept_proc(funcName); if (addr) return addr; dev_data = get_my_data_ptr(get_dispatch_key(device), layer_data_map); VkLayerDispatchTable *pTable = dev_data->device_dispatch_table; if (pTable->GetDeviceProcAddr == NULL) return NULL; return pTable->GetDeviceProcAddr(device, funcName); } VK_LAYER_EXPORT PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *funcName) { PFN_vkVoidFunction addr; layer_data *my_data; addr = layer_intercept_instance_proc(funcName); if (addr) { return addr; } if (instance == VK_NULL_HANDLE) { return NULL; } my_data = get_my_data_ptr(get_dispatch_key(instance), layer_data_map); addr = debug_report_get_instance_proc_addr(my_data->report_data, funcName); if (addr) { return addr; } VkLayerInstanceDispatchTable *pTable = my_data->instance_dispatch_table; if (pTable->GetInstanceProcAddr == NULL) { return NULL; } return pTable->GetInstanceProcAddr(instance, funcName); } VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugReportCallbackEXT *pMsgCallback) { layer_data *my_data = get_my_data_ptr(get_dispatch_key(instance), layer_data_map); startReadObject(my_data, instance); VkResult result = my_data->instance_dispatch_table->CreateDebugReportCallbackEXT(instance, pCreateInfo, pAllocator, pMsgCallback); if (VK_SUCCESS == result) { result = layer_create_msg_callback(my_data->report_data, pCreateInfo, pAllocator, pMsgCallback); } finishReadObject(my_data, instance); return result; } VK_LAYER_EXPORT VKAPI_ATTR void VKAPI_CALL vkDestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks *pAllocator) { layer_data *my_data = get_my_data_ptr(get_dispatch_key(instance), layer_data_map); startReadObject(my_data, instance); startWriteObject(my_data, callback); my_data->instance_dispatch_table->DestroyDebugReportCallbackEXT(instance, callback, pAllocator); layer_destroy_msg_callback(my_data->report_data, callback, pAllocator); finishReadObject(my_data, instance); finishWriteObject(my_data, callback); } VkResult VKAPI_CALL vkAllocateCommandBuffers(VkDevice device, const VkCommandBufferAllocateInfo *pAllocateInfo, VkCommandBuffer *pCommandBuffers) { dispatch_key key = get_dispatch_key(device); layer_data *my_data = get_my_data_ptr(key, layer_data_map); VkLayerDispatchTable *pTable = my_data->device_dispatch_table; VkResult result; startReadObject(my_data, device); startWriteObject(my_data, pAllocateInfo->commandPool); result = pTable->AllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers); finishReadObject(my_data, device); finishWriteObject(my_data, pAllocateInfo->commandPool); // Record mapping from command buffer to command pool if (VK_SUCCESS == result) { for (int index = 0; index < pAllocateInfo->commandBufferCount; index++) { loader_platform_thread_lock_mutex(&threadingLock); command_pool_map[pCommandBuffers[index]] = pAllocateInfo->commandPool; loader_platform_thread_unlock_mutex(&threadingLock); } } return result; } void VKAPI_CALL vkFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers) { dispatch_key key = get_dispatch_key(device); layer_data *my_data = get_my_data_ptr(key, layer_data_map); VkLayerDispatchTable *pTable = my_data->device_dispatch_table; const bool lockCommandPool = false; // pool is already directly locked startReadObject(my_data, device); startWriteObject(my_data, commandPool); for (int index = 0; index < commandBufferCount; index++) { startWriteObject(my_data, pCommandBuffers[index], lockCommandPool); } pTable->FreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers); finishReadObject(my_data, device); finishWriteObject(my_data, commandPool); for (int index = 0; index < commandBufferCount; index++) { finishWriteObject(my_data, pCommandBuffers[index], lockCommandPool); loader_platform_thread_lock_mutex(&threadingLock); command_pool_map.erase(pCommandBuffers[index]); loader_platform_thread_unlock_mutex(&threadingLock); } }
// -*- c++ -*- // // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // // All rights reserved. // // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. // // Copyright 1997, 1998, 1999 University of Notre Dame. // Authors: Andrew Lumsdaine, Jeremy G. Siek, Lie-Quan Lee // // This file is part of the Matrix Template Library // // You should have received a copy of the License Agreement for the // Matrix Template Library along with the software; see the // file LICENSE. If not, contact Office of Research, University of Notre // Dame, Notre Dame, IN 46556. // // Permission to modify the code and to distribute modified code is // granted, provided the text of this NOTICE is retained, a notice that // the code was modified is included with the above COPYRIGHT NOTICE and // with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE // file is distributed with the modified code. // // LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. // By way of example, but not limitation, Licensor MAKES NO // REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY // PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS // OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS // OR OTHER RIGHTS. // //=========================================================================== #include "mtl/utils.h" #include "mtl/matrix.h" #include "matrix_test.h" // matrix_attr.h is generated by make_and_test.pl and defines // NUMTYPE, SHAPE, STORAGE, ORIEN, and TESTNAME // you can create your own for testing purposes #include "matrix_attr.h" template <class Matrix, class Trans> bool trans_test(const Matrix& A, const Trans& T, std::string test_name) { for (typename Matrix::const_iterator i = A.begin(); i != A.end(); ++i) for (typename Matrix::OneD::const_iterator j = (*i).begin(); j != (*i).end(); ++j) if (*j != T(j.column(), j.row())) { std::cerr << "**** FAILED: (trans test) " << test_name.c_str() << " ****" << std::endl; return false; } return true; } template <class Matrix> bool trans_test(const Matrix& A, std::string test_name) { if (trans_test(A, mtl::trans(A), test_name) && trans_test(mtl::trans(A), A, test_name)) { std::cout << test_name.c_str() << " passed trans test" << std::endl; return true; } else return false; } template <class Matrix> void do_test(Matrix& A, std::string test_name) { using namespace mtl; typedef typename mtl::matrix_traits<Matrix>::value_type T; typedef typename mtl::matrix_traits<Matrix>::size_type Int; matrix_fill(A); trans_test(A, test_name); } int main(int argc, char* argv[]) { if (argc < 5) { std::cerr << "matrix_test <M> <N> <SUB> <SUPER>" << std::endl; return -1; } using namespace mtl; using std::string; const int M = atoi(argv[1]); const int N = atoi(argv[2]); const int SUB = atoi(argv[3]); const int SUP = atoi(argv[4]); std::cout << "M: " << M << " N: " << N << " SUB: " << SUB << " SUPER: " << SUP << std::endl; typedef matrix<NUMTYPE, SHAPE, STORAGE, ORIEN>::type Matrix; string test_name = TESTNAME; Matrix* a = 0; create_and_run(M, N, SUB, SUP, test_name, a, Matrix::shape()); return 0; }
#include <QtCore/QEvent> #include <QtCore/QDir> #include <QDebug> #include <QtWidgets/QFileDialog> #include <nodes/DataModelRegistry> #include "ImageTFInfModel.hpp" #include "PixmapData.hpp" ImageTFInfModel:: ImageTFInfModel() { const QString graph_fn = QString("/usr/local/tf_libs/resources/my_mnist_model.meta"); const QString checkpoint_fn = QString("/usr/local/tf_libs/resources/my_mnist_model"); _tftools = new TFTools(graph_fn, checkpoint_fn); } ImageTFInfModel:: ~ImageTFInfModel() { if (_tftools != nullptr ) delete _tftools; } std::shared_ptr<NodeData> ImageTFInfModel:: outData(PortIndex) { return _nodeData; } void ImageTFInfModel:: setInData(std::shared_ptr<NodeData> nodeData, PortIndex) { _nodeData = nodeData; if (_nodeData) { auto d = std::dynamic_pointer_cast<PixmapData>(_nodeData); //int w = _label->width(); //int h = _label->height(); // Danny Implementation if(!d->pixmap().isNull()) { qDebug() << "...convert pixmap to mat for tensorflow inference task"; cv::Mat _frame = PixmapData::QPixmapToCvMat(d->pixmap()); // do tensorflow inference task qDebug() << "...do tensorflow inference task"; _label_result = QString::fromStdString(_tftools->doInference(_frame)); _label->setText(_label_result); } } else { _label->setPixmap(QPixmap()); _label->setText("No image for inferencing"); } Q_EMIT dataUpdated(0); } bool ImageTFInfModel:: eventFilter(QObject *object, QEvent *event) { if (object == _label) { int w = _label->width(); int h = _label->height(); if (event->type() == QEvent::Resize) { auto d = std::dynamic_pointer_cast<PixmapData>(_nodeData); if (d) { _label->setText(_label_result); //_label->setPixmap(d->pixmap().scaled(w, h, Qt::KeepAspectRatio)); } } } return false; }
// This file is licensed under the Elastic License 2.0. Copyright 2021 StarRocks Limited. #include "exec/vectorized/olap_scan_node.h" #include <chrono> #include <limits> #include <thread> #include "column/column_pool.h" #include "column/type_traits.h" #include "common/status.h" #include "exec/pipeline/limit_operator.h" #include "exec/pipeline/pipeline_builder.h" #include "exec/pipeline/scan_operator.h" #include "exec/vectorized/olap_scan_prepare.h" #include "exprs/expr.h" #include "exprs/expr_context.h" #include "exprs/vectorized/in_const_predicate.hpp" #include "exprs/vectorized/runtime_filter_bank.h" #include "gutil/casts.h" #include "gutil/map_util.h" #include "runtime/current_mem_tracker.h" #include "runtime/current_thread.h" #include "runtime/descriptors.h" #include "runtime/exec_env.h" #include "storage/vectorized/chunk_helper.h" #include "util/priority_thread_pool.hpp" namespace starrocks::vectorized { OlapScanNode::OlapScanNode(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs) : ScanNode(pool, tnode, descs), _olap_scan_node(tnode.olap_scan_node), _status(Status::OK()) {} Status OlapScanNode::init(const TPlanNode& tnode, RuntimeState* state) { RETURN_IF_ERROR(ExecNode::init(tnode, state)); DCHECK(!tnode.olap_scan_node.__isset.sort_column) << "sorted result not supported any more"; return Status::OK(); } Status OlapScanNode::prepare(RuntimeState* state) { RETURN_IF_ERROR(ScanNode::prepare(state)); _tablet_counter = ADD_COUNTER(runtime_profile(), "TabletCount ", TUnit::UNIT); _tuple_desc = state->desc_tbl().get_tuple_descriptor(_olap_scan_node.tuple_id); _init_counter(state); if (_tuple_desc == nullptr) { return Status::InternalError("Failed to get tuple descriptor."); } _runtime_profile->add_info_string("Table", _tuple_desc->table_desc()->name()); if (_olap_scan_node.__isset.rollup_name) { _runtime_profile->add_info_string("Rollup", _olap_scan_node.rollup_name); } if (_olap_scan_node.__isset.sql_predicates) { _runtime_profile->add_info_string("Predicates", _olap_scan_node.sql_predicates); } _runtime_state = state; return Status::OK(); } Status OlapScanNode::open(RuntimeState* state) { SCOPED_TIMER(_runtime_profile->total_time_counter()); RETURN_IF_CANCELLED(state); RETURN_IF_ERROR(ExecNode::open(state)); CurrentThread::set_mem_tracker(mem_tracker()); Status status; OlapScanConjunctsManager::eval_const_conjuncts(_conjunct_ctxs, &status); _update_status(status); return Status::OK(); } Status OlapScanNode::get_next(RuntimeState* state, RowBatch* row_batch, bool* eos) { return Status::NotSupported("get_next for row_batch is not supported"); } // Current get_next the chunk is nullptr when eos==true // TODO: return the last chunk with eos=true, reduce one function call? Status OlapScanNode::get_next(RuntimeState* state, ChunkPtr* chunk, bool* eos) { RETURN_IF_ERROR(exec_debug_action(TExecNodePhase::GETNEXT)); SCOPED_TIMER(_runtime_profile->total_time_counter()); bool first_call = !_start; if (!_start && _status.ok()) { Status status = _start_scan(state); _update_status(status); LOG_IF(ERROR, !(status.ok() || status.is_end_of_file())) << "Failed to start scan node: " << status.to_string(); _start = true; if (!status.ok()) { *eos = true; return status.is_end_of_file() ? Status::OK() : status; } } else if (!_start) { _result_chunks.shutdown(); _start = true; } (*chunk).reset(); Status status = _get_status(); if (!status.ok()) { *eos = true; return status.is_end_of_file() ? Status::OK() : status; } { std::unique_lock<std::mutex> l(_mtx); const int32_t num_closed = _closed_scanners.load(std::memory_order_acquire); const int32_t num_pending = _pending_scanners.size(); const int32_t num_running = _num_scanners - num_pending - num_closed; if ((num_pending > 0) && (num_running < kMaxConcurrency)) { // before we submit a new scanner to run, check whether it can fetch // at least _chunks_per_scanner chunks from _chunk_pool. if (_chunk_pool.size() >= (num_running + 1) * _chunks_per_scanner) { TabletScanner* scanner = _pending_scanners.pop(); l.unlock(); (void)_submit_scanner(scanner, true); } } } Chunk* ptr = nullptr; if (_result_chunks.blocking_get(&ptr)) { // If the second argument of `_fill_chunk_pool` is false *AND* the column pool is empty, // the column object in the chunk will be destroyed and its memory will be deallocated // when the last remaining shared_ptr owning it is destroyed, otherwise the column object // will be placed into the column pool. // // If all columns returned to the parent executor node can be returned back into the column // pool before the next calling of `get_next`, the column pool would be nonempty before the // calling of `_fill_chunk_pool`, except for the first time of calling `get_next`. So if this // is the first time of calling `get_next`, pass the second argument of `_fill_chunk_pool` as // true to ensure that the newly allocated column objects will be returned back into the column // pool. _fill_chunk_pool(1, first_call); mem_tracker()->release(ptr->memory_usage()); *chunk = std::shared_ptr<Chunk>(ptr); eval_join_runtime_filters(chunk); _num_rows_returned += (*chunk)->num_rows(); COUNTER_SET(_rows_returned_counter, _num_rows_returned); // reach scan node limit if (reached_limit()) { int64_t num_rows_over = _num_rows_returned - _limit; DCHECK_GE((*chunk)->num_rows(), num_rows_over); (*chunk)->set_num_rows((*chunk)->num_rows() - num_rows_over); COUNTER_SET(_rows_returned_counter, _limit); _update_status(Status::EndOfFile("OlapScanNode has reach limit")); _result_chunks.shutdown(); } *eos = false; DCHECK_CHUNK(*chunk); return Status::OK(); } else { _update_status(Status::EndOfFile("EOF of OlapScanNode")); *eos = true; status = _get_status(); return status.is_end_of_file() ? Status::OK() : status; } } Status OlapScanNode::close(RuntimeState* state) { if (is_closed()) { return Status::OK(); } RETURN_IF_ERROR(exec_debug_action(TExecNodePhase::CLOSE)); _update_status(Status::Cancelled("closed")); _result_chunks.shutdown(); while (_running_threads.load(std::memory_order_acquire) > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } _close_pending_scanners(); // free chunks in _chunk_pool. while (!_chunk_pool.empty()) { Chunk* chunk = _chunk_pool.pop(); mem_tracker()->release(chunk->memory_usage()); delete chunk; } // free chunks in _result_chunks and release memory tracker. Chunk* chunk = nullptr; while (_result_chunks.blocking_get(&chunk)) { mem_tracker()->release(chunk->memory_usage()); delete chunk; } // Reduce the memory usage if the the average string size is greater than 512. release_large_columns<BinaryColumn>(config::vector_chunk_size * 512); return ScanNode::close(state); } OlapScanNode::~OlapScanNode() { DCHECK(is_closed()); } void OlapScanNode::_fill_chunk_pool(int count, bool force_column_pool) { const size_t capacity = config::vector_chunk_size; for (int i = 0; i < count; i++) { Chunk* chk = ChunkHelper::new_chunk_pooled(*_chunk_schema, capacity, force_column_pool); mem_tracker()->consume(chk->memory_usage()); std::lock_guard<std::mutex> l(_mtx); _chunk_pool.push(chk); } } void OlapScanNode::_scanner_thread(TabletScanner* scanner) { CurrentThread::set_query_id(scanner->runtime_state()->query_id()); CurrentThread::set_mem_tracker(mem_tracker()); Status status = scanner->open(_runtime_state); if (!status.ok()) { QUERY_LOG_IF(ERROR, !status.is_end_of_file()) << status; _update_status(status); } scanner->set_keep_priority(false); // Because we use thread pool to scan data from storage. One scanner can't // use this thread too long, this can starve other query's scanner. So, we // need yield this thread when we do enough work. However, OlapStorage read // data in pre-aggregate mode, then we can't use storage returned data to // judge if we need to yield. So we record all raw data read in this round // scan, if this exceed threshold, we yield this thread. bool resubmit = false; Chunk* chunk; int64_t raw_rows_threshold = scanner->raw_rows_read() + config::doris_scanner_row_num; while (status.ok()) { { std::lock_guard<std::mutex> l(_mtx); if (_chunk_pool.empty()) { // NOTE: DO NOT move these operations out of current lock scope. scanner->set_keep_priority(true); _pending_scanners.push(scanner); scanner = nullptr; break; } chunk = _chunk_pool.pop(); } DCHECK_EQ(chunk->num_rows(), 0); status = scanner->get_chunk(_runtime_state, chunk); if (!status.ok()) { QUERY_LOG_IF(ERROR, !status.is_end_of_file()) << status; std::lock_guard<std::mutex> l(_mtx); _chunk_pool.push(chunk); break; } DCHECK_CHUNK(chunk); // _result_chunks will be shutdown if error happened or has reached limit. if (!_result_chunks.put(chunk)) { mem_tracker()->release(chunk->memory_usage()); status = Status::Aborted("_result_chunks has been shutdown"); delete chunk; break; } if (scanner->raw_rows_read() >= raw_rows_threshold) { resubmit = true; break; } } Status global_status = _get_status(); if (global_status.ok()) { if (status.ok() && resubmit) { if (!_submit_scanner(scanner, false)) { std::lock_guard<std::mutex> l(_mtx); _pending_scanners.push(scanner); } } else if (status.ok()) { DCHECK(scanner == nullptr); // _chunk_pool is empty and scanner has been placed into _pending_scanners, // nothing to do here. } else if (status.is_end_of_file()) { scanner->close(_runtime_state); _closed_scanners.fetch_add(1, std::memory_order_release); // pick next scanner to run. std::lock_guard<std::mutex> l(_mtx); scanner = _pending_scanners.empty() ? nullptr : _pending_scanners.pop(); if (scanner != nullptr && !_submit_scanner(scanner, false)) { _pending_scanners.push(scanner); } } else { _update_status(status); scanner->close(_runtime_state); _closed_scanners.fetch_add(1, std::memory_order_release); _close_pending_scanners(); } } else { if (scanner != nullptr) { scanner->close(_runtime_state); _closed_scanners.fetch_add(1, std::memory_order_release); _close_pending_scanners(); } else { _close_pending_scanners(); } } if (_closed_scanners.load(std::memory_order_acquire) == _num_scanners) { _result_chunks.shutdown(); } _running_threads.fetch_sub(1, std::memory_order_release); CurrentThread::set_query_id(TUniqueId()); CurrentThread::set_mem_tracker(nullptr); // DO NOT touch any shared variables since here, as they may have been destructed. } Status OlapScanNode::set_scan_ranges(const std::vector<TScanRangeParams>& scan_ranges) { for (auto& scan_range : scan_ranges) { DCHECK(scan_range.scan_range.__isset.internal_scan_range); _scan_ranges.emplace_back(new TInternalScanRange(scan_range.scan_range.internal_scan_range)); COUNTER_UPDATE(_tablet_counter, 1); } return Status::OK(); } Status OlapScanNode::collect_query_statistics(QueryStatistics* statistics) { RETURN_IF_ERROR(ExecNode::collect_query_statistics(statistics)); QueryStatisticsItemPB stats_item; stats_item.set_scan_bytes(_read_compressed_counter->value()); stats_item.set_scan_rows(_raw_rows_counter->value()); stats_item.set_table_id(_tuple_desc->table_desc()->table_id()); statistics->add_stats_item(stats_item); return Status::OK(); } Status OlapScanNode::_start_scan(RuntimeState* state) { RETURN_IF_CANCELLED(state); OlapScanConjunctsManager& cm = _conjuncts_manager; cm.conjunct_ctxs_ptr = &_conjunct_ctxs; cm.tuple_desc = _tuple_desc; cm.obj_pool = &_obj_pool; cm.key_column_names = &_olap_scan_node.key_column_name; cm.runtime_filters = &_runtime_filter_collector; cm.runtime_state = state; const TQueryOptions& query_options = state->query_options(); int32_t max_scan_key_num; if (query_options.__isset.max_scan_key_num && query_options.max_scan_key_num > 0) { max_scan_key_num = query_options.max_scan_key_num; } else { max_scan_key_num = config::doris_max_scan_key_num; } bool scan_keys_unlimited = (limit() == -1); bool enable_column_expr_predicate = false; if (_olap_scan_node.__isset.enable_column_expr_predicate) { enable_column_expr_predicate = _olap_scan_node.enable_column_expr_predicate; } RETURN_IF_ERROR(cm.parse_conjuncts(scan_keys_unlimited, max_scan_key_num, enable_column_expr_predicate)); RETURN_IF_ERROR(_start_scan_thread(state)); return Status::OK(); } void OlapScanNode::_init_counter(RuntimeState* state) { _scan_timer = ADD_TIMER(_runtime_profile, "ScanTime"); _scan_profile = _runtime_profile->create_child("SCAN", true, false); _create_seg_iter_timer = ADD_TIMER(_scan_profile, "CreateSegmentIter"); _read_compressed_counter = ADD_COUNTER(_scan_profile, "CompressedBytesRead", TUnit::BYTES); _read_uncompressed_counter = ADD_COUNTER(_scan_profile, "UncompressedBytesRead", TUnit::BYTES); _raw_rows_counter = ADD_COUNTER(_scan_profile, "RawRowsRead", TUnit::UNIT); _total_pages_num_counter = ADD_COUNTER(_scan_profile, "TotalPagesNum", TUnit::UNIT); _cached_pages_num_counter = ADD_COUNTER(_scan_profile, "CachedPagesNum", TUnit::UNIT); _pushdown_predicates_counter = ADD_COUNTER(_scan_profile, "PushdownPredicates", TUnit::UNIT); /// SegmentInit _seg_init_timer = ADD_TIMER(_scan_profile, "SegmentInit"); _bi_filter_timer = ADD_CHILD_TIMER(_scan_profile, "BitmapIndexFilter", "SegmentInit"); _bi_filtered_counter = ADD_CHILD_COUNTER(_scan_profile, "BitmapIndexFilterRows", TUnit::UNIT, "SegmentInit"); _bf_filtered_counter = ADD_CHILD_COUNTER(_scan_profile, "BloomFilterFilterRows", TUnit::UNIT, "SegmentInit"); _zm_filtered_counter = ADD_CHILD_COUNTER(_scan_profile, "ZoneMapIndexFilterRows", TUnit::UNIT, "SegmentInit"); _sk_filtered_counter = ADD_CHILD_COUNTER(_scan_profile, "ShortKeyFilterRows", TUnit::UNIT, "SegmentInit"); /// SegmentRead _block_load_timer = ADD_TIMER(_scan_profile, "SegmentRead"); _block_fetch_timer = ADD_CHILD_TIMER(_scan_profile, "BlockFetch", "SegmentRead"); _block_load_counter = ADD_CHILD_COUNTER(_scan_profile, "BlockFetchCount", TUnit::UNIT, "SegmentRead"); _block_seek_timer = ADD_CHILD_TIMER(_scan_profile, "BlockSeek", "SegmentRead"); _block_seek_counter = ADD_CHILD_COUNTER(_scan_profile, "BlockSeekCount", TUnit::UNIT, "SegmentRead"); _pred_filter_timer = ADD_CHILD_TIMER(_scan_profile, "PredFilter", "SegmentRead"); _pred_filter_counter = ADD_CHILD_COUNTER(_scan_profile, "PredFilterRows", TUnit::UNIT, "SegmentRead"); _del_vec_filter_counter = ADD_CHILD_COUNTER(_scan_profile, "DelVecFilterRows", TUnit::UNIT, "SegmentRead"); _chunk_copy_timer = ADD_CHILD_TIMER(_scan_profile, "ChunkCopy", "SegmentRead"); _decompress_timer = ADD_CHILD_TIMER(_scan_profile, "DecompressT", "SegmentRead"); _index_load_timer = ADD_CHILD_TIMER(_scan_profile, "IndexLoad", "SegmentRead"); /// IOTime _io_timer = ADD_TIMER(_scan_profile, "IOTime"); } // The more tasks you submit, the less priority you get. int OlapScanNode::_compute_priority(int32_t num_submitted_tasks) { // int nice = 20; // while (nice > 0 && num_submitted_tasks > (22 - nice) * (20 - nice) * 6) { // --nice; // } // return nice; if (num_submitted_tasks < 5) return 20; if (num_submitted_tasks < 19) return 19; if (num_submitted_tasks < 49) return 18; if (num_submitted_tasks < 91) return 17; if (num_submitted_tasks < 145) return 16; if (num_submitted_tasks < 211) return 15; if (num_submitted_tasks < 289) return 14; if (num_submitted_tasks < 379) return 13; if (num_submitted_tasks < 481) return 12; if (num_submitted_tasks < 595) return 11; if (num_submitted_tasks < 721) return 10; if (num_submitted_tasks < 859) return 9; if (num_submitted_tasks < 1009) return 8; if (num_submitted_tasks < 1171) return 7; if (num_submitted_tasks < 1345) return 6; if (num_submitted_tasks < 1531) return 5; if (num_submitted_tasks < 1729) return 4; if (num_submitted_tasks < 1939) return 3; if (num_submitted_tasks < 2161) return 2; if (num_submitted_tasks < 2395) return 1; return 0; } bool OlapScanNode::_submit_scanner(TabletScanner* scanner, bool blockable) { PriorityThreadPool* thread_pool = _runtime_state->exec_env()->thread_pool(); int delta = !scanner->keep_priority(); int32_t num_submit = _scanner_submit_count.fetch_add(delta, std::memory_order_relaxed); PriorityThreadPool::Task task; task.work_function = [this, scanner] { _scanner_thread(scanner); }; task.priority = _compute_priority(num_submit); _running_threads.fetch_add(1, std::memory_order_release); if (LIKELY(thread_pool->try_offer(task))) { return true; } else if (blockable) { CHECK(thread_pool->offer(task)); return true; } else { LOG(WARNING) << "thread pool busy"; _running_threads.fetch_sub(1, std::memory_order_release); _scanner_submit_count.fetch_sub(delta, std::memory_order_relaxed); return false; } } Status OlapScanNode::_start_scan_thread(RuntimeState* state) { if (_scan_ranges.empty()) { _update_status(Status::EndOfFile("empty scan ranges")); _result_chunks.shutdown(); return Status::OK(); } std::vector<std::unique_ptr<OlapScanRange>> key_ranges; RETURN_IF_ERROR(_conjuncts_manager.get_key_ranges(&key_ranges)); std::vector<ExprContext*> conjunct_ctxs; _conjuncts_manager.get_not_push_down_conjuncts(&conjunct_ctxs); int scanners_per_tablet = std::max(1, 64 / (int)_scan_ranges.size()); for (auto& scan_range : _scan_ranges) { int num_ranges = key_ranges.size(); int ranges_per_scanner = std::max(1, num_ranges / scanners_per_tablet); for (int i = 0; i < num_ranges;) { std::vector<OlapScanRange*> agg_key_ranges; agg_key_ranges.push_back(key_ranges[i].get()); i++; for (int j = 1; i < num_ranges && j < ranges_per_scanner && key_ranges[i]->end_include == key_ranges[i - 1]->end_include; ++j, ++i) { agg_key_ranges.push_back(key_ranges[i].get()); } TabletScannerParams scanner_params; scanner_params.scan_range = scan_range.get(); scanner_params.key_ranges = &agg_key_ranges; scanner_params.conjunct_ctxs = &conjunct_ctxs; scanner_params.skip_aggregation = _olap_scan_node.is_preaggregation; scanner_params.need_agg_finalize = true; auto* scanner = _obj_pool.add(new TabletScanner(this)); RETURN_IF_ERROR(scanner->init(state, scanner_params)); // Assume all scanners have the same schema. _chunk_schema = &scanner->chunk_schema(); _pending_scanners.push(scanner); } } _pending_scanners.reverse(); _num_scanners = _pending_scanners.size(); _chunks_per_scanner = config::doris_scanner_row_num / config::vector_chunk_size; _chunks_per_scanner += (config::doris_scanner_row_num % config::vector_chunk_size != 0); int concurrency = std::min<int>(kMaxConcurrency, _num_scanners); int chunks = _chunks_per_scanner * concurrency; _chunk_pool.reserve(chunks); _fill_chunk_pool(chunks, true); std::lock_guard<std::mutex> l(_mtx); for (int i = 0; i < concurrency; i++) { CHECK(_submit_scanner(_pending_scanners.pop(), true)); } return Status::OK(); } Status OlapScanNode::set_scan_ranges(const std::vector<TInternalScanRange>& ranges) { for (auto& r : ranges) { _scan_ranges.emplace_back(new TInternalScanRange(r)); } return Status::OK(); } Status OlapScanNode::set_scan_range(const TInternalScanRange& range) { return set_scan_ranges({range}); } void OlapScanNode::_update_status(const Status& status) { std::lock_guard<SpinLock> lck(_status_mutex); if (_status.ok()) { _status = status; } } Status OlapScanNode::_get_status() { std::lock_guard<SpinLock> lck(_status_mutex); return _status; } void OlapScanNode::_close_pending_scanners() { std::lock_guard<std::mutex> l(_mtx); while (!_pending_scanners.empty()) { TabletScanner* scanner = _pending_scanners.pop(); scanner->close(_runtime_state); _closed_scanners.fetch_add(1, std::memory_order_release); } } pipeline::OpFactories OlapScanNode::decompose_to_pipeline(pipeline::PipelineBuilderContext* context) { using namespace pipeline; OpFactories operators; auto scan_operator = std::make_shared<ScanOperatorFactory>(context->next_operator_id(), id(), _olap_scan_node, std::move(_conjunct_ctxs), std::move(_runtime_filter_collector)); auto& morsel_queues = context->fragment_context()->morsel_queues(); auto source_id = scan_operator->plan_node_id(); DCHECK(morsel_queues.count(source_id)); auto& morsel_queue = morsel_queues[source_id]; // ScanOperator's degree_of_parallelism is not more than the number of morsels // If table is empty, then morsel size is zero and we still set degree of parallelism to 1 const auto degree_of_parallelism = std::min<size_t>(std::max<size_t>(1, morsel_queue->num_morsels()), context->degree_of_parallelism()); scan_operator->set_degree_of_parallelism(degree_of_parallelism); operators.emplace_back(std::move(scan_operator)); if (limit() != -1) { operators.emplace_back(std::make_shared<LimitOperatorFactory>(context->next_operator_id(), id(), limit())); } return operators; } } // namespace starrocks::vectorized
/* * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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 "It_vfs_jffs.h" static UINT32 Testcase(VOID) { INT32 fd1, fd2, fd3; INT32 ret, len; INT32 flags; ssize_t lenV = 0; CHAR readbuf[JFFS_STANDARD_NAME_LENGTH] = "liteos"; CHAR pathname1[JFFS_STANDARD_NAME_LENGTH] = { JFFS_PATH_NAME0 }; CHAR pathname2[JFFS_STANDARD_NAME_LENGTH] = { JFFS_PATH_NAME0 }; CHAR pathname3[JFFS_STANDARD_NAME_LENGTH] = { JFFS_MAIN_DIR0 }; CHAR bufW1[JFFS_SHORT_ARRAY_LENGTH + 1] = "0123456789"; CHAR bufW2[JFFS_SHORT_ARRAY_LENGTH + 1] = "abcefghijk"; CHAR bufW3[JFFS_STANDARD_NAME_LENGTH] = "lalalalala"; ret = mkdir(pathname1, S_IRWXU | S_IRWXG | S_IRWXO); ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT); ret = chdir(pathname1); ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT); JffsStrcat2(pathname1, "/1474_1", JFFS_STANDARD_NAME_LENGTH); fd1 = open(pathname1, O_NONBLOCK | O_CREAT | O_RDWR | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO); ICUNIT_GOTO_NOT_EQUAL(fd1, -1, fd1, EXIT2); JffsStrcat2(pathname1, "/1474_2", JFFS_STANDARD_NAME_LENGTH); fd2 = open(pathname1, O_NONBLOCK | O_CREAT | O_RDWR | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO); ICUNIT_GOTO_NOT_EQUAL(fd2, -1, fd2, EXIT4); JffsStrcat2(pathname1, "/1474_3", JFFS_STANDARD_NAME_LENGTH); fd3 = open(pathname1, O_NONBLOCK | O_CREAT | O_RDWR | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO); ICUNIT_GOTO_NOT_EQUAL(fd2, -1, fd2, EXIT6); len = write(fd1, bufW1, JFFS_SHORT_ARRAY_LENGTH); ICUNIT_GOTO_EQUAL(len, 10, len, EXIT6); // compare ret len with target len 10 len = write(fd2, bufW2, JFFS_SHORT_ARRAY_LENGTH); ICUNIT_GOTO_EQUAL(len, 10, len, EXIT6); // compare ret len with target len 10 ret = close(fd1); ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT6); ret = close(fd2); ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT6); JffsStrcat2(pathname1, "/1474_1", JFFS_STANDARD_NAME_LENGTH); fd1 = open(pathname1, O_NONBLOCK | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO); ICUNIT_GOTO_NOT_EQUAL(fd1, -1, fd1, EXIT6); JffsStrcat2(pathname1, "/1474_2", JFFS_STANDARD_NAME_LENGTH); fd2 = open(pathname1, O_NONBLOCK | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO); ICUNIT_GOTO_NOT_EQUAL(fd2, -1, fd2, EXIT6); memset(bufW1, 0, JFFS_SHORT_ARRAY_LENGTH + 1); memset(bufW2, 0, JFFS_SHORT_ARRAY_LENGTH + 1); len = read(fd1, bufW1, JFFS_SHORT_ARRAY_LENGTH); ICUNIT_GOTO_EQUAL(len, 10, len, EXIT6); // compare ret len with target len 10 len = read(fd2, bufW2, JFFS_SHORT_ARRAY_LENGTH); ICUNIT_GOTO_EQUAL(len, 10, len, EXIT6); // compare ret len with target len 10 g_jffsIov[0].iov_base = bufW1; g_jffsIov[0].iov_len = JFFS_SHORT_ARRAY_LENGTH + 1; g_jffsIov[1].iov_base = bufW2; g_jffsIov[1].iov_len = JFFS_SHORT_ARRAY_LENGTH + 1; lenV = writev(fd3, g_jffsIov, 2); // writes 2 buffers to the fd ICUNIT_GOTO_EQUAL(lenV, 2 * (JFFS_SHORT_ARRAY_LENGTH + 1), lenV, EXIT6); ret = close(fd3); ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT6); JffsStrcat2(pathname1, "/1474_3", JFFS_STANDARD_NAME_LENGTH); ret = remove(pathname1); ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT5); ret = close(fd2); ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT6); JffsStrcat2(pathname1, "/1474_2", JFFS_STANDARD_NAME_LENGTH); ret = remove(pathname1); ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT3); ret = close(fd1); ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT2); JffsStrcat2(pathname1, "/1474_1", JFFS_STANDARD_NAME_LENGTH); ret = remove(pathname1); ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT1); ret = chdir(JFFS_MAIN_DIR0); ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT); ret = rmdir(pathname2); ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT); return JFFS_NO_ERROR; EXIT6: close(fd3); EXIT5: JffsStrcat2(pathname1, "/1474_3", JFFS_STANDARD_NAME_LENGTH); remove(pathname1); EXIT4: close(fd2); EXIT3: JffsStrcat2(pathname1, "/1474_2", JFFS_STANDARD_NAME_LENGTH); remove(pathname1); EXIT2: close(fd1); EXIT1: JffsStrcat2(pathname1, "/1474_1", JFFS_STANDARD_NAME_LENGTH); remove(pathname1); EXIT: remove(pathname2); return JFFS_NO_ERROR; } /* * testcase brief in English * */ VOID ItFsJffs418(VOID) { TEST_ADD_CASE("IT_FS_JFFS_418", Testcase, TEST_VFS, TEST_JFFS, TEST_LEVEL2, TEST_FUNCTION); }
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent, const int alphaBits_, const int depthBufferBits_, const int stencilBufferBits_) noexcept : redBits (bitsPerRGBComponent), greenBits (bitsPerRGBComponent), blueBits (bitsPerRGBComponent), alphaBits (alphaBits_), depthBufferBits (depthBufferBits_), stencilBufferBits (stencilBufferBits_), accumulationBufferRedBits (0), accumulationBufferGreenBits (0), accumulationBufferBlueBits (0), accumulationBufferAlphaBits (0), multisamplingLevel (0) { } bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const noexcept { return redBits == other.redBits && greenBits == other.greenBits && blueBits == other.blueBits && alphaBits == other.alphaBits && depthBufferBits == other.depthBufferBits && stencilBufferBits == other.stencilBufferBits && accumulationBufferRedBits == other.accumulationBufferRedBits && accumulationBufferGreenBits == other.accumulationBufferGreenBits && accumulationBufferBlueBits == other.accumulationBufferBlueBits && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits && multisamplingLevel == other.multisamplingLevel; } bool OpenGLPixelFormat::operator!= (const OpenGLPixelFormat& other) const noexcept { return ! operator== (other); }
version https://git-lfs.github.com/spec/v1 oid sha256:633753f86a875ccde0bef26229d228bb0df1c4e9da4379998f1adeaea4c90b8d size 71867
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2012, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. --------------------------------------------------------------------------- */ /** @file ImporterRegistry.cpp Central registry for all importers available. Do not edit this file directly (unless you are adding new loaders), instead use the corresponding preprocessor flag to selectively disable formats. */ #include "AssimpPCH.h" // ------------------------------------------------------------------------------------------------ // Importers // (include_new_importers_here) // ------------------------------------------------------------------------------------------------ #ifndef ASSIMP_BUILD_NO_X_IMPORTER # include "XFileImporter.h" #endif #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER # include "3DSLoader.h" #endif #ifndef ASSIMP_BUILD_NO_MD3_IMPORTER # include "MD3Loader.h" #endif #ifndef ASSIMP_BUILD_NO_MDL_IMPORTER # include "MDLLoader.h" #endif #ifndef ASSIMP_BUILD_NO_MD2_IMPORTER # include "MD2Loader.h" #endif #ifndef ASSIMP_BUILD_NO_PLY_IMPORTER # include "PlyLoader.h" #endif #ifndef ASSIMP_BUILD_NO_ASE_IMPORTER # include "ASELoader.h" #endif #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER # include "ObjFileImporter.h" #endif #ifndef ASSIMP_BUILD_NO_HMP_IMPORTER # include "HMPLoader.h" #endif #ifndef ASSIMP_BUILD_NO_SMD_IMPORTER # include "SMDLoader.h" #endif #ifndef ASSIMP_BUILD_NO_MDC_IMPORTER # include "MDCLoader.h" #endif #ifndef ASSIMP_BUILD_NO_MD5_IMPORTER # include "MD5Loader.h" #endif #ifndef ASSIMP_BUILD_NO_STL_IMPORTER # include "STLLoader.h" #endif #ifndef ASSIMP_BUILD_NO_LWO_IMPORTER # include "LWOLoader.h" #endif #ifndef ASSIMP_BUILD_NO_DXF_IMPORTER # include "DXFLoader.h" #endif #ifndef ASSIMP_BUILD_NO_NFF_IMPORTER # include "NFFLoader.h" #endif #ifndef ASSIMP_BUILD_NO_RAW_IMPORTER # include "RawLoader.h" #endif #ifndef ASSIMP_BUILD_NO_OFF_IMPORTER # include "OFFLoader.h" #endif #ifndef ASSIMP_BUILD_NO_AC_IMPORTER # include "ACLoader.h" #endif #ifndef ASSIMP_BUILD_NO_BVH_IMPORTER # include "BVHLoader.h" #endif #ifndef ASSIMP_BUILD_NO_IRRMESH_IMPORTER # include "IRRMeshLoader.h" #endif #ifndef ASSIMP_BUILD_NO_IRR_IMPORTER # include "IRRLoader.h" #endif #ifndef ASSIMP_BUILD_NO_Q3D_IMPORTER # include "Q3DLoader.h" #endif #ifndef ASSIMP_BUILD_NO_B3D_IMPORTER # include "B3DImporter.h" #endif #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER # include "ColladaLoader.h" #endif #ifndef ASSIMP_BUILD_NO_TERRAGEN_IMPORTER # include "TerragenLoader.h" #endif #ifndef ASSIMP_BUILD_NO_CSM_IMPORTER # include "CSMLoader.h" #endif #ifndef ASSIMP_BUILD_NO_3D_IMPORTER # include "UnrealLoader.h" #endif #ifndef ASSIMP_BUILD_NO_LWS_IMPORTER # include "LWSLoader.h" #endif #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER # include "OgreImporter.hpp" #endif #ifndef ASSIMP_BUILD_NO_MS3D_IMPORTER # include "MS3DLoader.h" #endif #ifndef ASSIMP_BUILD_NO_COB_IMPORTER # include "COBLoader.h" #endif #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER # include "BlenderLoader.h" #endif #ifndef ASSIMP_BUILD_NO_Q3BSP_IMPORTER # include "Q3BSPFileImporter.h" #endif #ifndef ASSIMP_BUILD_NO_NDO_IMPORTER # include "NDOLoader.h" #endif #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER # include "IFCLoader.h" #endif #ifndef ASSIMP_BUILD_NO_M3_IMPORTER # include "M3Importer.h" #endif #ifndef ASSIMP_BUILD_NO_XGL_IMPORTER # include "XGLLoader.h" #endif namespace Assimp { // ------------------------------------------------------------------------------------------------ void GetImporterInstanceList(std::vector< BaseImporter* >& out) { // ---------------------------------------------------------------------------- // Add an instance of each worker class here // (register_new_importers_here) // ---------------------------------------------------------------------------- out.reserve(64); #if (!defined ASSIMP_BUILD_NO_X_IMPORTER) out.push_back( new XFileImporter()); #endif #if (!defined ASSIMP_BUILD_NO_OBJ_IMPORTER) out.push_back( new ObjFileImporter()); #endif #if (!defined ASSIMP_BUILD_NO_3DS_IMPORTER) out.push_back( new Discreet3DSImporter()); #endif #if (!defined ASSIMP_BUILD_NO_MD3_IMPORTER) out.push_back( new MD3Importer()); #endif #if (!defined ASSIMP_BUILD_NO_MD2_IMPORTER) out.push_back( new MD2Importer()); #endif #if (!defined ASSIMP_BUILD_NO_PLY_IMPORTER) out.push_back( new PLYImporter()); #endif #if (!defined ASSIMP_BUILD_NO_MDL_IMPORTER) out.push_back( new MDLImporter()); #endif #if (!defined ASSIMP_BUILD_NO_ASE_IMPORTER) out.push_back( new ASEImporter()); #endif #if (!defined ASSIMP_BUILD_NO_HMP_IMPORTER) out.push_back( new HMPImporter()); #endif #if (!defined ASSIMP_BUILD_NO_SMD_IMPORTER) out.push_back( new SMDImporter()); #endif #if (!defined ASSIMP_BUILD_NO_MDC_IMPORTER) out.push_back( new MDCImporter()); #endif #if (!defined ASSIMP_BUILD_NO_MD5_IMPORTER) out.push_back( new MD5Importer()); #endif #if (!defined ASSIMP_BUILD_NO_STL_IMPORTER) out.push_back( new STLImporter()); #endif #if (!defined ASSIMP_BUILD_NO_LWO_IMPORTER) out.push_back( new LWOImporter()); #endif #if (!defined ASSIMP_BUILD_NO_DXF_IMPORTER) out.push_back( new DXFImporter()); #endif #if (!defined ASSIMP_BUILD_NO_NFF_IMPORTER) out.push_back( new NFFImporter()); #endif #if (!defined ASSIMP_BUILD_NO_RAW_IMPORTER) out.push_back( new RAWImporter()); #endif #if (!defined ASSIMP_BUILD_NO_OFF_IMPORTER) out.push_back( new OFFImporter()); #endif #if (!defined ASSIMP_BUILD_NO_AC_IMPORTER) out.push_back( new AC3DImporter()); #endif #if (!defined ASSIMP_BUILD_NO_BVH_IMPORTER) out.push_back( new BVHLoader()); #endif #if (!defined ASSIMP_BUILD_NO_IRRMESH_IMPORTER) out.push_back( new IRRMeshImporter()); #endif #if (!defined ASSIMP_BUILD_NO_IRR_IMPORTER) out.push_back( new IRRImporter()); #endif #if (!defined ASSIMP_BUILD_NO_Q3D_IMPORTER) out.push_back( new Q3DImporter()); #endif #if (!defined ASSIMP_BUILD_NO_B3D_IMPORTER) out.push_back( new B3DImporter()); #endif #if (!defined ASSIMP_BUILD_NO_COLLADA_IMPORTER) out.push_back( new ColladaLoader()); #endif #if (!defined ASSIMP_BUILD_NO_TERRAGEN_IMPORTER) out.push_back( new TerragenImporter()); #endif #if (!defined ASSIMP_BUILD_NO_CSM_IMPORTER) out.push_back( new CSMImporter()); #endif #if (!defined ASSIMP_BUILD_NO_3D_IMPORTER) out.push_back( new UnrealImporter()); #endif #if (!defined ASSIMP_BUILD_NO_LWS_IMPORTER) out.push_back( new LWSImporter()); #endif #if (!defined ASSIMP_BUILD_NO_OGRE_IMPORTER) out.push_back( new Ogre::OgreImporter()); #endif #if (!defined ASSIMP_BUILD_NO_MS3D_IMPORTER) out.push_back( new MS3DImporter()); #endif #if (!defined ASSIMP_BUILD_NO_COB_IMPORTER) out.push_back( new COBImporter()); #endif #if (!defined ASSIMP_BUILD_NO_BLEND_IMPORTER) out.push_back( new BlenderImporter()); #endif #if (!defined ASSIMP_BUILD_NO_Q3BSP_IMPORTER) out.push_back( new Q3BSPFileImporter() ); #endif #if (!defined ASSIMP_BUILD_NO_NDO_IMPORTER) out.push_back( new NDOImporter() ); #endif #if (!defined ASSIMP_BUILD_NO_IFC_IMPORTER) out.push_back( new IFCImporter() ); #endif #if ( !defined ASSIMP_BUILD_NO_M3_IMPORTER ) out.push_back( new M3::M3Importer() ); #endif #if ( !defined ASSIMP_BUILD_NO_XGL_IMPORTER ) out.push_back( new XGLImporter() ); #endif } }
// dllmain.cpp : Defines the entry point for the DLL application. #include "framework.h" import onyx32.gui.global; // See https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain // https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices BOOL APIENTRY DllMain( HMODULE hModule, DWORD reasonForCall, void* lpReserved ) { Onyx32::GUI::Global::SetHInstance(hModule); switch (reasonForCall) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return true; }
// Copyright 2017 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "fxjs/xfa/cjx_rectangle.h" #include "xfa/fxfa/parser/cxfa_rectangle.h" CJX_Rectangle::CJX_Rectangle(CXFA_Rectangle* node) : CJX_Node(node) {} CJX_Rectangle::~CJX_Rectangle() = default;
#ifndef BOOST_MPL_SET_AUX_INSERT_RANGE_IMPL_HPP_INCLUDED #define BOOST_MPL_SET_AUX_INSERT_RANGE_IMPL_HPP_INCLUDED // Copyright Bruno Dutra 2015 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <boost/mpl/insert_range_fwd.hpp> #include <boost/mpl/set/aux_/tag.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/fold.hpp> #include <boost/mpl/insert.hpp> namespace boost { namespace mpl { template<> struct insert_range_impl< aux::set_tag > { template< typename Sequence , typename /*Pos*/ , typename Range > struct apply : fold<Range, Sequence, insert<_1, _2> > { }; }; }} #endif // BOOST_MPL_SET_AUX_INSERT_RANGE_IMPL_HPP_INCLUDED
/** * Copyright (c) 2009 Carnegie Mellon University. * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ // Copyright (c) 2005, Google Inc. // 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 Google Inc. 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. // --- // This file contains #include information about logging-related stuff. // Pretty much everybody needs to #include this file so that they can // log various happenings. // #ifndef _ASSERTIONS_H_ #define _ASSERTIONS_H_ #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #ifdef HAVE_UNISTD_H #include <unistd.h> // for write() #endif #include <string.h> // for strlen(), strcmp() #include <assert.h> #include <errno.h> // for errno #include <sstream> #include <cassert> #include <graphlab/logger/logger.hpp> #include <boost/typeof/typeof.hpp> extern void __print_back_trace(); // On some systems (like freebsd), we can't call write() at all in a // global constructor, perhaps because errno hasn't been set up. // Calling the write syscall is safer (it doesn't set errno), so we // prefer that. Note we don't care about errno for logging: we just // do logging on a best-effort basis. #define WRITE_TO_STDERR(buf, len) (logbuf(LOG_FATAL, buf, len)) // CHECK dies with a fatal error if condition is not true. It is *not* // controlled by NDEBUG, so the check will be executed regardless of // compilation mode. Therefore, it is safe to do things like: // CHECK(fp->Write(x) == 4) #define CHECK(condition) \ do { \ if (__builtin_expect(!(condition), 0)) { \ logstream(LOG_ERROR) \ << "Check failed: " << #condition << std::endl; \ __print_back_trace(); \ throw("assertion failure"); \ } \ } while(0) // This prints errno as well. errno is the posix defined last error // number. See errno.h #define PCHECK(condition) \ do { \ if (__builtin_expect(!(condition), 0)) { \ const int _PCHECK_err_no_ = errno; \ logstream(LOG_ERROR) \ << "Check failed: " << #condition << ": " \ << strerror(err_no) << std::endl; \ __print_back_trace(); \ throw("assertion failure"); \ } \ } while(0) // Helper macro for binary operators; prints the two values on error // Don't use this macro directly in your code, use CHECK_EQ et al below // WARNING: These don't compile correctly if one of the arguments is a pointer // and the other is NULL. To work around this, simply static_cast NULL to the // type of the desired pointer. #define CHECK_OP(op, val1, val2) \ do { \ const typeof(val1) _CHECK_OP_v1_ = val1; \ const typeof(val2) _CHECK_OP_v2_ = (typeof(val2))val2; \ if (__builtin_expect(!((_CHECK_OP_v1_) op \ (typeof(val1))(_CHECK_OP_v2_)), 0)) { \ logstream(LOG_ERROR) \ << "Check failed: " \ << #val1 << #op << #val2 \ << " [" \ << _CHECK_OP_v1_ \ << ' ' << #op << ' ' \ << _CHECK_OP_v2_ << "]" << std::endl; \ __print_back_trace(); \ throw("assertion failure"); \ } \ } while(0) #define CHECK_EQ(val1, val2) CHECK_OP(==, val1, val2) #define CHECK_NE(val1, val2) CHECK_OP(!=, val1, val2) #define CHECK_LE(val1, val2) CHECK_OP(<=, val1, val2) #define CHECK_LT(val1, val2) CHECK_OP(< , val1, val2) #define CHECK_GE(val1, val2) CHECK_OP(>=, val1, val2) #define CHECK_GT(val1, val2) CHECK_OP(> , val1, val2) // Synonyms for CHECK_* that are used in some unittests. #define EXPECT_EQ(val1, val2) CHECK_EQ(val1, val2) #define EXPECT_NE(val1, val2) CHECK_NE(val1, val2) #define EXPECT_LE(val1, val2) CHECK_LE(val1, val2) #define EXPECT_LT(val1, val2) CHECK_LT(val1, val2) #define EXPECT_GE(val1, val2) CHECK_GE(val1, val2) #define EXPECT_GT(val1, val2) CHECK_GT(val1, val2) #define ASSERT_EQ(val1, val2) EXPECT_EQ(val1, val2) #define ASSERT_NE(val1, val2) EXPECT_NE(val1, val2) #define ASSERT_LE(val1, val2) EXPECT_LE(val1, val2) #define ASSERT_LT(val1, val2) EXPECT_LT(val1, val2) #define ASSERT_GE(val1, val2) EXPECT_GE(val1, val2) #define ASSERT_GT(val1, val2) EXPECT_GT(val1, val2) // As are these variants. #define EXPECT_TRUE(cond) CHECK(cond) #define EXPECT_FALSE(cond) CHECK(!(cond)) #define EXPECT_STREQ(a, b) CHECK(strcmp(a, b) == 0) #define ASSERT_TRUE(cond) EXPECT_TRUE(cond) #define ASSERT_FALSE(cond) EXPECT_FALSE(cond) #define ASSERT_STREQ(a, b) EXPECT_STREQ(a, b) #define ASSERT_MSG(condition, fmt, ...) \ do { \ if (__builtin_expect(!(condition), 0)) { \ logstream(LOG_ERROR) \ << "Check failed: " << #condition << ":\n"; \ logger(LOG_ERROR, fmt, ##__VA_ARGS__); \ __print_back_trace(); \ throw("assertion failure"); \ } \ } while(0) // Used for (libc) functions that return -1 and set errno #define CHECK_ERR(invocation) PCHECK((invocation) != -1) // A few more checks that only happen in debug mode #ifdef NDEBUG #define DCHECK_EQ(val1, val2) #define DCHECK_NE(val1, val2) #define DCHECK_LE(val1, val2) #define DCHECK_LT(val1, val2) #define DCHECK_GE(val1, val2) #define DCHECK_GT(val1, val2) #define DASSERT_TRUE(cond) #define DASSERT_FALSE(cond) #define DASSERT_MSG(condition, fmt, ...) #else #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2) #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2) #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2) #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2) #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2) #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2) #define DASSERT_TRUE(cond) ASSERT_TRUE(cond) #define DASSERT_FALSE(cond) ASSERT_FALSE(cond) #define DASSERT_MSG(condition, fmt, ...) \ do { \ if (__builtin_expect(!(condition), 0)) { \ logstream(LOG_ERROR) \ << "Check failed: " << #condition << ":\n"; \ logger(LOG_ERROR, fmt, ##__VA_ARGS__); \ __print_back_trace(); \ throw("assertion failure"); \ } \ } while(0) #endif #ifdef ERROR #undef ERROR // may conflict with ERROR macro on windows #endif #endif // _LOGGING_H_
/* * * Copyright (c) 2020 Project CHIP Authors * 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. */ /** * @file * This file implements unit tests for the SecurePairingSession implementation. */ #include "TestTransportLayer.h" #include <errno.h> #include <nlunit-test.h> #include <core/CHIPCore.h> #include <transport/SecurePairingSession.h> #include <stdarg.h> #include <support/CodeUtils.h> #include <support/TestUtils.h> using namespace chip; class TestSecurePairingDelegate : public SecurePairingSessionDelegate { public: CHIP_ERROR SendMessage(System::PacketBuffer * msgBuf) override { mNumMessageSend++; if (peer != nullptr) { MessageHeader hdr; size_t headerSize = 0; hdr.packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize); msgBuf->ConsumeHead(headerSize); return peer->HandlePeerMessage(hdr, msgBuf); } return mMessageSendError; } void OnPairingError(CHIP_ERROR error) override { mNumPairingErrors++; } void OnPairingComplete() override { mNumPairingComplete++; } uint32_t mNumMessageSend = 0; uint32_t mNumPairingErrors = 0; uint32_t mNumPairingComplete = 0; CHIP_ERROR mMessageSendError = CHIP_NO_ERROR; SecurePairingSession * peer = nullptr; }; void SecurePairingWaitTest(nlTestSuite * inSuite, void * inContext) { // Test all combinations of invalid parameters TestSecurePairingDelegate delegate; SecurePairingSession pairing; NL_TEST_ASSERT(inSuite, pairing.WaitForPairing(1234, 500, nullptr, 0, Optional<NodeId>::Value(1), 0, &delegate) == CHIP_ERROR_INVALID_ARGUMENT); NL_TEST_ASSERT(inSuite, pairing.WaitForPairing(1234, 500, (const uint8_t *) "salt", 4, Optional<NodeId>::Value(1), 0, nullptr) == CHIP_ERROR_INVALID_ARGUMENT); NL_TEST_ASSERT(inSuite, pairing.WaitForPairing(1234, 500, (const uint8_t *) "salt", 4, Optional<NodeId>::Value(1), 0, &delegate) == CHIP_NO_ERROR); } void SecurePairingStartTest(nlTestSuite * inSuite, void * inContext) { // Test all combinations of invalid parameters TestSecurePairingDelegate delegate; SecurePairingSession pairing; NL_TEST_ASSERT(inSuite, pairing.Pair(1234, 500, nullptr, 0, Optional<NodeId>::Value(1), 0, &delegate) == CHIP_ERROR_INVALID_ARGUMENT); NL_TEST_ASSERT(inSuite, pairing.Pair(1234, 500, (const uint8_t *) "salt", 4, Optional<NodeId>::Value(1), 0, nullptr) == CHIP_ERROR_INVALID_ARGUMENT); NL_TEST_ASSERT(inSuite, pairing.Pair(1234, 500, (const uint8_t *) "salt", 4, Optional<NodeId>::Value(1), 0, &delegate) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, delegate.mNumMessageSend == 1); delegate.mMessageSendError = CHIP_ERROR_BAD_REQUEST; SecurePairingSession pairing1; NL_TEST_ASSERT(inSuite, pairing1.Pair(1234, 500, (const uint8_t *) "salt", 4, Optional<NodeId>::Value(1), 0, &delegate) == CHIP_ERROR_BAD_REQUEST); } void SecurePairingHandshakeTest(nlTestSuite * inSuite, void * inContext) { // Test all combinations of invalid parameters TestSecurePairingDelegate delegateAccessory, deleageCommissioner; SecurePairingSession pairingAccessory, pairingCommissioner; deleageCommissioner.peer = &pairingAccessory; delegateAccessory.peer = &pairingCommissioner; NL_TEST_ASSERT(inSuite, pairingAccessory.WaitForPairing(1234, 500, (const uint8_t *) "salt", 4, Optional<NodeId>::Value(1), 0, &delegateAccessory) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, pairingCommissioner.Pair(1234, 500, (const uint8_t *) "salt", 4, Optional<NodeId>::Value(2), 0, &deleageCommissioner) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, delegateAccessory.mNumMessageSend == 1); NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); NL_TEST_ASSERT(inSuite, deleageCommissioner.mNumMessageSend == 2); NL_TEST_ASSERT(inSuite, deleageCommissioner.mNumPairingComplete == 1); } // Test Suite /** * Test Suite that lists all the test functions. */ // clang-format off static const nlTest sTests[] = { NL_TEST_DEF("WaitInit", SecurePairingWaitTest), NL_TEST_DEF("Start", SecurePairingStartTest), NL_TEST_DEF("Handshake", SecurePairingHandshakeTest), NL_TEST_SENTINEL() }; // clang-format on // clang-format off static nlTestSuite sSuite = { "Test-CHIP-SecurePairing", &sTests[0], nullptr, nullptr }; // clang-format on /** * Main */ int TestSecurePairingSession() { // Run test suit against one context nlTestRunner(&sSuite, nullptr); return (nlTestRunnerStats(&sSuite)); } CHIP_REGISTER_TEST_SUITE(TestSecurePairingSession) namespace chip { namespace Logging { void LogV(uint8_t module, uint8_t category, const char * format, va_list argptr) { (void) module, (void) category; vfprintf(stderr, format, argptr); } } // namespace Logging } // namespace chip
// This is all that is needed to compile a test-runner executable. // More tests can be added here, or in a new tests/*.cpp file. #include "../tests/doctest/doctest.h" #include "Vector3.hh" #include "size.hh" #include "example.h" #include <cmath> #include <fstream> // Tests Vector TEST_CASE("Vector3 - sum"){ double arg1[] = {100,100,100}; double arg2[] = {300,300,300}; Vector3 vec1 = Vector3(arg1); Vector3 vec2 = Vector3(arg2); double argt[] = {400,400,400}; Vector3 temp = Vector3(argt); CHECK( (vec1 + vec2) == temp); } TEST_CASE("Vector3 - difference"){ double arg1[SIZE] = {100,100,100}; double arg2[SIZE] = {300,300,300}; Vector3 vec1 = Vector3(arg1); Vector3 vec2 = Vector3(arg2); double argt[SIZE] = {-200,-200,-200}; Vector3 temp = Vector3(argt); CHECK( temp == vec1 - vec2); } TEST_CASE("Vector3 - multiplication"){ double arg1[SIZE] = {100,100,100}; double arg = 2; Vector3 vec1 = Vector3(arg1); double argt[SIZE] = {200,200,200}; Vector3 temp = Vector3(argt); CHECK( temp == vec1 * arg); } TEST_CASE("Vector3 - division (arg = 2)"){ double arg1[SIZE] = {100,100,100}; double arg = 2; Vector3 vec1 = Vector3(arg1); double argt[SIZE] = {50,50,50}; Vector3 temp = Vector3(argt); CHECK( temp == vec1 / arg); } TEST_CASE("Vector3 - division (arg = 0)"){ double arg1[SIZE] = {100,100,100}; double arg = 0; Vector3 vec1 = Vector3(arg1); WARN_THROWS(vec1 / arg); } TEST_CASE("Index operator"){ double value[] = {3,4,5}; double a, b, c; Vector3 Vec(value); a = Vec[0]; b = Vec[1]; c = Vec[2]; CHECK( (a == 3 && b == 4 && c == 5)); } TEST_CASE("Index operator values to vector"){ double a = 3; double b = 4; double c = 5; Vector3 Vec; Vec[0] = a; Vec[1] = b; Vec[2] = c; CHECK( (Vec[0] == 3 && Vec[1] == 4 && Vec[2] == 5)); } TEST_CASE("Constructor values in"){ double value[] = {3,4,5}; Vector3 Vec(value); CHECK( (Vec[0] == 3 && Vec[1] == 4 && Vec[2] == 5)); } TEST_CASE("Out of range"){ double value[] = {3,4,5}; Vector3 Vec(value); WARN_THROWS( Vec[3]); } TEST_CASE("Start Constructor"){ Vector3 Vec; CHECK( (Vec[0] == 0 && Vec[1] == 0 && Vec[2] == 0)); } TEST_CASE(">> operator"){ Vector3 vec; std::istringstream in("0 1 2"); in >> vec; CHECK( (vec[0] == 0 && vec[1] == 1 && vec[2] == 2) ); } TEST_CASE("Vector3 - display"){ double arg[] = {0,1,2}; Vector3 vec1(arg); std::ostringstream stream; stream << vec1; CHECK( " 0.0000000000 1.0000000000 2.0000000000" == stream.str()); }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Reflection.MonoProperty #include "System/Reflection/MonoProperty.hpp" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::System::Reflection::MonoProperty::StaticGetter_1, "System.Reflection", "MonoProperty/StaticGetter`1"); // Type namespace: System.Reflection namespace System::Reflection { // WARNING Size may be invalid! // Autogenerated type: System.Reflection.MonoProperty/System.Reflection.StaticGetter`1 // [TokenAttribute] Offset: FFFFFFFF template<typename R> class MonoProperty::StaticGetter_1 : public ::System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0xFFFFFFFFFFFFFFFF template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MonoProperty::StaticGetter_1<R>* New_ctor(::Il2CppObject* object, ::System::IntPtr method) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Reflection::MonoProperty::StaticGetter_1::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MonoProperty::StaticGetter_1<R>*, creationType>(object, method))); } // public R Invoke() // Offset: 0xFFFFFFFFFFFFFFFF R Invoke() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Reflection::MonoProperty::StaticGetter_1::Invoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Invoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<R, false>(this, ___internal__method); } // public System.IAsyncResult BeginInvoke(System.AsyncCallback callback, System.Object object) // Offset: 0xFFFFFFFFFFFFFFFF ::System::IAsyncResult* BeginInvoke(::System::AsyncCallback* callback, ::Il2CppObject* object) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Reflection::MonoProperty::StaticGetter_1::BeginInvoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BeginInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IAsyncResult*, false>(this, ___internal__method, callback, object); } // public R EndInvoke(System.IAsyncResult result) // Offset: 0xFFFFFFFFFFFFFFFF R EndInvoke(::System::IAsyncResult* result) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Reflection::MonoProperty::StaticGetter_1::EndInvoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "EndInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)}))); return ::il2cpp_utils::RunMethodRethrow<R, false>(this, ___internal__method, result); } }; // System.Reflection.MonoProperty/System.Reflection.StaticGetter`1 // Could not write size check! Type: System.Reflection.MonoProperty/System.Reflection.StaticGetter`1 is generic, or has no fields that are valid for size checks! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Copyright 2014 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. #include "ash/shelf/app_list_button.h" #include <algorithm> #include <memory> #include <utility> #include "ash/app_list/app_list_controller_impl.h" #include "ash/assistant/assistant_controller.h" #include "ash/public/cpp/shelf_types.h" #include "ash/session/session_controller.h" #include "ash/shelf/assistant_overlay.h" #include "ash/shelf/ink_drop_button_listener.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_constants.h" #include "ash/shelf/shelf_view.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/tray/tray_popup_utils.h" #include "ash/voice_interaction/voice_interaction_controller.h" #include "base/command_line.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #include "base/timer/timer.h" #include "chromeos/chromeos_switches.h" #include "components/account_id/account_id.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/scoped_canvas.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_mask.h" #include "ui/views/painter.h" #include "ui/views/widget/widget.h" namespace ash { namespace { constexpr int kVoiceInteractionAnimationDelayMs = 200; constexpr int kVoiceInteractionAnimationHideDelayMs = 500; } // namespace constexpr uint8_t kVoiceInteractionRunningAlpha = 255; // 100% alpha constexpr uint8_t kVoiceInteractionNotRunningAlpha = 138; // 54% alpha AppListButton::AppListButton(InkDropButtonListener* listener, ShelfView* shelf_view, Shelf* shelf) : views::ImageButton(nullptr), listener_(listener), shelf_view_(shelf_view), shelf_(shelf) { DCHECK(listener_); DCHECK(shelf_view_); DCHECK(shelf_); Shell::Get()->AddShellObserver(this); Shell::Get()->session_controller()->AddObserver(this); Shell::Get()->voice_interaction_controller()->AddObserver(this); SetInkDropMode(InkDropMode::ON_NO_GESTURE_HANDLER); set_ink_drop_base_color(kShelfInkDropBaseColor); set_ink_drop_visible_opacity(kShelfInkDropVisibleOpacity); SetAccessibleName( l10n_util::GetStringUTF16(IDS_ASH_SHELF_APP_LIST_LAUNCHER_TITLE)); SetSize(gfx::Size(kShelfSize, kShelfSize)); SetFocusPainter(TrayPopupUtils::CreateFocusPainter()); set_notify_action(Button::NOTIFY_ON_PRESS); // Initialize voice interaction overlay and sync the flags if active user // session has already started. This could happen when an external monitor // is plugged in. if (Shell::Get()->session_controller()->IsActiveUserSessionStarted() && chromeos::switches::IsVoiceInteractionEnabled()) { InitializeVoiceInteractionOverlay(); } } AppListButton::~AppListButton() { Shell::Get()->voice_interaction_controller()->RemoveObserver(this); Shell::Get()->RemoveShellObserver(this); Shell::Get()->session_controller()->RemoveObserver(this); } void AppListButton::OnAppListShown() { AnimateInkDrop(views::InkDropState::ACTIVATED, nullptr); is_showing_app_list_ = true; shelf_->UpdateAutoHideState(); } void AppListButton::OnAppListDismissed() { AnimateInkDrop(views::InkDropState::DEACTIVATED, nullptr); is_showing_app_list_ = false; shelf_->UpdateAutoHideState(); } void AppListButton::OnGestureEvent(ui::GestureEvent* event) { // Handle gesture events that are on the app list circle. switch (event->type()) { case ui::ET_GESTURE_SCROLL_BEGIN: AnimateInkDrop(views::InkDropState::HIDDEN, event); ImageButton::OnGestureEvent(event); return; case ui::ET_GESTURE_TAP: case ui::ET_GESTURE_TAP_CANCEL: if (UseVoiceInteractionStyle()) { assistant_overlay_->EndAnimation(); assistant_animation_delay_timer_->Stop(); } ImageButton::OnGestureEvent(event); return; case ui::ET_GESTURE_TAP_DOWN: if (UseVoiceInteractionStyle()) { assistant_animation_delay_timer_->Start( FROM_HERE, base::TimeDelta::FromMilliseconds( kVoiceInteractionAnimationDelayMs), base::Bind(&AppListButton::StartVoiceInteractionAnimation, base::Unretained(this))); } if (!Shell::Get()->app_list_controller()->IsVisible()) AnimateInkDrop(views::InkDropState::ACTION_PENDING, event); ImageButton::OnGestureEvent(event); return; case ui::ET_GESTURE_LONG_PRESS: if (UseVoiceInteractionStyle()) { base::RecordAction(base::UserMetricsAction( "VoiceInteraction.Started.AppListButtonLongPress")); Shell::Get()->app_list_controller()->StartVoiceInteractionSession(); assistant_overlay_->BurstAnimation(); event->SetHandled(); } else if (chromeos::switches::IsAssistantEnabled()) { // TODO: Handle overlay animation similarly to above. Also needs to // factor in Assistant enabled state. Shell::Get()->assistant_controller()->StartInteraction(); event->SetHandled(); } else { ImageButton::OnGestureEvent(event); } return; case ui::ET_GESTURE_LONG_TAP: if (UseVoiceInteractionStyle() || chromeos::switches::IsAssistantEnabled()) { // Also consume the long tap event. This happens after the user long // presses and lifts the finger. We already handled the long press // ignore the long tap to avoid bringing up the context menu again. AnimateInkDrop(views::InkDropState::HIDDEN, event); event->SetHandled(); } else { ImageButton::OnGestureEvent(event); } return; default: ImageButton::OnGestureEvent(event); return; } } bool AppListButton::OnMousePressed(const ui::MouseEvent& event) { ImageButton::OnMousePressed(event); shelf_view_->PointerPressedOnButton(this, ShelfView::MOUSE, event); return true; } void AppListButton::OnMouseReleased(const ui::MouseEvent& event) { ImageButton::OnMouseReleased(event); shelf_view_->PointerReleasedOnButton(this, ShelfView::MOUSE, false); } void AppListButton::OnMouseCaptureLost() { shelf_view_->PointerReleasedOnButton(this, ShelfView::MOUSE, true); ImageButton::OnMouseCaptureLost(); } bool AppListButton::OnMouseDragged(const ui::MouseEvent& event) { ImageButton::OnMouseDragged(event); shelf_view_->PointerDraggedOnButton(this, ShelfView::MOUSE, event); return true; } void AppListButton::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kButton; node_data->SetName(shelf_view_->GetTitleForView(this)); } std::unique_ptr<views::InkDropRipple> AppListButton::CreateInkDropRipple() const { gfx::Point center = GetCenterPoint(); gfx::Rect bounds(center.x() - kAppListButtonRadius, center.y() - kAppListButtonRadius, 2 * kAppListButtonRadius, 2 * kAppListButtonRadius); return std::make_unique<views::FloodFillInkDropRipple>( size(), GetLocalBounds().InsetsFrom(bounds), GetInkDropCenterBasedOnLastEvent(), GetInkDropBaseColor(), ink_drop_visible_opacity()); } void AppListButton::NotifyClick(const ui::Event& event) { ImageButton::NotifyClick(event); if (listener_) listener_->ButtonPressed(this, event, GetInkDrop()); } bool AppListButton::ShouldEnterPushedState(const ui::Event& event) { if (!shelf_view_->ShouldEventActivateButton(this, event)) return false; if (Shell::Get()->app_list_controller()->IsVisible()) return false; return views::ImageButton::ShouldEnterPushedState(event); } std::unique_ptr<views::InkDrop> AppListButton::CreateInkDrop() { std::unique_ptr<views::InkDropImpl> ink_drop = Button::CreateDefaultInkDropImpl(); ink_drop->SetShowHighlightOnHover(false); return std::move(ink_drop); } std::unique_ptr<views::InkDropMask> AppListButton::CreateInkDropMask() const { return std::make_unique<views::CircleInkDropMask>(size(), GetCenterPoint(), kAppListButtonRadius); } void AppListButton::PaintButtonContents(gfx::Canvas* canvas) { gfx::PointF circle_center(GetCenterPoint()); // Paint a white ring as the foreground for the app list circle. The ceil/dsf // math assures that the ring draws sharply and is centered at all scale // factors. float ring_outer_radius_dp = 7.f; float ring_thickness_dp = 1.5f; if (UseVoiceInteractionStyle()) { ring_outer_radius_dp = 8.f; ring_thickness_dp = 1.f; } { gfx::ScopedCanvas scoped_canvas(canvas); const float dsf = canvas->UndoDeviceScaleFactor(); circle_center.Scale(dsf); cc::PaintFlags fg_flags; fg_flags.setAntiAlias(true); fg_flags.setStyle(cc::PaintFlags::kStroke_Style); fg_flags.setColor(kShelfIconColor); if (UseVoiceInteractionStyle()) { mojom::VoiceInteractionState state = Shell::Get() ->voice_interaction_controller() ->voice_interaction_state(); // active: 100% alpha, inactive: 54% alpha fg_flags.setAlpha(state == mojom::VoiceInteractionState::RUNNING ? kVoiceInteractionRunningAlpha : kVoiceInteractionNotRunningAlpha); } const float thickness = std::ceil(ring_thickness_dp * dsf); const float radius = std::ceil(ring_outer_radius_dp * dsf) - thickness / 2; fg_flags.setStrokeWidth(thickness); // Make sure the center of the circle lands on pixel centers. canvas->DrawCircle(circle_center, radius, fg_flags); if (UseVoiceInteractionStyle()) { fg_flags.setAlpha(255); const float kCircleRadiusDp = 5.f; fg_flags.setStyle(cc::PaintFlags::kFill_Style); canvas->DrawCircle(circle_center, std::ceil(kCircleRadiusDp * dsf), fg_flags); } } } gfx::Point AppListButton::GetCenterPoint() const { // For a bottom-aligned shelf, the button bounds could have a larger height // than width (in the case of touch-dragging the shelf upwards) or a larger // width than height (in the case of a shelf hide/show animation), so adjust // the y-position of the circle's center to ensure correct layout. Similarly // adjust the x-position for a left- or right-aligned shelf. const int x_mid = width() / 2.f; const int y_mid = height() / 2.f; const ShelfAlignment alignment = shelf_->alignment(); if (alignment == SHELF_ALIGNMENT_BOTTOM || alignment == SHELF_ALIGNMENT_BOTTOM_LOCKED) { return gfx::Point(x_mid, x_mid); } else if (alignment == SHELF_ALIGNMENT_RIGHT) { return gfx::Point(y_mid, y_mid); } else { DCHECK_EQ(alignment, SHELF_ALIGNMENT_LEFT); return gfx::Point(width() - y_mid, y_mid); } } void AppListButton::OnAppListVisibilityChanged(bool shown, aura::Window* root_window) { aura::Window* window = GetWidget() ? GetWidget()->GetNativeWindow() : nullptr; if (!window || window->GetRootWindow() != root_window) return; if (shown) OnAppListShown(); else OnAppListDismissed(); } void AppListButton::OnVoiceInteractionStatusChanged( mojom::VoiceInteractionState state) { SchedulePaint(); if (!assistant_overlay_) return; switch (state) { case mojom::VoiceInteractionState::STOPPED: UMA_HISTOGRAM_TIMES( "VoiceInteraction.OpenDuration", base::TimeTicks::Now() - voice_interaction_start_timestamp_); break; case mojom::VoiceInteractionState::NOT_READY: // If we are showing the bursting or waiting animation, no need to do // anything. Otherwise show the waiting animation now. if (!assistant_overlay_->IsBursting() && !assistant_overlay_->IsWaiting()) { assistant_overlay_->WaitingAnimation(); } break; case mojom::VoiceInteractionState::RUNNING: // we start hiding the animation if it is running. if (assistant_overlay_->IsBursting() || assistant_overlay_->IsWaiting()) { assistant_animation_hide_delay_timer_->Start( FROM_HERE, base::TimeDelta::FromMilliseconds( kVoiceInteractionAnimationHideDelayMs), base::Bind(&AssistantOverlay::HideAnimation, base::Unretained(assistant_overlay_))); } voice_interaction_start_timestamp_ = base::TimeTicks::Now(); break; } } void AppListButton::OnVoiceInteractionSettingsEnabled(bool enabled) { SchedulePaint(); } void AppListButton::OnVoiceInteractionSetupCompleted(bool completed) { SchedulePaint(); } void AppListButton::OnActiveUserSessionChanged(const AccountId& account_id) { SchedulePaint(); // Initialize voice interaction overlay when primary user session becomes // active. if (Shell::Get()->session_controller()->IsUserPrimary() && !assistant_overlay_ && chromeos::switches::IsVoiceInteractionEnabled()) { InitializeVoiceInteractionOverlay(); } } void AppListButton::StartVoiceInteractionAnimation() { // We only show the voice interaction icon and related animation when the // shelf is at the bottom position and voice interaction is not running and // voice interaction setup flow has completed. ShelfAlignment alignment = shelf_->alignment(); mojom::VoiceInteractionState state = Shell::Get()->voice_interaction_controller()->voice_interaction_state(); bool show_icon = (alignment == SHELF_ALIGNMENT_BOTTOM || alignment == SHELF_ALIGNMENT_BOTTOM_LOCKED) && state == mojom::VoiceInteractionState::STOPPED && Shell::Get()->voice_interaction_controller()->setup_completed(); assistant_overlay_->StartAnimation(show_icon); } bool AppListButton::UseVoiceInteractionStyle() { VoiceInteractionController* controller = Shell::Get()->voice_interaction_controller(); bool settings_enabled = controller->settings_enabled(); bool setup_completed = controller->setup_completed(); bool is_feature_allowed = controller->allowed_state() == mojom::AssistantAllowedState::ALLOWED; if (assistant_overlay_ && is_feature_allowed && (settings_enabled || !setup_completed)) { return true; } return false; } void AppListButton::InitializeVoiceInteractionOverlay() { assistant_overlay_ = new AssistantOverlay(this); AddChildView(assistant_overlay_); assistant_overlay_->SetVisible(false); assistant_animation_delay_timer_ = std::make_unique<base::OneShotTimer>(); assistant_animation_hide_delay_timer_ = std::make_unique<base::OneShotTimer>(); } } // namespace ash
#define _CRT_SECURE_NO_WARNINGS #pragma warning(disable: 4819) #include <pcl/console/parse.h> #include <pcl/io/ply_io.h> #include "rabv.hpp" enum class Mode { rab, pcd, ply }; int main(int argc, char* argv[]) { std::cout << "Rab Visualizer ver.3.00-rc1" << std::endl << "Copyright (C) 2015-2017 Chiba Naoya" << std::endl; Mode mode = Mode::rab; // read argument std::vector<int> filenames; filenames = pcl::console::parse_file_extension_argument(argc, argv, ".rab"); if (filenames.size() < 1) { mode = Mode::pcd; filenames = pcl::console::parse_file_extension_argument(argc, argv, ".pcd"); if (filenames.size() < 1) { mode = Mode::ply; filenames = pcl::console::parse_file_extension_argument(argc, argv, ".ply"); if (filenames.size() < 1) { std::cerr << "[Rab Visualizer] File name is not found." << std::endl << "Usage: " << argv[0] << " [loadfile.rab | loadfile.pcd | loadfile.ply]" << std::endl; exit(-1); } } } if (mode == Mode::rab) { const auto& reader = rabv::Reader::create(argv[filenames[0]]); const auto& viewer = reader->visualize(boost::filesystem::path(argv[filenames[0]]).stem().string()); viewer->spinLoop(); } else { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>()); auto rab = rabv::Rab::create(); if (mode == Mode::pcd) { if (pcl::io::loadPCDFile(argv[filenames[0]], *cloud) == -1) { std::cerr << "[Rab Visualizer] PCD file io error." << std::endl; } } if (mode == Mode::ply) { if (pcl::io::loadPLYFile(argv[filenames[0]], *cloud) == -1) { std::cerr << "[Rab Visualizer] PLY file io error." << std::endl; } } if (cloud->size() > 0) { rab->addCloud("cloud", cloud); } const auto viewer = rabv::Viewer::create("Viewer", rab); viewer->spinLoop(); } return 0; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =========================================================================== // File: CEELOAD.INL // // // CEELOAD.INL has inline methods from CEELOAD.H. // =========================================================================== #ifndef CEELOAD_INL_ #define CEELOAD_INL_ template<typename TYPE> inline TYPE LookupMap<TYPE>::GetValueAt(PTR_TADDR pValue, TADDR* pFlags, TADDR supportedFlags) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; TYPE value = RelativePointer<TYPE>::GetValueMaybeNullAtPtr(dac_cast<TADDR>(pValue)); if (pFlags) *pFlags = dac_cast<TADDR>(value) & supportedFlags; return (TYPE)(dac_cast<TADDR>(value) & ~supportedFlags); } #ifndef DACCESS_COMPILE template<typename TYPE> inline void LookupMap<TYPE>::SetValueAt(PTR_TADDR pValue, TYPE value, TADDR flags) { WRAPPER_NO_CONTRACT; value = (TYPE)(dac_cast<TADDR>(value) | flags); RelativePointer<TYPE> *pRelPtr = (RelativePointer<TYPE> *)pValue; pRelPtr->SetValue(value); } // // Specialization of Get/SetValueAt methods to support maps of pointer-sized value types // template<> inline SIZE_T LookupMap<SIZE_T>::GetValueAt(PTR_TADDR pValue, TADDR* pFlags, TADDR supportedFlags) { WRAPPER_NO_CONTRACT; TADDR value = *pValue; if (pFlags) *pFlags = value & supportedFlags; return (value & ~supportedFlags); } template<> inline void LookupMap<SIZE_T>::SetValueAt(PTR_TADDR pValue, SIZE_T value, TADDR flags) { WRAPPER_NO_CONTRACT; *pValue = value | flags; } #endif // DACCESS_COMPILE // // Specialization of GetValueAt methods for tables with cross-module references // template<> inline PTR_TypeRef LookupMap<PTR_TypeRef>::GetValueAt(PTR_TADDR pValue, TADDR* pFlags, TADDR supportedFlags) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; // Strip flags before RelativeFixupPointer dereference TADDR value = *pValue; TADDR flags = (value & supportedFlags); value -= flags; value = ((RelativeFixupPointer<TADDR>&)(value)).GetValueMaybeNull(dac_cast<TADDR>(pValue)); if (pFlags) *pFlags = flags; return dac_cast<PTR_TypeRef>(value); } template<> inline PTR_Module LookupMap<PTR_Module>::GetValueAt(PTR_TADDR pValue, TADDR* pFlags, TADDR supportedFlags) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; // Strip flags before RelativeFixupPointer dereference TADDR value = *pValue; TADDR flags = (value & supportedFlags); value -= flags; value = ((RelativeFixupPointer<TADDR>&)(value)).GetValueMaybeNull(dac_cast<TADDR>(pValue)); if (pFlags) *pFlags = flags; return dac_cast<PTR_Module>(value); } template<> inline PTR_MemberRef LookupMap<PTR_MemberRef>::GetValueAt(PTR_TADDR pValue, TADDR* pFlags, TADDR supportedFlags) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; // Strip flags before RelativeFixupPointer dereference TADDR value = *pValue; TADDR flags = (value & supportedFlags); value -= flags; value = ((RelativeFixupPointer<TADDR>&)(value)).GetValueMaybeNull(dac_cast<TADDR>(pValue)); if (pFlags) *pFlags = flags; return dac_cast<PTR_MemberRef>(value); } // Retrieve the value associated with a rid template<typename TYPE> TYPE LookupMap<TYPE>::GetElement(DWORD rid, TADDR* pFlags) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; #ifdef FEATURE_PREJIT if (MapIsCompressed()) { // Can't access compressed entries directly: we need to go through the special helper. However we // must still check the hot cache first (this would normally be done by GetElementPtr() below, but // we can't integrate compressed support there since compressed entries don't have addresses, at // least not byte-aligned ones). PTR_TADDR pHotItemValue = FindHotItemValuePtr(rid); if (pHotItemValue) return GetValueAt(pHotItemValue, pFlags, supportedFlags); TADDR value = GetValueFromCompressedMap(rid); if (value == NULL) { if ((pNext == NULL) || (rid < dwCount)) { if (pFlags) *pFlags = NULL; return NULL; } return dac_cast<DPTR(LookupMap)>(pNext)->GetElement(rid - dwCount, pFlags); } if (pFlags) *pFlags = (value & supportedFlags); return (TYPE)(value & ~supportedFlags); } #endif // FEATURE_PREJIT PTR_TADDR pElement = GetElementPtr(rid); return (pElement != NULL) ? GetValueAt(pElement, pFlags, supportedFlags) : NULL; } // Stores an association in a map that has been previously grown to // the required size. Will never throw or fail. template<typename TYPE> void LookupMap<TYPE>::SetElement(DWORD rid, TYPE value, TADDR flags) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; BOOL fSuccess; fSuccess = TrySetElement(rid, value, flags); _ASSERTE(fSuccess); } #ifndef DACCESS_COMPILE // Try to store an association in a map. Will never throw or fail. template<typename TYPE> BOOL LookupMap<TYPE>::TrySetElement(DWORD rid, TYPE value, TADDR flags) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; PTR_TADDR pElement = GetElementPtr(rid); if (pElement == NULL) return FALSE; #ifdef _DEBUG // Once set, the values in LookupMap should be immutable. TADDR oldFlags; TYPE oldValue = GetValueAt(pElement, &oldFlags, supportedFlags); _ASSERTE(oldValue == NULL || (oldValue == value && oldFlags == flags)); #endif // Avoid unnecessary writes - do not overwrite existing value if (*pElement == NULL) { SetValueAt(pElement, value, flags); } return TRUE; } // Stores an association in a map. Grows the map as necessary. template<typename TYPE> void LookupMap<TYPE>::AddElement(Module * pModule, DWORD rid, TYPE value, TADDR flags) { CONTRACTL { INSTANCE_CHECK; PRECONDITION(CheckPointer(pModule)); THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(ThrowOutOfMemory();); } CONTRACTL_END; PTR_TADDR pElement = GetElementPtr(rid); if (pElement == NULL) pElement = GrowMap(pModule, rid); #ifdef _DEBUG // Once set, the values in LookupMap should be immutable. TADDR oldFlags; TYPE oldValue = GetValueAt(pElement, &oldFlags, supportedFlags); _ASSERTE(oldValue == NULL || (oldValue == value && oldFlags == flags)); #endif // Avoid unnecessary writes - do not overwrite existing value if (*pElement == NULL) { SetValueAt(pElement, value, flags); } } // Ensures that the map has space for this element template<typename TYPE> inline void LookupMap<TYPE>::EnsureElementCanBeStored(Module * pModule, DWORD rid) { CONTRACTL { INSTANCE_CHECK; PRECONDITION(CheckPointer(pModule)); THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(ThrowOutOfMemory();); } CONTRACTL_END; #ifdef FEATURE_PREJIT // don't attempt to call GetElementPtr for rids inside the compressed portion of // a multi-node map if (MapIsCompressed() && rid < dwCount) return; #endif PTR_TADDR pElement = GetElementPtr(rid); if (pElement == NULL) GrowMap(pModule, rid); } #endif // DACCESS_COMPILE // Find the given value in the table and return its RID template<typename TYPE> DWORD LookupMap<TYPE>::Find(TYPE value, TADDR* pFlags) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; Iterator it(this); DWORD rid = 0; while (it.Next()) { TADDR flags; if (it.GetElementAndFlags(&flags) == value && (!pFlags || *pFlags == flags)) return rid; rid++; } return 0; } template<typename TYPE> inline LookupMap<TYPE>::Iterator::Iterator(LookupMap* map) { LIMITED_METHOD_DAC_CONTRACT; m_map = map; m_index = (DWORD) -1; #ifdef FEATURE_PREJIT // Compressed map support m_currentEntry = 0; if (map->pTable != NULL) m_tableStream = BitStreamReader(dac_cast<PTR_CBYTE>(map->pTable)); #endif // FEATURE_PREJIT } template<typename TYPE> inline BOOL LookupMap<TYPE>::Iterator::Next() { LIMITED_METHOD_DAC_CONTRACT; if (!m_map || !m_map->pTable) { return FALSE; } m_index++; if (m_index == m_map->dwCount) { m_map = dac_cast<DPTR(LookupMap)>(m_map->pNext); if (!m_map || !m_map->pTable) { return FALSE; } m_index = 0; } #ifdef FEATURE_PREJIT // For a compressed map we need to read the encoded delta for the next entry and apply it to our previous // value to obtain the new current value. if (m_map->MapIsCompressed()) m_currentEntry = m_map->GetNextCompressedEntry(&m_tableStream, m_currentEntry); #endif // FEATURE_PREJIT return TRUE; } template<typename TYPE> inline TYPE LookupMap<TYPE>::Iterator::GetElement(TADDR* pFlags) { SUPPORTS_DAC; WRAPPER_NO_CONTRACT; #ifdef FEATURE_PREJIT // The current value for a compressed map is actually a map-based RVA. A zero RVA indicates a NULL pointer // but otherwise we can recover the full pointer by adding the address of the map we're iterating. // Note that most LookupMaps are embedded structures (in Module) so we can't directly dac_cast<TADDR> our // "this" pointer for DAC builds. Instead we have to use the slightly slower (in DAC) but more flexible // PTR_HOST_INT_TO_TADDR() which copes with interior host pointers. if (m_map->MapIsCompressed()) { TADDR value = m_currentEntry ? PTR_HOST_INT_TO_TADDR(m_map) + m_currentEntry : 0; if (pFlags) *pFlags = (value & m_map->supportedFlags); return (TYPE)(value & ~m_map->supportedFlags); } else #endif // FEATURE_PREJIT return GetValueAt(m_map->GetIndexPtr(m_index), pFlags, m_map->supportedFlags); } inline PTR_Assembly Module::GetAssembly() const { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; return m_pAssembly; } inline MethodDesc *Module::LookupMethodDef(mdMethodDef token) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END _ASSERTE(TypeFromToken(token) == mdtMethodDef); g_IBCLogger.LogRidMapAccess( MakePair( this, token ) ); return m_MethodDefToDescMap.GetElement(RidFromToken(token)); } inline MethodDesc *Module::LookupMemberRefAsMethod(mdMemberRef token) { LIMITED_METHOD_DAC_CONTRACT; _ASSERTE(TypeFromToken(token) == mdtMemberRef); g_IBCLogger.LogRidMapAccess( MakePair( this, token ) ); BOOL flags = FALSE; PTR_MemberRef pMemberRef = m_pMemberRefToDescHashTable->GetValue(token, &flags); return flags ? dac_cast<PTR_MethodDesc>(pMemberRef) : NULL; } inline Assembly *Module::LookupAssemblyRef(mdAssemblyRef token) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; _ASSERTE(TypeFromToken(token) == mdtAssemblyRef); PTR_Module module= m_ManifestModuleReferencesMap.GetElement(RidFromToken(token)); return module?module->GetAssembly():NULL; } #ifndef DACCESS_COMPILE inline void Module::ForceStoreAssemblyRef(mdAssemblyRef token, Assembly *value) { WRAPPER_NO_CONTRACT; // THROWS/GC_NOTRIGGER/INJECT_FAULT()/MODE_ANY _ASSERTE(value->GetManifestModule()); _ASSERTE(TypeFromToken(token) == mdtAssemblyRef); m_ManifestModuleReferencesMap.AddElement(this, RidFromToken(token), value->GetManifestModule()); } inline void Module::StoreAssemblyRef(mdAssemblyRef token, Assembly *value) { WRAPPER_NO_CONTRACT; _ASSERTE(value->GetManifestModule()); _ASSERTE(TypeFromToken(token) == mdtAssemblyRef); m_ManifestModuleReferencesMap.TrySetElement(RidFromToken(token), value->GetManifestModule()); } inline mdAssemblyRef Module::FindAssemblyRef(Assembly *targetAssembly) { WRAPPER_NO_CONTRACT; return m_ManifestModuleReferencesMap.Find(targetAssembly->GetManifestModule()) | mdtAssemblyRef; } #endif //DACCESS_COMPILE FORCEINLINE PTR_DomainLocalModule Module::GetDomainLocalModule() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return m_ModuleID; } #include "nibblestream.h" FORCEINLINE BOOL Module::FixupDelayList(TADDR pFixupList, BOOL mayUsePrecompiledNDirectMethods) { WRAPPER_NO_CONTRACT; COUNT_T nImportSections; PTR_CORCOMPILE_IMPORT_SECTION pImportSections = GetImportSections(&nImportSections); return FixupDelayListAux(pFixupList, this, &Module::FixupNativeEntry, pImportSections, nImportSections, GetNativeOrReadyToRunImage(), mayUsePrecompiledNDirectMethods); } template<typename Ptr, typename FixupNativeEntryCallback> BOOL Module::FixupDelayListAux(TADDR pFixupList, Ptr pThis, FixupNativeEntryCallback pfnCB, PTR_CORCOMPILE_IMPORT_SECTION pImportSections, COUNT_T nImportSections, PEDecoder * pNativeImage, BOOL mayUsePrecompiledNDirectMethods) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; PRECONDITION(pFixupList != NULL); } CONTRACTL_END; // Fixup Encoding: // ============== // // The fixup list is sorted in tables. Within each table, the fixups are a // sorted list of INDEXes. The first INDEX in each table is encoded entirely, // but the remaining INDEXes store only the delta increment from the previous INDEX. // The encoding/compression is done by ZapperModule::CompressFixupList(). // //------------------------------------------------------------------------- // Here is the detailed description : // // The first entry stores the m_pFixupBlob table index. // // The next entry stores the INDEX into the particular table. // An "entry" can be one or more nibbles. 3 bits of a nibble are used // to store the value, and the top bit indicates if the following nibble // contains rest of the value. If the top bit is not set, then this // nibble is the last part of the value. // // If the next entry is non-0, it is another (delta-encoded relative to the // previous INDEX) INDEX belonging to the same table. If the next entry is 0, // it indicates that all INDEXes in this table are done. // // When the fixups for the previous table is done, there is entry to // indicate the next table (delta-encoded relative to the previous table). // If the entry is 0, then it is the end of the entire fixup list. // //------------------------------------------------------------------------- // This is what the fixup list looks like: // // CorCompileTokenTable index // absolute INDEX // INDEX delta // ... // INDEX delta // 0 // CorCompileTokenTable index delta // absolute INDEX // INDEX delta // ... // INDEX delta // 0 // CorCompileTokenTable index delta // absolute INDEX // INDEX delta // ... // INDEX delta // 0 // 0 // // NibbleReader reader(PTR_BYTE(pFixupList), (SIZE_T)-1); // // The fixups are sorted by the sections they point to. // Walk the set of fixups in every sections // DWORD curTableIndex = reader.ReadEncodedU32(); while (TRUE) { // Get the correct section to work with. This is stored in the first two nibbles (first byte) _ASSERTE(curTableIndex < nImportSections); PTR_CORCOMPILE_IMPORT_SECTION pImportSection = pImportSections + curTableIndex; COUNT_T cbData; TADDR pData = pNativeImage->GetDirectoryData(&pImportSection->Section, &cbData); // Now iterate thru the fixup entries SIZE_T fixupIndex = reader.ReadEncodedU32(); // Accumulate the real rva from the delta encoded rva while (TRUE) { CONSISTENCY_CHECK(fixupIndex * sizeof(TADDR) < cbData); if (!(pThis->*pfnCB)(pImportSection, fixupIndex, dac_cast<PTR_SIZE_T>(pData + fixupIndex * sizeof(TADDR)), mayUsePrecompiledNDirectMethods)) return FALSE; int delta = reader.ReadEncodedU32(); // Delta of 0 means end of entries in this table if (delta == 0) break; fixupIndex += delta; } unsigned tableIndex = reader.ReadEncodedU32(); if (tableIndex == 0) break; curTableIndex = curTableIndex + tableIndex; } // Done with all entries in this table return TRUE; } inline PTR_LoaderAllocator Module::GetLoaderAllocator() { LIMITED_METHOD_DAC_CONTRACT; return GetAssembly()->GetLoaderAllocator(); } inline MethodTable* Module::GetDynamicClassMT(DWORD dynamicClassID) { LIMITED_METHOD_CONTRACT; _ASSERTE(m_cDynamicEntries > dynamicClassID); return m_pDynamicStaticsInfo[dynamicClassID].pEnclosingMT; } #ifdef FEATURE_CODE_VERSIONING inline CodeVersionManager * Module::GetCodeVersionManager() { LIMITED_METHOD_CONTRACT; return GetDomain()->GetCodeVersionManager(); } #endif // FEATURE_CODE_VERSIONING #endif // CEELOAD_INL_
/* Copyright 2020 The OneFlow Authors. 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. */ #include "oneflow/api/python/functional/value_types.h" #include "oneflow/core/common/throw.h" #include "oneflow/core/common/hash_container.h" namespace oneflow { namespace one { namespace functional { HashMap<ValueType, std::string>* GetValueTypeNameMap() { static HashMap<ValueType, std::string> value_type_name_map = { {kVOID, "void"}, {kINT32, "int32"}, {kUINT32, "unsigned int32"}, {kINT64, "int64"}, {kUINT64, "unsigned int64"}, {kFLOAT, "float"}, {kDOUBLE, "double"}, {kBOOL, "bool"}, {kSTRING, "string"}, {kINT32_LIST, "int32 list"}, {kUINT32_LIST, "unsigned int32 list"}, {kINT64_LIST, "int64 list"}, {kUINT64_LIST, "unsigned int64 list"}, {kFLOAT_LIST, "float list"}, {kDOUBLE_LIST, "double list"}, {kDOUBLE_LIST, "bool list"}, {kSTRING_LIST, "string list"}, {kVOID_MAYBE, "maybe void"}, {kBOOL_MAYBE, "maybe bool"}, {kSCALAR, "scalar"}, {kTENSOR, "tensor"}, {kTENSOR_REF, "tensor"}, {kTENSOR_MAYBE, "maybe tensor"}, {kTENSOR_TUPLE, "tensor tuple"}, {kTENSOR_TUPLE_REF, "tensor tuple"}, {kTENSOR_TUPLE_MAYBE, "maybe tensor tuple"}, {kATTR, "attr"}, {kATTR_REF, "attr"}, {kDTYPE, "data type"}, {kDTYPE_LIST, "data type list"}, {kSHAPE, "shape"}, {kSHAPE_LIST, "shape list"}, {kGENERATOR, "generator"}, {kGENERATOR_REF, "generator"}, {kGENERATOR_MAYBE, "maybe generator"}, {kTENSOR_INDEX, "index"}, {kDEVICE, "device"}, {kPARALLEL_DESC, "placement"}, {kSBP_PARALLEL, "sbp"}, {kSBP_PARALLEL_LIST, "sbp list"}, {kOPEXPR, "opexpr"}, {kOPEXPR_REF, "opexpr"}, {kPY_OBJECT, "python object"}, }; return &value_type_name_map; } const std::string& ValueTypeName(ValueType type) { const auto* type_name_map = GetValueTypeNameMap(); const auto& it = type_name_map->find(type); CHECK_OR_THROW(it != type_name_map->end()) << "Value type " << type << " has no type name."; return it->second; } bool IsIntegralType(ValueType type) { return type >= kINT32 && type < kINTEGRAL_MASK; } bool IsIntegralListType(ValueType type) { return type >= kINT32_LIST && type < kINTEGRAL_LIST_MASK; } bool IsFloatingType(ValueType type) { return type >= kFLOAT && type < kFLOATING_MASK; } bool IsFloatingListType(ValueType type) { return type >= kFLOAT_LIST && type < kFLOATING_LIST_MASK; } } // namespace functional } // namespace one } // namespace oneflow
#include "Surface.h" #include <stdexcept> // Constructor Surface::Surface(const Instance* instance, const PhysicalDevice* physicalDevice, Window* window) : m_Instance(instance), m_PhysicalDevice(physicalDevice), m_Window(window) { // Create window surface if (m_Window->CreateSurface(m_Instance->GetInstance(), nullptr, &m_Surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create window surface!"); } // Get surface capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_PhysicalDevice->GetPhysicalDevice(), m_Surface, &m_Capabilities); // Query formats uint32_t formatCount; std::vector<VkSurfaceFormatKHR> formats; vkGetPhysicalDeviceSurfaceFormatsKHR(m_PhysicalDevice->GetPhysicalDevice(), m_Surface, &formatCount, nullptr); if (formatCount != 0) { formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(m_PhysicalDevice->GetPhysicalDevice(), m_Surface, &formatCount, formats.data()); } // Select format by looping through available formats for (const auto& format : formats) { if (format.format == VK_FORMAT_B8G8R8A8_UNORM && format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { m_Format = format; break; } } if (!m_Format.format) { m_Format = formats[0]; } // Query present modes uint32_t presentModeCount; std::vector<VkPresentModeKHR> presentModes; vkGetPhysicalDeviceSurfacePresentModesKHR(m_PhysicalDevice->GetPhysicalDevice(), m_Surface, &presentModeCount, nullptr); if (presentModeCount != 0) { presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(m_PhysicalDevice->GetPhysicalDevice(), m_Surface, &presentModeCount, presentModes.data()); } // Choose present mode for (const auto& presentMode : presentModes) { if (presentMode == VK_PRESENT_MODE_MAILBOX_KHR) { m_PresentMode = presentMode; break; } } if (!m_PresentMode) { m_PresentMode = VK_PRESENT_MODE_FIFO_KHR; } } // Destructor Surface::~Surface() { }
/* * Copyright (c) 2019-2021, NVIDIA CORPORATION. * * 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. */ #include <cudf/strings/convert/convert_floats.hpp> #include <cudf/strings/strings_column_view.hpp> #include <tests/strings/utilities.h> #include <cudf_test/base_fixture.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <vector> struct StringsConvertTest : public cudf::test::BaseFixture { }; TEST_F(StringsConvertTest, IsFloat) { cudf::test::strings_column_wrapper strings; auto strings_view = cudf::strings_column_view(strings); auto results = cudf::strings::is_float(strings_view); EXPECT_EQ(cudf::type_id::BOOL8, results->view().type().id()); EXPECT_EQ(0, results->view().size()); cudf::test::strings_column_wrapper strings1({"+175", "-9.8", "7+2", "+-4", "6.7e17", "-1.2e-5", "e", ".e", "1.e+-2", "00.00", "1.0e+1.0", "1.2.3", "+", "--", ""}); results = cudf::strings::is_float(cudf::strings_column_view(strings1)); cudf::test::fixed_width_column_wrapper<bool> expected1( {1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected1); cudf::test::strings_column_wrapper strings2( {"+175", "-34", "9.8", "1234567890", "6.7e17", "-917.2e5"}); results = cudf::strings::is_float(cudf::strings_column_view(strings2)); cudf::test::fixed_width_column_wrapper<bool> expected2({1, 1, 1, 1, 1, 1}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(*results, expected2); } TEST_F(StringsConvertTest, ToFloats32) { std::vector<const char*> h_strings{"1234", nullptr, "-876", "543.2", "-0.12", ".25", "-.002", "", "-0.0", "1.2e4", "NaN", "abc123", "123abc", "456e", "-1.78e+5", "-122.33644782123456789", "12e+309", "3.4028236E38"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<float> h_expected; std::for_each(h_strings.begin(), h_strings.end(), [&](const char* str) { h_expected.push_back(str ? std::atof(str) : 0); }); auto strings_view = cudf::strings_column_view(strings); auto results = cudf::strings::to_floats(strings_view, cudf::data_type{cudf::type_id::FLOAT32}); cudf::test::fixed_width_column_wrapper<float> expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, true); } TEST_F(StringsConvertTest, FromFloats32) { std::vector<float> h_floats{100, 654321.25, -12761.125, 0, 5, -4, std::numeric_limits<float>::quiet_NaN(), 839542223232.79, -0.0}; std::vector<const char*> h_expected{ "100.0", "654321.25", "-12761.125", "0.0", "5.0", "-4.0", "NaN", "8.395422433e+11", "-0.0"}; cudf::test::fixed_width_column_wrapper<float> floats( h_floats.begin(), h_floats.end(), thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; })); auto results = cudf::strings::from_floats(floats); cudf::test::strings_column_wrapper expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; })); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, true); } TEST_F(StringsConvertTest, ToFloats64) { std::vector<const char*> h_strings{"1234", nullptr, "-876", "543.2", "-0.12", ".25", "-.002", "", "-0.0", "1.28e256", "NaN", "abc123", "123abc", "456e", "-1.78e+5", "-122.33644782", "12e+309", "1.7976931348623159E308"}; cudf::test::strings_column_wrapper strings( h_strings.begin(), h_strings.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); std::vector<double> h_expected; std::for_each(h_strings.begin(), h_strings.end(), [&](const char* str) { h_expected.push_back(str ? std::atof(str) : 0); }); auto strings_view = cudf::strings_column_view(strings); auto results = cudf::strings::to_floats(strings_view, cudf::data_type{cudf::type_id::FLOAT64}); cudf::test::fixed_width_column_wrapper<double> expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator(h_strings.begin(), [](auto str) { return str != nullptr; })); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, true); } TEST_F(StringsConvertTest, FromFloats64) { std::vector<double> h_floats{100, 654321.25, -12761.125, 0, 5, -4, std::numeric_limits<double>::quiet_NaN(), 839542223232.794248339, -0.0}; std::vector<const char*> h_expected{ "100.0", "654321.25", "-12761.125", "0.0", "5.0", "-4.0", "NaN", "8.395422232e+11", "-0.0"}; cudf::test::fixed_width_column_wrapper<double> floats( h_floats.begin(), h_floats.end(), thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; })); auto results = cudf::strings::from_floats(floats); cudf::test::strings_column_wrapper expected( h_expected.begin(), h_expected.end(), thrust::make_transform_iterator(h_expected.begin(), [](auto str) { return str != nullptr; })); CUDF_TEST_EXPECT_COLUMNS_EQUIVALENT(*results, expected, true); } TEST_F(StringsConvertTest, ZeroSizeStringsColumnFloat) { cudf::column_view zero_size_column( cudf::data_type{cudf::type_id::FLOAT32}, 0, nullptr, nullptr, 0); auto results = cudf::strings::from_floats(zero_size_column); cudf::test::expect_strings_empty(results->view()); } TEST_F(StringsConvertTest, ZeroSizeFloatsColumn) { cudf::column_view zero_size_column( cudf::data_type{cudf::type_id::STRING}, 0, nullptr, nullptr, 0); auto results = cudf::strings::to_floats(zero_size_column, cudf::data_type{cudf::type_id::FLOAT32}); EXPECT_EQ(0, results->size()); } TEST_F(StringsConvertTest, FromToFloatsError) { auto dtype = cudf::data_type{cudf::type_id::INT32}; auto column = cudf::make_numeric_column(dtype, 100); EXPECT_THROW(cudf::strings::from_floats(column->view()), cudf::logic_error); cudf::test::strings_column_wrapper strings{"this string intentionally left blank"}; EXPECT_THROW(cudf::strings::to_floats(column->view(), dtype), cudf::logic_error); }
/* Copyright 2018 The TensorFlow Authors. 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. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/tests/ptx_codegen_test.h" #include "tensorflow/compiler/xla/service/gpu/gpu_executable.h" #include "tensorflow/compiler/xla/tests/filecheck.h" namespace xla { namespace gpu { void PtxCodegenTest::CompileAndVerifyPtx(std::unique_ptr<HloModule> hlo_module, const string& pattern) { std::unique_ptr<Executable> executable = std::move(CompileToExecutable(std::move(hlo_module)).ValueOrDie()); string ptx_str(static_cast<GpuExecutable*>(executable.get())->ptx()); StatusOr<bool> filecheck_result = RunFileCheck(ptx_str, pattern); ASSERT_TRUE(filecheck_result.ok()); EXPECT_TRUE(filecheck_result.ValueOrDie()); } } // namespace gpu } // namespace xla
// See LICENSE_CELLO file for license and copyright information /// @file control_stopping.cpp /// @author James Bordner (jobordner@ucsd.edu) /// @date 2013-04-26 /// @brief Charm-related functions associated with initialization /// @ingroup Control /// /// STOPPING /// /// Block::stopping() /// update_boundary_() /// compute dt /// compute stopping /// contribute( >>>>> Block::r_output() >>>>> ) #include "simulation.hpp" #include "mesh.hpp" #include "control.hpp" #include "charm_simulation.hpp" #include "charm_mesh.hpp" // #define DEBUG_STOPPING #ifdef DEBUG_STOPPING # define TRACE_STOPPING(A) \ CkPrintf ("%d %s:%d %s TRACE %s\n", \ CkMyPe(),__FILE__,__LINE__,name_.c_str(),A); \ fflush(stdout); #else # define TRACE_STOPPING(A) ; #endif //---------------------------------------------------------------------- void Block::stopping_enter_() { stopping_begin_(); } //---------------------------------------------------------------------- void Block::stopping_begin_() { TRACE_STOPPING("Block::stopping_begin_"); Simulation * simulation = cello::simulation(); simulation->set_phase(phase_stopping); int stopping_interval = simulation->config()->stopping_interval; bool stopping_reduce = stopping_interval ? ((cycle_ % stopping_interval) == 0) : false; if (stopping_reduce || dt_==0.0) { // Compute local dt Problem * problem = simulation->problem(); int index = 0; Method * method; double dt_block = std::numeric_limits<double>::max(); while ((method = problem->method(index++))) { dt_block = std::min(dt_block,method->timestep(this)); } // Reduce timestep to coincide with scheduled output if needed int index_output=0; while (Output * output = problem->output(index_output++)) { Schedule * schedule = output->schedule(); dt_block = schedule->update_timestep(time_,dt_block); } // Reduce timestep to not overshoot final time from stopping criteria Stopping * stopping = problem->stopping(); double time_stop = stopping->stop_time(); double time_curr = time_; dt_block = MIN (dt_block, (time_stop - time_curr)); // Evaluate local stopping criteria int stop_block = stopping->complete(cycle_,time_); // Reduce to find Block array minimum dt and stopping criteria double min_reduce[2]; min_reduce[0] = dt_block; min_reduce[1] = stop_block ? 1.0 : 0.0; CkCallback callback (CkIndex_Block::r_stopping_compute_timestep(NULL), thisProxy); #ifdef TRACE_CONTRIBUTE CkPrintf ("%s %s:%d DEBUG_CONTRIBUTE\n", name().c_str(),__FILE__,__LINE__); fflush(stdout); #endif contribute(2*sizeof(double), min_reduce, CkReduction::min_double, callback); } else { stopping_balance_(); } } //---------------------------------------------------------------------- void Block::r_stopping_compute_timestep(CkReductionMsg * msg) { performance_start_(perf_stopping); TRACE_STOPPING("Block::r_stopping_compute_timestep"); ++age_; double * min_reduce = (double * )msg->getData(); dt_ = min_reduce[0]; stop_ = min_reduce[1] == 1.0 ? true : false; delete msg; Simulation * simulation = cello::simulation(); dt_ *= Method::courant_global; set_dt (dt_); set_stop (stop_); simulation->set_dt(dt_); simulation->set_stop(stop_); #ifdef CONFIG_USE_PROJECTIONS // COMMENTED OUT--BUGGY, projections_schedule_on() crashed with bad schedule_on object bool was_off = (simulation->projections_tracing() == false); bool was_on = (simulation->projections_tracing() == true); Schedule * schedule_on = simulation->projections_schedule_on(); Schedule * schedule_off = simulation->projections_schedule_off(); bool turn_on = schedule_on ? schedule_on->write_this_cycle(cycle_,time_) : false; bool turn_off = schedule_off ? schedule_off->write_this_cycle(cycle_,time_) : false; static bool active = false; if (!active && turn_on) { active = true; simulation->monitor()->print ("Performance","turning projections logging ON\n"); simulation->set_projections_tracing(true); traceBegin(); } else if (active && turn_off) { active = false; simulation->monitor()->print ("Performance","turning projections logging OFF\n"); simulation->set_projections_tracing(false); traceEnd(); } #endif stopping_balance_(); performance_stop_(perf_stopping); } //---------------------------------------------------------------------- void Block::stopping_balance_() { TRACE_STOPPING("Block::stopping_balance_"); Schedule * schedule = cello::simulation()->schedule_balance(); bool do_balance = (schedule && schedule->write_this_cycle(cycle_,time_)); if (do_balance) { if (index_.is_root()) cello::monitor()->print ("Balance","staring load balance step"); control_sync_quiescence (CkIndex_Main::p_stopping_balance()); } else { stopping_exit_(); } } //---------------------------------------------------------------------- void Block::p_stopping_balance() { performance_start_(perf_stopping); TRACE_STOPPING("Block::p_stopping_balance"); cello::simulation()->set_phase (phase_balance); // Monitor * monitor = simulation()->monitor(); // int mode_saved = monitor->mode(); // monitor->set_mode(monitor_mode_all); // if (index().is_root()) monitor->print ("Balance","BEGIN"); // monitor->set_mode(mode_saved); AtSync(); performance_stop_(perf_stopping); } //---------------------------------------------------------------------- void Block::ResumeFromSync() { // Monitor * monitor = simulation()->monitor(); // int mode_saved = monitor->mode(); // monitor->set_mode(monitor_mode_all); // if (index().is_root()) monitor->print ("Balance","END"); // monitor->set_mode(mode_saved); TRACE_STOPPING("Block::balance_exit"); if (index_.is_root()) { thisProxy.doneInserting(); } stopping_exit_(); } //---------------------------------------------------------------------- void Block::exit_() { TRACE_STOPPING("Block::exit_"); const int in = cello::index_static(); if (index().is_root()) { if (MsgRefresh::counter[in] != 0) { CkPrintf ("%d Block::exit_() MsgRefresh::counter = %ld != 0\n", CkMyPe(),MsgRefresh::counter[in]); } if (MsgRefine::counter[in] != 0) { CkPrintf ("%d Block::exit_() MsgRefine::counter = %ld != 0\n", CkMyPe(),MsgRefine::counter[in]); } if (MsgCoarsen::counter[in] != 0) { CkPrintf ("%d Block::exit_() MsgCoarsen::counter = %ld != 0\n", CkMyPe(),MsgCoarsen::counter[in]); } if (FieldFace::counter[in] != 0) { CkPrintf ("%d Block::exit_() FieldFace::counter = %ld != 0\n", CkMyPe(),FieldFace::counter[in]); } if (DataMsg::counter[in] != 0) { CkPrintf ("%d Block::exit_() DataMsg::counter = %ld != 0\n", CkMyPe(),DataMsg::counter[in]); CkPrintf ("%d Block::exit_() ParticleData::counter = %ld != 0\n", CkMyPe(),ParticleData::counter[in]); } } if (index_.is_root()) { proxy_main.p_exit(1); } }
/* * Copyright 2002-2005 The Apache Software Foundation. * * 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. */ /* * XSEC * * XSECNameSpaceHolder := Container class for holding and managing the name space stack * Used when running through a DOM document * * $Id: XSECNameSpaceExpander.hpp 351214 2005-02-03 13:58:14Z milan $ * */ #ifndef XSECNAMESPACEEXPANDER_HEADER #define XSECNAMESPACEEXPANDER_HEADER // XSEC Includes #include <xsec/framework/XSECDefs.hpp> #include <xsec/utils/XSECSafeBuffer.hpp> #include <xsec/utils/XSECSafeBufferFormatter.hpp> // Xerces Includes XSEC_DECLARE_XERCES_CLASS(DOMDocument); XSEC_DECLARE_XERCES_CLASS(DOMNode); XSEC_DECLARE_XERCES_CLASS(DOMElement); #include <vector> // -------------------------------------------------------------------------------- // Structure Definition for the nodes within the list of nodes // -------------------------------------------------------------------------------- struct XSECNameSpaceEntry { // Variables safeBuffer m_name; // The name for this name space XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * mp_node; // The Element Node owner XERCES_CPP_NAMESPACE_QUALIFIER DOMNode * mp_att; // The added attribute node }; // -------------------------------------------------------------------------------- // Class definition for the list // -------------------------------------------------------------------------------- /** * @ingroup pubsig */ /*\@{*/ /** * @brief Class to "expand" name spaces * * For most things, a DOM model interoperates well with XPath. Unfortunately, * name-spaces are the one main problem. In particular, the XPath spec * states that every element node has an attribute node for its own * namespaces, and one for namespaces above that are in scope. * * In the DOM scheme of things, a namespace is only available in the node in * which it is defined. Normally this is not a problem, you can just just * refer backwards until you find the namespace you need. However, for XPath * expressions that select namespace nodes, we need to actually promulgate * the name-spaces down to every node where they are visible so that the XPath * selection will work properly. * * This is important for Canonicalisation of the found nodes, but we cannot * do this only in the canonicaliser as it does not internally understand how * to do DSIG style XPath. So the XPath is done externally, and the * resultant node set (including any selected "Expanded" attribute nodes). * are passed in. * * The expander therefore handles the propogation of the namespace nodes, and * removes the propogated nodes when it goes out of scope (or when * deleteAddedNamespaces() is called). * */ class CANON_EXPORT XSECNameSpaceExpander { #if defined(XALAN_NO_NAMESPACES) typedef vector<XSECNameSpaceEntry *> NameSpaceEntryListVectorType; #else typedef std::vector<XSECNameSpaceEntry *> NameSpaceEntryListVectorType; #endif public: /** @name Constructors and Destructors */ //@{ /** * \brief Main constructure * * Use this constructor to expand namespaces through an entire document. * * @param d The DOM document to be expanded. */ XSECNameSpaceExpander(XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *d); // Constructor /** * \brief Fragment constructor * * Use this constructor to expand namespaces in a given fragment only. * @note The fragment does not need to be rooted in an actual document. * * @param f The starting element of the fragment to be expanded. */ XSECNameSpaceExpander(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *f); // frag Constructor ~XSECNameSpaceExpander(); // Default destructor //@} // Operate /** * \brief Expand namespaces. * * Perform the expansion operation and create a list of all added nodes. */ void expandNameSpaces(void); /** * \brief Collapse name-spaces * * Delete all namespaces added in exandNameSpaces() (using the list that * was created at that time */ void deleteAddedNamespaces(void); // Check if a node is an added node bool nodeWasAdded(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *n); private: // Functions XSECNameSpaceExpander(void); // No default constructor void recurse(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *n); // data NameSpaceEntryListVectorType m_lst; // List of added name spaces XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument * mp_doc; // The owner document XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * mp_fragment; // If we are doing a fragment bool m_expanded; // Have we expanded already? XSECSafeBufferFormatter * mp_formatter; }; #endif /* XSECNAMESPACEEXPANDER_HEADER */
/* * Rody Oldenhuis * oldenhuis@gmail.com * * ode.hh * Created: 16.11.2012 16:29:30 CET */ #ifndef _ODE_HH #define _ODE_HH #include "Matrix.hh" namespace ODE { // defines options for the integrator struct Options { double abstol, reltol, maxstep, initial_step; bool show_stats; // Which integrator will be used? enum integrator_t { // Runge-Kutta-Nystrom types (RKN) RKN1210, // Runge-Kutta types (RK) ODE86, ODE45 } integrator; // ------------------------------------ // Event functions // ------------------------------------ // options for event functions struct eventOpts_t { std::vector<unsigned int> eventSel; int8_t direction; bool isTerminal; }; eventOpts_t eventOpt; // vector of pair of event function/options std::vector< std::pair< // value, isterminal, direction std::tuple<double, bool, int8_t> (*)( const double &t, const Vector<> &y, // const Vector<> &dy, const eventOpts_t &opts), eventOpts_t> > eventFcns; // ------------------------------------ // Output functions // ------------------------------------ // options for output functions struct outputOpts_t { std::vector<unsigned int> outputSel; double refine; }; outputOpts_t outputOpt; // vector of pair of output function/options std::vector< std::pair< // halt bool (*)( const double &t, const Vector<> &y, // const Vector<> &dy, const std::string &type, const outputOpts_t &opts), // outputOpts_t> > outputFcns; // ------------------------------------ // Default options // ------------------------------------ // constructor sets default options Options() : abstol (1e-12) , reltol (1e-6) , maxstep (0) // 0 means full interval , initial_step (0) // 0 means use default , show_stats (false) , integrator (RKN1210) , eventOpt (eventOpts_t()) , eventFcns {} , outputOpt (outputOpts_t()) , outputFcns {} {} }; // defines an output structure containing // performance statistics of the integration struct Stats { unsigned int rejected_steps, accepted_steps, fevals; Vec step_size, delta; std::string message; // constructor sets defaults Stats() : rejected_steps(0) , accepted_steps(0) , fevals (0) , step_size (Vec()) , delta (Vec()) , message ("Integration not yet started.") {} }; // Call any type integrator void integrate( Vec (*dydt) ( const double /*t*/, const Vec &/*y*/), const Vec &y0, const Vec &tspan, const Options &opts, Vec &t, Vec &y, double &exitflag, Stats &output); } #endif
// Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. // There is only one repeated number in nums, return this repeated number. // You must solve the problem without modifying the array nums and uses only constant extra space. // Example 1: // Input: nums = [1,3,4,2,2] // Output: 2 // Example 2: // Input: nums = [3,1,3,4,2] // Output: 3 // Example 3: // Input: nums = [1,1] // Output: 1 // Example 4: // Input: nums = [1,1,2] // Output: 1 // Constraints: // 1 <= n <= 105 // nums.length == n + 1 // 1 <= nums[i] <= n // All the integers in nums appear only once except for precisely one integer which appears two or more times. // Two Pointers class Solution { public: int findDuplicate(vector<int>& nums) { int fast = nums[0], slow = nums[0]; do{ slow = nums[slow]; fast = nums[nums[fast]]; } while(slow!=fast); fast = nums[0]; while(fast!=slow){ slow = nums[slow]; fast = nums[fast]; } return slow; } }; // Hashing class Solution { public: int findDuplicate(vector<int>& nums) { map<int, int> m; for(auto num: nums){ m[num]++; if(m[num] > 1) return num; } return 0; } };
/** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * 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. */ #ifndef IROHA_SHARED_MODEL_SET_ACCOUNT_DETAIL_HPP #define IROHA_SHARED_MODEL_SET_ACCOUNT_DETAIL_HPP #ifndef DISABLE_BACKWARD #include "model/commands/set_account_detail.hpp" #endif #include "interfaces/base/primitive.hpp" #include "interfaces/common_objects/types.hpp" namespace shared_model { namespace interface { /** * Set key-value pair of given account */ class SetAccountDetail : public PRIMITIVE(SetAccountDetail) { public: /** * @return Identity of user to set account detail */ virtual const types::AccountIdType &accountId() const = 0; /// Type of detail key using AccountDetailKeyType = std::string; /** * @return key of data to store in the account */ virtual const AccountDetailKeyType &key() const = 0; /// Type of detail value using AccountDetailValueType = std::string; /** * @return detail value to store by given key */ virtual const AccountDetailValueType &value() const = 0; std::string toString() const override { return detail::PrettyStringBuilder() .init("SetAccountDetail") .append("account_id", accountId()) .append("key", key()) .append("value", value()) .finalize(); } #ifndef DISABLE_BACKWARD OldModelType *makeOldModel() const override { auto oldModel = new OldModelType; oldModel->account_id = accountId(); oldModel->key = key(); oldModel->value = value(); return oldModel; } #endif bool operator==(const ModelType &rhs) const override { return accountId() == rhs.accountId() and key() == rhs.key() and value() == rhs.value(); } }; } // namespace interface } // namespace shared_model #endif // IROHA_SHARED_MODEL_SET_ACCOUNT_DETAIL_HPP
// Copyright © 1996-2018, Valve Corporation, All rights reserved. #include "mathlib/ssemath.h" #include "mathlib/ssequaternion.h" const fltx4 Four_PointFives = {0.5, 0.5, 0.5, 0.5}; const fltx4 Four_Zeros = {0.0, 0.0, 0.0, 0.0}; const fltx4 Four_Ones = {1.0, 1.0, 1.0, 1.0}; const fltx4 Four_Twos = {2.0, 2.0, 2.0, 2.0}; const fltx4 Four_Threes = {3.0, 3.0, 3.0, 3.0}; const fltx4 Four_Fours = {4.0, 4.0, 4.0, 4.0}; const fltx4 Four_Origin = {0, 0, 0, 1}; const fltx4 Four_2ToThe21s = {(f32)(1 << 21), (f32)(1 << 21), (f32)(1 << 21), (f32)(1 << 21)}; const fltx4 Four_2ToThe22s = {(f32)(1 << 22), (f32)(1 << 22), (f32)(1 << 22), (f32)(1 << 22)}; const fltx4 Four_2ToThe23s = {(f32)(1 << 23), (f32)(1 << 23), (f32)(1 << 23), (f32)(1 << 23)}; const fltx4 Four_2ToThe24s = {(f32)(1 << 24), (f32)(1 << 24), (f32)(1 << 24), (f32)(1 << 24)}; const fltx4 Four_Point225s = {.225f, .225f, .225f, .225f}; const fltx4 Four_Epsilons = {FLT_EPSILON, FLT_EPSILON, FLT_EPSILON, FLT_EPSILON}; const fltx4 Four_FLT_MAX = {FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX}; const fltx4 Four_Negative_FLT_MAX = {-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX}; const fltx4 g_QuatMultRowSign[4] = {{1.0f, 1.0f, -1.0f, 1.0f}, {-1.0f, 1.0f, 1.0f, 1.0f}, {1.0f, -1.0f, 1.0f, 1.0f}, {-1.0f, -1.0f, -1.0f, 1.0f}}; const i32 alignas(16) g_SIMD_clear_signmask[4] = {0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff}; const i32 alignas(16) g_SIMD_signmask[4] = {0x80000000i32, 0x80000000i32, 0x80000000i32, 0x80000000i32}; const i32 alignas(16) g_SIMD_lsbmask[4] = {0xfffffffei32, 0xfffffffei32, 0xfffffffei32, 0xfffffffei32}; const i32 alignas(16) g_SIMD_clear_wmask[4] = {0xffffffffi32, 0xffffffffi32, 0xffffffffi32, 0}; const i32 alignas(16) g_SIMD_ComponentMask[4][4] = {{0xFFFFFFFFi32, 0, 0, 0}, {0, 0xFFFFFFFFi32, 0, 0}, {0, 0, 0xFFFFFFFFi32, 0}, {0, 0, 0, 0xFFFFFFFFi32}}; // FUNCTIONS // NOTE: WHY YOU **DO NOT** WANT TO PUT FUNCTIONS HERE // Generally speaking, you want to make sure SIMD math functions // are inlined, because that gives the compiler much more latitude // in instruction scheduling. It's not that the overhead of calling // the function is particularly great; rather, many of the SIMD // opcodes have long latencies, and if you have a sequence of // several dependent ones inside a function call, the latencies // stack up to create a big penalty. If the function is inlined, // the compiler can interleave its operations with ones from the // caller to better hide those latencies. Finally, on the 360, // putting parameters or return values on the stack, and then // reading them back within the next forty cycles, is a very // severe penalty. So, as much as possible, you want to leave your // data on the registers. // That said, there are certain occasions where it is appropriate // to call into functions -- particularly for very large blocks // of code that will spill most of the registers anyway. Unless your // function is more than one screen long, yours is probably not one // of those occasions. // You can use this to rotate a long array of FourVectors all by the same // matrix. The first parameter is the head of the array. The second is the // number of vectors to rotate. The third is the matrix. void FourVectors::RotateManyBy(FourVectors* SOURCE_RESTRICT pVectors, u32 numVectors, const matrix3x4_t& rotationMatrix) { Assert(numVectors > 0); if (numVectors == 0) return; // Splat out each of the entries in the matrix to a fltx4. Do this // in the order that we will need them, to hide latency. I'm // avoiding making an array of them, so that they'll remain in // registers. fltx4 matSplat00, matSplat01, matSplat02, matSplat10, matSplat11, matSplat12, matSplat20, matSplat21, matSplat22; { // Load the matrix into local vectors. Sadly, matrix3x4_ts are // often unaligned. The w components will be the tranpose row of // the matrix, but we don't really care about that. fltx4 matCol0 = LoadUnalignedSIMD(rotationMatrix[0]); fltx4 matCol1 = LoadUnalignedSIMD(rotationMatrix[1]); fltx4 matCol2 = LoadUnalignedSIMD(rotationMatrix[2]); matSplat00 = SplatXSIMD(matCol0); matSplat01 = SplatYSIMD(matCol0); matSplat02 = SplatZSIMD(matCol0); matSplat10 = SplatXSIMD(matCol1); matSplat11 = SplatYSIMD(matCol1); matSplat12 = SplatZSIMD(matCol1); matSplat20 = SplatXSIMD(matCol2); matSplat21 = SplatYSIMD(matCol2); matSplat22 = SplatZSIMD(matCol2); } // PC does not benefit from the unroll/scheduling above fltx4 outX0, outY0, outZ0; // bank one of outputs // Because of instruction latencies and scheduling, it's actually faster to // use adds and muls rather than madds. (Empirically determined by timing.) const FourVectors* stop = pVectors + numVectors; // perform an even number of iterations through this loop. while (pVectors < stop) { outX0 = MaddSIMD(pVectors->z, matSplat02, AddSIMD(MulSIMD(pVectors->x, matSplat00), MulSIMD(pVectors->y, matSplat01))); outY0 = MaddSIMD(pVectors->z, matSplat12, AddSIMD(MulSIMD(pVectors->x, matSplat10), MulSIMD(pVectors->y, matSplat11))); outZ0 = MaddSIMD(pVectors->z, matSplat22, AddSIMD(MulSIMD(pVectors->x, matSplat20), MulSIMD(pVectors->y, matSplat21))); pVectors->x = outX0; pVectors->y = outY0; pVectors->z = outZ0; pVectors++; } }
//------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // 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. // //------------------------------------------------------------------------------ #include "core/serializers/main_serializer.hpp" #include "ml/core/graph.hpp" #include "ml/layers/fully_connected.hpp" #include "ml/ops/placeholder.hpp" #include "ml/serializers/ml_types.hpp" #include "ml/utilities/graph_builder.hpp" #include "test_types.hpp" #include "gtest/gtest.h" namespace fetch { namespace ml { namespace test { template <typename T> class SerializersTestWithInt : public ::testing::Test { }; template <typename T> class SerializersTestNoInt : public ::testing::Test { }; TYPED_TEST_CASE(SerializersTestWithInt, math::test::TensorIntAndFloatingTypes); TYPED_TEST_CASE(SerializersTestNoInt, math::test::TensorFloatingTypes); TYPED_TEST(SerializersTestWithInt, serialize_empty_state_dict) { fetch::ml::StateDict<TypeParam> sd1; fetch::serializers::MsgPackSerializer b; b << sd1; b.seek(0); fetch::ml::StateDict<TypeParam> sd2; b >> sd2; EXPECT_EQ(sd1, sd2); } TYPED_TEST(SerializersTestNoInt, serialize_state_dict) { // Generate a plausible state dict out of a fully connected layer fetch::ml::layers::FullyConnected<TypeParam> fc(10, 10); struct fetch::ml::StateDict<TypeParam> sd1 = fc.StateDict(); fetch::serializers::MsgPackSerializer b; b << sd1; b.seek(0); fetch::ml::StateDict<TypeParam> sd2; b >> sd2; EXPECT_EQ(sd1, sd2); } TYPED_TEST(SerializersTestWithInt, serialize_empty_graph_saveable_params) { fetch::ml::GraphSaveableParams<TypeParam> gsp1; fetch::serializers::MsgPackSerializer b; b << gsp1; b.seek(0); fetch::ml::GraphSaveableParams<TypeParam> gsp2; b >> gsp2; EXPECT_EQ(gsp1.connections, gsp2.connections); EXPECT_EQ(gsp1.nodes, gsp2.nodes); } TYPED_TEST(SerializersTestNoInt, serialize_graph_saveable_params) { using TensorType = TypeParam; using DataType = typename TypeParam::Type; using GraphType = typename fetch::ml::Graph<TensorType>; fetch::ml::RegularisationType regulariser = fetch::ml::RegularisationType::L1; auto reg_rate = fetch::math::Type<DataType>("0.01"); // Prepare graph with fairly random architecture auto g = std::make_shared<GraphType>(); std::string input = g->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>("Input", {}); std::string label_name = g->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>("label", {}); std::string layer_1 = g->template AddNode<fetch::ml::layers::FullyConnected<TensorType>>( "FC1", {input}, 10u, 20u, fetch::ml::details::ActivationType::RELU, regulariser, reg_rate); std::string layer_2 = g->template AddNode<fetch::ml::layers::FullyConnected<TensorType>>( "FC2", {layer_1}, 20u, 10u, fetch::ml::details::ActivationType::RELU, regulariser, reg_rate); std::string output = g->template AddNode<fetch::ml::layers::FullyConnected<TensorType>>( "FC3", {layer_2}, 10u, 10u, fetch::ml::details::ActivationType::SOFTMAX, regulariser, reg_rate); // Add loss function std::string error_output = g->template AddNode<fetch::ml::ops::MeanSquareErrorLoss<TensorType>>( "num_error", {output, label_name}); /// make a prediction and do nothing with it TensorType tmp_data = TensorType::FromString("1, 2, 3, 4, 5, 6, 7, 8, 9, 10"); g->SetInput("Input", tmp_data.Transpose()); TensorType tmp_prediction = g->Evaluate(output); fetch::ml::GraphSaveableParams<TypeParam> gsp1 = g->GetGraphSaveableParams(); fetch::serializers::LargeObjectSerializeHelper b; b.Serialize(gsp1); auto gsp2 = std::make_shared<fetch::ml::GraphSaveableParams<TypeParam>>(); b.Deserialize(*gsp2); EXPECT_EQ(gsp1.connections, gsp2->connections); for (auto const &gsp2_node_pair : gsp2->nodes) { auto gsp2_node = gsp2_node_pair.second; auto gsp1_node = gsp1.nodes[gsp2_node_pair.first]; EXPECT_TRUE(gsp1_node->operation_type == gsp2_node->operation_type); } auto g2 = std::make_shared<GraphType>(); fetch::ml::utilities::BuildGraph<TensorType>(*gsp2, g2); TensorType data = TensorType::FromString("1, 2, 3, 4, 5, 6, 7, 8, 9, 10"); TensorType labels = TensorType::FromString("1; 2; 3; 4; 5; 6; 7; 8; 9; 100"); g->SetInput("Input", data.Transpose()); g2->SetInput("Input", data.Transpose()); TensorType prediction = g->Evaluate(output); TensorType prediction2 = g2->Evaluate(output); // test correct values EXPECT_TRUE(prediction.AllClose(prediction2, fetch::math::function_tolerance<DataType>(), fetch::math::function_tolerance<DataType>())); // train g g->SetInput(label_name, labels); g->Evaluate(error_output); g->BackPropagate(error_output); auto grads = g->GetGradients(); for (auto &grad : grads) { grad *= fetch::math::Type<DataType>("-0.1"); } g->ApplyGradients(grads); // train g2 g2->SetInput(label_name, labels); g2->Evaluate(error_output); g2->BackPropagate(error_output); auto grads2 = g2->GetGradients(); for (auto &grad : grads2) { grad *= fetch::math::Type<DataType>("-0.1"); } g2->ApplyGradients(grads2); g->SetInput("Input", data.Transpose()); TensorType prediction3 = g->Evaluate(output); g2->SetInput("Input", data.Transpose()); TensorType prediction4 = g2->Evaluate(output); EXPECT_FALSE(prediction.AllClose(prediction3, fetch::math::function_tolerance<DataType>(), fetch::math::function_tolerance<DataType>())); EXPECT_TRUE(prediction3.AllClose(prediction4, fetch::math::function_tolerance<DataType>(), fetch::math::function_tolerance<DataType>())); } } // namespace test } // namespace ml } // namespace fetch
#include <iostream> #include <vector> #include <string> #include <fstream> #include <cmath> #include <memory> #include <limits> using namespace std; const double inf = numeric_limits<double>::infinity(); struct color { double r, g, b; color(double r, double g, double b) : r(r), g(g), b(b) {} color() : r(0), g(0), b(0) {} color operator* (const double &x) const { return color{r*x, g*x, b*x}; } }; class Image { private: int r, c; vector<vector<color> > im; public: Image(int _r, int _c) { r = _r; c = _c; im.resize(r); for ( int i = 0 ; i < r ; i++ ) { im[i].resize(c); } } Image* putpixel(int _r, int _c, color l) { im[_r][_c] = l; return this; } color getpixel(int _r, int _c) const { return im[_r][_c]; } void normalize() { color lowest{inf,inf,inf}, highest{-inf,-inf,-inf}; for ( int _r = 0 ; _r < r ; _r++ ) { for ( int _c = 0 ; _c < c ; _c++ ) { color l = getpixel(_r, _c); if ( l.r < lowest.r ) lowest.r = l.r; if ( l.g < lowest.g ) lowest.g = l.g; if ( l.b < lowest.b ) lowest.b = l.b; if ( l.r > highest.r ) highest.r = l.r; if ( l.g > highest.g ) highest.g = l.g; if ( l.b > highest.b ) highest.b = l.b; } } color mult{highest.r - lowest.r, highest.g - lowest.g, highest.b - lowest.b}; if (mult.r <= 0) mult.r = 1; // any strictly positive value suffices if (mult.g <= 0) mult.g = 1; // since this is only used to prevent a if (mult.b <= 0) mult.b = 1; // zero divide when all values are same for ( int _r = 0 ; _r < r ; _r++ ) { for ( int _c = 0 ; _c < c ; _c++ ) { color l = getpixel(_r, _c); l.r = (l.r - lowest.r) / mult.r; l.g = (l.g - lowest.g) / mult.g; l.b = (l.b - lowest.b) / mult.b; putpixel(_r, _c, l); } } } void save_to_ppm(string filename) { ofstream ofile(filename.c_str()); const int max_color = 255; ofile << "P3" << endl; // [magic number] ofile << c << ' ' << r << endl; // [width] [height] ofile << max_color << endl; // [max value of colors] for ( int _r = 0 ; _r < r ; _r++ ) { for ( int _c = 0 ; _c < c ; _c++ ) { color l = getpixel(_r, _c); ofile << (int)(l.r * max_color) << ' ' << (int)(l.g * max_color) << ' ' << (int)(l.b * max_color) << endl; } } } }; void test_Image() { Image im(2, 3); im. putpixel(0, 0, color(1, 0, 0))-> putpixel(0, 1, color(0, 1, 0))-> putpixel(0, 2, color(0, 0, 1))-> putpixel(1, 0, color(1, 1, 0))-> putpixel(1, 1, color(1, 0, 1))-> putpixel(1, 2, color(0, 1, 1))-> save_to_ppm("x.ppm"); } struct Vector { double x, y, z; Vector operator+ (const Vector& b) const { return Vector{x+b.x, y+b.y, z+b.z}; } Vector operator- (const Vector& b) const { return Vector{x-b.x, y-b.y, z-b.z}; } Vector operator- () const { return Vector{-x, -y, -z}; } Vector operator* (const double &b) const { return Vector{x*b, y*b, z*b}; } double dot(const Vector &b) const { return x*b.x + y*b.y + z*b.z; } double squared() const { return dot(*this); } double length() const { return sqrt(squared()); } Vector unit() const { double r = length(); return Vector{x/r, y/r, z/r}; } }; struct Ray { Vector pt, dir; color l; }; struct intersection { bool happened; Vector where; color col; Ray refl; intersection() : happened(false) {} intersection(Vector where, color col, Ray refl) : happened(true), where(where), col(col), refl(refl) {} }; const intersection no_intersection = intersection(); class WorldObject { public: virtual intersection intersect(Ray) const = 0; virtual ~WorldObject() {} // (is it intersecting, (where it intersected, color of // intersection)) }; inline double square(double a) { return a*a; } class Sphere : public WorldObject { private: Vector centre; double r; color col; public: Sphere(Vector pos, double radius, color l) : centre(pos), r(radius), col(l) {} intersection intersect(Ray ray) const { Vector c = centre; Vector s = ray.pt; Vector d = ray.dir; Vector v = s - c; double det = square(v.dot(d)) - (v.dot(v) - square(r)); if ( det < 0 ) // can't have intersection return no_intersection; double dets = sqrt(det); double z = -(v.dot(d)); double t1 = z + dets; double t2 = z - dets; double t = min(t1, t2); Vector y = s + d * t; // point of intersection Vector n = (y - c).unit(); // normal surface Vector r = d - n * (2 * n.dot(d)); // reflected ray direction double cosTheta = fabs(n.dot(d)); // for unit vectors, but n and d // are unit color res{ cosTheta * col.r * ray.l.r, cosTheta * col.g * ray.l.g, cosTheta * col.b * ray.l.b, }; color reflected_col = res; // temporary, until I add reflectance and stuff Ray refl{y, r, reflected_col}; return intersection(y, res, refl); } }; vector<WorldObject*> world; void initialize_world() { world.push_back(new Sphere{Vector{0, -300, 1200}, 200, color(1, 0, 0)}); world.push_back(new Sphere{Vector{-80, -150, 1200}, 200, color(0, 1, 0)}); world.push_back(new Sphere{Vector{70, -100, 1200}, 200, color(0, 0, 1)}); for ( int z = 3 ; z <= 8 ; z++ ) { for ( int x = -2 ; x <= 2 ; x++ ) { world.push_back(new Sphere{ Vector{200. * x, 300, 400. * z}, 40, color(1, 1, 1)}); } } } void cleanup_world() { int len = world.size(); for ( int i = 0 ; i < len ; i++ ) { delete world[i]; } world.clear(); } /* Global constants */ const Vector eye { 0, 0, -200 }; const Vector screen_center {0,0,0}; const int width = 100, height = 100; const int max_x = width / 2; const int max_y = height / 2; const int resolution = 10; color shoot_ray(Vector from, Vector to) { Ray ray{from, (to-from).unit(), color{1,1,1}}; bool hit_somewhere = false; Vector best_intersection{inf, inf, inf}; color best_color; for ( vector<WorldObject*>::iterator it = world.begin() ; it != world.end() ; it++ ) { WorldObject* wo = *it; intersection i = wo->intersect(ray); if ( ! i.happened ) // no intersection, ignore continue; hit_somewhere = true; if ( (i.where - from).length() < (best_intersection - from).length() ) { best_intersection = i.where; best_color = i.col; } } if ( ! hit_somewhere ) { best_color = color(0, 0, 0); } double dist_drop = 1/square((best_intersection - from).length()); return best_color * dist_drop; } int main() { initialize_world(); Image im(height * resolution, width * resolution); for ( int r = 0 ; r < height * resolution ; r++ ) { for ( int c = 0 ; c < width * resolution ; c++ ) { double x = (double)c / resolution - (double)width / 2; double y = (double)r / resolution - (double)height / 2; double z = 0; Vector screen_point { x, y, z }; im.putpixel(r, c, shoot_ray(eye, screen_point)); } } im.normalize(); im.save_to_ppm("x.ppm"); cleanup_world(); }
//--------------------------------------------------------------------------------------------------------------------// // // // Tuplex: Blazing Fast Python Data Science // // // // // // (c) 2017 - 2021, Tuplex team // // Created by Leonhard Spiegelberg first on 1/1/2021 // // License: Apache 2.0 // //--------------------------------------------------------------------------------------------------------------------// #include <logical/CacheOperator.h> namespace tuplex { // @TODO: need to save exception counts as well, so later stages can generate appropriate code! // => caching might also help, because if no exceptions are present no slow-code path needs to be executed/compiled! // => for join(.....cache()) case an upgrade must be compiled I fear... void CacheOperator::copyMembers(const LogicalOperator *other) { assert(other->type() == LogicalOperatorType::CACHE); LogicalOperator::copyMembers(other); auto cop = (CacheOperator*)other; setSchema(other->getOutputSchema()); _normalCasePartitions = cop->cachedPartitions(); _generalCasePartitions = cop->cachedExceptions(); _partitionToExceptionsMap = cop->partitionToExceptionsMap(); // copy python objects and incref for each! _py_objects = cop->_py_objects; python::lockGIL(); for(auto obj : _py_objects) Py_XINCREF(obj); python::unlockGIL(); _optimizedSchema = cop->_optimizedSchema; _cached = cop->_cached; _normalCaseRowCount = cop->_normalCaseRowCount; _generalCaseRowCount = cop->_generalCaseRowCount; _columns = cop->_columns; _sample = cop->_sample; _storeSpecialized = cop->_storeSpecialized; } LogicalOperator* CacheOperator::clone() { auto copy = new CacheOperator(parent()->clone(), _storeSpecialized, _memoryLayout); copy->setDataSet(getDataSet()); copy->copyMembers(this); assert(getID() == copy->getID()); return copy; } CacheOperator * CacheOperator::cloneWithoutParents() const { auto copy = new CacheOperator(); // => no parents! copy->setDataSet(getDataSet()); copy->copyMembers(this); assert(getID() == copy->getID()); return copy; } int64_t CacheOperator::cost() const { // is operator cached? => return combined cost! // @NOTE: could make exceptions more expensive than normal rows if(isCached()) { return _generalCaseRowCount + _normalCaseRowCount; } else { // return parent cost return parent()->cost(); } } void CacheOperator::setResult(const std::shared_ptr<ResultSet> &rs) { using namespace std; _cached = true; // fetch both partitions (consume) from resultset + any unresolved exceptions _normalCasePartitions = rs->partitions(); for(auto p : _normalCasePartitions) p->makeImmortal(); // @TODO: there are two sorts of exceptions here... // i.e. separate normal-case violations out from the rest // => these can be stored separately for faster processing! // @TODO: right now, everything just gets cached... _generalCasePartitions = rs->exceptions(); for(auto p : _generalCasePartitions) p->makeImmortal(); _partitionToExceptionsMap = rs->partitionToExceptionsMap(); // check whether partitions have different schema than the currently set one // => i.e. they have been specialized. if(!_normalCasePartitions.empty()) { _optimizedSchema = _normalCasePartitions.front()->schema(); assert(_optimizedSchema != Schema::UNKNOWN); } // if exceptions are empty, then force output schema to be the optimized one as well! if(_generalCasePartitions.empty()) setSchema(_optimizedSchema); // because the schema might have changed due to the result, need to update the dataset! if(getDataSet()) getDataSet()->setSchema(getOutputSchema()); // print out some statistics about cached data size_t cachedPartitionsMemory = 0; size_t totalCachedPartitionsMemory = 0; size_t totalCachedRows = 0; size_t cachedExceptionsMemory = 0; size_t totalCachedExceptionsMemory = 0; size_t totalCachedExceptions = 0; int pos = 0; for(auto p : _normalCasePartitions) { totalCachedRows += p->getNumRows(); cachedPartitionsMemory += p->bytesWritten(); totalCachedPartitionsMemory += p->size(); pos++; } for(auto p : _generalCasePartitions) { totalCachedExceptions += p->getNumRows(); cachedExceptionsMemory += p->bytesWritten(); totalCachedExceptionsMemory += p->size(); } _normalCaseRowCount = totalCachedRows; _generalCaseRowCount = totalCachedExceptions; stringstream ss; ss<<"Cached "<<pluralize(totalCachedRows, "common row") <<" ("<<pluralize(totalCachedExceptions, "general row") <<"), memory usage: "<<sizeToMemString(cachedPartitionsMemory) <<"/"<<sizeToMemString(totalCachedPartitionsMemory)<<" (" <<sizeToMemString(cachedExceptionsMemory) <<"/"<<sizeToMemString(totalCachedExceptionsMemory)<<")"; Logger::instance().defaultLogger().info(ss.str()); #ifndef NDEBUG // print schema Logger::instance().defaultLogger().info("CACHED common case schema: " + _optimizedSchema.getRowType().desc()); Logger::instance().defaultLogger().info("CACHED general case schema: " + getOutputSchema().getRowType().desc()); #endif } size_t CacheOperator::getTotalCachedRows() const { size_t totalCachedRows = 0; for(auto p : _normalCasePartitions) { totalCachedRows += p->getNumRows(); } for(auto p : _generalCasePartitions) { totalCachedRows += p->getNumRows(); } return totalCachedRows; } }
/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MSRImp.hpp" #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <cfloat> #include <cmath> #include <sstream> #include <numeric> #include <map> #include <memory> #include "MSRIO.hpp" #include "PlatformTopo.hpp" #include "Helper.hpp" #include "Exception.hpp" #include "geopm_sched.h" #include "geopm_hash.h" #include "config.h" #define GEOPM_IOC_MSR_BATCH _IOWR('c', 0xA2, struct MSRIO::m_msr_batch_array) namespace geopm { const std::map<std::string, MSR::m_function_e> MSR::M_FUNCTION_STRING = { {"scale", M_FUNCTION_SCALE}, {"log_half", M_FUNCTION_LOG_HALF}, {"7_bit_float", M_FUNCTION_7_BIT_FLOAT}, {"overflow", M_FUNCTION_OVERFLOW} }; const std::map<std::string, MSR::m_units_e> MSR::M_UNITS_STRING = { {"none", M_UNITS_NONE}, {"seconds", M_UNITS_SECONDS}, {"hertz", M_UNITS_HERTZ}, {"watts", M_UNITS_WATTS}, {"joules", M_UNITS_JOULES}, {"celsius", M_UNITS_CELSIUS} }; /// @brief Class for translating between a double precision value /// and the encoded 64 bit MSR value. class MSREncode { public: MSREncode(const struct MSR::m_encode_s &msre); MSREncode(int begin_bit, int end_bit, int function, int units, double scalar); virtual ~MSREncode() = default; double decode(uint64_t field, uint64_t &last_field, uint64_t &num_overflow); uint64_t encode(double value); uint64_t mask(void); int decode_function(void); int units(void); private: const int m_function; int m_units; int m_shift; int m_num_bit; uint64_t m_mask; uint64_t m_subfield_max; double m_scalar; double m_inverse; }; MSREncode::MSREncode(const struct MSR::m_encode_s &msre) : MSREncode(msre.begin_bit, msre.end_bit, msre.function, msre.units, msre.scalar) { } MSREncode::MSREncode(int begin_bit, int end_bit, int function, int units, double scalar) : m_function(function) , m_units(units) , m_shift(begin_bit) , m_num_bit(end_bit - begin_bit + 1) , m_mask(((1ULL << m_num_bit) - 1) << begin_bit) , m_subfield_max((1ULL << m_num_bit) - 1) , m_scalar(scalar) , m_inverse(1.0 / scalar) { #ifdef GEOPM_DEBUG if (m_num_bit >= 64) { throw Exception("MSREncode: 64 bit fields are not supported.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif } double MSREncode::decode(uint64_t field, uint64_t &last_field, uint64_t &num_overflow) { double result = NAN; uint64_t subfield = (field & m_mask) >> m_shift; uint64_t subfield_last = (last_field & m_mask) >> m_shift; uint64_t float_y, float_z; switch (m_function) { case MSR::M_FUNCTION_LOG_HALF: // F = S * 2.0 ^ -X result = 1.0 / (1ULL << subfield); break; case MSR::M_FUNCTION_7_BIT_FLOAT: // F = S * 2 ^ Y * (1.0 + Z / 4.0) // Y in bits [0:5) and Z in bits [5:7) float_y = subfield & 0x1F; float_z = subfield >> 5; result = (1ULL << float_y) * (1.0 + float_z / 4.0); break; case MSR::M_FUNCTION_OVERFLOW: if (subfield_last > subfield) { ++num_overflow; } result = subfield + ((m_subfield_max + 1.0) * num_overflow); break; case MSR::M_FUNCTION_SCALE: result = subfield; break; default: break; } result *= m_scalar; last_field = field; return result; } uint64_t MSREncode::encode(double value) { uint64_t result = 0; double value_inferred = 0.0; uint64_t float_y, float_z; switch (m_function) { case MSR::M_FUNCTION_SCALE: result = (uint64_t)(m_inverse * value); break; case MSR::M_FUNCTION_LOG_HALF: // F = S * 2.0 ^ -X => // X = log2(S / F) result = (uint64_t)std::log2(m_scalar / value); break; case MSR::M_FUNCTION_7_BIT_FLOAT: // F = S * 2 ^ Y * (1.0 + Z / 4.0) // Y in bits [0:5) and Z in bits [5:7) if (value > 0) { value *= m_inverse; float_y = (uint64_t)std::log2(value); float_z = (uint64_t)(4.0 * (value / (1 << float_y) - 1.0)); if ((float_y && (float_y >> 5) != 0) || (float_z && (float_z >> 2) != 0)) { throw Exception("MSR::encode(): integer overflow in M_FUNCTION_7_BIT_FLOAT datatype encoding", EOVERFLOW, __FILE__, __LINE__); } value_inferred = (1 << float_y) * (1.0 + (float_z / 4.0)); if ((value - value_inferred) > (value * 0.25)) { throw Exception("MSR::encode(): inferred value from encoded value is inaccurate", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } result = float_y | (float_z << 5); } else { throw Exception("MSR::encode(): input value <= 0 for M_FUNCTION_7_BIT_FLOAT", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } break; case MSR::M_FUNCTION_OVERFLOW: result = (uint64_t)value; break; default: throw Exception("MSR::encode(): unimplemented scale function: " + std::to_string(m_function), GEOPM_ERROR_NOT_IMPLEMENTED, __FILE__, __LINE__); break; } result = (result << m_shift) & m_mask; return result; } uint64_t MSREncode::mask(void) { return m_mask; } int MSREncode::decode_function(void) { return m_function; } int MSREncode::units(void) { return m_units; } MSRImp::MSRImp(const std::string &msr_name, uint64_t offset, const std::vector<std::pair<std::string, struct MSR::m_encode_s> > &signal, const std::vector<std::pair<std::string, struct MSR::m_encode_s> > &control) : m_name(msr_name) , m_offset(offset) , m_signal_encode(signal.size(), NULL) , m_control_encode(control.size()) , m_domain_type(GEOPM_DOMAIN_INVALID) , m_prog_msr(0) , m_prog_field_name(0) , m_prog_value(0) { init(signal, control); } MSRImp::~MSRImp() { for (auto it = m_control_encode.rbegin(); it != m_control_encode.rend(); ++it) { delete (*it); } for (auto it = m_signal_encode.rbegin(); it != m_signal_encode.rend(); ++it) { delete (*it); } } void MSRImp::init(const std::vector<std::pair<std::string, struct MSR::m_encode_s> > &signal, const std::vector<std::pair<std::string, struct MSR::m_encode_s> > &control) { int idx = 0; for (auto it = signal.begin(); it != signal.end(); ++it, ++idx) { m_signal_map.insert(std::pair<std::string, int>(it->first, idx)); m_signal_encode[idx] = new MSREncode(it->second); } idx = 0; for (auto it = control.begin(); it != control.end(); ++it, ++idx) { m_control_map.insert(std::pair<std::string, int>(it->first, idx)); m_control_encode[idx] = new MSREncode(it->second); } if (signal.size() != 0) { m_domain_type = signal[0].second.domain; } else if (control.size() != 0) { m_domain_type = control[0].second.domain; } else { throw Exception("MSRImp::init(): both signal and control vectors are empty", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } } std::string MSRImp::name(void) const { return m_name; } uint64_t MSRImp::offset(void) const { return m_offset; } int MSRImp::num_signal(void) const { return m_signal_encode.size(); } int MSRImp::num_control(void) const { return m_control_encode.size(); } std::string MSRImp::signal_name(int signal_idx) const { if (signal_idx < 0 || signal_idx >= num_signal()) { throw Exception("MSRImp::signal_name(): signal_idx out of range", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } std::string result = ""; for (auto it = m_signal_map.begin(); it != m_signal_map.end(); ++it) { if (it->second == signal_idx) { result = it->first; break; } } return result; } std::string MSRImp::control_name(int control_idx) const { if (control_idx < 0 || control_idx >= num_control()) { throw Exception("MSRImp::control_name(): control_idx out of range", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } std::string result = ""; for (auto it = m_control_map.begin(); it != m_control_map.end(); ++it) { if (it->second == control_idx) { result = it->first; break; } } return result; } int MSRImp::signal_index(const std::string &name) const { int result = -1; auto it = m_signal_map.find(name); if (it != m_signal_map.end()) { result = it->second; } return result; } int MSRImp::control_index(const std::string &name) const { int result = -1; auto it = m_control_map.find(name); if (it != m_control_map.end()) { result = it->second; } return result; } double MSRImp::signal(int signal_idx, uint64_t field, uint64_t &last_field, uint64_t &num_overflow) const { if (signal_idx < 0 || signal_idx >= num_signal()) { throw Exception("MSR::signal(): signal_idx out of range", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return m_signal_encode[signal_idx]->decode(field, last_field, num_overflow); } void MSRImp::control(int control_idx, double value, uint64_t &field, uint64_t &mask) const { if (control_idx < 0 || control_idx >= num_control()) { throw Exception("MSR::control(): control_idx out of range", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } field = m_control_encode[control_idx]->encode(value); mask = m_control_encode[control_idx]->mask(); } uint64_t MSRImp::mask(int control_idx) const { return m_control_encode[control_idx]->mask(); } int MSRImp::domain_type(void) const { return m_domain_type; } int MSRImp::decode_function(int signal_idx) const { return m_signal_encode[signal_idx]->decode_function(); } int MSRImp::units(int signal_idx) const { return m_signal_encode[signal_idx]->units(); } MSR::m_function_e MSR::string_to_function(const std::string &str) { auto it = M_FUNCTION_STRING.find(str); if (it == M_FUNCTION_STRING.end()) { throw Exception("MSR::string_to_units(): invalid function string", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } MSR::m_units_e MSR::string_to_units(const std::string &str) { auto it = M_UNITS_STRING.find(str); if (it == M_UNITS_STRING.end()) { throw Exception("MSR::string_to_units(): invalid units string", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return it->second; } std::shared_ptr<MSR> MSR::make_shared(const std::string &msr_name, uint64_t offset, const std::vector<std::pair<std::string, struct MSR::m_encode_s> > &signal, const std::vector<std::pair<std::string, struct MSR::m_encode_s> > &control) { return std::make_shared<MSRImp>(msr_name, offset, signal, control); } std::unique_ptr<MSR> MSR::make_unique(const std::string &msr_name, uint64_t offset, const std::vector<std::pair<std::string, struct MSR::m_encode_s> > &signal, const std::vector<std::pair<std::string, struct MSR::m_encode_s> > &control) { return geopm::make_unique<MSRImp>(msr_name, offset, signal, control); } }
#include <stdio.h> #include <math.h> #include <windows.h> #include <tchar.h> float f(float x, float y, float z) { float a = x * x + 9.0f / 4.0f * y * y + z * z - 1; return a * a * a - x * x * z * z * z - 9.0f / 80.0f * y * y * z * z * z; } float h(float x, float z) { for (float y = 1.0f; y >= 0.0f; y -= 0.001f) if (f(x, y, z) <= 0.0f) return y; return 0.0f; } int main(void) { HANDLE o = GetStdHandle(STD_OUTPUT_HANDLE); _TCHAR buffer[25][80] = { _T(' ') }; _TCHAR ramp[] = _T(".:-=+*#%@"); for (float t = 0.0f; t<50.0f; t += 0.1f) { int sy = 0; float s = sinf(t); float a = s * s * s * s * 0.2f; for (float z = 1.3f; z > -1.2f; z -= 0.1f) { _TCHAR* p = &buffer[sy++][0]; float tz = z * (1.2f - a); for (float x = -1.5f; x < 1.5f; x += 0.05f) { float tx = x * (1.2f + a); float v = f(tx, 0.0f, tz); if (v <= 0.0f) { float y0 = h(tx, tz); float ny = 0.01f; float nx = h(tx + ny, tz) - y0; float nz = h(tx, tz + ny) - y0; float nd = 1.0f / sqrtf(nx * nx + ny * ny + nz * nz); float d = (nx + ny - nz) * nd * 0.5f + 0.5f; *p++ = ramp[(int)(d * 5.0f)]; } else *p++ = ' '; } } for (sy = 0; sy < 25; sy++) { COORD coord = { 0, sy }; SetConsoleCursorPosition(o, coord); WriteConsole(o, buffer[sy], 79, NULL, 0); } Sleep(33); } system("pause"); return 0; }
#include "duckdb/optimizer/remove_unused_columns.hpp" #include "duckdb/function/aggregate/distributive_functions.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" #include <map> namespace duckdb { void RemoveUnusedColumns::ReplaceBinding(ColumnBinding current_binding, ColumnBinding new_binding) { auto colrefs = column_references.find(current_binding); if (colrefs != column_references.end()) { for (auto &colref : colrefs->second) { D_ASSERT(colref->binding == current_binding); colref->binding = new_binding; } } } template <class T> void RemoveUnusedColumns::ClearUnusedExpressions(vector<T> &list, idx_t table_idx) { idx_t offset = 0; for (idx_t col_idx = 0; col_idx < list.size(); col_idx++) { auto current_binding = ColumnBinding(table_idx, col_idx + offset); auto entry = column_references.find(current_binding); if (entry == column_references.end()) { // this entry is not referred to, erase it from the set of expressions list.erase(list.begin() + col_idx); offset++; col_idx--; } else if (offset > 0) { // column is used but the ColumnBinding has changed because of removed columns ReplaceBinding(current_binding, ColumnBinding(table_idx, col_idx)); } } } void RemoveUnusedColumns::VisitOperator(LogicalOperator &op) { switch (op.type) { case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { // aggregate if (!everything_referenced) { // FIXME: groups that are not referenced need to stay -> but they don't need to be scanned and output! auto &aggr = (LogicalAggregate &)op; ClearUnusedExpressions(aggr.expressions, aggr.aggregate_index); if (aggr.expressions.empty() && aggr.groups.empty()) { // removed all expressions from the aggregate: push a COUNT(*) auto count_star_fun = CountStarFun::GetFunction(); aggr.expressions.push_back( AggregateFunction::BindAggregateFunction(context, count_star_fun, {}, nullptr, false)); } } // then recurse into the children of the aggregate RemoveUnusedColumns remove(binder, context); remove.VisitOperatorExpressions(op); remove.VisitOperator(*op.children[0]); return; } case LogicalOperatorType::LOGICAL_DELIM_JOIN: case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { if (!everything_referenced) { auto &comp_join = (LogicalComparisonJoin &)op; if (comp_join.join_type != JoinType::INNER) { break; } // for inner joins with equality predicates in the form of (X=Y) // we can replace any references to the RHS (Y) to references to the LHS (X) // this reduces the amount of columns we need to extract from the join hash table for (auto &cond : comp_join.conditions) { if (cond.comparison == ExpressionType::COMPARE_EQUAL) { if (cond.left->expression_class == ExpressionClass::BOUND_COLUMN_REF && cond.right->expression_class == ExpressionClass::BOUND_COLUMN_REF) { // comparison join between two bound column refs // we can replace any reference to the RHS (build-side) with a reference to the LHS (probe-side) auto &lhs_col = (BoundColumnRefExpression &)*cond.left; auto &rhs_col = (BoundColumnRefExpression &)*cond.right; // if there are any columns that refer to the RHS, auto colrefs = column_references.find(rhs_col.binding); if (colrefs != column_references.end()) { for (auto &entry : colrefs->second) { entry->binding = lhs_col.binding; column_references[lhs_col.binding].push_back(entry); } column_references.erase(rhs_col.binding); } } } } } break; } case LogicalOperatorType::LOGICAL_ANY_JOIN: break; case LogicalOperatorType::LOGICAL_UNION: if (!everything_referenced) { // for UNION we can remove unreferenced columns as long as everything_referenced is false (i.e. we // encounter a UNION node that is not preceded by a DISTINCT) // this happens when UNION ALL is used auto &setop = (LogicalSetOperation &)op; vector<idx_t> entries; for (idx_t i = 0; i < setop.column_count; i++) { entries.push_back(i); } ClearUnusedExpressions(entries, setop.table_index); if (entries.size() < setop.column_count) { if (entries.empty()) { // no columns referenced: this happens in the case of a COUNT(*) // extract the first column entries.push_back(0); } // columns were cleared setop.column_count = entries.size(); for (idx_t child_idx = 0; child_idx < op.children.size(); child_idx++) { RemoveUnusedColumns remove(binder, context, true); auto &child = op.children[child_idx]; // we push a projection under this child that references the required columns of the union child->ResolveOperatorTypes(); auto bindings = child->GetColumnBindings(); vector<unique_ptr<Expression>> expressions; expressions.reserve(entries.size()); for (auto &column_idx : entries) { expressions.push_back( make_unique<BoundColumnRefExpression>(child->types[column_idx], bindings[column_idx])); } auto new_projection = make_unique<LogicalProjection>(binder.GenerateTableIndex(), move(expressions)); new_projection->children.push_back(move(child)); op.children[child_idx] = move(new_projection); remove.VisitOperator(*op.children[child_idx]); } return; } } for (auto &child : op.children) { RemoveUnusedColumns remove(binder, context, true); remove.VisitOperator(*child); } return; case LogicalOperatorType::LOGICAL_EXCEPT: case LogicalOperatorType::LOGICAL_INTERSECT: // for INTERSECT/EXCEPT operations we can't remove anything, just recursively visit the children for (auto &child : op.children) { RemoveUnusedColumns remove(binder, context, true); remove.VisitOperator(*child); } return; case LogicalOperatorType::LOGICAL_PROJECTION: { if (!everything_referenced) { auto &proj = (LogicalProjection &)op; ClearUnusedExpressions(proj.expressions, proj.table_index); if (proj.expressions.empty()) { // nothing references the projected expressions // this happens in the case of e.g. EXISTS(SELECT * FROM ...) // in this case we only need to project a single constant proj.expressions.push_back(make_unique<BoundConstantExpression>(Value::INTEGER(42))); } } // then recurse into the children of this projection RemoveUnusedColumns remove(binder, context); remove.VisitOperatorExpressions(op); remove.VisitOperator(*op.children[0]); return; } case LogicalOperatorType::LOGICAL_GET: LogicalOperatorVisitor::VisitOperatorExpressions(op); if (!everything_referenced) { auto &get = (LogicalGet &)op; // for every table filter, push a column binding into the column references map to prevent the column from // being projected out for (auto &filter : get.table_filters.filters) { idx_t index = DConstants::INVALID_INDEX; for (idx_t i = 0; i < get.column_ids.size(); i++) { if (get.column_ids[i] == filter.first) { index = i; break; } } if (index == DConstants::INVALID_INDEX) { throw InternalException("Could not find column index for table filter"); } ColumnBinding filter_binding(get.table_index, index); if (column_references.find(filter_binding) == column_references.end()) { column_references.insert(make_pair(filter_binding, vector<BoundColumnRefExpression *>())); } } // table scan: figure out which columns are referenced ClearUnusedExpressions(get.column_ids, get.table_index); if (get.column_ids.empty()) { // this generally means we are only interested in whether or not anything exists in the table (e.g. // EXISTS(SELECT * FROM tbl)) in this case, we just scan the row identifier column as it means we do not // need to read any of the columns get.column_ids.push_back(COLUMN_IDENTIFIER_ROW_ID); } } return; case LogicalOperatorType::LOGICAL_DISTINCT: { // distinct, all projected columns are used for the DISTINCT computation // mark all columns as used and continue to the children // FIXME: DISTINCT with expression list does not implicitly reference everything everything_referenced = true; break; } case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: { everything_referenced = true; break; } case LogicalOperatorType::LOGICAL_CTE_REF: { everything_referenced = true; break; } default: break; } LogicalOperatorVisitor::VisitOperatorExpressions(op); LogicalOperatorVisitor::VisitOperatorChildren(op); } unique_ptr<Expression> RemoveUnusedColumns::VisitReplace(BoundColumnRefExpression &expr, unique_ptr<Expression> *expr_ptr) { // add a column reference column_references[expr.binding].push_back(&expr); return nullptr; } unique_ptr<Expression> RemoveUnusedColumns::VisitReplace(BoundReferenceExpression &expr, unique_ptr<Expression> *expr_ptr) { // BoundReferenceExpression should not be used here yet, they only belong in the physical plan throw InternalException("BoundReferenceExpression should not be used here yet!"); } } // namespace duckdb
/** * @note This file is part of MABE, https://github.com/mercere99/MABE2 * @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md * @date 2019 * * @file AllOnes.cc * @brief Implementation of a simple all-ones problem using MABE. */ #include <iostream> #include "config/ArgManager.h" #include "tools/BitVector.h" #include "tools/Random.h" #include "../source/core/MABE.h" #include "../source/evaluate/EvalAll1s.h" #include "../source/orgs/BitsOrg.h" #include "../source/interface/CommandLine.h" #include "../source/placement/GrowthPlacement.h" #include "../source/schema/Mutate.h" #include "../source/select/SelectElite.h" #include "../source/select/SelectTournament.h" int main(int argc, char* argv[]) { mabe::MABE control(argc, argv); control.AddModule<mabe::CommandLine>(); control.AddOrganismManager<mabe::BitsOrgManager>("BitOrg"); control.AddModule<mabe::Mutate>(0, 1); control.AddModule<mabe::EvalAll1s>("bits", "fitness"); control.AddModule<mabe::SelectElite>("fitness", 1, 1); control.AddModule<mabe::SelectTournament>("fitness", 7, 199); control.AddModule<mabe::GrowthPlacement>(); control.Setup(); control.Inject("BitOrg", 200); control.Update(100); /* // emp::EAWorld<BitOrg, emp::FitCacheOff> pop(random, "NKWorld"); emp::World<BitOrg> pop(random, "NKWorld"); pop.SetupFitnessFile().SetTimingRepeat(10); pop.SetupSystematicsFile().SetTimingRepeat(10); pop.SetupPopulationFile().SetTimingRepeat(10); pop.SetPopStruct_Mixed(true); pop.SetCache(); // Build a random initial population for (uint32_t i = 0; i < POP_SIZE; i++) { BitOrg next_org(N); for (uint32_t j = 0; j < N; j++) next_org[j] = random.P(0.5); pop.Inject(next_org); } // Setup the mutation function. std::function<size_t(BitOrg &, emp::Random &)> mut_fun = [MUT_COUNT, N](BitOrg & org, emp::Random & random) { size_t num_muts = 0; for (uint32_t m = 0; m < MUT_COUNT; m++) { const uint32_t pos = random.GetUInt(N); if (random.P(0.5)) { org[pos] ^= 1; num_muts++; } } return num_muts; }; pop.SetMutFun( mut_fun ); pop.SetAutoMutate(); std::cout << 0 << " : " << pop[0] << " : " << landscape.GetFitness(pop[0]) << std::endl; std::function<double(BitOrg&)> fit_fun = [&landscape](BitOrg & org){ return landscape.GetFitness(org); }; pop.SetFitFun( fit_fun ); // Loop through updates for (uint32_t ud = 0; ud < MAX_GENS; ud++) { // Print current state. // for (uint32_t i = 0; i < pop.GetSize(); i++) std::cout << pop[i] << std::endl; // std::cout << std::endl; // Keep the best individual. emp::EliteSelect(pop, 1, 1); // Run a tournament for the rest... TournamentSelect(pop, 5, POP_SIZE-1); pop.Update(); std::cout << (ud+1) << " : " << pop[0] << " : " << landscape.GetFitness(pop[0]) << std::endl; } // pop.PrintLineage(0); // std::cout << MAX_GENS << " : " << pop[0] << " : " << landscape.GetFitness(pop[0]) << std::endl; // pop.GetSignalControl().PrintNames(); */ }
/////////////////////////////////////////////////////////////////////////////////// // Copyright(c) 2016, Lin Koon Wing Macgyver, macgyvercct@yahoo.com.hk // // // // Author : Mac Lin // // Module : Magnum Engine v1.0.0 // // Date : 14/Jun/2016 // // // /////////////////////////////////////////////////////////////////////////////////// #include "Input.h" #include "Stage.h" using namespace Magnum; Vector< Functor1<Input::TouchpadEvent> *> Input::touchpadMethods; Vector<Input::TouchpadEvent> Input::touchpadEvents; Vector< Functor1<Input::GamepadEvent> *> Input::gamepadMethods; Vector<Input::GamepadEvent> Input::gamepadEvents; Vector< Functor1<Input::AcceleratorEvent> *> Input::acceleratorMethods; Vector<Input::AcceleratorEvent> Input::acceleratorEvents; Vector< Functor1<Input::GUIEvent> *> Input::guiMethods; Vector<Input::GUIEvent> Input::guiEvents; void Input::onMouseEvent(TouchpadEvent::Modifier modifier, Input::Event evt, int fingerID, float x, float y) { Input::TouchpadEvent &touchpadEvent = Input::touchpadEvents.push(); touchpadEvent.event = evt; touchpadEvent.modifier = (TouchpadEvent::Modifier)modifier; touchpadEvent.fingerID = fingerID; touchpadEvent.position = Vector2(x, y); touchpadEvent.wheelAxis = 0; touchpadEvent.wheelRotation = 0; } void Input::onMouseEvent(TouchpadEvent::Modifier modifier, Input::Event evt, float x, float y, int axis, int rotation) { Input::TouchpadEvent &touchpadEvent = Input::touchpadEvents.push(); touchpadEvent.event = evt; touchpadEvent.modifier = (TouchpadEvent::Modifier)modifier; touchpadEvent.fingerID = 0; touchpadEvent.position = Vector2(x, y); touchpadEvent.wheelAxis = axis; touchpadEvent.wheelRotation = rotation; } void Input::onKeyEvent(Input::Event evt, int keyCode) { Input::GamepadEvent &gamepadEvent = Input::gamepadEvents.push(); gamepadEvent.event = evt; gamepadEvent.keyCode = keyCode; } void Input::onAcceleratorEvent(Input::Event evt, float x, float y, float z) { Input::AcceleratorEvent &acceleratorEvent = Input::acceleratorEvents.push(); acceleratorEvent.event = evt; acceleratorEvent.acceleration = Vector3(x, y, z); } void Input::onGUIEvent(Input::Event evt, const unsigned char *buffer, int len) { Input::GUIEvent &guiEvent = Input::guiEvents.push(); guiEvent.event = evt; guiEvent.buffer.resize(len); System::memcpy(&guiEvent.buffer[0], buffer, len); } /////////////////////////////////////////////////////////////////////////////////// bool Input::Service::initiate() { return true; } void Input::Service::process() { for(int i=0; i<touchpadEvents.length(); i++) { Input::TouchpadEvent &touchpadEvt = Input::touchpadEvents[i]; for(int j=0; j<touchpadMethods.length(); j++) { touchpadMethods[j]->invoke(touchpadEvt); } } for(int i=0; i<gamepadEvents.length(); i++) { Input::GamepadEvent &gamepadEvt = Input::gamepadEvents[i]; for(int j=0; j<gamepadMethods.length(); j++) { gamepadMethods[j]->invoke(gamepadEvt); } } for(int i=0; i<acceleratorEvents.length(); i++) { Input::AcceleratorEvent &acceleratorEvt = Input::acceleratorEvents[i]; for(int j=0; j<acceleratorMethods.length(); j++) { acceleratorMethods[j]->invoke(acceleratorEvt); } } for(int i=0; i<guiEvents.length(); i++) { Input::GUIEvent &guiEvt = Input::guiEvents[i]; for(int j=0; j<guiMethods.length(); j++) { guiMethods[j]->invoke(guiEvt); } } touchpadEvents.clear(); gamepadEvents.clear(); acceleratorEvents.clear(); guiEvents.clear(); } void Input::Service::pause() { } void Input::Service::resume() { } void Input::Service::terminate() { touchpadMethods.destroy(); touchpadEvents.destroy(); gamepadMethods.destroy(); gamepadEvents.destroy(); acceleratorMethods.destroy(); acceleratorEvents.destroy(); guiMethods.destroy(); guiEvents.destroy(); } void Input::Service::clear() { touchpadMethods.destroy(); touchpadEvents.destroy(); gamepadMethods.destroy(); gamepadEvents.destroy(); acceleratorMethods.destroy(); acceleratorEvents.destroy(); guiMethods.destroy(); guiEvents.destroy(); }
// Copyright (c) 2012 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. #include "chrome/browser/ui/views/dropdown_bar_host.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "ui/base/events/event.h" #include "ui/base/keycodes/keyboard_code_conversion_win.h" #include "ui/views/controls/scrollbar/native_scroll_bar.h" using content::NativeWebKeyboardEvent; using content::WebContents; NativeWebKeyboardEvent DropdownBarHost::GetKeyboardEvent( const WebContents* contents, const ui::KeyEvent& key_event) { HWND hwnd = contents->GetView()->GetContentNativeView(); WORD key = WindowsKeyCodeForKeyboardCode(key_event.key_code()); MSG msg = { hwnd, key_event.native_event().message, key, 0 }; return NativeWebKeyboardEvent(msg); } void DropdownBarHost::SetWidgetPositionNative(const gfx::Rect& new_pos, bool no_redraw) { DWORD swp_flags = SWP_NOOWNERZORDER; if (no_redraw) swp_flags |= SWP_NOREDRAW; if (!host_->IsVisible()) swp_flags |= SWP_SHOWWINDOW; ::SetWindowPos(host_->GetNativeView(), HWND_TOP, new_pos.x(), new_pos.y(), new_pos.width(), new_pos.height(), swp_flags); } void DropdownBarHost::SetHostViewNative(views::View* host_view) { // TODO(pkotwicz): Implement controlling the z-order of hwnds associated to a // host view via the z-order of the host views in |browser_view_|'s view tree. }
// Created on : Sat May 02 12:41:15 2020 // Created by: Irina KRYLOVA // Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V3.0 // Copyright (c) Open CASCADE 2020 // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepKinematics_LowOrderKinematicPairWithRange_HeaderFile_ #define _StepKinematics_LowOrderKinematicPairWithRange_HeaderFile_ #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepKinematics_LowOrderKinematicPair.hxx> #include <TCollection_HAsciiString.hxx> #include <StepRepr_RepresentationItem.hxx> #include <StepRepr_ItemDefinedTransformation.hxx> #include <StepKinematics_KinematicJoint.hxx> DEFINE_STANDARD_HANDLE(StepKinematics_LowOrderKinematicPairWithRange, StepKinematics_LowOrderKinematicPair) //! Representation of STEP entity LowOrderKinematicPairWithRange class StepKinematics_LowOrderKinematicPairWithRange : public StepKinematics_LowOrderKinematicPair { public : //! default constructor Standard_EXPORT StepKinematics_LowOrderKinematicPairWithRange(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theRepresentationItem_Name, const Handle(TCollection_HAsciiString)& theItemDefinedTransformation_Name, const Standard_Boolean hasItemDefinedTransformation_Description, const Handle(TCollection_HAsciiString)& theItemDefinedTransformation_Description, const Handle(StepRepr_RepresentationItem)& theItemDefinedTransformation_TransformItem1, const Handle(StepRepr_RepresentationItem)& theItemDefinedTransformation_TransformItem2, const Handle(StepKinematics_KinematicJoint)& theKinematicPair_Joint, const Standard_Boolean theLowOrderKinematicPair_TX, const Standard_Boolean theLowOrderKinematicPair_TY, const Standard_Boolean theLowOrderKinematicPair_TZ, const Standard_Boolean theLowOrderKinematicPair_RX, const Standard_Boolean theLowOrderKinematicPair_RY, const Standard_Boolean theLowOrderKinematicPair_RZ, const Standard_Boolean hasLowerLimitActualRotationX, const Standard_Real theLowerLimitActualRotationX, const Standard_Boolean hasUpperLimitActualRotationX, const Standard_Real theUpperLimitActualRotationX, const Standard_Boolean hasLowerLimitActualRotationY, const Standard_Real theLowerLimitActualRotationY, const Standard_Boolean hasUpperLimitActualRotationY, const Standard_Real theUpperLimitActualRotationY, const Standard_Boolean hasLowerLimitActualRotationZ, const Standard_Real theLowerLimitActualRotationZ, const Standard_Boolean hasUpperLimitActualRotationZ, const Standard_Real theUpperLimitActualRotationZ, const Standard_Boolean hasLowerLimitActualTranslationX, const Standard_Real theLowerLimitActualTranslationX, const Standard_Boolean hasUpperLimitActualTranslationX, const Standard_Real theUpperLimitActualTranslationX, const Standard_Boolean hasLowerLimitActualTranslationY, const Standard_Real theLowerLimitActualTranslationY, const Standard_Boolean hasUpperLimitActualTranslationY, const Standard_Real theUpperLimitActualTranslationY, const Standard_Boolean hasLowerLimitActualTranslationZ, const Standard_Real theLowerLimitActualTranslationZ, const Standard_Boolean hasUpperLimitActualTranslationZ, const Standard_Real theUpperLimitActualTranslationZ); //! Returns field LowerLimitActualRotationX Standard_EXPORT Standard_Real LowerLimitActualRotationX() const; //! Sets field LowerLimitActualRotationX Standard_EXPORT void SetLowerLimitActualRotationX (const Standard_Real theLowerLimitActualRotationX); //! Returns True if optional field LowerLimitActualRotationX is defined Standard_EXPORT Standard_Boolean HasLowerLimitActualRotationX() const; //! Returns field UpperLimitActualRotationX Standard_EXPORT Standard_Real UpperLimitActualRotationX() const; //! Sets field UpperLimitActualRotationX Standard_EXPORT void SetUpperLimitActualRotationX (const Standard_Real theUpperLimitActualRotationX); //! Returns True if optional field UpperLimitActualRotationX is defined Standard_EXPORT Standard_Boolean HasUpperLimitActualRotationX() const; //! Returns field LowerLimitActualRotationY Standard_EXPORT Standard_Real LowerLimitActualRotationY() const; //! Sets field LowerLimitActualRotationY Standard_EXPORT void SetLowerLimitActualRotationY (const Standard_Real theLowerLimitActualRotationY); //! Returns True if optional field LowerLimitActualRotationY is defined Standard_EXPORT Standard_Boolean HasLowerLimitActualRotationY() const; //! Returns field UpperLimitActualRotationY Standard_EXPORT Standard_Real UpperLimitActualRotationY() const; //! Sets field UpperLimitActualRotationY Standard_EXPORT void SetUpperLimitActualRotationY (const Standard_Real theUpperLimitActualRotationY); //! Returns True if optional field UpperLimitActualRotationY is defined Standard_EXPORT Standard_Boolean HasUpperLimitActualRotationY() const; //! Returns field LowerLimitActualRotationZ Standard_EXPORT Standard_Real LowerLimitActualRotationZ() const; //! Sets field LowerLimitActualRotationZ Standard_EXPORT void SetLowerLimitActualRotationZ (const Standard_Real theLowerLimitActualRotationZ); //! Returns True if optional field LowerLimitActualRotationZ is defined Standard_EXPORT Standard_Boolean HasLowerLimitActualRotationZ() const; //! Returns field UpperLimitActualRotationZ Standard_EXPORT Standard_Real UpperLimitActualRotationZ() const; //! Sets field UpperLimitActualRotationZ Standard_EXPORT void SetUpperLimitActualRotationZ (const Standard_Real theUpperLimitActualRotationZ); //! Returns True if optional field UpperLimitActualRotationZ is defined Standard_EXPORT Standard_Boolean HasUpperLimitActualRotationZ() const; //! Returns field LowerLimitActualTranslationX Standard_EXPORT Standard_Real LowerLimitActualTranslationX() const; //! Sets field LowerLimitActualTranslationX Standard_EXPORT void SetLowerLimitActualTranslationX (const Standard_Real theLowerLimitActualTranslationX); //! Returns True if optional field LowerLimitActualTranslationX is defined Standard_EXPORT Standard_Boolean HasLowerLimitActualTranslationX() const; //! Returns field UpperLimitActualTranslationX Standard_EXPORT Standard_Real UpperLimitActualTranslationX() const; //! Sets field UpperLimitActualTranslationX Standard_EXPORT void SetUpperLimitActualTranslationX (const Standard_Real theUpperLimitActualTranslationX); //! Returns True if optional field UpperLimitActualTranslationX is defined Standard_EXPORT Standard_Boolean HasUpperLimitActualTranslationX() const; //! Returns field LowerLimitActualTranslationY Standard_EXPORT Standard_Real LowerLimitActualTranslationY() const; //! Sets field LowerLimitActualTranslationY Standard_EXPORT void SetLowerLimitActualTranslationY (const Standard_Real theLowerLimitActualTranslationY); //! Returns True if optional field LowerLimitActualTranslationY is defined Standard_EXPORT Standard_Boolean HasLowerLimitActualTranslationY() const; //! Returns field UpperLimitActualTranslationY Standard_EXPORT Standard_Real UpperLimitActualTranslationY() const; //! Sets field UpperLimitActualTranslationY Standard_EXPORT void SetUpperLimitActualTranslationY (const Standard_Real theUpperLimitActualTranslationY); //! Returns True if optional field UpperLimitActualTranslationY is defined Standard_EXPORT Standard_Boolean HasUpperLimitActualTranslationY() const; //! Returns field LowerLimitActualTranslationZ Standard_EXPORT Standard_Real LowerLimitActualTranslationZ() const; //! Sets field LowerLimitActualTranslationZ Standard_EXPORT void SetLowerLimitActualTranslationZ (const Standard_Real theLowerLimitActualTranslationZ); //! Returns True if optional field LowerLimitActualTranslationZ is defined Standard_EXPORT Standard_Boolean HasLowerLimitActualTranslationZ() const; //! Returns field UpperLimitActualTranslationZ Standard_EXPORT Standard_Real UpperLimitActualTranslationZ() const; //! Sets field UpperLimitActualTranslationZ Standard_EXPORT void SetUpperLimitActualTranslationZ (const Standard_Real theUpperLimitActualTranslationZ); //! Returns True if optional field UpperLimitActualTranslationZ is defined Standard_EXPORT Standard_Boolean HasUpperLimitActualTranslationZ() const; DEFINE_STANDARD_RTTIEXT(StepKinematics_LowOrderKinematicPairWithRange, StepKinematics_LowOrderKinematicPair) private: Standard_Real myLowerLimitActualRotationX; //!< optional Standard_Real myUpperLimitActualRotationX; //!< optional Standard_Real myLowerLimitActualRotationY; //!< optional Standard_Real myUpperLimitActualRotationY; //!< optional Standard_Real myLowerLimitActualRotationZ; //!< optional Standard_Real myUpperLimitActualRotationZ; //!< optional Standard_Real myLowerLimitActualTranslationX; //!< optional Standard_Real myUpperLimitActualTranslationX; //!< optional Standard_Real myLowerLimitActualTranslationY; //!< optional Standard_Real myUpperLimitActualTranslationY; //!< optional Standard_Real myLowerLimitActualTranslationZ; //!< optional Standard_Real myUpperLimitActualTranslationZ; //!< optional Standard_Boolean defLowerLimitActualRotationX; //!< flag "is LowerLimitActualRotationX defined" Standard_Boolean defUpperLimitActualRotationX; //!< flag "is UpperLimitActualRotationX defined" Standard_Boolean defLowerLimitActualRotationY; //!< flag "is LowerLimitActualRotationY defined" Standard_Boolean defUpperLimitActualRotationY; //!< flag "is UpperLimitActualRotationY defined" Standard_Boolean defLowerLimitActualRotationZ; //!< flag "is LowerLimitActualRotationZ defined" Standard_Boolean defUpperLimitActualRotationZ; //!< flag "is UpperLimitActualRotationZ defined" Standard_Boolean defLowerLimitActualTranslationX; //!< flag "is LowerLimitActualTranslationX defined" Standard_Boolean defUpperLimitActualTranslationX; //!< flag "is UpperLimitActualTranslationX defined" Standard_Boolean defLowerLimitActualTranslationY; //!< flag "is LowerLimitActualTranslationY defined" Standard_Boolean defUpperLimitActualTranslationY; //!< flag "is UpperLimitActualTranslationY defined" Standard_Boolean defLowerLimitActualTranslationZ; //!< flag "is LowerLimitActualTranslationZ defined" Standard_Boolean defUpperLimitActualTranslationZ; //!< flag "is UpperLimitActualTranslationZ defined" }; #endif // _StepKinematics_LowOrderKinematicPairWithRange_HeaderFile_
// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <vector> #include "prevector.h" #include "random.h" #include "serialize.h" #include "streams.h" #include "test/test_lunex.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup) template<unsigned int N, typename T> class prevector_tester { typedef std::vector<T> realtype; realtype real_vector; realtype real_vector_alt; typedef prevector<N, T> pretype; pretype pre_vector; pretype pre_vector_alt; typedef typename pretype::size_type Size; bool passed = true; uint32_t insecure_rand_Rz_cache; uint32_t insecure_rand_Rw_cache; template <typename A, typename B> void local_check_equal(A a, B b) { local_check(a == b); } void local_check(bool b) { passed &= b; } void test() { const pretype& const_pre_vector = pre_vector; local_check_equal(real_vector.size(), pre_vector.size()); local_check_equal(real_vector.empty(), pre_vector.empty()); for (Size s = 0; s < real_vector.size(); s++) { local_check(real_vector[s] == pre_vector[s]); local_check(&(pre_vector[s]) == &(pre_vector.begin()[s])); local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s)); local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size())); } // local_check(realtype(pre_vector) == real_vector); local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector); local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector); size_t pos = 0; BOOST_FOREACH(const T& v, pre_vector) { local_check(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, pre_vector) { local_check(v == real_vector[--pos]); } BOOST_FOREACH(const T& v, const_pre_vector) { local_check(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) { local_check(v == real_vector[--pos]); } CDataStream ss1(SER_DISK, 0); CDataStream ss2(SER_DISK, 0); ss1 << real_vector; ss2 << pre_vector; local_check_equal(ss1.size(), ss2.size()); for (Size s = 0; s < ss1.size(); s++) { local_check_equal(ss1[s], ss2[s]); } } public: void resize(Size s) { real_vector.resize(s); local_check_equal(real_vector.size(), s); pre_vector.resize(s); local_check_equal(pre_vector.size(), s); test(); } void reserve(Size s) { real_vector.reserve(s); local_check(real_vector.capacity() >= s); pre_vector.reserve(s); local_check(pre_vector.capacity() >= s); test(); } void insert(Size position, const T& value) { real_vector.insert(real_vector.begin() + position, value); pre_vector.insert(pre_vector.begin() + position, value); test(); } void insert(Size position, Size count, const T& value) { real_vector.insert(real_vector.begin() + position, count, value); pre_vector.insert(pre_vector.begin() + position, count, value); test(); } template<typename I> void insert_range(Size position, I first, I last) { real_vector.insert(real_vector.begin() + position, first, last); pre_vector.insert(pre_vector.begin() + position, first, last); test(); } void erase(Size position) { real_vector.erase(real_vector.begin() + position); pre_vector.erase(pre_vector.begin() + position); test(); } void erase(Size first, Size last) { real_vector.erase(real_vector.begin() + first, real_vector.begin() + last); pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last); test(); } void update(Size pos, const T& value) { real_vector[pos] = value; pre_vector[pos] = value; test(); } void push_back(const T& value) { real_vector.push_back(value); pre_vector.push_back(value); test(); } void pop_back() { real_vector.pop_back(); pre_vector.pop_back(); test(); } void clear() { real_vector.clear(); pre_vector.clear(); } void assign(Size n, const T& value) { real_vector.assign(n, value); pre_vector.assign(n, value); } Size size() { return real_vector.size(); } Size capacity() { return pre_vector.capacity(); } void shrink_to_fit() { pre_vector.shrink_to_fit(); test(); } void swap() { real_vector.swap(real_vector_alt); pre_vector.swap(pre_vector_alt); test(); } ~prevector_tester() { BOOST_CHECK_MESSAGE(passed, "insecure_rand_Rz: " << insecure_rand_Rz_cache << ", insecure_rand_Rw: " << insecure_rand_Rw_cache); } prevector_tester() { seed_insecure_rand(); insecure_rand_Rz_cache = insecure_rand_Rz; insecure_rand_Rw_cache = insecure_rand_Rw; } }; BOOST_AUTO_TEST_CASE(PrevectorTestInt) { for (int j = 0; j < 64; j++) { BOOST_TEST_MESSAGE("PrevectorTestInt " << j); prevector_tester<8, int> test; for (int i = 0; i < 2048; i++) { int r = insecure_rand(); if ((r % 4) == 0) { test.insert(insecure_rand() % (test.size() + 1), insecure_rand()); } if (test.size() > 0 && ((r >> 2) % 4) == 1) { test.erase(insecure_rand() % test.size()); } if (((r >> 4) % 8) == 2) { int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_rand() % 5) - 2)); test.resize(new_size); } if (((r >> 7) % 8) == 3) { test.insert(insecure_rand() % (test.size() + 1), 1 + (insecure_rand() % 2), insecure_rand()); } if (((r >> 10) % 8) == 4) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 2)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } if (((r >> 13) % 16) == 5) { test.push_back(insecure_rand()); } if (test.size() > 0 && ((r >> 17) % 16) == 6) { test.pop_back(); } if (((r >> 21) % 32) == 7) { int values[4]; int num = 1 + (insecure_rand() % 4); for (int i = 0; i < num; i++) { values[i] = insecure_rand(); } test.insert_range(insecure_rand() % (test.size() + 1), values, values + num); } if (((r >> 26) % 32) == 8) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 4)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } r = insecure_rand(); if (r % 32 == 9) { test.reserve(insecure_rand() % 32); } if ((r >> 5) % 64 == 10) { test.shrink_to_fit(); } if (test.size() > 0) { test.update(insecure_rand() % test.size(), insecure_rand()); } if (((r >> 11) % 1024) == 11) { test.clear(); } if (((r >> 21) % 512) == 12) { test.assign(insecure_rand() % 32, insecure_rand()); } if (((r >> 15) % 64) == 3) { test.swap(); } } } } BOOST_AUTO_TEST_SUITE_END()
//Author:LanceYu #include<iostream> #include<string> #include<cstring> #include<cstdio> #include<fstream> #include<iosfwd> #include<sstream> #include<fstream> #include<cwchar> #include<iomanip> #include<ostream> #include<vector> #include<cstdlib> #include<queue> #include<set> #include<ctime> #include<algorithm> #include<complex> #include<cmath> #include<valarray> #include<bitset> #include<iterator> #define ll long long using namespace std; const double clf=1e-8; //const double e=2.718281828; const double PI=3.141592653589793; const int MMAX=2147483647; const int mod=1e9+7; //priority_queue<int>p; //priority_queue<int,vector<int>,greater<int> >pq; int main() { int n,x,sum; while(scanf("%d%d",&n,&x)!=EOF) { sum=1; for(int i=n;i>=1;i--) { sum*=i; while(sum%10==0) sum/=10; if(sum>=100000) sum%=100000; } for(int i=1;i<x;i++) sum/=10; printf("%d\n",sum%10); } return 0; }
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 Mark Joshi This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/models/marketmodels/callability/lsstrategy.hpp> #include <ql/models/marketmodels/discounter.hpp> #include <ql/models/marketmodels/utilities.hpp> #include <ql/models/marketmodels/evolutiondescription.hpp> #include <ql/models/marketmodels/curvestate.hpp> #include <ql/auto_ptr.hpp> namespace QuantLib { typedef MarketModelMultiProduct::CashFlow CashFlow; LongstaffSchwartzExerciseStrategy::LongstaffSchwartzExerciseStrategy( const Clone<MarketModelBasisSystem>& basisSystem, const std::vector<std::vector<Real> >& basisCoefficients, const EvolutionDescription& evolution, const std::vector<Size>& numeraires, const Clone<MarketModelExerciseValue>& exercise, const Clone<MarketModelExerciseValue>& control) : basisSystem_(basisSystem), basisCoefficients_(basisCoefficients), exercise_(exercise), control_(control), numeraires_(numeraires) { checkCompatibility(evolution, numeraires); relevantTimes_ = evolution.evolutionTimes(); isBasisTime_.resize(relevantTimes_.size()); isBasisTime_ = isInSubset(relevantTimes_, basisSystem_->evolution().evolutionTimes()); isRebateTime_.resize(relevantTimes_.size()); isRebateTime_ = isInSubset(relevantTimes_, exercise_->evolution().evolutionTimes()); isControlTime_.resize(relevantTimes_.size()); isControlTime_ = isInSubset(relevantTimes_, control_->evolution().evolutionTimes()); exerciseIndex_ = std::vector<Size>(relevantTimes_.size()); isExerciseTime_.resize(relevantTimes_.size(), false); std::valarray<bool> v = exercise_->isExerciseTime(); Size exercises = 0, idx = 0; Size i; for (i=0; i<relevantTimes_.size(); ++i) { exerciseIndex_[i] = exercises; if (isRebateTime_[i]) { isExerciseTime_[i] = v[idx++]; if (isExerciseTime_[i]) { exerciseTimes_.push_back(relevantTimes_[i]); ++exercises; } } } const std::vector<Time>& rateTimes = evolution.rateTimes(); std::vector<Time> rebateTimes = exercise_->possibleCashFlowTimes(); rebateDiscounters_.reserve(rebateTimes.size()); for (i=0; i<rebateTimes.size(); ++i) rebateDiscounters_.push_back( MarketModelDiscounter(rebateTimes[i], rateTimes)); std::vector<Time> controlTimes = control_->possibleCashFlowTimes(); controlDiscounters_.reserve(controlTimes.size()); for (i=0; i<controlTimes.size(); ++i) controlDiscounters_.push_back( MarketModelDiscounter(controlTimes[i], rateTimes)); std::vector<Size> basisSizes = basisSystem_->numberOfFunctions(); basisValues_.resize(basisSystem_->numberOfExercises()); for (i=0; i<basisValues_.size(); ++i) basisValues_[i].resize(basisSizes[i]); } std::vector<Time> LongstaffSchwartzExerciseStrategy::exerciseTimes() const { return exerciseTimes_; } std::vector<Time> LongstaffSchwartzExerciseStrategy::relevantTimes() const { return relevantTimes_; } void LongstaffSchwartzExerciseStrategy::reset() { exercise_->reset(); control_->reset(); basisSystem_->reset(); currentIndex_ = 0; principalInNumerairePortfolio_ = newPrincipal_ = 1.0; } bool LongstaffSchwartzExerciseStrategy::exercise( const CurveState& currentState) const { Size exerciseIndex = exerciseIndex_[currentIndex_-1]; CashFlow exerciseCF = exercise_->value(currentState); Real exerciseValue = exerciseCF.amount * rebateDiscounters_[exerciseCF.timeIndex] .numeraireBonds(currentState, numeraires_[currentIndex_-1]) / principalInNumerairePortfolio_; CashFlow controlCF = control_->value(currentState); Real controlValue = controlCF.amount * controlDiscounters_[controlCF.timeIndex] .numeraireBonds(currentState, numeraires_[currentIndex_-1]) / principalInNumerairePortfolio_; basisSystem_->values(currentState, basisValues_[exerciseIndex]); const std::vector<Real>& alphas = basisCoefficients_[exerciseIndex]; Real continuationValue = std::inner_product(alphas.begin(), alphas.end(), basisValues_[exerciseIndex].begin(), controlValue); return exerciseValue >= continuationValue; } void LongstaffSchwartzExerciseStrategy::nextStep( const CurveState& currentState) { principalInNumerairePortfolio_ = newPrincipal_; if (isRebateTime_[currentIndex_]) exercise_->nextStep(currentState); if (isControlTime_[currentIndex_]) control_->nextStep(currentState); if (isBasisTime_[currentIndex_]) basisSystem_->nextStep(currentState); if (currentIndex_ < numeraires_.size()-1) { Size numeraire = numeraires_[currentIndex_]; Size nextNumeraire = numeraires_[currentIndex_+1]; newPrincipal_ *= currentState.discountRatio(numeraire, nextNumeraire); } ++currentIndex_; } QL_UNIQUE_OR_AUTO_PTR<ExerciseStrategy<CurveState> > LongstaffSchwartzExerciseStrategy::clone() const { return QL_UNIQUE_OR_AUTO_PTR<ExerciseStrategy<CurveState> >( new LongstaffSchwartzExerciseStrategy(*this)); } }
#include <utility> #include "format_greeting.hpp" #include "get_person.hpp" #include "say_hello.hpp" namespace e5 { tl::expected<std::string, util::error> say_hello(opentracing::Span& span, std::string&& name) { const auto exp_person = get_person(&span.context(), std::move(name)); if (exp_person.has_value()) { const auto exp_greeting = format_greeting(span, *exp_person); if (exp_greeting.has_value()) { return *exp_greeting; } else { return tl::make_unexpected(exp_greeting.error()); } } else { return tl::make_unexpected(exp_person.error()); } } } // namespace e5
#include <iostream> #include <map> #include <string> #include <sstream> int main() { std::map<double, int> numbers; std::string input; std::getline(std::cin, input); std::istringstream strStream(input); std::string currNumber; while (strStream >> currNumber) { if (numbers.find(std::stod(currNumber)) == numbers.end()) { numbers[std::stod(currNumber)] = 1; } else { numbers[std::stod(currNumber)] += 1; } } std::map<double, int>::iterator itr; for (itr = numbers.begin(); itr != numbers.end(); itr++) { std::cout << itr->first << " -> " << itr->second << std::endl; } return 0; }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // TODO: Make this test pass for all standards. // XFAIL: c++03 // <type_traits> // __convert_to_integral(Tp) // Test that the __convert_to_integral functions properly converts Tp to the // correct type and value for integral, enum and user defined types. #include <limits> #include <type_traits> #include <cstdint> #include <cassert> #include "user_defined_integral.h" #include "test_macros.h" template <class T> struct EnumType { enum type : T {E_zero, E_one}; }; template <class From, class To> void check_integral_types() { typedef std::numeric_limits<From> Limits; const From max = Limits::max(); const From min = Limits::min(); { auto ret = std::__convert_to_integral((From)max); assert(ret == max); ret = std::__convert_to_integral((From)min); assert(ret == min); static_assert(std::is_same<decltype(ret), To>::value, ""); } { UserDefinedIntegral<From> f(max); auto ret = std::__convert_to_integral(f); assert(ret == max); f.value = min; ret = std::__convert_to_integral(f); assert(ret == min); static_assert(std::is_same<decltype(ret), To>::value, ""); } { typedef typename EnumType<From>::type Enum; Enum e(static_cast<Enum>(max)); auto ret = std::__convert_to_integral(e); assert(ret == max); e = static_cast<Enum>(min); ret = std::__convert_to_integral(min); assert(ret == min); static_assert(std::is_same<decltype(ret), To>::value, ""); } } template <class From, class To> void check_enum_types() { auto ret = std::__convert_to_integral((From)1); assert(ret == 1); static_assert(std::is_same<decltype(ret), To>::value, ""); } enum enum1 { zero = 0, one = 1 }; enum enum2 : unsigned long { value = std::numeric_limits<unsigned long>::max() }; int main(int, char**) { check_integral_types<bool, int>(); check_integral_types<char, int>(); check_integral_types<signed char, int>(); check_integral_types<unsigned char, int>(); check_integral_types<wchar_t, decltype(((wchar_t)1) + 1)>(); check_integral_types<char16_t, int>(); // On some platforms, unsigned int and long are the same size. These // platforms have a choice of making uint32_t an int or a long. However // char32_t must promote to an unsigned int on these platforms [conv.prom]. // Use the following logic to make the test work on such platforms. // (sizeof(uint32_t) == sizeof(unsigned int)) ? unsigned int : uint32_t; typedef std::conditional<sizeof(uint32_t) == sizeof(unsigned int), unsigned int, uint32_t>::type char_integral; check_integral_types<char32_t, char_integral>(); check_integral_types<short, int>(); check_integral_types<unsigned short, int>(); check_integral_types<int, int>(); check_integral_types<unsigned, unsigned>(); check_integral_types<long, long>(); check_integral_types<unsigned long, unsigned long>(); check_integral_types<long long, long long>(); check_integral_types<unsigned long long, unsigned long long>(); #ifndef _LIBCPP_HAS_NO_INT128 check_integral_types<__int128_t, __int128_t>(); check_integral_types<__uint128_t, __uint128_t>(); #endif // TODO(ericwf): Not standard typedef std::underlying_type<enum1>::type Enum1UT; check_enum_types<enum1, decltype(((Enum1UT)1) + 1)>(); typedef std::underlying_type<enum2>::type Enum2UT; check_enum_types<enum2, decltype(((Enum2UT)1) + 1)>(); return 0; }
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include "ModelFixture.hpp" #include "../ClimateZones.hpp" #include "../ClimateZones_Impl.hpp" #include "../Model.hpp" #include "../Model_Impl.hpp" #include "../Site.hpp" #include "../Site_Impl.hpp" #include "../../utilities/data/Attribute.hpp" using namespace openstudio; using namespace openstudio::model; TEST_F(ModelFixture, ClimateZones) { // construct directly Model model; EXPECT_FALSE(model.getOptionalUniqueModelObject<ClimateZones>()); ClimateZones czs = model.getUniqueModelObject<ClimateZones>(); // default ASSERT_EQ(1u,czs.numClimateZones()); ASSERT_EQ(1u,czs.climateZones().size()); ClimateZone acz = czs.climateZones()[0]; ASSERT_FALSE(acz.empty()); EXPECT_EQ(ClimateZones::ashraeInstitutionName(),acz.institution()); EXPECT_EQ(ClimateZones::ashraeDocumentName(),acz.documentName()); EXPECT_EQ(ClimateZones::ashraeDefaultYear(),acz.year()); EXPECT_EQ("",acz.value()); // after clear czs.clear(); EXPECT_EQ(0u,czs.numClimateZones()); EXPECT_EQ(0,czs.climateZones().size()); EXPECT_TRUE(acz.empty()); // append a climate zone ClimateZone cz = czs.appendClimateZone(ClimateZones::cecInstitutionName(), ClimateZones::validClimateZoneValues( ClimateZones::cecInstitutionName(), ClimateZones::cecDefaultYear())[0]); ASSERT_FALSE(cz.empty()); EXPECT_EQ(ClimateZones::cecInstitutionName(),cz.institution()); EXPECT_EQ(ClimateZones::cecDocumentName(),cz.documentName()); EXPECT_EQ(ClimateZones::cecDefaultYear(),cz.year()); EXPECT_EQ("1",cz.value()); } TEST_F(ModelFixture, ClimateZones_Site) { // construct Site Model model; Site site = model.getUniqueModelObject<Site>(); EXPECT_FALSE(site.climateZones()); // set value creates ClimateZones object StringVector validValues = ClimateZones::validClimateZoneValues( ClimateZones::ashraeInstitutionName(),ClimateZones::ashraeDefaultYear()); ASSERT_EQ(17u,validValues.size()); }
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <cassert> #include <concepts> #include <iterator> #include <type_traits> #include <utility> #include <range_algorithm_support.hpp> using namespace std; using P = pair<int, int>; // clang-format off template <class Iter> concept CanDifference = requires(Iter it) { { it - it }; }; template <class Iter> concept HasProxy = !is_reference_v<iter_reference_t<Iter>>; // clang-format on struct instantiator { template <input_or_output_iterator Iter> static constexpr void call() { if constexpr (copyable<Iter>) { using ConstIter = typename Iter::Consterator; using Sen = test::sentinel<iter_value_t<Iter>>; using OSen = test::sentinel<const iter_value_t<Iter>>; using Cit = common_iterator<Iter, Sen>; using OCit = common_iterator<ConstIter, OSen>; P input[3] = {{0, 1}, {0, 2}, {0, 3}}; // [common.iter.types] { using iconcept = typename iterator_traits<Cit>::iterator_concept; if constexpr (forward_iterator<Iter>) { STATIC_ASSERT(same_as<iconcept, forward_iterator_tag>); } else { STATIC_ASSERT(same_as<typename iterator_traits<Cit>::iterator_concept, input_iterator_tag>); } using icat = typename iterator_traits<Cit>::iterator_category; if constexpr (derived_from<icat, forward_iterator_tag>) { STATIC_ASSERT(same_as<icat, forward_iterator_tag>); } else { STATIC_ASSERT(same_as<icat, input_iterator_tag>); } using ipointer = typename iterator_traits<Cit>::pointer; if constexpr (_Has_member_arrow<Iter>) { STATIC_ASSERT(same_as<ipointer, decltype(declval<const Iter&>().operator->())>); } else { STATIC_ASSERT(same_as<ipointer, void>); } } { // [common.iter.const] Cit defaultConstructed{}; Cit iterConstructed{Iter{input}}; Cit sentinelConstructed(Sen{}); Cit copyConstructed{defaultConstructed}; copyConstructed = iterConstructed; OCit conversionConstructed{defaultConstructed}; conversionConstructed = iterConstructed; OCit conversionConstructedSentinel{sentinelConstructed}; conversionConstructed = iterConstructed; } { // [common.iter.access] Cit iter{Iter{input}}; assert(*iter == P(0, 1)); assert(iter->first == 0); assert(iter->second == 1); if constexpr (HasProxy<Iter>) { // We return a proxy class here static_assert(is_class_v<decltype(iter.operator->())>); } else { // Either a pointer or the wrapped iterator static_assert(!is_class_v<decltype(iter.operator->())>); } const Cit constIter{Iter{input}}; assert(*constIter == P(0, 1)); assert(constIter->first == 0); assert(constIter->second == 1); if constexpr (HasProxy<Iter>) { // We return a proxy class here static_assert(is_class_v<decltype(constIter.operator->())>); } else { // Either a pointer or the wrapped iterator static_assert(!is_class_v<decltype(constIter.operator->())>); } } { // [common.iter.nav] Cit iter{Iter{input}}; ++iter; assert(*iter == P(0, 2)); assert(*iter++ == P(0, 2)); assert(*iter == P(0, 3)); } { // [common.iter.cmp] // Compare iterator / iterator assert(Cit{Iter{input}} == Cit{Iter{input}}); assert(Cit{Iter{input}} != Cit{Iter{input + 1}}); // Compare iterator / sentinel assert(Cit{Iter{input}} == Cit{Sen{input}}); assert(Cit{Sen{input}} != Cit{Iter{input + 1}}); // Compare sentinel / sentinel assert(Cit{Sen{input}} == Cit{Sen{input}}); assert(Cit{Sen{input}} == Cit{Sen{input + 1}}); if constexpr (CanDifference<Iter>) { // Difference iterator / iterator const same_as<iter_difference_t<Iter>> auto diff_it_it = Cit{Iter{input}} - Cit{Iter{input + 1}}; assert(diff_it_it == -1); // Difference iterator / sentinel const same_as<iter_difference_t<Iter>> auto diff_it_sen = Cit{Iter{input}} - Cit{Sen{input + 1}}; const same_as<iter_difference_t<Iter>> auto diff_sen_it = Cit{Sen{input + 1}} - Cit{Iter{input}}; assert(diff_it_sen == -1); assert(diff_sen_it == 1); // Difference sentinel / sentinel const same_as<iter_difference_t<Iter>> auto diff_sen_sen = Cit{Sen{input}} - Cit{Sen{input + 1}}; assert(diff_sen_sen == 0); // Difference iterator / other iterator const same_as<iter_difference_t<Iter>> auto diff_it_oit = Cit{Iter{input}} - OCit{Iter{input + 1}}; assert(diff_it_oit == -1); // Difference iterator / other sentinel const same_as<iter_difference_t<Iter>> auto diff_it_osen = Cit{Iter{input}} - OCit{OSen{input + 1}}; assert(diff_it_osen == -1); // Difference other iterator / sentinel const same_as<iter_difference_t<Iter>> auto diff_sen_oit = Cit{Sen{input + 1}} - OCit{Iter{input}}; assert(diff_sen_oit == 1); // Difference sentinel / other sentinel const same_as<iter_difference_t<Iter>> auto diff_sen_osen = Cit{Sen{input}} - OCit{OSen{input + 1}}; assert(diff_sen_osen == 0); } } { // [common.iter.cust] if constexpr (input_iterator<Iter>) { // iter_move Cit iter1{Iter{input}}; const same_as<iter_value_t<Iter>> auto element1 = ranges::iter_move(iter1); assert(element1 == P(0, 1)); } if constexpr (indirectly_swappable<Iter>) { // iter_swap Cit iter1{Iter{input}}; Cit iter2{Iter{input + 1}}; ranges::iter_swap(iter1, iter2); assert(*iter1 == P(0, 2)); assert(*iter2 == P(0, 1)); } } } } }; constexpr bool test_operator_arrow() { P input[3] = {{0, 1}, {0, 2}, {0, 3}}; using pointerTest = common_iterator<P*, void*>; pointerTest pointerIter{input}; assert(*pointerIter == P(0, 1)); assert(pointerIter->first == 0); assert(pointerIter->second == 1); static_assert(is_same_v<decltype(pointerIter.operator->()), P* const&>); using countedTest = common_iterator<counted_iterator<P*>, default_sentinel_t>; countedTest countedIter{counted_iterator{input, 3}}; assert(*countedIter == P(0, 1)); assert(countedIter->first == 0); assert(countedIter->second == 1); static_assert(is_same_v<decltype(countedIter.operator->()), counted_iterator<P*> const&>); return true; } // common_iterator supports "copyable but not equality_comparable" iterators, which combination test::iterator does not // provide (I don't think this is a combination of properties that any real iterator will ever exhibit). Whip up // something so we can test the iterator_category metaprogramming. // clang-format off template <class T> concept no_iterator_traits = !requires { typename iterator_traits<T>::iterator_concept; } && !requires { typename iterator_traits<T>::iterator_category; } && !requires { typename iterator_traits<T>::value_type; } && !requires { typename iterator_traits<T>::difference_type; } && !requires { typename iterator_traits<T>::pointer; } && !requires { typename iterator_traits<T>::reference; }; // clang-format on struct input_copy_but_no_eq { using value_type = int; using difference_type = int; input_copy_but_no_eq() = delete; int operator*() const; input_copy_but_no_eq& operator++(); void operator++(int); bool operator==(default_sentinel_t) const; }; STATIC_ASSERT(input_iterator<input_copy_but_no_eq>); STATIC_ASSERT(no_iterator_traits<input_copy_but_no_eq>); STATIC_ASSERT(sentinel_for<default_sentinel_t, input_copy_but_no_eq>); using ICID = iterator_traits<common_iterator<input_copy_but_no_eq, default_sentinel_t>>; STATIC_ASSERT(same_as<typename ICID::iterator_category, input_iterator_tag>); struct poor_sentinel { poor_sentinel() = default; constexpr poor_sentinel(const poor_sentinel&) {} // non-trivial copy constructor, to test _Variantish behavior poor_sentinel& operator=(const poor_sentinel&) = default; template <weakly_incrementable Winc> [[nodiscard]] constexpr bool operator==(const Winc&) const noexcept { return true; } template <weakly_incrementable Winc> [[nodiscard]] constexpr iter_difference_t<Winc> operator-(const Winc&) const noexcept { return 0; } template <weakly_incrementable Winc> [[nodiscard]] friend constexpr iter_difference_t<Winc> operator-(const Winc&, const poor_sentinel&) noexcept { return 0; } }; constexpr bool test_gh_2065() { // Guard against regression of GH-2065, for which we previously stumbled over CWG-1699. { int x = 42; common_iterator<int*, unreachable_sentinel_t> it1{&x}; common_iterator<const int*, unreachable_sentinel_t> it2{&x}; assert(it1 == it2); } { int i = 1729; common_iterator<int*, poor_sentinel> it1{&i}; common_iterator<const int*, poor_sentinel> it2{&i}; assert(it1 - it2 == 0); } return true; } constexpr bool test_lwg_3574() { int arr[]{11, 22, 33}; { common_iterator<int*, const int*> x{arr}; common_iterator<int*, const int*> y{arr + 2}; assert(y - x == 2); } { // test that copy construction is constexpr, even when the sentinel isn't trivially copy constructible common_iterator<int*, poor_sentinel> a{arr}; common_iterator<int*, poor_sentinel> b{a}; // copy-construct with a stored iterator common_iterator<int*, poor_sentinel> x{poor_sentinel{}}; common_iterator<int*, poor_sentinel> y{x}; // copy-construct with a stored sentinel assert(b - a == 0); } common_iterator<int*, unreachable_sentinel_t> i{arr}; common_iterator<const int*, unreachable_sentinel_t> ci{arr + 1}; assert(*ci == 22); assert(*as_const(ci) == 22); assert(ci.operator->() == arr + 1); ci = i; assert(*ci == 11); assert(ci == i); assert(*++ci == 22); assert(ci != i); assert(*ci++ == 22); assert(*ci == 33); assert(iter_move(i) == 11); common_iterator<int*, unreachable_sentinel_t> k{arr + 2}; iter_swap(i, k); assert(arr[0] == 33); assert(arr[2] == 11); return true; } int main() { with_writable_iterators<instantiator, P>::call(); static_assert(with_writable_iterators<instantiator, P>::call()); test_operator_arrow(); static_assert(test_operator_arrow()); test_gh_2065(); static_assert(test_gh_2065()); test_lwg_3574(); static_assert(test_lwg_3574()); }
/******************************************************************************/ /* */ /* MtdsDemo2.cc -- MTDS Library Reference Example 2 */ /* */ /******************************************************************************/ /* Author: Gene Apperson */ /* Copyright 2016, Digilent Inc. All rights reserved. */ /******************************************************************************/ /* Module Description: */ /* */ /* This program demonstrates using the MTDS library to render graphics onto */ /* the display and saving and loading bitmaps to and from files on an SD */ /* card. It also demonstrates using some of the file system API functions to */ /* read and write files on the SD card. */ /* */ /* This program contains several test functions that each demonstrate the use */ /* of one or more features of the MTDS system. The basic use of the graphics */ /* functions in the MTDS library are explained in MtdsDemo1. It is assumed */ /* that the user will have worked through MtdsDemo1 prior to working through */ /* this example. Because of this, basic operation of the MTDS library is not */ /* explained here. Only the new features not previously covered in MtdsDemo1 */ /* are covered in detail here. */ /* */ /******************************************************************************/ /* Revision History: */ /* */ /* 09/29/2016(GeneA): Created */ /* 02/14/2017(SamB): Removed Serial references to port to Xilinx SDK */ /* 12/19/2017(atangzwj): Validated for Vivado 2016.4 */ /* 01/09/2018(atangzwj): Validated for Vivado 2017.4 */ /* */ /******************************************************************************/ /* ------------------------------------------------------------ */ /* Include File Definitions */ /* ------------------------------------------------------------ */ #include <mtds.h> #include <stdint.h> #include <string.h> #include "sleep.h" /* ------------------------------------------------------------ */ /* Local Type Definitions */ /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* Global Variables */ /* ------------------------------------------------------------ */ int itstCur = 1; bool fWriteTest1; bool fWriteTest2; /* ------------------------------------------------------------ */ /* Local Variables */ /* ------------------------------------------------------------ */ int itstMax = 2; /* ------------------------------------------------------------ */ /* Forward Declarations */ /* ------------------------------------------------------------ */ bool MtdsTestFs1(); bool MtdsTestFs2(); /* ------------------------------------------------------------ */ /* Procedure Definitions */ /* ------------------------------------------------------------ */ /*** setup() ** ** Parameters: ** none ** ** Return Values: ** none ** ** Errors: ** none ** ** Description: ** Arduino/MPIDE sketch initialization function. */ void setup() { bool fStat; DTM dtmSet; /* It is possible that we are trying to initialize the interface to the ** display board before it has finished its power on initialization. If so, ** then the first call to mtds.begin() will fail. We run in a loop trying ** to initialize until it succeeds. This usually doesn't take more than one ** or two iterations of the loop before it succeeds. */ while (true) { fStat = mtds.begin(pinMtdsSelStd, frqMtdsSpiDefault); if (fStat) { xil_printf("mtds.begin() succeeded\n\r"); break; } else { xil_printf("mtds.begin() failed\n\r"); sleep(1); } } /* Mount the file system. We are going to be writing a couple of files to the ** SD card, so we must have the file system successfully mounted or we can't ** proceed to the rest of the example. */ if (mtfs.MountFs(true, true)) { xil_printf("mtds.MountFs() succeeded\n\r"); } else { xil_printf("mtds.MountFs() failed\n\r"); /* Mount failed, so lock up rather than run on to the rest of the demo. */ while (true); } fWriteTest1 = true; fWriteTest2 = true; /* The file system code uses the real time clock to set the date and time ** stamps on the files that it writes. There is a simple software-maintained ** real time clock in the display board, but it isn't able to maintain the ** time when it is not powered. Each time the display board resets, the date ** and time get set to midnight, January 1, 2016 . Here we are setting it to ** a different time. Just for the purpose of the example, it is being set to ** approximately the time when this demo program was written. */ dtmSet.sec = 0; dtmSet.min = 50; dtmSet.hour = 13; dtmSet.day = 29; dtmSet.month = 9; dtmSet.year = 2016; mtds.SetDateTime(&dtmSet); } /* ------------------------------------------------------------ */ /*** loop() ** ** Parameters: ** none ** ** Return Values: ** none ** ** Errors: ** none ** ** Description: ** Arduino/MPIDE main sketch function */ void loop() { mtds.ClearDisplay(clrBlack); switch (itstCur) { case 1: if (!MtdsTestFs1()) { while (true); } break; case 2: if (!MtdsTestFs2()) { while (true); } break; } itstCur += 1; if (itstCur > itstMax) { itstCur = 1; } sleep(3); } /* ------------------------------------------------------------ */ /* GDI Test Functions */ /* ------------------------------------------------------------ */ /*** MtdsTestFs1() ** ** Parameters: ** none ** ** Return Values: ** none ** ** Errors: ** none ** ** Description: ** This demo illustrates drawing onto an off-screen bitmap and then using ** the SaveBitmap() function to write the off-screen bitmap to a file on ** the SD card. */ bool MtdsTestFs1() { HDS hdsDisp; HDS hdsTest; HBMP hbmpTest; HBMP hbmpLoad1; HBMP hbmpLoad2; char szFile1[] = "Images/IMG_0001.bmp"; char szFile2[] = "Images/IMG_0002.bmp"; RCT rctFrame = { 0, 0, 39, 39 }; /* Get the DS for drawing onto the display. */ hdsDisp = mtds.GetDisplayDs(); /* Get another DS and set up for drawing onto an off-screen bitmap. */ hdsTest = mtds.GetDs(); hbmpTest = mtds.CreateBitmap(40, 40, 16); mtds.SetDrawingSurface(hdsTest, hbmpTest); /* Draw a test pattern into the off-screen bitmap. Note here that we are ** using the drwXorPen drawing mode. This causes the colors to be XOR'd ** wherever the lines being drawn cross or overlap. */ mtds.SetDrwRop(hdsTest, drwXorPen); mtds.SetPen(hdsTest, penSolid); mtds.SetFgColor(hdsTest, clrGreen); mtds.MoveTo(hdsTest, 19, 9); mtds.LineTo(hdsTest, 29, 0); mtds.LineTo(hdsTest, 29, 9); mtds.LineTo(hdsTest, 39, 9); mtds.LineTo(hdsTest, 29, 19); mtds.LineTo(hdsTest, 39, 29); mtds.LineTo(hdsTest, 29, 29); mtds.LineTo(hdsTest, 29, 39); mtds.LineTo(hdsTest, 19, 29); mtds.LineTo(hdsTest, 9, 39); mtds.LineTo(hdsTest, 9, 29); mtds.LineTo(hdsTest, 0, 29); mtds.LineTo(hdsTest, 9, 19); mtds.LineTo(hdsTest, 0, 9); mtds.LineTo(hdsTest, 9, 9); mtds.LineTo(hdsTest, 9, 0); mtds.LineTo(hdsTest, 19, 9); mtds.SetFgColor(hdsTest, clrYellow); mtds.MoveTo(hdsTest, 9, 9); mtds.LineTo(hdsTest, 29, 29); mtds.MoveTo(hdsTest, 29, 9); mtds.LineTo(hdsTest, 9, 29); mtds.SetFgColor(hdsTest, clrRed); mtds.MoveTo(hdsTest, 19, 9); mtds.LineTo(hdsTest, 29, 19); mtds.LineTo(hdsTest, 19, 29); mtds.LineTo(hdsTest, 9, 19); mtds.LineTo(hdsTest, 19, 9); /* Now that we have drawn the test pattern onto the off-screen bitmap, copy ** it onto the display so that we can see it. */ mtds.BitBlt(hdsDisp, 10, 5, 40, 40, hdsTest, 0, 0, ropSrcCopy); /* Here, we come to the main purpose of this demo function. The StoreBitmap() ** function writes the off-screen bitmap to a file on the SD card in device ** independent bitmap format. ** ** In order to reduce wear on the SD card, we only write the bitmap to the SD ** card the first time this function is called. Each subsequent time we get ** called, we only draw the test pattern on the off-screen bitmap and then ** copy it to the display. */ if (fWriteTest1) { if (!mtds.StoreBitmap(szFile1, hbmpTest)) { xil_printf("StoreBitmap failed on Img_0001.bmp\n\r"); fWriteTest1 = false; return false; } } /* Now that we have written the bitmap to a file, we're going to clear the ** off-screen bitmap, draw a new test pattern and then save that bitmap to a ** different file. */ mtds.FillRect(hdsTest, &rctFrame, hbrBlack); mtds.SetFgColor(hdsTest, clrGreen); mtds.MoveTo(hdsTest, 0, 0); mtds.LineTo(hdsTest, 39, 39); mtds.MoveTo(hdsTest, 39, 0); mtds.LineTo(hdsTest, 0, 39); mtds.SetFgColor(hdsTest, clrRed); mtds.MoveTo(hdsTest, 0, 0); mtds.LineTo(hdsTest, 39, 0); mtds.LineTo(hdsTest, 39, 39); mtds.LineTo(hdsTest, 0, 39); mtds.LineTo(hdsTest, 0, 0); /* Copy the new test pattern to the display so that we can see it. */ mtds.BitBlt(hdsDisp, 55, 5, 40, 40, hdsTest, 0, 0, ropSrcCopy); /* Now, write the off-screen bitmap to the SD card again. Since this is a ** new pattern and we don't want to overwrite the previous one, we write it ** to a file with a different name. */ if (fWriteTest1) { if (!mtds.StoreBitmap(szFile2, hbmpTest)) { xil_printf("StoreBitmap failed on Img_0002.bmp\n\r"); fWriteTest1 = false; return false; } } /* Here, we come to the second main point being illustrated in this function. ** We are going to use LoadBitmap() to read the bitmap files from the SD card ** and then copy them to the display using BitBlt(). LoadBitmap() reads a ** device independent bitmap from a file on the SD card. It creates an ** off-screen bitmap and then loads the DIB data from the file, converts it ** to the internal bitmap format and saves the data into the off-screen ** bitmap in memory. We end up with a memory bitmap that is identical to one ** created by CreateBitmap() except that is has been initialized with the ** image data stored in the DIB file. It can be used in the same way that any ** other memory bitmap can be used. It needs to be selected into a DS as the ** drawing surface. Once that has been done, it can be drawn on the same as ** any other memory bitmap and it can be copied to the display using ** BitBlt(). */ if ((hbmpLoad1 = mtds.LoadBitmap(szFile1)) != 0) { mtds.SetDrawingSurface(hdsTest, hbmpLoad1); /* Note here that we are kind of cheating by assuming the dimensions of ** the bitmap that was obtained from LoadBitmap(). Since we created it ** originally, we can know what the dimensions are and use them. However, ** in general it is better practice to call GetBitmapDimensions() on a ** bitmap obtained from LoadBitmap(). In many cases, that will be the only ** way to determine its size. */ mtds.BitBlt(hdsDisp, 100, 140, 40, 40, hdsTest, 0, 0, ropSrcCopy); } else { xil_printf("LoadBitmap failed on IMG_0001\n\r"); return false; } /* Load the second bitmap file that we created above and copy the resulting ** bitmap to the display. */ if ((hbmpLoad2 = mtds.LoadBitmap(szFile2)) != 0) { mtds.SetDrawingSurface(hdsTest, hbmpLoad2); mtds.BitBlt(hdsDisp, 145, 140, 40, 40, hdsTest, 0, 0, ropSrcCopy); } else { xil_printf("LoadBitmap failed on IMG_0002.bmp\n\r"); return false; } /* We must free all resources used in this function before we return so that ** they aren't lost to the system. */ mtds.DestroyBitmap(hbmpTest); mtds.DestroyBitmap(hbmpLoad1); mtds.DestroyBitmap(hbmpLoad2); mtds.ReleaseDs(hdsDisp); mtds.ReleaseDs(hdsTest); /* Set the control variable so that we only write to the SD card the first ** time through this function. */ fWriteTest1 = false; return true; } /* ------------------------------------------------------------ */ /*** MtdsTestFs2() ** ** Parameters: ** none ** ** Return Values: ** none ** ** Errors: ** none ** ** Description: ** This demo function illustrates using some of the file system API ** functions to read and write files. In this case, we take the two bitmap ** files that were created by the MtdsTestFs1 function and copy them to new ** files. We then load the bitmaps from these new files into memory and ** then copy them to the display. */ bool MtdsTestFs2() { HFIL fhSrc; HFIL fhDst; char szSrc1[] = "Images/IMG_0001.bmp"; char szSrc2[] = "Images/IMG_0002.bmp"; char szDst1[] = "Images/IMG_0098.bmp"; char szDst2[] = "Images/IMG_0099.bmp"; HDS hdsDisp; HDS hdsTest1; HDS hdsTest2; HBMP hbmpTest1; HBMP hbmpTest2; uint8_t rgbBuf[512]; uint32_t cbRes; uint32_t cbRead; /* In order to reduce wear on the SD card, we only write the new files the ** first time that we execute this function. Each subsequent time that we ** are called, we just load them into memory and copy them to the display. */ if (fWriteTest2) { /* Copy the first bitmap file into a new bitmap file. We do this by ** opening the source file for read and the destination file for write. We ** read data from the source file and write it to the destination file ** until we reach the end of the source file. */ mtfs.DeleteFile(szDst1); fhSrc = mtfs.OpenFile(szSrc1, mdMtdsRead | mdMtdsOpenExisting); fhDst = mtfs.OpenFile(szDst1, mdMtdsWrite | mdMtdsCreateAlways); if ((fhSrc == 0) || (fhDst == 0)) { xil_printf("Error opening files to copy bitmap IMP_0001\n\r"); fWriteTest2 = false; return false; } while (!mtfs.Feof(fhSrc)) { mtfs.ReadFile(fhSrc, rgbBuf, 512, &cbRead); if (cbRead > 0) { mtfs.WriteFile(fhDst, rgbBuf, cbRead, &cbRes); } } mtfs.CloseFile(fhSrc); mtfs.CloseFile(fhDst); /* Copy the second bitmap file into a new bitmap file. This is done the ** same was as the first one. */ mtfs.DeleteFile(szDst2); fhSrc = mtfs.OpenFile(szSrc2, mdMtdsRead | mdMtdsOpenExisting); fhDst = mtfs.OpenFile(szDst2, mdMtdsWrite | mdMtdsCreateAlways); if ((fhSrc == 0) || (fhDst == 0)) { xil_printf("Error opening files to copy bitmap IMG_0002\n\r"); fWriteTest2 = false; return false; } while (!mtfs.Feof(fhSrc)) { mtfs.ReadFile(fhSrc, rgbBuf, 512, &cbRead); if (cbRead > 0) { mtfs.WriteFile(fhDst, rgbBuf, cbRead, &cbRes); } } mtfs.CloseFile(fhSrc); mtfs.CloseFile(fhDst); } /* Now that we have copied the two source bitmap files and created two new ** bitmap files, we are going to load the new ones into memory and copy them ** to the display. As long as we have correctly copied all of the data from ** the source files, the new files will be valid device independent bitmap ** files and can be loaded into memory using LoadBitmap(). */ /* We're going to be drawing on the display, so get the display DS to do it ** with. */ hdsDisp = mtds.GetDisplayDs(); /* Load the first of the new bitmap files into memory and set up to copy it ** to the display. In order to operate on the new bitmap, we need to obtain a ** DS and then set the bitmap we load into memory as the drawing surface. */ hbmpTest1 = mtds.LoadBitmap(szDst1); if (hbmpTest1 == 0) { xil_printf("Error loading IMG_0098.bmp\n\r"); return false; } hdsTest1 = mtds.GetDs(); mtds.SetDrawingSurface(hdsTest1, hbmpTest1); /* Do the same thing for the second new bitmap file. */ hbmpTest2 = mtds.LoadBitmap(szDst2); if (hbmpTest2 == 0) { xil_printf("Error loading IMG_0099.bmp\n\r"); return false; } hdsTest2 = mtds.GetDs(); mtds.SetDrawingSurface(hdsTest2, hbmpTest2); /* Now, copy these bitmaps to the display. Here, we are tiling the surface of ** the display with the new bitmaps, alternating between them. */ mtds.BitBlt(hdsDisp, 10, 5, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 55, 5, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 100, 5, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 145, 5, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 190, 5, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 10, 50, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 55, 50, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 100, 50, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 145, 50, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 190, 50, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 10, 95, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 55, 95, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 100, 95, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 145, 95, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 190, 95, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 10, 140, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 55, 140, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 100, 140, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 145, 140, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 190, 140, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 10, 185, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 55, 185, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 100, 185, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 145, 185, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 190, 185, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 10, 230, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 55, 230, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 100, 230, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 145, 230, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 190, 230, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 10, 275, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 55, 275, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 100, 275, 40, 40, hdsTest2, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 145, 275, 40, 40, hdsTest1, 0, 0, ropSrcCopy); mtds.BitBlt(hdsDisp, 190, 275, 40, 40, hdsTest2, 0, 0, ropSrcCopy); /* Free all of the resource used before we leave so that the memory isn't ** lost to the system. */ mtds.DestroyBitmap(hbmpTest1); mtds.DestroyBitmap(hbmpTest2); mtds.ReleaseDs(hdsTest1); mtds.ReleaseDs(hdsTest2); mtds.ReleaseDs(hdsDisp); /* Set the control variable so that we only write to the SD card the first ** time through this function. */ fWriteTest2 = false; return true; }
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED___ASSET__flixel_flixel_ui_xml_defaults_xml #include <__ASSET__flixel_flixel_ui_xml_defaults_xml.h> #endif #ifndef INCLUDED_haxe_Resource #include <haxe/Resource.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_0bb624e4e0669b45_34_new,"__ASSET__flixel_flixel_ui_xml_defaults_xml","new",0x9f4395df,"__ASSET__flixel_flixel_ui_xml_defaults_xml.new","lime/_internal/macros/AssetsMacro.hx",34,0xc651f030) HX_LOCAL_STACK_FRAME(_hx_pos_f4cb54353879e95e_604_boot,"__ASSET__flixel_flixel_ui_xml_defaults_xml","boot",0xb3f88dd3,"__ASSET__flixel_flixel_ui_xml_defaults_xml.boot","ManifestResources.hx",604,0xf77aa668) void __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__construct( ::Dynamic length,::Array< unsigned char > bytesData){ HX_STACKFRAME(&_hx_pos_0bb624e4e0669b45_34_new) HXLINE( 35) ::haxe::io::Bytes bytes = ::haxe::Resource_obj::getBytes(::__ASSET__flixel_flixel_ui_xml_defaults_xml_obj::resourceName); HXLINE( 41) super::__construct(bytes->length,bytes->b); } Dynamic __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__CreateEmpty() { return new __ASSET__flixel_flixel_ui_xml_defaults_xml_obj; } void *__ASSET__flixel_flixel_ui_xml_defaults_xml_obj::_hx_vtable = 0; Dynamic __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_xml_defaults_xml_obj > _hx_result = new __ASSET__flixel_flixel_ui_xml_defaults_xml_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x195c64b7) { return inClassId==(int)0x00000001 || inClassId==(int)0x195c64b7; } else { return inClassId==(int)0x47bbdd2d; } } ::String __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::resourceName; ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_xml_defaults_xml_obj > __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__new( ::Dynamic length,::Array< unsigned char > bytesData) { ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_xml_defaults_xml_obj > __this = new __ASSET__flixel_flixel_ui_xml_defaults_xml_obj(); __this->__construct(length,bytesData); return __this; } ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_xml_defaults_xml_obj > __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__alloc(::hx::Ctx *_hx_ctx, ::Dynamic length,::Array< unsigned char > bytesData) { __ASSET__flixel_flixel_ui_xml_defaults_xml_obj *__this = (__ASSET__flixel_flixel_ui_xml_defaults_xml_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(__ASSET__flixel_flixel_ui_xml_defaults_xml_obj), true, "__ASSET__flixel_flixel_ui_xml_defaults_xml")); *(void **)__this = __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::_hx_vtable; __this->__construct(length,bytesData); return __this; } __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__ASSET__flixel_flixel_ui_xml_defaults_xml_obj() { } bool __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 12: if (HX_FIELD_EQ(inName,"resourceName") ) { outValue = ( resourceName ); return true; } } return false; } bool __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 12: if (HX_FIELD_EQ(inName,"resourceName") ) { resourceName=ioValue.Cast< ::String >(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *__ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo __ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sStaticStorageInfo[] = { {::hx::fsString,(void *) &__ASSET__flixel_flixel_ui_xml_defaults_xml_obj::resourceName,HX_("resourceName",39,7a,62,90)}, { ::hx::fsUnknown, 0, null()} }; #endif static void __ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(__ASSET__flixel_flixel_ui_xml_defaults_xml_obj::resourceName,"resourceName"); }; #ifdef HXCPP_VISIT_ALLOCS static void __ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(__ASSET__flixel_flixel_ui_xml_defaults_xml_obj::resourceName,"resourceName"); }; #endif ::hx::Class __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__mClass; static ::String __ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sStaticFields[] = { HX_("resourceName",39,7a,62,90), ::String(null()) }; void __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__register() { __ASSET__flixel_flixel_ui_xml_defaults_xml_obj _hx_dummy; __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("__ASSET__flixel_flixel_ui_xml_defaults_xml",6d,ba,75,d7); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &__ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__GetStatic; __mClass->mSetStaticField = &__ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__SetStatic; __mClass->mMarkFunc = __ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sMarkStatics; __mClass->mStatics = ::hx::Class_obj::dupFunctions(__ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< __ASSET__flixel_flixel_ui_xml_defaults_xml_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = __ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = __ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = __ASSET__flixel_flixel_ui_xml_defaults_xml_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void __ASSET__flixel_flixel_ui_xml_defaults_xml_obj::__boot() { { HX_STACKFRAME(&_hx_pos_f4cb54353879e95e_604_boot) HXDLIN( 604) resourceName = HX_("__ASSET__:file___ASSET__flixel_flixel_ui_xml_defaults_xml",66,61,52,48); } }
#include "gtest/gtest.h" #include <random> #include "xtensor/xarray.hpp" #include "z5/factory.hxx" #include "z5/multiarray/xtensor_access.hxx" namespace z5 { namespace multiarray { // fixture for the zarr array test class XtensorTest : public ::testing::Test { protected: XtensorTest() : fZarr(fs::path("data.zr")), fN5(fs::path("data.n5")), shape_({100, 100, 100}), chunkShapeRegular_({10, 10, 10}), chunkShapeIrregular_({23, 17, 11}) { } ~XtensorTest() { } template<class T> void writeData(const std::unique_ptr<Dataset> & ds) { const auto & chunks = ds->chunksPerDimension(); const auto & chunkShape = ds->defaultChunkShape(); std::vector<T> data(ds->defaultChunkSize(), 42); for(std::size_t z = 0; z < chunks[0]; ++z) { for(std::size_t y = 0; y < chunks[1]; ++y) { for(std::size_t x = 0; x < chunks[2]; ++x) { ds->writeChunk(types::ShapeType({z, y, x}), &data[0]); } } } } virtual void SetUp() { { filesystem::createFile(fZarr, true); // create arrays Zarr auto intReg = createDataset(fZarr, "int_regular", "int32", shape_, chunkShapeRegular_, "raw"); writeData<int>(intReg); auto intIrreg = createDataset(fZarr, "int_irregular", "int32", shape_, chunkShapeIrregular_, "raw"); writeData<int>(intIrreg); auto floatReg = createDataset(fZarr, "float_regular", "float32", shape_, chunkShapeRegular_, "raw"); writeData<float>(floatReg); auto floatIrreg = createDataset(fZarr, "float_irregular", "float32", shape_, chunkShapeIrregular_, "raw"); writeData<float>(floatIrreg); } { filesystem::createFile(fN5, true); // create arrays n5 auto intReg = createDataset(fN5, "int_regular", "int32", shape_, chunkShapeRegular_, "raw"); writeData<int>(intReg); auto intIrreg = createDataset(fN5, "int_irregular", "int32", shape_, chunkShapeIrregular_, "raw"); writeData<int>(intIrreg); auto floatReg = createDataset(fN5, "float_regular", "float32", shape_, chunkShapeRegular_, "raw"); writeData<float>(floatReg); auto floatIrreg = createDataset(fN5, "float_irregular", "float32", shape_, chunkShapeIrregular_, "raw"); writeData<float>(floatIrreg); } } virtual void TearDown() { fs::remove_all(fZarr.path()); fs::remove_all(fN5.path()); } template<typename T> void testArrayRead(std::unique_ptr<Dataset> & array) { typedef typename xt::xarray<int32_t>::shape_type ArrayShape; const auto & shape = array->shape(); ArrayShape arrayShape(shape.begin(), shape.end()); // load a completely overlapping array consisting of 8 chunks { types::ShapeType offset({0, 0, 0}); ArrayShape subShape({20, 20, 20}); //types::ShapeType subShape({10, 10, 10}); xt::xarray<T> data(subShape); readSubarray<T>(array, data, offset.begin()); for(int i = 0; i < subShape[0]; ++i) { for(int j = 0; j < subShape[1]; ++j) { for(int k = 0; k < subShape[2]; ++k) { //std::cout << i << " " << j << " " << " " << k << std::endl; ASSERT_EQ(data(i, j, k), 42); } } } } // load the complete array { types::ShapeType offset({0, 0, 0}); xt::xarray<T> data(arrayShape); readSubarray<T>(array, data, offset.begin()); for(int i = 0; i < shape[0]; ++i) { for(int j = 0; j < shape[1]; ++j) { for(int k = 0; k < shape[2]; ++k) { ASSERT_EQ(data(i, j, k), 42); } } } } // load 25 random valid chunks and make sure that they // contain the correct data std::default_random_engine gen; std::uniform_int_distribution<std::size_t> xx(0, shape[0] - 2); std::uniform_int_distribution<std::size_t> yy(0, shape[1] - 2); std::uniform_int_distribution<std::size_t> zz(0, shape[2] - 2); std::size_t N = 25; std::size_t x, y, z; std::size_t sx, sy, sz; for(int t = 0; t < N; ++t) { // draw the offset coordinates x = xx(gen); y = yy(gen); z = zz(gen); types::ShapeType offset({x, y, z}); //types::ShapeType offset({20, 30, 34}); // draw the shape coordinates std::uniform_int_distribution<std::size_t> shape_xx(1, shape[0] - x); std::uniform_int_distribution<std::size_t> shape_yy(1, shape[1] - y); std::uniform_int_distribution<std::size_t> shape_zz(1, shape[2] - z); sx = shape_xx(gen); sy = shape_yy(gen); sz = shape_zz(gen); ArrayShape shape({sx, sy, sz}); //types::ShapeType shape({40, 42, 56}); //std::cout << "Random Request: " << t << " / " << N << std::endl; //std::cout << "Offset:" << std::endl; //std::cout << x << " " << y << " " << z << std::endl; //std::cout << "Shape:" << std::endl; //std::cout << sx << " " << sy << " " << sz << std::endl; xt::xarray<T> data(shape); readSubarray<T>(array, data, offset.begin()); for(int i = 0; i < shape[0]; ++i) { for(int j = 0; j < shape[1]; ++j) { for(int k = 0; k < shape[2]; ++k) { //std::cout << i << " " << j << " " << k << std::endl; ASSERT_EQ(data(i, j, k), 42); } } } } } template<typename T, typename DISTR> void testArrayWriteRead(std::unique_ptr<Dataset> & array, DISTR & distr) { typedef typename xt::xarray<int32_t>::shape_type ArrayShape; const auto & shape = array->shape(); ArrayShape arrayShape(shape.begin(), shape.end()); std::default_random_engine gen; auto draw = std::bind(distr, gen); // write and read a completely overlapping array consisting of 8 chunks { types::ShapeType offset({0, 0, 0}); ArrayShape subShape({20, 20, 20}); // generate random in data xt::xarray<T> dataIn(subShape); for(auto it = dataIn.begin(); it != dataIn.end(); ++it) { *it = draw(); } writeSubarray<T>(array, dataIn, offset.begin()); // read the out data xt::xarray<T> dataOut(subShape); readSubarray<T>(array, dataOut, offset.begin()); for(int i = 0; i < subShape[0]; ++i) { for(int j = 0; j < subShape[1]; ++j) { for(int k = 0; k < subShape[2]; ++k) { ASSERT_EQ(dataIn(i, j, k), dataOut(i, j, k)); } } } } // load the complete array { types::ShapeType offset({0, 0, 0}); // generate random in data xt::xarray<T> dataIn(arrayShape); for(auto it = dataIn.begin(); it != dataIn.end(); ++it) { *it = draw(); } writeSubarray<T>(array, dataIn, offset.begin()); // read the out data xt::xarray<T> dataOut(arrayShape); readSubarray<T>(array, dataOut, offset.begin()); for(int i = 0; i < shape[0]; ++i) { for(int j = 0; j < shape[1]; ++j) { for(int k = 0; k < shape[2]; ++k) { ASSERT_EQ(dataIn(i, j, k), dataOut(i, j, k)); } } } } // load 25 random valid chunks and make sure that they // contain the correct data std::uniform_int_distribution<std::size_t> xx(0, shape[0] - 2); std::uniform_int_distribution<std::size_t> yy(0, shape[1] - 2); std::uniform_int_distribution<std::size_t> zz(0, shape[2] - 2); std::size_t N = 25; std::size_t x, y, z; std::size_t sx, sy, sz; for(int t = 0; t < N; ++t) { // draw the offset coordinates x = xx(gen); y = yy(gen); z = zz(gen); types::ShapeType offset({x, y, z}); // draw the shape coordinates std::uniform_int_distribution<std::size_t> shape_xx(1, shape[0] - x); std::uniform_int_distribution<std::size_t> shape_yy(1, shape[1] - y); std::uniform_int_distribution<std::size_t> shape_zz(1, shape[2] - z); sx = shape_xx(gen); sy = shape_yy(gen); sz = shape_zz(gen); ArrayShape shape({sx, sy, sz}); //std::cout << "Offset:" << std::endl; //std::cout << x << " " << y << " " << z << std::endl; //std::cout << "Shape:" << std::endl; //std::cout << sx << " " << sy << " " << sz << std::endl; // generate random in data xt::xarray<T> dataIn(shape); for(auto it = dataIn.begin(); it != dataIn.end(); ++it) { *it = draw(); } writeSubarray<T>(array, dataIn, offset.begin()); // read the out data xt::xarray<T> dataOut(shape); readSubarray<T>(array, dataOut, offset.begin()); for(int i = 0; i < shape[0]; ++i) { for(int j = 0; j < shape[1]; ++j) { for(int k = 0; k < shape[2]; ++k) { ASSERT_EQ(dataIn(i, j, k), dataOut(i, j, k)); } } } } } z5::filesystem::handle::File fZarr; z5::filesystem::handle::File fN5; types::ShapeType shape_; types::ShapeType chunkShapeRegular_; types::ShapeType chunkShapeIrregular_; }; TEST_F(XtensorTest, TestThrow) { auto array = openDataset(fZarr, "int_regular"); typedef typename xt::xarray<int32_t>::shape_type ArrayShape; // check for shape throws #0 ArrayShape shape0({120, 120, 120}); types::ShapeType offset0({0, 0, 0}); xt::xarray<int32_t> sub0(shape0); ASSERT_THROW(readSubarray<int32_t>(array, sub0, offset0.begin()), std::runtime_error); // check for shape throws #1 ArrayShape shape1({80, 80, 80}); types::ShapeType offset1({30, 30, 30}); xt::xarray<int32_t> sub1(shape1); ASSERT_THROW(readSubarray<int32_t>(array, sub1, offset1.begin()), std::runtime_error); // check for shape throws #2 ArrayShape shape2({80, 80, 0}); types::ShapeType offset2({0, 0, 0}); xt::xarray<int32_t> sub2(shape2); ASSERT_THROW(readSubarray<int32_t>(array, sub2, offset2.begin()), std::runtime_error); ArrayShape shape({80, 80, 80}); types::ShapeType offset({0, 0, 0}); // check for dtype throws #0 xt::xarray<int64_t> sub64(shape); ASSERT_THROW(readSubarray<int64_t>(array, sub64, offset.begin()), std::runtime_error); // check for dtype throws #1 xt::xarray<uint32_t> subu(shape); ASSERT_THROW(readSubarray<uint32_t>(array, subu, offset.begin()), std::runtime_error); // check for dtype throws #2 xt::xarray<float> subf(shape); ASSERT_THROW(readSubarray<float>(array, subf, offset.begin()), std::runtime_error); } TEST_F(XtensorTest, TestReadIntRegular) { // load the regular array and run the test auto array = openDataset(fZarr, "int_regular"); testArrayRead<int32_t>(array); // load the regular array and run the test auto arrayN5 = openDataset(fN5, "int_regular"); testArrayRead<int32_t>(arrayN5); } TEST_F(XtensorTest, TestReadFloatRegular) { // load the regular array and run the test auto array = openDataset(fZarr, "float_regular"); testArrayRead<float>(array); // load the regular array and run the test auto arrayN5 = openDataset(fN5, "float_regular"); testArrayRead<float>(arrayN5); } TEST_F(XtensorTest, TestReadIntIrregular) { // load the regular array and run the test auto array = openDataset(fZarr, "int_irregular"); testArrayRead<int32_t>(array); // load the regular array and run the test auto arrayN5 = openDataset(fN5, "int_irregular"); testArrayRead<int32_t>(arrayN5); } TEST_F(XtensorTest, TestReadFloatIrregular) { // load the regular array and run the test auto array = openDataset(fZarr, "float_irregular"); testArrayRead<float>(array); // load the regular array and run the test auto arrayN5 = openDataset(fN5, "float_irregular"); testArrayRead<float>(arrayN5); } TEST_F(XtensorTest, TestWriteReadIntRegular) { auto array = openDataset(fZarr, "int_regular"); std::uniform_int_distribution<int32_t> distr(-100, 100); testArrayWriteRead<int32_t>(array, distr); auto arrayN5 = openDataset(fN5, "int_regular"); testArrayWriteRead<int32_t>(arrayN5, distr); } TEST_F(XtensorTest, TestWriteReadFloatRegular) { std::uniform_real_distribution<float> distr(0., 1.); auto array = openDataset(fZarr, "float_regular"); testArrayWriteRead<float>(array, distr); auto arrayN5 = openDataset(fN5, "float_regular"); testArrayWriteRead<float>(arrayN5, distr); } TEST_F(XtensorTest, TestWriteReadIntIrregular) { auto array = openDataset(fZarr, "int_irregular"); std::uniform_int_distribution<int32_t> distr(-100, 100); testArrayWriteRead<int32_t>(array, distr); auto arrayN5 = openDataset(fN5, "int_irregular"); testArrayWriteRead<int32_t>(arrayN5, distr); } TEST_F(XtensorTest, TestWriteReadFloatIrregular) { auto array = openDataset(fZarr, "float_irregular"); std::uniform_real_distribution<float> distr(0., 1.); testArrayWriteRead<float>(array, distr); auto arrayN5 = openDataset(fN5, "float_irregular"); testArrayWriteRead<float>(arrayN5, distr); } } }
//***************************************************************************** // Copyright 2017-2021 Intel Corporation // // 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. //***************************************************************************** #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" using namespace ngraph; using namespace std; TEST(ngraph_api, parse_version) { size_t major; size_t minor; size_t patch; string extra; { string version = "0.25.1-rc.0+7c32240"; parse_version_string(version, major, minor, patch, extra); EXPECT_EQ(0, major); EXPECT_EQ(25, minor); EXPECT_EQ(1, patch); EXPECT_STREQ(extra.c_str(), "-rc.0+7c32240"); } { string version = "v0.25.1-rc.0+7c32240"; parse_version_string(version, major, minor, patch, extra); EXPECT_EQ(0, major); EXPECT_EQ(25, minor); EXPECT_EQ(1, patch); EXPECT_STREQ(extra.c_str(), "-rc.0+7c32240"); } { string version = "0.25.1+7c32240"; parse_version_string(version, major, minor, patch, extra); EXPECT_EQ(0, major); EXPECT_EQ(25, minor); EXPECT_EQ(1, patch); EXPECT_STREQ(extra.c_str(), "+7c32240"); } { string version = "0.25.1"; parse_version_string(version, major, minor, patch, extra); EXPECT_EQ(0, major); EXPECT_EQ(25, minor); EXPECT_EQ(1, patch); EXPECT_STREQ(extra.c_str(), ""); } { string version = "x0.25.1"; EXPECT_THROW(parse_version_string(version, major, minor, patch, extra), runtime_error); } { string version = "0x.25.1"; EXPECT_THROW(parse_version_string(version, major, minor, patch, extra), runtime_error); } { string version = ".25.1"; EXPECT_THROW(parse_version_string(version, major, minor, patch, extra), runtime_error); } { string version = "123.456"; EXPECT_THROW(parse_version_string(version, major, minor, patch, extra), runtime_error); } { string version = ""; EXPECT_THROW(parse_version_string(version, major, minor, patch, extra), runtime_error); } { string version = "this is a test"; EXPECT_THROW(parse_version_string(version, major, minor, patch, extra), runtime_error); } } TEST(ngraph_api, version) { string version_label = NGRAPH_VERSION_LABEL; size_t expected_major; size_t expected_minor; size_t expected_patch; string expected_extra; parse_version_string( version_label, expected_major, expected_minor, expected_patch, expected_extra); size_t actual_major; size_t actual_minor; size_t actual_patch; string actual_extra; get_version(actual_major, actual_minor, actual_patch, actual_extra); EXPECT_EQ(expected_major, actual_major); EXPECT_EQ(expected_minor, actual_minor); EXPECT_EQ(expected_patch, actual_patch); EXPECT_STREQ(expected_extra.c_str(), actual_extra.c_str()); }
// mapnik #include <mapnik/color.hpp> // for color #include <mapnik/image.hpp> // for image types #include <mapnik/image_any.hpp> // for image_any #include <mapnik/image_reader.hpp> // for get_image_reader, etc #include <mapnik/image_util.hpp> // for save_to_string, guess_type, etc #include <mapnik/image_copy.hpp> #include <mapnik/image_compositing.hpp> #include <mapnik/image_filter_types.hpp> #include <mapnik/image_filter.hpp> // filter_visitor #include <mapnik/image_scaling.hpp> #include <mapnik/marker.hpp> #include <mapnik/marker_cache.hpp> #ifdef MAPNIK_METRICS #include <mapnik/metrics.hpp> #endif #include <mapnik/svg/svg_parser.hpp> #include <mapnik/svg/svg_storage.hpp> #include <mapnik/svg/svg_converter.hpp> #include <mapnik/svg/svg_path_adapter.hpp> #include <mapnik/svg/svg_path_attributes.hpp> #include <mapnik/svg/svg_path_adapter.hpp> #include <mapnik/svg/svg_renderer_agg.hpp> #include <mapnik/svg/svg_path_attributes.hpp> #include "mapnik_image.hpp" #include "mapnik_image_view.hpp" #include "mapnik_palette.hpp" #include "mapnik_color.hpp" #include "utils.hpp" #include "agg_rasterizer_scanline_aa.h" #include "agg_basics.h" #include "agg_rendering_buffer.h" #include "agg_renderer_base.h" #include "agg_pixfmt_rgba.h" #include "agg_scanline_u.h" // boost #include <boost/optional/optional.hpp> // std #include <exception> #include <ostream> // for operator<<, basic_ostream #include <sstream> // for basic_ostringstream, etc #include <cstdlib> Nan::Persistent<v8::FunctionTemplate> Image::constructor; /** * **`mapnik.Image`** * * Create a new image object (surface) that can be used for rendering data to. * @class Image * @param {number} width - width in pixels * @param {number} height - height in pixels * @param {Object} [options] * @param {Object<mapnik.imageType>} [options.type=mapnik.imageType.rgb8] - a {@link mapnik.imageType} object * @param {boolean} [options.initialize=true] * @param {boolean} [options.premultiplied=false] * @param {boolean} [options.painted=false] * @property {number} offset - offset number * @property {number} scaling - scaling number * @throws {TypeError} if any argument is the wrong type, like if width * or height is not numeric. * @example * var im = new mapnik.Image(256, 256, { * premultiplied: true, * type: mapnik.imageType.gray8 * }); */ void Image::Initialize(v8::Local<v8::Object> target) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> lcons = Nan::New<v8::FunctionTemplate>(Image::New); lcons->InstanceTemplate()->SetInternalFieldCount(1); lcons->SetClassName(Nan::New("Image").ToLocalChecked()); Nan::SetPrototypeMethod(lcons, "getType", getType); Nan::SetPrototypeMethod(lcons, "getPixel", getPixel); Nan::SetPrototypeMethod(lcons, "setPixel", setPixel); Nan::SetPrototypeMethod(lcons, "encodeSync", encodeSync); Nan::SetPrototypeMethod(lcons, "encode", encode); Nan::SetPrototypeMethod(lcons, "view", view); Nan::SetPrototypeMethod(lcons, "saveSync", saveSync); Nan::SetPrototypeMethod(lcons, "save", save); Nan::SetPrototypeMethod(lcons, "setGrayScaleToAlpha", setGrayScaleToAlpha); Nan::SetPrototypeMethod(lcons, "width", width); Nan::SetPrototypeMethod(lcons, "height", height); Nan::SetPrototypeMethod(lcons, "painted", painted); Nan::SetPrototypeMethod(lcons, "composite", composite); Nan::SetPrototypeMethod(lcons, "filter", filter); Nan::SetPrototypeMethod(lcons, "filterSync", filterSync); Nan::SetPrototypeMethod(lcons, "fillSync", fillSync); Nan::SetPrototypeMethod(lcons, "fill", fill); Nan::SetPrototypeMethod(lcons, "premultiplySync", premultiplySync); Nan::SetPrototypeMethod(lcons, "premultiply", premultiply); Nan::SetPrototypeMethod(lcons, "premultiplied", premultiplied); Nan::SetPrototypeMethod(lcons, "demultiplySync", demultiplySync); Nan::SetPrototypeMethod(lcons, "demultiply", demultiply); Nan::SetPrototypeMethod(lcons, "clear", clear); Nan::SetPrototypeMethod(lcons, "clearSync", clearSync); Nan::SetPrototypeMethod(lcons, "compare", compare); Nan::SetPrototypeMethod(lcons, "isSolid", isSolid); Nan::SetPrototypeMethod(lcons, "isSolidSync", isSolidSync); Nan::SetPrototypeMethod(lcons, "copy", copy); Nan::SetPrototypeMethod(lcons, "copySync", copySync); Nan::SetPrototypeMethod(lcons, "resize", resize); Nan::SetPrototypeMethod(lcons, "resizeSync", resizeSync); Nan::SetPrototypeMethod(lcons, "data", data); Nan::SetPrototypeMethod(lcons, "get_metrics", get_metrics); // properties ATTR(lcons, "scaling", get_scaling, set_scaling); ATTR(lcons, "offset", get_offset, set_offset); ATTR(lcons, "metrics_enabled", get_metrics_enabled, set_metrics_enabled); // This *must* go after the ATTR setting Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "open", Image::open); Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "fromBytes", Image::fromBytes); Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "openSync", Image::openSync); Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "fromBytesSync", Image::fromBytesSync); Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "fromBufferSync", Image::fromBufferSync); Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "fromSVG", Image::fromSVG); Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "fromSVGSync", Image::fromSVGSync); Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "fromSVGBytes", Image::fromSVGBytes); Nan::SetMethod(Nan::GetFunction(lcons).ToLocalChecked().As<v8::Object>(), "fromSVGBytesSync", Image::fromSVGBytesSync); Nan::Set(target, Nan::New("Image").ToLocalChecked(),Nan::GetFunction(lcons).ToLocalChecked()); constructor.Reset(lcons); } Image::Image(unsigned int width, unsigned int height, mapnik::image_dtype type, bool initialized, bool premultiplied, bool painted) : Nan::ObjectWrap(), this_(std::make_shared<mapnik::image_any>(width,height,type,initialized,premultiplied,painted)) { } Image::Image(image_ptr _this) : Nan::ObjectWrap(), this_(_this) { } Image::~Image() { } NAN_METHOD(Image::New) { if (!info.IsConstructCall()) { Nan::ThrowError("Cannot call constructor as function, you need to use 'new' keyword"); return; } if (info[0]->IsExternal()) { v8::Local<v8::External> ext = info[0].As<v8::External>(); void* ptr = ext->Value(); Image* im = static_cast<Image*>(ptr); im->Wrap(info.This()); info.GetReturnValue().Set(info.This()); return; } if (info.Length() >= 2) { mapnik::image_dtype type = mapnik::image_dtype_rgba8; bool initialize = true; bool premultiplied = false; bool painted = false; if (!info[0]->IsNumber() || !info[1]->IsNumber()) { Nan::ThrowTypeError("Image 'width' and 'height' must be a integers"); return; } if (info.Length() >= 3) { if (info[2]->IsObject()) { v8::Local<v8::Object> options = v8::Local<v8::Object>::Cast(info[2]); if (Nan::Has(options, Nan::New("type").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> init_val = Nan::Get(options, Nan::New("type").ToLocalChecked()).ToLocalChecked(); if (!init_val.IsEmpty() && init_val->IsNumber()) { int int_val = init_val->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (int_val >= mapnik::image_dtype::IMAGE_DTYPE_MAX || int_val < 0) { Nan::ThrowTypeError("Image 'type' must be a valid image type"); return; } type = static_cast<mapnik::image_dtype>(init_val->IntegerValue(Nan::GetCurrentContext()).ToChecked()); } else { Nan::ThrowTypeError("'type' option must be a valid 'mapnik.imageType'"); return; } } if (Nan::Has(options, Nan::New("initialize").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> init_val = Nan::Get(options, Nan::New("initialize").ToLocalChecked()).ToLocalChecked(); if (!init_val.IsEmpty() && init_val->IsBoolean()) { initialize = init_val->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowTypeError("initialize option must be a boolean"); return; } } if (Nan::Has(options, Nan::New("premultiplied").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> pre_val = Nan::Get(options, Nan::New("premultiplied").ToLocalChecked()).ToLocalChecked(); if (!pre_val.IsEmpty() && pre_val->IsBoolean()) { premultiplied = pre_val->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowTypeError("premultiplied option must be a boolean"); return; } } if (Nan::Has(options, Nan::New("painted").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> painted_val = Nan::Get(options, Nan::New("painted").ToLocalChecked()).ToLocalChecked(); if (!painted_val.IsEmpty() && painted_val->IsBoolean()) { painted = painted_val->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowTypeError("painted option must be a boolean"); return; } } } else { Nan::ThrowTypeError("Options parameter must be an object"); return; } } try { Image* im = new Image(info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked(), info[1]->IntegerValue(Nan::GetCurrentContext()).ToChecked(), type, initialize, premultiplied, painted); im->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } catch (std::exception const& ex) { Nan::ThrowError(ex.what()); } return; } else { Nan::ThrowError("please provide at least Image width and height"); return; } return; } /** * Determine the image type * * @name getType * @instance * @returns {number} Number of the image type * @memberof Image * @example * var img = new mapnik.Image(256, 256, { * type: mapnik.imageType.gray8 * }); * var type = img.getType(); * var typeCheck = mapnik.imageType.gray8; * console.log(type, typeCheck); // 1, 1 */ NAN_METHOD(Image::getType) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); unsigned type = im->this_->get_dtype(); info.GetReturnValue().Set(Nan::New<v8::Number>(type)); } struct visitor_get_pixel { visitor_get_pixel(int x, int y) : x_(x), y_(y) {} v8::Local<v8::Value> operator() (mapnik::image_null const&) { // This should never be reached because the width and height of 0 for a null // image will prevent the visitor from being called. /* LCOV_EXCL_START */ Nan::EscapableHandleScope scope; return scope.Escape(Nan::Undefined()); /* LCOV_EXCL_STOP */ } v8::Local<v8::Value> operator() (mapnik::image_gray8 const& data) { Nan::EscapableHandleScope scope; std::uint32_t val = mapnik::get_pixel<std::uint32_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Uint32>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray8s const& data) { Nan::EscapableHandleScope scope; std::int32_t val = mapnik::get_pixel<std::int32_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Int32>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray16 const& data) { Nan::EscapableHandleScope scope; std::uint32_t val = mapnik::get_pixel<std::uint32_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Uint32>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray16s const& data) { Nan::EscapableHandleScope scope; std::int32_t val = mapnik::get_pixel<std::int32_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Int32>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray32 const& data) { Nan::EscapableHandleScope scope; std::uint32_t val = mapnik::get_pixel<std::uint32_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Uint32>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray32s const& data) { Nan::EscapableHandleScope scope; std::int32_t val = mapnik::get_pixel<std::int32_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Int32>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray32f const& data) { Nan::EscapableHandleScope scope; double val = mapnik::get_pixel<double>(data, x_, y_); return scope.Escape(Nan::New<v8::Number>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray64 const& data) { Nan::EscapableHandleScope scope; std::uint64_t val = mapnik::get_pixel<std::uint64_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Number>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray64s const& data) { Nan::EscapableHandleScope scope; std::int64_t val = mapnik::get_pixel<std::int64_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Number>(val)); } v8::Local<v8::Value> operator() (mapnik::image_gray64f const& data) { Nan::EscapableHandleScope scope; double val = mapnik::get_pixel<double>(data, x_, y_); return scope.Escape(Nan::New<v8::Number>(val)); } v8::Local<v8::Value> operator() (mapnik::image_rgba8 const& data) { Nan::EscapableHandleScope scope; std::uint32_t val = mapnik::get_pixel<std::uint32_t>(data, x_, y_); return scope.Escape(Nan::New<v8::Number>(val)); } private: int x_; int y_; }; /** * Get a specific pixel and its value * @name getPixel * @instance * @memberof Image * @param {number} x - position within image from top left * @param {number} y - position within image from top left * @param {Object} [options] the only valid option is `get_color`, which * should be a `boolean`. If set, the return is an Object with `rgba` values * instead of a pixel number. * @returns {number|Object} color number or object of rgba values * @example * // check for color after rendering image * var img = new mapnik.Image(4, 4); * var map = new mapnik.Map(4, 4); * map.background = new mapnik.Color('green'); * map.render(img, {},function(err, img) { * console.log(img.painted()); // false * var pixel = img.getPixel(0,0); * var values = img.getPixel(0,0, {get_color: true}); * console.log(pixel); // 4278222848 * console.log(values); // { premultiplied: false, a: 255, b: 0, g: 128, r: 0 } * }); */ NAN_METHOD(Image::getPixel) { int x = 0; int y = 0; bool get_color = false; if (info.Length() >= 3) { if (!info[2]->IsObject()) { Nan::ThrowTypeError("optional third argument must be an options object"); return; } v8::Local<v8::Object> options = info[2]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (Nan::Has(options, Nan::New("get_color").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> bind_opt = Nan::Get(options, Nan::New("get_color").ToLocalChecked()).ToLocalChecked(); if (!bind_opt->IsBoolean()) { Nan::ThrowTypeError("optional arg 'color' must be a boolean"); return; } get_color = bind_opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } } if (info.Length() >= 2) { if (!info[0]->IsNumber()) { Nan::ThrowTypeError("first arg, 'x' must be an integer"); return; } if (!info[1]->IsNumber()) { Nan::ThrowTypeError("second arg, 'y' must be an integer"); return; } x = info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); y = info[1]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowError("must supply x,y to query pixel color"); return; } Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (x >= 0 && x < static_cast<int>(im->this_->width()) && y >= 0 && y < static_cast<int>(im->this_->height())) { if (get_color) { mapnik::color val = mapnik::get_pixel<mapnik::color>(*im->this_, x, y); info.GetReturnValue().Set(Color::NewInstance(val)); } else { visitor_get_pixel visitor(x, y); info.GetReturnValue().Set(mapnik::util::apply_visitor(visitor, *im->this_)); } } return; } /** * Set a pixels value * @name setPixel * @instance * @memberof Image * @param {number} x position within image from top left * @param {number} y position within image from top left * @param {Object|number} numeric or object representation of a color, typically used with {@link mapnik.Color} * @example * var gray = new mapnik.Image(256, 256); * gray.setPixel(0,0,new mapnik.Color('white')); * var pixel = gray.getPixel(0,0,{get_color:true}); * console.log(pixel); // { premultiplied: false, a: 255, b: 255, g: 255, r: 255 } */ NAN_METHOD(Image::setPixel) { if (info.Length() < 3 || (!info[0]->IsNumber() && !info[1]->IsNumber())) { Nan::ThrowTypeError("expects three arguments: x, y, and pixel value"); return; } int x = info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); int y = info[1]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (x < 0 || x >= static_cast<int>(im->this_->width()) || y < 0 || y >= static_cast<int>(im->this_->height())) { Nan::ThrowTypeError("invalid pixel requested"); return; } if (info[2]->IsUint32()) { std::uint32_t val = info[2]->Uint32Value(Nan::GetCurrentContext()).ToChecked(); mapnik::set_pixel<std::uint32_t>(*im->this_,x,y,val); } else if (info[2]->IsInt32()) { std::int32_t val = info[2]->Int32Value(Nan::GetCurrentContext()).ToChecked(); mapnik::set_pixel<std::int32_t>(*im->this_,x,y,val); } else if (info[2]->IsNumber()) { double val = info[2]->NumberValue(Nan::GetCurrentContext()).ToChecked(); mapnik::set_pixel<double>(*im->this_,x,y,val); } else if (info[2]->IsObject()) { v8::Local<v8::Object> obj = info[2]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Color::constructor)->HasInstance(obj)) { Nan::ThrowTypeError("A numeric or color value is expected as third arg"); } else { Color * color = Nan::ObjectWrap::Unwrap<Color>(obj); mapnik::set_pixel(*im->this_,x,y,*(color->get())); } } else { Nan::ThrowTypeError("A numeric or color value is expected as third arg"); } return; } /** * Compare the pixels of one image to the pixels of another. Returns the number * of pixels that are different. So, if the images are identical then it returns `0`. * And if the images share no common pixels it returns the total number of pixels * in an image which is equivalent to `im.width()*im.height()`. * * @name compare * @instance * @memberof Image * @param {mapnik.Image} image - another {@link mapnik.Image} instance to compare to * @param {Object} [options] * @param {number} [options.threshold=16] - A value that should be `0` or greater to * determine if the pixels match. Defaults to 16 which means that `rgba(0,0,0,0)` * would be considered the same as `rgba(15,15,15,0)`. * @param {boolean} [options.alpha=true] - `alpha` value, along with `rgb`, is considered * when comparing pixels * @returns {number} quantified visual difference between these two images in "number of * pixels" (i.e. `80` pixels are different); * @example * // start with the exact same images * var img1 = new mapnik.Image(2,2); * var img2 = new mapnik.Image(2,2); * console.log(img1.compare(img2)); // 0 * * // change 1 pixel in img2 * img2.setPixel(0,0, new mapnik.Color('green')); * console.log(img1.compare(img2)); // 1 * * // difference in color at first pixel * img1.setPixel(0,0, new mapnik.Color('red')); * console.log(img1.compare(img2)); // 1 * * // two pixels different * img2.setPixel(0,1, new mapnik.Color('red')); * console.log(img1.compare(img2)); // 2 * * // all pixels different * img2.setPixel(1,1, new mapnik.Color('blue')); * img2.setPixel(1,0, new mapnik.Color('blue')); * console.log(img1.compare(img2)); // 4 */ NAN_METHOD(Image::compare) { if (info.Length() < 1 || !info[0]->IsObject()) { Nan::ThrowTypeError("first argument should be a mapnik.Image"); return; } v8::Local<v8::Object> obj = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Image::constructor)->HasInstance(obj)) { Nan::ThrowTypeError("mapnik.Image expected as first arg"); return; } int threshold = 16; unsigned alpha = true; if (info.Length() > 1) { if (!info[1]->IsObject()) { Nan::ThrowTypeError("optional second argument must be an options object"); return; } v8::Local<v8::Object> options = info[1]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (Nan::Has(options, Nan::New("threshold").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> bind_opt = Nan::Get(options, Nan::New("threshold").ToLocalChecked()).ToLocalChecked(); if (!bind_opt->IsNumber()) { Nan::ThrowTypeError("optional arg 'threshold' must be a number"); return; } threshold = bind_opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("alpha").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> bind_opt = Nan::Get(options, Nan::New("alpha").ToLocalChecked()).ToLocalChecked(); if (!bind_opt->IsBoolean()) { Nan::ThrowTypeError("optional arg 'alpha' must be a boolean"); return; } alpha = bind_opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } } Image* im = Nan::ObjectWrap::Unwrap<Image>(info.This()); Image* im2 = Nan::ObjectWrap::Unwrap<Image>(obj); if (im->this_->width() != im2->this_->width() || im->this_->height() != im2->this_->height()) { Nan::ThrowTypeError("image dimensions do not match"); return; } unsigned difference = mapnik::compare(*im->this_, *im2->this_, threshold, alpha); info.GetReturnValue().Set(Nan::New<v8::Integer>(difference)); } /** * Apply a filter to this image. This changes all pixel values. (synchronous) * * @name filterSync * @instance * @memberof Image * @param {string} filter - can be `blur`, `emboss`, `sharpen`, * `sobel`, or `gray`. * @example * var img = new mapnik.Image(5, 5); * img.filter('blur'); * // your custom code with `img` having blur applied */ NAN_METHOD(Image::filterSync) { info.GetReturnValue().Set(_filterSync(info)); } v8::Local<v8::Value> Image::_filterSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; if (info.Length() < 1) { Nan::ThrowTypeError("expects one argument: string filter argument"); return scope.Escape(Nan::Undefined()); } Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (!info[0]->IsString()) { Nan::ThrowTypeError("A string is expected for filter argument"); return scope.Escape(Nan::Undefined()); } std::string filter = TOSTR(info[0]); try { mapnik::filter::filter_image(*im->this_,filter); } catch(std::exception const& ex) { Nan::ThrowError(ex.what()); } return scope.Escape(Nan::Undefined()); } typedef struct { uv_work_t request; Image* im; std::string filter; bool error; std::string error_name; Nan::Persistent<v8::Function> cb; } filter_image_baton_t; /** * Apply a filter to this image. Changes all pixel values. * * @name filter * @instance * @memberof Image * @param {string} filter - can be `blur`, `emboss`, `sharpen`, * `sobel`, or `gray`. * @param {Function} callback - `function(err, img)` * @example * var img = new mapnik.Image(5, 5); * img.filter('sobel', function(err, img) { * if (err) throw err; * // your custom `img` with sobel filter * // https://en.wikipedia.org/wiki/Sobel_operator * }); */ NAN_METHOD(Image::filter) { if (info.Length() <= 1) { info.GetReturnValue().Set(_filterSync(info)); return; } if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (!info[0]->IsString()) { Nan::ThrowTypeError("A string is expected for filter argument"); return; } filter_image_baton_t *closure = new filter_image_baton_t(); closure->filter = TOSTR(info[0]); // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length()-1]; closure->request.data = closure; closure->im = im; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Filter, (uv_after_work_cb)EIO_AfterFilter); im->_ref(); return; } void Image::EIO_Filter(uv_work_t* req) { filter_image_baton_t *closure = static_cast<filter_image_baton_t *>(req->data); try { mapnik::filter::filter_image(*closure->im->this_,closure->filter); } catch(std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterFilter(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); filter_image_baton_t *closure = static_cast<filter_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), closure->im->handle() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } closure->im->_unref(); closure->cb.Reset(); delete closure; } /** * Fill this image with a given color. Changes all pixel values. (synchronous) * * @name fillSync * @instance * @memberof Image * @param {mapnik.Color|number} color * @example * var img = new mapnik.Image(5,5); * // blue pixels * img.fillSync(new mapnik.Color('blue')); * var colors = img.getPixel(0,0, {get_color: true}); * // blue value is filled * console.log(colors.b); // 255 */ NAN_METHOD(Image::fillSync) { info.GetReturnValue().Set(_fillSync(info)); } v8::Local<v8::Value> Image::_fillSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; if (info.Length() < 1 ) { Nan::ThrowTypeError("expects one argument: Color object or a number"); return scope.Escape(Nan::Undefined()); } Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); try { if (info[0]->IsUint32()) { std::uint32_t val = info[0]->Uint32Value(Nan::GetCurrentContext()).ToChecked(); mapnik::fill<std::uint32_t>(*im->this_,val); } else if (info[0]->IsInt32()) { std::int32_t val = info[0]->Int32Value(Nan::GetCurrentContext()).ToChecked(); mapnik::fill<std::int32_t>(*im->this_,val); } else if (info[0]->IsNumber()) { double val = info[0]->NumberValue(Nan::GetCurrentContext()).ToChecked(); mapnik::fill<double>(*im->this_,val); } else if (info[0]->IsObject()) { v8::Local<v8::Object> obj = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Color::constructor)->HasInstance(obj)) { Nan::ThrowTypeError("A numeric or color value is expected"); } else { Color * color = Nan::ObjectWrap::Unwrap<Color>(obj); mapnik::fill(*im->this_,*(color->get())); } } else { Nan::ThrowTypeError("A numeric or color value is expected"); } } catch(std::exception const& ex) { Nan::ThrowError(ex.what()); } return scope.Escape(Nan::Undefined()); } enum fill_type : std::uint8_t { FILL_COLOR = 0, FILL_UINT32, FILL_INT32, FILL_DOUBLE }; typedef struct { uv_work_t request; Image* im; fill_type type; mapnik::color c; std::uint32_t val_u32; std::int32_t val_32; double val_double; //std::string format; bool error; std::string error_name; Nan::Persistent<v8::Function> cb; } fill_image_baton_t; /** * Fill this image with a given color. Changes all pixel values. * * @name fill * @instance * @memberof Image * @param {mapnik.Color|number} color * @param {Function} callback - `function(err, img)` * @example * var img = new mapnik.Image(5,5); * img.fill(new mapnik.Color('blue'), function(err, img) { * if (err) throw err; * var colors = img.getPixel(0,0, {get_color: true}); * pixel is colored blue * console.log(color.b); // 255 * }); * * // or fill with rgb string * img.fill('rgba(255,255,255,0)', function(err, img) { ... }); */ NAN_METHOD(Image::fill) { if (info.Length() <= 1) { info.GetReturnValue().Set(_fillSync(info)); return; } Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); fill_image_baton_t *closure = new fill_image_baton_t(); if (info[0]->IsUint32()) { closure->val_u32 = info[0]->Uint32Value(Nan::GetCurrentContext()).ToChecked(); closure->type = FILL_UINT32; } else if (info[0]->IsInt32()) { closure->val_32 = info[0]->Int32Value(Nan::GetCurrentContext()).ToChecked(); closure->type = FILL_INT32; } else if (info[0]->IsNumber()) { closure->val_double = info[0]->NumberValue(Nan::GetCurrentContext()).ToChecked(); closure->type = FILL_DOUBLE; } else if (info[0]->IsObject()) { v8::Local<v8::Object> obj = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Color::constructor)->HasInstance(obj)) { delete closure; Nan::ThrowTypeError("A numeric or color value is expected"); return; } else { Color * color = Nan::ObjectWrap::Unwrap<Color>(obj); closure->c = *(color->get()); } } else { delete closure; Nan::ThrowTypeError("A numeric or color value is expected"); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length()-1]; if (!info[info.Length()-1]->IsFunction()) { delete closure; Nan::ThrowTypeError("last argument must be a callback function"); return; } else { closure->request.data = closure; closure->im = im; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Fill, (uv_after_work_cb)EIO_AfterFill); im->_ref(); } return; } void Image::EIO_Fill(uv_work_t* req) { fill_image_baton_t *closure = static_cast<fill_image_baton_t *>(req->data); try { switch (closure->type) { case FILL_UINT32: mapnik::fill(*closure->im->this_, closure->val_u32); break; case FILL_INT32: mapnik::fill(*closure->im->this_, closure->val_32); break; default: case FILL_DOUBLE: mapnik::fill(*closure->im->this_, closure->val_double); break; case FILL_COLOR: mapnik::fill(*closure->im->this_,closure->c); break; } } catch(std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterFill(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); fill_image_baton_t *closure = static_cast<fill_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), closure->im->handle() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } closure->im->_unref(); closure->cb.Reset(); delete closure; } /** * Make this image transparent. (synchronous) * * @name clearSync * @instance * @memberof Image * @example * var img = new mapnik.Image(5,5); * img.fillSync(1); * console.log(img.getPixel(0, 0)); // 1 * img.clearSync(); * console.log(img.getPixel(0, 0)); // 0 */ NAN_METHOD(Image::clearSync) { info.GetReturnValue().Set(_clearSync(info)); } v8::Local<v8::Value> Image::_clearSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); try { mapnik::fill(*im->this_, 0); } catch(std::exception const& ex) { Nan::ThrowError(ex.what()); } return scope.Escape(Nan::Undefined()); } typedef struct { uv_work_t request; Image* im; //std::string format; bool error; std::string error_name; Nan::Persistent<v8::Function> cb; } clear_image_baton_t; /** * Make this image transparent, removing all image data from it. * * @name clear * @instance * @param {Function} callback * @memberof Image * @example * var img = new mapnik.Image(5,5); * img.fillSync(1); * console.log(img.getPixel(0, 0)); // 1 * img.clear(function(err, result) { * console.log(result.getPixel(0,0)); // 0 * }); */ NAN_METHOD(Image::clear) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (info.Length() == 0) { info.GetReturnValue().Set(_clearSync(info)); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length()-1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } clear_image_baton_t *closure = new clear_image_baton_t(); closure->request.data = closure; closure->im = im; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Clear, (uv_after_work_cb)EIO_AfterClear); im->_ref(); return; } void Image::EIO_Clear(uv_work_t* req) { clear_image_baton_t *closure = static_cast<clear_image_baton_t *>(req->data); try { mapnik::fill(*closure->im->this_, 0); } catch(std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterClear(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); clear_image_baton_t *closure = static_cast<clear_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), closure->im->handle() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } closure->im->_unref(); closure->cb.Reset(); delete closure; } /** * Convert all grayscale values to alpha values. Great for creating * a mask layer based on alpha values. * * @name setGrayScaleToAlpha * @memberof Image * @instance * @param {mapnik.Color} color * @example * var image = new mapnik.Image(2,2); * image.fillSync(new mapnik.Color('rgba(0,0,0,255)')); * console.log(image.getPixel(0,0, {get_color:true})); // { premultiplied: false, a: 255, b: 0, g: 0, r: 0 } * * image.setGrayScaleToAlpha(); * // turns a black pixel into a completely transparent mask * console.log(image.getPixel(0,0, {get_color:true})); // { premultiplied: false, a: 0, b: 255, g: 255, r: 255 } */ NAN_METHOD(Image::setGrayScaleToAlpha) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (info.Length() == 0) { mapnik::set_grayscale_to_alpha(*im->this_); } else { if (!info[0]->IsObject()) { Nan::ThrowTypeError("optional first arg must be a mapnik.Color"); return; } v8::Local<v8::Object> obj = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Color::constructor)->HasInstance(obj)) { Nan::ThrowTypeError("mapnik.Color expected as first arg"); return; } Color * color = Nan::ObjectWrap::Unwrap<Color>(obj); mapnik::set_grayscale_to_alpha(*im->this_, *color->get()); } return; } typedef struct { uv_work_t request; Image* im; Nan::Persistent<v8::Function> cb; } image_op_baton_t; /** * Determine whether the given image is premultiplied. * https://en.wikipedia.org/wiki/Alpha_compositing * * @name premultiplied * @memberof Image * @instance * @returns {boolean} premultiplied `true` if the image is premultiplied * @example * var img = new mapnik.Image(5,5); * console.log(img.premultiplied()); // false * img.premultiplySync() * console.log(img.premultiplied()); // true */ NAN_METHOD(Image::premultiplied) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); bool premultiplied = im->this_->get_premultiplied(); info.GetReturnValue().Set(Nan::New<v8::Boolean>(premultiplied)); } /** * Premultiply the pixels in this image. * * @name premultiplySync * @instance * @memberof Image * @example * var img = new mapnik.Image(5,5); * img.premultiplySync(); * console.log(img.premultiplied()); // true */ NAN_METHOD(Image::premultiplySync) { info.GetReturnValue().Set(_premultiplySync(info)); } v8::Local<v8::Value> Image::_premultiplySync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); mapnik::premultiply_alpha(*im->this_); return scope.Escape(Nan::Undefined()); } /** * Premultiply the pixels in this image, asynchronously * * @name premultiply * @memberof Image * @instance * @param {Function} callback * @example * var img = new mapnik.Image(5,5); * img.premultiply(function(err, img) { * if (err) throw err; * // your custom code with premultiplied img * }) */ NAN_METHOD(Image::premultiply) { if (info.Length() == 0) { info.GetReturnValue().Set(_premultiplySync(info)); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length()-1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); image_op_baton_t *closure = new image_op_baton_t(); closure->request.data = closure; closure->im = im; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Premultiply, (uv_after_work_cb)EIO_AfterMultiply); im->_ref(); return; } void Image::EIO_Premultiply(uv_work_t* req) { image_op_baton_t *closure = static_cast<image_op_baton_t *>(req->data); mapnik::premultiply_alpha(*closure->im->this_); } void Image::EIO_AfterMultiply(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); image_op_baton_t *closure = static_cast<image_op_baton_t *>(req->data); v8::Local<v8::Value> argv[2] = { Nan::Null(), closure->im->handle() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); closure->im->_unref(); closure->cb.Reset(); delete closure; } /** * Demultiply the pixels in this image. The opposite of * premultiplying. * * @name demultiplySync * @instance * @memberof Image */ NAN_METHOD(Image::demultiplySync) { Nan::HandleScope scope; info.GetReturnValue().Set(_demultiplySync(info)); } v8::Local<v8::Value> Image::_demultiplySync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); mapnik::demultiply_alpha(*im->this_); return scope.Escape(Nan::Undefined()); } /** * Demultiply the pixels in this image, asynchronously. The opposite of * premultiplying * * @name demultiply * @param {Function} callback * @instance * @memberof Image */ NAN_METHOD(Image::demultiply) { if (info.Length() == 0) { info.GetReturnValue().Set(_demultiplySync(info)); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length()-1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); image_op_baton_t *closure = new image_op_baton_t(); closure->request.data = closure; closure->im = im; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Demultiply, (uv_after_work_cb)EIO_AfterMultiply); im->_ref(); return; } void Image::EIO_Demultiply(uv_work_t* req) { image_op_baton_t *closure = static_cast<image_op_baton_t *>(req->data); mapnik::demultiply_alpha(*closure->im->this_); } typedef struct { uv_work_t request; Image* im; Nan::Persistent<v8::Function> cb; bool error; std::string error_name; bool result; } is_solid_image_baton_t; /** * Test if an image's pixels are all exactly the same * @name isSolid * @memberof Image * @instance * @returns {boolean} `true` means all pixels are exactly the same * @example * var img = new mapnik.Image(2,2); * console.log(img.isSolid()); // true * * // change a pixel * img.setPixel(0,0, new mapnik.Color('green')); * console.log(img.isSolid()); // false */ NAN_METHOD(Image::isSolid) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (info.Length() == 0) { info.GetReturnValue().Set(_isSolidSync(info)); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length() - 1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } is_solid_image_baton_t *closure = new is_solid_image_baton_t(); closure->request.data = closure; closure->im = im; closure->result = true; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_IsSolid, (uv_after_work_cb)EIO_AfterIsSolid); im->_ref(); return; } void Image::EIO_IsSolid(uv_work_t* req) { is_solid_image_baton_t *closure = static_cast<is_solid_image_baton_t *>(req->data); if (closure->im->this_->width() > 0 && closure->im->this_->height() > 0) { closure->result = mapnik::is_solid(*(closure->im->this_)); } else { closure->error = true; closure->error_name = "image does not have valid dimensions"; } } void Image::EIO_AfterIsSolid(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); is_solid_image_baton_t *closure = static_cast<is_solid_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { if (closure->result) { v8::Local<v8::Value> argv[3] = { Nan::Null(), Nan::New(closure->result), mapnik::util::apply_visitor(visitor_get_pixel(0,0),*(closure->im->this_)), }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 3, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), Nan::New(closure->result) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } } closure->im->_unref(); closure->cb.Reset(); delete closure; } /** * Determine whether the image is solid - whether it has alpha values of greater * than one. * * @name isSolidSync * @returns {boolean} whether the image is solid * @instance * @memberof Image * @example * var img = new mapnik.Image(256, 256); * var view = img.view(0, 0, 256, 256); * console.log(view.isSolidSync()); // true */ NAN_METHOD(Image::isSolidSync) { info.GetReturnValue().Set(_isSolidSync(info)); } v8::Local<v8::Value> Image::_isSolidSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (im->this_->width() > 0 && im->this_->height() > 0) { return scope.Escape(Nan::New<v8::Boolean>(mapnik::is_solid(*(im->this_)))); } Nan::ThrowError("image does not have valid dimensions"); return scope.Escape(Nan::Undefined()); } typedef struct { uv_work_t request; Image* im1; image_ptr im2; mapnik::image_dtype type; double offset; double scaling; Nan::Persistent<v8::Function> cb; bool error; std::string error_name; } copy_image_baton_t; /** * Copy an image into a new image by creating a clone * @name copy * @instance * @memberof Image * @param {number} type - image type to clone into, can be any mapnik.imageType number * @param {Object} [options={}] * @param {number} [options.scaling] - scale the image * @param {number} [options.offset] - offset this image * @param {Function} callback * @example * var img = new mapnik.Image(4, 4, {type: mapnik.imageType.gray16}); * var img2 = img.copy(mapnik.imageType.gray8, function(err, img2) { * if (err) throw err; * // custom code with `img2` converted into gray8 type * }); */ NAN_METHOD(Image::copy) { // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length() - 1]; if (!info[info.Length()-1]->IsFunction()) { info.GetReturnValue().Set(_copySync(info)); return; } Image* im1 = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); double offset = 0.0; bool scaling_or_offset_set = false; double scaling = 1.0; mapnik::image_dtype type = im1->this_->get_dtype(); v8::Local<v8::Object> options = Nan::New<v8::Object>(); if (info.Length() >= 2) { if (info[0]->IsNumber()) { type = static_cast<mapnik::image_dtype>(info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked()); if (type >= mapnik::image_dtype::IMAGE_DTYPE_MAX) { Nan::ThrowTypeError("Image 'type' must be a valid image type"); return; } } else if (info[0]->IsObject()) { options = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); } else { Nan::ThrowTypeError("Unknown parameters passed"); return; } } if (info.Length() >= 3) { if (info[1]->IsObject()) { options = info[1]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); } else { Nan::ThrowTypeError("Expected options object as second argument"); return; } } if (Nan::Has(options, Nan::New("scaling").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> scaling_val = Nan::Get(options, Nan::New("scaling").ToLocalChecked()).ToLocalChecked(); if (scaling_val->IsNumber()) { scaling = scaling_val->NumberValue(Nan::GetCurrentContext()).ToChecked(); scaling_or_offset_set = true; } else { Nan::ThrowTypeError("scaling argument must be a number"); return; } } if (Nan::Has(options, Nan::New("offset").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> offset_val = Nan::Get(options, Nan::New("offset").ToLocalChecked()).ToLocalChecked(); if (offset_val->IsNumber()) { offset = offset_val->NumberValue(Nan::GetCurrentContext()).ToChecked(); scaling_or_offset_set = true; } else { Nan::ThrowTypeError("offset argument must be a number"); return; } } if (!scaling_or_offset_set && type == im1->this_->get_dtype()) { scaling = im1->this_->get_scaling(); offset = im1->this_->get_offset(); } copy_image_baton_t *closure = new copy_image_baton_t(); closure->request.data = closure; closure->im1 = im1; closure->offset = offset; closure->scaling = scaling; closure->type = type; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Copy, (uv_after_work_cb)EIO_AfterCopy); closure->im1->_ref(); return; } void Image::EIO_Copy(uv_work_t* req) { copy_image_baton_t *closure = static_cast<copy_image_baton_t *>(req->data); try { closure->im2 = std::make_shared<mapnik::image_any>( mapnik::image_copy(*(closure->im1->this_), closure->type, closure->offset, closure->scaling) ); } catch (std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterCopy(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); copy_image_baton_t *closure = static_cast<copy_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else if (!closure->im2) { // Not quite sure if this is even required or ever can be reached, but leaving it // and simply removing it from coverage tests. /* LCOV_EXCL_START */ v8::Local<v8::Value> argv[1] = { Nan::Error("could not render to image") }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); /* LCOV_EXCL_STOP */ } else { Image* im = new Image(closure->im2); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) { v8::Local<v8::Value> argv[1] = { Nan::Error("Could not create new Image instance") }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), maybe_local.ToLocalChecked() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } } closure->im1->_unref(); closure->cb.Reset(); delete closure; } /** * Copy an image into a new image by creating a clone * @name copySync * @instance * @memberof Image * @param {number} type - image type to clone into, can be any mapnik.imageType number * @param {Object} [options={}] * @param {number} [options.scaling] - scale the image * @param {number} [options.offset] - offset this image * @returns {mapnik.Image} copy * @example * var img = new mapnik.Image(4, 4, {type: mapnik.imageType.gray16}); * var img2 = img.copy(mapnik.imageType.gray8); * // custom code with `img2` as a gray8 type */ NAN_METHOD(Image::copySync) { info.GetReturnValue().Set(_copySync(info)); } v8::Local<v8::Value> Image::_copySync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); double offset = 0.0; bool scaling_or_offset_set = false; double scaling = 1.0; mapnik::image_dtype type = im->this_->get_dtype(); v8::Local<v8::Object> options = Nan::New<v8::Object>(); if (info.Length() >= 1) { if (info[0]->IsNumber()) { type = static_cast<mapnik::image_dtype>(info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked()); if (type >= mapnik::image_dtype::IMAGE_DTYPE_MAX) { Nan::ThrowTypeError("Image 'type' must be a valid image type"); return scope.Escape(Nan::Undefined()); } } else if (info[0]->IsObject()) { options = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); } else { Nan::ThrowTypeError("Unknown parameters passed"); return scope.Escape(Nan::Undefined()); } } if (info.Length() >= 2) { if (info[1]->IsObject()) { options = info[1]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); } else { Nan::ThrowTypeError("Expected options object as second argument"); return scope.Escape(Nan::Undefined()); } } if (Nan::Has(options, Nan::New("scaling").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> scaling_val = Nan::Get(options, Nan::New("scaling").ToLocalChecked()).ToLocalChecked(); if (scaling_val->IsNumber()) { scaling = scaling_val->NumberValue(Nan::GetCurrentContext()).ToChecked(); scaling_or_offset_set = true; } else { Nan::ThrowTypeError("scaling argument must be a number"); return scope.Escape(Nan::Undefined()); } } if (Nan::Has(options, Nan::New("offset").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> offset_val = Nan::Get(options, Nan::New("offset").ToLocalChecked()).ToLocalChecked(); if (offset_val->IsNumber()) { offset = offset_val->NumberValue(Nan::GetCurrentContext()).ToChecked(); scaling_or_offset_set = true; } else { Nan::ThrowTypeError("offset argument must be a number"); return scope.Escape(Nan::Undefined()); } } if (!scaling_or_offset_set && type == im->this_->get_dtype()) { scaling = im->this_->get_scaling(); offset = im->this_->get_offset(); } try { image_ptr imagep = std::make_shared<mapnik::image_any>( mapnik::image_copy(*(im->this_), type, offset, scaling) ); Image* new_im = new Image(imagep); v8::Local<v8::Value> ext = Nan::New<v8::External>(new_im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) Nan::ThrowError("Could not create new Image instance"); return scope.Escape(maybe_local.ToLocalChecked()); } catch (std::exception const& ex) { Nan::ThrowError(ex.what()); return scope.Escape(Nan::Undefined()); } } typedef struct { uv_work_t request; Image* im1; image_ptr im2; mapnik::scaling_method_e scaling_method; std::size_t size_x; std::size_t size_y; int offset_x; int offset_y; double filter_factor; Nan::Persistent<v8::Function> cb; bool error; std::string error_name; } resize_image_baton_t; /** * Resize this image (makes a copy) * * @name resize * @instance * @memberof Image * @param {number} width - in pixels * @param {number} height - in pixels * @param {Object} [options={}] * @param {number} [options.offset_x=0] - offset the image horizontally in pixels * @param {number} [options.offset_y=0] - offset the image vertically in pixels * @param {mapnik.imageScaling} [options.scaling_method=mapnik.imageScaling.near] - scaling method * @param {number} [options.filter_factor=1.0] * @param {Function} callback - `function(err, result)` * @example * var img = new mapnik.Image(4, 4, {type: mapnik.imageType.gray8}); * img.resize(8, 8, function(err, result) { * if (err) throw err; * // new image object as `result` * }); */ NAN_METHOD(Image::resize) { // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length() - 1]; if (!info[info.Length()-1]->IsFunction()) { info.GetReturnValue().Set(_resizeSync(info)); return; } Image* im1 = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); std::size_t width = 0; std::size_t height = 0; int offset_x = 0; int offset_y = 0; double filter_factor = 1.0; mapnik::scaling_method_e scaling_method = mapnik::SCALING_NEAR; v8::Local<v8::Object> options = Nan::New<v8::Object>(); if (info.Length() >= 3) { if (info[0]->IsNumber()) { auto width_tmp = info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (width_tmp <= 0) { Nan::ThrowTypeError("Width must be a integer greater then zero"); return; } width = static_cast<std::size_t>(width_tmp); } else { Nan::ThrowTypeError("Width must be a number"); return; } if (info[1]->IsNumber()) { auto height_tmp = info[1]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (height_tmp <= 0) { Nan::ThrowTypeError("Height must be a integer greater then zero"); return; } height = static_cast<std::size_t>(height_tmp); } else { Nan::ThrowTypeError("Height must be a number"); return; } } else { Nan::ThrowTypeError("resize requires a width and height parameter."); return; } if (info.Length() >= 4) { if (info[2]->IsObject()) { options = info[2]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); } else { Nan::ThrowTypeError("Expected options object as third argument"); return; } } if (Nan::Has(options, Nan::New("offset_x").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> bind_opt = Nan::Get(options, Nan::New("offset_x").ToLocalChecked()).ToLocalChecked(); if (!bind_opt->IsNumber()) { Nan::ThrowTypeError("optional arg 'offset_x' must be a number"); return; } offset_x = bind_opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("offset_y").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> bind_opt = Nan::Get(options, Nan::New("offset_y").ToLocalChecked()).ToLocalChecked(); if (!bind_opt->IsNumber()) { Nan::ThrowTypeError("optional arg 'offset_y' must be a number"); return; } offset_y = bind_opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("scaling_method").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> scaling_val = Nan::Get(options, Nan::New("scaling_method").ToLocalChecked()).ToLocalChecked(); if (scaling_val->IsNumber()) { std::int64_t scaling_int = scaling_val->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (scaling_int > mapnik::SCALING_BLACKMAN || scaling_int < 0) { Nan::ThrowTypeError("Invalid scaling_method"); return; } scaling_method = static_cast<mapnik::scaling_method_e>(scaling_int); } else { Nan::ThrowTypeError("scaling_method argument must be an integer"); return; } } if (Nan::Has(options, Nan::New("filter_factor").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> ff_val = Nan::Get(options, Nan::New("filter_factor").ToLocalChecked()).ToLocalChecked(); if (ff_val->IsNumber()) { filter_factor = ff_val->NumberValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowTypeError("filter_factor argument must be a number"); return; } } resize_image_baton_t *closure = new resize_image_baton_t(); closure->request.data = closure; closure->im1 = im1; closure->scaling_method = scaling_method; closure->size_x = width; closure->size_y = height; closure->offset_x = offset_x; closure->offset_y = offset_y; closure->filter_factor = filter_factor; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Resize, (uv_after_work_cb)EIO_AfterResize); closure->im1->_ref(); return; } struct resize_visitor { resize_visitor(mapnik::image_any const& im1, mapnik::scaling_method_e scaling_method, double image_ratio_x, double image_ratio_y, double filter_factor, int offset_x, int offset_y) : im1_(im1), scaling_method_(scaling_method), image_ratio_x_(image_ratio_x), image_ratio_y_(image_ratio_y), filter_factor_(filter_factor), offset_x_(offset_x), offset_y_(offset_y) {} void operator()(mapnik::image_rgba8 & im2) const { if (!im1_.get_premultiplied()) { throw std::runtime_error("RGBA8 images must be premultiplied prior to using resize"); } mapnik::scale_image_agg(im2, mapnik::util::get<mapnik::image_rgba8>(im1_), scaling_method_, image_ratio_x_, image_ratio_y_, offset_x_, offset_y_, filter_factor_); } template <typename T> void operator()(T & im2) const { mapnik::scale_image_agg(im2, mapnik::util::get<T>(im1_), scaling_method_, image_ratio_x_, image_ratio_y_, offset_x_, offset_y_, filter_factor_); } void operator()(mapnik::image_null &) const { // Should be caught earlier so no test coverage should reach here. /* LCOV_EXCL_START */ throw std::runtime_error("Can not resize null images"); /* LCOV_EXCL_STOP */ } void operator()(mapnik::image_gray8s &) const { throw std::runtime_error("Mapnik currently does not support resizing signed 8 bit integer rasters"); } void operator()(mapnik::image_gray16s &) const { throw std::runtime_error("Mapnik currently does not support resizing signed 16 bit integer rasters"); } void operator()(mapnik::image_gray32 &) const { throw std::runtime_error("Mapnik currently does not support resizing unsigned 32 bit integer rasters"); } void operator()(mapnik::image_gray32s &) const { throw std::runtime_error("Mapnik currently does not support resizing signed 32 bit integer rasters"); } void operator()(mapnik::image_gray64 &) const { throw std::runtime_error("Mapnik currently does not support resizing unsigned 64 bit integer rasters"); } void operator()(mapnik::image_gray64s &) const { throw std::runtime_error("Mapnik currently does not support resizing signed 64 bit integer rasters"); } void operator()(mapnik::image_gray64f &) const { throw std::runtime_error("Mapnik currently does not support resizing 64 bit floating point rasters"); } private: mapnik::image_any const & im1_; mapnik::scaling_method_e scaling_method_; double image_ratio_x_; double image_ratio_y_; double filter_factor_; int offset_x_; int offset_y_; }; void Image::EIO_Resize(uv_work_t* req) { resize_image_baton_t *closure = static_cast<resize_image_baton_t *>(req->data); if (closure->im1->this_->is<mapnik::image_null>()) { closure->error = true; closure->error_name = "Can not resize a null image."; return; } try { double offset = closure->im1->this_->get_offset(); double scaling = closure->im1->this_->get_scaling(); closure->im2 = std::make_shared<mapnik::image_any>(closure->size_x, closure->size_y, closure->im1->this_->get_dtype(), true, true, false); closure->im2->set_offset(offset); closure->im2->set_scaling(scaling); int im_width = closure->im1->this_->width(); int im_height = closure->im1->this_->height(); if (im_width <= 0 || im_height <= 0) { closure->error = true; closure->error_name = "Image width or height is zero or less then zero."; return; } double image_ratio_x = static_cast<double>(closure->size_x) / im_width; double image_ratio_y = static_cast<double>(closure->size_y) / im_height; resize_visitor visit(*(closure->im1->this_), closure->scaling_method, image_ratio_x, image_ratio_y, closure->filter_factor, closure->offset_x, closure->offset_y); mapnik::util::apply_visitor(visit, *(closure->im2)); } catch (std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterResize(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); resize_image_baton_t *closure = static_cast<resize_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { Image* im = new Image(closure->im2); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) { v8::Local<v8::Value> argv[1] = { Nan::Error("Could not create new Image instance") }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), maybe_local.ToLocalChecked() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } } closure->im1->_unref(); closure->cb.Reset(); delete closure; } /** * Resize this image (makes a copy). Synchronous version of {@link mapnik.Image.resize}. * * @name resizeSync * @instance * @memberof Image * @param {number} width * @param {number} height * @param {Object} [options={}] * @param {number} [options.offset_x=0] - offset the image horizontally in pixels * @param {number} [options.offset_y=0] - offset the image vertically in pixels * @param {mapnik.imageScaling} [options.scaling_method=mapnik.imageScaling.near] - scaling method * @param {number} [options.filter_factor=1.0] * @returns {mapnik.Image} copy * @example * var img = new mapnik.Image(4, 4, {type: mapnik.imageType.gray8}); * var img2 = img.resizeSync(8, 8); * // new copy as `img2` */ NAN_METHOD(Image::resizeSync) { info.GetReturnValue().Set(_resizeSync(info)); } v8::Local<v8::Value> Image::_resizeSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); std::size_t width = 0; std::size_t height = 0; double filter_factor = 1.0; int offset_x = 0; int offset_y = 0; mapnik::scaling_method_e scaling_method = mapnik::SCALING_NEAR; v8::Local<v8::Object> options = Nan::New<v8::Object>(); if (info.Length() >= 2) { if (info[0]->IsNumber()) { int width_tmp = info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (width_tmp <= 0) { Nan::ThrowTypeError("Width parameter must be an integer greater then zero"); return scope.Escape(Nan::Undefined()); } width = static_cast<std::size_t>(width_tmp); } else { Nan::ThrowTypeError("Width must be a number"); return scope.Escape(Nan::Undefined()); } if (info[1]->IsNumber()) { int height_tmp = info[1]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (height_tmp <= 0) { Nan::ThrowTypeError("Height parameter must be an integer greater then zero"); return scope.Escape(Nan::Undefined()); } height = static_cast<std::size_t>(height_tmp); } else { Nan::ThrowTypeError("Height must be a number"); return scope.Escape(Nan::Undefined()); } } else { Nan::ThrowTypeError("Resize requires at least a width and height parameter"); return scope.Escape(Nan::Undefined()); } if (info.Length() >= 3) { if (info[2]->IsObject()) { options = info[2]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); } else { Nan::ThrowTypeError("Expected options object as third argument"); return scope.Escape(Nan::Undefined()); } } if (Nan::Has(options, Nan::New("offset_x").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> bind_opt = Nan::Get(options, Nan::New("offset_x").ToLocalChecked()).ToLocalChecked(); if (!bind_opt->IsNumber()) { Nan::ThrowTypeError("optional arg 'offset_x' must be a number"); return scope.Escape(Nan::Undefined()); } offset_x = bind_opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("offset_y").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> bind_opt = Nan::Get(options, Nan::New("offset_y").ToLocalChecked()).ToLocalChecked(); if (!bind_opt->IsNumber()) { Nan::ThrowTypeError("optional arg 'offset_y' must be a number"); return scope.Escape(Nan::Undefined()); } offset_y = bind_opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("scaling_method").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> scaling_val = Nan::Get(options, Nan::New("scaling_method").ToLocalChecked()).ToLocalChecked(); if (scaling_val->IsNumber()) { std::int64_t scaling_int = scaling_val->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (scaling_int > mapnik::SCALING_BLACKMAN || scaling_int < 0) { Nan::ThrowTypeError("Invalid scaling_method"); return scope.Escape(Nan::Undefined()); } scaling_method = static_cast<mapnik::scaling_method_e>(scaling_int); } else { Nan::ThrowTypeError("scaling_method argument must be a number"); return scope.Escape(Nan::Undefined()); } } if (Nan::Has(options, Nan::New("filter_factor").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> ff_val = Nan::Get(options, Nan::New("filter_factor").ToLocalChecked()).ToLocalChecked(); if (ff_val->IsNumber()) { filter_factor = ff_val->NumberValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowTypeError("filter_factor argument must be a number"); return scope.Escape(Nan::Undefined()); } } if (im->this_->is<mapnik::image_null>()) { Nan::ThrowTypeError("Can not resize a null image"); return scope.Escape(Nan::Undefined()); } int im_width = im->this_->width(); int im_height = im->this_->height(); if (im_width <= 0 || im_height <= 0) { Nan::ThrowTypeError("Image width or height is zero or less then zero."); return scope.Escape(Nan::Undefined()); } try { double offset = im->this_->get_offset(); double scaling = im->this_->get_scaling(); image_ptr imagep = std::make_shared<mapnik::image_any>(width, height, im->this_->get_dtype(), true, true, false); imagep->set_offset(offset); imagep->set_scaling(scaling); double image_ratio_x = static_cast<double>(width) / im_width; double image_ratio_y = static_cast<double>(height) / im_height; resize_visitor visit(*(im->this_), scaling_method, image_ratio_x, image_ratio_y, filter_factor, offset_x, offset_y); mapnik::util::apply_visitor(visit, *imagep); Image* new_im = new Image(imagep); v8::Local<v8::Value> ext = Nan::New<v8::External>(new_im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) Nan::ThrowError("Could not create new Image instance"); return scope.Escape(maybe_local.ToLocalChecked()); } catch (std::exception const& ex) { Nan::ThrowError(ex.what()); return scope.Escape(Nan::Undefined()); } } /** * Check if this image is painted. "Painted" refers to if it has * data or not. An image created with `new mapnik.Image(4,4)` defaults to * `false` since we loaded a new image without rendering and have no idea * if it was painted or not. You can run `new mapnik.Image(4, 4, {painted: true})` * to manually set the `painted` value. * * @name painted * @instance * @memberof Image * @returns {boolean} whether it is painted or not * @example * var img = new mapnik.Image(5,5); * console.log(img.painted()); // false */ NAN_METHOD(Image::painted) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); info.GetReturnValue().Set(Nan::New<v8::Boolean>(im->this_->painted())); } /** * Get this image's width in pixels * * @name width * @instance * @memberof Image * @returns {number} width * @example * var img = new mapnik.Image(4,4); * console.log(img.width()); // 4 */ NAN_METHOD(Image::width) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); info.GetReturnValue().Set(Nan::New<v8::Int32>(static_cast<std::int32_t>(im->this_->width()))); } /** * Get this image's height in pixels * * @name height * @instance * @memberof Image * @returns {number} height * @example * var img = new mapnik.Image(4,4); * console.log(img.height()); // 4 */ NAN_METHOD(Image::height) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); info.GetReturnValue().Set(Nan::New<v8::Int32>(static_cast<std::int32_t>(im->this_->height()))); } /** * Load in a pre-existing image as an image object * @name openSync * @memberof Image * @instance * @param {string} path - path to the image you want to load * @returns {mapnik.Image} new image object based on existing image * @example * var img = new mapnik.Image.open('./path/to/image.jpg'); */ NAN_METHOD(Image::openSync) { info.GetReturnValue().Set(_openSync(info)); } v8::Local<v8::Value> Image::_openSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; if (info.Length() < 1) { Nan::ThrowError("must provide a string argument"); return scope.Escape(Nan::Undefined()); } if (!info[0]->IsString()) { Nan::ThrowTypeError("Argument must be a string"); return scope.Escape(Nan::Undefined()); } try { std::string filename = TOSTR(info[0]); boost::optional<std::string> type = mapnik::type_from_filename(filename); if (type) { std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename,*type)); if (reader.get()) { image_ptr imagep = std::make_shared<mapnik::image_any>(reader->read(0,0,reader->width(), reader->height())); if (!reader->has_alpha()) { mapnik::set_premultiplied_alpha(*imagep, true); } Image* im = new Image(imagep); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) Nan::ThrowError("Could not create new Image instance"); return scope.Escape(maybe_local.ToLocalChecked()); } } Nan::ThrowTypeError(("Unsupported image format:" + filename).c_str()); return scope.Escape(Nan::Undefined()); } catch (std::exception const& ex) { Nan::ThrowError(ex.what()); return scope.Escape(Nan::Undefined()); } } typedef struct { uv_work_t request; image_ptr im; std::string error_name; Nan::Persistent<v8::Object> buffer; Nan::Persistent<v8::Function> cb; bool premultiply; std::uint32_t max_size; const char *data; size_t dataLength; bool error; } image_mem_ptr_baton_t; typedef struct { uv_work_t request; image_ptr im; std::string filename; bool error; std::string error_name; Nan::Persistent<v8::Function> cb; } image_file_ptr_baton_t; /** * Load in a pre-existing image as an image object * @name open * @memberof Image * @static * @param {string} path - path to the image you want to load * @param {Function} callback - * @example * mapnik.Image.open('./path/to/image.jpg', function(err, img) { * if (err) throw err; * // img is now an Image object * }); */ NAN_METHOD(Image::open) { if (info.Length() == 1) { info.GetReturnValue().Set(_openSync(info)); return; } if (info.Length() < 2) { Nan::ThrowError("must provide a string argument"); return; } if (!info[0]->IsString()) { Nan::ThrowTypeError("Argument must be a string"); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length()-1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } image_file_ptr_baton_t *closure = new image_file_ptr_baton_t(); closure->request.data = closure; closure->filename = TOSTR(info[0]); closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Open, (uv_after_work_cb)EIO_AfterOpen); return; } void Image::EIO_Open(uv_work_t* req) { image_file_ptr_baton_t *closure = static_cast<image_file_ptr_baton_t *>(req->data); try { boost::optional<std::string> type = mapnik::type_from_filename(closure->filename); if (!type) { closure->error = true; closure->error_name = "Unsupported image format: " + closure->filename; } else { std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(closure->filename,*type)); if (reader.get()) { closure->im = std::make_shared<mapnik::image_any>(reader->read(0,0,reader->width(),reader->height())); if (!reader->has_alpha()) { mapnik::set_premultiplied_alpha(*(closure->im), true); } } else { // The only way this is ever reached is if the reader factory in // mapnik was not providing an image type it should. This should never // be occuring so marking this out from coverage /* LCOV_EXCL_START */ closure->error = true; closure->error_name = "Failed to load: " + closure->filename; /* LCOV_EXCL_STOP */ } } } catch (std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterOpen(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); image_file_ptr_baton_t *closure = static_cast<image_file_ptr_baton_t *>(req->data); if (closure->error || !closure->im) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { Image* im = new Image(closure->im); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) { v8::Local<v8::Value> argv[1] = { Nan::Error("Could not create new Image instance") }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), maybe_local.ToLocalChecked() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } } closure->cb.Reset(); delete closure; } /** * Load image from an SVG buffer (synchronous) * @name fromSVGBytesSync * @memberof Image * @static * @param {string} path - path to SVG image * @param {Object} [options] * @param {number} [options.scale] - scale the image. For example passing `0.5` as scale would render * your SVG at 50% the original size. * @param {number} [options.max_size] - the maximum allowed size of the svg dimensions * scale. The default is 2048. * This option can be passed a smaller or larger size in order to control the final size of the image allocated for * rasterizing the SVG. * @returns {mapnik.Image} Image object * @example * var buffer = fs.readFileSync('./path/to/image.svg'); * var img = mapnik.Image.fromSVGBytesSync(buffer); */ NAN_METHOD(Image::fromSVGBytesSync) { info.GetReturnValue().Set(_fromSVGSync(false, info)); } /** * Create a new image from an SVG file (synchronous) * * @name fromSVGSync * @param {string} filename * @param {Object} [options] * @param {number} [options.scale] - scale the image. For example passing `0.5` as scale would render * your SVG at 50% the original size. * @param {number} [options.max_size] - the maximum allowed size of the svg dimensions * scale. The default is 2048. * This option can be passed a smaller or larger size in order to control the final size of the image allocated for * rasterizing the SVG. * @returns {mapnik.Image} image object * @static * @memberof Image * @example * var img = mapnik.Image.fromSVG('./path/to/image.svg'); */ NAN_METHOD(Image::fromSVGSync) { info.GetReturnValue().Set(_fromSVGSync(true, info)); } v8::Local<v8::Value> Image::_fromSVGSync(bool fromFile, Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; if (!fromFile && (info.Length() < 1 || !info[0]->IsObject())) { Nan::ThrowTypeError("must provide a buffer argument"); return scope.Escape(Nan::Undefined()); } if (fromFile && (info.Length() < 1 || !info[0]->IsString())) { Nan::ThrowTypeError("must provide a filename argument"); return scope.Escape(Nan::Undefined()); } double scale = 1.0; std::uint32_t max_size = 2048; bool strict = false; bool throw_on_unhandled_elements = false; if (info.Length() >= 2) { if (!info[1]->IsObject()) { Nan::ThrowTypeError("optional second arg must be an options object"); return scope.Escape(Nan::Undefined()); } v8::Local<v8::Object> options = info[1]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (Nan::Has(options, Nan::New("scale").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> scale_opt = Nan::Get(options, Nan::New("scale").ToLocalChecked()).ToLocalChecked(); if (!scale_opt->IsNumber()) { Nan::ThrowTypeError("'scale' must be a number"); return scope.Escape(Nan::Undefined()); } scale = scale_opt->NumberValue(Nan::GetCurrentContext()).ToChecked(); if (scale <= 0) { Nan::ThrowTypeError("'scale' must be a positive non zero number"); return scope.Escape(Nan::Undefined()); } } if (Nan::Has(options, Nan::New("max_size").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("max_size").ToLocalChecked()).ToLocalChecked(); if (!opt->IsNumber()) { Nan::ThrowTypeError("'max_size' must be a positive integer"); return scope.Escape(Nan::Undefined()); } auto max_size_val = opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (max_size_val < 0 || max_size_val > 65535) { Nan::ThrowTypeError("'max_size' must be a positive integer between 0 and 65535"); return scope.Escape(Nan::Undefined()); } max_size = static_cast<std::uint32_t>(max_size_val); } if (Nan::Has(options, Nan::New("strict").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("strict").ToLocalChecked()).ToLocalChecked(); if (!opt->IsBoolean()) { Nan::ThrowTypeError("'strict' must be a boolean value"); return scope.Escape(Nan::Undefined()); } strict = opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("throw_on_unhandled_elements").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("throw_on_unhandled_elements").ToLocalChecked()).ToLocalChecked(); if (!opt->IsBoolean()) { Nan::ThrowTypeError("'throw_on_unhandled_elements' must be a boolean value"); return scope.Escape(Nan::Undefined()); } throw_on_unhandled_elements = opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } } try { using namespace mapnik::svg; mapnik::svg_path_ptr marker_path(std::make_shared<mapnik::svg_storage_type>()); vertex_stl_adapter<svg_path_storage> stl_storage(marker_path->source()); svg_path_adapter svg_path(stl_storage); svg_converter_type svg(svg_path, marker_path->attributes()); svg_parser p(svg, strict); if (fromFile) { p.parse(TOSTR(info[0])); if (throw_on_unhandled_elements && !p.err_handler().error_messages().empty()) { std::ostringstream errorMessage; errorMessage << "SVG parse error:" << std::endl; for (auto const& error : p.err_handler().error_messages()) { errorMessage << error << std::endl; } Nan::ThrowTypeError(errorMessage.str().c_str()); return scope.Escape(Nan::Undefined()); } } else { v8::Local<v8::Object> obj = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj)) { Nan::ThrowTypeError("first argument is invalid, must be a Buffer"); return scope.Escape(Nan::Undefined()); } std::string svg_buffer(node::Buffer::Data(obj),node::Buffer::Length(obj)); p.parse_from_string(svg_buffer); if (throw_on_unhandled_elements && !p.err_handler().error_messages().empty()) { std::ostringstream errorMessage; errorMessage << "SVG parse error:" << std::endl; for (auto const& error : p.err_handler().error_messages()) { errorMessage << error << std::endl; } Nan::ThrowTypeError(errorMessage.str().c_str()); return scope.Escape(Nan::Undefined()); } } double lox,loy,hix,hiy; svg.bounding_rect(&lox, &loy, &hix, &hiy); marker_path->set_bounding_box(lox,loy,hix,hiy); marker_path->set_dimensions(svg.width(),svg.height()); using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::rasterizer_scanline_aa<> ras_ptr; agg::scanline_u8 sl; double opacity = 1; double svg_width = svg.width() * scale; double svg_height = svg.height() * scale; if (svg_width <= 0 || svg_height <= 0) { Nan::ThrowTypeError("image created from svg must have a width and height greater then zero"); return scope.Escape(Nan::Undefined()); } if (svg_width > static_cast<double>(max_size) || svg_height > static_cast<double>(max_size)) { std::stringstream s; s << "image created from svg must be " << max_size << " pixels or fewer on each side"; Nan::ThrowTypeError(s.str().c_str()); return scope.Escape(Nan::Undefined()); } mapnik::image_rgba8 im(static_cast<int>(svg_width), static_cast<int>(svg_height), true, true); agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); mapnik::box2d<double> const& bbox = marker_path->bounding_box(); mapnik::coord<double,2> c = bbox.center(); // center the svg marker on '0,0' agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y); // Scale the image mtx.scale(scale); // render the marker at the center of the marker box mtx.translate(0.5 * im.width(), 0.5 * im.height()); mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter, mapnik::svg_attribute_type, renderer_solid, agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path, marker_path->attributes()); svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox); mapnik::demultiply_alpha(im); image_ptr imagep = std::make_shared<mapnik::image_any>(im); Image *im2 = new Image(imagep); v8::Local<v8::Value> ext = Nan::New<v8::External>(im2); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) Nan::ThrowError("Could not create new Image instance"); return scope.Escape(maybe_local.ToLocalChecked()); } catch (std::exception const& ex) { // There is currently no known way to make these operations throw an exception, however, // since the underlying agg library does possibly have some operation that might throw // it is a good idea to keep this. Therefore, any exceptions thrown will fail gracefully. // LCOV_EXCL_START Nan::ThrowError(ex.what()); return scope.Escape(Nan::Undefined()); // LCOV_EXCL_STOP } } typedef struct { uv_work_t request; image_ptr im; std::string filename; bool error; double scale; std::uint32_t max_size; bool strict; bool throw_on_unhandled_elements; std::string error_name; Nan::Persistent<v8::Function> cb; } svg_file_ptr_baton_t; typedef struct { uv_work_t request; image_ptr im; const char *data; size_t dataLength; bool error; double scale; std::uint32_t max_size; bool strict; bool throw_on_unhandled_elements; std::string error_name; Nan::Persistent<v8::Object> buffer; Nan::Persistent<v8::Function> cb; } svg_mem_ptr_baton_t; /** * Create a new image from an SVG file * * @name fromSVG * @param {string} filename * @param {Object} [options] * @param {number} [options.scale] - scale the image. For example passing `0.5` as scale would render * your SVG at 50% the original size. * @param {number} [options.max_size] - the maximum allowed size of the svg dimensions * scale. The default is 2048. * This option can be passed a smaller or larger size in order to control the final size of the image allocated for * rasterizing the SVG. * @param {Function} callback * @static * @memberof Image * @example * mapnik.Image.fromSVG('./path/to/image.svg', {scale: 0.5}, function(err, img) { * if (err) throw err; * // new img object (at 50% scale) * }); */ NAN_METHOD(Image::fromSVG) { if (info.Length() == 1) { info.GetReturnValue().Set(_fromSVGSync(true, info)); return; } if (info.Length() < 2 || !info[0]->IsString()) { Nan::ThrowTypeError("must provide a filename argument"); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length() - 1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } double scale = 1.0; std::uint32_t max_size = 2048; bool strict = false; bool throw_on_unhandled_elements = false; if (info.Length() >= 3) { if (!info[1]->IsObject()) { Nan::ThrowTypeError("optional second arg must be an options object"); return; } v8::Local<v8::Object> options = info[1]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (Nan::Has(options, Nan::New("scale").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> scale_opt = Nan::Get(options, Nan::New("scale").ToLocalChecked()).ToLocalChecked(); if (!scale_opt->IsNumber()) { Nan::ThrowTypeError("'scale' must be a number"); return; } scale = scale_opt->NumberValue(Nan::GetCurrentContext()).ToChecked(); if (scale <= 0) { Nan::ThrowTypeError("'scale' must be a positive non zero number"); return; } } if (Nan::Has(options, Nan::New("max_size").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("max_size").ToLocalChecked()).ToLocalChecked(); if (!opt->IsNumber()) { Nan::ThrowTypeError("'max_size' must be a positive integer"); return; } auto max_size_val = opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (max_size_val < 0 || max_size_val > 65535) { Nan::ThrowTypeError("'max_size' must be a positive integer between 0 and 65535"); return; } max_size = static_cast<std::uint32_t>(max_size_val); } if (Nan::Has(options, Nan::New("strict").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("strict").ToLocalChecked()).ToLocalChecked(); if (!opt->IsBoolean()) { Nan::ThrowTypeError("'strict' must be a boolean value"); return; } strict = opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("throw_on_unhandled_elements").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("throw_on_unhandled_elements").ToLocalChecked()).ToLocalChecked(); if (!opt->IsBoolean()) { Nan::ThrowTypeError("'throw_on_unhandled_elements' must be a boolean value"); return; } throw_on_unhandled_elements = opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } } svg_file_ptr_baton_t *closure = new svg_file_ptr_baton_t(); closure->request.data = closure; closure->filename = TOSTR(info[0]); closure->error = false; closure->scale = scale; closure->max_size = max_size; closure->strict = strict; closure->throw_on_unhandled_elements = throw_on_unhandled_elements; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_FromSVG, (uv_after_work_cb)EIO_AfterFromSVG); return; } void Image::EIO_FromSVG(uv_work_t* req) { svg_file_ptr_baton_t *closure = static_cast<svg_file_ptr_baton_t *>(req->data); try { using namespace mapnik::svg; mapnik::svg_path_ptr marker_path(std::make_shared<mapnik::svg_storage_type>()); vertex_stl_adapter<svg_path_storage> stl_storage(marker_path->source()); svg_path_adapter svg_path(stl_storage); svg_converter_type svg(svg_path, marker_path->attributes()); svg_parser p(svg, closure->strict); p.parse(closure->filename); if (closure->throw_on_unhandled_elements && !p.err_handler().error_messages().empty()) { std::ostringstream errorMessage; errorMessage << "SVG parse error:" << std::endl; for (auto const& error : p.err_handler().error_messages()) { errorMessage << error << std::endl; } closure->error = true; closure->error_name = errorMessage.str(); return; } double lox,loy,hix,hiy; svg.bounding_rect(&lox, &loy, &hix, &hiy); marker_path->set_bounding_box(lox,loy,hix,hiy); marker_path->set_dimensions(svg.width(),svg.height()); using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::rasterizer_scanline_aa<> ras_ptr; agg::scanline_u8 sl; double opacity = 1; double svg_width = svg.width() * closure->scale; double svg_height = svg.height() * closure->scale; if (svg_width <= 0 || svg_height <= 0) { closure->error = true; closure->error_name = "image created from svg must have a width and height greater then zero"; return; } if (svg_width > static_cast<double>(closure->max_size) || svg_height > static_cast<double>(closure->max_size)) { closure->error = true; std::stringstream s; s << "image created from svg must be " << closure->max_size << " pixels or fewer on each side"; closure->error_name = s.str(); return; } mapnik::image_rgba8 im(static_cast<int>(svg_width), static_cast<int>(svg_height), true, true); agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); mapnik::box2d<double> const& bbox = marker_path->bounding_box(); mapnik::coord<double,2> c = bbox.center(); // center the svg marker on '0,0' agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y); // Scale the image mtx.scale(closure->scale); // render the marker at the center of the marker box mtx.translate(0.5 * im.width(), 0.5 * im.height()); mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter, mapnik::svg_attribute_type, renderer_solid, agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path, marker_path->attributes()); svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox); mapnik::demultiply_alpha(im); closure->im = std::make_shared<mapnik::image_any>(im); } catch (std::exception const& ex) { // There is currently no known way to make these operations throw an exception, however, // since the underlying agg library does possibly have some operation that might throw // it is a good idea to keep this. Therefore, any exceptions thrown will fail gracefully. // LCOV_EXCL_START closure->error = true; closure->error_name = ex.what(); // LCOV_EXCL_STOP } } void Image::EIO_AfterFromSVG(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); svg_file_ptr_baton_t *closure = static_cast<svg_file_ptr_baton_t *>(req->data); if (closure->error || !closure->im) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { Image* im = new Image(closure->im); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) { v8::Local<v8::Value> argv[1] = { Nan::Error("Could not create new Image instance") }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), maybe_local.ToLocalChecked() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } } closure->cb.Reset(); delete closure; } /** * Load image from an SVG buffer * @name fromSVGBytes * @memberof Image * @static * @param {string} path - path to SVG image * @param {Object} [options] * @param {number} [options.scale] - scale the image. For example passing `0.5` as scale would render * your SVG at 50% the original size. * @param {number} [options.max_size] - the maximum allowed size of the svg dimensions * scale. The default is 2048. * @param {boolean} [options.strict] - enable `strict` parsing mode e.g throw on unsupported element/attribute. The default is `false`. * This option can be passed a smaller or larger size in order to control the final size of the image allocated for * rasterizing the SVG. * @param {Function} callback = `function(err, img)` * @example * var buffer = fs.readFileSync('./path/to/image.svg'); * mapnik.Image.fromSVGBytes(buffer, function(err, img) { * if (err) throw err; * // your custom code with `img` * }); */ NAN_METHOD(Image::fromSVGBytes) { if (info.Length() == 1) { info.GetReturnValue().Set(_fromSVGSync(false, info)); return; } if (info.Length() < 2 || !info[0]->IsObject()) { Nan::ThrowError("must provide a buffer argument"); return; } v8::Local<v8::Object> obj = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj)) { Nan::ThrowTypeError("first argument is invalid, must be a Buffer"); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length() - 1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } double scale = 1.0; std::uint32_t max_size = 2048; bool strict = false; bool throw_on_unhandled_elements = false; if (info.Length() >= 3) { if (!info[1]->IsObject()) { Nan::ThrowTypeError("optional second arg must be an options object"); return; } v8::Local<v8::Object> options = info[1]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (Nan::Has(options, Nan::New("scale").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> scale_opt = Nan::Get(options, Nan::New("scale").ToLocalChecked()).ToLocalChecked(); if (!scale_opt->IsNumber()) { Nan::ThrowTypeError("'scale' must be a number"); return; } scale = scale_opt->NumberValue(Nan::GetCurrentContext()).ToChecked(); if (scale <= 0) { Nan::ThrowTypeError("'scale' must be a positive non zero number"); return; } } if (Nan::Has(options, Nan::New("max_size").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("max_size").ToLocalChecked()).ToLocalChecked(); if (!opt->IsNumber()) { Nan::ThrowTypeError("'max_size' must be a positive integer"); return; } auto max_size_val = opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (max_size_val < 0 || max_size_val > 65535) { Nan::ThrowTypeError("'max_size' must be a positive integer between 0 and 65535"); return; } max_size = static_cast<std::uint32_t>(max_size_val); } if (Nan::Has(options, Nan::New("strict").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("strict").ToLocalChecked()).ToLocalChecked(); if (!opt->IsBoolean()) { Nan::ThrowTypeError("'strict' must be a boolean value"); return; } strict = opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("throw_on_unhandled_elements").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("throw_on_unhandled_elements").ToLocalChecked()).ToLocalChecked(); if (!opt->IsBoolean()) { Nan::ThrowTypeError("'throw_on_unhandled_elements' must be a boolean value"); return; } throw_on_unhandled_elements = opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } } svg_mem_ptr_baton_t *closure = new svg_mem_ptr_baton_t(); closure->request.data = closure; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); closure->buffer.Reset(obj.As<v8::Object>()); closure->data = node::Buffer::Data(obj); closure->scale = scale; closure->max_size = max_size; closure->strict = strict; closure->throw_on_unhandled_elements = throw_on_unhandled_elements; closure->dataLength = node::Buffer::Length(obj); uv_queue_work(uv_default_loop(), &closure->request, EIO_FromSVGBytes, (uv_after_work_cb)EIO_AfterFromSVGBytes); return; } void Image::EIO_FromSVGBytes(uv_work_t* req) { svg_mem_ptr_baton_t *closure = static_cast<svg_mem_ptr_baton_t *>(req->data); try { using namespace mapnik::svg; mapnik::svg_path_ptr marker_path(std::make_shared<mapnik::svg_storage_type>()); vertex_stl_adapter<svg_path_storage> stl_storage(marker_path->source()); svg_path_adapter svg_path(stl_storage); svg_converter_type svg(svg_path, marker_path->attributes()); svg_parser p(svg, closure->strict); std::string svg_buffer(closure->data,closure->dataLength); p.parse_from_string(svg_buffer); if (closure->throw_on_unhandled_elements && !p.err_handler().error_messages().empty()) { std::ostringstream errorMessage; errorMessage << "SVG parse error:" << std::endl; for (auto const& error : p.err_handler().error_messages()) { errorMessage << error << std::endl; } closure->error = true; closure->error_name = errorMessage.str(); return; } double lox,loy,hix,hiy; svg.bounding_rect(&lox, &loy, &hix, &hiy); marker_path->set_bounding_box(lox,loy,hix,hiy); marker_path->set_dimensions(svg.width(),svg.height()); using pixfmt = agg::pixfmt_rgba32_pre; using renderer_base = agg::renderer_base<pixfmt>; using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>; agg::rasterizer_scanline_aa<> ras_ptr; agg::scanline_u8 sl; double opacity = 1; double svg_width = svg.width() * closure->scale; double svg_height = svg.height() * closure->scale; if (svg_width <= 0 || svg_height <= 0) { closure->error = true; closure->error_name = "image created from svg must have a width and height greater then zero"; return; } if (svg_width > static_cast<double>(closure->max_size) || svg_height > static_cast<double>(closure->max_size)) { closure->error = true; std::stringstream s; s << "image created from svg must be " << closure->max_size << " pixels or fewer on each side"; closure->error_name = s.str(); return; } mapnik::image_rgba8 im(static_cast<int>(svg_width), static_cast<int>(svg_height), true, true); agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size()); pixfmt pixf(buf); renderer_base renb(pixf); mapnik::box2d<double> const& bbox = marker_path->bounding_box(); mapnik::coord<double,2> c = bbox.center(); // center the svg marker on '0,0' agg::trans_affine mtx = agg::trans_affine_translation(-c.x,-c.y); // Scale the image mtx.scale(closure->scale); // render the marker at the center of the marker box mtx.translate(0.5 * im.width(), 0.5 * im.height()); mapnik::svg::svg_renderer_agg<mapnik::svg::svg_path_adapter, mapnik::svg_attribute_type, renderer_solid, agg::pixfmt_rgba32_pre > svg_renderer_this(svg_path, marker_path->attributes()); svg_renderer_this.render(ras_ptr, sl, renb, mtx, opacity, bbox); mapnik::demultiply_alpha(im); closure->im = std::make_shared<mapnik::image_any>(im); } catch (std::exception const& ex) { // There is currently no known way to make these operations throw an exception, however, // since the underlying agg library does possibly have some operation that might throw // it is a good idea to keep this. Therefore, any exceptions thrown will fail gracefully. // LCOV_EXCL_START closure->error = true; closure->error_name = ex.what(); // LCOV_EXCL_STOP } } void Image::EIO_AfterFromSVGBytes(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); svg_mem_ptr_baton_t *closure = static_cast<svg_mem_ptr_baton_t *>(req->data); if (closure->error || !closure->im) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { Image* im = new Image(closure->im); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) { v8::Local<v8::Value> argv[1] = { Nan::Error("Could not create new Image instance") }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Object> image_obj = maybe_local.ToLocalChecked()->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); v8::Local<v8::Value> argv[2] = { Nan::Null(), image_obj }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } } closure->cb.Reset(); closure->buffer.Reset(); delete closure; } /** * Create an image of the existing buffer. * * Note: the buffer must live as long as the image. * It is recommended that you do not use this method. Be warned! * * @name fromBufferSync * @param {number} width * @param {number} height * @param {Buffer} buffer * @returns {mapnik.Image} image object * @static * @memberof Image * @example * var img = new mapnik.Image.open('./path/to/image.png'); * var buffer = img.data(); // returns data as buffer * var img2 = mapnik.Image.fromBufferSync(img.width(), img.height(), buffer); */ NAN_METHOD(Image::fromBufferSync) { info.GetReturnValue().Set(_fromBufferSync(info)); } v8::Local<v8::Value> Image::_fromBufferSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; if (info.Length() < 3 || !info[0]->IsNumber() || !info[1]->IsNumber() || !info[2]->IsObject()) { Nan::ThrowTypeError("must provide a width, height, and buffer argument"); return scope.Escape(Nan::Undefined()); } unsigned width = info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); unsigned height = info[1]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (width <= 0 || height <= 0) { Nan::ThrowTypeError("width and height must be greater then zero"); return scope.Escape(Nan::Undefined()); } v8::Local<v8::Object> obj = info[2]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj)) { Nan::ThrowTypeError("third argument is invalid, must be a Buffer"); return scope.Escape(Nan::Undefined()); } // TODO - support other image types? auto im_size = mapnik::image_rgba8::pixel_size * width * height; if (im_size != node::Buffer::Length(obj)) { Nan::ThrowTypeError("invalid image size"); return scope.Escape(Nan::Undefined()); } bool premultiplied = false; bool painted = false; if (info.Length() >= 4) { if (info[3]->IsObject()) { v8::Local<v8::Object> options = v8::Local<v8::Object>::Cast(info[3]); if (Nan::Has(options, Nan::New("type").ToLocalChecked()).FromMaybe(false)) { Nan::ThrowTypeError("'type' option not supported (only rgba images currently viable)"); return scope.Escape(Nan::Undefined()); } if (Nan::Has(options, Nan::New("premultiplied").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> pre_val = Nan::Get(options, Nan::New("premultiplied").ToLocalChecked()).ToLocalChecked(); if (!pre_val.IsEmpty() && pre_val->IsBoolean()) { premultiplied = pre_val->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowTypeError("premultiplied option must be a boolean"); return scope.Escape(Nan::Undefined()); } } if (Nan::Has(options, Nan::New("painted").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> painted_val = Nan::Get(options, Nan::New("painted").ToLocalChecked()).ToLocalChecked(); if (!painted_val.IsEmpty() && painted_val->IsBoolean()) { painted = painted_val->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowTypeError("painted option must be a boolean"); return scope.Escape(Nan::Undefined()); } } } else { Nan::ThrowTypeError("Options parameter must be an object"); return scope.Escape(Nan::Undefined()); } } try { mapnik::image_rgba8 im_wrapper(width, height, reinterpret_cast<unsigned char*>(node::Buffer::Data(obj)), premultiplied, painted); image_ptr imagep = std::make_shared<mapnik::image_any>(im_wrapper); Image* im = new Image(imagep); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) Nan::ThrowError("Could not create new Image instance"); v8::Local<v8::Object> image_obj = maybe_local.ToLocalChecked()->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); Nan::Set(image_obj, Nan::New("_buffer").ToLocalChecked(),obj); return scope.Escape(maybe_local.ToLocalChecked()); } catch (std::exception const& ex) { // There is no known way for this exception to be reached currently. // LCOV_EXCL_START Nan::ThrowError(ex.what()); return scope.Escape(Nan::Undefined()); // LCOV_EXCL_STOP } } /** * Create an image from a byte stream buffer. (synchronous) * * @name fromBytesSync * @param {Buffer} buffer - image buffer * @returns {mapnik.Image} image object * @instance * @memberof Image * @example * var buffer = fs.readFileSync('./path/to/image.png'); * var img = new mapnik.Image.fromBytesSync(buffer); */ NAN_METHOD(Image::fromBytesSync) { info.GetReturnValue().Set(_fromBytesSync(info)); } v8::Local<v8::Value> Image::_fromBytesSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; if (info.Length() < 1 || !info[0]->IsObject()) { Nan::ThrowTypeError("must provide a buffer argument"); return scope.Escape(Nan::Undefined()); } v8::Local<v8::Object> obj = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj)) { Nan::ThrowTypeError("first argument is invalid, must be a Buffer"); return scope.Escape(Nan::Undefined()); } try { std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(node::Buffer::Data(obj),node::Buffer::Length(obj))); if (reader.get()) { image_ptr imagep = std::make_shared<mapnik::image_any>(reader->read(0,0,reader->width(),reader->height())); Image* im = new Image(imagep); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) Nan::ThrowError("Could not create new Image instance"); return scope.Escape(maybe_local.ToLocalChecked()); } // The only way this is ever reached is if the reader factory in // mapnik was not providing an image type it should. This should never // be occuring so marking this out from coverage /* LCOV_EXCL_START */ Nan::ThrowTypeError("Failed to load from buffer"); return scope.Escape(Nan::Undefined()); /* LCOV_EXCL_STOP */ } catch (std::exception const& ex) { Nan::ThrowError(ex.what()); return scope.Escape(Nan::Undefined()); } } /** * Create an image from a byte stream buffer. * * @name fromBytes * @param {Buffer} buffer - image buffer * @param {Object} [options] * @param {Boolean} [options.premultiply] - Default false, if true, then the image will be premultiplied before being returned * @param {Number} [options.max_size] - the maximum allowed size of the image dimensions. The default is 2048. * @param {Function} callback - `function(err, img)` * @static * @memberof Image * @example * var buffer = fs.readFileSync('./path/to/image.png'); * mapnik.Image.fromBytes(buffer, function(err, img) { * if (err) throw err; * // your custom code with `img` object * }); */ NAN_METHOD(Image::fromBytes) { if (info.Length() == 1) { info.GetReturnValue().Set(_fromBytesSync(info)); return; } if (info.Length() < 2) { Nan::ThrowError("must provide a buffer argument"); return; } if (!info[0]->IsObject()) { Nan::ThrowTypeError("must provide a buffer argument"); return; } v8::Local<v8::Object> obj = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !node::Buffer::HasInstance(obj)) { Nan::ThrowTypeError("first argument is invalid, must be a Buffer"); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length() - 1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } bool premultiply = false; std::uint32_t max_size = 2048; if (info.Length() >= 2) { if (info[1]->IsObject()) { v8::Local<v8::Object> options = v8::Local<v8::Object>::Cast(info[1]); if (Nan::Has(options, Nan::New("premultiply").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("premultiply").ToLocalChecked()).ToLocalChecked(); if (!opt.IsEmpty() && opt->IsBoolean()) { premultiply = opt->BooleanValue(Nan::GetCurrentContext()).ToChecked(); } else { Nan::ThrowTypeError("premultiply option must be a boolean"); return; } } if (Nan::Has(options, Nan::New("max_size").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("max_size").ToLocalChecked()).ToLocalChecked(); if (opt->IsNumber()) { auto max_size_val = opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (max_size_val < 0 || max_size_val > 65535) { Nan::ThrowTypeError("max_size must be a positive integer between 0 and 65535"); return; } max_size = static_cast<std::uint32_t>(max_size_val); } else { Nan::ThrowTypeError("max_size option must be a number"); return; } } } } image_mem_ptr_baton_t *closure = new image_mem_ptr_baton_t(); closure->request.data = closure; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); closure->buffer.Reset(obj.As<v8::Object>()); closure->data = node::Buffer::Data(obj); closure->dataLength = node::Buffer::Length(obj); closure->premultiply = premultiply; closure->max_size = max_size; closure->im = nullptr; uv_queue_work(uv_default_loop(), &closure->request, EIO_FromBytes, (uv_after_work_cb)EIO_AfterFromBytes); return; } void Image::EIO_FromBytes(uv_work_t* req) { image_mem_ptr_baton_t *closure = static_cast<image_mem_ptr_baton_t *>(req->data); try { std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(closure->data,closure->dataLength)); if (reader.get()) { if (reader->width() > closure->max_size || reader->height() > closure->max_size) { std::stringstream s; s << "image created from bytes must be " << closure->max_size << " pixels or fewer on each side"; closure->error_name = s.str(); } else { closure->im = std::make_shared<mapnik::image_any>(reader->read(0,0,reader->width(),reader->height())); if (closure->premultiply) { mapnik::premultiply_alpha(*closure->im); } } } } catch (std::exception const& ex) { closure->error_name = ex.what(); } } void Image::EIO_AfterFromBytes(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); image_mem_ptr_baton_t *closure = static_cast<image_mem_ptr_baton_t *>(req->data); if (!closure->error_name.empty()) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else if (closure->im == nullptr) { /* LCOV_EXCL_START */ // The only way this is ever reached is if the reader factory in // mapnik was not providing an image type it should. This should never // be occuring so marking this out from coverage v8::Local<v8::Value> argv[1] = { Nan::Error("Failed to load from buffer") }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); /* LCOV_EXCL_STOP */ } else { Image* im = new Image(closure->im); v8::Local<v8::Value> ext = Nan::New<v8::External>(im); Nan::MaybeLocal<v8::Object> maybe_local = Nan::NewInstance(Nan::GetFunction(Nan::New(constructor)).ToLocalChecked(), 1, &ext); if (maybe_local.IsEmpty()) { v8::Local<v8::Value> argv[1] = { Nan::Error("Could not create new Image instance") }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), maybe_local.ToLocalChecked() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } } closure->cb.Reset(); closure->buffer.Reset(); delete closure; } /** * Encode this image into a buffer of encoded data (synchronous) * * @name encodeSync * @param {string} [format=png] image format * @param {Object} [options] * @param {mapnik.Palette} [options.palette] - mapnik.Palette object * @returns {Buffer} buffer - encoded image data * @instance * @memberof Image * @example * var img = new mapnik.Image.open('./path/to/image.png'); * var buffer = img.encodeSync('png'); * // write buffer to a new file * fs.writeFileSync('myimage.png', buffer); */ NAN_METHOD(Image::encodeSync) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); std::string format = "png"; palette_ptr palette; // accept custom format if (info.Length() >= 1){ if (!info[0]->IsString()) { Nan::ThrowTypeError("first arg, 'format' must be a string"); return; } format = TOSTR(info[0]); } // options hash if (info.Length() >= 2) { if (!info[1]->IsObject()) { Nan::ThrowTypeError("optional second arg must be an options object"); return; } v8::Local<v8::Object> options = info[1]->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (Nan::Has(options, Nan::New("palette").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> format_opt = Nan::Get(options, Nan::New("palette").ToLocalChecked()).ToLocalChecked(); if (!format_opt->IsObject()) { Nan::ThrowTypeError("'palette' must be an object"); return; } v8::Local<v8::Object> obj = format_opt->ToObject(Nan::GetCurrentContext()).ToLocalChecked(); if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Palette::constructor)->HasInstance(obj)) { Nan::ThrowTypeError("mapnik.Palette expected as second arg"); return; } palette = Nan::ObjectWrap::Unwrap<Palette>(obj)->palette(); } } try { std::string s; if (palette.get()) { s = save_to_string(*(im->this_), format, *palette); } else { s = save_to_string(*(im->this_), format); } info.GetReturnValue().Set(Nan::CopyBuffer((char*)s.data(), s.size()).ToLocalChecked()); } catch (std::exception const& ex) { Nan::ThrowError(ex.what()); return; } } typedef struct { uv_work_t request; Image* im; std::string format; palette_ptr palette; bool error; std::string error_name; Nan::Persistent<v8::Function> cb; std::string result; } encode_image_baton_t; /** * Encode this image into a buffer of encoded data * * @name encode * @param {string} [format=png] image format * @param {Object} [options] * @param {mapnik.Palette} [options.palette] - mapnik.Palette object * @param {Function} callback - `function(err, encoded)` * @returns {Buffer} encoded image data * @instance * @memberof Image * @example * var img = new mapnik.Image.open('./path/to/image.png'); * myImage.encode('png', function(err, encoded) { * if (err) throw err; * // write buffer to new file * fs.writeFileSync('myimage.png', encoded); * }); * * // encoding an image object with a mapnik.Palette * var im = new mapnik.Image(256, 256); * var pal = new mapnik.Palette(new Buffer('\xff\x09\x93\xFF\x01\x02\x03\x04','ascii')); * im.encode('png', {palette: pal}, function(err, encode) { * if (err) throw err; * // your custom code with `encode` image buffer * }); */ NAN_METHOD(Image::encode) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); std::string format = "png"; palette_ptr palette; // accept custom format if (info.Length() >= 1){ if (!info[0]->IsString()) { Nan::ThrowTypeError("first arg, 'format' must be a string"); return; } format = TOSTR(info[0]); } // options hash if (info.Length() >= 2) { if (!info[1]->IsObject()) { Nan::ThrowTypeError("optional second arg must be an options object"); return; } v8::Local<v8::Object> options = info[1].As<v8::Object>(); if (Nan::Has(options, Nan::New("palette").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> format_opt = Nan::Get(options, Nan::New("palette").ToLocalChecked()).ToLocalChecked(); if (!format_opt->IsObject()) { Nan::ThrowTypeError("'palette' must be an object"); return; } v8::Local<v8::Object> obj = format_opt.As<v8::Object>(); if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Palette::constructor)->HasInstance(obj)) { Nan::ThrowTypeError("mapnik.Palette expected as second arg"); return; } palette = Nan::ObjectWrap::Unwrap<Palette>(obj)->palette(); } } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length() - 1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } encode_image_baton_t *closure = new encode_image_baton_t(); closure->request.data = closure; closure->im = im; closure->format = format; closure->palette = palette; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Encode, (uv_after_work_cb)EIO_AfterEncode); im->_ref(); return; } void Image::EIO_Encode(uv_work_t* req) { encode_image_baton_t *closure = static_cast<encode_image_baton_t *>(req->data); try { if (closure->palette.get()) { closure->result = save_to_string(*(closure->im->this_), closure->format, *closure->palette); } else { closure->result = save_to_string(*(closure->im->this_), closure->format); } } catch (std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterEncode(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); encode_image_baton_t *closure = static_cast<encode_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), Nan::CopyBuffer((char*)closure->result.data(), closure->result.size()).ToLocalChecked() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } closure->im->_unref(); closure->cb.Reset(); delete closure; } /** * Get a constrained view of this image given x, y, width, height parameters. * @memberof Image * @instance * @name view * @param {number} x * @param {number} y * @param {number} width * @param {number} height * @returns {mapnik.Image} an image constrained to this new view * @example * var img = new mapnik.Image(10, 10); * // This function says "starting from the 0/0 pixel, grab 5 pixels along * // the x-axis and 5 along the y-axis" which gives us a quarter of the original * // 10x10 pixel image * var img2 = img.view(0, 0, 5, 5); * console.log(img.width(), img2.width()); // 10, 5 */ NAN_METHOD(Image::view) { if ( (info.Length() != 4) || (!info[0]->IsNumber() && !info[1]->IsNumber() && !info[2]->IsNumber() && !info[3]->IsNumber() )) { Nan::ThrowTypeError("requires 4 integer arguments: x, y, width, height"); return; } // TODO parse args unsigned x = info[0]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); unsigned y = info[1]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); unsigned w = info[2]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); unsigned h = info[3]->IntegerValue(Nan::GetCurrentContext()).ToChecked(); Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); info.GetReturnValue().Set(ImageView::NewInstance(im,x,y,w,h)); } /** * Encode this image and save it to disk as a file. * * @name saveSync * @param {string} filename * @param {string} [format=png] * @instance * @memberof Image * @example * img.saveSync('foo.png'); */ NAN_METHOD(Image::saveSync) { info.GetReturnValue().Set(_saveSync(info)); } v8::Local<v8::Value> Image::_saveSync(Nan::NAN_METHOD_ARGS_TYPE info) { Nan::EscapableHandleScope scope; Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (info.Length() == 0 || !info[0]->IsString()){ Nan::ThrowTypeError("filename required to save file"); return scope.Escape(Nan::Undefined()); } std::string filename = TOSTR(info[0]); std::string format(""); if (info.Length() >= 2) { if (!info[1]->IsString()) { Nan::ThrowTypeError("both 'filename' and 'format' arguments must be strings"); return scope.Escape(Nan::Undefined()); } format = TOSTR(info[1]); } else { format = mapnik::guess_type(filename); if (format == "<unknown>") { std::ostringstream s(""); s << "unknown output extension for: " << filename << "\n"; Nan::ThrowError(s.str().c_str()); return scope.Escape(Nan::Undefined()); } } try { mapnik::save_to_file(*(im->this_),filename, format); } catch (std::exception const& ex) { Nan::ThrowError(ex.what()); } return scope.Escape(Nan::Undefined()); } typedef struct { uv_work_t request; Image* im; std::string format; std::string filename; bool error; std::string error_name; Nan::Persistent<v8::Function> cb; } save_image_baton_t; /** * Encode this image and save it to disk as a file. * * @name save * @param {string} filename * @param {string} [format=png] * @param {Function} callback * @instance * @memberof Image * @example * img.save('image.png', 'png', function(err) { * if (err) throw err; * // your custom code * }); */ NAN_METHOD(Image::save) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (info.Length() == 0 || !info[0]->IsString()){ Nan::ThrowTypeError("filename required to save file"); return; } if (!info[info.Length()-1]->IsFunction()) { info.GetReturnValue().Set(_saveSync(info)); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length()-1]; std::string filename = TOSTR(info[0]); std::string format(""); if (info.Length() >= 3) { if (!info[1]->IsString()) { Nan::ThrowTypeError("both 'filename' and 'format' arguments must be strings"); return; } format = TOSTR(info[1]); } else { format = mapnik::guess_type(filename); if (format == "<unknown>") { std::ostringstream s(""); s << "unknown output extension for: " << filename << "\n"; Nan::ThrowError(s.str().c_str()); return; } } save_image_baton_t *closure = new save_image_baton_t(); closure->request.data = closure; closure->format = format; closure->filename = filename; closure->im = im; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Save, (uv_after_work_cb)EIO_AfterSave); im->_ref(); return; } void Image::EIO_Save(uv_work_t* req) { save_image_baton_t *closure = static_cast<save_image_baton_t *>(req->data); try { mapnik::save_to_file(*(closure->im->this_), closure->filename, closure->format); } catch (std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterSave(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); save_image_baton_t *closure = static_cast<save_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[1] = { Nan::Null() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } closure->im->_unref(); closure->cb.Reset(); delete closure; } typedef struct { uv_work_t request; Image* im1; Image* im2; mapnik::composite_mode_e mode; int dx; int dy; float opacity; std::vector<mapnik::filter::filter_type> filters; bool error; std::string error_name; Nan::Persistent<v8::Function> cb; } composite_image_baton_t; /** * Overlay this image with another image, creating a layered composite as * a new image * * @name composite * @param {mapnik.Image} image - image to composite with * @param {Object} [options] * @param {mapnik.compositeOp} [options.comp_op] - compositing operation. Must be an integer * value that relates to a compositing operation. * @param {number} [options.opacity] - opacity must be a floating point number between 0-1 * @param {number} [options.dx] * @param {number} [options.dy] * @param {string} [options.image_filters] - a string of filter names * @param {Function} callback * @instance * @memberof Image * @example * var img1 = new mapnik.Image.open('./path/to/image.png'); * var img2 = new mapnik.Image.open('./path/to/another-image.png'); * img1.composite(img2, { * comp_op: mapnik.compositeOp['multiply'], * dx: 0, * dy: 0, * opacity: 0.5, * image_filters: 'invert agg-stack-blur(10,10)' * }, function(err, result) { * if (err) throw err; * // new image with `result` * }); */ NAN_METHOD(Image::composite) { if (info.Length() < 1){ Nan::ThrowTypeError("requires at least one argument: an image mask"); return; } if (!info[0]->IsObject()) { Nan::ThrowTypeError("first argument must be an image mask"); return; } v8::Local<v8::Object> im2 = info[0].As<v8::Object>(); if (im2->IsNull() || im2->IsUndefined() || !Nan::New(Image::constructor)->HasInstance(im2)) { Nan::ThrowTypeError("mapnik.Image expected as first arg"); return; } // ensure callback is a function v8::Local<v8::Value> callback = info[info.Length() - 1]; if (!info[info.Length()-1]->IsFunction()) { Nan::ThrowTypeError("last argument must be a callback function"); return; } Image * dest_image = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); Image * source_image = Nan::ObjectWrap::Unwrap<Image>(im2); if (!dest_image->this_->get_premultiplied()) { Nan::ThrowTypeError("destination image must be premultiplied"); return; } if (!source_image->this_->get_premultiplied()) { Nan::ThrowTypeError("source image must be premultiplied"); return; } mapnik::composite_mode_e mode = mapnik::src_over; float opacity = 1.0; std::vector<mapnik::filter::filter_type> filters; int dx = 0; int dy = 0; if (info.Length() >= 2) { if (!info[1]->IsObject()) { Nan::ThrowTypeError("optional second arg must be an options object"); return; } v8::Local<v8::Object> options = info[1].As<v8::Object>(); if (Nan::Has(options, Nan::New("comp_op").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("comp_op").ToLocalChecked()).ToLocalChecked(); if (!opt->IsNumber()) { Nan::ThrowTypeError("comp_op must be a mapnik.compositeOp value"); return; } int mode_int = opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); if (mode_int > static_cast<int>(mapnik::composite_mode_e::divide) || mode_int < 0) { Nan::ThrowTypeError("Invalid comp_op value"); return; } mode = static_cast<mapnik::composite_mode_e>(mode_int); } if (Nan::Has(options, Nan::New("opacity").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("opacity").ToLocalChecked()).ToLocalChecked(); if (!opt->IsNumber()) { Nan::ThrowTypeError("opacity must be a floating point number"); return; } opacity = opt->NumberValue(Nan::GetCurrentContext()).ToChecked(); if (opacity < 0 || opacity > 1) { Nan::ThrowTypeError("opacity must be a floating point number between 0-1"); return; } } if (Nan::Has(options, Nan::New("dx").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("dx").ToLocalChecked()).ToLocalChecked(); if (!opt->IsNumber()) { Nan::ThrowTypeError("dx must be an integer"); return; } dx = opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("dy").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("dy").ToLocalChecked()).ToLocalChecked(); if (!opt->IsNumber()) { Nan::ThrowTypeError("dy must be an integer"); return; } dy = opt->IntegerValue(Nan::GetCurrentContext()).ToChecked(); } if (Nan::Has(options, Nan::New("image_filters").ToLocalChecked()).FromMaybe(false)) { v8::Local<v8::Value> opt = Nan::Get(options, Nan::New("image_filters").ToLocalChecked()).ToLocalChecked(); if (!opt->IsString()) { Nan::ThrowTypeError("image_filters argument must string of filter names"); return; } std::string filter_str = TOSTR(opt); bool result = mapnik::filter::parse_image_filters(filter_str, filters); if (!result) { Nan::ThrowTypeError("could not parse image_filters"); return; } } } composite_image_baton_t *closure = new composite_image_baton_t(); closure->request.data = closure; closure->im1 = dest_image; closure->im2 = source_image; closure->mode = mode; closure->opacity = opacity; closure->filters = std::move(filters); closure->dx = dx; closure->dy = dy; closure->error = false; closure->cb.Reset(callback.As<v8::Function>()); uv_queue_work(uv_default_loop(), &closure->request, EIO_Composite, (uv_after_work_cb)EIO_AfterComposite); closure->im1->_ref(); closure->im2->_ref(); return; } void Image::EIO_Composite(uv_work_t* req) { composite_image_baton_t *closure = static_cast<composite_image_baton_t *>(req->data); try { if (closure->filters.size() > 0) { // TODO: expose passing custom scale_factor: https://github.com/mapnik/mapnik/commit/b830469d2d574ac575ff24713935378894f8bdc9 mapnik::filter::filter_visitor<mapnik::image_any> visitor(*closure->im2->this_); for (mapnik::filter::filter_type const& filter_tag : closure->filters) { mapnik::util::apply_visitor(visitor, filter_tag); } mapnik::premultiply_alpha(*closure->im2->this_); } mapnik::composite(*closure->im1->this_,*closure->im2->this_, closure->mode, closure->opacity, closure->dx, closure->dy); } catch (std::exception const& ex) { closure->error = true; closure->error_name = ex.what(); } } void Image::EIO_AfterComposite(uv_work_t* req, int) { Nan::HandleScope scope; Nan::AsyncResource async_resource(__func__); composite_image_baton_t *closure = static_cast<composite_image_baton_t *>(req->data); if (closure->error) { v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv); } else { v8::Local<v8::Value> argv[2] = { Nan::Null(), closure->im1->handle() }; async_resource.runInAsyncScope(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv); } closure->im1->_unref(); closure->im2->_unref(); closure->cb.Reset(); delete closure; } NAN_GETTER(Image::get_scaling) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); info.GetReturnValue().Set(Nan::New<v8::Number>(im->this_->get_scaling())); } NAN_GETTER(Image::get_offset) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); info.GetReturnValue().Set(Nan::New<v8::Number>(im->this_->get_offset())); } NAN_SETTER(Image::set_scaling) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (!value->IsNumber()) { Nan::ThrowError("Must provide a number"); } else { double val = value->NumberValue(Nan::GetCurrentContext()).ToChecked(); if (val == 0.0) { Nan::ThrowError("Scaling value can not be zero"); return; } im->this_->set_scaling(val); } } NAN_SETTER(Image::set_offset) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (!value->IsNumber()) { Nan::ThrowError("Must provide a number"); } else { double val = value->NumberValue(Nan::GetCurrentContext()).ToChecked(); im->this_->set_offset(val); } } /** * Return a copy of the pixel data in this image as a buffer * * @name data * @instance * @memberof Image * @returns {Buffer} pixel data as a buffer * @example * var img = new mapnik.Image.open('./path/to/image.png'); * var buffr = img.data(); */ NAN_METHOD(Image::data) { Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); // TODO - make this zero copy info.GetReturnValue().Set(Nan::CopyBuffer(reinterpret_cast<const char *>(im->this_->bytes()), im->this_->size()).ToLocalChecked()); } NAN_GETTER(Image::get_metrics_enabled) { #ifndef MAPNIK_METRICS bool active = false; #else Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); bool active = im->this_->get_metrics().enabled_; #endif info.GetReturnValue().Set(Nan::New<v8::Boolean>(active)); } NAN_SETTER(Image::set_metrics_enabled) { #ifdef MAPNIK_METRICS Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); if (!value->IsBoolean()) { Nan::ThrowError("Must provide a boolean"); } else { bool val = value->BooleanValue(Nan::GetCurrentContext()).ToChecked(); im->this_->get_metrics().enabled_ = val; } #endif } NAN_METHOD(Image::get_metrics) { #ifdef MAPNIK_METRICS Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder()); auto result = node_mapnik::metrics_to_object(im->this_->get_metrics()); if (!result.IsEmpty()) { info.GetReturnValue().Set(result.ToLocalChecked()); return; } #endif info.GetReturnValue().Set(Nan::New<v8::Object>()); }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__struct_twoIntsStruct_calloc_83a.cpp Label Definition File: CWE401_Memory_Leak.c.label.xml Template File: sources-sinks-83a.tmpl.cpp */ /* * @description * CWE: 401 Memory Leak * BadSource: calloc Allocate data using calloc() * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call free() on data * BadSink : no deallocation of data * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #include "std_testcase.h" #include "CWE401_Memory_Leak__struct_twoIntsStruct_calloc_83.h" namespace CWE401_Memory_Leak__struct_twoIntsStruct_calloc_83 { #ifndef OMITBAD void bad() { struct _twoIntsStruct * data; data = NULL; CWE401_Memory_Leak__struct_twoIntsStruct_calloc_83_bad badObject(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { struct _twoIntsStruct * data; data = NULL; CWE401_Memory_Leak__struct_twoIntsStruct_calloc_83_goodG2B goodG2BObject(data); } /* goodG2B uses the BadSource with the GoodSink */ static void goodB2G() { struct _twoIntsStruct * data; data = NULL; CWE401_Memory_Leak__struct_twoIntsStruct_calloc_83_goodB2G goodB2GObject(data); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE401_Memory_Leak__struct_twoIntsStruct_calloc_83; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
// The Art of C++ / PostgreSQL // Copyright (c) 2016 Daniel Frey #ifndef TAOCPP_INCLUDE_POSTGRES_RESULT_HPP #define TAOCPP_INCLUDE_POSTGRES_RESULT_HPP #include <memory> #include <string> #include <stdexcept> #include <utility> #include <tuple> #include <vector> #include <list> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <tao/optional/optional.hpp> #include <tao/utility/printf.hpp> #include <tao/postgres/row.hpp> // forward-declare libpq structures struct pg_result; typedef struct pg_result PGresult; namespace tao { namespace postgres { class connection; class table_writer; namespace result_impl { template< typename T, typename = void > struct has_reserve : std::false_type { }; template< typename T > struct has_reserve< T, typename std::enable_if< std::is_void< decltype( T::reserve( std::declval< typename T::size_type >() ) ) >::value >::type > : std::true_type { }; } class result { private: friend class connection; friend class table_writer; const std::shared_ptr< ::PGresult > pgresult_; const std::size_t columns_; const std::size_t rows_; void check_has_result_set() const; enum class mode_t { EXPECT_OK, EXPECT_COPY_IN }; result( ::PGresult* pgresult, const mode_t mode = mode_t::EXPECT_OK ); public: bool has_rows_affected() const; std::size_t rows_affected() const; std::size_t columns() const { return columns_; } std::string name( const std::size_t column ) const; std::size_t index( const std::string& name ) const; bool empty() const; std::size_t size() const; class const_iterator : private row { private: friend class result; const_iterator( const row& r ) : row( r ) { } public: friend bool operator!=( const const_iterator& lhs, const const_iterator& rhs ) { return lhs.row_ != rhs.row_; } const_iterator& operator++() { ++row_; return *this; } const row& operator*() const { return *this; } }; const_iterator begin() const; const_iterator end() const; bool is_null( const std::size_t row, const std::size_t column ) const; const char* get( const std::size_t row, const std::size_t column ) const; row operator[]( const std::size_t row ) const { return postgres::row( *this, row, 0, columns_ ); } row at( const std::size_t row ) const; template< typename T > T as() const { if( size() != 1 ) { throw std::runtime_error( utility::printf( "invalid result size: %zu rows, expected 1 row", rows_ ) ); } return (*this)[ 0 ].as< T >(); } template< typename T > tao::optional< T > optional() const { if( empty() ) { return tao::optional< T >(); } return tao::optional< T >( as< T >() ); } template< typename T, typename U > std::pair< T, U > pair() const { return as< std::pair< T, U > >(); } template< typename... Ts > std::tuple< Ts... > tuple() const { return as< std::tuple< Ts... > >(); } template< typename T > typename std::enable_if< result_impl::has_reserve< T >::value, T >::type as_container() const { T nrv; nrv.reserve( size() ); for( const auto& row : *this ) { nrv.insert( nrv.end(), row.as< typename T::value_type >() ); } return nrv; } template< typename T > typename std::enable_if< !result_impl::has_reserve< T >::value, T >::type as_container() const { T nrv; check_has_result_set(); for( const auto& row : *this ) { nrv.insert( nrv.end(), row.as< typename T::value_type >() ); } return nrv; } template< typename... Ts > std::vector< Ts... > vector() const { return as_container< std::vector< Ts... > >(); } template< typename... Ts > std::list< Ts... > list() const { return as_container< std::list< Ts... > >(); } template< typename... Ts > std::set< Ts... > set() const { return as_container< std::set< Ts... > >(); } template< typename... Ts > std::multiset< Ts... > multiset() const { return as_container< std::multiset< Ts... > >(); } template< typename... Ts > std::unordered_set< Ts... > unordered_set() const { return as_container< std::unordered_set< Ts... > >(); } template< typename... Ts > std::unordered_multiset< Ts... > unordered_multiset() const { return as_container< std::unordered_multiset< Ts... > >(); } template< typename... Ts > std::map< Ts... > map() const { return as_container< std::map< Ts... > >(); } template< typename... Ts > std::multimap< Ts... > multimap() const { return as_container< std::multimap< Ts... > >(); } template< typename... Ts > std::unordered_map< Ts... > unordered_map() const { return as_container< std::unordered_map< Ts... > >(); } template< typename... Ts > std::unordered_multimap< Ts... > unordered_multimap() const { return as_container< std::unordered_multimap< Ts... > >(); } // make sure you include libpq-fe.h before accessing the raw pointer ::PGresult* underlying_raw_ptr() { return pgresult_.get(); } // make sure you include libpq-fe.h before accessing the raw pointer const ::PGresult* underlying_raw_ptr() const { return pgresult_.get(); } }; } } #endif // TAOCPP_INCLUDE_POSTGRES_RESULT_HPP
#include "blitter.h" _Blitter *_Blitter::singleton = NULL; void _Blitter::_bind_methods() { ObjectTypeDB::bind_method(_MD("calculate_new_rect_from_mins_max", "p_base_size", "p_mins", "p_max"), &_Blitter::calculate_new_rect_from_mins_max); ObjectTypeDB::bind_method(_MD("calculate_new_size_from_mins_max", "p_base_size", "p_mins", "p_max"), &_Blitter::calculate_new_size_from_mins_max); ObjectTypeDB::bind_method(_MD("blit_rect_modulate", "p_src:Image", "p_src_rect", "p_dest_point", "p_modulate"), &_Blitter::blit_rect_modulate); ObjectTypeDB::bind_method(_MD("blit_rect_modulate_inverted_alpha", "p_src:Image", "p_src_rect", "p_dest_point", "p_modulate"), &_Blitter::blit_rect_modulate_inverted_alpha); ObjectTypeDB::bind_method(_MD("blit_rect_modulate_inverted_alpha_translucent", "p_src:Image", "p_src_rect", "p_dest_point", "p_modulate"), &_Blitter::blit_rect_modulate_inverted_alpha_translucent); } _Blitter *_Blitter::get_singleton() { return singleton; } Rect2 _Blitter::calculate_new_rect_from_mins_max(const Vector2 &p_base_size, const Vector2 &p_mins, const Vector2 &p_max) { return Blitter::calculate_new_rect_from_mins_max(p_base_size, p_mins, p_max); } Vector2 _Blitter::calculate_new_size_from_mins_max(const Vector2 &p_base_size, const Vector2 &p_mins, const Vector2 &p_max) { return Blitter::calculate_new_size_from_mins_max(p_base_size, p_mins, p_max); } Image _Blitter::blit_rect_modulate(const Image& p_src, const Rect2& p_src_rect, const Image& p_dest, const Point2& p_dest_point, const Color &p_modulate) { return Blitter::blit_rect<true, false, false>(p_src, p_src_rect, p_dest, p_dest_point, p_modulate); } Image _Blitter::blit_rect_modulate_inverted_alpha(const Image& p_src, const Rect2& p_src_rect, const Image& p_dest, const Point2& p_dest_point, const Color &p_modulate) { return Blitter::blit_rect<true, true, false>(p_src, p_src_rect, p_dest, p_dest_point, p_modulate); } Image _Blitter::blit_rect_modulate_inverted_alpha_translucent(const Image& p_src, const Rect2& p_src_rect, const Image& p_dest, const Point2& p_dest_point, const Color &p_modulate) { return Blitter::blit_rect<true, true, true>(p_src, p_src_rect, p_dest, p_dest_point, p_modulate); } _Blitter::_Blitter() { singleton = this; }
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "meta/processors/AddHostsProcessor.h" namespace nebula { namespace meta { void AddHostsProcessor::process(const cpp2::AddHostsReq& req) { folly::SharedMutex::WriteHolder wHolder(LockUtils::spaceLock()); std::vector<kvstore::KV> data; for (auto& h : req.get_hosts()) { data.emplace_back(MetaServiceUtils::hostKey(h.ip, h.port), MetaServiceUtils::hostVal()); } doPut(std::move(data)); } } // namespace meta } // namespace nebula
/* Copyright (c) 2020-2021, Collab * All rights reserved */ /* WaterFlowMeter.cpp - Control water flow meter. */ #include <WaterFlowMeter.h> FlowMeter* _sensor; // define an 'interrupt service handler' (ISR) void countPulse() { // let our flow meter count the pulses _sensor->count(); } WaterFlowMeter::WaterFlowMeter(int pin, const char * ns) { _pin = pin; _namespace = ns; // preferences storage _prefs = new Preferences(); // flow sensor FlowSensorProperties sensorConfig = {cap, kf, {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.08955223881f, 0.08860759494f, 0.08791208791f, 0.08737864078f, 0.08771929825f}}; _sensor = new FlowMeter(_pin, sensorConfig); } void WaterFlowMeter::begin() { // enable a call to the 'interrupt service handler' (ISR) on every // rising edge at the interrupt pin. do this setup step for every // ISR you have defined, depending on how many interrupts you use attachInterrupt(_pin, countPulse, RISING); // sometimes initializing the gear generates some pulses that we // should ignore _sensor->reset(); } void WaterFlowMeter::measure(unsigned long period) { // process the (possibly) counted ticks _sensor->tick(period); } double WaterFlowMeter::getTotalVolume() { return _sensor->getTotalVolume(); } double WaterFlowMeter::getFlowRate() { return _sensor->getCurrentFlowrate(); } double WaterFlowMeter::getHistoricVolume() { _prefs->begin(_namespace, true); double historicLiters = _prefs->getDouble(keyName, 0); _prefs->end(); return historicLiters; } void WaterFlowMeter::saveHistoric() { double liters = getTotalVolume(); if (liters > 0) { _prefs->begin(_namespace, false); double historicLiters = _prefs->getDouble(keyName, 0); double updatedLiters = historicLiters + liters; // update data _prefs->putDouble(keyName, updatedLiters); _prefs->end(); } } void WaterFlowMeter::reset() { _prefs->begin(_namespace, false); // reset to zero _prefs->putDouble(keyName, 0); _prefs->end(); }
#pragma once #include <mgs/base_n/padding_policy.hpp> #include <mgs/exceptions/unexpected_eof_error.hpp> namespace mgs { namespace detail { template <typename EncodingTraits, base_n::padding_policy = EncodingTraits::padding_policy> struct encoded_input_reader { template <typename Iterator, typename Sentinel> static char read(Iterator& current, Sentinel const sent) { if (current == sent) { throw exceptions::unexpected_eof_error{"unexpected end of input"}; } return *current++; } }; template <typename EncodingTraits> struct encoded_input_reader<EncodingTraits, base_n::padding_policy::optional> { template <typename Iterator, typename Sentinel> static char read(Iterator& current, Sentinel const sent) { if (current == sent) return EncodingTraits::padding_character; return *current++; } }; } }
/* * Copyright (c) 2007, Michael Lehn * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2) 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. * 3) Neither the name of the FLENS development 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. */ #include <flens/storage.h> namespace flens { //-- crs - compressed row storage ---------------------------------------------- template <typename T> void crs_gemv(Transpose trans, int m, int n, T alpha, const T *a, const int *ia, const int *ja, const T *x, T beta, T *y) { assert((beta==T(0)) || (beta==T(1))); // shift to index base 1 a = a-1; ia = ia-1; ja = ja-1; x = x-1; y = y-1; const bool init = (beta==T(0)); if (trans==NoTrans) { if (init) { for (int i=1; i<=m; ++i) { y[i] = T(0); for (int k=ia[i]; k<ia[i+1]; ++k) { y[i] += alpha*a[k]*x[ja[k]]; } } } else { for (int i=1; i<=m; ++i) { for (int k=ia[i]; k<ia[i+1]; ++k) { y[i] += alpha*a[k]*x[ja[k]]; } } } } else { if (init) { for (int i=1; i<=n; ++i) { y[i] = T(0); } } for (int i=1; i<=m; ++i) { for (int k=ia[i]; k<ia[i+1]; ++k) { y[ja[k]] += alpha*a[k]*x[i]; } } } } template <typename T> void crs_symv(StorageUpLo upLo, int m, T alpha, const T *a, const int *ia, const int *ja, const T *x, T beta, T *y) { assert((beta==T(0)) || (beta==T(1))); // shift to index base 1 a = a-1; ia = ia-1; ja = ja-1; x = x-1; y = y-1; if (beta==T(0)) { for (int i=1; i<=m; ++i) { y[i] = 0; } } T a_k, x_i, y_i; if (upLo==Upper) { for (int i=1; i<=m; ++i) { assert(ja[ia[i]]==i); y_i = y[i]; x_i = x[i]; y_i += alpha*a[ia[i]]*x_i; for (int k=ia[i]+1; k<ia[i+1]; ++k) { a_k = a[k]; y_i += alpha*a_k*x[ja[k]]; y[ja[k]] += alpha*a_k*x_i; } y[i] = y_i; } } else { for (int i=1; i<=m; ++i) { y_i = y[i]; x_i = x[i]; for (int k=ia[i]; k<ia[i+1]-1; ++k) { a_k = a[k]; y_i += alpha*a_k*x[ja[k]]; y[ja[k]] += alpha*a_k*x_i; } assert(ja[ia[i+1]-1]==i); y_i += alpha*a[ia[i+1]-1]*x_i; y[i] = y_i; } } } } // namespace flens
#include "class_6.h" #include "class_0.h" #include "class_5.h" #include "class_8.h" #include "class_6.h" #include "class_2.h" #include <lib_20/class_3.h> #include <lib_0/class_5.h> #include <lib_52/class_8.h> #include <lib_26/class_0.h> #include <lib_39/class_2.h> class_6::class_6() {} class_6::~class_6() {}
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// UNIX_BGPAttributes::UNIX_BGPAttributes(void) { } UNIX_BGPAttributes::~UNIX_BGPAttributes(void) { } Boolean UNIX_BGPAttributes::getInstanceID(CIMProperty &p) const { p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID()); return true; } String UNIX_BGPAttributes::getInstanceID() const { return String (""); } Boolean UNIX_BGPAttributes::getCaption(CIMProperty &p) const { p = CIMProperty(PROPERTY_CAPTION, getCaption()); return true; } String UNIX_BGPAttributes::getCaption() const { return String (""); } Boolean UNIX_BGPAttributes::getDescription(CIMProperty &p) const { p = CIMProperty(PROPERTY_DESCRIPTION, getDescription()); return true; } String UNIX_BGPAttributes::getDescription() const { return String (""); } Boolean UNIX_BGPAttributes::getElementName(CIMProperty &p) const { p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName()); return true; } String UNIX_BGPAttributes::getElementName() const { return String("BGPAttributes"); } Boolean UNIX_BGPAttributes::getInstallDate(CIMProperty &p) const { p = CIMProperty(PROPERTY_INSTALL_DATE, getInstallDate()); return true; } CIMDateTime UNIX_BGPAttributes::getInstallDate() const { struct tm* clock; // create a time structure time_t val = time(NULL); clock = gmtime(&(val)); // Get the last modified time and put it into the time structure return CIMDateTime( clock->tm_year + 1900, clock->tm_mon + 1, clock->tm_mday, clock->tm_hour, clock->tm_min, clock->tm_sec, 0,0, clock->tm_gmtoff); } Boolean UNIX_BGPAttributes::getName(CIMProperty &p) const { p = CIMProperty(PROPERTY_NAME, getName()); return true; } String UNIX_BGPAttributes::getName() const { return String (""); } Boolean UNIX_BGPAttributes::getOperationalStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_OPERATIONAL_STATUS, getOperationalStatus()); return true; } Array<Uint16> UNIX_BGPAttributes::getOperationalStatus() const { Array<Uint16> as; return as; } Boolean UNIX_BGPAttributes::getStatusDescriptions(CIMProperty &p) const { p = CIMProperty(PROPERTY_STATUS_DESCRIPTIONS, getStatusDescriptions()); return true; } Array<String> UNIX_BGPAttributes::getStatusDescriptions() const { Array<String> as; return as; } Boolean UNIX_BGPAttributes::getStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_STATUS, getStatus()); return true; } String UNIX_BGPAttributes::getStatus() const { return String(DEFAULT_STATUS); } Boolean UNIX_BGPAttributes::getHealthState(CIMProperty &p) const { p = CIMProperty(PROPERTY_HEALTH_STATE, getHealthState()); return true; } Uint16 UNIX_BGPAttributes::getHealthState() const { return Uint16(DEFAULT_HEALTH_STATE); } Boolean UNIX_BGPAttributes::getCommunicationStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_COMMUNICATION_STATUS, getCommunicationStatus()); return true; } Uint16 UNIX_BGPAttributes::getCommunicationStatus() const { return Uint16(0); } Boolean UNIX_BGPAttributes::getDetailedStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_DETAILED_STATUS, getDetailedStatus()); return true; } Uint16 UNIX_BGPAttributes::getDetailedStatus() const { return Uint16(0); } Boolean UNIX_BGPAttributes::getOperatingStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_OPERATING_STATUS, getOperatingStatus()); return true; } Uint16 UNIX_BGPAttributes::getOperatingStatus() const { return Uint16(DEFAULT_OPERATING_STATUS); } Boolean UNIX_BGPAttributes::getPrimaryStatus(CIMProperty &p) const { p = CIMProperty(PROPERTY_PRIMARY_STATUS, getPrimaryStatus()); return true; } Uint16 UNIX_BGPAttributes::getPrimaryStatus() const { return Uint16(DEFAULT_PRIMARY_STATUS); } Boolean UNIX_BGPAttributes::getSystemCreationClassName(CIMProperty &p) const { p = CIMProperty(PROPERTY_SYSTEM_CREATION_CLASS_NAME, getSystemCreationClassName()); return true; } String UNIX_BGPAttributes::getSystemCreationClassName() const { return String("UNIX_ComputerSystem"); } Boolean UNIX_BGPAttributes::getSystemName(CIMProperty &p) const { p = CIMProperty(PROPERTY_SYSTEM_NAME, getSystemName()); return true; } String UNIX_BGPAttributes::getSystemName() const { return CIMHelper::HostName; } Boolean UNIX_BGPAttributes::getVersion(CIMProperty &p) const { p = CIMProperty(PROPERTY_VERSION, getVersion()); return true; } String UNIX_BGPAttributes::getVersion() const { return String (""); } Boolean UNIX_BGPAttributes::getLocalPreference(CIMProperty &p) const { p = CIMProperty(PROPERTY_LOCAL_PREFERENCE, getLocalPreference()); return true; } Uint16 UNIX_BGPAttributes::getLocalPreference() const { return Uint16(0); } Boolean UNIX_BGPAttributes::getASPath(CIMProperty &p) const { p = CIMProperty(PROPERTY_A_S_PATH, getASPath()); return true; } String UNIX_BGPAttributes::getASPath() const { return String (""); } Boolean UNIX_BGPAttributes::getAsSet(CIMProperty &p) const { p = CIMProperty(PROPERTY_AS_SET, getAsSet()); return true; } String UNIX_BGPAttributes::getAsSet() const { return String (""); } Boolean UNIX_BGPAttributes::getNextHop(CIMProperty &p) const { p = CIMProperty(PROPERTY_NEXT_HOP, getNextHop()); return true; } String UNIX_BGPAttributes::getNextHop() const { return String (""); } Boolean UNIX_BGPAttributes::getNextHopSelf(CIMProperty &p) const { p = CIMProperty(PROPERTY_NEXT_HOP_SELF, getNextHopSelf()); return true; } String UNIX_BGPAttributes::getNextHopSelf() const { return String (""); } Boolean UNIX_BGPAttributes::getMED(CIMProperty &p) const { p = CIMProperty(PROPERTY_M_E_D, getMED()); return true; } Uint32 UNIX_BGPAttributes::getMED() const { return Uint32(0); } Boolean UNIX_BGPAttributes::getBGPCommunityValue(CIMProperty &p) const { p = CIMProperty(PROPERTY_B_G_P_COMMUNITY_VALUE, getBGPCommunityValue()); return true; } Uint32 UNIX_BGPAttributes::getBGPCommunityValue() const { return Uint32(0); } Boolean UNIX_BGPAttributes::getAtomicAggregate(CIMProperty &p) const { p = CIMProperty(PROPERTY_ATOMIC_AGGREGATE, getAtomicAggregate()); return true; } Boolean UNIX_BGPAttributes::getAtomicAggregate() const { return Boolean(false); } Boolean UNIX_BGPAttributes::getAggregator(CIMProperty &p) const { p = CIMProperty(PROPERTY_AGGREGATOR, getAggregator()); return true; } String UNIX_BGPAttributes::getAggregator() const { return String (""); } Boolean UNIX_BGPAttributes::getOrigin(CIMProperty &p) const { p = CIMProperty(PROPERTY_ORIGIN, getOrigin()); return true; } Uint16 UNIX_BGPAttributes::getOrigin() const { return Uint16(0); } Boolean UNIX_BGPAttributes::getOriginatorID(CIMProperty &p) const { p = CIMProperty(PROPERTY_ORIGINATOR_ID, getOriginatorID()); return true; } String UNIX_BGPAttributes::getOriginatorID() const { return String (""); } Boolean UNIX_BGPAttributes::initialize() { return false; } Boolean UNIX_BGPAttributes::load(int &pIndex) { return false; } Boolean UNIX_BGPAttributes::finalize() { return false; } Boolean UNIX_BGPAttributes::find(Array<CIMKeyBinding> &kbArray) { CIMKeyBinding kb; String systemCreationClassNameKey; String systemNameKey; String versionKey; for(Uint32 i = 0; i < kbArray.size(); i++) { kb = kbArray[i]; CIMName keyName = kb.getName(); if (keyName.equal(PROPERTY_SYSTEM_CREATION_CLASS_NAME)) systemCreationClassNameKey = kb.getValue(); else if (keyName.equal(PROPERTY_SYSTEM_NAME)) systemNameKey = kb.getValue(); else if (keyName.equal(PROPERTY_VERSION)) versionKey = kb.getValue(); } /* EXecute find with extracted keys */ return false; }
#include "drake/systems/rendering/pose_vector.h" #include <memory> #include <sstream> #include <string> #include <vector> #include <Eigen/Dense> #include <Eigen/Geometry> #include <gtest/gtest.h> #include "drake/common/symbolic.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { using Eigen::Vector3d; using math::RigidTransform; using math::RigidTransformd; using symbolic::test::ExprEqual; namespace systems { namespace rendering { namespace { // Tests that the default PoseVector is initialized to identity. GTEST_TEST(PoseVector, InitiallyIdentity) { const PoseVector<double> vec; EXPECT_TRUE(CompareMatrices(RigidTransformd().GetAsMatrix4(), vec.get_transform().GetAsMatrix4())); // Check that the underlying storage has the values we'd expect. for (int i = 0; i < 3; ++i) { // p_WA is entirely zero. EXPECT_EQ(0.0, vec[i]); } // The real part of R_WA is cos(0) = 1. EXPECT_EQ(1.0, vec[3]); for (int i = 4; i < vec.kSize; ++i) { // The imaginary parts of R_WA are sin(0) = 0. EXPECT_EQ(0.0, vec[i]); } } // Tests the fully-parameterized PoseVector. GTEST_TEST(PoseVector, FullyParameterizedCtor) { const Eigen::Quaternion<double> rotation(0.5, 0.5, 0.5, 0.5); const Eigen::Vector3d origin(1.0, 2.0, 3.0); const Eigen::Translation3d translation(origin); const PoseVector<double> vec(rotation, translation); RigidTransformd transform_expected(rotation, origin); EXPECT_TRUE(CompareMatrices(transform_expected.GetAsMatrix4(), vec.get_transform().GetAsMatrix4())); EXPECT_TRUE(CompareMatrices( RigidTransformd(translation).GetAsMatrix4(), RigidTransformd(vec.get_translation().vector()).GetAsMatrix4())); EXPECT_TRUE(CompareMatrices(rotation.matrix(), vec.get_rotation().matrix())); } GTEST_TEST(PoseVector, Rotation) { PoseVector<double> vec; // Rotate by 2π/3 around the axis {1, 1, 1}. vec.set_rotation(Eigen::Quaternion<double>(0.5, 0.5, 0.5, 0.5)); // Check that the data was copied. for (int i = 3; i < vec.kSize; ++i) { EXPECT_EQ(0.5, vec[i]); } // Check that the isometry transforms the x-axis to the y-axis. const RigidTransformd X_WA = vec.get_transform(); const Eigen::Vector3d p_in = {1.0, 0.0, 0.0}; const Eigen::Vector3d p_out = X_WA * p_in; EXPECT_EQ((Eigen::Vector3d{0.0, 1.0, 0.0}), p_out); } GTEST_TEST(PoseVector, Translation) { PoseVector<double> vec; vec.set_translation(Eigen::Translation<double, 3>(1.0, 2.0, 3.0)); // Check that the data was copied. for (int i = 0; i < 3; ++i) { EXPECT_EQ(1.0 * (i + 1), vec[i]); } // Check that the isometry is a pure translation. const RigidTransformd X_WA = vec.get_transform(); const Eigen::Vector3d p_in = {1.0, 2.0, 3.0}; const Eigen::Vector3d p_out = X_WA * p_in; EXPECT_EQ((Eigen::Vector3d{2.0, 4.0, 6.0}), p_out); } // Tests that PoseVector<T>::Clone has PoseVector type. GTEST_TEST(PoseVector, Clone) { const PoseVector<double> vec; auto clone = vec.Clone(); EXPECT_NE(nullptr, dynamic_cast<PoseVector<double>*>(clone.get())); } GTEST_TEST(PoseVector, Symbolic) { PoseVector<symbolic::Expression> vec; vec[0] = symbolic::Variable("x"); vec[1] = symbolic::Variable("y"); vec[2] = symbolic::Variable("z"); vec[3] = symbolic::Variable("w"); vec[4] = symbolic::Variable("a"); vec[5] = symbolic::Variable("b"); vec[6] = symbolic::Variable("c"); // Spot-check some terms from the output. const RigidTransform<symbolic::Expression> X_WA = vec.get_transform(); const auto matrix = X_WA.GetAsMatrix4(); // Note: RigidTransform normalizes the quaternion in an order of operations // that leads to a *very* specific set of symbolic expressions. That is what // is represented below. // The squared L2 norm of the quaternion; if it were already unit length, // this factor would be one and the expressions down below would be much // simpler. const symbolic::Expression q_norm2 = vec[3] * vec[3] + vec[4] * vec[4] + vec[5] * vec[5] + vec[6] * vec[6]; // Rotation - first element on the diagonal EXPECT_PRED2( ExprEqual, 1 - vec[5] * ((2 * vec[5]) / q_norm2) - vec[6] * ((2 * vec[6]) / q_norm2), matrix(0, 0)); // Rotation - second element in the third row EXPECT_PRED2( ExprEqual, vec[5] * ((2 * vec[6]) / q_norm2) + vec[3] * ((2 * vec[4]) / q_norm2), matrix(2, 1)); // Translation - fourth element in the second row EXPECT_PRED2(ExprEqual, vec[1], matrix(1, 3)); } GTEST_TEST(PoseVector, Autodiff) { PoseVector<AutoDiffXd> vec; for (int i = 0; i < vec.size(); ++i) { // Initialize the position to {0.5, 0.5, 0.5}, and the rotation to // 2π/3 around the axis {1, 1, 1}. vec[i].value() = 0.5; // Initialize the Jacobian to the identity matrix. vec[i].derivatives().resize(vec.kSize); for (int j = 0; j < vec.kSize; ++j) { vec[i].derivatives()[j] = j == i ? 1.0 : 0.0; } } // Spot-check some terms from the output. const RigidTransform<AutoDiffXd> X_WA = vec.get_transform(); auto matrix = X_WA.GetAsMatrix4(); // Converting quaternion to RigidTransform performs a normalization step. // As illustrated in the `Symbolic` test the value stored in M(0, 0) is: // // 2b² + 2c² // M(0,0) = 1 - ────────── // |q|² // // ∂ 4b(a² + w²) // ── M(0, 0) = - ─────────────, and // ∂b (|q|²)² // // ∂ 4w(b² + c²) // ── M(0, 0) = ───────────── // ∂w (|q|²)² // const double w = vec[3].value(); const double a = vec[4].value(); const double b = vec[5].value(); const double c = vec[6].value(); const double q_norm2 = w * w + a * a + b * b + c * c; const double dMdb = -4 * b * (a * a + w * w) / (q_norm2 * q_norm2); EXPECT_DOUBLE_EQ(dMdb, matrix(0, 0).derivatives()[5]); const double dMdw = 4 * w * (b * b + c * c) / (q_norm2 * q_norm2); EXPECT_DOUBLE_EQ(dMdw, matrix(0, 0).derivatives()[3]); // The partial of the third element of the transformation vector with respect // to "z" is 1. With respect to anything else, it's zero. const auto& dz = matrix(2, 3).derivatives(); for (int i = 0; i < dz.size(); ++i) { EXPECT_EQ(i == 2 ? 1 : 0, dz[i]); } // The bottom row of the rotation matrix is constant. for (int i = 0; i < 4; ++i) { const auto& partials = matrix(3, i).derivatives(); for (int j = 0; j < partials.size(); ++j) { EXPECT_EQ(0.0, partials[j]); } } } }; // namespace } // namespace rendering } // namespace systems } // namespace drake
/** * @author : archit * @GitHub : archit-1997 * @email : architsingh456@gmail.com * @file : meregeIntervals.cpp * @created : Monday Jul 26, 2021 04:51:09 IST */ #include <bits/stdc++.h> using namespace std; bool compare(const vector<int> &a,const vector<int> &b){ if(a[0]==b[0]) return a[1]<b[1]; return a[0]<b[0]; } class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { int n=intervals.size(); sort(intervals.begin(),intervals.end(),compare); int start=intervals[0][0],end=intervals[0][1]; vector<vector<int>> ans; for(int i=1;i<n;i++){ if(intervals[i][0]<=end){ end=max(end,intervals[i][1]); } else{ ans.push_back({start,end}); start=intervals[i][0],end=intervals[i][1]; } } ans.push_back({start,end}); return ans; } };
// Copyright (c) 2012 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. #include "chrome/common/service_process_util.h" #include "base/basictypes.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/process/kill.h" #include "base/process/launch.h" #if !defined(OS_MACOSX) #include "base/at_exit.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/multiprocess_test.h" #include "base/test/test_timeouts.h" #include "base/threading/thread.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "testing/multiprocess_func_list.h" #if defined(OS_WIN) #include "base/win/win_util.h" #endif #if defined(OS_POSIX) #include <glib.h> #include "chrome/common/auto_start_linux.h" #endif #if defined(USE_AURA) // This test fails http://crbug.com/84854, and is very flaky on CrOS and // somewhat flaky on other Linux. #define MAYBE_ForceShutdown DISABLED_ForceShutdown #else #if defined(OS_LINUX) || defined(OS_WIN) #define MAYBE_ForceShutdown DISABLED_ForceShutdown #else #define MAYBE_ForceShutdown ForceShutdown #endif #endif namespace { bool g_good_shutdown = false; void ShutdownTask(base::MessageLoop* loop) { // Quit the main message loop. ASSERT_FALSE(g_good_shutdown); g_good_shutdown = true; loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure()); } } // namespace TEST(ServiceProcessUtilTest, ScopedVersionedName) { std::string test_str = "test"; std::string scoped_name = GetServiceProcessScopedVersionedName(test_str); chrome::VersionInfo version_info; DCHECK(version_info.is_valid()); EXPECT_TRUE(EndsWith(scoped_name, test_str, true)); EXPECT_NE(std::string::npos, scoped_name.find(version_info.Version())); } class ServiceProcessStateTest : public base::MultiProcessTest { public: ServiceProcessStateTest(); virtual ~ServiceProcessStateTest(); virtual void SetUp(); base::MessageLoopProxy* IOMessageLoopProxy() { return io_thread_.message_loop_proxy().get(); } void LaunchAndWait(const std::string& name); private: // This is used to release the ServiceProcessState singleton after each test. base::ShadowingAtExitManager at_exit_manager_; base::Thread io_thread_; }; ServiceProcessStateTest::ServiceProcessStateTest() : io_thread_("ServiceProcessStateTestThread") { } ServiceProcessStateTest::~ServiceProcessStateTest() { } void ServiceProcessStateTest::SetUp() { base::Thread::Options options(base::MessageLoop::TYPE_IO, 0); ASSERT_TRUE(io_thread_.StartWithOptions(options)); } void ServiceProcessStateTest::LaunchAndWait(const std::string& name) { base::ProcessHandle handle = SpawnChild(name, false); ASSERT_TRUE(handle); int exit_code = 0; ASSERT_TRUE(base::WaitForExitCode(handle, &exit_code)); ASSERT_EQ(exit_code, 0); } TEST_F(ServiceProcessStateTest, Singleton) { ServiceProcessState state; ASSERT_TRUE(state.Initialize()); LaunchAndWait("ServiceProcessStateTestSingleton"); } TEST_F(ServiceProcessStateTest, ReadyState) { ASSERT_FALSE(CheckServiceProcessReady()); ServiceProcessState state; ASSERT_TRUE(state.Initialize()); ASSERT_TRUE(state.SignalReady(IOMessageLoopProxy(), base::Closure())); LaunchAndWait("ServiceProcessStateTestReadyTrue"); state.SignalStopped(); LaunchAndWait("ServiceProcessStateTestReadyFalse"); } TEST_F(ServiceProcessStateTest, AutoRun) { ServiceProcessState state; ASSERT_TRUE(state.AddToAutoRun()); scoped_ptr<CommandLine> autorun_command_line; #if defined(OS_WIN) std::string value_name = GetServiceProcessScopedName("_service_run"); base::string16 value; EXPECT_TRUE(base::win::ReadCommandFromAutoRun(HKEY_CURRENT_USER, UTF8ToWide(value_name), &value)); autorun_command_line.reset(new CommandLine(CommandLine::FromString(value))); #elif defined(OS_POSIX) && !defined(OS_MACOSX) #if defined(GOOGLE_CHROME_BUILD) std::string base_desktop_name = "google-chrome-service.desktop"; #else // CHROMIUM_BUILD std::string base_desktop_name = "chromium-service.desktop"; #endif std::string exec_value; EXPECT_TRUE(AutoStart::GetAutostartFileValue( GetServiceProcessScopedName(base_desktop_name), "Exec", &exec_value)); GError *error = NULL; gchar **argv = NULL; gint argc = 0; if (g_shell_parse_argv(exec_value.c_str(), &argc, &argv, &error)) { autorun_command_line.reset(new CommandLine(argc, argv)); g_strfreev(argv); } else { ADD_FAILURE(); g_error_free(error); } #endif // defined(OS_WIN) if (autorun_command_line.get()) { EXPECT_EQ(autorun_command_line->GetSwitchValueASCII(switches::kProcessType), std::string(switches::kServiceProcess)); } ASSERT_TRUE(state.RemoveFromAutoRun()); #if defined(OS_WIN) EXPECT_FALSE(base::win::ReadCommandFromAutoRun(HKEY_CURRENT_USER, UTF8ToWide(value_name), &value)); #elif defined(OS_POSIX) && !defined(OS_MACOSX) EXPECT_FALSE(AutoStart::GetAutostartFileValue( GetServiceProcessScopedName(base_desktop_name), "Exec", &exec_value)); #endif // defined(OS_WIN) } TEST_F(ServiceProcessStateTest, SharedMem) { std::string version; base::ProcessId pid; #if defined(OS_WIN) // On Posix, named shared memory uses a file on disk. This file // could be lying around from previous crashes which could cause // GetServiceProcessPid to lie. On Windows, we use a named event so we // don't have this issue. Until we have a more stable shared memory // implementation on Posix, this check will only execute on Windows. ASSERT_FALSE(GetServiceProcessData(&version, &pid)); #endif // defined(OS_WIN) ServiceProcessState state; ASSERT_TRUE(state.Initialize()); ASSERT_TRUE(GetServiceProcessData(&version, &pid)); ASSERT_EQ(base::GetCurrentProcId(), pid); } TEST_F(ServiceProcessStateTest, MAYBE_ForceShutdown) { base::ProcessHandle handle = SpawnChild("ServiceProcessStateTestShutdown", true); ASSERT_TRUE(handle); for (int i = 0; !CheckServiceProcessReady() && i < 10; ++i) { base::PlatformThread::Sleep(TestTimeouts::tiny_timeout()); } ASSERT_TRUE(CheckServiceProcessReady()); std::string version; base::ProcessId pid; ASSERT_TRUE(GetServiceProcessData(&version, &pid)); ASSERT_TRUE(ForceServiceProcessShutdown(version, pid)); int exit_code = 0; ASSERT_TRUE(base::WaitForExitCodeWithTimeout(handle, &exit_code, TestTimeouts::action_max_timeout())); base::CloseProcessHandle(handle); ASSERT_EQ(exit_code, 0); } MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestSingleton) { ServiceProcessState state; EXPECT_FALSE(state.Initialize()); return 0; } MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestReadyTrue) { EXPECT_TRUE(CheckServiceProcessReady()); return 0; } MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestReadyFalse) { EXPECT_FALSE(CheckServiceProcessReady()); return 0; } MULTIPROCESS_TEST_MAIN(ServiceProcessStateTestShutdown) { base::MessageLoop message_loop; message_loop.set_thread_name("ServiceProcessStateTestShutdownMainThread"); base::Thread io_thread_("ServiceProcessStateTestShutdownIOThread"); base::Thread::Options options(base::MessageLoop::TYPE_IO, 0); EXPECT_TRUE(io_thread_.StartWithOptions(options)); ServiceProcessState state; EXPECT_TRUE(state.Initialize()); EXPECT_TRUE(state.SignalReady( io_thread_.message_loop_proxy().get(), base::Bind(&ShutdownTask, base::MessageLoop::current()))); message_loop.PostDelayedTask(FROM_HERE, base::MessageLoop::QuitClosure(), TestTimeouts::action_max_timeout()); EXPECT_FALSE(g_good_shutdown); message_loop.Run(); EXPECT_TRUE(g_good_shutdown); return 0; } #else // !OS_MACOSX #include <CoreFoundation/CoreFoundation.h> #include "base/file_util.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/mac/mac_util.h" #include "base/test/test_timeouts.h" #include "base/threading/thread.h" #include "chrome/common/mac/launchd.h" #include "chrome/common/mac/mock_launchd.h" #include "testing/gtest/include/gtest/gtest.h" class ServiceProcessStateFileManipulationTest : public ::testing::Test { protected: ServiceProcessStateFileManipulationTest() : io_thread_("ServiceProcessStateFileManipulationTest_IO") { } virtual ~ServiceProcessStateFileManipulationTest() { } virtual void SetUp() { base::Thread::Options options; options.message_loop_type = base::MessageLoop::TYPE_IO; ASSERT_TRUE(io_thread_.StartWithOptions(options)); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(MockLaunchd::MakeABundle(GetTempDirPath(), "Test", &bundle_path_, &executable_path_)); mock_launchd_.reset(new MockLaunchd(executable_path_, &loop_, false, false)); scoped_launchd_instance_.reset( new Launchd::ScopedInstance(mock_launchd_.get())); ASSERT_TRUE(service_process_state_.Initialize()); ASSERT_TRUE(service_process_state_.SignalReady( io_thread_.message_loop_proxy().get(), base::Closure())); loop_.PostDelayedTask(FROM_HERE, base::MessageLoop::QuitClosure(), TestTimeouts::action_max_timeout()); } const MockLaunchd* mock_launchd() const { return mock_launchd_.get(); } const base::FilePath& executable_path() const { return executable_path_; } const base::FilePath& bundle_path() const { return bundle_path_; } const base::FilePath& GetTempDirPath() const { return temp_dir_.path(); } base::MessageLoopProxy* GetIOMessageLoopProxy() { return io_thread_.message_loop_proxy().get(); } void Run() { loop_.Run(); } private: base::ScopedTempDir temp_dir_; base::MessageLoopForUI loop_; base::Thread io_thread_; base::FilePath executable_path_, bundle_path_; scoped_ptr<MockLaunchd> mock_launchd_; scoped_ptr<Launchd::ScopedInstance> scoped_launchd_instance_; ServiceProcessState service_process_state_; }; void DeleteFunc(const base::FilePath& file) { EXPECT_TRUE(base::DeleteFile(file, true)); } void MoveFunc(const base::FilePath& from, const base::FilePath& to) { EXPECT_TRUE(base::Move(from, to)); } void ChangeAttr(const base::FilePath& from, int mode) { EXPECT_EQ(chmod(from.value().c_str(), mode), 0); } class ScopedAttributesRestorer { public: ScopedAttributesRestorer(const base::FilePath& path, int mode) : path_(path), mode_(mode) { } ~ScopedAttributesRestorer() { ChangeAttr(path_, mode_); } private: base::FilePath path_; int mode_; }; void TrashFunc(const base::FilePath& src) { FSRef path_ref; FSRef new_path_ref; EXPECT_TRUE(base::mac::FSRefFromPath(src.value(), &path_ref)); OSStatus status = FSMoveObjectToTrashSync(&path_ref, &new_path_ref, kFSFileOperationDefaultOptions); EXPECT_EQ(status, noErr) << "FSMoveObjectToTrashSync " << status; } TEST_F(ServiceProcessStateFileManipulationTest, VerifyLaunchD) { // There have been problems where launchd has gotten into a bad state, usually // because something had deleted all the files in /tmp. launchd depends on // a Unix Domain Socket that it creates at /tmp/launchd*/sock. // The symptom of this problem is that the service process connect fails // on Mac and "launch_msg(): Socket is not connected" appears. // This test is designed to make sure that launchd is working. // http://crbug/75518 CommandLine cl(base::FilePath("/bin/launchctl")); cl.AppendArg("list"); cl.AppendArg("com.apple.launchctl.Aqua"); std::string output; int exit_code = -1; ASSERT_TRUE(base::GetAppOutputWithExitCode(cl, &output, &exit_code) && exit_code == 0) << " exit_code:" << exit_code << " " << output; } TEST_F(ServiceProcessStateFileManipulationTest, DeleteFile) { GetIOMessageLoopProxy()->PostTask( FROM_HERE, base::Bind(&DeleteFunc, executable_path())); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); } TEST_F(ServiceProcessStateFileManipulationTest, DeleteBundle) { GetIOMessageLoopProxy()->PostTask( FROM_HERE, base::Bind(&DeleteFunc, bundle_path())); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); } TEST_F(ServiceProcessStateFileManipulationTest, MoveBundle) { base::FilePath new_loc = GetTempDirPath().AppendASCII("MoveBundle"); GetIOMessageLoopProxy()->PostTask( FROM_HERE, base::Bind(&MoveFunc, bundle_path(), new_loc)); Run(); ASSERT_TRUE(mock_launchd()->restart_called()); ASSERT_TRUE(mock_launchd()->write_called()); } TEST_F(ServiceProcessStateFileManipulationTest, MoveFile) { base::FilePath new_loc = GetTempDirPath().AppendASCII("MoveFile"); GetIOMessageLoopProxy()->PostTask( FROM_HERE, base::Bind(&MoveFunc, executable_path(), new_loc)); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); } TEST_F(ServiceProcessStateFileManipulationTest, TrashBundle) { FSRef bundle_ref; ASSERT_TRUE(base::mac::FSRefFromPath(bundle_path().value(), &bundle_ref)); GetIOMessageLoopProxy()->PostTask( FROM_HERE, base::Bind(&TrashFunc, bundle_path())); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); std::string path(base::mac::PathFromFSRef(bundle_ref)); base::FilePath file_path(path); ASSERT_TRUE(base::DeleteFile(file_path, true)); } TEST_F(ServiceProcessStateFileManipulationTest, ChangeAttr) { ScopedAttributesRestorer restorer(bundle_path(), 0777); GetIOMessageLoopProxy()->PostTask( FROM_HERE, base::Bind(&ChangeAttr, bundle_path(), 0222)); Run(); ASSERT_TRUE(mock_launchd()->remove_called()); ASSERT_TRUE(mock_launchd()->delete_called()); } #endif // !OS_MACOSX
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Tencent is pleased to support the open source community by making WeChat QRCode available. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Modified from ZXing. Copyright ZXing authors. // Licensed under the Apache License, Version 2.0 (the "License"). #ifndef __ZXING_EXCEPTION_HPP__ #define __ZXING_EXCEPTION_HPP__ #include <exception> #include <string> namespace zxing { class Exception : public std::exception { private: char const* const message; public: Exception() throw() : message(0) {} explicit Exception(const char* msg) throw() : message(copy(msg)) {} Exception(Exception const& that) throw() : std::exception(that), message(copy(that.message)) {} ~Exception() throw() { if (message) { deleteMessage(); } } char const* what() const throw() override { return message ? message : ""; } private: static char const* copy(char const*); void deleteMessage(); }; } // namespace zxing #endif // __ZXING_EXCEPTION_HPP__
/* Copyright 2019 Intel Corporation * * 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. */ #include <malloc.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include "Dispatch.h" #include "Cryptography.h" #include "Environment.h" #include "KeyValue.h" #include "Message.h" #include "Response.h" #include "StringArray.h" #include "Value.h" #include "WasmExtensions.h" static KeyValueStore meta_store("meta"); static KeyValueStore value_store("values"); static KeyValueStore owner_store("owners"); const StringArray owner_key("owner"); const StringArray signing_key("ecdsa-private-key"); const StringArray verifying_key("ecdsa-public-key"); const StringArray symmetric_key("aes-encryption-key"); const StringArray public_encrypt_key("rsa-public-key"); const StringArray private_decrypt_key("rsa-private-key"); const StringArray kv_test_key("test"); const StringArray kv_hash_id("kv-store-hash-id"); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // NAME: initialize // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX bool initialize_contract(const Environment& env, Response& rsp) { // ---------- Save owner information ---------- const StringArray owner_val(env.creator_id_); if (! meta_store.set(owner_key, owner_val)) return rsp.error("failed to save creator metadata"); // ---------- Create and save the ECDSA key pair ---------- StringArray public_key; StringArray private_key; if (! ww::crypto::ecdsa::generate_keys(private_key, public_key)) return rsp.error("failed to create contract ecdsa keys"); if (! meta_store.set(verifying_key, public_key)) return rsp.error("failed to save ecdsa public key"); if (! meta_store.set(signing_key, private_key)) return rsp.error("failed to save ecdsa private key"); // ---------- Create and save the AES key ---------- StringArray aes_key; if (! ww::crypto::aes::generate_key(aes_key)) return rsp.error("failed to create the AES key"); if (! meta_store.set(symmetric_key, aes_key)) return rsp.error("failed to save the AES key"); // ---------- Create and save the RSA key pair ---------- StringArray rsa_private_key; StringArray rsa_public_key; if (! ww::crypto::rsa::generate_keys(rsa_private_key, rsa_public_key)) return rsp.error("failed to create rsa keys"); if (! meta_store.set(public_encrypt_key, rsa_public_key)) return rsp.error("failed to save rsa public key"); if (! meta_store.set(private_decrypt_key, rsa_private_key)) return rsp.error("failed to save rsa private key"); // ---------- Create the return value ---------- return rsp.success(true); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // NAME: ecdsa_test // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX bool ecdsa_test(const Message& msg, const Environment& env, Response& rsp) { const StringArray message(msg.get_string("message")); // ---------- get the keys we need ---------- StringArray private_key; if (! meta_store.get(signing_key, private_key)) return rsp.error("failed to find private key"); StringArray public_key; if (! meta_store.get(verifying_key, public_key)) return rsp.error("failed to find public key"); // ---------- sign the message ---------- StringArray signature; if (! ww::crypto::ecdsa::sign_message(message, private_key, signature)) return rsp.error("failed to sign message"); if (! ww::crypto::ecdsa::verify_signature(message, public_key, signature)) return rsp.error("failed to verify the signature"); // ---------- return the signature ---------- StringArray encoded; if (! ww::crypto::b64_encode(signature, encoded)) return rsp.error("failed to encode signature"); ww::value::String v((char*)encoded.c_data()); return rsp.value(v, false); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // NAME: aes_test // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX bool aes_test(const Message& msg, const Environment& env, Response& rsp) { const StringArray message(msg.get_string("message")); // ---------- get the keys we need ---------- StringArray key; if (! meta_store.get(symmetric_key, key)) return rsp.error("failed to find private key"); StringArray encoded_key; if (! ww::crypto::b64_encode(key, encoded_key)) return rsp.error("failed to encode the aes key"); StringArray iv; if (! ww::crypto::aes::generate_iv(iv)) return rsp.error("failed to generate iv"); // ---------- encrypt the message ---------- StringArray cipher; if (! ww::crypto::aes::encrypt_message(message, key, iv, cipher)) return rsp.error("failed to encrypt the message"); // ---------- decrypt the message ---------- StringArray newmessage; if (! ww::crypto::aes::decrypt_message(cipher, key, iv, newmessage)) return rsp.error("failed to decrypt the message"); if (! message.equal(newmessage)) return rsp.error("decrypted message differs from original message"); // ---------- return the signature ---------- StringArray encoded; if (! ww::crypto::b64_encode(cipher, encoded)) return rsp.error("failed to encode cipher text"); ww::value::String v((char*)encoded.c_data()); return rsp.value(v, false); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // NAME: rsa_test // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX bool rsa_test(const Message& msg, const Environment& env, Response& rsp) { // ---------- get the keys we need ---------- StringArray rsa_public; if (! meta_store.get(public_encrypt_key, rsa_public)) return rsp.error("failed to find rsa public key"); StringArray rsa_private; if (! meta_store.get(private_decrypt_key, rsa_private)) return rsp.error("failed to find rsa private key"); StringArray aes_key; if (! meta_store.get(symmetric_key, aes_key)) return rsp.error("failed to find aes key"); // ---------- encrypt the aes key ---------- StringArray cipher; if (! ww::crypto::rsa::encrypt_message(aes_key, rsa_public, cipher)) return rsp.error("failed to encrypt the key"); // ---------- decrypt the message ---------- StringArray new_aes_key; if (! ww::crypto::rsa::decrypt_message(cipher, rsa_private, new_aes_key)) return rsp.error("failed to decrypt the key"); if (! aes_key.equal(new_aes_key)) return rsp.error("decrypted key differs from the original key"); // ---------- return the signature ---------- StringArray encoded; if (! ww::crypto::b64_encode(cipher, encoded)) return rsp.error("failed to encode cipher text"); ww::value::String v((char*)encoded.c_data()); return rsp.value(v, false); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // kv store test // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX bool kv_test_set(const Message& msg, const Environment& env, Response& rsp) { StringArray aes_key; if (! meta_store.get(symmetric_key, aes_key)) return rsp.error("failed to find aes key"); int handle = KeyValueStore::create(aes_key); if (handle < 0) return rsp.error("failed to create the key value store"); KeyValueStore temp_store("temp", handle); uint32_t value = 1; if (! temp_store.set(kv_test_key, value)) return rsp.error("failed to save the value"); StringArray block_id; if (! KeyValueStore::finalize(handle, block_id)) return rsp.error("failed to finalize block store"); if (! meta_store.set(kv_hash_id, block_id)) return rsp.error("failed to save the new block identifier"); return rsp.success(true); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // kv store test // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX bool kv_test_get(const Message& msg, const Environment& env, Response& rsp) { StringArray aes_key; if (! meta_store.get(symmetric_key, aes_key)) return rsp.error("failed to find aes key"); StringArray block_id; if (! meta_store.get(kv_hash_id, block_id)) return rsp.error("failed to find the new block identifier"); int handle = KeyValueStore::open(block_id, aes_key); if (handle < 0) return rsp.error("failed to create the key value store"); KeyValueStore temp_store("temp", handle); uint32_t value; if (! temp_store.get(kv_test_key, value)) return rsp.error("failed to retrieve the value"); if (value != 1) return rsp.error("failed to get the correct value"); if (! KeyValueStore::finalize(handle, block_id)) return rsp.error("failed to finalize block store"); ww::value::Number v((double)value); return rsp.value(v, false); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX contract_method_reference_t contract_method_dispatch_table[] = { CONTRACT_METHOD(ecdsa_test), CONTRACT_METHOD(aes_test), CONTRACT_METHOD(rsa_test), CONTRACT_METHOD(kv_test_set), CONTRACT_METHOD(kv_test_get), { NULL, NULL } };
//===- DWARFDebugAddr.cpp -------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h" #include "llvm/BinaryFormat/Dwarf.h" #include "llvm/DebugInfo/DWARF/DWARFUnit.h" using namespace llvm; void DWARFDebugAddrTable::clear() { HeaderData = {}; Addrs.clear(); invalidateLength(); } Error DWARFDebugAddrTable::extract(DWARFDataExtractor Data, uint64_t *OffsetPtr, uint16_t Version, uint8_t AddrSize, std::function<void(Error)> WarnCallback) { clear(); HeaderOffset = *OffsetPtr; // Read and verify the length field. if (!Data.isValidOffsetForDataOfSize(*OffsetPtr, sizeof(uint32_t))) return createStringError(errc::invalid_argument, "section is not large enough to contain a " ".debug_addr table length at offset 0x%" PRIx64, *OffsetPtr); uint16_t UnitVersion; if (Version == 0) { WarnCallback(createStringError(errc::invalid_argument, "DWARF version is not defined in CU," " assuming version 5")); UnitVersion = 5; } else { UnitVersion = Version; } // TODO: Add support for DWARF64. Format = dwarf::DwarfFormat::DWARF32; if (UnitVersion >= 5) { HeaderData.Length = Data.getU32(OffsetPtr); if (HeaderData.Length == dwarf::DW_LENGTH_DWARF64) { invalidateLength(); return createStringError(errc::not_supported, "DWARF64 is not supported in .debug_addr at offset 0x%" PRIx64, HeaderOffset); } if (HeaderData.Length + sizeof(uint32_t) < sizeof(Header)) { uint32_t TmpLength = getLength(); invalidateLength(); return createStringError(errc::invalid_argument, ".debug_addr table at offset 0x%" PRIx64 " has too small length (0x%" PRIx32 ") to contain a complete header", HeaderOffset, TmpLength); } uint64_t End = HeaderOffset + getLength(); if (!Data.isValidOffsetForDataOfSize(HeaderOffset, End - HeaderOffset)) { uint32_t TmpLength = getLength(); invalidateLength(); return createStringError(errc::invalid_argument, "section is not large enough to contain a .debug_addr table " "of length 0x%" PRIx32 " at offset 0x%" PRIx64, TmpLength, HeaderOffset); } HeaderData.Version = Data.getU16(OffsetPtr); HeaderData.AddrSize = Data.getU8(OffsetPtr); HeaderData.SegSize = Data.getU8(OffsetPtr); DataSize = getDataSize(); } else { HeaderData.Version = UnitVersion; HeaderData.AddrSize = AddrSize; // TODO: Support for non-zero SegSize. HeaderData.SegSize = 0; DataSize = Data.size(); } // Perform basic validation of the remaining header fields. // We support DWARF version 5 for now as well as pre-DWARF5 // implementations of .debug_addr table, which doesn't contain a header // and consists only of a series of addresses. if (HeaderData.Version > 5) { return createStringError(errc::not_supported, "version %" PRIu16 " of .debug_addr section at offset 0x%" PRIx64 " is not supported", HeaderData.Version, HeaderOffset); } // FIXME: For now we just treat version mismatch as an error, // however the correct way to associate a .debug_addr table // with a .debug_info table is to look at the DW_AT_addr_base // attribute in the info table. if (HeaderData.Version != UnitVersion) return createStringError(errc::invalid_argument, ".debug_addr table at offset 0x%" PRIx64 " has version %" PRIu16 " which is different from the version suggested" " by the DWARF unit header: %" PRIu16, HeaderOffset, HeaderData.Version, UnitVersion); if (HeaderData.AddrSize != 4 && HeaderData.AddrSize != 8) return createStringError(errc::not_supported, ".debug_addr table at offset 0x%" PRIx64 " has unsupported address size %" PRIu8, HeaderOffset, HeaderData.AddrSize); if (HeaderData.AddrSize != AddrSize && AddrSize != 0) return createStringError(errc::invalid_argument, ".debug_addr table at offset 0x%" PRIx64 " has address size %" PRIu8 " which is different from CU address size %" PRIu8, HeaderOffset, HeaderData.AddrSize, AddrSize); // TODO: add support for non-zero segment selector size. if (HeaderData.SegSize != 0) return createStringError(errc::not_supported, ".debug_addr table at offset 0x%" PRIx64 " has unsupported segment selector size %" PRIu8, HeaderOffset, HeaderData.SegSize); if (DataSize % HeaderData.AddrSize != 0) { invalidateLength(); return createStringError(errc::invalid_argument, ".debug_addr table at offset 0x%" PRIx64 " contains data of size %" PRIu32 " which is not a multiple of addr size %" PRIu8, HeaderOffset, DataSize, HeaderData.AddrSize); } Data.setAddressSize(HeaderData.AddrSize); uint32_t AddrCount = DataSize / HeaderData.AddrSize; for (uint32_t I = 0; I < AddrCount; ++I) if (HeaderData.AddrSize == 4) Addrs.push_back(Data.getU32(OffsetPtr)); else Addrs.push_back(Data.getU64(OffsetPtr)); return Error::success(); } void DWARFDebugAddrTable::dump(raw_ostream &OS, DIDumpOptions DumpOpts) const { if (DumpOpts.Verbose) OS << format("0x%8.8" PRIx32 ": ", HeaderOffset); OS << format("Addr Section: length = 0x%8.8" PRIx32 ", version = 0x%4.4" PRIx16 ", " "addr_size = 0x%2.2" PRIx8 ", seg_size = 0x%2.2" PRIx8 "\n", HeaderData.Length, HeaderData.Version, HeaderData.AddrSize, HeaderData.SegSize); if (Addrs.size() > 0) { const char *AddrFmt = (HeaderData.AddrSize == 4) ? "0x%8.8" PRIx64 "\n" : "0x%16.16" PRIx64 "\n"; OS << "Addrs: [\n"; for (uint64_t Addr : Addrs) OS << format(AddrFmt, Addr); OS << "]\n"; } } Expected<uint64_t> DWARFDebugAddrTable::getAddrEntry(uint32_t Index) const { if (Index < Addrs.size()) return Addrs[Index]; return createStringError(errc::invalid_argument, "Index %" PRIu32 " is out of range of the " ".debug_addr table at offset 0x%" PRIx64, Index, HeaderOffset); } uint32_t DWARFDebugAddrTable::getLength() const { if (HeaderData.Length == 0) return 0; // TODO: DWARF64 support. return HeaderData.Length + sizeof(uint32_t); } uint32_t DWARFDebugAddrTable::getDataSize() const { if (DataSize != 0) return DataSize; if (getLength() == 0) return 0; return getLength() - getHeaderSize(); }
// Copyright 2020 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. #include "content/browser/prerender/prerender_host.h" #include "base/test/scoped_feature_list.h" #include "content/browser/prerender/prerender_host_registry.h" #include "content/browser/site_instance_impl.h" #include "content/public/test/navigation_simulator.h" #include "content/public/test/test_browser_context.h" #include "content/test/navigation_simulator_impl.h" #include "content/test/test_render_frame_host.h" #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" #include "third_party/blink/public/common/features.h" namespace content { namespace { // Finish a prerendering navigation that was already started with // CreateAndStartHost(). void CommitPrerenderNavigation(PrerenderHost& host) { // Normally we could use EmbeddedTestServer to provide a response, but these // tests use RenderViewHostImplTestHarness so the load goes through a // TestNavigationURLLoader which we don't have access to in order to // complete. Use NavigationSimulator to finish the navigation. FrameTreeNode* ftn = FrameTreeNode::From(host.GetPrerenderedMainFrameHost()); std::unique_ptr<NavigationSimulator> sim = NavigationSimulatorImpl::CreateFromPendingInFrame(ftn); sim->ReadyToCommit(); sim->Commit(); EXPECT_TRUE(host.is_ready_for_activation()); } class TestWebContentsDelegate : public WebContentsDelegate { public: TestWebContentsDelegate() = default; ~TestWebContentsDelegate() override = default; }; class PrerenderHostTest : public RenderViewHostImplTestHarness { public: PrerenderHostTest() { scoped_feature_list_.InitAndEnableFeature(blink::features::kPrerender2); } ~PrerenderHostTest() override = default; void SetUp() override { RenderViewHostImplTestHarness::SetUp(); browser_context_ = std::make_unique<TestBrowserContext>(); } void TearDown() override { browser_context_.reset(); RenderViewHostImplTestHarness::TearDown(); } void ExpectFinalStatus(PrerenderHost::FinalStatus status) { histogram_tester_.ExpectUniqueSample( "Prerender.Experimental.PrerenderHostFinalStatus", status, 1); } std::unique_ptr<TestWebContents> CreateWebContents(const GURL& url) { std::unique_ptr<TestWebContents> web_contents(TestWebContents::Create( browser_context_.get(), SiteInstanceImpl::Create(browser_context_.get()))); web_contents_delegate_ = std::make_unique<TestWebContentsDelegate>(); web_contents->SetDelegate(web_contents_delegate_.get()); web_contents->NavigateAndCommit(url); return web_contents; } private: base::test::ScopedFeatureList scoped_feature_list_; std::unique_ptr<TestBrowserContext> browser_context_; std::unique_ptr<TestWebContentsDelegate> web_contents_delegate_; base::HistogramTester histogram_tester_; }; TEST_F(PrerenderHostTest, Activate) { std::unique_ptr<TestWebContents> web_contents = CreateWebContents(GURL("https://example.com/")); RenderFrameHostImpl* initiator_rfh = web_contents->GetMainFrame(); PrerenderHostRegistry* registry = web_contents->GetPrerenderHostRegistry(); // Start prerendering a page. const GURL kPrerenderingUrl("https://example.com/next"); auto attributes = blink::mojom::PrerenderAttributes::New(); attributes->url = kPrerenderingUrl; const int prerender_frame_tree_node_id = registry->CreateAndStartHost(std::move(attributes), *initiator_rfh); PrerenderHost* prerender_host = registry->FindNonReservedHostById(prerender_frame_tree_node_id); CommitPrerenderNavigation(*prerender_host); // Perform a navigation in the primary frame tree which activates the // prerendered page. auto sim_2 = NavigationSimulatorImpl::CreateBrowserInitiated( kPrerenderingUrl, web_contents.get()); sim_2->Start(); sim_2->Commit(); ExpectFinalStatus(PrerenderHost::FinalStatus::kActivated); } TEST_F(PrerenderHostTest, DontActivate) { std::unique_ptr<TestWebContents> web_contents = CreateWebContents(GURL("https://example.com/")); RenderFrameHostImpl* initiator_rfh = web_contents->GetMainFrame(); PrerenderHostRegistry* registry = web_contents->GetPrerenderHostRegistry(); const GURL kPrerenderingUrl("https://example.com/next"); auto attributes = blink::mojom::PrerenderAttributes::New(); attributes->url = kPrerenderingUrl; // Start the prerendering navigation, but don't activate it. const int prerender_frame_tree_node_id = registry->CreateAndStartHost(std::move(attributes), *initiator_rfh); registry->CancelHost(prerender_frame_tree_node_id, PrerenderHost::FinalStatus::kDestroyed); ExpectFinalStatus(PrerenderHost::FinalStatus::kDestroyed); } // Tests that main frame navigations in a prerendered page can occur if they // start after the prerendered page has been reserved for activation. // // Regression test for https://crbug.com/1190262. TEST_F(PrerenderHostTest, MainFrameNavigationForReservedHost) { std::unique_ptr<TestWebContents> web_contents = CreateWebContents(GURL("https://example.com/")); RenderFrameHostImpl* initiator_rfh = web_contents->GetMainFrame(); PrerenderHostRegistry* registry = web_contents->GetPrerenderHostRegistry(); // Start prerendering a page. const GURL kPrerenderingUrl("https://example.com/next"); auto attributes = blink::mojom::PrerenderAttributes::New(); attributes->url = kPrerenderingUrl; const int prerender_ftn_id = registry->CreateAndStartHost(std::move(attributes), *initiator_rfh); PrerenderHost* prerender_host = registry->FindNonReservedHostById(prerender_ftn_id); CommitPrerenderNavigation(*prerender_host); std::unique_ptr<NavigationSimulatorImpl> navigation = NavigationSimulatorImpl::CreateRendererInitiated(kPrerenderingUrl, initiator_rfh); navigation->Start(); NavigationRequest* navigation_request = static_cast<NavigationRequest*>(navigation->GetNavigationHandle()); EXPECT_EQ(navigation_request->prerender_frame_tree_node_id(), prerender_ftn_id); // Start a cross-origin navigation in the prerendered page. It should not // be deferred. // TODO(https://crbug.com/1198395): Defer or cancel in this case, which will // change this expectation. RenderFrameHostImpl* prerender_rfh = prerender_host->GetPrerenderedMainFrameHost(); auto navigation_2 = NavigationSimulatorImpl::CreateRendererInitiated( GURL("https://example2.test/"), prerender_rfh); navigation_2->Start(); EXPECT_FALSE(navigation_2->IsDeferred()); navigation_2->Commit(); // Activate the prerendered page. prerender_host->Activate(*navigation->GetNavigationHandle()); ExpectFinalStatus(PrerenderHost::FinalStatus::kActivated); } // Tests that cross-origin subframe navigations in a prerendered page are // deferred even if they start after the prerendered page has been reserved for // activation. // // Regression test for https://crbug.com/1190262. TEST_F(PrerenderHostTest, SubframeNavigationForReservedHost) { std::unique_ptr<TestWebContents> web_contents = CreateWebContents(GURL("https://example.com/")); RenderFrameHostImpl* initiator_rfh = web_contents->GetMainFrame(); PrerenderHostRegistry* registry = web_contents->GetPrerenderHostRegistry(); // Start prerendering a page. const GURL kPrerenderingUrl("https://example.com/next"); auto attributes = blink::mojom::PrerenderAttributes::New(); attributes->url = kPrerenderingUrl; const int prerender_ftn_id = registry->CreateAndStartHost(std::move(attributes), *initiator_rfh); PrerenderHost* prerender_host = registry->FindNonReservedHostById(prerender_ftn_id); CommitPrerenderNavigation(*prerender_host); std::unique_ptr<NavigationSimulatorImpl> navigation = NavigationSimulatorImpl::CreateRendererInitiated(kPrerenderingUrl, initiator_rfh); navigation->Start(); NavigationRequest* navigation_request = static_cast<NavigationRequest*>(navigation->GetNavigationHandle()); EXPECT_EQ(navigation_request->prerender_frame_tree_node_id(), prerender_ftn_id); // Start a cross-origin subframe navigation in the prerendered page. It // should be deferred. RenderFrameHostImpl* prerender_rfh = prerender_host->GetPrerenderedMainFrameHost(); RenderFrameHost* subframe = RenderFrameHostTester::For(prerender_rfh)->AppendChild("subframe"); std::unique_ptr<NavigationSimulatorImpl> subframe_nav_sim = NavigationSimulatorImpl::CreateRendererInitiated( GURL("https://example2.test/"), subframe); subframe_nav_sim->SetAutoAdvance(false); subframe_nav_sim->Start(); EXPECT_TRUE(subframe_nav_sim->IsDeferred()); // Activate the prerendered page. prerender_host->Activate(*navigation->GetNavigationHandle()); ExpectFinalStatus(PrerenderHost::FinalStatus::kActivated); // The subframe navigation should no longer be deferred. subframe_nav_sim->Wait(); EXPECT_FALSE(subframe_nav_sim->IsDeferred()); } // Tests that an activation can successfully commit after the prerendering page // has updated its PageState. TEST_F(PrerenderHostTest, ActivationAfterPageStateUpdate) { std::unique_ptr<TestWebContents> web_contents = CreateWebContents(GURL("https://example.com/")); RenderFrameHostImpl* initiator_rfh = web_contents->GetMainFrame(); PrerenderHostRegistry* registry = web_contents->GetPrerenderHostRegistry(); // Start prerendering a page. const GURL kPrerenderingUrl("https://example.com/next"); auto attributes = blink::mojom::PrerenderAttributes::New(); attributes->url = kPrerenderingUrl; const int prerender_frame_tree_node_id = registry->CreateAndStartHost(std::move(attributes), *initiator_rfh); PrerenderHost* prerender_host = registry->FindNonReservedHostById(prerender_frame_tree_node_id); CommitPrerenderNavigation(*prerender_host); FrameTreeNode* prerender_root_ftn = FrameTreeNode::GloballyFindByID(prerender_frame_tree_node_id); RenderFrameHostImpl* prerender_rfh = prerender_root_ftn->current_frame_host(); NavigationEntryImpl* prerender_nav_entry = prerender_root_ftn->frame_tree()->controller().GetLastCommittedEntry(); FrameNavigationEntry* prerender_root_fne = prerender_nav_entry->GetFrameEntry(prerender_root_ftn); blink::PageState page_state = blink::PageState::CreateForTestingWithSequenceNumbers( GURL("about:blank"), prerender_root_fne->item_sequence_number(), prerender_root_fne->document_sequence_number()); // Update PageState for prerender RFH, causing it to become different from // the one stored in RFH's last commit params. static_cast<mojom::FrameHost*>(prerender_rfh)->UpdateState(page_state); // Perform a navigation in the primary frame tree which activates the // prerendered page. The main expectation is that this navigation commits // successfully and doesn't hit any DCHECKs. NavigationSimulatorImpl::NavigateAndCommitFromBrowser(web_contents.get(), kPrerenderingUrl); ExpectFinalStatus(PrerenderHost::FinalStatus::kActivated); // Ensure that the the page_state was preserved. EXPECT_EQ(web_contents->GetMainFrame(), prerender_rfh); NavigationEntryImpl* activated_nav_entry = web_contents->GetController().GetLastCommittedEntry(); EXPECT_EQ( page_state, activated_nav_entry->GetFrameEntry(web_contents->GetFrameTree()->root()) ->page_state()); } } // namespace } // namespace content
// RUN: %clang_analyze_cc1 -std=c++1z -analyzer-checker=alpha.clone.CloneChecker -analyzer-config alpha.clone.CloneChecker:MinimumCloneComplexity=10 -verify %s // expected-no-diagnostics int foo1(int n) { int result = 0; switch (n) { case 33: result += 33; [[clang::fallthrough]]; case 44: result += 44; } return result; } // Identical to foo1 except the missing attribute. int foo2(int n) { int result = 0; switch (n) { case 33: result += 33; ; case 44: result += 44; } return result; }
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "acpidump.h" #include <errno.h> #include <fcntl.h> #include <fidl/fuchsia.hardware.acpi/cpp/wire.h> #include <lib/cmdline/args_parser.h> #include <lib/fdio/cpp/caller.h> #include <lib/fidl/llcpp/vector_view.h> #include <lib/zx/time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <zircon/status.h> #include <zircon/types.h> #include <iostream> #include <optional> #include <string> #include <string_view> #include <fbl/array.h> #include <fbl/span.h> #include <fbl/string_printf.h> #include <fbl/unique_fd.h> namespace acpidump { using fuchsia_hardware_acpi::Acpi; using fuchsia_hardware_acpi::wire::TableInfo; const char kAcpiDevicePath[] = "/dev/sys/platform/acpi"; // Set up an argument parser. We attempt to follow the conventions of // Linux's "acpidump" commands where possible, though we also add long // versions of the switches. static std::unique_ptr<cmdline::ArgsParser<Args>> MakeArgsParser() { auto parser = std::make_unique<cmdline::ArgsParser<Args>>(); parser->AddSwitch("summary", 's', "Summarise table names, but don't show content.", &Args::table_names_only); parser->AddSwitch("binary", 'b', "Dump raw binary data format.", &Args::dump_raw); parser->AddSwitch("help", 'h', "Show this help message.", &Args::show_help); parser->AddSwitch("table", 't', "Only dump the named table.", &Args::table); return parser; } void PrintUsage(const char* prog_name) { // cmdline::ArgParser has only a very simple usage screen, so we just // print out our own. fprintf(stderr, "usage:\n" "%s [options]\n" "\n" "Dumps raw system ACPI tables.\n" "\n" "Options:\n" " -s : Summarise table names, but don't show content.\n" " -t <table name> : Only dump the named table.\n" " -b : Dump raw binary data format.\n" " Requires a table name to be specified.\n" " -h, --help : Show this help message.\n", prog_name); } bool ParseArgs(fbl::Span<const char* const> args, Args* result) { *result = Args{}; // Parse the args. std::vector<std::string> params; cmdline::Status status = MakeArgsParser()->Parse(static_cast<int>(args.size()), args.data(), result, &params); if (!status.ok()) { fprintf(stderr, "Could not parse arguments: %s\n", status.error_message().c_str()); return false; } // Ensure no additional args were given. if (params.size() > 0) { fprintf(stderr, "Unknown argument: '%s'\n", params[0].c_str()); return false; } // Check for incompatible arguments. if (result->table_names_only) { if (result->dump_raw) { fprintf(stderr, "Error: Cannot summarise and dump as raw.\n"); return false; } if (result->table.has_value()) { fprintf(stderr, "Error: Cannot summarise a single table only.\n"); return false; } } if (result->dump_raw && !result->table.has_value()) { fprintf(stderr, "Error: Dumping binary requires specifying a table name.\n"); return false; } return true; } // Convert a fidl::Array<uint8_t, n> type to a std::string. template <uint64_t N> std::string SignatureToString(const fidl::Array<uint8_t, N>& array) { return std::string(reinterpret_cast<const char*>(array.data()), array.size()); } // Print the list of table names. // // We attempt to copy the same output as Linux's "acpidump" command. void PrintTableNames(const fidl::VectorView<TableInfo>& entries) { for (size_t i = 0; i < entries.count(); i++) { printf("ACPI: %s %06x\n", SignatureToString(entries[i].name).c_str(), entries[i].size); } } // Fetch raw data for a table. zx_status_t FetchTable(const zx::channel& channel, const TableInfo& table, fbl::Array<uint8_t>* data) { // Allocate a VMO for the read. zx::vmo vmo; if (zx_status_t status = zx::vmo::create(table.size, /*options=*/0, &vmo); status != ZX_OK) { return status; } // Make a copy to send to the driver. zx::vmo vmo_copy; if (zx_status_t status = vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy); status != ZX_OK) { return status; } // Fetch the data. fidl::WireResult<Acpi::ReadNamedTable> result = fidl::WireCall<Acpi>(channel.borrow()).ReadNamedTable(table.name, 0, std::move(vmo_copy)); if (!result.ok()) { return result.status(); } // Copy the data into memory. uint32_t size = result.value().result.response().size; auto table_data = fbl::Array<uint8_t>(new uint8_t[size], size); if (zx_status_t status = vmo.read(table_data.data(), 0, size); status != ZX_OK) { return status; } *data = std::move(table_data); return ZX_OK; } // Print the given data directly to stdout. void PrintRaw(const fbl::Array<uint8_t>& data) { fwrite(data.begin(), 1, data.size(), stdout); } // Print the ACPI table |name|. // // We attempt to duplicate the formatting of the native Linux "acpidump" // command to allow user scripts, "xxd" invocations etc to work without // modification. // // Example output: // // DSDT // 0000: 44 53 44 54 B4 1F 00 00 01 9B 42 4F 43 48 53 20 DSDT......BOCHS // 0010: 42 58 50 43 44 53 44 54 01 00 00 00 42 58 50 43 BXPCDSDT....BXPC // (...) void PrintHex(const char* name, const fbl::Array<uint8_t>& data) { // Print table name. printf("%s\n", name); // Print hex dump of data. for (size_t address = 0; address < data.size(); address += 16) { // Print ' 1234:' (4x ' ' padding, 4x '0' padding). printf("%8s: ", fbl::StringPrintf("%04lX", address).c_str()); // Print ' AA BB CC DD' (16x bytes as hex) size_t i; for (i = 0; i < 16 && i + address < data.size(); i++) { printf("%02X ", data[i + address]); } // Print any extra padding for the last line. for (; i < 16; i++) { printf(" "); } // Print gap between hex values and ASCII. putchar(' '); // Print ASCII chars. for (i = 0; i < 16 && i + address < data.size(); i++) { putchar(isprint(data[i + address]) ? data[i + address] : '.'); } putchar('\n'); } putchar('\n'); } // Open the ACPI device, waiting until it appears if necessary (e.g., if we run shortly // after system boot). static fbl::unique_fd OpenAcpiDevice() { zx::duration poll_delay = zx::msec(1); bool first_poll = true; while (true) { // Attempt to open the device. fbl::unique_fd fd{open(kAcpiDevicePath, O_RDWR)}; if (fd.is_valid()) { return fd; } // If we have an error (other than "file not found") print an error and return. if (errno != ENOENT) { fprintf(stderr, "Failed to open '%s': %s\n", kAcpiDevicePath, strerror(errno)); return fbl::unique_fd(); } // If we couldn't open it because it doesn't exist, it might just be that // ACPI hasn't been enumerated yet. Poll the file every so often. // // TODO(dgreenaway): Instead of polling, using the Watch API. if (first_poll) { fprintf(stderr, "ACPI device '%s' not found. Waiting for it to appear...\n", kAcpiDevicePath); first_poll = false; } // Poll with exponential backoff, up to a 1 second polling interval. zx::nanosleep(zx::deadline_after(poll_delay)); poll_delay = std::min(poll_delay * 2, zx::sec(1)); } } zx_status_t AcpiDump(const Args& args) { // Open up channel to ACPI device. fbl::unique_fd fd = OpenAcpiDevice(); if (!fd.is_valid()) { return ZX_ERR_UNAVAILABLE; } fdio_cpp::FdioCaller dev(std::move(fd)); // List ACPI entries. fidl::WireResult<Acpi::ListTableEntries> result = fidl::WireCall<Acpi>(dev.channel()).ListTableEntries(); if (!result.ok()) { fprintf(stderr, "Could not list ACPI table entries: %s.\n", zx_status_get_string(result.status())); return result.status(); } if (result.value().result.is_err()) { fprintf(stderr, "Call to list ACPI table entries failed: %s.\n", zx_status_get_string(result.value().result.err())); return result.value().result.err(); } // Print summary if requested. auto& entries = result.value().result.response().entries; if (args.table_names_only) { PrintTableNames(entries); return 0; } // Print each table if requested. bool found_table = false; for (auto table : entries) { // Skip over tables we should ignore. if (args.table.has_value() && std::string_view(reinterpret_cast<const char*>(table.name.begin()), table.name.size()) != args.table.value()) { continue; } found_table = true; // Fetch table. fbl::Array<uint8_t> table_data; if (zx_status_t status = FetchTable(*dev.channel(), table, &table_data); status != ZX_OK) { fprintf(stderr, "Failed to read table '%s': %s\n", SignatureToString(table.name).c_str(), zx_status_get_string(status)); return 1; } // Print data. if (args.dump_raw) { PrintRaw(table_data); } else { PrintHex(SignatureToString(table.name).c_str(), table_data); } } // Print an error if we didn't find the user's requested table. if (args.table.has_value() && !found_table) { fprintf(stderr, "Table '%s' not found.\n", args.table->c_str()); return 1; } return 0; } int Main(int argc, const char** argv) { Args args; if (!ParseArgs(fbl::Span<const char*>(argv, argc), &args)) { PrintUsage(argv[0]); return 1; } if (args.show_help) { PrintUsage(argv[0]); return 0; } return AcpiDump(args) == ZX_OK ? 0 : 1; } } // namespace acpidump
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <seastar/core/deleter.hh> #include <seastar/core/temporary_buffer.hh> #include <seastar/net/const.hh> #include <vector> #include <cassert> #include <algorithm> #include <iosfwd> #include <seastar/util/std-compat.hh> #include <functional> namespace seastar { namespace net { struct fragment { char* base; size_t size; }; struct offload_info { ip_protocol_num protocol = ip_protocol_num::unused; bool needs_csum = false; uint8_t ip_hdr_len = 20; uint8_t tcp_hdr_len = 20; uint8_t udp_hdr_len = 8; bool needs_ip_csum = false; bool reassembled = false; uint16_t tso_seg_size = 0; // HW stripped VLAN header (CPU order) std::optional<uint16_t> vlan_tci; }; // Zero-copy friendly packet class // // For implementing zero-copy, we need a flexible destructor that can // destroy packet data in different ways: decrementing a reference count, // or calling a free()-like function. // // Moreover, we need different destructors for each set of fragments within // a single fragment. For example, a header and trailer might need delete[] // to be called, while the internal data needs a reference count to be // released. Matters are complicated in that fragments can be split // (due to virtual/physical translation). // // To implement this, we associate each packet with a single destructor, // but allow composing a packet from another packet plus a fragment to // be added, with its own destructor, causing the destructors to be chained. // // The downside is that the data needed for the destructor is duplicated, // if it is already available in the fragment itself. // // As an optimization, when we allocate small fragments, we allocate some // extra space, so prepending to the packet does not require extra // allocations. This is useful when adding headers. // class packet final { // enough for lots of headers, not quite two cache lines: static constexpr size_t internal_data_size = 128 - 16; static constexpr size_t default_nr_frags = 4; struct pseudo_vector { fragment* _start; fragment* _finish; pseudo_vector(fragment* start, size_t nr) : _start(start), _finish(_start + nr) {} fragment* begin() { return _start; } fragment* end() { return _finish; } fragment& operator[](size_t idx) { return _start[idx]; } }; struct impl { // when destroyed, virtual destructor will reclaim resources deleter _deleter; unsigned _len = 0; uint16_t _nr_frags = 0; uint16_t _allocated_frags; offload_info _offload_info; std::optional<uint32_t> _rss_hash; char _data[internal_data_size]; // only _frags[0] may use unsigned _headroom = internal_data_size; // in _data // FIXME: share _data/_frags space fragment _frags[]; impl(size_t nr_frags = default_nr_frags) noexcept; impl(const impl&) = delete; impl(fragment frag, size_t nr_frags = default_nr_frags); pseudo_vector fragments() { return { _frags, _nr_frags }; } static std::unique_ptr<impl> allocate(size_t nr_frags) { nr_frags = std::max(nr_frags, default_nr_frags); return std::unique_ptr<impl>(new (nr_frags) impl(nr_frags)); } static std::unique_ptr<impl> copy(impl* old, size_t nr) { auto n = allocate(nr); n->_deleter = std::move(old->_deleter); n->_len = old->_len; n->_nr_frags = old->_nr_frags; n->_headroom = old->_headroom; n->_offload_info = old->_offload_info; n->_rss_hash = old->_rss_hash; std::copy(old->_frags, old->_frags + old->_nr_frags, n->_frags); old->copy_internal_fragment_to(n.get()); return n; } static std::unique_ptr<impl> copy(impl* old) { return copy(old, old->_nr_frags); } static std::unique_ptr<impl> allocate_if_needed(std::unique_ptr<impl> old, size_t extra_frags) { if (old->_allocated_frags >= old->_nr_frags + extra_frags) { return old; } return copy(old.get(), std::max<size_t>(old->_nr_frags + extra_frags, 2 * old->_nr_frags)); } void* operator new(size_t size, size_t nr_frags = default_nr_frags) { assert(nr_frags == uint16_t(nr_frags)); return ::operator new(size + nr_frags * sizeof(fragment)); } // Matching the operator new above void operator delete(void* ptr, size_t nr_frags) { return ::operator delete(ptr); } // Since the above "placement delete" hides the global one, expose it void operator delete(void* ptr) { return ::operator delete(ptr); } bool using_internal_data() const { return _nr_frags && _frags[0].base >= _data && _frags[0].base < _data + internal_data_size; } void unuse_internal_data() { if (!using_internal_data()) { return; } auto buf = static_cast<char*>(::malloc(_frags[0].size)); if (!buf) { throw std::bad_alloc(); } deleter d = make_free_deleter(buf); std::copy(_frags[0].base, _frags[0].base + _frags[0].size, buf); _frags[0].base = buf; d.append(std::move(_deleter)); _deleter = std::move(d); _headroom = internal_data_size; } void copy_internal_fragment_to(impl* to) { if (!using_internal_data()) { return; } to->_frags[0].base = to->_data + _headroom; std::copy(_frags[0].base, _frags[0].base + _frags[0].size, to->_frags[0].base); } }; packet(std::unique_ptr<impl>&& impl) noexcept : _impl(std::move(impl)) {} std::unique_ptr<impl> _impl; public: static packet from_static_data(const char* data, size_t len) noexcept { return {fragment{const_cast<char*>(data), len}, deleter()}; } // build empty packet packet(); // build empty packet with nr_frags allocated packet(size_t nr_frags); // move existing packet packet(packet&& x) noexcept; // copy data into packet packet(const char* data, size_t len); // copy data into packet packet(fragment frag); // zero-copy single fragment packet(fragment frag, deleter del); // zero-copy multiple fragments packet(std::vector<fragment> frag, deleter del); // build packet with iterator template <typename Iterator> packet(Iterator begin, Iterator end, deleter del); // append fragment (copying new fragment) packet(packet&& x, fragment frag); // prepend fragment (copying new fragment, with header optimization) packet(fragment frag, packet&& x); // prepend fragment (zero-copy) packet(fragment frag, deleter del, packet&& x); // append fragment (zero-copy) packet(packet&& x, fragment frag, deleter d); // append temporary_buffer (zero-copy) packet(packet&& x, temporary_buffer<char> buf); // create from temporary_buffer (zero-copy) packet(temporary_buffer<char> buf); // append deleter packet(packet&& x, deleter d); packet& operator=(packet&& x) noexcept { if (this != &x) { this->~packet(); new (this) packet(std::move(x)); } return *this; } unsigned len() const { return _impl->_len; } unsigned memory() const { return len() + sizeof(packet::impl); } fragment frag(unsigned idx) const { return _impl->_frags[idx]; } fragment& frag(unsigned idx) { return _impl->_frags[idx]; } unsigned nr_frags() const { return _impl->_nr_frags; } pseudo_vector fragments() const { return { _impl->_frags, _impl->_nr_frags }; } fragment* fragment_array() const { return _impl->_frags; } // share packet data (reference counted, non COW) packet share(); packet share(size_t offset, size_t len); void append(packet&& p); void trim_front(size_t how_much); void trim_back(size_t how_much); // get a header pointer, linearizing if necessary template <typename Header> Header* get_header(size_t offset = 0); // get a header pointer, linearizing if necessary char* get_header(size_t offset, size_t size); // prepend a header (default-initializing it) template <typename Header> Header* prepend_header(size_t extra_size = 0); // prepend a header (uninitialized!) char* prepend_uninitialized_header(size_t size); packet free_on_cpu(unsigned cpu, std::function<void()> cb = []{}); void linearize() { return linearize(0, len()); } void reset() { _impl.reset(); } void reserve(int n_frags) { if (n_frags > _impl->_nr_frags) { auto extra = n_frags - _impl->_nr_frags; _impl = impl::allocate_if_needed(std::move(_impl), extra); } } std::optional<uint32_t> rss_hash() { return _impl->_rss_hash; } std::optional<uint32_t> set_rss_hash(uint32_t hash) { return _impl->_rss_hash = hash; } // Call `func` for each fragment, avoiding data copies when possible // `func` is called with a temporary_buffer<char> parameter template <typename Func> void release_into(Func&& func) { unsigned idx = 0; if (_impl->using_internal_data()) { auto&& f = frag(idx++); func(temporary_buffer<char>(f.base, f.size)); } while (idx < nr_frags()) { auto&& f = frag(idx++); func(temporary_buffer<char>(f.base, f.size, _impl->_deleter.share())); } } std::vector<temporary_buffer<char>> release() { std::vector<temporary_buffer<char>> ret; ret.reserve(_impl->_nr_frags); release_into([&ret] (temporary_buffer<char>&& frag) { ret.push_back(std::move(frag)); }); return ret; } explicit operator bool() { return bool(_impl); } static packet make_null_packet() noexcept { return net::packet(nullptr); } private: void linearize(size_t at_frag, size_t desired_size); bool allocate_headroom(size_t size); public: struct offload_info offload_info() const { return _impl->_offload_info; } struct offload_info& offload_info_ref() { return _impl->_offload_info; } void set_offload_info(struct offload_info oi) { _impl->_offload_info = oi; } }; std::ostream& operator<<(std::ostream& os, const packet& p); inline packet::packet(packet&& x) noexcept : _impl(std::move(x._impl)) { } inline packet::impl::impl(size_t nr_frags) noexcept : _len(0), _allocated_frags(nr_frags) { } inline packet::impl::impl(fragment frag, size_t nr_frags) : _len(frag.size), _allocated_frags(nr_frags) { assert(_allocated_frags > _nr_frags); if (frag.size <= internal_data_size) { _headroom -= frag.size; _frags[0] = { _data + _headroom, frag.size }; } else { auto buf = static_cast<char*>(::malloc(frag.size)); if (!buf) { throw std::bad_alloc(); } deleter d = make_free_deleter(buf); _frags[0] = { buf, frag.size }; _deleter.append(std::move(d)); } std::copy(frag.base, frag.base + frag.size, _frags[0].base); ++_nr_frags; } inline packet::packet() : _impl(impl::allocate(1)) { } inline packet::packet(size_t nr_frags) : _impl(impl::allocate(nr_frags)) { } inline packet::packet(fragment frag) : _impl(new impl(frag)) { } inline packet::packet(const char* data, size_t size) : packet(fragment{const_cast<char*>(data), size}) { } inline packet::packet(fragment frag, deleter d) : _impl(impl::allocate(1)) { _impl->_deleter = std::move(d); _impl->_frags[_impl->_nr_frags++] = frag; _impl->_len = frag.size; } inline packet::packet(std::vector<fragment> frag, deleter d) : _impl(impl::allocate(frag.size())) { _impl->_deleter = std::move(d); std::copy(frag.begin(), frag.end(), _impl->_frags); _impl->_nr_frags = frag.size(); _impl->_len = 0; for (auto&& f : _impl->fragments()) { _impl->_len += f.size; } } template <typename Iterator> inline packet::packet(Iterator begin, Iterator end, deleter del) { unsigned nr_frags = 0, len = 0; nr_frags = std::distance(begin, end); std::for_each(begin, end, [&] (const fragment& frag) { len += frag.size; }); _impl = impl::allocate(nr_frags); _impl->_deleter = std::move(del); _impl->_len = len; _impl->_nr_frags = nr_frags; std::copy(begin, end, _impl->_frags); } inline packet::packet(packet&& x, fragment frag) : _impl(impl::allocate_if_needed(std::move(x._impl), 1)) { _impl->_len += frag.size; std::unique_ptr<char[]> buf(new char[frag.size]); std::copy(frag.base, frag.base + frag.size, buf.get()); _impl->_frags[_impl->_nr_frags++] = {buf.get(), frag.size}; _impl->_deleter = make_deleter(std::move(_impl->_deleter), [buf = buf.release()] { delete[] buf; }); } inline bool packet::allocate_headroom(size_t size) { if (_impl->_headroom >= size) { _impl->_len += size; if (!_impl->using_internal_data()) { _impl = impl::allocate_if_needed(std::move(_impl), 1); std::copy_backward(_impl->_frags, _impl->_frags + _impl->_nr_frags, _impl->_frags + _impl->_nr_frags + 1); _impl->_frags[0] = { _impl->_data + internal_data_size, 0 }; ++_impl->_nr_frags; } _impl->_headroom -= size; _impl->_frags[0].base -= size; _impl->_frags[0].size += size; return true; } else { return false; } } inline packet::packet(fragment frag, packet&& x) : _impl(std::move(x._impl)) { // try to prepend into existing internal fragment if (allocate_headroom(frag.size)) { std::copy(frag.base, frag.base + frag.size, _impl->_frags[0].base); return; } else { // didn't work out, allocate and copy _impl->unuse_internal_data(); _impl = impl::allocate_if_needed(std::move(_impl), 1); _impl->_len += frag.size; std::unique_ptr<char[]> buf(new char[frag.size]); std::copy(frag.base, frag.base + frag.size, buf.get()); std::copy_backward(_impl->_frags, _impl->_frags + _impl->_nr_frags, _impl->_frags + _impl->_nr_frags + 1); ++_impl->_nr_frags; _impl->_frags[0] = {buf.get(), frag.size}; _impl->_deleter = make_deleter(std::move(_impl->_deleter), [buf = std::move(buf)] {}); } } inline packet::packet(packet&& x, fragment frag, deleter d) : _impl(impl::allocate_if_needed(std::move(x._impl), 1)) { _impl->_len += frag.size; _impl->_frags[_impl->_nr_frags++] = frag; d.append(std::move(_impl->_deleter)); _impl->_deleter = std::move(d); } inline packet::packet(packet&& x, deleter d) : _impl(std::move(x._impl)) { _impl->_deleter.append(std::move(d)); } inline packet::packet(packet&& x, temporary_buffer<char> buf) : packet(std::move(x), fragment{buf.get_write(), buf.size()}, buf.release()) { } inline packet::packet(temporary_buffer<char> buf) : packet(fragment{buf.get_write(), buf.size()}, buf.release()) {} inline void packet::append(packet&& p) { if (!_impl->_len) { *this = std::move(p); return; } _impl = impl::allocate_if_needed(std::move(_impl), p._impl->_nr_frags); _impl->_len += p._impl->_len; p._impl->unuse_internal_data(); std::copy(p._impl->_frags, p._impl->_frags + p._impl->_nr_frags, _impl->_frags + _impl->_nr_frags); _impl->_nr_frags += p._impl->_nr_frags; p._impl->_deleter.append(std::move(_impl->_deleter)); _impl->_deleter = std::move(p._impl->_deleter); } inline char* packet::get_header(size_t offset, size_t size) { if (offset + size > _impl->_len) { return nullptr; } size_t i = 0; while (i != _impl->_nr_frags && offset >= _impl->_frags[i].size) { offset -= _impl->_frags[i++].size; } if (i == _impl->_nr_frags) { return nullptr; } if (offset + size > _impl->_frags[i].size) { linearize(i, offset + size); } return _impl->_frags[i].base + offset; } template <typename Header> inline Header* packet::get_header(size_t offset) { return reinterpret_cast<Header*>(get_header(offset, sizeof(Header))); } inline void packet::trim_front(size_t how_much) { assert(how_much <= _impl->_len); _impl->_len -= how_much; size_t i = 0; while (how_much && how_much >= _impl->_frags[i].size) { how_much -= _impl->_frags[i++].size; } std::copy(_impl->_frags + i, _impl->_frags + _impl->_nr_frags, _impl->_frags); _impl->_nr_frags -= i; if (!_impl->using_internal_data()) { _impl->_headroom = internal_data_size; } if (how_much) { if (_impl->using_internal_data()) { _impl->_headroom += how_much; } _impl->_frags[0].base += how_much; _impl->_frags[0].size -= how_much; } } inline void packet::trim_back(size_t how_much) { assert(how_much <= _impl->_len); _impl->_len -= how_much; size_t i = _impl->_nr_frags - 1; while (how_much && how_much >= _impl->_frags[i].size) { how_much -= _impl->_frags[i--].size; } _impl->_nr_frags = i + 1; if (how_much) { _impl->_frags[i].size -= how_much; if (i == 0 && _impl->using_internal_data()) { _impl->_headroom += how_much; } } } template <typename Header> Header* packet::prepend_header(size_t extra_size) { auto h = prepend_uninitialized_header(sizeof(Header) + extra_size); return new (h) Header{}; } // prepend a header (uninitialized!) inline char* packet::prepend_uninitialized_header(size_t size) { if (!allocate_headroom(size)) { // didn't work out, allocate and copy _impl->unuse_internal_data(); // try again, after unuse_internal_data we may have space after all if (!allocate_headroom(size)) { // failed _impl->_len += size; _impl = impl::allocate_if_needed(std::move(_impl), 1); std::unique_ptr<char[]> buf(new char[size]); std::copy_backward(_impl->_frags, _impl->_frags + _impl->_nr_frags, _impl->_frags + _impl->_nr_frags + 1); ++_impl->_nr_frags; _impl->_frags[0] = {buf.get(), size}; _impl->_deleter = make_deleter(std::move(_impl->_deleter), [buf = std::move(buf)] {}); } } return _impl->_frags[0].base; } inline packet packet::share() { return share(0, _impl->_len); } inline packet packet::share(size_t offset, size_t len) { _impl->unuse_internal_data(); // FIXME: eliminate? packet n; n._impl = impl::allocate_if_needed(std::move(n._impl), _impl->_nr_frags); size_t idx = 0; while (offset > 0 && offset >= _impl->_frags[idx].size) { offset -= _impl->_frags[idx++].size; } while (n._impl->_len < len) { auto& f = _impl->_frags[idx++]; auto fsize = std::min(len - n._impl->_len, f.size - offset); n._impl->_frags[n._impl->_nr_frags++] = { f.base + offset, fsize }; n._impl->_len += fsize; offset = 0; } n._impl->_offload_info = _impl->_offload_info; assert(!n._impl->_deleter); n._impl->_deleter = _impl->_deleter.share(); return n; } } }
// SPDX-License-Identifier: BSD-2-Clause /* Copyright (C) 2015 - 2021 Intel Corporation. */ #include "StressIncreaseToMax.h" void StressIncreaseToMax::run() { // Generate constant allocation sizes. VectorIterator<size_t> allocation_sizes = AllocationSizes::generate_random_sizes(task_conf.allocation_sizes_conf, task_conf.seed); // Generate only mallocs. VectorIterator<int> func_calls = FunctionCalls::generate_random_allocator_func_calls( task_conf.n, task_conf.seed, task_conf.func_calls); unsigned type; for (type = 0; type < AllocatorTypes::NUM_OF_ALLOCATOR_TYPES; type++) { if (task_conf.allocators_types.is_enabled(type)) break; // Assume that there is only one type. } AllocatorFactory allocator_factory; VectorIterator<Allocator *> allocators_calls = allocator_factory.generate_random_allocator_calls( task_conf.n, task_conf.seed, task_conf.allocators_types); ScenarioWorkload scenario_workload(&allocators_calls, &allocation_sizes, &func_calls); scenario_workload.enable_touch_memory_on_allocation(task_conf.touch_memory); test_status.is_allocation_error = false; size_t requested_memory = 0; bool has_reach_memory_request_limit = false; while (!has_reach_memory_request_limit && !test_status.is_allocation_error && (test_status.has_next_memory_operation = scenario_workload.run())) { memory_operation data = scenario_workload.get_allocations_info().back(); test_status.is_allocation_error = (data.error_code == ENOMEM) || (data.ptr == NULL); if (data.allocation_method != FunctionCalls::FREE) { requested_memory += data.size_of_allocation; has_reach_memory_request_limit = requested_memory >= req_mem_limit; } } if (!(scenario_workload.get_allocations_info().size() < task_conf.n) && !has_reach_memory_request_limit) printf("\nWARNING: Too few memory operations to reach the limit.\n"); if (test_status.is_allocation_error) printf("\nWARNING: Allocation error. \n"); results = scenario_workload.get_allocations_info(); } std::vector<iteration_result> StressIncreaseToMax::execute_test_iterations( const TaskConf &task_conf, unsigned time, size_t requested_memory_limit) { TimerSysTime timer; unsigned itr = 0; std::vector<iteration_result> results; std::ofstream csv_file; csv::Row row; row.append("Iteration"); row.append("Allocated memory (MB)"); row.append("Elapsed time (seconds)"); if (task_conf.is_csv_log_enabled) { csv_file.open("stress_test_increase_to_max.csv"); csv_file << row.export_row(); } printf("%s", row.export_row().c_str()); timer.start(); while (timer.getElapsedTime() < time) { StressIncreaseToMax stress_test(task_conf, requested_memory_limit); stress_test.run(); float elapsed_time = timer.getElapsedTime(); TimeStats stats; stats += stress_test.get_results(); results.push_back(stress_test.get_test_status()); // Log every iteration of StressIncreaseToMax test. csv::Row row; row.append(itr); row.append(convert_bytes_to_mb(stats.get_allocated())); row.append(elapsed_time); if (task_conf.is_csv_log_enabled) { csv_file << row.export_row(); } printf("%s", row.export_row().c_str()); fflush(stdout); itr++; } printf("\nStress test (StressIncreaseToMax) finish in time %f.\n", timer.getElapsedTime()); csv_file.close(); return results; }
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The infinitemoneycoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "chainparams.h" #include "main.h" #include "uint256.h" #include <stdint.h> #include <boost/foreach.hpp> namespace Checkpoints { /** * How many times we expect transactions after the last checkpoint to * be slower. This number is a compromise, as it can't be accurate for * every system. When reindexing from a fast disk with a slow CPU, it * can be up to 20, while when downloading from a slow network with a * fast multicore CPU, it won't be much higher than 1. */ static const double SIGCHECK_VERIFICATION_FACTOR = 5.0; bool fEnabled = true; bool CheckBlock(int nHeight, const uint256& hash, bool fMatchesCheckpoint) { if (!fEnabled) return true; const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); // If looking for an exact match, then return false if (i == checkpoints.end()) return !fMatchesCheckpoint; return hash == i->second; } //! Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex* pindex, bool fSigchecks) { if (pindex == NULL) return 0.0; int64_t nNow = time(NULL); double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0; double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData& data = Params().Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint) / 86400.0 * data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter * fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->GetBlockTime()) / 86400.0 * data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore * fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter * fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!fEnabled) return 0; const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint() { if (!fEnabled) return NULL; const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH (const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; BlockMap::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } // namespace Checkpoints
// Copyright 2002 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Boost.MultiArray Library // Authors: Ronald Garcia // Jeremy Siek // Andrew Lumsdaine // See http://www.boost.org/libs/multi_array for documentation. // // fail_ref_cbracket.cpp // checking constness of const operator[]. // #include "boost/multi_array.hpp" #include "boost/test/minimal.hpp" #include "boost/array.hpp" int test_main(int,char*[]) { const int ndims=3; typedef boost::multi_array_ref<int,ndims> array_ref; boost::array<array_ref::size_type,ndims> sma_dims = {{2,3,4}}; int data[] = {77,77,77,77,77,77,77,77,77,77,77,77, 77,77,77,77,77,77,77,77,77,77,77,77}; array_ref sma(data,sma_dims); const array_ref& csma = sma; // FAIL! can't assign to const multi_array_ref. csma[0][0][0] = 5; return boost::exit_success; }
// Copyright 2020 The XLS 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. #include "xls/dslx/parametric_instantiator.h" #include "absl/strings/match.h" #include "xls/dslx/interpreter.h" namespace xls::dslx { namespace internal { ParametricInstantiator::ParametricInstantiator( Span span, absl::Span<std::unique_ptr<ConcreteType> const> arg_types, DeduceCtx* ctx, absl::optional<absl::Span<ParametricBinding* const>> parametric_constraints, const absl::flat_hash_map<std::string, int64>* explicit_constraints) : span_(std::move(span)), arg_types_(arg_types), ctx_(ctx) { if (explicit_constraints != nullptr) { symbolic_bindings_ = *explicit_constraints; } if (parametric_constraints.has_value()) { for (ParametricBinding* binding : *parametric_constraints) { constraint_order_.push_back(binding->identifier()); TypeAnnotation* type = binding->type(); auto* bits_type = dynamic_cast<BuiltinTypeAnnotation*>(type); // TODO(leary): 2020-12-11 This is a bug, we should be able to use uN[32] // style annotations here. XLS_CHECK(bits_type != nullptr); bit_widths_[binding->identifier()] = bits_type->GetBitCount(); constraints_[binding->identifier()] = binding->expr(); } } } absl::StatusOr<std::unique_ptr<ConcreteType>> ParametricInstantiator::InstantiateOneArg(int64 i, const ConcreteType& param_type, const ConcreteType& arg_type) { if (typeid(param_type) != typeid(arg_type)) { std::string message = absl::StrFormat( "Parameter %d and argument types are different kinds (%s vs %s).", i, param_type.GetDebugTypeName(), arg_type.GetDebugTypeName()); return XlsTypeErrorStatus(span_, param_type, arg_type, message); } XLS_VLOG(5) << absl::StreamFormat( "Symbolically binding param %d formal %s against arg %s", i, param_type.ToString(), arg_type.ToString()); XLS_RETURN_IF_ERROR(SymbolicBind(param_type, arg_type)); XLS_ASSIGN_OR_RETURN(std::unique_ptr<ConcreteType> resolved, Resolve(param_type)); XLS_VLOG(5) << "Resolved parameter type: " << resolved->ToString(); return resolved; } absl::StatusOr<std::unique_ptr<ConcreteType>> ParametricInstantiator::Resolve( const ConcreteType& annotated) { XLS_RETURN_IF_ERROR(VerifyConstraints()); return annotated.MapSize( [this](ConcreteTypeDim dim) -> absl::StatusOr<ConcreteTypeDim> { if (!absl::holds_alternative<ConcreteTypeDim::OwnedParametric>( dim.value())) { return dim; } const auto& parametric_expr = absl::get<ConcreteTypeDim::OwnedParametric>(dim.value()); ParametricExpression::Evaluated evaluated = parametric_expr->Evaluate( ToParametricEnv(SymbolicBindings(symbolic_bindings_))); return ConcreteTypeDim(std::move(evaluated)); }); } absl::Status ParametricInstantiator::VerifyConstraints() { XLS_VLOG(5) << "Verifying " << constraints_.size() << " constraints"; for (const auto& name : constraint_order_) { Expr* expr = constraints_[name]; XLS_VLOG(5) << "name: " << name << " expr: " << (expr == nullptr ? "<none>" : expr->ToString()); if (expr == nullptr) { // e.g. <X: u32> has no expr continue; } const FnStackEntry& entry = ctx_->fn_stack().back(); FnCtx fn_ctx{ctx_->module()->name(), entry.name(), entry.symbolic_bindings()}; absl::StatusOr<int64> result = Interpreter::InterpretExpr( ctx_->module(), ctx_->type_info(), ctx_->typecheck_module(), ctx_->additional_search_paths(), ctx_->import_cache(), symbolic_bindings_, bit_widths_, expr, fn_ctx); XLS_VLOG(5) << "Interpreted expr: " << expr->ToString() << " @ " << expr->span() << " to status: " << result.status(); if (!result.ok() && result.status().code() == absl::StatusCode::kNotFound && (absl::StartsWith(result.status().message(), "Could not find bindings entry for identifier") || absl::StartsWith(result.status().message(), "Could not find callee bindings in type info"))) { // We haven't seen enough bindings to evaluate this constraint yet. continue; } if (auto it = symbolic_bindings_.find(name); it != symbolic_bindings_.end()) { int64 seen = it->second; if (result.value() != seen) { auto lhs = absl::make_unique<BitsType>(/*signed=*/false, /*size=*/seen); auto rhs = absl::make_unique<BitsType>(/*signed=*/false, /*size=*/result.value()); std::string message = absl::StrFormat( "Parametric constraint violated, first saw %s = %d; then saw %s = " "%s = %d", name, seen, name, expr->ToString(), result.value()); return XlsTypeErrorStatus(span_, *lhs, *rhs, std::move(message)); } } else { symbolic_bindings_[name] = result.value(); } } return absl::OkStatus(); } static const ParametricSymbol* TryGetParametricSymbol( const ConcreteTypeDim& dim) { if (!absl::holds_alternative<ConcreteTypeDim::OwnedParametric>(dim.value())) { return nullptr; } const ParametricExpression* parametric = absl::get<ConcreteTypeDim::OwnedParametric>(dim.value()).get(); return dynamic_cast<const ParametricSymbol*>(parametric); } template <typename T> absl::Status ParametricInstantiator::SymbolicBindDims(const T& param_type, const T& arg_type) { // Create bindings for symbolic parameter dimensions based on argument values // passed. ConcreteTypeDim param_dim = param_type.size(); const ParametricSymbol* symbol = TryGetParametricSymbol(param_dim); if (symbol == nullptr) { return absl::OkStatus(); // Nothing to bind in the formal argument type. } int64 arg_dim = absl::get<int64>(arg_type.size().value()); const std::string& pdim_name = symbol->identifier(); if (symbolic_bindings_.contains(pdim_name) && symbolic_bindings_.at(pdim_name) != arg_dim) { int64 seen = symbolic_bindings_.at(pdim_name); // We see a conflict between something we previously observed and something // we are now observing. if (Expr* expr = constraints_[pdim_name]) { // Error is violated constraint. std::string message = absl::StrFormat( "Parametric constraint violated, saw %s = %d; then %s = %s = %d", pdim_name, seen, pdim_name, expr->ToString(), arg_dim); auto saw_type = absl::make_unique<BitsType>(/*signed=*/false, /*size=*/seen); return XlsTypeErrorStatus(span_, *saw_type, arg_type, message); } else { // Error is conflicting argument types. std::string message = absl::StrFormat( "Parametric value %s was bound to different values at different " "places in invocation; saw: %d; then: %d", pdim_name, seen, arg_dim); return XlsTypeErrorStatus(span_, param_type, arg_type, message); } } XLS_VLOG(5) << "Binding " << pdim_name << " to " << arg_dim; symbolic_bindings_[pdim_name] = arg_dim; return absl::OkStatus(); } absl::Status ParametricInstantiator::SymbolicBindTuple( const TupleType& param_type, const TupleType& arg_type) { XLS_RET_CHECK_EQ(param_type.size(), arg_type.size()); for (int64 i = 0; i < param_type.size(); ++i) { const ConcreteType& param_member = param_type.GetUnnamedMember(i); const ConcreteType& arg_member = arg_type.GetUnnamedMember(i); XLS_RETURN_IF_ERROR(SymbolicBind(param_member, arg_member)); } return absl::OkStatus(); } absl::Status ParametricInstantiator::SymbolicBindBits( const ConcreteType& param_type, const ConcreteType& arg_type) { if (dynamic_cast<const EnumType*>(&param_type) != nullptr) { return absl::OkStatus(); // Enums have no size, so nothing to bind. } auto* param_bits = dynamic_cast<const BitsType*>(&param_type); XLS_RET_CHECK(param_bits != nullptr); auto* arg_bits = dynamic_cast<const BitsType*>(&arg_type); XLS_RET_CHECK(arg_bits != nullptr); return SymbolicBindDims(*param_bits, *arg_bits); } absl::Status ParametricInstantiator::SymbolicBindArray( const ArrayType& param_type, const ArrayType& arg_type) { XLS_RETURN_IF_ERROR( SymbolicBind(param_type.element_type(), arg_type.element_type())); return SymbolicBindDims(param_type, arg_type); } absl::Status ParametricInstantiator::SymbolicBindFunction( const FunctionType& param_type, const FunctionType& arg_type) { return absl::UnimplementedError("SymbolicBindFunction()"); } absl::Status ParametricInstantiator::SymbolicBind( const ConcreteType& param_type, const ConcreteType& arg_type) { if (auto* param_bits = dynamic_cast<const BitsType*>(&param_type)) { auto* arg_bits = dynamic_cast<const BitsType*>(&arg_type); XLS_RET_CHECK(arg_bits != nullptr); return SymbolicBindBits(*param_bits, *arg_bits); } if (auto* param_enum = dynamic_cast<const EnumType*>(&param_type)) { auto* arg_enum = dynamic_cast<const EnumType*>(&arg_type); XLS_RET_CHECK(arg_enum != nullptr); XLS_RET_CHECK_EQ(param_enum->nominal_type(), arg_enum->nominal_type()); // If the enums are the same, we do the same thing as we do with bits // (ignore the primitive and symbolic bind the dims). return SymbolicBindBits(*param_enum, *arg_enum); } if (auto* param_tuple = dynamic_cast<const TupleType*>(&param_type)) { auto* arg_tuple = dynamic_cast<const TupleType*>(&arg_type); StructDef* param_nominal = param_tuple->nominal_type(); StructDef* arg_nominal = arg_tuple->nominal_type(); XLS_VLOG(5) << "param nominal " << (param_nominal == nullptr ? "none" : param_nominal->ToString()) << " arg nominal " << (arg_nominal == nullptr ? "none" : arg_nominal->ToString()); if (param_nominal != arg_nominal) { std::string message = absl::StrFormat( "parameter type name: '%s'; argument type name: '%s'", param_nominal == nullptr ? "<none>" : param_nominal->identifier(), arg_nominal == nullptr ? "<none>" : arg_nominal->identifier()); return XlsTypeErrorStatus(span_, param_type, arg_type, message); } return SymbolicBindTuple(*param_tuple, *arg_tuple); } if (auto* param_array = dynamic_cast<const ArrayType*>(&param_type)) { auto* arg_array = dynamic_cast<const ArrayType*>(&arg_type); XLS_RET_CHECK(arg_array != nullptr); return SymbolicBindArray(*param_array, *arg_array); } if (auto* param_fn = dynamic_cast<const FunctionType*>(&param_type)) { auto* arg_fn = dynamic_cast<const FunctionType*>(&arg_type); XLS_RET_CHECK(arg_fn != nullptr); return SymbolicBindFunction(*param_fn, *arg_fn); } return absl::InternalError( absl::StrFormat("Unhandled parameter type for symbolic binding: %s @ %s", param_type.ToString(), span_.ToString())); } /* static */ absl::StatusOr<FunctionInstantiator> FunctionInstantiator::Make( Span span, const FunctionType& function_type, absl::Span<std::unique_ptr<ConcreteType> const> arg_types, DeduceCtx* ctx, absl::optional<absl::Span<ParametricBinding* const>> parametric_constraints, const absl::flat_hash_map<std::string, int64>* explicit_constraints) { XLS_VLOG(5) << "Making FunctionInstantiator for " << function_type.ToString() << " with " << (parametric_constraints.has_value() ? parametric_constraints->size() : 0) << " parametric constraints and " << (explicit_constraints == nullptr ? 0 : explicit_constraints->size()) << " explicit constraints"; if (arg_types.size() != function_type.params().size()) { return absl::InvalidArgumentError(absl::StrFormat( "ArgCountMismatchError: %s Expected %d parameter(s) but got %d " "argument(s)", span.ToString(), function_type.params().size(), arg_types.size())); } return FunctionInstantiator(std::move(span), function_type, arg_types, ctx, parametric_constraints, explicit_constraints); } absl::StatusOr<TypeAndBindings> FunctionInstantiator::Instantiate() { // Walk through all the params/args to collect symbolic bindings. for (int64 i = 0; i < arg_types().size(); ++i) { const ConcreteType& param_type = *param_types_[i]; const ConcreteType& arg_type = *arg_types()[i]; XLS_ASSIGN_OR_RETURN(std::unique_ptr<ConcreteType> instantiated_param_type, InstantiateOneArg(i, param_type, arg_type)); if (*instantiated_param_type != arg_type) { return XlsTypeErrorStatus(span(), param_type, arg_type, "Mismatch between parameter and argument types " "(after instantiation)."); } } // Resolve the return type according to the bindings we collected. const ConcreteType& orig = function_type_->return_type(); XLS_ASSIGN_OR_RETURN(std::unique_ptr<ConcreteType> resolved, Resolve(orig)); XLS_VLOG(5) << "Resolved return type from " << orig.ToString() << " to " << resolved->ToString(); return TypeAndBindings{std::move(resolved), SymbolicBindings(symbolic_bindings())}; } /* static */ absl::StatusOr<StructInstantiator> StructInstantiator::Make( Span span, const TupleType& struct_type, absl::Span<std::unique_ptr<ConcreteType> const> arg_types, absl::Span<std::unique_ptr<ConcreteType> const> member_types, DeduceCtx* ctx, absl::optional<absl::Span<ParametricBinding* const>> parametric_bindings) { XLS_RET_CHECK_EQ(arg_types.size(), member_types.size()); return StructInstantiator(std::move(span), struct_type, arg_types, member_types, ctx, parametric_bindings); } absl::StatusOr<TypeAndBindings> StructInstantiator::Instantiate() { for (int64 i = 0; i < member_types_.size(); ++i) { const ConcreteType& member_type = *member_types_[i]; const ConcreteType& arg_type = GetArgType(i); XLS_ASSIGN_OR_RETURN(std::unique_ptr<ConcreteType> instantiated_member_type, InstantiateOneArg(i, member_type, arg_type)); if (*instantiated_member_type != arg_type) { return XlsTypeErrorStatus(span(), *instantiated_member_type, arg_type, "Mismatch between member and argument types."); } } XLS_ASSIGN_OR_RETURN(std::unique_ptr<ConcreteType> resolved, Resolve(*struct_type_)); return TypeAndBindings{std::move(resolved), SymbolicBindings(symbolic_bindings())}; } } // namespace internal // Helper ToString()s for debug logging. static std::string ToString( absl::Span<std::unique_ptr<ConcreteType> const> ts) { if (ts.empty()) { return "none"; } return absl::StrJoin(ts, ", ", [](std::string* out, const auto& t) { absl::StrAppend(out, t->ToString()); }); } static std::string ToString( absl::optional<absl::Span<ParametricBinding* const>> pbs) { if (!pbs.has_value() || pbs->empty()) { return "none"; } return absl::StrJoin(*pbs, ", ", [](std::string* out, ParametricBinding* pb) { absl::StrAppend(out, pb->ToString()); }); } static std::string ToString( const absl::flat_hash_map<std::string, int64>* map) { if (map == nullptr || map->empty()) { return "none"; } return absl::StrJoin(*map, ", ", absl::PairFormatter(":")); } absl::StatusOr<TypeAndBindings> InstantiateFunction( Span span, const FunctionType& function_type, absl::Span<std::unique_ptr<ConcreteType> const> arg_types, DeduceCtx* ctx, absl::optional<absl::Span<ParametricBinding* const>> parametric_constraints, const absl::flat_hash_map<std::string, int64>* explicit_constraints) { XLS_VLOG(5) << "Function instantiation @ " << span << " type: " << function_type.ToString(); XLS_VLOG(5) << " arg types: " << ToString(arg_types); XLS_VLOG(5) << " parametric constraints: " << ToString(parametric_constraints); XLS_VLOG(5) << " explicit constraints: " << ToString(explicit_constraints); XLS_ASSIGN_OR_RETURN(auto instantiator, internal::FunctionInstantiator::Make( std::move(span), function_type, arg_types, ctx, parametric_constraints, explicit_constraints)); return instantiator.Instantiate(); } absl::StatusOr<TypeAndBindings> InstantiateStruct( Span span, const TupleType& struct_type, absl::Span<std::unique_ptr<ConcreteType> const> arg_types, absl::Span<std::unique_ptr<ConcreteType> const> member_types, DeduceCtx* ctx, absl::optional<absl::Span<ParametricBinding* const>> parametric_bindings) { XLS_VLOG(5) << "Struct instantiation @ " << span << " type: " << struct_type.ToString(); XLS_VLOG(5) << " arg types: " << ToString(arg_types); XLS_VLOG(5) << " member types: " << ToString(member_types); XLS_VLOG(5) << " parametric bindings: " << ToString(parametric_bindings); XLS_ASSIGN_OR_RETURN(auto instantiator, internal::StructInstantiator::Make( std::move(span), struct_type, arg_types, member_types, ctx, parametric_bindings)); return instantiator.Instantiate(); } } // namespace xls::dslx
#include <fcntl.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #ifdef USE_OPENCV #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/highgui/highgui_c.h> #include <opencv2/imgproc/imgproc.hpp> #endif // USE_OPENCV #include <stdint.h> #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <string> #include <vector> #include "caffe/common.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" const int kProtoReadBytesLimit = INT_MAX; // Max size of 2 GB minus 1 byte. namespace caffe { using google::protobuf::io::FileInputStream; using google::protobuf::io::FileOutputStream; using google::protobuf::io::ZeroCopyInputStream; using google::protobuf::io::CodedInputStream; using google::protobuf::io::ZeroCopyOutputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::Message; bool ReadProtoFromTextFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; FileInputStream* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, proto); delete input; close(fd); return success; } void WriteProtoToTextFile(const Message& proto, const char* filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); FileOutputStream* output = new FileOutputStream(fd); CHECK(google::protobuf::TextFormat::Print(proto, output)); delete output; close(fd); } bool ReadProtoFromBinaryFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; ZeroCopyInputStream* raw_input = new FileInputStream(fd); CodedInputStream* coded_input = new CodedInputStream(raw_input); coded_input->SetTotalBytesLimit(kProtoReadBytesLimit); bool success = proto->ParseFromCodedStream(coded_input); delete coded_input; delete raw_input; close(fd); return success; } void WriteProtoToBinaryFile(const Message& proto, const char* filename) { fstream output(filename, ios::out | ios::trunc | ios::binary); CHECK(proto.SerializeToOstream(&output)); } #ifdef USE_OPENCV cv::Mat ReadImageToCVMat(const string& filename, const int height, const int width, const bool is_color) { cv::Mat cv_img; int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR : CV_LOAD_IMAGE_GRAYSCALE); cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag); if (!cv_img_origin.data) { LOG(ERROR) << "Could not open or find file " << filename; return cv_img_origin; } if (height > 0 && width > 0) { cv::resize(cv_img_origin, cv_img, cv::Size(width, height)); } else { cv_img = cv_img_origin; } return cv_img; } cv::Mat ReadImageToCVMat(const string& filename, const int height, const int width) { return ReadImageToCVMat(filename, height, width, true); } cv::Mat ReadImageToCVMat(const string& filename, const bool is_color) { return ReadImageToCVMat(filename, 0, 0, is_color); } cv::Mat ReadImageToCVMat(const string& filename) { return ReadImageToCVMat(filename, 0, 0, true); } // Do the file extension and encoding match? static bool matchExt(const std::string & fn, std::string en) { size_t p = fn.rfind('.'); std::string ext = p != fn.npos ? fn.substr(p+1) : fn; std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); std::transform(en.begin(), en.end(), en.begin(), ::tolower); if ( ext == en ) return true; if ( en == "jpg" && ext == "jpeg" ) return true; return false; } bool ReadImageToDatum(const string& filename, const int label, const int height, const int width, const bool is_color, const std::string & encoding, Datum* datum) { cv::Mat cv_img = ReadImageToCVMat(filename, height, width, is_color); if (cv_img.data) { if (encoding.size()) { if ( (cv_img.channels() == 3) == is_color && !height && !width && matchExt(filename, encoding) ) return ReadFileToDatum(filename, label, datum); std::vector<uchar> buf; cv::imencode("."+encoding, cv_img, buf); datum->set_data(std::string(reinterpret_cast<char*>(&buf[0]), buf.size())); datum->set_label(label); datum->set_encoded(true); return true; } CVMatToDatum(cv_img, datum); datum->set_label(label); return true; } else { return false; } } #endif // USE_OPENCV bool ReadFileToDatum(const string& filename, const int label, Datum* datum) { std::streampos size; fstream file(filename.c_str(), ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); std::string buffer(size, ' '); file.seekg(0, ios::beg); file.read(&buffer[0], size); file.close(); datum->set_data(buffer); datum->set_label(label); datum->set_encoded(true); return true; } else { return false; } } #ifdef USE_OPENCV cv::Mat DecodeDatumToCVMatNative(const Datum& datum) { cv::Mat cv_img; CHECK(datum.encoded()) << "Datum not encoded"; const string& data = datum.data(); std::vector<char> vec_data(data.c_str(), data.c_str() + data.size()); cv_img = cv::imdecode(vec_data, -1); if (!cv_img.data) { LOG(ERROR) << "Could not decode datum "; } return cv_img; } cv::Mat DecodeDatumToCVMat(const Datum& datum, bool is_color) { cv::Mat cv_img; CHECK(datum.encoded()) << "Datum not encoded"; const string& data = datum.data(); std::vector<char> vec_data(data.c_str(), data.c_str() + data.size()); int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR : CV_LOAD_IMAGE_GRAYSCALE); cv_img = cv::imdecode(vec_data, cv_read_flag); if (!cv_img.data) { LOG(ERROR) << "Could not decode datum "; } return cv_img; } // If Datum is encoded will decoded using DecodeDatumToCVMat and CVMatToDatum // If Datum is not encoded will do nothing bool DecodeDatumNative(Datum* datum) { if (datum->encoded()) { cv::Mat cv_img = DecodeDatumToCVMatNative((*datum)); CVMatToDatum(cv_img, datum); return true; } else { return false; } } bool DecodeDatum(Datum* datum, bool is_color) { if (datum->encoded()) { cv::Mat cv_img = DecodeDatumToCVMat((*datum), is_color); CVMatToDatum(cv_img, datum); return true; } else { return false; } } void CVMatToDatum(const cv::Mat& cv_img, Datum* datum) { CHECK(cv_img.depth() == CV_8U) << "Image data type must be unsigned byte"; datum->set_channels(cv_img.channels()); datum->set_height(cv_img.rows); datum->set_width(cv_img.cols); datum->clear_data(); datum->clear_float_data(); datum->set_encoded(false); int datum_channels = datum->channels(); int datum_height = datum->height(); int datum_width = datum->width(); int datum_size = datum_channels * datum_height * datum_width; std::string buffer(datum_size, ' '); for (int h = 0; h < datum_height; ++h) { const uchar* ptr = cv_img.ptr<uchar>(h); int img_index = 0; for (int w = 0; w < datum_width; ++w) { for (int c = 0; c < datum_channels; ++c) { int datum_index = (c * datum_height + h) * datum_width + w; buffer[datum_index] = static_cast<char>(ptr[img_index++]); } } } datum->set_data(buffer); } #endif // USE_OPENCV } // namespace caffe
#ifndef _PERSISTENT_TM_RESIZABLE_HASH_MAP_H_ #define _PERSISTENT_TM_RESIZABLE_HASH_MAP_H_ #include <string> /** * An imprecise but fast random number generator */ uint64_t randomLong(uint64_t x) { x ^= x >> 12; // a x ^= x << 25; // b x ^= x >> 27; // c return x * 2685821657736338717LL; } /** * <h1> A Resizable Hash Map for PTMs </h1> */ template<typename K, typename V, typename TM, template <typename> class TMTYPE> class TMHashMap { private: struct Node { TMTYPE<K> key; TMTYPE<V> val; TMTYPE<Node*> next {nullptr}; Node(const K& k, const V& v) : key{k}, val{v} { } // Copy constructor for k and value Node() {} }; TMTYPE<uint64_t> capacity; TMTYPE<uint64_t> sizeHM = 0; //TMTYPE<double> loadFactor = 0.75; static constexpr double loadFactor = 0.75; alignas(128) TMTYPE<TMTYPE<Node*>*> buckets; // An array of pointers to Nodes public: TMHashMap(uint64_t capacity=4) : capacity{capacity} { buckets = (TMTYPE<Node*>*)TM::pmalloc(capacity*sizeof(TMTYPE<Node*>)); for (int i = 0; i < capacity; i++) buckets[i]=nullptr; } ~TMHashMap() { for(int i = 0; i < capacity; i++){ Node* node = buckets[i]; while (node!=nullptr) { Node* next = node->next; TM::tmDelete(node); node = next; } } TM::pfree(buckets); } static std::string className() { return TM::className() + "-HashMap"; } void rebuild() { uint64_t newcapacity = 2*capacity; //printf("increasing capacity to %d\n", newcapacity); TMTYPE<Node*>* newbuckets = (TMTYPE<Node*>*)TM::pmalloc(newcapacity*sizeof(TMTYPE<Node*>)); for (int i = 0; i < newcapacity; i++) newbuckets[i] = nullptr; for (int i = 0; i < capacity; i++) { Node* node = buckets[i]; while(node!=nullptr){ Node* next = node->next; auto h = std::hash<K>{}(node->key) % newcapacity; node->next = newbuckets[h]; newbuckets[h] = node; node = next; } } TM::pfree(buckets); buckets = newbuckets; capacity = newcapacity; } /* * Adds a node with a key if the key is not present, otherwise replaces the value. * If saveOldValue is set, it will set 'oldValue' to the previous value, iff there was already a mapping. * * Returns true if there was no mapping for the key, false if there was already a value and it was replaced. */ // bool innerPut(const K& key, const V& value, V& oldValue, const bool saveOldValue) { bool innerPut(const K& key, const V& value) { //printf("innerPut %d %d %f\n", sizeHM.pload(), capacity.pload(), loadFactor.pload()*capacity.pload()); if (sizeHM.pload() > capacity.pload()*loadFactor) rebuild(); auto h = std::hash<K>{}(key) % capacity; Node* node = buckets[h]; Node* prev = node; while (true) { if (node == nullptr) { Node* newnode = TM::template tmNew<Node>(key,value); if (node == prev) { buckets[h] = newnode; } else { prev->next = newnode; } sizeHM++; return true; // New insertion } if (key == node->key) return false; prev = node; node = node->next; } } /* * Removes a key and its mapping. * Saves the value in 'oldvalue' if 'saveOldValue' is set. * * Returns returns true if a matching key was found */ //bool innerRemove(const K& key, V& oldValue, const bool saveOldValue) { bool innerRemove(const K& key) { auto h = std::hash<K>{}(key) % capacity; Node* node = buckets[h]; Node* prev = node; while (true) { if (node == nullptr) return false; if (key == node->key) { // if (saveOldValue) oldValue = node->val; // Makes a copy of V if (node == prev) { buckets[h] = node->next; } else { prev->next = node->next; } sizeHM--; TM::tmDelete(node); return true; } prev = node; node = node->next; } } /* * Returns true if key is present. Saves a copy of 'value' in 'oldValue' if 'saveOldValue' is set. */ bool innerGet(const K& key, V& oldValue, const bool saveOldValue) { auto h = std::hash<K>{}(key) % capacity; Node* node = buckets[h]; while (true) { if (node == nullptr) return false; if (key == node->key) { return true; } node = node->next; } } // // Set methods for running the usual tests and benchmarks // bool bigtxn(K** udarray, int tid, int numElements){ return TM::template updateTx<bool>([this,udarray,tid,numElements] () { V notused; uint64_t seed = tid*133 + 1234567890123456781ULL; for(int i=0; i<1; i++){ // Specify number of ops per txn for OneFile seed = randomLong(seed); auto ix = (unsigned int)((seed)%numElements); if(innerRemove(*udarray[ix])){ innerPut(*udarray[ix],*udarray[ix]); } } return true; }); } /* bool bigreadtxn(K** udarray, int tid, int numElements){ return TM::template readTx<bool>([this,udarray,tid,numElements] () { V notused; uint64_t seed = tid*133 + 1234567890123456781ULL; for(int i=0; i<5; i++){ seed = randomLong(seed); auto ix = (unsigned int)((seed)%numElements); if(innerGet(*udarray[ix],notused,false)){ seed = randomLong(seed); } } return true; }); } */ // Inserts a key only if it's not already present bool add(const K& key) { return TM::template updateTx<bool>([this,key] () { V notused; return innerPut(key,key); }); } // Returns true only if the key was present bool remove(const K& key) { return TM::template updateTx<bool>([this,key] () { V notused; return innerRemove(key); }); } bool contains(const K& key) { return TM::template readTx<bool>([this,key] () { V notused; return innerGet(key,notused,false); }); } // Used only for benchmarks bool addAll(K** keys, const int size) { for (int i = 0; i < size; i++) add(*keys[i]); return true; } }; #endif /* _PERSISTENT_TM_RESIZABLE_HASH_MAP_H_ */