{"text":"\/* brushlib - The MyPaint Brush Library\n * Copyright (C) 2008 Martin Renold \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY. See the COPYING file for more details.\n *\/\n\n\/\/ surface interface required by brush.hpp\nclass Surface {\npublic:\n virtual bool draw_dab (float x, float y, \n float radius, \n float color_r, float color_g, float color_b,\n float opaque, float hardness = 0.5,\n float alpha_eraser = 1.0,\n \t\t\t float aspect_ratio = 1.0, float angle = 0.0\n ) = 0;\n\n virtual void get_color (float x, float y, \n float radius, \n float * color_r, float * color_g, float * color_b, float * color_a\n ) = 0;\n};\nbrushlib: virtual destructor\/* brushlib - The MyPaint Brush Library\n * Copyright (C) 2008 Martin Renold \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY. See the COPYING file for more details.\n *\/\n\n\/\/ surface interface required by brush.hpp\nclass Surface {\npublic:\n\n virtual ~Surface() {}\n\n virtual bool draw_dab (float x, float y, \n float radius, \n float color_r, float color_g, float color_b,\n float opaque, float hardness = 0.5,\n float alpha_eraser = 1.0,\n \t\t\t float aspect_ratio = 1.0, float angle = 0.0\n ) = 0;\n\n virtual void get_color (float x, float y, \n float radius, \n float * color_r, float * color_g, float * color_b, float * color_a\n ) = 0;\n};\n<|endoftext|>"} {"text":"\/*\n* Copyright (C) 2007-2014 German Aerospace Center (DLR\/SC)\n*\n* Created: 2014-02-10 Tobias Stollenwerk \n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\/**\n* @file\n* @brief Implementation of CPACS guide curve container handling routines\n*\/\n\n#include \"CCPACSGuideCurves.h\"\n#include \"CCPACSGuideCurve.h\"\n\n\nnamespace tigl\n{\n\nCCPACSGuideCurves::CCPACSGuideCurves(CCPACSFuselageSegment* parent, CTiglUIDManager* uidMgr)\n : generated::CPACSGuideCurves(parent, uidMgr) {}\n\nCCPACSGuideCurves::CCPACSGuideCurves(CCPACSWingSegment* parent, CTiglUIDManager* uidMgr)\n : generated::CPACSGuideCurves(parent, uidMgr) {}\n\n\nvoid CCPACSGuideCurves::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) {\n generated::CPACSGuideCurves::ReadCPACS(tixiHandle, xpath);\n\n \/\/ sort by uid as some unit tests rely on this (TODO: should we fix the tests?)\n \/\/ WARN: this destroys the order of the guide curves as stored in the CPACS file\n std::sort(m_guideCurves.begin(), m_guideCurves.end(), [](const std::unique_ptr& a, const std::unique_ptr& b) {\n return a->GetUID() < b->GetUID();\n });\n}\n\n\/\/ Returns the total count of guide curves in this configuration\nint CCPACSGuideCurves::GetGuideCurveCount() const\n{\n return static_cast(m_guideCurves.size());\n}\n\n\/\/ Returns the guide curve for a given index\nconst CCPACSGuideCurve& CCPACSGuideCurves::GetGuideCurve(int index) const\n{\n index--;\n if (index < 0 || index >= GetGuideCurveCount()) {\n throw CTiglError(\"Invalid index in CCPACSGuideCurves::GetGuideCurve\", TIGL_INDEX_ERROR);\n }\n return *m_guideCurves[index];\n}\n\n\/\/ Returns the guide curve for a given index\nCCPACSGuideCurve& CCPACSGuideCurves::GetGuideCurve(int index)\n{\n return const_cast(static_cast(this)->GetGuideCurve(index));\n}\n\n\/\/ Returns the guide curve for a given uid.\nconst CCPACSGuideCurve& CCPACSGuideCurves::GetGuideCurve(std::string uid) const\n{\n for (std::size_t i = 0; i < m_guideCurves.size(); i++) {\n if (m_guideCurves[i]->GetUID() == uid) {\n return *m_guideCurves[i];\n }\n }\n throw CTiglError(\"CCPACSGuideCurve::GetGuideCurve: Guide curve \\\"\" + uid + \"\\\" not found in CPACS file!\", TIGL_UID_ERROR);\n}\n\n\/\/ Returns the guide curve for a given uid.\nCCPACSGuideCurve& CCPACSGuideCurves::GetGuideCurve(std::string uid)\n{\n return const_cast(static_cast(this)->GetGuideCurve(uid));\n}\n\n\/\/ Returns the guide curve for a given uid.\nbool CCPACSGuideCurves::GuideCurveExists(std::string uid) const\n{\n for (std::size_t i = 0; i < m_guideCurves.size(); i++) {\n if (m_guideCurves[i]->GetUID() == uid) {\n return true;\n }\n }\n return false;\n}\n\nstd::vector CCPACSGuideCurves::GetRelativeCircumferenceParameters() const\n{\n std::vector relCircs;\n for (int iguide = 1; iguide <= GetGuideCurveCount(); ++iguide) {\n const CCPACSGuideCurve* root = GetGuideCurve(iguide).GetRootCurve();\n relCircs.push_back(*root->GetFromRelativeCircumference_choice2());\n }\n\n std::sort(relCircs.begin(), relCircs.end());\n\n double eps = 1e-10;\n if ( relCircs.back() < 1.0 - eps ) {\n relCircs.push_back(1.0);\n }\n\n return relCircs;\n}\n\nvoid CCPACSGuideCurves::GetRelativeCircumferenceRange(double relCirc,\n double& relCircStart,\n double& relCircEnd,\n int& idx) const\n{\n std::vector relCircs = GetRelativeCircumferenceParameters();\n\n \/\/ probably best to assert for performance reasons...\n assert( relCircs.size() > 0 );\n assert( relCirc >= relCircs[0] );\n assert( relCirc <= relCircs.back() );\n\n for (size_t i = 1; i < relCircs.size(); ++i ) {\n if (relCircs[i] >= relCirc ) {\n relCircStart = relCircs[i-1];\n relCircEnd = relCircs[i];\n idx = static_cast(i-1);\n break;\n }\n }\n}\n\n} \/\/ end namespace tigl\n\n\nChanged code to comply with tolerance at other places\/*\n* Copyright (C) 2007-2014 German Aerospace Center (DLR\/SC)\n*\n* Created: 2014-02-10 Tobias Stollenwerk \n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\/**\n* @file\n* @brief Implementation of CPACS guide curve container handling routines\n*\/\n\n#include \"CCPACSGuideCurves.h\"\n#include \"CCPACSGuideCurve.h\"\n\n\nnamespace tigl\n{\n\nCCPACSGuideCurves::CCPACSGuideCurves(CCPACSFuselageSegment* parent, CTiglUIDManager* uidMgr)\n : generated::CPACSGuideCurves(parent, uidMgr) {}\n\nCCPACSGuideCurves::CCPACSGuideCurves(CCPACSWingSegment* parent, CTiglUIDManager* uidMgr)\n : generated::CPACSGuideCurves(parent, uidMgr) {}\n\n\nvoid CCPACSGuideCurves::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) {\n generated::CPACSGuideCurves::ReadCPACS(tixiHandle, xpath);\n\n \/\/ sort by uid as some unit tests rely on this (TODO: should we fix the tests?)\n \/\/ WARN: this destroys the order of the guide curves as stored in the CPACS file\n std::sort(m_guideCurves.begin(), m_guideCurves.end(), [](const std::unique_ptr& a, const std::unique_ptr& b) {\n return a->GetUID() < b->GetUID();\n });\n}\n\n\/\/ Returns the total count of guide curves in this configuration\nint CCPACSGuideCurves::GetGuideCurveCount() const\n{\n return static_cast(m_guideCurves.size());\n}\n\n\/\/ Returns the guide curve for a given index\nconst CCPACSGuideCurve& CCPACSGuideCurves::GetGuideCurve(int index) const\n{\n index--;\n if (index < 0 || index >= GetGuideCurveCount()) {\n throw CTiglError(\"Invalid index in CCPACSGuideCurves::GetGuideCurve\", TIGL_INDEX_ERROR);\n }\n return *m_guideCurves[index];\n}\n\n\/\/ Returns the guide curve for a given index\nCCPACSGuideCurve& CCPACSGuideCurves::GetGuideCurve(int index)\n{\n return const_cast(static_cast(this)->GetGuideCurve(index));\n}\n\n\/\/ Returns the guide curve for a given uid.\nconst CCPACSGuideCurve& CCPACSGuideCurves::GetGuideCurve(std::string uid) const\n{\n for (std::size_t i = 0; i < m_guideCurves.size(); i++) {\n if (m_guideCurves[i]->GetUID() == uid) {\n return *m_guideCurves[i];\n }\n }\n throw CTiglError(\"CCPACSGuideCurve::GetGuideCurve: Guide curve \\\"\" + uid + \"\\\" not found in CPACS file!\", TIGL_UID_ERROR);\n}\n\n\/\/ Returns the guide curve for a given uid.\nCCPACSGuideCurve& CCPACSGuideCurves::GetGuideCurve(std::string uid)\n{\n return const_cast(static_cast(this)->GetGuideCurve(uid));\n}\n\n\/\/ Returns the guide curve for a given uid.\nbool CCPACSGuideCurves::GuideCurveExists(std::string uid) const\n{\n for (std::size_t i = 0; i < m_guideCurves.size(); i++) {\n if (m_guideCurves[i]->GetUID() == uid) {\n return true;\n }\n }\n return false;\n}\n\nstd::vector CCPACSGuideCurves::GetRelativeCircumferenceParameters() const\n{\n std::vector relCircs;\n for (int iguide = 1; iguide <= GetGuideCurveCount(); ++iguide) {\n const CCPACSGuideCurve* root = GetGuideCurve(iguide).GetRootCurve();\n relCircs.push_back(*root->GetFromRelativeCircumference_choice2());\n }\n\n std::sort(relCircs.begin(), relCircs.end());\n\n if (std::abs(relCircs.back() - 1.0) >= 1e-3 ) {\n relCircs.push_back(1.0);\n }\n\n return relCircs;\n}\n\nvoid CCPACSGuideCurves::GetRelativeCircumferenceRange(double relCirc,\n double& relCircStart,\n double& relCircEnd,\n int& idx) const\n{\n std::vector relCircs = GetRelativeCircumferenceParameters();\n\n \/\/ probably best to assert for performance reasons...\n assert( relCircs.size() > 0 );\n assert( relCirc >= relCircs[0] );\n assert( relCirc <= relCircs.back() );\n\n for (size_t i = 1; i < relCircs.size(); ++i ) {\n if (relCircs[i] >= relCirc ) {\n relCircStart = relCircs[i-1];\n relCircEnd = relCircs[i];\n idx = static_cast(i-1);\n break;\n }\n }\n}\n\n} \/\/ end namespace tigl\n\n\n<|endoftext|>"} {"text":"#include \"Variant.h\"\n#include \"split.h\"\n#include \"cdflib.hpp\"\n#include \"pdflib.hpp\"\n#include \"var.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace vcf;\nvoid printVersion(void){\n\t cerr << \"INFO: version 1.1.0 ; date: April 2014 ; author: Zev Kronenberg; email : zev.kronenberg@utah.edu \" << endl;\n\t exit(1);\n\n}\n\nvoid printHelp(void){\n cerr << endl << endl;\n cerr << \"INFO: help\" << endl;\n cerr << \"INFO: description:\" << endl;\n cerr << \" iHS calculates the integrated ratio of haplotype decay between the reference and non-reference allele. \" << endl;\n cerr << \" This implementation of iHS integrates over a SNP index, NOT a physical distance or genetic distance. \" << endl << endl;\n\n cerr << \"Output : 4 columns : \" << endl;\n cerr << \" 1. seqid \" << endl;\n cerr << \" 2. position \" << endl;\n cerr << \" 3. target allele frequency \" << endl;\n cerr << \" 4. integrated EHH (alternative) \" << endl;\n cerr << \" 5. integrated EHH (reference) \" << endl;\n cerr << \" 6. iHS log(iEHHalt\/iEHHref) \" << endl << endl;\n\n cerr << \"INFO: iHS --target 0,1,2,3,4,5,6,7 --file my.phased.vcf --region chr1:1-1000 \" << endl << endl;\n \n cerr << \"INFO: required: t,target -- argument: a zero base comma separated list of target individuals corrisponding to VCF columns \" << endl;\n cerr << \"INFO: required: f,file -- argument: proper formatted and phased VCF. \" << endl;\n cerr << \"INFO: required: y,type -- argument: genotype likelihood format: PL,GL,GP \" << endl;\n cerr << \"INFO: optional: r,region -- argument: a tabix compliant genomic range : \\\"seqid:start-end\\\" or \\\"seqid\\\" \" << endl; \n cerr << endl;\n \n printVersion();\n\n exit(1);\n}\n\nvoid clearHaplotypes(string haplotypes[][2], int ntarget){\n for(int i= 0; i < ntarget; i++){\n haplotypes[i][0].clear();\n haplotypes[i][1].clear();\n }\n}\n\nvoid loadIndices(map & index, string set){\n \n vector indviduals = split(set, \",\");\n vector::iterator it = indviduals.begin();\n \n for(; it != indviduals.end(); it++){\n index[ atoi( (*it).c_str() ) ] = 1;\n }\n}\n\nvoid calc(string haplotypes[][2], int nhaps, vector afs, vector pos, vector & target, vector & background, string seqid){\n\n \/\/cerr << \"about to calc\" << endl;\n \/\/cerr << \"nhap: \" << nhaps << endl;\n\n for(int snp = 0; snp < haplotypes[0][0].length(); snp++){\n \n double ehhA = 1;\n double ehhR = 1;\n\n double iHSA = 1;\n double iHSR = 1;\n\n int start = snp;\n int end = snp;\n int core = snp; \n\n while( ehhA > 0.05 && ehhR > 0.05 ) {\n \n start -= 1;\n end += 1;\n \n if(start == -1){\n\tbreak;\n }\n if(end == haplotypes[0][0].length() - 1){\n\tbreak;\n }\n \n map targetH;\n\n double sumrT = 0;\n double sumaT = 0;\n double nrefT = 0;\n double naltT = 0;\n\n for(int i = 0; i < nhaps; i++){\n\ttargetH[ haplotypes[i][0].substr(start, (end - start)) ]++;\n\ttargetH[ haplotypes[i][1].substr(start, (end - start)) ]++;\n } \n for( map::iterator th = targetH.begin(); th != targetH.end(); th++){ \t\n\tif( (*th).first.substr((end-start)\/2, 1) == \"1\"){ \n\t sumaT += r8_choose(th->second, 2); \n\t naltT += th->second;\n\t}\n\telse{\n\t sumrT += r8_choose(th->second, 2); \n\t nrefT += th->second;\n\t}\n }\n\n ehhA = sumaT \/ (r8_choose(naltT, 2));\n ehhR = sumrT \/ (r8_choose(nrefT, 2));\n\n iHSA += ehhA;\n iHSR += ehhR;\n } \n if(isnan(iHSA) || isnan(iHSR)){\n continue;\n }\n cout << seqid << \"\\t\" << pos[snp] << \"\\t\" << afs[snp] << \"\\t\" << iHSA << \"\\t\" << iHSR << \"\\t\" << log(iHSA\/iHSR) << endl;\n } \n}\n\ndouble EHH(string haplotypes[][2], int nhaps){\n\n map hapcounts;\n\n for(int i = 0; i < nhaps; i++){\n hapcounts[ haplotypes[i][0] ]++;\n hapcounts[ haplotypes[i][1] ]++;\n }\n\n double sum = 0;\n double nh = 0;\n\n for( map::iterator it = hapcounts.begin(); it != hapcounts.end(); it++){\n nh += it->second; \n sum += r8_choose(it->second, 2);\n }\n\n double max = (sum \/ r8_choose(nh, 2));\n \n return max;\n\n}\n\nvoid loadPhased(string haplotypes[][2], genotype * pop, int ntarget){\n \n int indIndex = 0;\n\n for(vector::iterator ind = pop->gts.begin(); ind != pop->gts.end(); ind++){\n string g = (*ind);\n vector< string > gs = split(g, \"|\");\n haplotypes[indIndex][0].append(gs[0]);\n haplotypes[indIndex][1].append(gs[1]);\n indIndex += 1;\n }\n}\n\nint main(int argc, char** argv) {\n\n \/\/ set the random seed for MCMC\n\n srand((unsigned)time(NULL));\n\n \/\/ the filename\n\n string filename = \"NA\";\n\n \/\/ set region to scaffold\n\n string region = \"NA\"; \n\n \/\/ using vcflib; thanks to Erik Garrison \n\n VariantCallFile variantFile;\n\n \/\/ zero based index for the target and background indivudals \n \n map it, ib;\n \n \/\/ deltaaf is the difference of allele frequency we bother to look at \n\n \/\/ ancestral state is set to zero by default\n\n\n int counts = 0;\n \n \/\/ phased \n\n int phased = 0;\n\n string type = \"NA\";\n\n const struct option longopts[] = \n {\n\t{\"version\" , 0, 0, 'v'},\n\t{\"help\" , 0, 0, 'h'},\n {\"file\" , 1, 0, 'f'},\n\t{\"target\" , 1, 0, 't'},\n\t{\"region\" , 1, 0, 'r'},\n\t{\"type\" , 1, 0, 'y'},\n\t{0,0,0,0}\n };\n\n int findex;\n int iarg=0;\n\n while(iarg != -1)\n {\n\tiarg = getopt_long(argc, argv, \"y:r:d:t:b:f:hv\", longopts, &findex);\n\t\n\tswitch (iarg)\n\t {\n\t case 'h':\n\t printHelp();\n\t case 'v':\n\t printVersion();\n\t case 'y':\n\t type = optarg;\n\t break;\n\t case 't':\n\t loadIndices(it, optarg);\n\t cerr << \"INFO: there are \" << it.size() << \" individuals in the target\" << endl;\n\t cerr << \"INFO: target ids: \" << optarg << endl;\n\t break;\n\t case 'f':\n\t cerr << \"INFO: file: \" << optarg << endl;\n\t filename = optarg;\n\t break;\n\t case 'r':\n cerr << \"INFO: set seqid region to : \" << optarg << endl;\n\t region = optarg; \n\t break;\n\t default:\n\t break;\n\t }\n }\n\n map okayGenotypeLikelihoods;\n okayGenotypeLikelihoods[\"PL\"] = 1;\n okayGenotypeLikelihoods[\"GL\"] = 1;\n okayGenotypeLikelihoods[\"GP\"] = 1;\n okayGenotypeLikelihoods[\"GT\"] = 1;\n \n\n if(type == \"NA\"){\n cerr << \"FATAL: failed to specify genotype likelihood format : PL or GL\" << endl;\n printHelp();\n return 1;\n }\n if(okayGenotypeLikelihoods.find(type) == okayGenotypeLikelihoods.end()){\n cerr << \"FATAL: genotype likelihood is incorrectly formatted, only use: PL or GL\" << endl;\n printHelp();\n return 1;\n }\n\n if(filename == \"NA\"){\n cerr << \"FATAL: did not specify a file\" << endl;\n printHelp();\n return(1);\n }\n\n if(it.size() < 2){\n cerr << \"FATAL: target option is required -- or -- less than two individuals in target\\n\";\n printHelp();\n return(1);\n }\n\n variantFile.open(filename);\n \n if(region != \"NA\"){\n if(! variantFile.setRegion(region)){\n\tcerr <<\"FATAL: unable to set region\" << endl;\n\treturn 1;\n }\n }\n\n \n if (!variantFile.is_open()) {\n return 1;\n }\n \n Variant var(variantFile);\n\n vector target_h, background_h;\n\n\n int index = 0; \n int indexi = 0;\n\n\n vector samples = variantFile.sampleNames;\n int nsamples = samples.size();\n\n for(vector::iterator samp = samples.begin(); samp != samples.end(); samp++){\n \n string sampleName = (*samp);\n \n if(it.find(index) != it.end() ){\n\ttarget_h.push_back(indexi);\n\tindexi++;\n }\n index++;\n }\n \n \n \/\/ cerr << \"n in target : \" << target_h.size() << endl;\n\n vector positions;\n \n vector afs;\n\n string haplotypes [target_h.size()][2]; \n \n string currentSeqid = \"NA\";\n \n \/\/ cerr << \"about to loop variants\" << endl;\n\n while (variantFile.getNextVariant(var)) {\n\n if(!var.isPhased()){\n\tcerr << \"FATAL: Found an unphased variant. All genotypes must be phased!\" << endl;\n\treturn(1);\n }\n\n if(var.alt.size() > 1){\n\tcontinue;\n }\n\n if(currentSeqid != var.sequenceName){\n\tif(haplotypes[0][0].length() > 10){\n\t calc(haplotypes, target_h.size(), afs, positions, target_h, background_h, currentSeqid);\n\t}\n\tclearHaplotypes(haplotypes, target_h.size());\n\tpositions.clear();\n\tcurrentSeqid = var.sequenceName;\n\tafs.clear();\n }\n\n\n vector < map< string, vector > > target, background, total;\n \n int sindex = 0;\n \n for(int nsamp = 0; nsamp < nsamples; nsamp++){\n\n\tmap > sample = var.samples[ samples[nsamp]];\n\t\n\tif(it.find(sindex) != it.end() ){\n\t target.push_back(sample);\n\t}\t\n\tsindex += 1;\n }\n \n genotype * populationTarget ;\n\n \n if(type == \"PL\"){\n\tpopulationTarget = new pl();\n }\n if(type == \"GL\"){\n\tpopulationTarget = new gl();\n }\n if(type == \"GP\"){\n\tpopulationTarget = new gp();\n }\n if(type == \"GT\"){\n\tpopulationTarget = new gt();\n }\n\n populationTarget->loadPop(target, var.sequenceName, var.position);\n \n if(populationTarget->af == 1 || populationTarget->af == 0){\n\tdelete populationTarget;\n\tcontinue;\n }\n positions.push_back(var.position);\n afs.push_back(populationTarget->af);\n loadPhased(haplotypes, populationTarget, populationTarget->gts.size()); \n \n populationTarget = NULL;\n delete populationTarget;\n }\n \n calc(haplotypes, target_h.size(), afs, positions, target_h, background_h, currentSeqid);\n \n return 0;\t\t \n}\nupdated iHS#include \"Variant.h\"\n#include \"split.h\"\n#include \"cdflib.hpp\"\n#include \"pdflib.hpp\"\n#include \"var.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace vcf;\nvoid printVersion(void){\n\t cerr << \"INFO: version 1.1.0 ; date: April 2014 ; author: Zev Kronenberg; email : zev.kronenberg@utah.edu \" << endl;\n\t exit(1);\n\n}\n\nvoid printHelp(void){\n cerr << endl << endl;\n cerr << \"INFO: help\" << endl;\n cerr << \"INFO: description:\" << endl;\n cerr << \" iHS calculates the integrated ratio of haplotype decay between the reference and non-reference allele. \" << endl;\n cerr << \" This implementation of iHS integrates over a SNP index, NOT a physical distance or genetic distance. \" << endl << endl;\n\n cerr << \"Output : 4 columns : \" << endl;\n cerr << \" 1. seqid \" << endl;\n cerr << \" 2. position \" << endl;\n cerr << \" 3. target allele frequency \" << endl;\n cerr << \" 4. integrated EHH (alternative) \" << endl;\n cerr << \" 5. integrated EHH (reference) \" << endl;\n cerr << \" 6. iHS log(iEHHalt\/iEHHref) \" << endl << endl;\n\n cerr << \"INFO: iHS --target 0,1,2,3,4,5,6,7 --file my.phased.vcf --region chr1:1-1000 \" << endl << endl;\n \n cerr << \"INFO: required: t,target -- argument: a zero base comma separated list of target individuals corrisponding to VCF columns \" << endl;\n cerr << \"INFO: required: f,file -- argument: proper formatted and phased VCF. \" << endl;\n cerr << \"INFO: required: y,type -- argument: genotype likelihood format: PL,GL,GP \" << endl;\n cerr << \"INFO: optional: r,region -- argument: a tabix compliant genomic range : \\\"seqid:start-end\\\" or \\\"seqid\\\" \" << endl; \n cerr << endl;\n \n printVersion();\n\n exit(1);\n}\n\nvoid clearHaplotypes(string haplotypes[][2], int ntarget){\n for(int i= 0; i < ntarget; i++){\n haplotypes[i][0].clear();\n haplotypes[i][1].clear();\n }\n}\n\nvoid loadIndices(map & index, string set){\n \n vector indviduals = split(set, \",\");\n vector::iterator it = indviduals.begin();\n \n for(; it != indviduals.end(); it++){\n index[ atoi( (*it).c_str() ) ] = 1;\n }\n}\n\nvoid calc(string haplotypes[][2], int nhaps, vector afs, vector pos, vector & target, vector & background, string seqid){\n\n \/\/cerr << \"about to calc\" << endl;\n \/\/cerr << \"nhap: \" << nhaps << endl;\n\n for(int snp = 0; snp < haplotypes[0][0].length(); snp++){\n \n int breakflag = 1;\n int count = 0;\n\n double ehhA = 1;\n double ehhR = 1;\n\n double iHSA = 0;\n double iHSR = 0;\n\n int start = snp;\n int end = snp;\n int core = snp; \n\n while( breakflag ) {\n \n if(count > 0){\n\tstart -= 1;\n\tend += 1;\n }\n if(start == -1){\n\tbreak;\n }\n if(end == haplotypes[0][0].length() - 1){\n\tbreak;\n }\n count += 1;\n\n map targetH;\n\n double sumrT = 0;\n double sumaT = 0;\n double nrefT = 0;\n double naltT = 0;\n\n for(int i = 0; i < nhaps; i++){\n\ttargetH[ haplotypes[i][0].substr(start, (end - start)) ]++;\n\ttargetH[ haplotypes[i][1].substr(start, (end - start)) ]++;\n } \n for( map::iterator th = targetH.begin(); th != targetH.end(); th++){ \n\tif( (*th).first.substr((end-start)\/2, 1) == \"1\"){ \n\t sumaT += r8_choose(th->second, 2); \n\t naltT += th->second;\n\t}\n\telse{\n\t sumrT += r8_choose(th->second, 2); \n\t nrefT += th->second;\n\t}\n }\n cerr << pos[snp] << \" \" << naltT << \" \" << nrefT << endl; \n \n double ehhAC = sumaT \/ (r8_choose(naltT, 2));\n double ehhRC = sumrT \/ (r8_choose(nrefT, 2));\n\n if(count == 1){\n\tehhA = ehhAC;\n\tehhR = ehhRC;\n\tcontinue;\n }\n\n iHSA += (ehhA + ehhAC) \/ 2;\n iHSR += (ehhR + ehhRC) \/ 2;\n\n ehhA = ehhAC;\n ehhR = ehhRC;\n\n if(ehhA < 0.05 && ehhR < 0.05){\n\tbreakflag = 0;\n }\n } \n\n cout << seqid << \"\\t\" << pos[snp] << \"\\t\" << afs[snp] << \"\\t\" << iHSA << \"\\t\" << iHSR << \"\\t\" << log(iHSA\/iHSR) << endl;\n } \n}\n\ndouble EHH(string haplotypes[][2], int nhaps){\n\n map hapcounts;\n\n for(int i = 0; i < nhaps; i++){\n hapcounts[ haplotypes[i][0] ]++;\n hapcounts[ haplotypes[i][1] ]++;\n }\n\n double sum = 0;\n double nh = 0;\n\n for( map::iterator it = hapcounts.begin(); it != hapcounts.end(); it++){\n nh += it->second; \n sum += r8_choose(it->second, 2);\n }\n\n double max = (sum \/ r8_choose(nh, 2));\n \n return max;\n\n}\n\nvoid loadPhased(string haplotypes[][2], genotype * pop, int ntarget){\n \n int indIndex = 0;\n\n for(vector::iterator ind = pop->gts.begin(); ind != pop->gts.end(); ind++){\n string g = (*ind);\n vector< string > gs = split(g, \"|\");\n haplotypes[indIndex][0].append(gs[0]);\n haplotypes[indIndex][1].append(gs[1]);\n indIndex += 1;\n }\n}\n\nint main(int argc, char** argv) {\n\n \/\/ set the random seed for MCMC\n\n srand((unsigned)time(NULL));\n\n \/\/ the filename\n\n string filename = \"NA\";\n\n \/\/ set region to scaffold\n\n string region = \"NA\"; \n\n \/\/ using vcflib; thanks to Erik Garrison \n\n VariantCallFile variantFile;\n\n \/\/ zero based index for the target and background indivudals \n \n map it, ib;\n \n \/\/ deltaaf is the difference of allele frequency we bother to look at \n\n \/\/ ancestral state is set to zero by default\n\n\n int counts = 0;\n \n \/\/ phased \n\n int phased = 0;\n\n string type = \"NA\";\n\n const struct option longopts[] = \n {\n\t{\"version\" , 0, 0, 'v'},\n\t{\"help\" , 0, 0, 'h'},\n {\"file\" , 1, 0, 'f'},\n\t{\"target\" , 1, 0, 't'},\n\t{\"region\" , 1, 0, 'r'},\n\t{\"type\" , 1, 0, 'y'},\n\t{0,0,0,0}\n };\n\n int findex;\n int iarg=0;\n\n while(iarg != -1)\n {\n\tiarg = getopt_long(argc, argv, \"y:r:d:t:b:f:hv\", longopts, &findex);\n\t\n\tswitch (iarg)\n\t {\n\t case 'h':\n\t printHelp();\n\t case 'v':\n\t printVersion();\n\t case 'y':\n\t type = optarg;\n\t break;\n\t case 't':\n\t loadIndices(it, optarg);\n\t cerr << \"INFO: there are \" << it.size() << \" individuals in the target\" << endl;\n\t cerr << \"INFO: target ids: \" << optarg << endl;\n\t break;\n\t case 'f':\n\t cerr << \"INFO: file: \" << optarg << endl;\n\t filename = optarg;\n\t break;\n\t case 'r':\n cerr << \"INFO: set seqid region to : \" << optarg << endl;\n\t region = optarg; \n\t break;\n\t default:\n\t break;\n\t }\n }\n\n map okayGenotypeLikelihoods;\n okayGenotypeLikelihoods[\"PL\"] = 1;\n okayGenotypeLikelihoods[\"GL\"] = 1;\n okayGenotypeLikelihoods[\"GP\"] = 1;\n okayGenotypeLikelihoods[\"GT\"] = 1;\n \n\n if(type == \"NA\"){\n cerr << \"FATAL: failed to specify genotype likelihood format : PL or GL\" << endl;\n printHelp();\n return 1;\n }\n if(okayGenotypeLikelihoods.find(type) == okayGenotypeLikelihoods.end()){\n cerr << \"FATAL: genotype likelihood is incorrectly formatted, only use: PL or GL\" << endl;\n printHelp();\n return 1;\n }\n\n if(filename == \"NA\"){\n cerr << \"FATAL: did not specify a file\" << endl;\n printHelp();\n return(1);\n }\n\n if(it.size() < 2){\n cerr << \"FATAL: target option is required -- or -- less than two individuals in target\\n\";\n printHelp();\n return(1);\n }\n\n variantFile.open(filename);\n \n if(region != \"NA\"){\n if(! variantFile.setRegion(region)){\n\tcerr <<\"FATAL: unable to set region\" << endl;\n\treturn 1;\n }\n }\n\n \n if (!variantFile.is_open()) {\n return 1;\n }\n \n Variant var(variantFile);\n\n vector target_h, background_h;\n\n\n int index = 0; \n int indexi = 0;\n\n\n vector samples = variantFile.sampleNames;\n int nsamples = samples.size();\n\n for(vector::iterator samp = samples.begin(); samp != samples.end(); samp++){\n \n string sampleName = (*samp);\n \n if(it.find(index) != it.end() ){\n\ttarget_h.push_back(indexi);\n\tindexi++;\n }\n index++;\n }\n \n \n \/\/ cerr << \"n in target : \" << target_h.size() << endl;\n\n vector positions;\n \n vector afs;\n\n string haplotypes [target_h.size()][2]; \n \n string currentSeqid = \"NA\";\n \n \/\/ cerr << \"about to loop variants\" << endl;\n\n while (variantFile.getNextVariant(var)) {\n\n if(!var.isPhased()){\n\tcerr << \"FATAL: Found an unphased variant. All genotypes must be phased!\" << endl;\n\treturn(1);\n }\n\n if(var.alt.size() > 1){\n\tcontinue;\n }\n\n if(currentSeqid != var.sequenceName){\n\tif(haplotypes[0][0].length() > 10){\n\t calc(haplotypes, target_h.size(), afs, positions, target_h, background_h, currentSeqid);\n\t}\n\tclearHaplotypes(haplotypes, target_h.size());\n\tpositions.clear();\n\tcurrentSeqid = var.sequenceName;\n\tafs.clear();\n }\n\n\n vector < map< string, vector > > target, background, total;\n \n int sindex = 0;\n \n for(int nsamp = 0; nsamp < nsamples; nsamp++){\n\n\tmap > sample = var.samples[ samples[nsamp]];\n\t\n\tif(it.find(sindex) != it.end() ){\n\t target.push_back(sample);\n\t}\t\n\tsindex += 1;\n }\n \n genotype * populationTarget ;\n\n \n if(type == \"PL\"){\n\tpopulationTarget = new pl();\n }\n if(type == \"GL\"){\n\tpopulationTarget = new gl();\n }\n if(type == \"GP\"){\n\tpopulationTarget = new gp();\n }\n if(type == \"GT\"){\n\tpopulationTarget = new gt();\n }\n\n populationTarget->loadPop(target, var.sequenceName, var.position);\n \n if(populationTarget->af > 0.95 || populationTarget->af < 0.05){\n\tdelete populationTarget;\n\tcontinue;\n }\n positions.push_back(var.position);\n afs.push_back(populationTarget->af);\n loadPhased(haplotypes, populationTarget, populationTarget->gts.size()); \n \n populationTarget = NULL;\n delete populationTarget;\n }\n \n calc(haplotypes, target_h.size(), afs, positions, target_h, background_h, currentSeqid);\n \n return 0;\t\t \n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct SetundefWorker\n{\n\tint next_bit_mode;\n\tuint32_t next_bit_state;\n\n\tRTLIL::State next_bit()\n\t{\n\t\tif (next_bit_mode == 0)\n\t\t\treturn RTLIL::State::S0;\n\n\t\tif (next_bit_mode == 1)\n\t\t\treturn RTLIL::State::S1;\n\n\t\t\/\/ xorshift32\n\t\tnext_bit_state ^= next_bit_state << 13;\n\t\tnext_bit_state ^= next_bit_state >> 17;\n\t\tnext_bit_state ^= next_bit_state << 5;\n\t\tlog_assert(next_bit_state != 0);\n\n\t\treturn ((next_bit_state >> (next_bit_state & 15)) & 16) ? RTLIL::State::S0 : RTLIL::State::S1;\n\t}\n\n\tvoid operator()(RTLIL::SigSpec &sig)\n\t{\n\t\tfor (auto &bit : sig)\n\t\t\tif (bit.wire == NULL && bit.data > RTLIL::State::S1)\n\t\t\t\tbit = next_bit();\n\t}\n};\n\nstruct SetundefPass : public Pass {\n\tSetundefPass() : Pass(\"setundef\", \"replace undef values with defined constants\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" setundef [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command replaced undef (x) constants with defined (0\/1) constants.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -undriven\\n\");\n\t\tlog(\" also set undriven nets to constant values\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -zero\\n\");\n\t\tlog(\" replace with bits cleared (0)\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -one\\n\");\n\t\tlog(\" replace with bits set (1)\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -random \\n\");\n\t\tlog(\" replace with random bits using the specified integer als seed\\n\");\n\t\tlog(\" value for the random number generator.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -init\\n\");\n\t\tlog(\" also create\/update init values for flip-flops\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\tbool got_value = false;\n\t\tbool undriven_mode = false;\n\t\tbool init_mode = false;\n\t\tSetundefWorker worker;\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-undriven\") {\n\t\t\t\tundriven_mode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-zero\") {\n\t\t\t\tgot_value = true;\n\t\t\t\tworker.next_bit_mode = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-one\") {\n\t\t\t\tgot_value = true;\n\t\t\t\tworker.next_bit_mode = 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-init\") {\n\t\t\t\tinit_mode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-random\" && !got_value && argidx+1 < args.size()) {\n\t\t\t\tgot_value = true;\n\t\t\t\tworker.next_bit_mode = 2;\n\t\t\t\tworker.next_bit_state = atoi(args[++argidx].c_str()) + 1;\n\t\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t\t\tworker.next_bit();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tif (!got_value)\n\t\t\tlog_cmd_error(\"One of the options -zero, -one, or -random must be specified.\\n\");\n\n\t\tfor (auto module : design->selected_modules())\n\t\t{\n\t\t\tif (undriven_mode)\n\t\t\t{\n\t\t\t\tif (!module->processes.empty())\n\t\t\t\t\tlog_error(\"The 'setundef' command can't operate in -undriven mode on modules with processes. Run 'proc' first.\\n\");\n\n\t\t\t\tSigMap sigmap(module);\n\t\t\t\tSigPool undriven_signals;\n\n\t\t\t\tfor (auto &it : module->wires_)\n\t\t\t\t\tif (!it.second->port_input)\n\t\t\t\t\t\tundriven_signals.add(sigmap(it.second));\n\n\t\t\t\tCellTypes ct(design);\n\t\t\t\tfor (auto &it : module->cells_)\n\t\t\t\tfor (auto &conn : it.second->connections())\n\t\t\t\t\tif (!ct.cell_known(it.second->type) || ct.cell_output(it.second->type, conn.first))\n\t\t\t\t\t\tundriven_signals.del(sigmap(conn.second));\n\n\t\t\t\tRTLIL::SigSpec sig = undriven_signals.export_all();\n\t\t\t\tfor (auto &c : sig.chunks()) {\n\t\t\t\t\tRTLIL::SigSpec bits;\n\t\t\t\t\tfor (int i = 0; i < c.width; i++)\n\t\t\t\t\t\tbits.append(worker.next_bit());\n\t\t\t\t\tmodule->connect(RTLIL::SigSig(c, bits));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (init_mode)\n\t\t\t{\n\t\t\t\tSigMap sigmap(module);\n\t\t\t\tpool ffbits;\n\t\t\t\tpool initwires;\n\n\t\t\t\tpool fftypes;\n\t\t\t\tfftypes.insert(\"$dff\");\n\t\t\t\tfftypes.insert(\"$dffe\");\n\t\t\t\tfftypes.insert(\"$dffsr\");\n\t\t\t\tfftypes.insert(\"$adff\");\n\n\t\t\t\tstd::vector list_np = {'N', 'P'}, list_01 = {'0', '1'};\n\n\t\t\t\tfor (auto c1 : list_np)\n\t\t\t\t\tfftypes.insert(stringf(\"$_DFF_%c_\", c1));\n\n\t\t\t\tfor (auto c1 : list_np)\n\t\t\t\tfor (auto c2 : list_np)\n\t\t\t\t\tfftypes.insert(stringf(\"$_DFFE_%c%c_\", c1, c2));\n\n\t\t\t\tfor (auto c1 : list_np)\n\t\t\t\tfor (auto c2 : list_np)\n\t\t\t\tfor (auto c3 : list_01)\n\t\t\t\t\tfftypes.insert(stringf(\"$_DFF_%c%c%c_\", c1, c2, c3));\n\n\t\t\t\tfor (auto c1 : list_np)\n\t\t\t\tfor (auto c2 : list_np)\n\t\t\t\tfor (auto c3 : list_np)\n\t\t\t\t\tfftypes.insert(stringf(\"$_DFFSR_%c%c%c_\", c1, c2, c3));\n\n\t\t\t\tfor (auto cell : module->cells())\n\t\t\t\t{\n\t\t\t\t\tif (!fftypes.count(cell->type))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tfor (auto bit : sigmap(cell->getPort(\"\\\\Q\")))\n\t\t\t\t\t\tffbits.insert(bit);\n\t\t\t\t}\n\n\t\t\t\tfor (auto wire : module->wires())\n\t\t\t\t{\n\t\t\t\t\tif (!wire->attributes.count(\"\\\\init\"))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\t\tffbits.erase(bit);\n\n\t\t\t\t\tinitwires.insert(wire);\n\t\t\t\t}\n\n\t\t\t\tfor (int wire_types = 0; wire_types < 2; wire_types++)\n\t\t\t\t\tfor (auto wire : module->wires())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (wire->name[0] == (wire_types ? '\\\\' : '$'))\n\t\t\t\t\tnext_wire:\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\t\t\tif (!ffbits.count(bit))\n\t\t\t\t\t\t\t\tgoto next_wire;\n\n\t\t\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\t\t\tffbits.erase(bit);\n\n\t\t\t\t\t\tinitwires.insert(wire);\n\t\t\t\t\t}\n\n\t\t\t\tfor (auto wire : initwires)\n\t\t\t\t{\n\t\t\t\t\tConst &initval = wire->attributes[\"\\\\init\"];\n\n\t\t\t\t\tfor (int i = 0; i < GetSize(wire); i++)\n\t\t\t\t\t\tif (GetSize(initval) <= i)\n\t\t\t\t\t\t\tinitval.bits.push_back(worker.next_bit());\n\t\t\t\t\t\telse if (initval.bits[i] == State::Sx)\n\t\t\t\t\t\t\tinitval.bits[i] = worker.next_bit();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmodule->rewrite_sigspecs(worker);\n\t\t}\n\t}\n} SetundefPass;\n\nPRIVATE_NAMESPACE_END\nBugfix in \"setundef\" pass\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct SetundefWorker\n{\n\tint next_bit_mode;\n\tuint32_t next_bit_state;\n\n\tRTLIL::State next_bit()\n\t{\n\t\tif (next_bit_mode == 0)\n\t\t\treturn RTLIL::State::S0;\n\n\t\tif (next_bit_mode == 1)\n\t\t\treturn RTLIL::State::S1;\n\n\t\t\/\/ xorshift32\n\t\tnext_bit_state ^= next_bit_state << 13;\n\t\tnext_bit_state ^= next_bit_state >> 17;\n\t\tnext_bit_state ^= next_bit_state << 5;\n\t\tlog_assert(next_bit_state != 0);\n\n\t\treturn ((next_bit_state >> (next_bit_state & 15)) & 16) ? RTLIL::State::S0 : RTLIL::State::S1;\n\t}\n\n\tvoid operator()(RTLIL::SigSpec &sig)\n\t{\n\t\tfor (auto &bit : sig)\n\t\t\tif (bit.wire == NULL && bit.data > RTLIL::State::S1)\n\t\t\t\tbit = next_bit();\n\t}\n};\n\nstruct SetundefPass : public Pass {\n\tSetundefPass() : Pass(\"setundef\", \"replace undef values with defined constants\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" setundef [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command replaced undef (x) constants with defined (0\/1) constants.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -undriven\\n\");\n\t\tlog(\" also set undriven nets to constant values\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -zero\\n\");\n\t\tlog(\" replace with bits cleared (0)\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -one\\n\");\n\t\tlog(\" replace with bits set (1)\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -random \\n\");\n\t\tlog(\" replace with random bits using the specified integer als seed\\n\");\n\t\tlog(\" value for the random number generator.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -init\\n\");\n\t\tlog(\" also create\/update init values for flip-flops\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\tbool got_value = false;\n\t\tbool undriven_mode = false;\n\t\tbool init_mode = false;\n\t\tSetundefWorker worker;\n\n\t\tlog_header(design, \"Executing SETUNDEF pass (replace undef values with defined constants).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-undriven\") {\n\t\t\t\tundriven_mode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-zero\") {\n\t\t\t\tgot_value = true;\n\t\t\t\tworker.next_bit_mode = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-one\") {\n\t\t\t\tgot_value = true;\n\t\t\t\tworker.next_bit_mode = 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-init\") {\n\t\t\t\tinit_mode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-random\" && !got_value && argidx+1 < args.size()) {\n\t\t\t\tgot_value = true;\n\t\t\t\tworker.next_bit_mode = 2;\n\t\t\t\tworker.next_bit_state = atoi(args[++argidx].c_str()) + 1;\n\t\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t\t\tworker.next_bit();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tif (!got_value)\n\t\t\tlog_cmd_error(\"One of the options -zero, -one, or -random must be specified.\\n\");\n\n\t\tfor (auto module : design->selected_modules())\n\t\t{\n\t\t\tif (undriven_mode)\n\t\t\t{\n\t\t\t\tif (!module->processes.empty())\n\t\t\t\t\tlog_error(\"The 'setundef' command can't operate in -undriven mode on modules with processes. Run 'proc' first.\\n\");\n\n\t\t\t\tSigMap sigmap(module);\n\t\t\t\tSigPool undriven_signals;\n\n\t\t\t\tfor (auto &it : module->wires_)\n\t\t\t\t\tundriven_signals.add(sigmap(it.second));\n\n\t\t\t\tfor (auto &it : module->wires_)\n\t\t\t\t\tif (it.second->port_input)\n\t\t\t\t\t\tundriven_signals.del(sigmap(it.second));\n\n\t\t\t\tCellTypes ct(design);\n\t\t\t\tfor (auto &it : module->cells_)\n\t\t\t\tfor (auto &conn : it.second->connections())\n\t\t\t\t\tif (!ct.cell_known(it.second->type) || ct.cell_output(it.second->type, conn.first))\n\t\t\t\t\t\tundriven_signals.del(sigmap(conn.second));\n\n\t\t\t\tRTLIL::SigSpec sig = undriven_signals.export_all();\n\t\t\t\tfor (auto &c : sig.chunks()) {\n\t\t\t\t\tRTLIL::SigSpec bits;\n\t\t\t\t\tfor (int i = 0; i < c.width; i++)\n\t\t\t\t\t\tbits.append(worker.next_bit());\n\t\t\t\t\tmodule->connect(RTLIL::SigSig(c, bits));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (init_mode)\n\t\t\t{\n\t\t\t\tSigMap sigmap(module);\n\t\t\t\tpool ffbits;\n\t\t\t\tpool initwires;\n\n\t\t\t\tpool fftypes;\n\t\t\t\tfftypes.insert(\"$dff\");\n\t\t\t\tfftypes.insert(\"$dffe\");\n\t\t\t\tfftypes.insert(\"$dffsr\");\n\t\t\t\tfftypes.insert(\"$adff\");\n\n\t\t\t\tstd::vector list_np = {'N', 'P'}, list_01 = {'0', '1'};\n\n\t\t\t\tfor (auto c1 : list_np)\n\t\t\t\t\tfftypes.insert(stringf(\"$_DFF_%c_\", c1));\n\n\t\t\t\tfor (auto c1 : list_np)\n\t\t\t\tfor (auto c2 : list_np)\n\t\t\t\t\tfftypes.insert(stringf(\"$_DFFE_%c%c_\", c1, c2));\n\n\t\t\t\tfor (auto c1 : list_np)\n\t\t\t\tfor (auto c2 : list_np)\n\t\t\t\tfor (auto c3 : list_01)\n\t\t\t\t\tfftypes.insert(stringf(\"$_DFF_%c%c%c_\", c1, c2, c3));\n\n\t\t\t\tfor (auto c1 : list_np)\n\t\t\t\tfor (auto c2 : list_np)\n\t\t\t\tfor (auto c3 : list_np)\n\t\t\t\t\tfftypes.insert(stringf(\"$_DFFSR_%c%c%c_\", c1, c2, c3));\n\n\t\t\t\tfor (auto cell : module->cells())\n\t\t\t\t{\n\t\t\t\t\tif (!fftypes.count(cell->type))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tfor (auto bit : sigmap(cell->getPort(\"\\\\Q\")))\n\t\t\t\t\t\tffbits.insert(bit);\n\t\t\t\t}\n\n\t\t\t\tfor (auto wire : module->wires())\n\t\t\t\t{\n\t\t\t\t\tif (!wire->attributes.count(\"\\\\init\"))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\t\tffbits.erase(bit);\n\n\t\t\t\t\tinitwires.insert(wire);\n\t\t\t\t}\n\n\t\t\t\tfor (int wire_types = 0; wire_types < 2; wire_types++)\n\t\t\t\t\tfor (auto wire : module->wires())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (wire->name[0] == (wire_types ? '\\\\' : '$'))\n\t\t\t\t\tnext_wire:\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\t\t\tif (!ffbits.count(bit))\n\t\t\t\t\t\t\t\tgoto next_wire;\n\n\t\t\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\t\t\tffbits.erase(bit);\n\n\t\t\t\t\t\tinitwires.insert(wire);\n\t\t\t\t\t}\n\n\t\t\t\tfor (auto wire : initwires)\n\t\t\t\t{\n\t\t\t\t\tConst &initval = wire->attributes[\"\\\\init\"];\n\n\t\t\t\t\tfor (int i = 0; i < GetSize(wire); i++)\n\t\t\t\t\t\tif (GetSize(initval) <= i)\n\t\t\t\t\t\t\tinitval.bits.push_back(worker.next_bit());\n\t\t\t\t\t\telse if (initval.bits[i] == State::Sx)\n\t\t\t\t\t\t\tinitval.bits[i] = worker.next_bit();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmodule->rewrite_sigspecs(worker);\n\t\t}\n\t}\n} SetundefPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"#include \"hmac.h\"\n\nPersistent Hmac::constructor;\n\nvoid Hmac::Initialize(Handle target) {\n HandleScope scope;\n\n constructor = Persistent::New(FunctionTemplate::New(Hmac::New));\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(String::NewSymbol(\"Hmac\"));\n\n NODE_SET_PROTOTYPE_METHOD(constructor, \"init\", HmacInit);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"update\", HmacUpdate);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"digest\", HmacDigest);\n Local proto = constructor->PrototypeTemplate();\n\n target->Set(String::NewSymbol(\"Hmac\"), constructor->GetFunction());\n}\n\nbool Hmac::HmacInit(char* hashType, char* key, int key_len) {\n md = EVP_get_digestbyname(hashType);\n if(!md) {\n fprintf(stderr, \"node-crypto : Unknown message digest %s\\n\", hashType);\n return false;\n }\n\n HMAC_CTX_init(&ctx2);\n \/\/ HMAC_Init(ctx, key, key_len, md);\n HMAC_Init_ex(&ctx2, key, key_len, md, NULL);\n initialised_ = true;\n return true;\n}\n\nHandle Hmac::HmacInit(const Arguments& args) {\n Hmac *hmac = ObjectWrap::Unwrap(args.This());\n\n HandleScope scope;\n\n if (args.Length() == 0 || !args[0]->IsString()) {\n return ThrowException(Exception::Error(String::New(\n \"Must give hashtype string as argument\")));\n }\n\n ASSERT_IS_STRING_OR_BUFFER(args[1]);\n ssize_t len = DecodeBytes(args[1], BINARY);\n\n if (len < 0) {\n Local exception = Exception::TypeError(String::New(\"Bad argument\"));\n return ThrowException(exception);\n }\n\n char* buf = new char[len];\n ssize_t written = DecodeWrite(buf, len, args[1], BINARY);\n assert(written == len);\n\n String::Utf8Value hashType(args[0]->ToString());\n\n bool r = hmac->HmacInit(*hashType, buf, len);\n\n delete [] buf;\n\n if (!r) {\n return ThrowException(Exception::Error(String::New(\"hmac error\")));\n }\n\n return args.This();\n}\n\n\nint Hmac::HmacUpdate(char* data, int len) {\n if (!initialised_) return 0;\n HMAC_Update(&ctx2, (unsigned char*)data, len);\n return 1;\n}\n\nHandle Hmac::HmacUpdate(const Arguments& args) {\n Hmac *hmac = ObjectWrap::Unwrap(args.This());\n\n HandleScope scope;\n\n ASSERT_IS_STRING_OR_BUFFER(args[0]);\n enum encoding enc = ParseEncoding(args[1]);\n ssize_t len = DecodeBytes(args[0], enc);\n\n if (len < 0) {\n Local exception = Exception::TypeError(String::New(\"Bad argument\"));\n return ThrowException(exception);\n }\n\n int r;\n\n if(Buffer::HasInstance(args[0])) {\n Local buffer_obj = args[0]->ToObject();\n char *buffer_data = Buffer::Data(buffer_obj);\n size_t buffer_length = Buffer::Length(buffer_obj);\n\n r = hmac->HmacUpdate(buffer_data, buffer_length);\n } else {\n char* buf = new char[len];\n ssize_t written = DecodeWrite(buf, len, args[0], enc);\n assert(written == len);\n r = hmac->HmacUpdate(buf, len);\n delete [] buf;\n }\n\n if (!r) {\n Local exception = Exception::TypeError(String::New(\"HmacUpdate fail\"));\n return ThrowException(exception);\n }\n\n return args.This();\n}\n\nHandle Hmac::HmacDigest(const Arguments& args) {\n Hmac *hmac = ObjectWrap::Unwrap(args.This());\n\n HandleScope scope;\n\n unsigned char* md_value;\n unsigned int md_len;\n char* md_hexdigest;\n int md_hex_len;\n Local outString ;\n\n int r = hmac->HmacDigest(&md_value, &md_len);\n\n if (md_len == 0 || r == 0) {\n return scope.Close(String::New(\"\"));\n }\n\n if (args.Length() == 0 || !args[0]->IsString()) {\n \/\/ Binary\n outString = Encode(md_value, md_len, BINARY);\n } else {\n String::Utf8Value encoding(args[0]->ToString());\n if (strcasecmp(*encoding, \"hex\") == 0) {\n \/\/ Hex encoding\n HexEncode(md_value, md_len, &md_hexdigest, &md_hex_len);\n outString = Encode(md_hexdigest, md_hex_len, BINARY);\n delete [] md_hexdigest;\n } else if (strcasecmp(*encoding, \"base64\") == 0) {\n base64(md_value, md_len, &md_hexdigest, &md_hex_len);\n outString = Encode(md_hexdigest, md_hex_len, BINARY);\n delete [] md_hexdigest;\n } else if (strcasecmp(*encoding, \"binary\") == 0) {\n outString = Encode(md_value, md_len, BINARY);\n } else {\n fprintf(stderr, \"node-crypto : Hmac .digest encoding \"\n \"can be binary, hex or base64\\n\");\n }\n }\n delete [] md_value;\n return scope.Close(outString);\n}\n\n\nint Hmac::HmacDigest(unsigned char** md_value, unsigned int *md_len) {\n if (!initialised_) return 0;\n *md_value = new unsigned char[EVP_MAX_MD_SIZE];\n HMAC_Final(&ctx2, *md_value, md_len);\n HMAC_CTX_cleanup(&ctx2);\n initialised_ = false;\n return 1;\n}\n\nHandle Hmac::New(const Arguments &args) {\n HandleScope scope;\n\n Hmac *hmac = new Hmac();\n hmac->Wrap(args.This());\n\n return args.This();\n}\n\n\nHmac::Hmac() : ObjectWrap() {\n initialised_ = false;\n \/\/ HMAC_CTX_init(&ctx2);\n ctx = (HMAC_CTX *)OPENSSL_malloc(sizeof(HMAC_CTX));\n \/\/ ctx = &ctx2;\n fprintf(stderr, \"%d \\n\", &ctx2);\n fprintf(stderr, \"%d \\n\", sizeof(HMAC_CTX));\n}\n\nHmac::~Hmac() {\n \/\/ OPENSSL_free(&ctx2);\n}\nfix the *2 sizeof in HMAC when able#include \"hmac.h\"\n\nPersistent Hmac::constructor;\n\nvoid Hmac::Initialize(Handle target) {\n HandleScope scope;\n\n constructor = Persistent::New(FunctionTemplate::New(Hmac::New));\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(String::NewSymbol(\"Hmac\"));\n\n NODE_SET_PROTOTYPE_METHOD(constructor, \"init\", HmacInit);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"update\", HmacUpdate);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"digest\", HmacDigest);\n Local proto = constructor->PrototypeTemplate();\n\n target->Set(String::NewSymbol(\"Hmac\"), constructor->GetFunction());\n}\n\nbool Hmac::HmacInit(char* hashType, char* key, int key_len) {\n md = EVP_get_digestbyname(hashType);\n if(!md) {\n fprintf(stderr, \"node-crypto : Unknown message digest %s\\n\", hashType);\n return false;\n }\n\n HMAC_CTX_init(ctx);\n HMAC_Init(ctx, key, key_len, md);\n \/\/ HMAC_Init_ex(&ctx2, key, key_len, md, NULL);\n initialised_ = true;\n return true;\n}\n\nHandle Hmac::HmacInit(const Arguments& args) {\n Hmac *hmac = ObjectWrap::Unwrap(args.This());\n\n HandleScope scope;\n\n if (args.Length() == 0 || !args[0]->IsString()) {\n return ThrowException(Exception::Error(String::New(\n \"Must give hashtype string as argument\")));\n }\n\n ASSERT_IS_STRING_OR_BUFFER(args[1]);\n ssize_t len = DecodeBytes(args[1], BINARY);\n\n if (len < 0) {\n Local exception = Exception::TypeError(String::New(\"Bad argument\"));\n return ThrowException(exception);\n }\n\n char* buf = new char[len];\n ssize_t written = DecodeWrite(buf, len, args[1], BINARY);\n assert(written == len);\n\n String::Utf8Value hashType(args[0]->ToString());\n\n bool r = hmac->HmacInit(*hashType, buf, len);\n\n delete [] buf;\n\n if (!r) {\n return ThrowException(Exception::Error(String::New(\"hmac error\")));\n }\n\n return args.This();\n}\n\n\nint Hmac::HmacUpdate(char* data, int len) {\n if (!initialised_) return 0;\n HMAC_Update(ctx, (unsigned char*)data, len);\n return 1;\n}\n\nHandle Hmac::HmacUpdate(const Arguments& args) {\n Hmac *hmac = ObjectWrap::Unwrap(args.This());\n\n HandleScope scope;\n\n ASSERT_IS_STRING_OR_BUFFER(args[0]);\n enum encoding enc = ParseEncoding(args[1]);\n ssize_t len = DecodeBytes(args[0], enc);\n\n if (len < 0) {\n Local exception = Exception::TypeError(String::New(\"Bad argument\"));\n return ThrowException(exception);\n }\n\n int r;\n\n if(Buffer::HasInstance(args[0])) {\n Local buffer_obj = args[0]->ToObject();\n char *buffer_data = Buffer::Data(buffer_obj);\n size_t buffer_length = Buffer::Length(buffer_obj);\n\n r = hmac->HmacUpdate(buffer_data, buffer_length);\n } else {\n char* buf = new char[len];\n ssize_t written = DecodeWrite(buf, len, args[0], enc);\n assert(written == len);\n r = hmac->HmacUpdate(buf, len);\n delete [] buf;\n }\n\n if (!r) {\n Local exception = Exception::TypeError(String::New(\"HmacUpdate fail\"));\n return ThrowException(exception);\n }\n\n return args.This();\n}\n\nHandle Hmac::HmacDigest(const Arguments& args) {\n Hmac *hmac = ObjectWrap::Unwrap(args.This());\n\n HandleScope scope;\n\n unsigned char* md_value;\n unsigned int md_len;\n char* md_hexdigest;\n int md_hex_len;\n Local outString ;\n\n int r = hmac->HmacDigest(&md_value, &md_len);\n\n if (md_len == 0 || r == 0) {\n return scope.Close(String::New(\"\"));\n }\n\n if (args.Length() == 0 || !args[0]->IsString()) {\n \/\/ Binary\n outString = Encode(md_value, md_len, BINARY);\n } else {\n String::Utf8Value encoding(args[0]->ToString());\n if (strcasecmp(*encoding, \"hex\") == 0) {\n \/\/ Hex encoding\n HexEncode(md_value, md_len, &md_hexdigest, &md_hex_len);\n outString = Encode(md_hexdigest, md_hex_len, BINARY);\n delete [] md_hexdigest;\n } else if (strcasecmp(*encoding, \"base64\") == 0) {\n base64(md_value, md_len, &md_hexdigest, &md_hex_len);\n outString = Encode(md_hexdigest, md_hex_len, BINARY);\n delete [] md_hexdigest;\n } else if (strcasecmp(*encoding, \"binary\") == 0) {\n outString = Encode(md_value, md_len, BINARY);\n } else {\n fprintf(stderr, \"node-crypto : Hmac .digest encoding \"\n \"can be binary, hex or base64\\n\");\n }\n }\n delete [] md_value;\n return scope.Close(outString);\n}\n\n\nint Hmac::HmacDigest(unsigned char** md_value, unsigned int *md_len) {\n if (!initialised_) return 0;\n *md_value = new unsigned char[EVP_MAX_MD_SIZE];\n HMAC_Final(ctx, *md_value, md_len);\n HMAC_CTX_cleanup(ctx);\n initialised_ = false;\n return 1;\n}\n\nHandle Hmac::New(const Arguments &args) {\n HandleScope scope;\n\n Hmac *hmac = new Hmac();\n hmac->Wrap(args.This());\n\n return args.This();\n}\n\n\nHmac::Hmac() : ObjectWrap() {\n initialised_ = false;\n \/\/FIXME\n ctx = (HMAC_CTX *)OPENSSL_malloc(sizeof(HMAC_CTX)*2);\n}\n\nHmac::~Hmac() {\n OPENSSL_free(ctx);\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"MMFilesRestWalHandler.h\"\n#include \"Basics\/VelocyPackHelper.h\"\n#include \"Cluster\/ClusterMethods.h\"\n#include \"Cluster\/ServerState.h\"\n#include \"MMFiles\/MMFilesLogfileManager.h\"\n\nusing namespace arangodb;\nusing namespace arangodb::rest;\n\nMMFilesRestWalHandler::MMFilesRestWalHandler(\n GeneralRequest* request, GeneralResponse* response)\n : RestVocbaseBaseHandler(request, response) {}\n\nRestStatus MMFilesRestWalHandler::execute() {\n std::vector const& suffixes = _request->suffixes();\n\n if (suffixes.size() != 1) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"expecting \/_admin\/wal\/\");\n return RestStatus::DONE;\n }\n \n std::string const& operation = suffixes[0];\n\n \/\/ extract the sub-request type\n auto const type = _request->requestType();\n\n if (operation == \"transactions\") {\n if (type == rest::RequestType::GET) {\n transactions();\n return RestStatus::DONE;\n }\n } else if (operation == \"flush\") {\n if (type == rest::RequestType::PUT) {\n flush();\n return RestStatus::DONE;\n }\n } else if (operation == \"properties\") {\n if (type == rest::RequestType::GET || type == rest::RequestType::PUT) {\n properties();\n return RestStatus::DONE;\n }\n } else {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"expecting \/_admin\/wal\/\");\n return RestStatus::DONE;\n }\n\n generateError(rest::ResponseCode::METHOD_NOT_ALLOWED,\n TRI_ERROR_HTTP_METHOD_NOT_ALLOWED);\n return RestStatus::DONE;\n}\n\nvoid MMFilesRestWalHandler::properties() {\n auto l = MMFilesLogfileManager::instance();\n\n if (_request->requestType() == rest::RequestType::PUT) {\n std::shared_ptr parsedRequest;\n VPackSlice slice;\n try {\n slice = _request->payload();\n } catch (...) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"invalid body value. expecting object\");\n return;\n }\n if (!slice.isObject()) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"invalid body value. expecting object\");\n }\n\n if (slice.hasKey(\"allowOversizeEntries\")) {\n bool value = slice.get(\"allowOversizeEntries\").getBoolean();\n l->allowOversizeEntries(value);\n }\n \n if (slice.hasKey(\"logfileSize\")) {\n uint32_t value = slice.get(\"logfileSize\").getNumericValue();\n l->filesize(value);\n }\n \n if (slice.hasKey(\"historicLogfiles\")) {\n uint32_t value = slice.get(\"historicLogfiles\").getNumericValue();\n l->historicLogfiles(value);\n }\n \n if (slice.hasKey(\"reserveLogfiles\")) {\n uint32_t value = slice.get(\"reserveLogfiles\").getNumericValue();\n l->reserveLogfiles(value);\n }\n \n if (slice.hasKey(\"throttleWait\")) {\n uint64_t value = slice.get(\"throttleWait\").getNumericValue();\n l->maxThrottleWait(value);\n }\n \n if (slice.hasKey(\"throttleWhenPending\")) {\n uint64_t value = slice.get(\"throttleWhenPending\").getNumericValue();\n l->throttleWhenPending(value);\n }\n }\n\n VPackBuilder builder;\n builder.openObject();\n builder.add(\"allowOversizeEntries\", VPackValue(l->allowOversizeEntries()));\n builder.add(\"logfileSize\", VPackValue(l->filesize()));\n builder.add(\"historicLogfiles\", VPackValue(l->historicLogfiles()));\n builder.add(\"reserveLogfiles\", VPackValue(l->reserveLogfiles()));\n builder.add(\"syncInterval\", VPackValue(l->syncInterval()));\n builder.add(\"throttleWait\", VPackValue(l->maxThrottleWait()));\n builder.add(\"throttleWhenPending\", VPackValue(l->throttleWhenPending()));\n\n builder.close();\n generateResult(rest::ResponseCode::OK, builder.slice());\n}\n\nvoid MMFilesRestWalHandler::flush() {\n std::shared_ptr parsedRequest;\n VPackSlice slice;\n try {\n slice = _request->payload();\n } catch (...) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"invalid body value. expecting object\");\n return;\n }\n if (!slice.isObject() && !slice.isNone()) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"invalid body value. expecting object\");\n }\n \n bool waitForSync = false;\n bool waitForCollector = false;\n\n if (slice.isObject()) {\n \/\/ got a request body\n VPackSlice value = slice.get(\"waitForSync\");\n if (value.isString()) {\n waitForSync = (value.copyString() == \"true\");\n } else if (value.isBoolean()) {\n waitForSync = value.getBoolean();\n }\n \n value = slice.get(\"waitForCollector\");\n if (value.isString()) {\n waitForCollector = (value.copyString() == \"true\");\n } else if (value.isBoolean()) {\n waitForCollector = value.getBoolean();\n }\n } else {\n \/\/ no request body\n bool found;\n {\n std::string const& v = _request->value(\"waitForSync\", found);\n if (found) {\n waitForSync = (v == \"1\" || v == \"true\");\n }\n }\n {\n std::string const& v = _request->value(\"waitForCollector\", found);\n if (found) {\n waitForCollector = (v == \"1\" || v == \"true\");\n }\n }\n }\n \n int res;\n if (ServerState::instance()->isCoordinator()) {\n res = flushWalOnAllDBServers(waitForSync, waitForCollector);\n } else {\n res = MMFilesLogfileManager::instance()->flush(\n waitForSync, waitForCollector, false);\n }\n\n if (res != TRI_ERROR_NO_ERROR) {\n THROW_ARANGO_EXCEPTION(res);\n }\n\n generateResult(rest::ResponseCode::OK, basics::VelocyPackHelper::EmptyObjectValue());\n}\n\nvoid MMFilesRestWalHandler::transactions() {\n auto const& info =\n MMFilesLogfileManager::instance()->runningTransactions();\n \n VPackBuilder builder;\n builder.openObject();\n builder.add(\"runningTransactions\", VPackValue(static_cast(std::get<0>(info))));\n\n \/\/ lastCollectedId\n {\n auto value = std::get<1>(info);\n if (value == UINT64_MAX) {\n builder.add(\"minLastCollected\", VPackValue(VPackValueType::Null));\n } else {\n builder.add(\"minLastCollected\", VPackValue(value));\n }\n }\n\n \/\/ lastSealedId\n {\n auto value = std::get<2>(info);\n if (value == UINT64_MAX) {\n builder.add(\"minLastSealed\", VPackValue(VPackValueType::Null));\n } else {\n builder.add(\"minLastSealed\", VPackValue(value));\n }\n }\n\n builder.close();\n\n generateResult(rest::ResponseCode::OK, builder.slice());\n}\nissue #2505\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"MMFilesRestWalHandler.h\"\n#include \"Basics\/VelocyPackHelper.h\"\n#include \"Cluster\/ClusterMethods.h\"\n#include \"Cluster\/ServerState.h\"\n#include \"MMFiles\/MMFilesLogfileManager.h\"\n\nusing namespace arangodb;\nusing namespace arangodb::rest;\n\nMMFilesRestWalHandler::MMFilesRestWalHandler(\n GeneralRequest* request, GeneralResponse* response)\n : RestVocbaseBaseHandler(request, response) {}\n\nRestStatus MMFilesRestWalHandler::execute() {\n std::vector const& suffixes = _request->suffixes();\n\n if (suffixes.size() != 1) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"expecting \/_admin\/wal\/\");\n return RestStatus::DONE;\n }\n \n std::string const& operation = suffixes[0];\n\n \/\/ extract the sub-request type\n auto const type = _request->requestType();\n\n if (operation == \"transactions\") {\n if (type == rest::RequestType::GET) {\n transactions();\n return RestStatus::DONE;\n }\n } else if (operation == \"flush\") {\n if (type == rest::RequestType::PUT) {\n flush();\n return RestStatus::DONE;\n }\n } else if (operation == \"properties\") {\n if (type == rest::RequestType::GET || type == rest::RequestType::PUT) {\n properties();\n return RestStatus::DONE;\n }\n } else {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"expecting \/_admin\/wal\/\");\n return RestStatus::DONE;\n }\n\n generateError(rest::ResponseCode::METHOD_NOT_ALLOWED,\n TRI_ERROR_HTTP_METHOD_NOT_ALLOWED);\n return RestStatus::DONE;\n}\n\nvoid MMFilesRestWalHandler::properties() {\n auto l = MMFilesLogfileManager::instance();\n\n if (_request->requestType() == rest::RequestType::PUT) {\n std::shared_ptr parsedRequest;\n VPackSlice slice;\n try {\n slice = _request->payload();\n } catch (...) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"invalid body value. expecting object\");\n return;\n }\n if (!slice.isObject()) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"invalid body value. expecting object\");\n return;\n }\n\n if (slice.hasKey(\"allowOversizeEntries\")) {\n bool value = slice.get(\"allowOversizeEntries\").getBoolean();\n l->allowOversizeEntries(value);\n }\n \n if (slice.hasKey(\"logfileSize\")) {\n uint32_t value = slice.get(\"logfileSize\").getNumericValue();\n l->filesize(value);\n }\n \n if (slice.hasKey(\"historicLogfiles\")) {\n uint32_t value = slice.get(\"historicLogfiles\").getNumericValue();\n l->historicLogfiles(value);\n }\n \n if (slice.hasKey(\"reserveLogfiles\")) {\n uint32_t value = slice.get(\"reserveLogfiles\").getNumericValue();\n l->reserveLogfiles(value);\n }\n \n if (slice.hasKey(\"throttleWait\")) {\n uint64_t value = slice.get(\"throttleWait\").getNumericValue();\n l->maxThrottleWait(value);\n }\n \n if (slice.hasKey(\"throttleWhenPending\")) {\n uint64_t value = slice.get(\"throttleWhenPending\").getNumericValue();\n l->throttleWhenPending(value);\n }\n }\n\n VPackBuilder builder;\n builder.openObject();\n builder.add(\"allowOversizeEntries\", VPackValue(l->allowOversizeEntries()));\n builder.add(\"logfileSize\", VPackValue(l->filesize()));\n builder.add(\"historicLogfiles\", VPackValue(l->historicLogfiles()));\n builder.add(\"reserveLogfiles\", VPackValue(l->reserveLogfiles()));\n builder.add(\"syncInterval\", VPackValue(l->syncInterval()));\n builder.add(\"throttleWait\", VPackValue(l->maxThrottleWait()));\n builder.add(\"throttleWhenPending\", VPackValue(l->throttleWhenPending()));\n\n builder.close();\n generateResult(rest::ResponseCode::OK, builder.slice());\n}\n\nvoid MMFilesRestWalHandler::flush() {\n std::shared_ptr parsedRequest;\n VPackSlice slice;\n try {\n slice = _request->payload();\n } catch (...) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"invalid body value. expecting object\");\n return;\n }\n if (!slice.isObject() && !slice.isNone()) {\n generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,\n \"invalid body value. expecting object\");\n }\n \n bool waitForSync = false;\n bool waitForCollector = false;\n\n if (slice.isObject()) {\n \/\/ got a request body\n VPackSlice value = slice.get(\"waitForSync\");\n if (value.isString()) {\n waitForSync = (value.copyString() == \"true\");\n } else if (value.isBoolean()) {\n waitForSync = value.getBoolean();\n }\n \n value = slice.get(\"waitForCollector\");\n if (value.isString()) {\n waitForCollector = (value.copyString() == \"true\");\n } else if (value.isBoolean()) {\n waitForCollector = value.getBoolean();\n }\n } else {\n \/\/ no request body\n bool found;\n {\n std::string const& v = _request->value(\"waitForSync\", found);\n if (found) {\n waitForSync = (v == \"1\" || v == \"true\");\n }\n }\n {\n std::string const& v = _request->value(\"waitForCollector\", found);\n if (found) {\n waitForCollector = (v == \"1\" || v == \"true\");\n }\n }\n }\n \n int res;\n if (ServerState::instance()->isCoordinator()) {\n res = flushWalOnAllDBServers(waitForSync, waitForCollector);\n } else {\n res = MMFilesLogfileManager::instance()->flush(\n waitForSync, waitForCollector, false);\n }\n\n if (res != TRI_ERROR_NO_ERROR) {\n THROW_ARANGO_EXCEPTION(res);\n }\n\n generateResult(rest::ResponseCode::OK, basics::VelocyPackHelper::EmptyObjectValue());\n}\n\nvoid MMFilesRestWalHandler::transactions() {\n auto const& info =\n MMFilesLogfileManager::instance()->runningTransactions();\n \n VPackBuilder builder;\n builder.openObject();\n builder.add(\"runningTransactions\", VPackValue(static_cast(std::get<0>(info))));\n\n \/\/ lastCollectedId\n {\n auto value = std::get<1>(info);\n if (value == UINT64_MAX) {\n builder.add(\"minLastCollected\", VPackValue(VPackValueType::Null));\n } else {\n builder.add(\"minLastCollected\", VPackValue(value));\n }\n }\n\n \/\/ lastSealedId\n {\n auto value = std::get<2>(info);\n if (value == UINT64_MAX) {\n builder.add(\"minLastSealed\", VPackValue(VPackValueType::Null));\n } else {\n builder.add(\"minLastSealed\", VPackValue(value));\n }\n }\n\n builder.close();\n\n generateResult(rest::ResponseCode::OK, builder.slice());\n}\n<|endoftext|>"} {"text":"\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file EthashAux.cpp\n * @author Gav Wood \n * @date 2014\n *\/\n\n#include \"EthashAux.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"BlockInfo.h\"\n#include \"Exceptions.h\"\nusing namespace std;\nusing namespace chrono;\nusing namespace dev;\nusing namespace eth;\n\nEthashAux* dev::eth::EthashAux::s_this = nullptr;\n\nEthashAux::~EthashAux()\n{\n}\n\nuint64_t EthashAux::cacheSize(BlockInfo const& _header)\n{\n\treturn ethash_get_cachesize((uint64_t)_header.number);\n}\n\nh256 EthashAux::seedHash(unsigned _number)\n{\n\tunsigned epoch = _number \/ ETHASH_EPOCH_LENGTH;\n\tGuard l(get()->x_epochs);\n\tif (epoch >= get()->m_seedHashes.size())\n\t{\n\t\th256 ret;\n\t\tunsigned n = 0;\n\t\tif (!get()->m_seedHashes.empty())\n\t\t{\n\t\t\tret = get()->m_seedHashes.back();\n\t\t\tn = get()->m_seedHashes.size() - 1;\n\t\t}\n\t\tget()->m_seedHashes.resize(epoch + 1);\n\/\/\t\tcdebug << \"Searching for seedHash of epoch \" << epoch;\n\t\tfor (; n <= epoch; ++n, ret = sha3(ret))\n\t\t{\n\t\t\tget()->m_seedHashes[n] = ret;\n\/\/\t\t\tcdebug << \"Epoch\" << n << \"is\" << ret;\n\t\t}\n\t}\n\treturn get()->m_seedHashes[epoch];\n}\n\nvoid EthashAux::killCache(h256 const& _s)\n{\n\tRecursiveGuard l(x_this);\n\tm_lights.erase(_s);\n}\n\nEthashAux::LightType EthashAux::light(BlockInfo const& _header)\n{\n\treturn light((uint64_t)_header.number);\n}\n\nEthashAux::LightType EthashAux::light(uint64_t _blockNumber)\n{\n\tRecursiveGuard l(get()->x_this);\n\th256 seedHash = EthashAux::seedHash(_blockNumber);\n\tLightType ret = get()->m_lights[seedHash];\n\treturn ret ? ret : (get()->m_lights[seedHash] = make_shared(_blockNumber));\n}\n\nEthashAux::LightAllocation::LightAllocation(uint64_t _blockNumber)\n{\n\tlight = ethash_light_new(_blockNumber);\n\tsize = ethash_get_cachesize(_blockNumber);\n}\n\nEthashAux::LightAllocation::~LightAllocation()\n{\n\tethash_light_delete(light);\n}\n\nbytesConstRef EthashAux::LightAllocation::data() const\n{\n\treturn bytesConstRef((byte const*)light->cache, size);\n}\n\nEthashAux::FullAllocation::FullAllocation(ethash_light_t _light, ethash_callback_t _cb)\n{\n\tfull = ethash_full_new(_light, _cb);\n}\n\nEthashAux::FullAllocation::~FullAllocation()\n{\n\tethash_full_delete(full);\n}\n\nbytesConstRef EthashAux::FullAllocation::data() const\n{\n\treturn bytesConstRef((byte const*)ethash_full_dag(full), size());\n}\n\nEthashAux::FullType EthashAux::full(BlockInfo const& _header)\n{\n\treturn full((uint64_t) _header.number);\n}\n\nEthashAux::FullType EthashAux::full(uint64_t _blockNumber)\n{\n\tRecursiveGuard l(get()->x_this);\n\th256 seedHash = EthashAux::seedHash(_blockNumber);\n\tFullType ret;\n\tif ((ret = get()->m_fulls[seedHash].lock()))\n\t{\n\t\tget()->m_lastUsedFull = ret;\n\t\treturn ret;\n\t}\n\tret = get()->m_lastUsedFull = make_shared(light(_blockNumber)->light, nullptr);\n\tget()->m_fulls[seedHash] = ret;\n\treturn ret;\n}\n\nEthash::Result EthashAux::FullAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const\n{\n\tethash_return_value_t r = ethash_full_compute(full, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce);\n\tif (!r.success)\n\t\tBOOST_THROW_EXCEPTION(DAGCreationFailure());\n\treturn Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)};\n}\n\nEthash::Result EthashAux::LightAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const\n{\n\tethash_return_value r = ethash_light_compute(light, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce);\n\tif (!r.success)\n\t\tBOOST_THROW_EXCEPTION(DAGCreationFailure());\n\treturn Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)};\n}\n\nEthash::Result EthashAux::eval(BlockInfo const& _header, Nonce const& _nonce)\n{\n\treturn eval((uint64_t)_header.number, _header.headerHash(WithoutNonce), _nonce);\n}\n\nEthash::Result EthashAux::eval(uint64_t _blockNumber, h256 const& _headerHash, Nonce const& _nonce)\n{\n\th256 seedHash = EthashAux::seedHash(_blockNumber);\n\tif (FullType dag = get()->m_fulls[seedHash].lock())\n\t\treturn dag->compute(_headerHash, _nonce);\n\treturn EthashAux::get()->light(_blockNumber)->compute(_headerHash, _nonce);\n}\nAdd simple callback for DAG generation progress reporting\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file EthashAux.cpp\n * @author Gav Wood \n * @date 2014\n *\/\n\n#include \"EthashAux.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"BlockInfo.h\"\n#include \"Exceptions.h\"\nusing namespace std;\nusing namespace chrono;\nusing namespace dev;\nusing namespace eth;\n\nEthashAux* dev::eth::EthashAux::s_this = nullptr;\n\nEthashAux::~EthashAux()\n{\n}\n\nuint64_t EthashAux::cacheSize(BlockInfo const& _header)\n{\n\treturn ethash_get_cachesize((uint64_t)_header.number);\n}\n\nh256 EthashAux::seedHash(unsigned _number)\n{\n\tunsigned epoch = _number \/ ETHASH_EPOCH_LENGTH;\n\tGuard l(get()->x_epochs);\n\tif (epoch >= get()->m_seedHashes.size())\n\t{\n\t\th256 ret;\n\t\tunsigned n = 0;\n\t\tif (!get()->m_seedHashes.empty())\n\t\t{\n\t\t\tret = get()->m_seedHashes.back();\n\t\t\tn = get()->m_seedHashes.size() - 1;\n\t\t}\n\t\tget()->m_seedHashes.resize(epoch + 1);\n\/\/\t\tcdebug << \"Searching for seedHash of epoch \" << epoch;\n\t\tfor (; n <= epoch; ++n, ret = sha3(ret))\n\t\t{\n\t\t\tget()->m_seedHashes[n] = ret;\n\/\/\t\t\tcdebug << \"Epoch\" << n << \"is\" << ret;\n\t\t}\n\t}\n\treturn get()->m_seedHashes[epoch];\n}\n\nvoid EthashAux::killCache(h256 const& _s)\n{\n\tRecursiveGuard l(x_this);\n\tm_lights.erase(_s);\n}\n\nEthashAux::LightType EthashAux::light(BlockInfo const& _header)\n{\n\treturn light((uint64_t)_header.number);\n}\n\nEthashAux::LightType EthashAux::light(uint64_t _blockNumber)\n{\n\tRecursiveGuard l(get()->x_this);\n\th256 seedHash = EthashAux::seedHash(_blockNumber);\n\tLightType ret = get()->m_lights[seedHash];\n\treturn ret ? ret : (get()->m_lights[seedHash] = make_shared(_blockNumber));\n}\n\nEthashAux::LightAllocation::LightAllocation(uint64_t _blockNumber)\n{\n\tlight = ethash_light_new(_blockNumber);\n\tsize = ethash_get_cachesize(_blockNumber);\n}\n\nEthashAux::LightAllocation::~LightAllocation()\n{\n\tethash_light_delete(light);\n}\n\nbytesConstRef EthashAux::LightAllocation::data() const\n{\n\treturn bytesConstRef((byte const*)light->cache, size);\n}\n\nEthashAux::FullAllocation::FullAllocation(ethash_light_t _light, ethash_callback_t _cb)\n{\n\tfull = ethash_full_new(_light, _cb);\n}\n\nEthashAux::FullAllocation::~FullAllocation()\n{\n\tethash_full_delete(full);\n}\n\nbytesConstRef EthashAux::FullAllocation::data() const\n{\n\treturn bytesConstRef((byte const*)ethash_full_dag(full), size());\n}\n\nEthashAux::FullType EthashAux::full(BlockInfo const& _header)\n{\n\treturn full((uint64_t) _header.number);\n}\n\nstruct DAGChannel: public LogChannel { static const char* name(); static const int verbosity = 0; };\nconst char* DAGChannel::name() { return EthGreen \"DAG\"; }\nstatic int ethash_callback(unsigned int _progress)\n{\n clog(DAGChannel) << \"Generating DAG file. Progress: \" << toString(_progress) << \"%\";\n return 0;\n}\n\nEthashAux::FullType EthashAux::full(uint64_t _blockNumber)\n{\n\tRecursiveGuard l(get()->x_this);\n\th256 seedHash = EthashAux::seedHash(_blockNumber);\n\tFullType ret;\n\tif ((ret = get()->m_fulls[seedHash].lock()))\n\t{\n\t\tget()->m_lastUsedFull = ret;\n\t\treturn ret;\n\t}\n\tret = get()->m_lastUsedFull = make_shared(light(_blockNumber)->light, ethash_callback);\n\tget()->m_fulls[seedHash] = ret;\n\treturn ret;\n}\n\nEthash::Result EthashAux::FullAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const\n{\n\tethash_return_value_t r = ethash_full_compute(full, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce);\n\tif (!r.success)\n\t\tBOOST_THROW_EXCEPTION(DAGCreationFailure());\n\treturn Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)};\n}\n\nEthash::Result EthashAux::LightAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const\n{\n\tethash_return_value r = ethash_light_compute(light, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce);\n\tif (!r.success)\n\t\tBOOST_THROW_EXCEPTION(DAGCreationFailure());\n\treturn Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)};\n}\n\nEthash::Result EthashAux::eval(BlockInfo const& _header, Nonce const& _nonce)\n{\n\treturn eval((uint64_t)_header.number, _header.headerHash(WithoutNonce), _nonce);\n}\n\nEthash::Result EthashAux::eval(uint64_t _blockNumber, h256 const& _headerHash, Nonce const& _nonce)\n{\n\th256 seedHash = EthashAux::seedHash(_blockNumber);\n\tif (FullType dag = get()->m_fulls[seedHash].lock())\n\t\treturn dag->compute(_headerHash, _nonce);\n\treturn EthashAux::get()->light(_blockNumber)->compute(_headerHash, _nonce);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef OFILL\n#define OFILL 0000100\n#endif\n#ifndef OFDEL\n#define OFDEL 0000200\n#endif\n#ifndef NLDLY\n#define NLDLY 0000400\n#endif\n#ifndef CRDLY\n#define CRDLY 0003000\n#endif\n#ifndef BSDLY\n#define BSDLY 0020000\n#endif\n#ifndef VTDLY\n#define VTDLY 0040000\n#endif\n#ifndef FFDLY\n#define FFDLY 0100000\n#endif\n\n#include \"Crc16.h\"\n#include \"Command.h\"\n\nclass Display {\n public:\n Display(std::string devName, speed_t baud = B115200) {\n _devName = devName;\n _baud = baud;\n std::cout << \"Init device: \" << _devName.c_str() << std::endl;\n\n _fd = open(_devName.c_str(), O_NOCTTY | O_NONBLOCK | O_RDWR );\n if (_fd == -1) {\n std::perror(\"Display():open\");\n }\n\n struct termios term;\n tcgetattr(_fd, &term);\n\n term.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL\n |IXON|IXOFF);\n term.c_iflag |= IGNPAR;\n\n \/\/output modes\n term.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONOCR|ONLRET|OFILL\n |OFDEL|NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);\n\n \/\/control modes\n term.c_cflag &= ~(CSIZE|PARENB|PARODD|HUPCL|CRTSCTS);\n term.c_cflag |= CREAD|CS8|CSTOPB|CLOCAL;\n\n \/\/local modes\n term.c_lflag &= ~(ISIG|ICANON|IEXTEN|ECHO);\n term.c_lflag |= NOFLSH;\n\n cfsetospeed(&term, baud);\n cfsetispeed(&term, baud);\n\n \/\/set new device settings\n if(tcsetattr(_fd, TCSANOW, &term) == -1) {\n std::perror(\"Display():tcsetattr\");\n }\n\n }\n\n ~Display() {\n close(_fd);\n _fd = -1;\n }\n\n void clear() {\n uint8_t data[4] = { 0 };\n data[0] = 0x06;\n data[1] = 0;\n\n uint16_t crc = Crc16::compute(data, 2);\n data[3] = (0xFF00 & crc) >> 8;\n data[2] = 0x00FF & crc;\n\n write(_fd, data, 4);\n\n }\n\n void text() {\n std::string text(\"hello world!\");\n uint8_t data[1 + 1 + 22 + 2] = { 0 };\n data[0] = 0x1F;\n data[1] = text.length() + 2;\n data[2] = 0;\n data[3] = 1;\n std::copy(text.begin(), text.end(), &data[4]);\n uint16_t crc = Crc16::compute(data, data[1] + 2);\n printf(\"crc: %x\\n\", crc);\n data[16] = 0xFF & crc;\n data[17] = (0xFF00 & crc) >> 8;\n\n write(_fd, data, 18);\n\n }\n\n void setLedState() {\n Command cmd;\n cmd.type = 0x22;\n cmd.length = 2;\n cmd.data[0] = 5;\n cmd.data[1] = 100;\n cmd.crc = Crc16::compute((uint8_t *) &cmd, cmd.length + 2);\n\n \/\/write(_fd, (uint8_t *) &cmd, cmd.length + 2 + 2);\n send(cmd);\n }\n\n void send(Command &cmd) {\n uint16_t crc = Crc16::compute(cmd);\n cmd.data[cmd.length] = Crc16::compute(cmd);\n write(_fd, &cmd, sizeof(uint8_t) * (4 + cmd.length));\n printf(\"CRC: %x\\n\", crc);\n\n\n }\n\n private:\n int _fd;\n std::string _devName;\n speed_t _baud;\n\n};\n\nint main (int argc, char *argv[]) {\n\n Display d(\"\/dev\/ttyU0\");\n d.clear();\n d.text();\n d.setLedState();\n Command cmd;\n cmd.type = 0x1F;\n cmd.length = 14;\n cmd.data[0] = 0;\n cmd.data[1] = 1;\n std::string msg(\"hello cool world!\");\n std::copy(msg.begin(), msg.end(), &cmd.data[2]);\n d.send(cmd);\n\n}\n\n\nSingle-write() send method with error checking#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef OFILL\n#define OFILL 0000100\n#endif\n#ifndef OFDEL\n#define OFDEL 0000200\n#endif\n#ifndef NLDLY\n#define NLDLY 0000400\n#endif\n#ifndef CRDLY\n#define CRDLY 0003000\n#endif\n#ifndef BSDLY\n#define BSDLY 0020000\n#endif\n#ifndef VTDLY\n#define VTDLY 0040000\n#endif\n#ifndef FFDLY\n#define FFDLY 0100000\n#endif\n\n#include \"Crc16.h\"\n#include \"Command.h\"\n#include \n\nclass Display {\n public:\n Display(std::string devName, speed_t baud = B115200) {\n _devName = devName;\n _baud = baud;\n std::cout << \"Init device: \" << _devName.c_str() << std::endl;\n\n _fd = open(_devName.c_str(), O_NOCTTY | O_NONBLOCK | O_RDWR );\n if (_fd == -1) {\n std::perror(\"Display():open\");\n }\n\n struct termios term;\n tcgetattr(_fd, &term);\n\n term.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL\n |IXON|IXOFF);\n term.c_iflag |= IGNPAR;\n\n \/\/output modes\n term.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONOCR|ONLRET|OFILL\n |OFDEL|NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);\n\n \/\/control modes\n term.c_cflag &= ~(CSIZE|PARENB|PARODD|HUPCL|CRTSCTS);\n term.c_cflag |= CREAD|CS8|CSTOPB|CLOCAL;\n\n \/\/local modes\n term.c_lflag &= ~(ISIG|ICANON|IEXTEN|ECHO);\n term.c_lflag |= NOFLSH;\n\n cfsetospeed(&term, baud);\n cfsetispeed(&term, baud);\n\n \/\/set new device settings\n if(tcsetattr(_fd, TCSANOW, &term) == -1) {\n std::perror(\"Display():tcsetattr\");\n }\n\n }\n\n ~Display() {\n close(_fd);\n _fd = -1;\n }\n\n void clear() {\n uint8_t data[4] = { 0 };\n data[0] = 0x06;\n data[1] = 0;\n\n uint16_t crc = Crc16::compute(data, 2);\n data[3] = (0xFF00 & crc) >> 8;\n data[2] = 0x00FF & crc;\n\n write(_fd, data, 4);\n\n }\n\n void text() {\n std::string text(\"hello world!\");\n uint8_t data[1 + 1 + 22 + 2] = { 0 };\n data[0] = 0x1F;\n data[1] = text.length() + 2;\n data[2] = 0;\n data[3] = 1;\n std::copy(text.begin(), text.end(), &data[4]);\n uint16_t crc = Crc16::compute(data, data[1] + 2);\n printf(\"crc: %x\\n\", crc);\n data[16] = 0xFF & crc;\n data[17] = (0xFF00 & crc) >> 8;\n\n write(_fd, data, 18);\n\n }\n\n void setLedState() {\n Command cmd;\n cmd.type = 0x22;\n cmd.length = 2;\n cmd.data[0] = 5;\n cmd.data[1] = 100;\n cmd.crc = Crc16::compute((uint8_t *) &cmd, cmd.length + 2);\n\n \/\/write(_fd, (uint8_t *) &cmd, cmd.length + 2 + 2);\n send(cmd);\n }\n\n ssize_t send(Command &cmd) {\n if (cmd.length > MAX_COMMAND_LEN) {\n return -1;\n }\n\n uint16_t crc = Crc16::compute(cmd);\n memcpy(&cmd.data[cmd.length], &crc, sizeof(crc));\n size_t numBytes = sizeof(cmd.data) * (cmd.length + 2) + sizeof(crc);\n ssize_t out = write(_fd, &cmd, numBytes);\n if (out == -1) {\n std::perror(\"Display::send()\");\n }\n return out;\n }\n\n private:\n int _fd;\n std::string _devName;\n speed_t _baud;\n\n};\n\nint main (int argc, char *argv[]) {\n\n Display d(\"\/dev\/ttyU0\");\n d.clear();\n d.text();\n d.setLedState();\n Command cmd;\n cmd.type = 0x1F;\n cmd.length = 14;\n cmd.data[0] = 0;\n cmd.data[1] = 1;\n std::string msg(\"hello cool world!\");\n std::copy(msg.begin(), msg.end(), &cmd.data[2]);\n d.send(cmd);\n\n}\n\n\n<|endoftext|>"} {"text":"\/** This is a TcpServer's performance test.\n * It could be run in N different modes:\n * 1) Local throughput test:\n * Clients and server created on the same machine and communicates through the loopback.\n * This mode is designated to test server performance locally, on a single machine. And\n * this mode is very limited because clients affects the server performance.\n * 2) Server mode:\n * Application starts in server mode and accepts incomming connections. It can be termia\n * ted using ^C signal. This mode can be used to test server performance in isolation.\n * Also, this test mode takes network into account. Application should dump number of me\n * ssages per second to stdout.\n * 3) Client mode:\n * Application started in client mode can connect to server (the same application should\n * be started on another node in server mode) and dump specified number of messages to\n * the server.\n *\n * Parameters:\n * a) `mode` can accept three parameters - 'client', 'server' or 'local'.\n * b) `host` url or ip of the server if app was started in client mode.\n * c) `count` number of messages to send inf started in client mode.\n * d) `njobs` number of threads to use\n *\/\n#include \n#include \n#include \n#include \n\n#include \"tcp_server.h\"\n#include \"perftest_tools.h\"\n#include \n\nusing namespace Akumuli;\nnamespace po = boost::program_options;\n\nstruct DbMock : DbConnection {\n typedef std::tuple ValueT;\n aku_ParamId idsum;\n aku_TimeStamp tssum;\n double valsum;\n\n DbMock() {\n idsum = 0;\n tssum = 0;\n valsum = 0;\n }\n\n void write_double(aku_ParamId param, aku_TimeStamp ts, double data) {\n idsum += param;\n tssum += ts;\n valsum += data;\n }\n};\n\nenum Mode {\n CLIENT,\n SERVER,\n LOCAL,\n};\n\n\nMode str_to_mode(std::string str) {\n if (str == \"client\" || str == \"CLIENT\") {\n return CLIENT;\n } else if (str == \"server\" || str == \"SERVER\") {\n return SERVER;\n } else if (str == \"local\" || str == \"LOCAL\") {\n return LOCAL;\n }\n throw std::runtime_error(\"Bad mode value\");\n}\n\nstruct Server {\n\n Mode mode;\n std::shared_ptr pline;\n std::shared_ptr dbcon;\n std::shared_ptr serv;\n boost::asio::io_service ioA;\n std::vector iovec = { &ioA };\n boost::barrier barrier;\n\n Server(Mode mode)\n : mode(mode)\n , barrier(iovec.size() + 1)\n {\n dbcon = std::make_shared();\n pline = std::make_shared(dbcon, AKU_LINEAR_BACKOFF);\n int port = 4096;\n serv = std::make_shared(iovec, port, pline);\n pline->start();\n serv->start();\n }\n\n \/\/! Run IO service\n void start() {\n auto iorun = [](IOService& io, boost::barrier& bar) {\n auto fn = [&]() {\n io.run();\n bar.wait();\n };\n return fn;\n };\n\n for (auto io: iovec) {\n std::thread iothread(iorun(*io, barrier));\n iothread.detach();\n }\n }\n\n void stop() {\n serv->stop();\n std::cout << \"TcpServer stopped\" << std::endl;\n\n \/\/ No need to joint I\/O threads, just wait until they completes.\n barrier.wait();\n std::cout << \"I\/O threads stopped\" << std::endl;\n\n pline->stop();\n std::cout << \"Pipeline stopped\" << std::endl;\n\n for (auto io: iovec) {\n io->stop();\n }\n std::cout << \"I\/O service stopped\" << std::endl;\n\n std::cout << dbcon->idsum << \" messages received\" << std::endl;\n }\n};\n\n\nstruct Client {\n int nthreads;\n int count;\n boost::barrier start_barrier, stop_barrier;\n EndpointT endpoint;\n PerfTimer *timer;\n\n Client(EndpointT ep, PerfTimer *timer, int nthreads = 4, int count = 2500000)\n : nthreads(nthreads)\n , count(count)\n , start_barrier(nthreads + 1)\n , stop_barrier(nthreads + 1)\n , endpoint(ep)\n , timer(timer)\n {\n }\n\n void start() {\n auto self = this;\n auto push = [self]() {\n std::vector threshold_values;\n IOService io;\n TcpSocket socket(io);\n std::cout << \"Connecting to server at \" << self->endpoint << std::endl;\n socket.connect(self->endpoint);\n self->start_barrier.wait();\n\n boost::asio::streambuf stream;\n std::ostream os(&stream);\n size_t nsent = 0u;\n double tm = self->timer->elapsed();\n for (int i = self->count; i --> 0; ) {\n os << \":1\\r\\n\" \":2\\r\\n\" \"+3.14\\r\\n\";\n nsent += boost::asio::write(socket, stream);\n if (nsent >= 1024*1024) { \/\/ +1Mb was sent\n double newtm = self->timer->elapsed();\n threshold_values.push_back(newtm - tm);\n nsent = 0u;\n tm = newtm;\n }\n }\n socket.shutdown(TcpSocket::shutdown_both);\n self->stop_barrier.wait();\n std::cout << \"Push process completed\" << std::endl;\n if (threshold_values.size()) {\n std::sort(threshold_values.begin(), threshold_values.end());\n double min = threshold_values.front(), max = threshold_values.back();\n double sum = 0, avg = 0, med = threshold_values[threshold_values.size() \/ 2];\n for (auto x: threshold_values) { sum += x; }\n avg = sum \/ threshold_values.size();\n auto convert = [&](double val) {\n \/\/ Convert seconds per Mb to Mb per second\n return 1.0\/val;\n };\n std::cout << \"Push process performance\" << std::endl;\n std::cout << \"max: \" << convert(min) << \" Mb\/sec\" << std::endl; \/\/ min and max should be\n std::cout << \"min: \" << convert(max) << \" Mb\/sec\" << std::endl; \/\/ swapped because of conv\n std::cout << \"avg: \" << convert(avg) << \" Mb\/sec\" << std::endl;\n std::cout << \"med: \" << convert(med) << \" Mb\/sec\" << std::endl;\n }\n };\n\n for (int i = 0; i < nthreads; i++) {\n std::thread th(push);\n th.detach();\n }\n\n start_barrier.wait();\n timer->restart();\n }\n\n void wait() {\n stop_barrier.wait();\n }\n};\n\nint main(int argc, char *argv[]) {\n std::cout << \"Tcp server performance test\" << std::endl;\n po::options_description desc(\"Allowed options\");\n \/*\n * Parameters:\n * a) `mode` can accept three parameters - 'client', 'server' or 'local'.\n * b) `host` url or ip of the server if app was started in client mode.\n * c) `count` number of messages to send inf started in client mode.\n * d) `njobs` number of threads to use\n *\/\n std::string strmode;\n std::string host;\n int num_messages;\n bool graphite_enabled = false;\n desc.add_options()\n (\"help\", \"produce help message\")\n (\"mode\", po::value(&strmode)->default_value(\"local\"), \"test mode\")\n (\"host\", po::value(&host)->default_value(\"localhost\"), \"server host in client mode\")\n (\"count\", po::value(&num_messages)->default_value(1000000), \"number of messages to send\")\n (\"graphite\", po::value(&graphite_enabled)->default_value(false), \"push result to graphite\")\n ;\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 0;\n }\n\n Mode mode = str_to_mode(strmode);\n\n switch(mode) {\n case LOCAL: {\n PerfTimer tm;\n Server server(mode);\n EndpointT ep(boost::asio::ip::address_v4::loopback(), 4096);\n Client client(ep, &tm, 4, 2500000);\n server.start();\n client.start();\n client.wait();\n server.stop();\n double elapsed = tm.elapsed();\n std::cout << \"Local test completed in \" << elapsed << \" seconds\" << std::endl;\n if (graphite_enabled) {\n push_metric_to_graphite(\"tcp_server_local\", elapsed);\n }\n break;\n }\n case SERVER:\n break;\n case CLIENT:\n break;\n }\n\n\n return 0;\n}\nWIP: tcp server test suite, client and server mode implemented\/** This is a TcpServer's performance test.\n * It could be run in N different modes:\n * 1) Local throughput test:\n * Clients and server created on the same machine and communicates through the loopback.\n * This mode is designated to test server performance locally, on a single machine. And\n * this mode is very limited because clients affects the server performance.\n * 2) Server mode:\n * Application starts in server mode and accepts incomming connections. It can be termia\n * ted using ^C signal. This mode can be used to test server performance in isolation.\n * Also, this test mode takes network into account. Application should dump number of me\n * ssages per second to stdout.\n * 3) Client mode:\n * Application started in client mode can connect to server (the same application should\n * be started on another node in server mode) and dump specified number of messages to\n * the server.\n *\n * Parameters:\n * a) `mode` can accept three parameters - 'client', 'server' or 'local'.\n * b) `host` url or ip of the server if app was started in client mode.\n * c) `count` number of messages to send inf started in client mode.\n * d) `njobs` number of threads to use\n *\/\n#include \n#include \n#include \n#include \n\n#include \"tcp_server.h\"\n#include \"perftest_tools.h\"\n#include \n\nusing namespace Akumuli;\nnamespace po = boost::program_options;\n\nstruct DbMock : DbConnection {\n typedef std::tuple ValueT;\n aku_ParamId idsum;\n aku_TimeStamp tssum;\n double valsum;\n\n DbMock() {\n idsum = 0;\n tssum = 0;\n valsum = 0;\n }\n\n void write_double(aku_ParamId param, aku_TimeStamp ts, double data) {\n idsum += param;\n tssum += ts;\n valsum += data;\n }\n};\n\nenum Mode {\n CLIENT,\n SERVER,\n LOCAL,\n};\n\n\nMode str_to_mode(std::string str) {\n if (str == \"client\" || str == \"CLIENT\") {\n return CLIENT;\n } else if (str == \"server\" || str == \"SERVER\") {\n return SERVER;\n } else if (str == \"local\" || str == \"LOCAL\") {\n return LOCAL;\n }\n throw std::runtime_error(\"Bad mode value\");\n}\n\nstruct Server {\n\n Mode mode;\n std::shared_ptr pline;\n std::shared_ptr dbcon;\n std::shared_ptr serv;\n boost::asio::io_service ioA;\n std::vector iovec = { &ioA };\n boost::barrier barrier;\n boost::asio::signal_set sig;\n std::atomic stopped = {0};\n\n Server(Mode mode)\n : mode(mode)\n , barrier(iovec.size() + 1)\n , sig(ioA, SIGINT)\n {\n dbcon = std::make_shared();\n pline = std::make_shared(dbcon, AKU_LINEAR_BACKOFF);\n int port = 4096;\n serv = std::make_shared(iovec, port, pline);\n pline->start();\n serv->start();\n }\n\n \/\/! Run IO service\n void start() {\n\n sig.async_wait(\n \/\/ Wait for sigint\n boost::bind(&Server::handle_sigint,\n this,\n boost::asio::placeholders::error)\n );\n\n auto iorun = [](IOService& io, boost::barrier& bar) {\n auto fn = [&]() {\n io.run();\n bar.wait();\n };\n return fn;\n };\n\n for (auto io: iovec) {\n std::thread iothread(iorun(*io, barrier));\n iothread.detach();\n }\n }\n\n void handle_sigint(boost::system::error_code err) {\n if (!err) {\n if (stopped++ == 0) {\n std::cout << \"SIGINT catched, stopping pipeline\" << std::endl;\n for (auto io: iovec) {\n io->stop();\n }\n pline->stop();\n serv->stop();\n barrier.wait();\n std::cout << \"Server stopped\" << std::endl;\n } else {\n std::cout << \"Already stopped (sigint)\" << std::endl;\n }\n } else {\n std::cout << \"Signal handler error \" << err.message() << std::endl;\n }\n }\n\n void stop() {\n if (stopped++ == 0) {\n serv->stop();\n std::cout << \"TcpServer stopped\" << std::endl;\n\n sig.cancel();\n\n \/\/ No need to joint I\/O threads, just wait until they completes.\n barrier.wait();\n std::cout << \"I\/O threads stopped\" << std::endl;\n\n pline->stop();\n std::cout << \"Pipeline stopped\" << std::endl;\n\n for (auto io: iovec) {\n io->stop();\n }\n std::cout << \"I\/O service stopped\" << std::endl;\n\n std::cout << dbcon->idsum << \" messages received\" << std::endl;\n } else {\n std::cout << \"Already stopped\" << std::endl;\n }\n }\n\n void wait() {\n while(!stopped) {\n sleep(1);\n }\n }\n};\n\n\nstruct Client {\n int nthreads;\n int count;\n boost::barrier start_barrier, stop_barrier;\n EndpointT endpoint;\n PerfTimer *timer;\n\n Client(EndpointT ep, PerfTimer *timer, int nthreads = 4, int count = 2500000)\n : nthreads(nthreads)\n , count(count)\n , start_barrier(nthreads + 1)\n , stop_barrier(nthreads + 1)\n , endpoint(ep)\n , timer(timer)\n {\n }\n\n void start() {\n auto self = this;\n auto push = [self]() {\n std::vector threshold_values;\n IOService io;\n TcpSocket socket(io);\n std::cout << \"Connecting to server at \" << self->endpoint << std::endl;\n socket.connect(self->endpoint);\n self->start_barrier.wait();\n\n boost::asio::streambuf stream;\n std::ostream os(&stream);\n size_t nsent = 0u;\n double tm = self->timer->elapsed();\n for (int i = self->count; i --> 0; ) {\n os << \":1\\r\\n\" \":2\\r\\n\" \"+3.14\\r\\n\";\n nsent += boost::asio::write(socket, stream);\n if (nsent >= 1024*1024) { \/\/ +1Mb was sent\n double newtm = self->timer->elapsed();\n threshold_values.push_back(newtm - tm);\n nsent = 0u;\n tm = newtm;\n }\n }\n socket.shutdown(TcpSocket::shutdown_both);\n self->stop_barrier.wait();\n std::cout << \"Push process completed\" << std::endl;\n if (threshold_values.size()) {\n std::sort(threshold_values.begin(), threshold_values.end());\n double min = threshold_values.front(), max = threshold_values.back();\n double sum = 0, avg = 0, med = threshold_values[threshold_values.size() \/ 2];\n for (auto x: threshold_values) { sum += x; }\n avg = sum \/ threshold_values.size();\n auto convert = [&](double val) {\n \/\/ Convert seconds per Mb to Mb per second\n return 1.0\/val;\n };\n std::cout << \"Push process performance\" << std::endl;\n std::cout << \"max: \" << convert(min) << \" Mb\/sec\" << std::endl; \/\/ min and max should be\n std::cout << \"min: \" << convert(max) << \" Mb\/sec\" << std::endl; \/\/ swapped because of conv\n std::cout << \"avg: \" << convert(avg) << \" Mb\/sec\" << std::endl;\n std::cout << \"med: \" << convert(med) << \" Mb\/sec\" << std::endl;\n }\n };\n\n for (int i = 0; i < nthreads; i++) {\n std::thread th(push);\n th.detach();\n }\n\n start_barrier.wait();\n timer->restart();\n }\n\n void wait() {\n stop_barrier.wait();\n }\n};\n\nint main(int argc, char *argv[]) {\n std::cout << \"Tcp server performance test\" << std::endl;\n po::options_description desc(\"Allowed options\");\n \/*\n * Parameters:\n * a) `mode` can accept three parameters - 'client', 'server' or 'local'.\n * b) `host` url or ip of the server if app was started in client mode.\n * c) `count` number of messages to send inf started in client mode.\n * d) `njobs` number of threads to use\n *\/\n std::string strmode;\n std::string host;\n int num_messages;\n bool graphite_enabled = false;\n desc.add_options()\n (\"help\", \"produce help message\")\n (\"mode\", po::value(&strmode)->default_value(\"local\"), \"test mode\")\n (\"host\", po::value(&host)->default_value(\"localhost\"), \"server host in client mode\")\n (\"count\", po::value(&num_messages)->default_value(1000000), \"number of messages to send\")\n (\"graphite\", po::value(&graphite_enabled)->default_value(false), \"push result to graphite\")\n ;\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 0;\n }\n\n Mode mode = str_to_mode(strmode);\n\n switch(mode) {\n case LOCAL: {\n PerfTimer tm;\n Server server(mode);\n EndpointT ep(boost::asio::ip::address_v4::loopback(), 4096);\n Client client(ep, &tm, 4, 2500000);\n server.start();\n client.start();\n client.wait();\n server.stop();\n double elapsed = tm.elapsed();\n std::cout << \"Local test completed in \" << elapsed << \" seconds\" << std::endl;\n if (graphite_enabled) {\n push_metric_to_graphite(\"tcp_server_local\", elapsed);\n }\n break;\n }\n case SERVER: {\n PerfTimer tm;\n Server server(mode);\n server.start();\n server.wait();\n server.stop();\n break;\n }\n case CLIENT:\n PerfTimer tm;\n Server server(mode);\n EndpointT ep(boost::asio::ip::address_v4::from_string(host), 4096);\n Client client(ep, &tm, 1, num_messages);\n client.start();\n client.wait();\n break;\n }\n\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"BasicBlock.h\"\n\n#include \n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"Type.h\"\n#include \"Utils.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nBasicBlock::BasicBlock(instr_idx _firstInstrIdx, code_iterator _begin, code_iterator _end, llvm::Function* _mainFunc):\n\tm_firstInstrIdx{_firstInstrIdx},\n\tm_begin(_begin),\n\tm_end(_end),\n\tm_llvmBB(llvm::BasicBlock::Create(_mainFunc->getContext(), {\"Instr.\", std::to_string(_firstInstrIdx)}, _mainFunc))\n{}\n\nLocalStack::LocalStack(Stack& _globalStack):\n\tm_global(_globalStack)\n{}\n\nvoid LocalStack::push(llvm::Value* _value)\n{\n\tassert(_value->getType() == Type::Word);\n\tm_local.push_back(_value);\n\tm_maxSize = std::max(m_maxSize, size());\n}\n\nllvm::Value* LocalStack::pop()\n{\n\tauto item = get(0);\n\tassert(!m_local.empty() || !m_input.empty());\n\n\tif (m_local.size() > 0)\n\t\tm_local.pop_back();\n\telse\n\t\t++m_globalPops;\n\n\tm_minSize = std::min(m_minSize, size());\n\treturn item;\n}\n\n\/**\n * Pushes a copy of _index-th element (tos is 0-th elem).\n *\/\nvoid LocalStack::dup(size_t _index)\n{\n\tauto val = get(_index);\n\tpush(val);\n}\n\n\/**\n * Swaps tos with _index-th element (tos is 0-th elem).\n * _index must be > 0.\n *\/\nvoid LocalStack::swap(size_t _index)\n{\n\tassert(_index > 0);\n\tauto val = get(_index);\n\tauto tos = get(0);\n\tset(_index, tos);\n\tset(0, val);\n}\n\nllvm::Value* LocalStack::get(size_t _index)\n{\n\tif (_index < m_local.size())\n\t\treturn *(m_local.rbegin() + _index); \/\/ count from back\n\n\tauto idx = _index - m_local.size() + m_globalPops;\n\tif (idx >= m_input.size())\n\t\tm_input.resize(idx + 1);\n\tauto& item = m_input[idx];\n\n\tif (!item)\n\t\titem = m_global.get(idx);\n\n\treturn item;\n}\n\nvoid LocalStack::set(size_t _index, llvm::Value* _word)\n{\n\tif (_index < m_local.size())\n\t{\n\t\t*(m_local.rbegin() + _index) = _word;\n\t\treturn;\n\t}\n\n\tauto idx = _index - m_local.size() + m_globalPops;\n\tassert(idx < m_input.size());\n\tm_input[idx] = _word;\n}\n\n\nvoid LocalStack::finalize(llvm::IRBuilder<>& _builder, llvm::BasicBlock& _bb)\n{\n\tauto blockTerminator = _bb.getTerminator();\n\tassert(blockTerminator);\n\tif (blockTerminator->getOpcode() != llvm::Instruction::Ret)\n\t{\n\t\t\/\/ Not needed in case of ret instruction. Ret invalidates the stack.\n\t\t_builder.SetInsertPoint(blockTerminator);\n\n\t\t\/\/ Update items fetched from global stack ignoring the poped ones\n\t\tassert(m_globalPops <= m_input.size()); \/\/ pop() always does get()\n\t\tfor (auto i = m_globalPops; i < m_input.size(); ++i)\n\t\t{\n\t\t\tif (m_input[i])\n\t\t\t\tm_global.set(i, m_input[i]);\n\t\t}\n\n\t\t\/\/ Add new items\n\t\tfor (auto& item: m_local)\n\t\t{\n\t\t\tif (m_globalPops) \t\t\t\t\t\t\/\/ Override poped global items\n\t\t\t\tm_global.set(--m_globalPops, item);\t\/\/ using pops counter as the index\n\t\t\telse\n\t\t\t\tm_global.push(item);\n\t\t}\n\n\t\t\/\/ Pop not overriden items\n\t\tif (m_globalPops)\n\t\t\tm_global.pop(m_globalPops);\n\t}\n}\n\n\n}\n}\n}\nDo not modify pops counter of LocalStack during finalization.#include \"BasicBlock.h\"\n\n#include \n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"Type.h\"\n#include \"Utils.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nBasicBlock::BasicBlock(instr_idx _firstInstrIdx, code_iterator _begin, code_iterator _end, llvm::Function* _mainFunc):\n\tm_firstInstrIdx{_firstInstrIdx},\n\tm_begin(_begin),\n\tm_end(_end),\n\tm_llvmBB(llvm::BasicBlock::Create(_mainFunc->getContext(), {\"Instr.\", std::to_string(_firstInstrIdx)}, _mainFunc))\n{}\n\nLocalStack::LocalStack(Stack& _globalStack):\n\tm_global(_globalStack)\n{}\n\nvoid LocalStack::push(llvm::Value* _value)\n{\n\tassert(_value->getType() == Type::Word);\n\tm_local.push_back(_value);\n\tm_maxSize = std::max(m_maxSize, size());\n}\n\nllvm::Value* LocalStack::pop()\n{\n\tauto item = get(0);\n\tassert(!m_local.empty() || !m_input.empty());\n\n\tif (m_local.size() > 0)\n\t\tm_local.pop_back();\n\telse\n\t\t++m_globalPops;\n\n\tm_minSize = std::min(m_minSize, size());\n\treturn item;\n}\n\n\/**\n * Pushes a copy of _index-th element (tos is 0-th elem).\n *\/\nvoid LocalStack::dup(size_t _index)\n{\n\tauto val = get(_index);\n\tpush(val);\n}\n\n\/**\n * Swaps tos with _index-th element (tos is 0-th elem).\n * _index must be > 0.\n *\/\nvoid LocalStack::swap(size_t _index)\n{\n\tassert(_index > 0);\n\tauto val = get(_index);\n\tauto tos = get(0);\n\tset(_index, tos);\n\tset(0, val);\n}\n\nllvm::Value* LocalStack::get(size_t _index)\n{\n\tif (_index < m_local.size())\n\t\treturn *(m_local.rbegin() + _index); \/\/ count from back\n\n\tauto idx = _index - m_local.size() + m_globalPops;\n\tif (idx >= m_input.size())\n\t\tm_input.resize(idx + 1);\n\tauto& item = m_input[idx];\n\n\tif (!item)\n\t\titem = m_global.get(idx);\n\n\treturn item;\n}\n\nvoid LocalStack::set(size_t _index, llvm::Value* _word)\n{\n\tif (_index < m_local.size())\n\t{\n\t\t*(m_local.rbegin() + _index) = _word;\n\t\treturn;\n\t}\n\n\tauto idx = _index - m_local.size() + m_globalPops;\n\tassert(idx < m_input.size());\n\tm_input[idx] = _word;\n}\n\n\nvoid LocalStack::finalize(llvm::IRBuilder<>& _builder, llvm::BasicBlock& _bb)\n{\n\tauto blockTerminator = _bb.getTerminator();\n\tassert(blockTerminator);\n\tif (blockTerminator->getOpcode() != llvm::Instruction::Ret)\n\t{\n\t\t\/\/ Not needed in case of ret instruction. Ret invalidates the stack.\n\t\t_builder.SetInsertPoint(blockTerminator);\n\n\t\t\/\/ Update items fetched from global stack ignoring the poped ones\n\t\tassert(m_globalPops <= m_input.size()); \/\/ pop() always does get()\n\t\tfor (auto i = m_globalPops; i < m_input.size(); ++i)\n\t\t{\n\t\t\tif (m_input[i])\n\t\t\t\tm_global.set(i, m_input[i]);\n\t\t}\n\n\t\t\/\/ Add new items\n\t\tauto pops = m_globalPops;\t\t\t\/\/ Copy pops counter to keep original value\n\t\tfor (auto& item: m_local)\n\t\t{\n\t\t\tif (pops) \t\t\t\t\t\t\/\/ Override poped global items\n\t\t\t\tm_global.set(--pops, item);\t\/\/ using pops counter as the index\n\t\t\telse\n\t\t\t\tm_global.push(item);\n\t\t}\n\n\t\t\/\/ Pop not overriden items\n\t\tif (pops)\n\t\t\tm_global.pop(pops);\n\t}\n}\n\n\n}\n}\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * Extrae *\n * Instrumentation package for parallel applications *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version: $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n#include \"common.h\"\n\nstatic char UNUSED rcsid[] = \"$Id$\";\n\n#include \"applicationType.h\"\n\n#include \n#include \n\n#include \n\n#include \n\n\/* For Intel 8.x - 9.x (maybe 10.x?) *\/\n#define INTEL_PARLOOP_RTNS \".*_[0-9]+__par_loop[0-9]+.*\"\n#define INTEL_PARRGN_RTNS \".*_[0-9]+__par_region[0-9]+.*\"\n\nstring ApplicationType::TranslatePFToUF (string PF, OMP_rte_t type)\n{\n\tstring result;\n\n\tif (type == Intel_v8_1 || type == Intel_v9_1)\n\t{\n\t\tstring tmp1 = PF.substr (0, PF.rfind(\"__par_\"));\n\t\tstring tmp2 = tmp1.substr (0, tmp1.rfind(\"_\"));\n\n\t\tif (type == Intel_v8_1)\n\t\t\tresult = tmp2.substr (1, tmp2.length()-1);\n\t\telse \n\t\t\tresult = tmp2.substr (2, tmp2.length()-1);\n\t}\n\telse if (type == Intel_v11)\n\t{\n\t\t\/* We don't know how to handle this, if possible *\/\n\t\tresult = PF;\n\t}\n\telse if (type == IBM_v16)\n\t{\n\t\tresult = PF.substr (0, PF.find (\"$.OL$.\"));\n\t}\n\telse if (type == GNU_v42)\n\t{\n\t\tif (PF.find (\".omp_fn.\") != string::npos)\n\t\t\tresult = PF.substr (0, PF.find (\".omp_fn.\"));\n\t\telse if (PF.find (\"._omp_fn.\") != string::npos)\n\t\t\tresult = PF.substr (0, PF.find (\"._omp_fn.\"));\n\t\telse \/* unhandled *\/\n\t\t\tresult = PF;\n\t}\n\n\treturn result;\n}\n\nstring ApplicationType::demangleOpenMProutine (string name)\n{\n\treturn TranslatePFToUF (name, OpenMP_runtime);\n}\n\nApplicationType::OMP_rte_t ApplicationType::checkIntelOpenMPRuntime (BPatch_image *appImage)\n{\n\tBPatch_Vector found_funcs;\n\n\t\/* Check if there's any OpenMP parallel routine in the binary *\/\n\tif (appImage->findFunction (INTEL_PARLOOP_RTNS, found_funcs) != NULL)\n\t\tif (found_funcs.size() == 0)\n\t\t\tappImage->findFunction (INTEL_PARRGN_RTNS, found_funcs);\n\n\tif (found_funcs.size() > 0)\n\t{\n\t\tchar functionName[1024];\n\t\tfound_funcs[0]->getName (functionName, 1024);\n\t\tstring routinev8_1 = TranslatePFToUF (functionName, Intel_v8_1);\n\t\tstring routinev9_1 = TranslatePFToUF (functionName, Intel_v9_1);\n\n\t\tif (appImage->findFunction (routinev8_1.c_str(), found_funcs) != NULL)\n\t\t\tif (found_funcs.size() > 0)\n\t\t\t\treturn Intel_v8_1;\n\n\t\tif (appImage->findFunction (routinev9_1.c_str(), found_funcs) != NULL)\n\t\t\tif (found_funcs.size() > 0)\n\t\t\t\treturn Intel_v9_1;\n\t}\n\n\t\/* If we don't know about the runtime, try with icc v11 *\/\n\treturn Intel_v11;\n}\n\nbool ApplicationType::detectApplicationType_checkOpenMPrte (\n\tvector &routines, string library, BPatch_image *appImage)\n{\n\tbool result = false;\n\n\tunsigned numroutines = routines.size();\n\tfor (unsigned r = 0; r < numroutines && !result; r++)\n\t{\n\t\tBPatch_Vector found_funcs;\n\t\tfound_funcs = getRoutines (routines[r], appImage, false);\n\t\tunsigned numfuncs = found_funcs.size();\n\t\tfor (unsigned u = 0; u < numfuncs; u++)\n\t\t{\n\t\t\tchar buffer[1024];\n\t\t\tchar *module = found_funcs[u]->getModuleName (buffer, sizeof(buffer));\n\t\t\tresult = library == module;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nbool ApplicationType::detectApplicationType_checkGNUOpenMPrte (BPatch_image *appImage)\n{\n\tconst char *functions[] = {\"GOMP_parallel_start\",\n\t\t\"GOMP_loop_end\",\n\t\t\"GOMP_barrier\"};\n\tvector v (functions, functions+3);\n\n\treturn detectApplicationType_checkOpenMPrte (v, \"libgomp.so.1\", appImage);\n}\n\nbool ApplicationType::detectApplicationType_checkIntelOpenMPrte (BPatch_image *appImage)\n{\n\tconst char *functions[] = {\"__kmpc_fork_call\",\n\t\t\"__kmpc_invoke_task_func\",\n\t\t\"__kmpc_barrier\"};\n\tvector v (functions, functions+3);\n\n\treturn detectApplicationType_checkOpenMPrte (v, \"libiomp5.so\", appImage);\n}\n\nbool ApplicationType::detectApplicationType_checkIBMOpenMPrte (BPatch_image *appImage)\n{\n\tconst char *functions[] = {\"_xlsmpParallelDoSetup_TPO\",\n\t\t\"_xlsmpParRegionSetup_TPO\",\n\t\t\"_xlsmpWSDoSetup_TPO\" };\n\tvector v (functions, functions+3);\n\n\treturn detectApplicationType_checkOpenMPrte (v, \"libxlsmp.so.1\", appImage);\n}\n\nvoid ApplicationType::detectApplicationType (BPatch_image *appImage)\n{\n\tBPatch_Vector found_funcs;\n\n\tisOpenMP = isMPI = isCUDA = false;\n\n\t\/* Check for different implementation of OpenMP rte *\/\n\tif (detectApplicationType_checkIntelOpenMPrte (appImage))\n\t{\n\t\tisOpenMP = true;\n\t\tOpenMP_runtime = checkIntelOpenMPRuntime (appImage);\n\t}\n\telse if (detectApplicationType_checkGNUOpenMPrte (appImage))\n\t{\n\t\tisOpenMP = true;\n\t\tOpenMP_runtime = GNU_v42;\n\t}\n\telse if (detectApplicationType_checkIBMOpenMPrte (appImage))\n\t{\n\t\tOpenMP_runtime = IBM_v16;\n\t\tisOpenMP = true;\n\t}\n\n\t\/* MPI applications must have MPI_Init (or mpi_init fortran names) *\/\n\tif ((appImage->findFunction (\"MPI_Init\", found_funcs) != NULL) ||\n\t (appImage->findFunction (\"mpi_init\", found_funcs) != NULL) ||\n\t (appImage->findFunction (\"mpi_init_\", found_funcs) != NULL) ||\n\t (appImage->findFunction (\"mpi_init__\", found_funcs) != NULL) ||\n\t (appImage->findFunction (\"MPI_INIT\", found_funcs) != NULL))\n\t{\n\t\tisMPI = true;\n\t\tif (appImage->findFunction (\"mpi_init\", found_funcs) != NULL)\n\t\t\tMPI_type = MPI_Fortran_0u;\n\t\telse if (appImage->findFunction (\"mpi_init__\", found_funcs) != NULL)\n\t\t\tMPI_type = MPI_Fortran_2u;\n\t\telse if (appImage->findFunction (\"mpi_init_\", found_funcs) != NULL)\n\t\t\tMPI_type = MPI_Fortran_1u;\n\t\telse if (appImage->findFunction (\"MPI_INIT\", found_funcs) != NULL)\n\t\t\tMPI_type = MPI_Fortran_ucase;\n\t\telse \n\t\t\tMPI_type = MPI_C;\n\t}\n\n\t\/* Check for two typical CUDA routines in CUDA apps *\/\n\tif ((appImage->findFunction (\"cudaLaunch\", found_funcs) != NULL) &&\n\t (appImage->findFunction (\"cudaConfigureCall\", found_funcs) != NULL))\n\t\tisCUDA = true;\n}\n\nvoid ApplicationType::dumpApplicationType (void)\n{\n\tcout << PACKAGE_NAME << \": Detected application type: \";\n\tif (isOpenMP)\n\t{\n\t\tcout << \"OpenMP \";\n\t\tif (OpenMP_runtime == GNU_v42)\n\t\t\tcout << \"(GNU >= 4.2) \";\n\t\telse if (OpenMP_runtime == IBM_v16)\n\t\t\tcout << \"(IBM >= 1.6) \";\n\t\telse if (OpenMP_runtime == Intel_v8_1)\n\t\t\tcout << \"(Intel 8.x) \";\n\t\telse if (OpenMP_runtime == Intel_v9_1)\n\t\t\tcout << \"(Intel 9.x or 10.x) \";\n\t\telse if (OpenMP_runtime == Intel_v11)\n\t\t\tcout << \"(Intel >= 11.x) \";\n\t\telse\n\t\t\tcout << \"(Unknown) \";\n\t}\n\tif (isMPI)\n\t{\n\t\tcout << \"MPI \";\n\t\tif (MPI_type == MPI_C)\n\t\t\tcout << \"(C language) \";\n\t\telse if (MPI_type == MPI_Fortran_0u)\n\t\t\tcout << \"(Fortran language with 0 underscores) \";\n\t\telse if (MPI_type == MPI_Fortran_0u)\n\t\t\tcout << \"(Fortran language with 1 underscore) \";\n\t\telse if (MPI_type == MPI_Fortran_0u)\n\t\t\tcout << \"(Fortran language with 2 underscores) \";\n\t\telse if (MPI_type == MPI_Fortran_ucase)\n\t\t\tcout << \"(Fortran language in uppercase) \";\n\t}\n\tif (!isOpenMP && !isMPI)\n\t\tcout << \"Sequential \";\n\n\tif (isCUDA)\n\t\tcout << \"CUDA-accelerated\";\n\n\tcout << endl;\n}\n\nbool ApplicationType::isMangledOpenMProutine (string name)\n{\n\tbool result = false;\n\n\tif (OpenMP_runtime == Intel_v8_1 || OpenMP_runtime == Intel_v9_1)\n\t{\n\t\tresult = name.find (\"__par_loop\") != string::npos\n\t\t || \n\t\t name.find (\"__par_region\") != string::npos;\n\t}\n\telse if (OpenMP_runtime == Intel_v11)\n\t{\n\t\t\/* We don't know how to handle these *\/\n\t\tresult = false;\n\t}\n\telse if (OpenMP_runtime == IBM_v16)\n\t{\n\t\tresult = name.find (\"$.OL$.\") != string::npos;\n\t}\n\telse if (OpenMP_runtime == GNU_v42)\n\t{\n\t\tresult = name.find (\".omp_fn.\") != string::npos || name.find (\"._omp_fn.\") != string::npos;\n\t}\n\n\treturn result;\n}\nSmall fixes to allow insturmenting\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * Extrae *\n * Instrumentation package for parallel applications *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version: $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n#include \"common.h\"\n\nstatic char UNUSED rcsid[] = \"$Id$\";\n\n#include \"applicationType.h\"\n\n#include \n#include \n\n#include \n\n#include \n\n\/* For Intel 8.x - 9.x (maybe 10.x?) *\/\n#define INTEL_PARLOOP_RTNS \".*_[0-9]+__par_loop[0-9]+.*\"\n#define INTEL_PARRGN_RTNS \".*_[0-9]+__par_region[0-9]+.*\"\n\nstring ApplicationType::TranslatePFToUF (string PF, OMP_rte_t type)\n{\n\tstring result;\n\n\tif (type == Intel_v8_1 || type == Intel_v9_1)\n\t{\n\t\tstring tmp1 = PF.substr (0, PF.rfind(\"__par_\"));\n\t\tstring tmp2 = tmp1.substr (0, tmp1.rfind(\"_\"));\n\n\t\tif (type == Intel_v8_1)\n\t\t\tresult = tmp2.substr (1, tmp2.length()-1);\n\t\telse \n\t\t\tresult = tmp2.substr (2, tmp2.length()-1);\n\t}\n\telse if (type == Intel_v11)\n\t{\n\t\t\/* We don't know how to handle this, if possible *\/\n\t\tresult = PF;\n\t}\n\telse if (type == IBM_v16)\n\t{\n\t\tresult = PF.substr (0, PF.find (\"$.OL$.\"));\n\t}\n\telse if (type == GNU_v42)\n\t{\n\t\tif (PF.find (\".omp_fn.\") != string::npos)\n\t\t\tresult = PF.substr (0, PF.find (\".omp_fn.\"));\n\t\telse if (PF.find (\"._omp_fn.\") != string::npos)\n\t\t\tresult = PF.substr (0, PF.find (\"._omp_fn.\"));\n\t\telse \/* unhandled *\/\n\t\t\tresult = PF;\n\t}\n\n\treturn result;\n}\n\nstring ApplicationType::demangleOpenMProutine (string name)\n{\n\treturn TranslatePFToUF (name, OpenMP_runtime);\n}\n\nApplicationType::OMP_rte_t ApplicationType::checkIntelOpenMPRuntime (BPatch_image *appImage)\n{\n\tBPatch_Vector found_funcs;\n\n\t\/* Check if there's any OpenMP parallel routine in the binary *\/\n\tif (appImage->findFunction (INTEL_PARLOOP_RTNS, found_funcs) != NULL)\n\t\tif (found_funcs.size() == 0)\n\t\t\tappImage->findFunction (INTEL_PARRGN_RTNS, found_funcs);\n\n\tif (found_funcs.size() > 0)\n\t{\n\t\tchar functionName[1024];\n\t\tfound_funcs[0]->getName (functionName, 1024);\n\t\tstring routinev8_1 = TranslatePFToUF (functionName, Intel_v8_1);\n\t\tstring routinev9_1 = TranslatePFToUF (functionName, Intel_v9_1);\n\n\t\tif (appImage->findFunction (routinev8_1.c_str(), found_funcs) != NULL)\n\t\t\tif (found_funcs.size() > 0)\n\t\t\t\treturn Intel_v8_1;\n\n\t\tif (appImage->findFunction (routinev9_1.c_str(), found_funcs) != NULL)\n\t\t\tif (found_funcs.size() > 0)\n\t\t\t\treturn Intel_v9_1;\n\t}\n\n\t\/* If we don't know about the runtime, try with icc v11 *\/\n\treturn Intel_v11;\n}\n\nbool ApplicationType::detectApplicationType_checkOpenMPrte (\n\tvector &routines, string library, BPatch_image *appImage)\n{\n\tbool result = false;\n\n\tunsigned numroutines = routines.size();\n\tfor (unsigned r = 0; r < numroutines && !result; r++)\n\t{\n\t\tBPatch_Vector found_funcs;\n\t\tfound_funcs = getRoutines (routines[r], appImage, false);\n\t\tunsigned numfuncs = found_funcs.size();\n\t\tfor (unsigned u = 0; u < numfuncs && !result; u++)\n\t\t{\n\t\t\tchar buffer[1024];\n\t\t\tchar *module = found_funcs[u]->getModuleName (buffer, sizeof(buffer));\n\t\t\tstring smodule (module);\n\t\t\tresult = smodule.find (library) == 0;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nbool ApplicationType::detectApplicationType_checkGNUOpenMPrte (BPatch_image *appImage)\n{\n\tconst char *functions[] = {\"GOMP_parallel_start\",\n\t\t\"GOMP_loop_end\",\n\t\t\"GOMP_barrier\"};\n\tvector v (functions, functions+3);\n\n\treturn detectApplicationType_checkOpenMPrte (v, \"libgomp.so.1\", appImage);\n}\n\nbool ApplicationType::detectApplicationType_checkIntelOpenMPrte (BPatch_image *appImage)\n{\n\tconst char *functions[] = {\"__kmpc_fork_call\",\n\t\t\"__kmpc_invoke_task_func\",\n\t\t\"__kmpc_barrier\"};\n\tvector v (functions, functions+3);\n\n\treturn detectApplicationType_checkOpenMPrte (v, \"libiomp5.so\", appImage);\n}\n\nbool ApplicationType::detectApplicationType_checkIBMOpenMPrte (BPatch_image *appImage)\n{\n\tconst char *functions[] = {\"_xlsmpParallelDoSetup_TPO\",\n\t\t\"_xlsmpParRegionSetup_TPO\",\n\t\t\"_xlsmpWSDoSetup_TPO\" };\n\tvector v (functions, functions+3);\n\n\treturn detectApplicationType_checkOpenMPrte (v, \"libxlsmp.so.1\", appImage);\n}\n\nvoid ApplicationType::detectApplicationType (BPatch_image *appImage)\n{\n\tBPatch_Vector found_funcs;\n\n\tisOpenMP = isMPI = isCUDA = false;\n\n\t\/* Check for different implementation of OpenMP rte *\/\n\tif (detectApplicationType_checkIntelOpenMPrte (appImage))\n\t{\n\t\tisOpenMP = true;\n\t\tOpenMP_runtime = checkIntelOpenMPRuntime (appImage);\n\t}\n\telse if (detectApplicationType_checkGNUOpenMPrte (appImage))\n\t{\n\t\tisOpenMP = true;\n\t\tOpenMP_runtime = GNU_v42;\n\t}\n\telse if (detectApplicationType_checkIBMOpenMPrte (appImage))\n\t{\n\t\tisOpenMP = true;\n\t\tOpenMP_runtime = IBM_v16;\n\t}\n\n\t\/* MPI applications must have MPI_Init (or mpi_init fortran names) *\/\n\tif ((appImage->findFunction (\"MPI_Init\", found_funcs) != NULL) ||\n\t (appImage->findFunction (\"mpi_init\", found_funcs) != NULL) ||\n\t (appImage->findFunction (\"mpi_init_\", found_funcs) != NULL) ||\n\t (appImage->findFunction (\"mpi_init__\", found_funcs) != NULL) ||\n\t (appImage->findFunction (\"MPI_INIT\", found_funcs) != NULL))\n\t{\n\t\tisMPI = true;\n\t\tif (appImage->findFunction (\"mpi_init\", found_funcs) != NULL)\n\t\t\tMPI_type = MPI_Fortran_0u;\n\t\telse if (appImage->findFunction (\"mpi_init__\", found_funcs) != NULL)\n\t\t\tMPI_type = MPI_Fortran_2u;\n\t\telse if (appImage->findFunction (\"mpi_init_\", found_funcs) != NULL)\n\t\t\tMPI_type = MPI_Fortran_1u;\n\t\telse if (appImage->findFunction (\"MPI_INIT\", found_funcs) != NULL)\n\t\t\tMPI_type = MPI_Fortran_ucase;\n\t\telse \n\t\t\tMPI_type = MPI_C;\n\t}\n\n\t\/* Check for two typical CUDA routines in CUDA apps *\/\n\tif ((appImage->findFunction (\"cudaLaunch\", found_funcs) != NULL) &&\n\t (appImage->findFunction (\"cudaConfigureCall\", found_funcs) != NULL))\n\t\tisCUDA = true;\n}\n\nvoid ApplicationType::dumpApplicationType (void)\n{\n\tcout << PACKAGE_NAME << \": Detected application type: \";\n\tif (isOpenMP)\n\t{\n\t\tcout << \"OpenMP \";\n\t\tif (OpenMP_runtime == GNU_v42)\n\t\t\tcout << \"(GNU >= 4.2) \";\n\t\telse if (OpenMP_runtime == IBM_v16)\n\t\t\tcout << \"(IBM >= 1.6) \";\n\t\telse if (OpenMP_runtime == Intel_v8_1)\n\t\t\tcout << \"(Intel 8.x) \";\n\t\telse if (OpenMP_runtime == Intel_v9_1)\n\t\t\tcout << \"(Intel 9.x or 10.x) \";\n\t\telse if (OpenMP_runtime == Intel_v11)\n\t\t\tcout << \"(Intel >= 11.x) \";\n\t\telse\n\t\t\tcout << \"(Unknown) \";\n\t}\n\tif (isMPI)\n\t{\n\t\tcout << \"MPI \";\n\t\tif (MPI_type == MPI_C)\n\t\t\tcout << \"(C language) \";\n\t\telse if (MPI_type == MPI_Fortran_0u)\n\t\t\tcout << \"(Fortran language with 0 underscores) \";\n\t\telse if (MPI_type == MPI_Fortran_0u)\n\t\t\tcout << \"(Fortran language with 1 underscore) \";\n\t\telse if (MPI_type == MPI_Fortran_0u)\n\t\t\tcout << \"(Fortran language with 2 underscores) \";\n\t\telse if (MPI_type == MPI_Fortran_ucase)\n\t\t\tcout << \"(Fortran language in uppercase) \";\n\t}\n\tif (!isOpenMP && !isMPI)\n\t\tcout << \"Sequential \";\n\n\tif (isCUDA)\n\t\tcout << \"CUDA-accelerated\";\n\n\tcout << endl;\n}\n\nbool ApplicationType::isMangledOpenMProutine (string name)\n{\n\tbool result = false;\n\n\tif (OpenMP_runtime == Intel_v8_1 || OpenMP_runtime == Intel_v9_1)\n\t{\n\t\tresult = name.find (\"__par_loop\") != string::npos\n\t\t || \n\t\t name.find (\"__par_region\") != string::npos;\n\t}\n\telse if (OpenMP_runtime == Intel_v11)\n\t{\n\t\t\/* We don't know how to handle these *\/\n\t\tresult = false;\n\t}\n\telse if (OpenMP_runtime == IBM_v16)\n\t{\n\t\tresult = name.find (\"$.OL$.\") != string::npos;\n\t}\n\telse if (OpenMP_runtime == GNU_v42)\n\t{\n\t\tresult = name.find (\".omp_fn.\") != string::npos || name.find (\"._omp_fn.\") != string::npos;\n\t}\n\n\treturn result;\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Project: RooFit *\n * Package: RooFitCore *\n * File: $Id: RooIntegratorConfig.cc,v 1.5 2002\/09\/05 04:33:35 verkerke Exp $\n * Authors: *\n * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *\n * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *\n * *\n * Copyright (c) 2000-2002, Regents of the University of California *\n * and Stanford University. All rights reserved. *\n * *\n * Redistribution and use in source and binary forms, *\n * with or without modification, are permitted according to the terms *\n * listed in LICENSE (http:\/\/roofit.sourceforge.net\/license.txt) *\n *****************************************************************************\/\n\n\/\/ -- CLASS DESCRIPTION [MISC] --\n\/\/ RooIntegratorConfig holds the configuration parameters of the various\n\/\/ numeric integrators used by RooRealIntegral. RooRealIntegral and RooAbsPdf\n\/\/ use this class in the (normalization) integral configuration interface\n\n#include \"RooFitCore\/RooIntegratorConfig.hh\"\n\nClassImp(RooIntegratorConfig)\n;\n\nRooIntegratorConfig::RooIntegratorConfig()\n{\n \/\/ 1D integrator\n _rule = RooIntegrator1D::Trapezoid ;\n _maxSteps = 20 ;\n _epsRel = 1e-6 ;\n _epsAbs = 1e-6 ;\n\n \/\/ 2D integrator\n _useMCFor2D = kFALSE ;\n\n \/\/ MC Integrator\n _mode = RooMCIntegrator::Importance ;\n _genType = RooMCIntegrator::QuasiRandom ;\n _verboseMC = kFALSE ;\n _alpha = 1.5 ;\n _nRefineIter = 5 ;\n _nRefinePerDim = 1000 ;\n _nIntegratePerDim = 5000 ; \n}\n\nRooIntegratorConfig::~RooIntegratorConfig()\n{\n}\n\nRooIntegratorConfig::RooIntegratorConfig(const RooIntegratorConfig& other) \n{\n \/\/ 1D integrator\n _rule = other._rule ;\n _maxSteps = other._maxSteps ;\n _epsRel = other._epsRel ;\n _epsAbs = other._epsAbs ;\n\n\n \/\/ 2D integrator\n _useMCFor2D = other._useMCFor2D ;\n\n \/\/ MC Integrator\n _mode = other._mode ;\n _genType = other._genType ;\n _verboseMC = other._verboseMC ;\n _alpha = other._alpha ;\n _nRefineIter = other._nRefineIter ;\n _nRefinePerDim = other._nRefinePerDim ;\n _nIntegratePerDim = other._nIntegratePerDim ;\n}\n\/*****************************************************************************\n * Project: RooFit *\n * Package: RooFitCore *\n * File: $Id: RooIntegratorConfig.cc,v 1.6 2003\/05\/07 21:06:25 wverkerke Exp $\n * Authors: *\n * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *\n * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *\n * *\n * Copyright (c) 2000-2002, Regents of the University of California *\n * and Stanford University. All rights reserved. *\n * *\n * Redistribution and use in source and binary forms, *\n * with or without modification, are permitted according to the terms *\n * listed in LICENSE (http:\/\/roofit.sourceforge.net\/license.txt) *\n *****************************************************************************\/\n\n\/\/ -- CLASS DESCRIPTION [MISC] --\n\/\/ RooIntegratorConfig holds the configuration parameters of the various\n\/\/ numeric integrators used by RooRealIntegral. RooRealIntegral and RooAbsPdf\n\/\/ use this class in the (normalization) integral configuration interface\n\n#include \"RooFitCore\/RooIntegratorConfig.hh\"\n\nClassImp(RooIntegratorConfig)\n;\n\nRooIntegratorConfig::RooIntegratorConfig()\n{\n \/\/ 1D integrator\n _rule = RooIntegrator1D::Trapezoid ;\n _maxSteps = 20 ;\n _epsRel = 1e-6 ;\n _epsAbs = 1e-6 ;\n\n \/\/ 2D integrator\n _useMCFor2D = kTRUE ;\n\n \/\/ MC Integrator\n _mode = RooMCIntegrator::Importance ;\n _genType = RooMCIntegrator::QuasiRandom ;\n _verboseMC = kFALSE ;\n _alpha = 1.5 ;\n _nRefineIter = 5 ;\n _nRefinePerDim = 1000 ;\n _nIntegratePerDim = 5000 ; \n}\n\nRooIntegratorConfig::~RooIntegratorConfig()\n{\n}\n\nRooIntegratorConfig::RooIntegratorConfig(const RooIntegratorConfig& other) \n{\n \/\/ 1D integrator\n _rule = other._rule ;\n _maxSteps = other._maxSteps ;\n _epsRel = other._epsRel ;\n _epsAbs = other._epsAbs ;\n\n\n \/\/ 2D integrator\n _useMCFor2D = other._useMCFor2D ;\n\n \/\/ MC Integrator\n _mode = other._mode ;\n _genType = other._genType ;\n _verboseMC = other._verboseMC ;\n _alpha = other._alpha ;\n _nRefineIter = other._nRefineIter ;\n _nRefinePerDim = other._nRefinePerDim ;\n _nIntegratePerDim = other._nIntegratePerDim ;\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/\/TESTED_COMPONENT=src\/systeminfo\n\n#include \n#include \"qsysteminfo.h\"\n#include \"..\/qsysteminfotestcommon.h\"\n\nQTM_USE_NAMESPACE\nQ_DECLARE_METATYPE(QSystemDeviceInfo::BatteryStatus);\nQ_DECLARE_METATYPE(QSystemDeviceInfo::PowerState);\nQ_DECLARE_METATYPE(QSystemDeviceInfo::InputMethodFlags);\nQ_DECLARE_METATYPE(QSystemDeviceInfo::Profile);\nQ_DECLARE_METATYPE(QSystemDeviceInfo::SimStatus);\n\nQ_DECLARE_METATYPE(QSystemDeviceInfo::KeyboardTypeFlags);\n\nclass tst_QSystemDeviceInfo : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n\n void initTestCase();\n void tst_inputMethodType();\n\n void tst_imei();\n void tst_imsi();\n void tst_manufacturer();\n void tst_model();\n void tst_productName();\n\n void tst_batteryLevel();\n void tst_batteryStatus();\n\n void tst_currentProfile();\n\n void tst_simStatus();\n\n void tst_isDeviceLocked();\n\n void tst_currentPowerState();\n\n void tst_currentBluetoothPowerState();\n\n void tst_keyboardType();\n void tst_isWirelessKeyboardConnected();\n void tst_isKeyboardFlipOpen();\n\n};\n\/*\nsignal todo:\n\/\/ void profileChanged(QSystemDeviceInfo::Profile);\n void batteryLevelChanged(QSystemDeviceInfo::BatteryLevel);\n void batteryLevelCritical(qint32);\n void powerStateChanged(QSystemDeviceInfo::PowerState);\n *\/\n\nvoid tst_QSystemDeviceInfo::initTestCase()\n{\n qRegisterMetaType(\"QSystemDeviceInfo::BatteryStatus\");\n qRegisterMetaType(\"QSystemDeviceInfo::PowerState\");\n\n qRegisterMetaType(\"QSystemDeviceInfo::InputMethodFlags\");\n qRegisterMetaType(\"QSystemDeviceInfo::Profile\");\n\n qRegisterMetaType(\"QSystemDeviceInfo::SimStatus\");\n\n qRegisterMetaType(\"QSystemDeviceInfo::KeyboardTypeFlags\");\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_inputMethodType()\n{\n QSystemDeviceInfo di;\n QVERIFY( di.inputMethodType() != 0\n || di.inputMethodType() == 0);\n}\n\nvoid tst_QSystemDeviceInfo::tst_imei()\n{\n QSystemDeviceInfo di;\n QString imeiStr =di.imei();\n QVERIFY(!imeiStr.isEmpty() || imeiStr.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_imsi()\n{\n QSystemDeviceInfo di;\n QString imsiStr = di.imsi();\n QVERIFY(!imsiStr.isEmpty() || imsiStr.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_manufacturer()\n{\n QSystemDeviceInfo di;\n QString manu = di.manufacturer();\n QVERIFY(!manu.isEmpty() || manu.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_model()\n{\n QSystemDeviceInfo di;\n QString model = di.model();\n QVERIFY(!model.isEmpty() || model.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_productName()\n{\n QSystemDeviceInfo di;\n QString product = di.productName();\n QVERIFY(!product.isEmpty() | product.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_batteryLevel()\n{\n QSystemDeviceInfo di;\n QVERIFY(di.batteryLevel() > -1);\n\n\/\/ until we simulate this, or wait the signalspy to olong, this will always fail\n\/\/ if(di.currentPowerState() == QSystemDeviceInfo::WallPowerChargingBattery) {\n\/\/ QSignalSpy batSpy(&di, SIGNAL(batteryLevelChanged(int)));\n\/\/ QVERIFY(!batSpy.isEmpty());\n\/\/ int level = batSpy.first().at(0).toInt();\n\/\/ QVERIFY( level > -1 || level < 101);\n\/\/ }\n}\n\nvoid tst_QSystemDeviceInfo::tst_batteryStatus()\n{\n QSystemDeviceInfo di;\n int level = di.batteryLevel();\n if(level < 4) {\n QVERIFY(di.batteryStatus() ==QSystemDeviceInfo::BatteryCritical );\n } else if(level < 11) {\n QVERIFY(di.batteryStatus() == QSystemDeviceInfo::BatteryVeryLow);\n } else if(level < 41) {\n QVERIFY(di.batteryStatus() == QSystemDeviceInfo::BatteryLow);\n } else if(level > 40) {\n QVERIFY(di.batteryStatus() == QSystemDeviceInfo::BatteryNormal);\n }\n\n \/\/ until we simulate this, or wait the signalspy to olong, this will always fail\n\/\/ if(di.currentPowerState() == QSystemDeviceInfo::WallPowerChargingBattery) {\n\/\/ QSignalSpy batSpy(&di, SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));\n\/\/ QVERIFY(!batSpy.isEmpty());\n\/\/ QSystemDeviceInfo::BatteryStatus status = qvariant_cast(batSpy.first().at(0));\n\/\/ QVERIFY( status == QSystemDeviceInfo::NoBatteryLevel\n\/\/ || status == QSystemDeviceInfo::BatteryCritical\n\/\/ || status == QSystemDeviceInfo::BatteryVeryLow\n\/\/ || status == QSystemDeviceInfo::BatteryLow\n\/\/ || status == QSystemDeviceInfo::BatteryNormal);\n\/\/ }\n}\n\nvoid tst_QSystemDeviceInfo::tst_currentProfile()\n{\n QSystemDeviceInfo di;\n QSystemDeviceInfo::Profile profile = di.currentProfile();\n QVERIFY( profile == QSystemDeviceInfo::UnknownProfile\n || profile == QSystemDeviceInfo::SilentProfile\n || profile == QSystemDeviceInfo::NormalProfile\n || profile == QSystemDeviceInfo::LoudProfile\n || profile == QSystemDeviceInfo::VibProfile\n || profile == QSystemDeviceInfo::OfflineProfile\n || profile == QSystemDeviceInfo::PowersaveProfile\n || profile == QSystemDeviceInfo::CustomProfile);\n}\n\nvoid tst_QSystemDeviceInfo::tst_simStatus()\n{\n QSystemDeviceInfo di;\n bool simStat = di.simStatus();\n QVERIFY(simStat == true || simStat == false);\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_isDeviceLocked()\n{\n QSystemDeviceInfo di;\n bool devLock = di.isDeviceLocked();\n QVERIFY(devLock == true || devLock == false);\n}\n\nvoid tst_QSystemDeviceInfo::tst_currentPowerState()\n{\n QSystemDeviceInfo di;\n QSystemDeviceInfo::PowerState state = di.currentPowerState();\n QVERIFY( state == QSystemDeviceInfo::UnknownPower\n || state == QSystemDeviceInfo::BatteryPower\n || state == QSystemDeviceInfo::WallPower\n || state == QSystemDeviceInfo::WallPowerChargingBattery);\n}\n\nvoid tst_QSystemDeviceInfo::tst_currentBluetoothPowerState()\n{\n QSystemDeviceInfo di;\n bool state = di.currentPowerState();\n QVERIFY(state || !state);\n}\n\n\nvoid tst_QSystemDeviceInfo::tst_keyboardType()\n{\n QSystemDeviceInfo di;\n QSystemDeviceInfo::KeyboardTypeFlags flags = di.keyboardType();\n\n QVERIFY( (flags && QSystemDeviceInfo::UnknownKeyboard == QSystemDeviceInfo::UnknownKeyboard)\n || (flags && QSystemDeviceInfo::SoftwareKeyboard == QSystemDeviceInfo::SoftwareKeyboard)\n || (flags && QSystemDeviceInfo::ITUKeypad == QSystemDeviceInfo::ITUKeypad)\n || (flags && QSystemDeviceInfo::HalfQwertyKeyboard == QSystemDeviceInfo::HalfQwertyKeyboard)\n || (flags && QSystemDeviceInfo::FullQwertyKeyboard == QSystemDeviceInfo::FullQwertyKeyboard)\n || (flags && QSystemDeviceInfo::WirelessKeyboard == QSystemDeviceInfo::WirelessKeyboard));\n}\n\nvoid tst_QSystemDeviceInfo::tst_isWirelessKeyboardConnected()\n{\n QSystemDeviceInfo di;\n bool on = di.isWirelessKeyboardConnected();\n QVERIFY(on || !on);\n}\n\nvoid tst_QSystemDeviceInfo::tst_isKeyboardFlipOpen()\n{\n QSystemDeviceInfo di;\n bool on = di.isKeyboardFlipOpen();\n QVERIFY(on || !on);\n}\n\n\nQTEST_MAIN(tst_QSystemDeviceInfo)\n#include \"tst_qsystemdeviceinfo.moc\"\nadd some tests fro new functions\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/\/TESTED_COMPONENT=src\/systeminfo\n\n#include \n#include \"qsysteminfo.h\"\n#include \"..\/qsysteminfotestcommon.h\"\n\nQTM_USE_NAMESPACE\nQ_DECLARE_METATYPE(QSystemDeviceInfo::BatteryStatus);\nQ_DECLARE_METATYPE(QSystemDeviceInfo::PowerState);\nQ_DECLARE_METATYPE(QSystemDeviceInfo::InputMethodFlags);\nQ_DECLARE_METATYPE(QSystemDeviceInfo::Profile);\nQ_DECLARE_METATYPE(QSystemDeviceInfo::SimStatus);\n\nQ_DECLARE_METATYPE(QSystemDeviceInfo::KeyboardTypeFlags);\n\nclass tst_QSystemDeviceInfo : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n\n void initTestCase();\n void tst_inputMethodType();\n\n void tst_imei();\n void tst_imsi();\n void tst_manufacturer();\n void tst_model();\n void tst_productName();\n\n void tst_batteryLevel();\n void tst_batteryStatus();\n\n void tst_currentProfile();\n\n void tst_simStatus();\n\n void tst_isDeviceLocked();\n\n void tst_currentPowerState();\n\n void tst_currentBluetoothPowerState();\n\n void tst_keyboardType();\n void tst_isWirelessKeyboardConnected();\n void tst_isKeyboardFlipOpen();\n void tst_keypadLightOn();\n void tst_backLightOn();\n void tst_hostId();\n\n};\n\/*\nsignal todo:\n\/\/ void profileChanged(QSystemDeviceInfo::Profile);\n void batteryLevelChanged(QSystemDeviceInfo::BatteryLevel);\n void batteryLevelCritical(qint32);\n void powerStateChanged(QSystemDeviceInfo::PowerState);\n *\/\n\nvoid tst_QSystemDeviceInfo::initTestCase()\n{\n qRegisterMetaType(\"QSystemDeviceInfo::BatteryStatus\");\n qRegisterMetaType(\"QSystemDeviceInfo::PowerState\");\n\n qRegisterMetaType(\"QSystemDeviceInfo::InputMethodFlags\");\n qRegisterMetaType(\"QSystemDeviceInfo::Profile\");\n\n qRegisterMetaType(\"QSystemDeviceInfo::SimStatus\");\n\n qRegisterMetaType(\"QSystemDeviceInfo::KeyboardTypeFlags\");\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_inputMethodType()\n{\n QSystemDeviceInfo di;\n QVERIFY( di.inputMethodType() != 0\n || di.inputMethodType() == 0);\n}\n\nvoid tst_QSystemDeviceInfo::tst_imei()\n{\n QSystemDeviceInfo di;\n QString imeiStr =di.imei();\n QVERIFY(!imeiStr.isEmpty() || imeiStr.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_imsi()\n{\n QSystemDeviceInfo di;\n QString imsiStr = di.imsi();\n QVERIFY(!imsiStr.isEmpty() || imsiStr.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_manufacturer()\n{\n QSystemDeviceInfo di;\n QString manu = di.manufacturer();\n QVERIFY(!manu.isEmpty() || manu.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_model()\n{\n QSystemDeviceInfo di;\n QString model = di.model();\n QVERIFY(!model.isEmpty() || model.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_productName()\n{\n QSystemDeviceInfo di;\n QString product = di.productName();\n QVERIFY(!product.isEmpty() | product.isEmpty());\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_batteryLevel()\n{\n QSystemDeviceInfo di;\n QVERIFY(di.batteryLevel() > -1);\n\n\/\/ until we simulate this, or wait the signalspy to olong, this will always fail\n\/\/ if(di.currentPowerState() == QSystemDeviceInfo::WallPowerChargingBattery) {\n\/\/ QSignalSpy batSpy(&di, SIGNAL(batteryLevelChanged(int)));\n\/\/ QVERIFY(!batSpy.isEmpty());\n\/\/ int level = batSpy.first().at(0).toInt();\n\/\/ QVERIFY( level > -1 || level < 101);\n\/\/ }\n}\n\nvoid tst_QSystemDeviceInfo::tst_batteryStatus()\n{\n QSystemDeviceInfo di;\n int level = di.batteryLevel();\n if(level < 4) {\n QVERIFY(di.batteryStatus() ==QSystemDeviceInfo::BatteryCritical );\n } else if(level < 11) {\n QVERIFY(di.batteryStatus() == QSystemDeviceInfo::BatteryVeryLow);\n } else if(level < 41) {\n QVERIFY(di.batteryStatus() == QSystemDeviceInfo::BatteryLow);\n } else if(level > 40) {\n QVERIFY(di.batteryStatus() == QSystemDeviceInfo::BatteryNormal);\n }\n\n \/\/ until we simulate this, or wait the signalspy to olong, this will always fail\n\/\/ if(di.currentPowerState() == QSystemDeviceInfo::WallPowerChargingBattery) {\n\/\/ QSignalSpy batSpy(&di, SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));\n\/\/ QVERIFY(!batSpy.isEmpty());\n\/\/ QSystemDeviceInfo::BatteryStatus status = qvariant_cast(batSpy.first().at(0));\n\/\/ QVERIFY( status == QSystemDeviceInfo::NoBatteryLevel\n\/\/ || status == QSystemDeviceInfo::BatteryCritical\n\/\/ || status == QSystemDeviceInfo::BatteryVeryLow\n\/\/ || status == QSystemDeviceInfo::BatteryLow\n\/\/ || status == QSystemDeviceInfo::BatteryNormal);\n\/\/ }\n}\n\nvoid tst_QSystemDeviceInfo::tst_currentProfile()\n{\n QSystemDeviceInfo di;\n QSystemDeviceInfo::Profile profile = di.currentProfile();\n QVERIFY( profile == QSystemDeviceInfo::UnknownProfile\n || profile == QSystemDeviceInfo::SilentProfile\n || profile == QSystemDeviceInfo::NormalProfile\n || profile == QSystemDeviceInfo::LoudProfile\n || profile == QSystemDeviceInfo::VibProfile\n || profile == QSystemDeviceInfo::OfflineProfile\n || profile == QSystemDeviceInfo::PowersaveProfile\n || profile == QSystemDeviceInfo::CustomProfile);\n}\n\nvoid tst_QSystemDeviceInfo::tst_simStatus()\n{\n QSystemDeviceInfo di;\n bool simStat = di.simStatus();\n QVERIFY(simStat == true || simStat == false);\n\n}\n\nvoid tst_QSystemDeviceInfo::tst_isDeviceLocked()\n{\n QSystemDeviceInfo di;\n bool devLock = di.isDeviceLocked();\n QVERIFY(devLock == true || devLock == false);\n}\n\nvoid tst_QSystemDeviceInfo::tst_currentPowerState()\n{\n QSystemDeviceInfo di;\n QSystemDeviceInfo::PowerState state = di.currentPowerState();\n QVERIFY( state == QSystemDeviceInfo::UnknownPower\n || state == QSystemDeviceInfo::BatteryPower\n || state == QSystemDeviceInfo::WallPower\n || state == QSystemDeviceInfo::WallPowerChargingBattery);\n}\n\nvoid tst_QSystemDeviceInfo::tst_currentBluetoothPowerState()\n{\n QSystemDeviceInfo di;\n bool state = di.currentPowerState();\n QVERIFY(state || !state);\n}\n\n\nvoid tst_QSystemDeviceInfo::tst_keyboardType()\n{\n QSystemDeviceInfo di;\n QSystemDeviceInfo::KeyboardTypeFlags flags = di.keyboardType();\n\n QVERIFY( (flags && QSystemDeviceInfo::UnknownKeyboard == QSystemDeviceInfo::UnknownKeyboard)\n || (flags && QSystemDeviceInfo::SoftwareKeyboard == QSystemDeviceInfo::SoftwareKeyboard)\n || (flags && QSystemDeviceInfo::ITUKeypad == QSystemDeviceInfo::ITUKeypad)\n || (flags && QSystemDeviceInfo::HalfQwertyKeyboard == QSystemDeviceInfo::HalfQwertyKeyboard)\n || (flags && QSystemDeviceInfo::FullQwertyKeyboard == QSystemDeviceInfo::FullQwertyKeyboard)\n || (flags && QSystemDeviceInfo::WirelessKeyboard == QSystemDeviceInfo::WirelessKeyboard));\n}\n\nvoid tst_QSystemDeviceInfo::tst_isWirelessKeyboardConnected()\n{\n QSystemDeviceInfo di;\n bool on = di.isWirelessKeyboardConnected();\n QVERIFY(on || !on);\n}\n\nvoid tst_QSystemDeviceInfo::tst_isKeyboardFlipOpen()\n{\n QSystemDeviceInfo di;\n bool on = di.isKeyboardFlipOpen();\n QVERIFY(on || !on);\n}\n\nvoid tst_QSystemDeviceInfo::tst_keypadLightOn()\n{\n QSystemDeviceInfo di;\n bool on = di.keypadLightOn();\n QVERIFY(on || !on);\n}\n\nvoid tst_QSystemDeviceInfo::tst_backLightOn()\n{\n QSystemDeviceInfo di;\n bool on = di.backLightOn();\n QVERIFY(on || !on);\n}\n\nvoid tst_QSystemDeviceInfo::tst_hostId()\n{\n QSystemDeviceInfo di;\n quint64 id = di.hostId();\n qDebug() << id;\n QVERIFY(id == 0 || id > 0);\n}\n\nQTEST_MAIN(tst_QSystemDeviceInfo)\n#include \"tst_qsystemdeviceinfo.moc\"\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2020-2021 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace i2p {\n\n\/**\n * Swap Standard Base64 <-> I2P Base64.\n * Standard Base64 uses `+` and `\/` as last two characters of its alphabet.\n * I2P Base64 uses `-` and `~` respectively.\n * So it is easy to detect in which one is the input and convert to the other.\n * @param[in] from Input to convert.\n * @return converted `from`\n *\/\nstatic std::string SwapBase64(const std::string& from)\n{\n std::string to;\n to.resize(from.size());\n for (size_t i = 0; i < from.size(); ++i) {\n switch (from[i]) {\n case '-':\n to[i] = '+';\n break;\n case '~':\n to[i] = '\/';\n break;\n case '+':\n to[i] = '-';\n break;\n case '\/':\n to[i] = '~';\n break;\n default:\n to[i] = from[i];\n break;\n }\n }\n return to;\n}\n\n\/**\n * Decode an I2P-style Base64 string.\n * @param[in] i2p_b64 I2P-style Base64 string.\n * @return decoded `i2p_b64`\n * @throw std::runtime_error if decoding fails\n *\/\nstatic Binary DecodeI2PBase64(const std::string& i2p_b64)\n{\n const std::string& std_b64 = SwapBase64(i2p_b64);\n auto decoded = DecodeBase64(std_b64);\n if (!decoded) {\n throw std::runtime_error(strprintf(\"Cannot decode Base64: \\\"%s\\\"\", i2p_b64));\n }\n return std::move(*decoded);\n}\n\n\/**\n * Derive the .b32.i2p address of an I2P destination (binary).\n * @param[in] dest I2P destination.\n * @return the address that corresponds to `dest`\n * @throw std::runtime_error if conversion fails\n *\/\nstatic CNetAddr DestBinToAddr(const Binary& dest)\n{\n CSHA256 hasher;\n hasher.Write(dest.data(), dest.size());\n unsigned char hash[CSHA256::OUTPUT_SIZE];\n hasher.Finalize(hash);\n\n CNetAddr addr;\n const std::string addr_str = EncodeBase32(hash, false) + \".b32.i2p\";\n if (!addr.SetSpecial(addr_str)) {\n throw std::runtime_error(strprintf(\"Cannot parse I2P address: \\\"%s\\\"\", addr_str));\n }\n\n return addr;\n}\n\n\/**\n * Derive the .b32.i2p address of an I2P destination (I2P-style Base64).\n * @param[in] dest I2P destination.\n * @return the address that corresponds to `dest`\n * @throw std::runtime_error if conversion fails\n *\/\nstatic CNetAddr DestB64ToAddr(const std::string& dest)\n{\n const Binary& decoded = DecodeI2PBase64(dest);\n return DestBinToAddr(decoded);\n}\n\nnamespace sam {\n\nSession::Session(const fs::path& private_key_file,\n const CService& control_host,\n CThreadInterrupt* interrupt)\n : m_private_key_file{private_key_file},\n m_control_host{control_host},\n m_interrupt{interrupt},\n m_control_sock{std::make_unique(INVALID_SOCKET)},\n m_transient{false}\n{\n}\n\nSession::Session(const CService& control_host, CThreadInterrupt* interrupt)\n : m_control_host{control_host},\n m_interrupt{interrupt},\n m_control_sock{std::make_unique(INVALID_SOCKET)},\n m_transient{true}\n{\n}\n\nSession::~Session()\n{\n LOCK(m_mutex);\n Disconnect();\n}\n\nbool Session::Listen(Connection& conn)\n{\n try {\n LOCK(m_mutex);\n CreateIfNotCreatedAlready();\n conn.me = m_my_addr;\n conn.sock = StreamAccept();\n return true;\n } catch (const std::runtime_error& e) {\n Log(\"Error listening: %s\", e.what());\n CheckControlSock();\n }\n return false;\n}\n\nbool Session::Accept(Connection& conn)\n{\n try {\n while (!*m_interrupt) {\n Sock::Event occurred;\n if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {\n throw std::runtime_error(\"wait on socket failed\");\n }\n\n if (occurred == 0) {\n \/\/ Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.\n continue;\n }\n\n const std::string& peer_dest =\n conn.sock->RecvUntilTerminator('\\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);\n\n conn.peer = CService(DestB64ToAddr(peer_dest), I2P_SAM31_PORT);\n\n return true;\n }\n } catch (const std::runtime_error& e) {\n Log(\"Error accepting: %s\", e.what());\n CheckControlSock();\n }\n return false;\n}\n\nbool Session::Connect(const CService& to, Connection& conn, bool& proxy_error)\n{\n \/\/ Refuse connecting to arbitrary ports. We don't specify any destination port to the SAM proxy\n \/\/ when connecting (SAM 3.1 does not use ports) and it forces\/defaults it to I2P_SAM31_PORT.\n if (to.GetPort() != I2P_SAM31_PORT) {\n proxy_error = false;\n return false;\n }\n\n proxy_error = true;\n\n std::string session_id;\n std::unique_ptr sock;\n conn.peer = to;\n\n try {\n {\n LOCK(m_mutex);\n CreateIfNotCreatedAlready();\n session_id = m_session_id;\n conn.me = m_my_addr;\n sock = Hello();\n }\n\n const Reply& lookup_reply =\n SendRequestAndGetReply(*sock, strprintf(\"NAMING LOOKUP NAME=%s\", to.ToStringIP()));\n\n const std::string& dest = lookup_reply.Get(\"VALUE\");\n\n const Reply& connect_reply = SendRequestAndGetReply(\n *sock, strprintf(\"STREAM CONNECT ID=%s DESTINATION=%s SILENT=false\", session_id, dest),\n false);\n\n const std::string& result = connect_reply.Get(\"RESULT\");\n\n if (result == \"OK\") {\n conn.sock = std::move(sock);\n return true;\n }\n\n if (result == \"INVALID_ID\") {\n LOCK(m_mutex);\n Disconnect();\n throw std::runtime_error(\"Invalid session id\");\n }\n\n if (result == \"CANT_REACH_PEER\" || result == \"TIMEOUT\") {\n proxy_error = false;\n }\n\n throw std::runtime_error(strprintf(\"\\\"%s\\\"\", connect_reply.full));\n } catch (const std::runtime_error& e) {\n Log(\"Error connecting to %s: %s\", to.ToString(), e.what());\n CheckControlSock();\n return false;\n }\n}\n\n\/\/ Private methods\n\nstd::string Session::Reply::Get(const std::string& key) const\n{\n const auto& pos = keys.find(key);\n if (pos == keys.end() || !pos->second.has_value()) {\n throw std::runtime_error(\n strprintf(\"Missing %s= in the reply to \\\"%s\\\": \\\"%s\\\"\", key, request, full));\n }\n return pos->second.value();\n}\n\ntemplate \nvoid Session::Log(const std::string& fmt, const Args&... args) const\n{\n LogPrint(BCLog::I2P, \"%s\\n\", tfm::format(fmt, args...));\n}\n\nSession::Reply Session::SendRequestAndGetReply(const Sock& sock,\n const std::string& request,\n bool check_result_ok) const\n{\n sock.SendComplete(request + \"\\n\", MAX_WAIT_FOR_IO, *m_interrupt);\n\n Reply reply;\n\n \/\/ Don't log the full \"SESSION CREATE ...\" because it contains our private key.\n reply.request = request.substr(0, 14) == \"SESSION CREATE\" ? \"SESSION CREATE ...\" : request;\n\n \/\/ It could take a few minutes for the I2P router to reply as it is querying the I2P network\n \/\/ (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking\n \/\/ `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is\n \/\/ signaled.\n static constexpr auto recv_timeout = 3min;\n\n reply.full = sock.RecvUntilTerminator('\\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE);\n\n for (const auto& kv : spanparsing::Split(reply.full, ' ')) {\n const auto& pos = std::find(kv.begin(), kv.end(), '=');\n if (pos != kv.end()) {\n reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()});\n } else {\n reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt);\n }\n }\n\n if (check_result_ok && reply.Get(\"RESULT\") != \"OK\") {\n throw std::runtime_error(\n strprintf(\"Unexpected reply to \\\"%s\\\": \\\"%s\\\"\", request, reply.full));\n }\n\n return reply;\n}\n\nstd::unique_ptr Session::Hello() const\n{\n auto sock = CreateSock(m_control_host);\n\n if (!sock) {\n throw std::runtime_error(\"Cannot create socket\");\n }\n\n if (!ConnectSocketDirectly(m_control_host, *sock, nConnectTimeout, true)) {\n throw std::runtime_error(strprintf(\"Cannot connect to %s\", m_control_host.ToString()));\n }\n\n SendRequestAndGetReply(*sock, \"HELLO VERSION MIN=3.1 MAX=3.1\");\n\n return sock;\n}\n\nvoid Session::CheckControlSock()\n{\n LOCK(m_mutex);\n\n std::string errmsg;\n if (!m_control_sock->IsConnected(errmsg)) {\n Log(\"Control socket error: %s\", errmsg);\n Disconnect();\n }\n}\n\nvoid Session::DestGenerate(const Sock& sock)\n{\n \/\/ https:\/\/geti2p.net\/spec\/common-structures#key-certificates\n \/\/ \"7\" or \"EdDSA_SHA512_Ed25519\" - \"Recent Router Identities and Destinations\".\n \/\/ Use \"7\" because i2pd <2.24.0 does not recognize the textual form.\n const Reply& reply = SendRequestAndGetReply(sock, \"DEST GENERATE SIGNATURE_TYPE=7\", false);\n\n m_private_key = DecodeI2PBase64(reply.Get(\"PRIV\"));\n}\n\nvoid Session::GenerateAndSavePrivateKey(const Sock& sock)\n{\n DestGenerate(sock);\n\n \/\/ umask is set to 077 in init.cpp, which is ok (unless -sysperms is given)\n if (!WriteBinaryFile(m_private_key_file,\n std::string(m_private_key.begin(), m_private_key.end()))) {\n throw std::runtime_error(\n strprintf(\"Cannot save I2P private key to %s\", fs::quoted(fs::PathToString(m_private_key_file))));\n }\n}\n\nBinary Session::MyDestination() const\n{\n \/\/ From https:\/\/geti2p.net\/spec\/common-structures#destination:\n \/\/ \"They are 387 bytes plus the certificate length specified at bytes 385-386, which may be\n \/\/ non-zero\"\n static constexpr size_t DEST_LEN_BASE = 387;\n static constexpr size_t CERT_LEN_POS = 385;\n\n uint16_t cert_len;\n memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));\n cert_len = be16toh(cert_len);\n\n const size_t dest_len = DEST_LEN_BASE + cert_len;\n\n return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};\n}\n\nvoid Session::CreateIfNotCreatedAlready()\n{\n std::string errmsg;\n if (m_control_sock->IsConnected(errmsg)) {\n return;\n }\n\n const auto session_type = m_transient ? \"transient\" : \"persistent\";\n const auto session_id = GetRandHash().GetHex().substr(0, 10); \/\/ full is overkill, too verbose in the logs\n\n Log(\"Creating %s SAM session %s with %s\", session_type, session_id, m_control_host.ToString());\n\n auto sock = Hello();\n\n if (m_transient) {\n \/\/ The destination (private key) is generated upon session creation and returned\n \/\/ in the reply in DESTINATION=.\n const Reply& reply = SendRequestAndGetReply(\n *sock,\n strprintf(\"SESSION CREATE STYLE=STREAM ID=%s DESTINATION=TRANSIENT\", session_id));\n\n m_private_key = DecodeI2PBase64(reply.Get(\"DESTINATION\"));\n } else {\n \/\/ Read our persistent destination (private key) from disk or generate\n \/\/ one and save it to disk. Then use it when creating the session.\n const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file);\n if (read_ok) {\n m_private_key.assign(data.begin(), data.end());\n } else {\n GenerateAndSavePrivateKey(*sock);\n }\n\n const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key));\n\n SendRequestAndGetReply(*sock,\n strprintf(\"SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s\",\n session_id,\n private_key_b64));\n }\n\n m_my_addr = CService(DestBinToAddr(MyDestination()), I2P_SAM31_PORT);\n m_session_id = session_id;\n m_control_sock = std::move(sock);\n\n Log(\"%s SAM session %s created, my address=%s\",\n Capitalize(session_type),\n m_session_id,\n m_my_addr.ToString());\n}\n\nstd::unique_ptr Session::StreamAccept()\n{\n auto sock = Hello();\n\n const Reply& reply = SendRequestAndGetReply(\n *sock, strprintf(\"STREAM ACCEPT ID=%s SILENT=false\", m_session_id), false);\n\n const std::string& result = reply.Get(\"RESULT\");\n\n if (result == \"OK\") {\n return sock;\n }\n\n if (result == \"INVALID_ID\") {\n \/\/ If our session id is invalid, then force session re-creation on next usage.\n Disconnect();\n }\n\n throw std::runtime_error(strprintf(\"\\\"%s\\\"\", reply.full));\n}\n\nvoid Session::Disconnect()\n{\n if (m_control_sock->Get() != INVALID_SOCKET) {\n if (m_session_id.empty()) {\n Log(\"Destroying incomplete session\");\n } else {\n Log(\"Destroying session %s\", m_session_id);\n }\n }\n m_control_sock = std::make_unique(INVALID_SOCKET);\n m_session_id.clear();\n}\n} \/\/ namespace sam\n} \/\/ namespace i2p\ni2p: log \"SAM session\" instead of \"session\"\/\/ Copyright (c) 2020-2021 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace i2p {\n\n\/**\n * Swap Standard Base64 <-> I2P Base64.\n * Standard Base64 uses `+` and `\/` as last two characters of its alphabet.\n * I2P Base64 uses `-` and `~` respectively.\n * So it is easy to detect in which one is the input and convert to the other.\n * @param[in] from Input to convert.\n * @return converted `from`\n *\/\nstatic std::string SwapBase64(const std::string& from)\n{\n std::string to;\n to.resize(from.size());\n for (size_t i = 0; i < from.size(); ++i) {\n switch (from[i]) {\n case '-':\n to[i] = '+';\n break;\n case '~':\n to[i] = '\/';\n break;\n case '+':\n to[i] = '-';\n break;\n case '\/':\n to[i] = '~';\n break;\n default:\n to[i] = from[i];\n break;\n }\n }\n return to;\n}\n\n\/**\n * Decode an I2P-style Base64 string.\n * @param[in] i2p_b64 I2P-style Base64 string.\n * @return decoded `i2p_b64`\n * @throw std::runtime_error if decoding fails\n *\/\nstatic Binary DecodeI2PBase64(const std::string& i2p_b64)\n{\n const std::string& std_b64 = SwapBase64(i2p_b64);\n auto decoded = DecodeBase64(std_b64);\n if (!decoded) {\n throw std::runtime_error(strprintf(\"Cannot decode Base64: \\\"%s\\\"\", i2p_b64));\n }\n return std::move(*decoded);\n}\n\n\/**\n * Derive the .b32.i2p address of an I2P destination (binary).\n * @param[in] dest I2P destination.\n * @return the address that corresponds to `dest`\n * @throw std::runtime_error if conversion fails\n *\/\nstatic CNetAddr DestBinToAddr(const Binary& dest)\n{\n CSHA256 hasher;\n hasher.Write(dest.data(), dest.size());\n unsigned char hash[CSHA256::OUTPUT_SIZE];\n hasher.Finalize(hash);\n\n CNetAddr addr;\n const std::string addr_str = EncodeBase32(hash, false) + \".b32.i2p\";\n if (!addr.SetSpecial(addr_str)) {\n throw std::runtime_error(strprintf(\"Cannot parse I2P address: \\\"%s\\\"\", addr_str));\n }\n\n return addr;\n}\n\n\/**\n * Derive the .b32.i2p address of an I2P destination (I2P-style Base64).\n * @param[in] dest I2P destination.\n * @return the address that corresponds to `dest`\n * @throw std::runtime_error if conversion fails\n *\/\nstatic CNetAddr DestB64ToAddr(const std::string& dest)\n{\n const Binary& decoded = DecodeI2PBase64(dest);\n return DestBinToAddr(decoded);\n}\n\nnamespace sam {\n\nSession::Session(const fs::path& private_key_file,\n const CService& control_host,\n CThreadInterrupt* interrupt)\n : m_private_key_file{private_key_file},\n m_control_host{control_host},\n m_interrupt{interrupt},\n m_control_sock{std::make_unique(INVALID_SOCKET)},\n m_transient{false}\n{\n}\n\nSession::Session(const CService& control_host, CThreadInterrupt* interrupt)\n : m_control_host{control_host},\n m_interrupt{interrupt},\n m_control_sock{std::make_unique(INVALID_SOCKET)},\n m_transient{true}\n{\n}\n\nSession::~Session()\n{\n LOCK(m_mutex);\n Disconnect();\n}\n\nbool Session::Listen(Connection& conn)\n{\n try {\n LOCK(m_mutex);\n CreateIfNotCreatedAlready();\n conn.me = m_my_addr;\n conn.sock = StreamAccept();\n return true;\n } catch (const std::runtime_error& e) {\n Log(\"Error listening: %s\", e.what());\n CheckControlSock();\n }\n return false;\n}\n\nbool Session::Accept(Connection& conn)\n{\n try {\n while (!*m_interrupt) {\n Sock::Event occurred;\n if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {\n throw std::runtime_error(\"wait on socket failed\");\n }\n\n if (occurred == 0) {\n \/\/ Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.\n continue;\n }\n\n const std::string& peer_dest =\n conn.sock->RecvUntilTerminator('\\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);\n\n conn.peer = CService(DestB64ToAddr(peer_dest), I2P_SAM31_PORT);\n\n return true;\n }\n } catch (const std::runtime_error& e) {\n Log(\"Error accepting: %s\", e.what());\n CheckControlSock();\n }\n return false;\n}\n\nbool Session::Connect(const CService& to, Connection& conn, bool& proxy_error)\n{\n \/\/ Refuse connecting to arbitrary ports. We don't specify any destination port to the SAM proxy\n \/\/ when connecting (SAM 3.1 does not use ports) and it forces\/defaults it to I2P_SAM31_PORT.\n if (to.GetPort() != I2P_SAM31_PORT) {\n proxy_error = false;\n return false;\n }\n\n proxy_error = true;\n\n std::string session_id;\n std::unique_ptr sock;\n conn.peer = to;\n\n try {\n {\n LOCK(m_mutex);\n CreateIfNotCreatedAlready();\n session_id = m_session_id;\n conn.me = m_my_addr;\n sock = Hello();\n }\n\n const Reply& lookup_reply =\n SendRequestAndGetReply(*sock, strprintf(\"NAMING LOOKUP NAME=%s\", to.ToStringIP()));\n\n const std::string& dest = lookup_reply.Get(\"VALUE\");\n\n const Reply& connect_reply = SendRequestAndGetReply(\n *sock, strprintf(\"STREAM CONNECT ID=%s DESTINATION=%s SILENT=false\", session_id, dest),\n false);\n\n const std::string& result = connect_reply.Get(\"RESULT\");\n\n if (result == \"OK\") {\n conn.sock = std::move(sock);\n return true;\n }\n\n if (result == \"INVALID_ID\") {\n LOCK(m_mutex);\n Disconnect();\n throw std::runtime_error(\"Invalid session id\");\n }\n\n if (result == \"CANT_REACH_PEER\" || result == \"TIMEOUT\") {\n proxy_error = false;\n }\n\n throw std::runtime_error(strprintf(\"\\\"%s\\\"\", connect_reply.full));\n } catch (const std::runtime_error& e) {\n Log(\"Error connecting to %s: %s\", to.ToString(), e.what());\n CheckControlSock();\n return false;\n }\n}\n\n\/\/ Private methods\n\nstd::string Session::Reply::Get(const std::string& key) const\n{\n const auto& pos = keys.find(key);\n if (pos == keys.end() || !pos->second.has_value()) {\n throw std::runtime_error(\n strprintf(\"Missing %s= in the reply to \\\"%s\\\": \\\"%s\\\"\", key, request, full));\n }\n return pos->second.value();\n}\n\ntemplate \nvoid Session::Log(const std::string& fmt, const Args&... args) const\n{\n LogPrint(BCLog::I2P, \"%s\\n\", tfm::format(fmt, args...));\n}\n\nSession::Reply Session::SendRequestAndGetReply(const Sock& sock,\n const std::string& request,\n bool check_result_ok) const\n{\n sock.SendComplete(request + \"\\n\", MAX_WAIT_FOR_IO, *m_interrupt);\n\n Reply reply;\n\n \/\/ Don't log the full \"SESSION CREATE ...\" because it contains our private key.\n reply.request = request.substr(0, 14) == \"SESSION CREATE\" ? \"SESSION CREATE ...\" : request;\n\n \/\/ It could take a few minutes for the I2P router to reply as it is querying the I2P network\n \/\/ (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking\n \/\/ `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is\n \/\/ signaled.\n static constexpr auto recv_timeout = 3min;\n\n reply.full = sock.RecvUntilTerminator('\\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE);\n\n for (const auto& kv : spanparsing::Split(reply.full, ' ')) {\n const auto& pos = std::find(kv.begin(), kv.end(), '=');\n if (pos != kv.end()) {\n reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()});\n } else {\n reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt);\n }\n }\n\n if (check_result_ok && reply.Get(\"RESULT\") != \"OK\") {\n throw std::runtime_error(\n strprintf(\"Unexpected reply to \\\"%s\\\": \\\"%s\\\"\", request, reply.full));\n }\n\n return reply;\n}\n\nstd::unique_ptr Session::Hello() const\n{\n auto sock = CreateSock(m_control_host);\n\n if (!sock) {\n throw std::runtime_error(\"Cannot create socket\");\n }\n\n if (!ConnectSocketDirectly(m_control_host, *sock, nConnectTimeout, true)) {\n throw std::runtime_error(strprintf(\"Cannot connect to %s\", m_control_host.ToString()));\n }\n\n SendRequestAndGetReply(*sock, \"HELLO VERSION MIN=3.1 MAX=3.1\");\n\n return sock;\n}\n\nvoid Session::CheckControlSock()\n{\n LOCK(m_mutex);\n\n std::string errmsg;\n if (!m_control_sock->IsConnected(errmsg)) {\n Log(\"Control socket error: %s\", errmsg);\n Disconnect();\n }\n}\n\nvoid Session::DestGenerate(const Sock& sock)\n{\n \/\/ https:\/\/geti2p.net\/spec\/common-structures#key-certificates\n \/\/ \"7\" or \"EdDSA_SHA512_Ed25519\" - \"Recent Router Identities and Destinations\".\n \/\/ Use \"7\" because i2pd <2.24.0 does not recognize the textual form.\n const Reply& reply = SendRequestAndGetReply(sock, \"DEST GENERATE SIGNATURE_TYPE=7\", false);\n\n m_private_key = DecodeI2PBase64(reply.Get(\"PRIV\"));\n}\n\nvoid Session::GenerateAndSavePrivateKey(const Sock& sock)\n{\n DestGenerate(sock);\n\n \/\/ umask is set to 077 in init.cpp, which is ok (unless -sysperms is given)\n if (!WriteBinaryFile(m_private_key_file,\n std::string(m_private_key.begin(), m_private_key.end()))) {\n throw std::runtime_error(\n strprintf(\"Cannot save I2P private key to %s\", fs::quoted(fs::PathToString(m_private_key_file))));\n }\n}\n\nBinary Session::MyDestination() const\n{\n \/\/ From https:\/\/geti2p.net\/spec\/common-structures#destination:\n \/\/ \"They are 387 bytes plus the certificate length specified at bytes 385-386, which may be\n \/\/ non-zero\"\n static constexpr size_t DEST_LEN_BASE = 387;\n static constexpr size_t CERT_LEN_POS = 385;\n\n uint16_t cert_len;\n memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));\n cert_len = be16toh(cert_len);\n\n const size_t dest_len = DEST_LEN_BASE + cert_len;\n\n return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};\n}\n\nvoid Session::CreateIfNotCreatedAlready()\n{\n std::string errmsg;\n if (m_control_sock->IsConnected(errmsg)) {\n return;\n }\n\n const auto session_type = m_transient ? \"transient\" : \"persistent\";\n const auto session_id = GetRandHash().GetHex().substr(0, 10); \/\/ full is overkill, too verbose in the logs\n\n Log(\"Creating %s SAM session %s with %s\", session_type, session_id, m_control_host.ToString());\n\n auto sock = Hello();\n\n if (m_transient) {\n \/\/ The destination (private key) is generated upon session creation and returned\n \/\/ in the reply in DESTINATION=.\n const Reply& reply = SendRequestAndGetReply(\n *sock,\n strprintf(\"SESSION CREATE STYLE=STREAM ID=%s DESTINATION=TRANSIENT\", session_id));\n\n m_private_key = DecodeI2PBase64(reply.Get(\"DESTINATION\"));\n } else {\n \/\/ Read our persistent destination (private key) from disk or generate\n \/\/ one and save it to disk. Then use it when creating the session.\n const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file);\n if (read_ok) {\n m_private_key.assign(data.begin(), data.end());\n } else {\n GenerateAndSavePrivateKey(*sock);\n }\n\n const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key));\n\n SendRequestAndGetReply(*sock,\n strprintf(\"SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s\",\n session_id,\n private_key_b64));\n }\n\n m_my_addr = CService(DestBinToAddr(MyDestination()), I2P_SAM31_PORT);\n m_session_id = session_id;\n m_control_sock = std::move(sock);\n\n Log(\"%s SAM session %s created, my address=%s\",\n Capitalize(session_type),\n m_session_id,\n m_my_addr.ToString());\n}\n\nstd::unique_ptr Session::StreamAccept()\n{\n auto sock = Hello();\n\n const Reply& reply = SendRequestAndGetReply(\n *sock, strprintf(\"STREAM ACCEPT ID=%s SILENT=false\", m_session_id), false);\n\n const std::string& result = reply.Get(\"RESULT\");\n\n if (result == \"OK\") {\n return sock;\n }\n\n if (result == \"INVALID_ID\") {\n \/\/ If our session id is invalid, then force session re-creation on next usage.\n Disconnect();\n }\n\n throw std::runtime_error(strprintf(\"\\\"%s\\\"\", reply.full));\n}\n\nvoid Session::Disconnect()\n{\n if (m_control_sock->Get() != INVALID_SOCKET) {\n if (m_session_id.empty()) {\n Log(\"Destroying incomplete SAM session\");\n } else {\n Log(\"Destroying SAM session %s\", m_session_id);\n }\n }\n m_control_sock = std::make_unique(INVALID_SOCKET);\n m_session_id.clear();\n}\n} \/\/ namespace sam\n} \/\/ namespace i2p\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace std::chrono;\n\nclass SparseLevenshteinAutomaton {\n private:\n\tstring word;\n\tint n;\n public:\n void set_values (string auto_word, int num_mis);\n tuple, vector> start();\n tuple, vector> step(tuple, vector> &previous, char c);\n bool is_match(tuple, vector>& previous);\n};\n \nvoid SparseLevenshteinAutomaton::set_values (string auto_word, int num_mis) {\n word = auto_word;\n n = num_mis;\n }\n\ntuple, vector> SparseLevenshteinAutomaton::start () {\n\tvector range_max_edits;\n\tfor (int i=0; i <= n; i++) {\n\t\trange_max_edits.push_back(i);\n\t}\n\treturn make_tuple(range_max_edits, range_max_edits); \n}\n\ntuple, vector> SparseLevenshteinAutomaton::step(tuple, vector>& previous, char c) {\n\tvector new_indices;\n\tvector new_values;\n\tif (get<0>(previous).size() and get<0>(previous).at(0) == 0 and get<1>(previous).at(0) < n) {\n\t\tnew_indices = {0};\n\t\tnew_values = {get<1>(previous).at(0) + 1};\n\t}\n\telse {\n\t\tnew_indices = {};\n\t\tnew_values = {};\n\t}\n\tfor (int i = 0; i < get<0>(previous).size(); i++) {\n\t}\n\tfor (int i = 0; i < get<0>(previous).size(); i++) {\n\t\tif (get<0>(previous).at(i) == word.length()) {\n\t\t\tbreak;\n\t\t}\n\t\tint cost;\n\t\tif (word[get<0>(previous).at(i)] == c)\n\t\t{\n\t\t\tcost = 0;\n\t\t}\n\t\telse {\n\t\t\tcost = 1;\n\t\t}\n\t\tint val = get<1>(previous).at(i) + cost;\n\t\tif (new_indices.size() and new_indices.at(new_indices.size() - 1) == get<0>(previous).at(i)) {\n\t\t\tval = min(val, (new_values.at(new_values.size() - 1) + 1));\n\t\t}\n\t\tif ((i + 1) < get<0>(previous).size() and get<0>(previous).at(i + 1) == get<0>(previous).at(i) + 1) {\n\t\t\tval = min(val, (get<1>(previous).at(i + 1) + 1));\n\t\t}\n\t\tif (val <= n) {\n\t\t\tnew_indices.push_back(get<0>(previous).at(i) + 1);\n\t\t\tnew_values.push_back(val);\n\t\t}\n\t}\n\treturn make_tuple(new_indices, new_values);\n\n}\n\nbool SparseLevenshteinAutomaton::is_match(tuple, vector>& previous) {\n return (get<0>(previous).size() and get<0>(previous).at(get<0>(previous).size() - 1) == word.length());\n}\n\n\nvoid benchmark(size_t mistakes, \n\t\t\t\tconst vector &first_file_seq, \n\t\t\t\t const vector &second_file_seq, \n\t\t\t\t size_t first_file_size, \n\t\t\t\t size_t second_file_size, ofstream &outfile)\n{\n\tstd::chrono::milliseconds tp1 = std::chrono::duration_cast(system_clock::now().time_since_epoch());\n\n\tfor (int k = 0; k < first_file_size; k++) {\n\t\tstring auto_word = first_file_seq[k];\n\t\tSparseLevenshteinAutomaton sparse;\n\t\tsparse.set_values (auto_word, mistakes);\n\t\ttuple, vector> s_sparse1 = sparse.start();\n\t\tfor (int j = 0; j < second_file_size; j++) {\n\t\t\ttuple, vector> s_sparse = s_sparse1;\n\t\t\t for (int i = 0; i < second_file_seq[j].length(); i++) {\n\t\t\t\t s_sparse = sparse.step(s_sparse, second_file_seq[j][i]);\n\t\t\t\t if ((i == second_file_seq[j].length() - 1) && sparse.is_match(s_sparse)) {\n\t\t\t\t\t\t \/\/ outfile << word_check << \" \" << auto_word << \"\\n\";\n\t\t\t\t\t \toutfile << (int) i << \" \" << (int) j << \"\\n\";\n\t\t\t\t }\n\t\t\t }\n\t\t}\n\t }\n\n\n\tstd::chrono::milliseconds tp2 = std::chrono::duration_cast(system_clock::now().time_since_epoch());\n\tauto diff = tp2.count() - tp1.count();\n\n\tcout << \"benchmark (\" << (size_t) first_file_size << \" : \" << second_file_size << \") - \" << diff << \" milsec\" << endl;\n}\n\n\nint main (int argc, char** argv) {\n string line1, line2;\n char* file1 = argv[1];\n char* file2 = argv[2];\n int mistakes = atoi(argv[3]);\n string outfilename = argv[4];\n ifstream myfile2 (file2);\n vector first_file_seq;\n vector second_file_seq;\n if (myfile2.is_open())\n {\n while ( getline (myfile2,line2) )\n {\n second_file_seq.push_back(line2);\n }\n myfile2.close();\n }\n ifstream myfile1 (file1);\n ofstream outfile;\n outfile.open(outfilename, std::ios_base::app);\n if (myfile1.is_open())\n {\n while ( getline (myfile1,line1) )\n { \t\n \tfirst_file_seq.push_back(line1);\n }\n myfile1.close();\n }\n benchmark(mistakes, first_file_seq, second_file_seq, 100, 100, outfile);\n benchmark(mistakes, first_file_seq, second_file_seq, 500, 500, outfile);\n \/\/ benchmark(mistakes, first_file_seq, second_file_seq, 1000, 1000, outfile);\n \/\/ benchmark(mistakes, first_file_seq, second_file_seq, 3000, 3000, outfile);\n \/\/ benchmark(mistakes, first_file_seq, second_file_seq, 5000, 5000, outfile);\n outfile.close();\n return 0;\n}few minor changes#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace std::chrono;\n\nclass SparseLevenshteinAutomaton {\n private:\n\tstring word;\n\tint n;\n public:\n void set_values (string auto_word, int num_mis);\n tuple, vector> start();\n tuple, vector> step(tuple, vector> &previous, char c);\n bool is_match(tuple, vector>& previous);\n};\n \nvoid SparseLevenshteinAutomaton::set_values (string auto_word, int num_mis) {\n word = auto_word;\n n = num_mis;\n }\n\ntuple, vector> SparseLevenshteinAutomaton::start () {\n\tvector range_max_edits;\n\tfor (int i=0; i <= n; i++) {\n\t\trange_max_edits.push_back(i);\n\t}\n\treturn make_tuple(range_max_edits, range_max_edits); \n}\n\ntuple, vector> SparseLevenshteinAutomaton::step(tuple, vector>& previous, char c) {\n\tvector new_indices;\n\tvector new_values;\n\tif (get<0>(previous).size() and get<0>(previous).at(0) == 0 and get<1>(previous).at(0) < n) {\n\t\tnew_indices = {0};\n\t\tnew_values = {get<1>(previous).at(0) + 1};\n\t}\n\telse {\n\t\tnew_indices = {};\n\t\tnew_values = {};\n\t}\n\tfor (int i = 0; i < get<0>(previous).size(); i++) {\n\t}\n\tfor (int i = 0; i < get<0>(previous).size(); i++) {\n\t\tif (get<0>(previous).at(i) == word.length()) {\n\t\t\tbreak;\n\t\t}\n\t\tint cost;\n\t\tif (word[get<0>(previous).at(i)] == c)\n\t\t{\n\t\t\tcost = 0;\n\t\t}\n\t\telse {\n\t\t\tcost = 1;\n\t\t}\n\t\tint val = get<1>(previous).at(i) + cost;\n\t\tif (new_indices.size() and new_indices.at(new_indices.size() - 1) == get<0>(previous).at(i)) {\n\t\t\tval = min(val, (new_values.at(new_values.size() - 1) + 1));\n\t\t}\n\t\tif ((i + 1) < get<0>(previous).size() and get<0>(previous).at(i + 1) == get<0>(previous).at(i) + 1) {\n\t\t\tval = min(val, (get<1>(previous).at(i + 1) + 1));\n\t\t}\n\t\tif (val <= n) {\n\t\t\tnew_indices.push_back(get<0>(previous).at(i) + 1);\n\t\t\tnew_values.push_back(val);\n\t\t}\n\t}\n\treturn make_tuple(new_indices, new_values);\n\n}\n\nbool SparseLevenshteinAutomaton::is_match(tuple, vector>& previous) {\n return (get<0>(previous).size() and get<0>(previous).at(get<0>(previous).size() - 1) == word.length());\n}\n\n\nvoid benchmark(size_t mistakes, \n\t\t\t\tconst vector &first_file_seq, \n\t\t\t\t const vector &second_file_seq, \n\t\t\t\t size_t first_file_size, \n\t\t\t\t size_t second_file_size, ofstream &outfile)\n{\n\tstd::chrono::milliseconds tp1 = std::chrono::duration_cast(system_clock::now().time_since_epoch());\n\n\tSparseLevenshteinAutomaton sparse;\n\tfor (int k = 0; k < first_file_size; k++) {\n\t\t\/\/ string auto_word = first_file_seq[k];\n\t\t\/\/ SparseLevenshteinAutomaton sparse;\n\t\tsparse.set_values (first_file_seq[k], mistakes);\n\t\ttuple, vector> s_sparse1 = sparse.start();\n\t\tfor (int j = 0; j < second_file_size; j++) {\n\t\t\ttuple, vector> s_sparse = s_sparse1;\n\t\t\t for (int i = 0; i < second_file_seq[j].length(); i++) {\n\t\t\t\t s_sparse = sparse.step(s_sparse, second_file_seq[j][i]);\n\t\t\t\t if ((i == second_file_seq[j].length() - 1) && sparse.is_match(s_sparse)) {\n\t\t\t\t\t\t \/\/ outfile << word_check << \" \" << auto_word << \"\\n\";\n\t\t\t\t\t \toutfile << (int) (i+1) << \" \" << (int) (j+1) << \"\\n\";\n\t\t\t\t\t \t\/\/ cout << (size_t) get<0>(s_sparse).size() << \":\" << (size_t) get<1>(s_sparse).size() << endl;\n\t\t\t\t }\n\t\t\t }\n\t\t}\n\t }\n\n\n\tstd::chrono::milliseconds tp2 = std::chrono::duration_cast(system_clock::now().time_since_epoch());\n\tauto diff = tp2.count() - tp1.count();\n\n\tcout << \"benchmark (\" << (size_t) first_file_size << \" : \" << second_file_size << \") - \" << diff << \" milsec\" << endl;\n}\n\n\nint main (int argc, char** argv) {\n string line1, line2;\n char* file1 = argv[1];\n char* file2 = argv[2];\n int mistakes = atoi(argv[3]);\n string outfilename = argv[4];\n ifstream myfile2 (file2);\n vector first_file_seq;\n vector second_file_seq;\n if (myfile2.is_open())\n {\n while ( getline (myfile2,line2) )\n {\n second_file_seq.push_back(line2);\n }\n myfile2.close();\n }\n ifstream myfile1 (file1);\n ofstream outfile;\n outfile.open(outfilename, std::ios_base::app);\n if (myfile1.is_open())\n {\n while ( getline (myfile1,line1) )\n { \t\n \tfirst_file_seq.push_back(line1);\n }\n myfile1.close();\n }\n benchmark(mistakes, first_file_seq, second_file_seq, 100, 100, outfile);\n benchmark(mistakes, first_file_seq, second_file_seq, 500, 500, outfile);\n \/\/ benchmark(mistakes, first_file_seq, second_file_seq, 1000, 1000, outfile);\n \/\/ benchmark(mistakes, first_file_seq, second_file_seq, 3000, 3000, outfile);\n \/\/ benchmark(mistakes, first_file_seq, second_file_seq, 5000, 5000, outfile);\n outfile.close();\n return 0;\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"Crypto.h\"\n#include \"Gost.h\"\n#include \"key.h\"\n\n#include \n#include \n#include \n\n\/\/ anonymous namespace with local implementation code (OpenSSL interaction)\nnamespace {\n\n\/\/ Generate a private key from just the secret parameter\nint EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)\n{\n int ok = 0;\n BN_CTX *ctx = NULL;\n EC_POINT *pub_key = NULL;\n\n if (!eckey) return 0;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n\n if ((ctx = BN_CTX_new()) == NULL)\n goto err;\n\n pub_key = EC_POINT_new(group);\n\n if (pub_key == NULL)\n goto err;\n\n if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))\n goto err;\n\n EC_KEY_set_private_key(eckey,priv_key);\n EC_KEY_set_public_key(eckey,pub_key);\n\n ok = 1;\n\nerr:\n\n if (pub_key)\n EC_POINT_free(pub_key);\n if (ctx != NULL)\n BN_CTX_free(ctx);\n\n return(ok);\n}\n\n\/\/ Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields\n\/\/ recid selects which key is recovered\n\/\/ if check is non-zero, additional checks are performed\nstatic int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)\n{\n if (!eckey) return 0;\n\tBIGNUM * d = BN_bin2bn (msg, msglen, nullptr); \n\tconst auto& curve = i2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA);\n const BIGNUM * r, * s;\n\tECDSA_SIG_get0 (ecsig, &r, &s);\n\tEC_POINT * pub = curve->RecoverPublicKey (d, r, s, recid % 2);\n\tBN_free (d);\n\tif (!pub) return 0;\n\tEC_KEY_set_public_key(eckey, pub);\t\n\tEC_POINT_free (pub);\n\treturn 1;\n}\n\n\/\/ RAII Wrapper around OpenSSL's EC_KEY\nclass CECKey {\nprivate:\n EC_KEY *pkey;\n\npublic:\n CECKey() \n\t{\n\t\tpkey = EC_KEY_new ();\n\t\t\/\/ GOST 34.10-2012\n\t\tauto ret = EC_KEY_set_group(pkey, i2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA)->GetGroup ());\n\t\tassert (ret == 1);\n }\n\n ~CECKey() {\n EC_KEY_free(pkey);\n }\n\n void GetSecretBytes(unsigned char vch[32]) const {\n const BIGNUM *bn = EC_KEY_get0_private_key(pkey);\n assert(bn);\n int nBytes = BN_num_bytes(bn);\n int n=BN_bn2bin(bn,&vch[32 - nBytes]);\n assert(n == nBytes);\n memset(vch, 0, 32 - nBytes);\n }\n\n void SetSecretBytes(const unsigned char vch[32]) {\n BIGNUM bn;\n BN_init(&bn);\n assert(BN_bin2bn(vch, 32, &bn));\n assert(EC_KEY_regenerate_key(pkey, &bn));\n BN_clear_free(&bn);\n }\n\n void GetPrivKey(CPrivKey &privkey, bool fCompressed) {\n EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);\n int nSize = i2d_ECPrivateKey(pkey, NULL);\n assert(nSize);\n privkey.resize(nSize);\n unsigned char* pbegin = &privkey[0];\n int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);\n assert(nSize == nSize2);\n }\n\n bool SetPrivKey(const CPrivKey &privkey) {\n const unsigned char* pbegin = &privkey[0];\n if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {\n \/\/ d2i_ECPrivateKey returns true if parsing succeeds.\n \/\/ This doesn't necessarily mean the key is valid.\n if (EC_KEY_check_key(pkey))\n return true;\n }\n return false;\n }\n\n void GetPubKey(CPubKey &pubkey, bool fCompressed) {\n EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);\n int nSize = i2o_ECPublicKey(pkey, NULL);\n assert(nSize);\n assert(nSize <= 65);\n unsigned char c[65];\n unsigned char *pbegin = c;\n int nSize2 = i2o_ECPublicKey(pkey, &pbegin);\n assert(nSize == nSize2);\n pubkey.Set(&c[0], &c[nSize]);\n }\n\n bool SetPubKey(const CPubKey &pubkey) {\n const unsigned char* pbegin = pubkey.begin();\n return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size());\n }\n\n bool Sign(const uint256 &hash, std::vector& vchSig) \n\t{\n\t\tconst BIGNUM * priv = EC_KEY_get0_private_key(pkey);\n\t\tBIGNUM * d = BN_bin2bn (hash.begin (), 32, nullptr); \n BIGNUM * r = BN_new (), * s = BN_new ();\n\t\ti2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA)->Sign (priv, d, r, s);\n ECDSA_SIG *sig = ECDSA_SIG_new ();\t\n ECDSA_SIG_set0 (sig, r, s);\n\t\t\/\/ encode signature is in DER format\t\t\n\t\tauto nSize = ECDSA_size (pkey); \/\/ max size\n\t\tvchSig.resize(nSize);\n\t\tauto p = &vchSig[0];\n\t\tnSize = i2d_ECDSA_SIG (sig, &p);\n\t\tvchSig.resize(nSize); \/\/ acutal size\n\t\tBN_free (d);\t\n\t\tECDSA_SIG_free(sig);\n return true;\n }\n\n bool Verify(const uint256 &hash, const std::vector& vchSig) \n\t{\n\t\t\/\/ decode from DER\n\t\tECDSA_SIG *sig = nullptr;\n\t\tauto p = &vchSig[0];\t\n\t\td2i_ECDSA_SIG (&sig, &p, vchSig.size());\t\n\t\tconst EC_POINT * pub = EC_KEY_get0_public_key(pkey);\n\t\tBIGNUM * d = BN_bin2bn (hash.begin (), 32, nullptr);\n const BIGNUM * r, * s;\n\t\tECDSA_SIG_get0 (sig, &r, &s);\n\t\tbool ret = i2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA)->Verify (pub, d, r, s);\n\t\tBN_free (d); \n\t\tECDSA_SIG_free(sig);\n\t\treturn ret;\n }\n\n bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec) \n\t{\n bool fOk = false;\n ECDSA_SIG *sig = ECDSA_SIG_new ();\n\t\tconst BIGNUM * priv = EC_KEY_get0_private_key(pkey);\n\t\tBIGNUM * d = BN_bin2bn (hash.begin (), 32, nullptr);\n BIGNUM * r = BN_new (), * s = BN_new ();\n\t\ti2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA)->Sign (priv, d, r, s);\n ECDSA_SIG_set0 (sig, r, s);\n\t\tBN_free (d);\n if (sig==NULL)\n return false;\n memset(p64, 0, 64);\n int nBitsR = BN_num_bits(r);\n int nBitsS = BN_num_bits(s);\n if (nBitsR <= 256 && nBitsS <= 256) {\n CPubKey pubkey;\n GetPubKey(pubkey, true);\n for (int i=0; i<2; i++) {\n CECKey keyRec;\n if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {\n CPubKey pubkeyRec;\n keyRec.GetPubKey(pubkeyRec, true);\n if (pubkeyRec == pubkey) {\n rec = i;\n fOk = true;\n break;\n }\n }\n }\n assert(fOk);\n BN_bn2bin(r,&p64[32-(nBitsR+7)\/8]);\n BN_bn2bin(s,&p64[64-(nBitsS+7)\/8]);\n }\n ECDSA_SIG_free(sig);\n return fOk;\n }\n\n \/\/ reconstruct public key from a compact signature\n \/\/ This is only slightly more CPU intensive than just verifying it.\n \/\/ If this function succeeds, the recovered public key is guaranteed to be valid\n \/\/ (the signature is a valid signature of the given data for that key)\n bool Recover(const uint256 &hash, const unsigned char *p64, int rec)\n {\n if (rec<0 || rec>=3)\n return false;\n ECDSA_SIG *sig = ECDSA_SIG_new();\n auto r = BN_bin2bn(&p64[0], 32, NULL);\n auto s = BN_bin2bn(&p64[32], 32, NULL);\n ECDSA_SIG_set0 (sig, r, s);\n bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;\n ECDSA_SIG_free(sig);\n return ret;\n }\n};\n\n}; \/\/ end of anonymous namespace\n\nbool CKey::Check(const unsigned char *vch) {\n \/\/ Do not convert to OpenSSL's data structures for range-checking keys,\n \/\/ it's easy enough to do directly.\n static const unsigned char vchMax[32] = {\n 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,\n 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,\n 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,\n 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40\n };\n bool fIsZero = true;\n for (int i=0; i<32 && fIsZero; i++)\n if (vch[i] != 0)\n fIsZero = false;\n if (fIsZero)\n return false;\n for (int i=0; i<32; i++) {\n if (vch[i] < vchMax[i])\n return true;\n if (vch[i] > vchMax[i])\n return false;\n }\n return true;\n}\n\nvoid CKey::MakeNewKey(bool fCompressedIn) {\n do {\n RAND_bytes(vch, sizeof(vch));\n } while (!Check(vch));\n fValid = true;\n fCompressed = fCompressedIn;\n}\n\nbool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {\n CECKey key;\n if (!key.SetPrivKey(privkey))\n return false;\n key.GetSecretBytes(vch);\n fCompressed = fCompressedIn;\n fValid = true;\n return true;\n}\n\nCPrivKey CKey::GetPrivKey() const {\n assert(fValid);\n CECKey key;\n key.SetSecretBytes(vch);\n CPrivKey privkey;\n key.GetPrivKey(privkey, fCompressed);\n return privkey;\n}\n\nCPubKey CKey::GetPubKey() const {\n assert(fValid);\n CECKey key;\n key.SetSecretBytes(vch);\n CPubKey pubkey;\n key.GetPubKey(pubkey, fCompressed);\n return pubkey;\n}\n\nbool CKey::Sign(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n CECKey key;\n key.SetSecretBytes(vch);\n return key.Sign(hash, vchSig);\n}\n\nbool CKey::SignCompact(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n CECKey key;\n key.SetSecretBytes(vch);\n vchSig.resize(65);\n int rec = -1;\n if (!key.SignCompact(hash, &vchSig[1], rec))\n return false;\n assert(rec != -1);\n vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);\n return true;\n}\n\nbool CPubKey::Verify(const uint256 &hash, const std::vector& vchSig) const {\n if (!IsValid())\n return false;\n CECKey key;\n if (!key.SetPubKey(*this))\n return false;\n if (!key.Verify(hash, vchSig))\n return false;\n return true;\n}\n\nbool CPubKey::RecoverCompact(const uint256 &hash, const std::vector& vchSig) {\n if (vchSig.size() != 65)\n return false;\n CECKey key;\n if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))\n return false;\n key.GetPubKey(*this, (vchSig[0] - 27) & 4);\n return true;\n}\n\nbool CPubKey::VerifyCompact(const uint256 &hash, const std::vector& vchSig) const {\n if (!IsValid())\n return false;\n if (vchSig.size() != 65)\n return false;\n CECKey key;\n if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))\n return false;\n CPubKey pubkeyRec;\n key.GetPubKey(pubkeyRec, IsCompressed());\n if (*this != pubkeyRec)\n return false;\n return true;\n}\n\nbool CPubKey::IsFullyValid() const {\n if (!IsValid())\n return false;\n CECKey key;\n if (!key.SetPubKey(*this))\n return false;\n return true;\n}\n\nbool CPubKey::Decompress() {\n if (!IsValid())\n return false;\n CECKey key;\n if (!key.SetPubKey(*this))\n return false;\n key.GetPubKey(*this, false);\n return true;\n}\nopenssl 1.1 support\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"Crypto.h\"\n#include \"Gost.h\"\n#include \"key.h\"\n\n#include \n#include \n#include \n\n\/\/ anonymous namespace with local implementation code (OpenSSL interaction)\nnamespace {\n\n\/\/ Generate a private key from just the secret parameter\nint EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)\n{\n int ok = 0;\n BN_CTX *ctx = NULL;\n EC_POINT *pub_key = NULL;\n\n if (!eckey) return 0;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n\n if ((ctx = BN_CTX_new()) == NULL)\n goto err;\n\n pub_key = EC_POINT_new(group);\n\n if (pub_key == NULL)\n goto err;\n\n if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))\n goto err;\n\n EC_KEY_set_private_key(eckey,priv_key);\n EC_KEY_set_public_key(eckey,pub_key);\n\n ok = 1;\n\nerr:\n\n if (pub_key)\n EC_POINT_free(pub_key);\n if (ctx != NULL)\n BN_CTX_free(ctx);\n\n return(ok);\n}\n\n\/\/ Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields\n\/\/ recid selects which key is recovered\n\/\/ if check is non-zero, additional checks are performed\nstatic int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)\n{\n if (!eckey) return 0;\n\tBIGNUM * d = BN_bin2bn (msg, msglen, nullptr); \n\tconst auto& curve = i2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA);\n const BIGNUM * r, * s;\n\tECDSA_SIG_get0 (ecsig, &r, &s);\n\tEC_POINT * pub = curve->RecoverPublicKey (d, r, s, recid % 2);\n\tBN_free (d);\n\tif (!pub) return 0;\n\tEC_KEY_set_public_key(eckey, pub);\t\n\tEC_POINT_free (pub);\n\treturn 1;\n}\n\n\/\/ RAII Wrapper around OpenSSL's EC_KEY\nclass CECKey {\nprivate:\n EC_KEY *pkey;\n\npublic:\n CECKey() \n\t{\n\t\tpkey = EC_KEY_new ();\n\t\t\/\/ GOST 34.10-2012\n\t\tauto ret = EC_KEY_set_group(pkey, i2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA)->GetGroup ());\n\t\tassert (ret == 1);\n }\n\n ~CECKey() {\n EC_KEY_free(pkey);\n }\n\n void GetSecretBytes(unsigned char vch[32]) const {\n const BIGNUM *bn = EC_KEY_get0_private_key(pkey);\n assert(bn);\n int nBytes = BN_num_bytes(bn);\n int n=BN_bn2bin(bn,&vch[32 - nBytes]);\n assert(n == nBytes);\n memset(vch, 0, 32 - nBytes);\n }\n\n void SetSecretBytes(const unsigned char vch[32]) {\n BIGNUM * bn = BN_new ();\n assert(BN_bin2bn(vch, 32, bn));\n assert(EC_KEY_regenerate_key(pkey, bn));\n BN_clear_free(bn);\n }\n\n void GetPrivKey(CPrivKey &privkey, bool fCompressed) {\n EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);\n int nSize = i2d_ECPrivateKey(pkey, NULL);\n assert(nSize);\n privkey.resize(nSize);\n unsigned char* pbegin = &privkey[0];\n int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);\n assert(nSize == nSize2);\n }\n\n bool SetPrivKey(const CPrivKey &privkey) {\n const unsigned char* pbegin = &privkey[0];\n if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {\n \/\/ d2i_ECPrivateKey returns true if parsing succeeds.\n \/\/ This doesn't necessarily mean the key is valid.\n if (EC_KEY_check_key(pkey))\n return true;\n }\n return false;\n }\n\n void GetPubKey(CPubKey &pubkey, bool fCompressed) {\n EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);\n int nSize = i2o_ECPublicKey(pkey, NULL);\n assert(nSize);\n assert(nSize <= 65);\n unsigned char c[65];\n unsigned char *pbegin = c;\n int nSize2 = i2o_ECPublicKey(pkey, &pbegin);\n assert(nSize == nSize2);\n pubkey.Set(&c[0], &c[nSize]);\n }\n\n bool SetPubKey(const CPubKey &pubkey) {\n const unsigned char* pbegin = pubkey.begin();\n return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size());\n }\n\n bool Sign(const uint256 &hash, std::vector& vchSig) \n\t{\n\t\tconst BIGNUM * priv = EC_KEY_get0_private_key(pkey);\n\t\tBIGNUM * d = BN_bin2bn (hash.begin (), 32, nullptr); \n BIGNUM * r = BN_new (), * s = BN_new ();\n\t\ti2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA)->Sign (priv, d, r, s);\n ECDSA_SIG *sig = ECDSA_SIG_new ();\t\n ECDSA_SIG_set0 (sig, r, s);\n\t\t\/\/ encode signature is in DER format\t\t\n\t\tauto nSize = ECDSA_size (pkey); \/\/ max size\n\t\tvchSig.resize(nSize);\n\t\tauto p = &vchSig[0];\n\t\tnSize = i2d_ECDSA_SIG (sig, &p);\n\t\tvchSig.resize(nSize); \/\/ acutal size\n\t\tBN_free (d);\t\n\t\tECDSA_SIG_free(sig);\n return true;\n }\n\n bool Verify(const uint256 &hash, const std::vector& vchSig) \n\t{\n\t\t\/\/ decode from DER\n\t\tECDSA_SIG *sig = nullptr;\n\t\tauto p = &vchSig[0];\t\n\t\td2i_ECDSA_SIG (&sig, &p, vchSig.size());\t\n\t\tconst EC_POINT * pub = EC_KEY_get0_public_key(pkey);\n\t\tBIGNUM * d = BN_bin2bn (hash.begin (), 32, nullptr);\n const BIGNUM * r, * s;\n\t\tECDSA_SIG_get0 (sig, &r, &s);\n\t\tbool ret = i2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA)->Verify (pub, d, r, s);\n\t\tBN_free (d); \n\t\tECDSA_SIG_free(sig);\n\t\treturn ret;\n }\n\n bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec) \n\t{\n bool fOk = false;\n ECDSA_SIG *sig = ECDSA_SIG_new ();\n\t\tconst BIGNUM * priv = EC_KEY_get0_private_key(pkey);\n\t\tBIGNUM * d = BN_bin2bn (hash.begin (), 32, nullptr);\n BIGNUM * r = BN_new (), * s = BN_new ();\n\t\ti2p::crypto::GetGOSTR3410Curve (i2p::crypto::eGOSTR3410CryptoProA)->Sign (priv, d, r, s);\n ECDSA_SIG_set0 (sig, r, s);\n\t\tBN_free (d);\n if (sig==NULL)\n return false;\n memset(p64, 0, 64);\n int nBitsR = BN_num_bits(r);\n int nBitsS = BN_num_bits(s);\n if (nBitsR <= 256 && nBitsS <= 256) {\n CPubKey pubkey;\n GetPubKey(pubkey, true);\n for (int i=0; i<2; i++) {\n CECKey keyRec;\n if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {\n CPubKey pubkeyRec;\n keyRec.GetPubKey(pubkeyRec, true);\n if (pubkeyRec == pubkey) {\n rec = i;\n fOk = true;\n break;\n }\n }\n }\n assert(fOk);\n BN_bn2bin(r,&p64[32-(nBitsR+7)\/8]);\n BN_bn2bin(s,&p64[64-(nBitsS+7)\/8]);\n }\n ECDSA_SIG_free(sig);\n return fOk;\n }\n\n \/\/ reconstruct public key from a compact signature\n \/\/ This is only slightly more CPU intensive than just verifying it.\n \/\/ If this function succeeds, the recovered public key is guaranteed to be valid\n \/\/ (the signature is a valid signature of the given data for that key)\n bool Recover(const uint256 &hash, const unsigned char *p64, int rec)\n {\n if (rec<0 || rec>=3)\n return false;\n ECDSA_SIG *sig = ECDSA_SIG_new();\n auto r = BN_bin2bn(&p64[0], 32, NULL);\n auto s = BN_bin2bn(&p64[32], 32, NULL);\n ECDSA_SIG_set0 (sig, r, s);\n bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;\n ECDSA_SIG_free(sig);\n return ret;\n }\n};\n\n}; \/\/ end of anonymous namespace\n\nbool CKey::Check(const unsigned char *vch) {\n \/\/ Do not convert to OpenSSL's data structures for range-checking keys,\n \/\/ it's easy enough to do directly.\n static const unsigned char vchMax[32] = {\n 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,\n 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,\n 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,\n 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40\n };\n bool fIsZero = true;\n for (int i=0; i<32 && fIsZero; i++)\n if (vch[i] != 0)\n fIsZero = false;\n if (fIsZero)\n return false;\n for (int i=0; i<32; i++) {\n if (vch[i] < vchMax[i])\n return true;\n if (vch[i] > vchMax[i])\n return false;\n }\n return true;\n}\n\nvoid CKey::MakeNewKey(bool fCompressedIn) {\n do {\n RAND_bytes(vch, sizeof(vch));\n } while (!Check(vch));\n fValid = true;\n fCompressed = fCompressedIn;\n}\n\nbool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {\n CECKey key;\n if (!key.SetPrivKey(privkey))\n return false;\n key.GetSecretBytes(vch);\n fCompressed = fCompressedIn;\n fValid = true;\n return true;\n}\n\nCPrivKey CKey::GetPrivKey() const {\n assert(fValid);\n CECKey key;\n key.SetSecretBytes(vch);\n CPrivKey privkey;\n key.GetPrivKey(privkey, fCompressed);\n return privkey;\n}\n\nCPubKey CKey::GetPubKey() const {\n assert(fValid);\n CECKey key;\n key.SetSecretBytes(vch);\n CPubKey pubkey;\n key.GetPubKey(pubkey, fCompressed);\n return pubkey;\n}\n\nbool CKey::Sign(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n CECKey key;\n key.SetSecretBytes(vch);\n return key.Sign(hash, vchSig);\n}\n\nbool CKey::SignCompact(const uint256 &hash, std::vector& vchSig) const {\n if (!fValid)\n return false;\n CECKey key;\n key.SetSecretBytes(vch);\n vchSig.resize(65);\n int rec = -1;\n if (!key.SignCompact(hash, &vchSig[1], rec))\n return false;\n assert(rec != -1);\n vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);\n return true;\n}\n\nbool CPubKey::Verify(const uint256 &hash, const std::vector& vchSig) const {\n if (!IsValid())\n return false;\n CECKey key;\n if (!key.SetPubKey(*this))\n return false;\n if (!key.Verify(hash, vchSig))\n return false;\n return true;\n}\n\nbool CPubKey::RecoverCompact(const uint256 &hash, const std::vector& vchSig) {\n if (vchSig.size() != 65)\n return false;\n CECKey key;\n if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))\n return false;\n key.GetPubKey(*this, (vchSig[0] - 27) & 4);\n return true;\n}\n\nbool CPubKey::VerifyCompact(const uint256 &hash, const std::vector& vchSig) const {\n if (!IsValid())\n return false;\n if (vchSig.size() != 65)\n return false;\n CECKey key;\n if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))\n return false;\n CPubKey pubkeyRec;\n key.GetPubKey(pubkeyRec, IsCompressed());\n if (*this != pubkeyRec)\n return false;\n return true;\n}\n\nbool CPubKey::IsFullyValid() const {\n if (!IsValid())\n return false;\n CECKey key;\n if (!key.SetPubKey(*this))\n return false;\n return true;\n}\n\nbool CPubKey::Decompress() {\n if (!IsValid())\n return false;\n CECKey key;\n if (!key.SetPubKey(*this))\n return false;\n key.GetPubKey(*this, false);\n return true;\n}\n<|endoftext|>"} {"text":"#include \"log.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/#include \n#include \n#include \n\nLinePositionList allLinePos(const QByteArray &bts) {\n\n int count = 0;\n auto size = bts.size();\n for (int i = 0; i < size; ++i) {\n if (bts[i] == '\\n') {\n count++;\n }\n }\n LinePositionList result(count);\n int start = 0;\n int index = 0;\n for (int i = 0; i < size; ++i) {\n if (bts[i] == '\\n') {\n LinePosition lp;\n lp.first = start;\n lp.second = i;\n result[index++] = lp;\n start = i + 1;\n }\n }\n return result;\n}\n\nLog *Log::openFile(const QString &fname, const HighlightPatterns *global_highlight,\n const QString &default_encoding, QObject *parent) {\n qDebug() << \"openFile\" << fname;\n QFileInfo fileInfo(fname);\n auto ll = new Log(fileInfo, fname, global_highlight, default_encoding, parent);\n return ll;\n}\n\nvoid Log::loadFile() {\n qDebug() << \"loadFile \" << m_fname;\n auto curDT = QDateTime::currentDateTimeUtc();\n QFile inputFile(m_fname);\n if (inputFile.open(QIODevice::ReadOnly)) {\n m_bts = std::move(inputFile.readAll());\n m_lines = allLinePos(m_bts);\n m_cache.resize(m_lines.size());\n inputFile.close();\n } else {\n throw std::logic_error(\"file not exists!\");\n }\n qDebug() << \"elapsed time:\" << curDT.secsTo(QDateTime::currentDateTimeUtc());\n m_load_complete = true;\n}\n\nLog::Log(const QFileInfo &fileInfo, const QString &filename,\n const HighlightPatterns *global_highlight, const QString &default_encoding,\n QObject *parent)\n : QAbstractItemModel(parent) {\n m_default_encoding = default_encoding;\n m_fileInfo = fileInfo;\n m_lastModifed = m_fileInfo.lastModified();\n m_name = m_fileInfo.fileName();\n m_fname = filename;\n m_global_highlight = global_highlight;\n m_load_complete = false;\n m_codec = QTextCodec::codecForName(m_default_encoding.toStdString().c_str());\n if (m_codec == nullptr) {\n throw std::logic_error(\"m_codec==nullptr\");\n }\n loadFile();\n auto idx = createIndex(-1, -1, nullptr);\n while (canFetchMore(idx)) {\n fetchMore(idx);\n }\n qDebug() << \"loaded \" << m_name << \" lines:\" << m_lines.size();\n}\n\nQString Log::name() const {\n return m_name;\n}\n\nQString Log::filename() const {\n return m_fname;\n}\n\nvoid Log::update() {\n qDebug() << \"update \" << m_name << \"=>\" << m_fname;\n std::lock_guard lg(_locker);\n QFileInfo fileInfo(m_fname);\n\n \/\/ if(fileInfo.lastModified()<=m_lastModifed){\n \/\/ qDebug()<<\"nothing to read: curDt:\"< 0) {\n auto old_size = m_lines.size();\n \/\/ m_load_complete=false;\n \/\/ this->beginResetModel();\n m_bts = std::move(bts);\n\n m_lines = std::move(lines);\n m_cache.clear();\n m_cache.resize(m_lines.size());\n\n m_load_complete = true;\n \/\/ this->endResetModel();\n\n emit countChanged(m_lines.size());\n emit linesChanged();\n\n if (_fltr != nullptr) {\n resetFilter(_fltr);\n } else {\n beginInsertRows(createIndex(0, 0, nullptr), old_size - 1, old_size + diff);\n \/\/ for (auto &kv : local_res) {\n \/\/ m_cache.insert(std::make_pair(kv.first, kv.second));\n \/\/ }\n endInsertRows();\n }\n emit m_lv_object->scrollToBottom();\n }\n\n inputFile.close();\n } else {\n throw std::logic_error(\"file not exists!\");\n }\n\n qDebug() << \"update elapsed time:\" << curDT.secsTo(QDateTime::currentDateTimeUtc());\n}\n\nstd::shared_ptr Log::makeRawString(int row) const {\n qDebug() << \"Log::makeRawString\";\n auto line_pos = m_lines[row];\n int start = line_pos.first;\n int i = line_pos.second;\n\n int stringSize = int(i - start + 1);\n QByteArray localStr(stringSize, ' ');\n\n int insertPos = 0;\n for (int pos = start; pos < i; ++pos) {\n localStr[insertPos++] = m_bts[pos];\n }\n\n std::shared_ptr result =\n std::make_shared(m_codec->toUnicode(localStr));\n return result;\n}\n\nvoid Log::rawStringToValue(std::shared_ptr &rawString) const {\n if (m_global_highlight == nullptr) {\n throw std::logic_error(\"m_global_highlight==nullptr\");\n }\n rawString->replace('<', \"<\");\n rawString->replace('>', \">\");\n rawString->replace(' ', \" \"); \/\/ html eats white spaces\n for (auto it = m_global_highlight->begin(); it != m_global_highlight->end(); ++it) {\n heighlightStr(rawString.get(), *it);\n }\n}\n\nstd::shared_ptr Log::makeString(int row) const {\n auto result = makeRawString(row);\n rawStringToValue(result);\n return result;\n}\n\nint Log::rowCount(const QModelIndex &parent) const {\n qDebug() << \"Log::rowCount\";\n std::lock_guard lg(_locker);\n Q_UNUSED(parent);\n if (!m_load_complete) {\n return 0;\n }\n if (_fltr != nullptr) {\n return m_fltr_cache.size();\n }\n return m_lines.size();\n \/\/ return m_cache.size();\n}\n\nQVariant Log::data(const QModelIndex &index, int role) const {\n\n const QString emptyString = \"EmptyString\";\n if (!m_load_complete) {\n return emptyString;\n }\n\n if (index.row() < 0 || index.row() >= int(m_lines.size()))\n return QVariant();\n if (role == Qt::DisplayRole || role == Qt::EditRole) {\n qDebug() << \"Log::data\";\n std::lock_guard lg(_locker);\n if (_fltr != nullptr) {\n return *m_fltr_cache[index.row()].Value;\n }\n if (m_cache[index.row()].Value != nullptr) {\n return *m_cache[index.row()].Value;\n } else {\n CachedString cs;\n cs.originValue = makeRawString(index.row());\n cs.index = index.row();\n rawStringToValue(cs.originValue);\n cs.Value = cs.originValue;\n m_cache[index.row()] = cs;\n return *cs.Value;\n }\n }\n return QVariant();\n}\n\nQString Log::plainText(const QModelIndex &index) const {\n if (index.row() < 0 || index.row() >= int(m_lines.size()))\n return QString(\"error\");\n if (_fltr == nullptr) {\n return *makeRawString(index.row());\n } else {\n return *makeRawString(m_fltr_cache[index.row()].index);\n }\n}\n\nvoid Log::clearHightlight() {\n \/\/ m_load_complete=false;\n \/\/ this->beginResetModel();\n \/\/ QtConcurrent::blockingMap(m_buffer,[](CachedString&cs){\n \/\/ cs.Value=cs.originValue;\n \/\/ });\n \/\/ for(int k=0;kcreateIndex(k,0);\n \/\/ dataChanged(mi, mi);\n \/\/ }\n \/\/ m_load_complete=true;\n \/\/ this->endResetModel();\n}\n\nbool Log::heighlightStr(QString *str, const HighlightPattern &pattern) {\n if (pattern.pattern.size() == 0) {\n return false;\n }\n bool result = false;\n\n QRegExp re(pattern.pattern);\n if (re.indexIn(*str) != -1) {\n auto ct = re.capturedTexts();\n for (auto &&captured_str : ct) {\n str->replace(re,\n \"\" + captured_str +\n \"<\/b><\/font>\");\n }\n result = true;\n }\n\n return result;\n}\n\nvoid Log::updateHeighlights(QVector::iterator \/*begin*\/,\n QVector::iterator \/*end*\/,\n const QString &pattern) {\n if (pattern.size() == 0) {\n return;\n }\n auto curDT = QDateTime::currentDateTimeUtc();\n\n qDebug() << m_fname << \"updateHeighlights elapsed time:\"\n << curDT.secsTo(QDateTime::currentDateTimeUtc());\n}\n\nvoid Log::updateHeighlights(const QString & \/*pattern*\/) {\n \/\/ updateHeighlights(m_buffer.begin(), m_buffer.end(), pattern);\n}\n\nvoid Log::localHightlightPattern(const QString &pattern) {\n if (pattern.size() == 0) {\n return;\n }\n updateHeighlights(pattern);\n}\n\nvoid Log::setListVoxObject(QListView *object) {\n m_lv_object = object;\n}\n\nQPair Log::findFrom(const QString &pattern, int index,\n SearchDirection direction) {\n qDebug() << \"Log::findFrom\";\n std::lock_guard lg(_locker);\n \/\/ TODO make thread safety. m_cache can be brokent, when timer is active\n if (index == m_cache.size() || index < 0) {\n return QPair(index, QString());\n }\n\n QRegExp re(pattern.toUpper());\n\n int i = direction == SearchDirection::Down ? index + 1 : index - 1;\n\n while (true) {\n QString str = plainText(createIndex(int(i), 0, nullptr)).toUpper();\n if (re.indexIn(str) != -1) {\n return QPair(i, str);\n }\n if (direction == SearchDirection::Down) {\n i++;\n if (i == m_cache.size()) {\n break;\n }\n } else {\n i--;\n if (i < 0) {\n break;\n }\n }\n }\n return QPair(index, \"\");\n}\n\nvoid Log::resetFilter(const Filter_Ptr &fltr) {\n qDebug() << \"Log::resetFilter\";\n std::lock_guard lg(_locker);\n m_cache.resize(m_lines.size());\n setFilter_impl(fltr);\n}\n\nvoid Log::setFilter(const Filter_Ptr &fltr) {\n qDebug() << \"Log::setFilter\";\n std::lock_guard lg(_locker);\n setFilter_impl(fltr);\n}\n\nvoid Log::setFilter_impl(const Filter_Ptr &fltr) {\n _fltr = fltr;\n int count = 0;\n m_fltr_cache.resize(m_lines.size());\n for (size_t i = 0; i < m_lines.size(); ++i) {\n auto qs = makeRawString(i);\n if (fltr->inFilter(*qs)) {\n rawStringToValue(qs);\n CachedString cs;\n cs.index = i;\n cs.originValue = qs;\n cs.Value = cs.originValue;\n m_fltr_cache[count] = cs;\n count++;\n }\n }\n\n beginResetModel();\n m_fltr_cache.resize(count);\n endResetModel();\n}\n\nvoid Log::clearFilter() {\n qDebug() << \"Log::clearFilter\";\n if (_fltr != nullptr) {\n beginResetModel();\n _fltr = nullptr;\n m_fltr_cache.resize(1);\n endResetModel();\n }\n}\nrm debug output.#include \"log.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/#include \n#include \n#include \n\nLinePositionList allLinePos(const QByteArray &bts) {\n\n int count = 0;\n auto size = bts.size();\n for (int i = 0; i < size; ++i) {\n if (bts[i] == '\\n') {\n count++;\n }\n }\n LinePositionList result(count);\n int start = 0;\n int index = 0;\n for (int i = 0; i < size; ++i) {\n if (bts[i] == '\\n') {\n LinePosition lp;\n lp.first = start;\n lp.second = i;\n result[index++] = lp;\n start = i + 1;\n }\n }\n return result;\n}\n\nLog *Log::openFile(const QString &fname, const HighlightPatterns *global_highlight,\n const QString &default_encoding, QObject *parent) {\n qDebug() << \"openFile\" << fname;\n QFileInfo fileInfo(fname);\n auto ll = new Log(fileInfo, fname, global_highlight, default_encoding, parent);\n return ll;\n}\n\nvoid Log::loadFile() {\n qDebug() << \"loadFile \" << m_fname;\n auto curDT = QDateTime::currentDateTimeUtc();\n QFile inputFile(m_fname);\n if (inputFile.open(QIODevice::ReadOnly)) {\n m_bts = std::move(inputFile.readAll());\n m_lines = allLinePos(m_bts);\n m_cache.resize(m_lines.size());\n inputFile.close();\n } else {\n throw std::logic_error(\"file not exists!\");\n }\n qDebug() << \"elapsed time:\" << curDT.secsTo(QDateTime::currentDateTimeUtc());\n m_load_complete = true;\n}\n\nLog::Log(const QFileInfo &fileInfo, const QString &filename,\n const HighlightPatterns *global_highlight, const QString &default_encoding,\n QObject *parent)\n : QAbstractItemModel(parent) {\n m_default_encoding = default_encoding;\n m_fileInfo = fileInfo;\n m_lastModifed = m_fileInfo.lastModified();\n m_name = m_fileInfo.fileName();\n m_fname = filename;\n m_global_highlight = global_highlight;\n m_load_complete = false;\n m_codec = QTextCodec::codecForName(m_default_encoding.toStdString().c_str());\n if (m_codec == nullptr) {\n throw std::logic_error(\"m_codec==nullptr\");\n }\n loadFile();\n auto idx = createIndex(-1, -1, nullptr);\n while (canFetchMore(idx)) {\n fetchMore(idx);\n }\n qDebug() << \"loaded \" << m_name << \" lines:\" << m_lines.size();\n}\n\nQString Log::name() const {\n return m_name;\n}\n\nQString Log::filename() const {\n return m_fname;\n}\n\nvoid Log::update() {\n qDebug() << \"update \" << m_name << \"=>\" << m_fname;\n std::lock_guard lg(_locker);\n QFileInfo fileInfo(m_fname);\n\n \/\/ if(fileInfo.lastModified()<=m_lastModifed){\n \/\/ qDebug()<<\"nothing to read: curDt:\"< 0) {\n auto old_size = m_lines.size();\n \/\/ m_load_complete=false;\n \/\/ this->beginResetModel();\n m_bts = std::move(bts);\n\n m_lines = std::move(lines);\n m_cache.clear();\n m_cache.resize(m_lines.size());\n\n m_load_complete = true;\n \/\/ this->endResetModel();\n\n emit countChanged(m_lines.size());\n emit linesChanged();\n\n if (_fltr != nullptr) {\n resetFilter(_fltr);\n } else {\n beginInsertRows(createIndex(0, 0, nullptr), old_size - 1, old_size + diff);\n \/\/ for (auto &kv : local_res) {\n \/\/ m_cache.insert(std::make_pair(kv.first, kv.second));\n \/\/ }\n endInsertRows();\n }\n emit m_lv_object->scrollToBottom();\n }\n\n inputFile.close();\n } else {\n throw std::logic_error(\"file not exists!\");\n }\n\n qDebug() << \"update elapsed time:\" << curDT.secsTo(QDateTime::currentDateTimeUtc());\n}\n\nstd::shared_ptr Log::makeRawString(int row) const {\n \/\/qDebug() << \"Log::makeRawString\";\n auto line_pos = m_lines[row];\n int start = line_pos.first;\n int i = line_pos.second;\n\n int stringSize = int(i - start + 1);\n QByteArray localStr(stringSize, ' ');\n\n int insertPos = 0;\n for (int pos = start; pos < i; ++pos) {\n localStr[insertPos++] = m_bts[pos];\n }\n\n std::shared_ptr result =\n std::make_shared(m_codec->toUnicode(localStr));\n return result;\n}\n\nvoid Log::rawStringToValue(std::shared_ptr &rawString) const {\n if (m_global_highlight == nullptr) {\n throw std::logic_error(\"m_global_highlight==nullptr\");\n }\n rawString->replace('<', \"<\");\n rawString->replace('>', \">\");\n rawString->replace(' ', \" \"); \/\/ html eats white spaces\n for (auto it = m_global_highlight->begin(); it != m_global_highlight->end(); ++it) {\n heighlightStr(rawString.get(), *it);\n }\n}\n\nstd::shared_ptr Log::makeString(int row) const {\n auto result = makeRawString(row);\n rawStringToValue(result);\n return result;\n}\n\nint Log::rowCount(const QModelIndex &parent) const {\n \/\/qDebug() << \"Log::rowCount\";\n std::lock_guard lg(_locker);\n Q_UNUSED(parent);\n if (!m_load_complete) {\n return 0;\n }\n if (_fltr != nullptr) {\n return m_fltr_cache.size();\n }\n return m_lines.size();\n \/\/ return m_cache.size();\n}\n\nQVariant Log::data(const QModelIndex &index, int role) const {\n\n const QString emptyString = \"EmptyString\";\n if (!m_load_complete) {\n return emptyString;\n }\n\n if (index.row() < 0 || index.row() >= int(m_lines.size()))\n return QVariant();\n if (role == Qt::DisplayRole || role == Qt::EditRole) {\n \/\/qDebug() << \"Log::data\";\n std::lock_guard lg(_locker);\n if (_fltr != nullptr) {\n return *m_fltr_cache[index.row()].Value;\n }\n if (m_cache[index.row()].Value != nullptr) {\n return *m_cache[index.row()].Value;\n } else {\n CachedString cs;\n cs.originValue = makeRawString(index.row());\n cs.index = index.row();\n rawStringToValue(cs.originValue);\n cs.Value = cs.originValue;\n m_cache[index.row()] = cs;\n return *cs.Value;\n }\n }\n return QVariant();\n}\n\nQString Log::plainText(const QModelIndex &index) const {\n if (index.row() < 0 || index.row() >= int(m_lines.size()))\n return QString(\"error\");\n if (_fltr == nullptr) {\n return *makeRawString(index.row());\n } else {\n return *makeRawString(m_fltr_cache[index.row()].index);\n }\n}\n\nvoid Log::clearHightlight() {\n \/\/ m_load_complete=false;\n \/\/ this->beginResetModel();\n \/\/ QtConcurrent::blockingMap(m_buffer,[](CachedString&cs){\n \/\/ cs.Value=cs.originValue;\n \/\/ });\n \/\/ for(int k=0;kcreateIndex(k,0);\n \/\/ dataChanged(mi, mi);\n \/\/ }\n \/\/ m_load_complete=true;\n \/\/ this->endResetModel();\n}\n\nbool Log::heighlightStr(QString *str, const HighlightPattern &pattern) {\n if (pattern.pattern.size() == 0) {\n return false;\n }\n bool result = false;\n\n QRegExp re(pattern.pattern);\n if (re.indexIn(*str) != -1) {\n auto ct = re.capturedTexts();\n for (auto &&captured_str : ct) {\n str->replace(re,\n \"\" + captured_str +\n \"<\/b><\/font>\");\n }\n result = true;\n }\n\n return result;\n}\n\nvoid Log::updateHeighlights(QVector::iterator \/*begin*\/,\n QVector::iterator \/*end*\/,\n const QString &pattern) {\n if (pattern.size() == 0) {\n return;\n }\n auto curDT = QDateTime::currentDateTimeUtc();\n\n qDebug() << m_fname << \"updateHeighlights elapsed time:\"\n << curDT.secsTo(QDateTime::currentDateTimeUtc());\n}\n\nvoid Log::updateHeighlights(const QString & \/*pattern*\/) {\n \/\/ updateHeighlights(m_buffer.begin(), m_buffer.end(), pattern);\n}\n\nvoid Log::localHightlightPattern(const QString &pattern) {\n if (pattern.size() == 0) {\n return;\n }\n updateHeighlights(pattern);\n}\n\nvoid Log::setListVoxObject(QListView *object) {\n m_lv_object = object;\n}\n\nQPair Log::findFrom(const QString &pattern, int index,\n SearchDirection direction) {\n qDebug() << \"Log::findFrom\";\n std::lock_guard lg(_locker);\n \/\/ TODO make thread safety. m_cache can be brokent, when timer is active\n if (index == m_cache.size() || index < 0) {\n return QPair(index, QString());\n }\n\n QRegExp re(pattern.toUpper());\n\n int i = direction == SearchDirection::Down ? index + 1 : index - 1;\n\n while (true) {\n QString str = plainText(createIndex(int(i), 0, nullptr)).toUpper();\n if (re.indexIn(str) != -1) {\n return QPair(i, str);\n }\n if (direction == SearchDirection::Down) {\n i++;\n if (i == m_cache.size()) {\n break;\n }\n } else {\n i--;\n if (i < 0) {\n break;\n }\n }\n }\n return QPair(index, \"\");\n}\n\nvoid Log::resetFilter(const Filter_Ptr &fltr) {\n qDebug() << \"Log::resetFilter\";\n std::lock_guard lg(_locker);\n m_cache.resize(m_lines.size());\n setFilter_impl(fltr);\n}\n\nvoid Log::setFilter(const Filter_Ptr &fltr) {\n qDebug() << \"Log::setFilter\";\n std::lock_guard lg(_locker);\n setFilter_impl(fltr);\n}\n\nvoid Log::setFilter_impl(const Filter_Ptr &fltr) {\n _fltr = fltr;\n int count = 0;\n m_fltr_cache.resize(m_lines.size());\n for (size_t i = 0; i < m_lines.size(); ++i) {\n auto qs = makeRawString(i);\n if (fltr->inFilter(*qs)) {\n rawStringToValue(qs);\n CachedString cs;\n cs.index = i;\n cs.originValue = qs;\n cs.Value = cs.originValue;\n m_fltr_cache[count] = cs;\n count++;\n }\n }\n\n beginResetModel();\n m_fltr_cache.resize(count);\n endResetModel();\n}\n\nvoid Log::clearFilter() {\n qDebug() << \"Log::clearFilter\";\n if (_fltr != nullptr) {\n beginResetModel();\n _fltr = nullptr;\n m_fltr_cache.resize(1);\n endResetModel();\n }\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \"libtorrent\/lsd.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::bind;\nusing namespace libtorrent;\n\nnamespace libtorrent\n{\n\t\/\/ defined in broadcast_socket.cpp\n\taddress guess_local_address(asio::io_service&);\n}\n\nlsd::lsd(io_service& ios, address const& listen_interface\n\t, peer_callback_t const& cb)\n\t: m_callback(cb)\n\t, m_retry_count(0)\n\t, m_socket(ios, udp::endpoint(address_v4::from_string(\"239.192.152.143\"), 6771)\n\t\t, bind(&lsd::on_announce, self(), _1, _2, _3))\n\t, m_broadcast_timer(ios)\n\t, m_disabled(false)\n{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log.open(\"lsd.log\", std::ios::in | std::ios::out | std::ios::trunc);\n#endif\n}\n\nlsd::~lsd() {}\n\nvoid lsd::announce(sha1_hash const& ih, int listen_port)\n{\n\tif (m_disabled) return;\n\n\tstd::stringstream btsearch;\n\tbtsearch << \"BT-SEARCH * HTTP\/1.1\\r\\n\"\n\t\t\"Host: 239.192.152.143:6771\\r\\n\"\n\t\t\"Port: \" << listen_port << \"\\r\\n\"\n\t\t\"Infohash: \" << ih << \"\\r\\n\"\n\t\t\"\\r\\n\\r\\n\";\n\tstd::string const& msg = btsearch.str();\n\n\tm_retry_count = 0;\n\tasio::error_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\tif (ec)\n\t{\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" ==> announce: ih: \" << ih << \" port: \" << listen_port << std::endl;\n#endif\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::resend_announce(asio::error_code const& e, std::string msg)\n{\n\tif (e) return;\n\n\tasio::error_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\n\t++m_retry_count;\n\tif (m_retry_count >= 5)\n\t\treturn;\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::on_announce(udp::endpoint const& from, char* buffer\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\n\thttp_parser p;\n\n\tbool error = false;\n\tp.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)\n\t\t, error);\n\n\tif (!p.header_finished() || error)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: incomplete HTTP message\\n\";\n#endif\n\t\treturn;\n\t}\n\n\tif (p.method() != \"bt-search\")\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid HTTP method: \" << p.method() << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& port_str = p.header(\"port\");\n\tif (port_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing port\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& ih_str = p.header(\"infohash\");\n\tif (ih_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing infohash\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tsha1_hash ih(0);\n\tstd::istringstream ih_sstr(ih_str);\n\tih_sstr >> ih;\n\tint port = atoi(port_str.c_str());\n\n\tif (!ih.is_all_zeros() && port != 0)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << time_now_string()\n\t\t\t<< \" *** incoming local announce \" << from.address()\n\t\t\t<< \":\" << port << \" ih: \" << ih << std::endl;\n#endif\n\t\t\/\/ we got an announce, pass it on through the callback\n#ifndef BOOST_NO_EXCEPTIONS\n\t\ttry {\n#endif\n\t\t\tm_callback(tcp::endpoint(from.address(), port), ih);\n#ifndef BOOST_NO_EXCEPTIONS\n\t\t}\n\t\tcatch (std::exception&) {}\n#endif\n\t}\n}\n\nvoid lsd::close()\n{\n\tm_socket.close();\n\tasio::error_code ec;\n\tm_broadcast_timer.cancel(ec);\n\tm_disabled = true;\n\tm_callback.clear();\n}\n\nlocal service discovert resend fix\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \"libtorrent\/lsd.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::bind;\nusing namespace libtorrent;\n\nnamespace libtorrent\n{\n\t\/\/ defined in broadcast_socket.cpp\n\taddress guess_local_address(asio::io_service&);\n}\n\nlsd::lsd(io_service& ios, address const& listen_interface\n\t, peer_callback_t const& cb)\n\t: m_callback(cb)\n\t, m_retry_count(1)\n\t, m_socket(ios, udp::endpoint(address_v4::from_string(\"239.192.152.143\"), 6771)\n\t\t, bind(&lsd::on_announce, self(), _1, _2, _3))\n\t, m_broadcast_timer(ios)\n\t, m_disabled(false)\n{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log.open(\"lsd.log\", std::ios::in | std::ios::out | std::ios::trunc);\n#endif\n}\n\nlsd::~lsd() {}\n\nvoid lsd::announce(sha1_hash const& ih, int listen_port)\n{\n\tif (m_disabled) return;\n\n\tstd::stringstream btsearch;\n\tbtsearch << \"BT-SEARCH * HTTP\/1.1\\r\\n\"\n\t\t\"Host: 239.192.152.143:6771\\r\\n\"\n\t\t\"Port: \" << listen_port << \"\\r\\n\"\n\t\t\"Infohash: \" << ih << \"\\r\\n\"\n\t\t\"\\r\\n\\r\\n\";\n\tstd::string const& msg = btsearch.str();\n\n\tm_retry_count = 1;\n\tasio::error_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\tif (ec)\n\t{\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" ==> announce: ih: \" << ih << \" port: \" << listen_port << std::endl;\n#endif\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::resend_announce(asio::error_code const& e, std::string msg)\n{\n\tif (e) return;\n\n\tasio::error_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\n\t++m_retry_count;\n\tif (m_retry_count >= 5)\n\t\treturn;\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::on_announce(udp::endpoint const& from, char* buffer\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\n\thttp_parser p;\n\n\tbool error = false;\n\tp.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)\n\t\t, error);\n\n\tif (!p.header_finished() || error)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: incomplete HTTP message\\n\";\n#endif\n\t\treturn;\n\t}\n\n\tif (p.method() != \"bt-search\")\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid HTTP method: \" << p.method() << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& port_str = p.header(\"port\");\n\tif (port_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing port\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& ih_str = p.header(\"infohash\");\n\tif (ih_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing infohash\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tsha1_hash ih(0);\n\tstd::istringstream ih_sstr(ih_str);\n\tih_sstr >> ih;\n\tint port = atoi(port_str.c_str());\n\n\tif (!ih.is_all_zeros() && port != 0)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << time_now_string()\n\t\t\t<< \" *** incoming local announce \" << from.address()\n\t\t\t<< \":\" << port << \" ih: \" << ih << std::endl;\n#endif\n\t\t\/\/ we got an announce, pass it on through the callback\n#ifndef BOOST_NO_EXCEPTIONS\n\t\ttry {\n#endif\n\t\t\tm_callback(tcp::endpoint(from.address(), port), ih);\n#ifndef BOOST_NO_EXCEPTIONS\n\t\t}\n\t\tcatch (std::exception&) {}\n#endif\n\t}\n}\n\nvoid lsd::close()\n{\n\tm_socket.close();\n\tasio::error_code ec;\n\tm_broadcast_timer.cancel(ec);\n\tm_disabled = true;\n\tm_callback.clear();\n}\n\n<|endoftext|>"} {"text":"\/* -*- mode: C++ ; c-file-style: \"stroustrup\" -*- *****************************\n * Qwt Widget Library\n * Copyright (C) 1997 Josef Wilgen\n * Copyright (C) 2002 Uwe Rathmann\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the Qwt License, Version 1.0\n *****************************************************************************\/\n\n#include \"qwt_series_data.h\"\n#include \"qwt_math.h\"\n\nstatic inline QRectF qwtBoundingRect( const QPointF &sample )\n{\n return QRectF( sample.x(), sample.y(), 0.0, 0.0 );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtPoint3D &sample )\n{\n return QRectF( sample.x(), sample.y(), 0.0, 0.0 );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtPointPolar &sample )\n{\n return QRectF( sample.azimuth(), sample.radius(), 0.0, 0.0 );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtIntervalSample &sample )\n{\n return QRectF( sample.interval.minValue(), sample.value,\n sample.interval.maxValue() - sample.interval.minValue(), 0.0 );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtSetSample &sample )\n{\n double minY = sample.set[0];\n double maxY = sample.set[0];\n\n for ( int i = 1; i < sample.set.size(); i++ )\n {\n if ( sample.set[i] < minY )\n minY = sample.set[i];\n if ( sample.set[i] > maxY )\n maxY = sample.set[i];\n }\n\n double minX = sample.value;\n double maxX = sample.value;\n\n return QRectF( minX, minY, maxX - minX, maxY - minY );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtOHLCSample &sample )\n{\n const QwtInterval interval = sample.boundingInterval();\n return QRectF( interval.minValue(), sample.time, interval.width(), 0.0 );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\n\ntemplate \nQRectF qwtBoundingRectT(\n const QwtSeriesData& series, int from, int to )\n{\n QRectF boundingRect( 1.0, 1.0, -2.0, -2.0 ); \/\/ invalid;\n\n if ( from < 0 )\n from = 0;\n\n if ( to < 0 )\n to = series.size() - 1;\n\n if ( to < from )\n return boundingRect;\n\n int i;\n for ( i = from; i <= to; i++ )\n {\n const QRectF rect = qwtBoundingRect( series.sample( i ) );\n if ( rect.width() >= 0.0 && rect.height() >= 0.0 )\n {\n boundingRect = rect;\n i++;\n break;\n }\n }\n\n for ( ; i <= to; i++ )\n {\n const QRectF rect = qwtBoundingRect( series.sample( i ) );\n if ( rect.width() >= 0.0 && rect.height() >= 0.0 )\n {\n boundingRect.setLeft( qMin( boundingRect.left(), rect.left() ) );\n boundingRect.setRight( qMax( boundingRect.right(), rect.right() ) );\n boundingRect.setTop( qMin( boundingRect.top(), rect.top() ) );\n boundingRect.setBottom( qMax( boundingRect.bottom(), rect.bottom() ) );\n }\n }\n\n return boundingRect;\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData &series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData &series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n The horizontal coordinates represent the azimuth, the\n vertical coordinates the radius.\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData &series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData& series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData& series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData& series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtPointSeriesData::QwtPointSeriesData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtPointSeriesData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtPoint3DSeriesData::QwtPoint3DSeriesData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtPoint3DSeriesData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtIntervalSeriesData::QwtIntervalSeriesData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtIntervalSeriesData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtSetSeriesData::QwtSetSeriesData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtSetSeriesData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtTradingChartData::QwtTradingChartData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtTradingChartData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\npmchart: fix chart auto-scaling under fetch error conditions\/* -*- mode: C++ ; c-file-style: \"stroustrup\" -*- *****************************\n * Qwt Widget Library\n * Copyright (C) 1997 Josef Wilgen\n * Copyright (C) 2002 Uwe Rathmann\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the Qwt License, Version 1.0\n *****************************************************************************\/\n\n#include \"qwt_series_data.h\"\n#include \"qwt_math.h\"\n\nstatic inline QRectF qwtBoundingRect( const QPointF &sample )\n{\n return QRectF( sample.x(), sample.y(), 0.0, 0.0 );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtPoint3D &sample )\n{\n return QRectF( sample.x(), sample.y(), 0.0, 0.0 );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtPointPolar &sample )\n{\n return QRectF( sample.azimuth(), sample.radius(), 0.0, 0.0 );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtIntervalSample &sample )\n{\n return QRectF( sample.interval.minValue(), sample.value,\n sample.interval.maxValue() - sample.interval.minValue(), 0.0 );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtSetSample &sample )\n{\n double minY = sample.set[0];\n double maxY = sample.set[0];\n\n for ( int i = 1; i < sample.set.size(); i++ )\n {\n if ( sample.set[i] < minY )\n minY = sample.set[i];\n if ( sample.set[i] > maxY )\n maxY = sample.set[i];\n }\n\n double minX = sample.value;\n double maxX = sample.value;\n\n return QRectF( minX, minY, maxX - minX, maxY - minY );\n}\n\nstatic inline QRectF qwtBoundingRect( const QwtOHLCSample &sample )\n{\n const QwtInterval interval = sample.boundingInterval();\n return QRectF( interval.minValue(), sample.time, interval.width(), 0.0 );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series. Ignores samples that\n are NaN as they do not lie within a finite bounding box.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nstatic inline bool sampleBoundValid(QRectF rect)\n{\n if ( qIsNaN(rect.left()) || qIsNaN(rect.right()) ||\n qIsNaN(rect.top()) || qIsNaN(rect.bottom()) )\n return false;\n if ( rect.width() < 0.0 || rect.height() < 0.0 )\n return false;\n return true;\n}\n\ntemplate \nQRectF qwtBoundingRectT(\n const QwtSeriesData& series, int from, int to )\n{\n QRectF boundingRect( 1.0, 1.0, -2.0, -2.0 ); \/\/ invalid;\n\n if ( from < 0 )\n from = 0;\n\n if ( to < 0 )\n to = series.size() - 1;\n\n if ( to < from )\n return boundingRect;\n\n int i;\n for ( i = from; i <= to; i++ )\n {\n const QRectF rect = qwtBoundingRect( series.sample( i ) );\n if ( sampleBoundValid( rect ) )\n {\n boundingRect = rect;\n i++;\n break;\n }\n }\n\n for ( ; i <= to; i++ )\n {\n const QRectF rect = qwtBoundingRect( series.sample( i ) );\n if ( sampleBoundValid( rect ) )\n {\n boundingRect.setLeft( qMin( boundingRect.left(), rect.left() ) );\n boundingRect.setRight( qMax( boundingRect.right(), rect.right() ) );\n boundingRect.setTop( qMin( boundingRect.top(), rect.top() ) );\n boundingRect.setBottom( qMax( boundingRect.bottom(), rect.bottom() ) );\n }\n }\n\n return boundingRect;\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData &series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData &series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n The horizontal coordinates represent the azimuth, the\n vertical coordinates the radius.\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData &series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData& series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData& series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n \\brief Calculate the bounding rectangle of a series subset\n\n Slow implementation, that iterates over the series.\n\n \\param series Series\n \\param from Index of the first sample, <= 0 means from the beginning\n \\param to Index of the last sample, < 0 means to the end\n\n \\return Bounding rectangle\n*\/\nQRectF qwtBoundingRect(\n const QwtSeriesData& series, int from, int to )\n{\n return qwtBoundingRectT( series, from, to );\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtPointSeriesData::QwtPointSeriesData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtPointSeriesData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtPoint3DSeriesData::QwtPoint3DSeriesData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtPoint3DSeriesData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtIntervalSeriesData::QwtIntervalSeriesData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtIntervalSeriesData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtSetSeriesData::QwtSetSeriesData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtSetSeriesData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n\n\/*!\n Constructor\n \\param samples Samples\n*\/\nQwtTradingChartData::QwtTradingChartData(\n const QVector &samples ):\n QwtArraySeriesData( samples )\n{\n}\n\n\/*!\n \\brief Calculate the bounding rectangle\n\n The bounding rectangle is calculated once by iterating over all\n points and is stored for all following requests.\n\n \\return Bounding rectangle\n*\/\nQRectF QwtTradingChartData::boundingRect() const\n{\n if ( d_boundingRect.width() < 0.0 )\n d_boundingRect = qwtBoundingRect( *this );\n\n return d_boundingRect;\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/sum_op.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"paddle\/fluid\/framework\/var_type_inference.h\"\n#include \"paddle\/fluid\/operators\/detail\/safe_ref.h\"\n\n#ifdef PADDLE_WITH_MKLDNN\n#include \"paddle\/fluid\/platform\/mkldnn_helper.h\"\n#endif\n\nnamespace paddle {\nnamespace operators {\nusing framework::Tensor;\n\nclass SumOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE(ctx->HasInputs(\"X\"), \"Inputs(X) should not be null\");\n\n PADDLE_ENFORCE(ctx->HasOutput(\"Out\"),\n \"Output(Out) of SumOp should not be null.\");\n if (ctx->IsRuntime() &&\n ctx->GetOutputsVarType(\"Out\")[0] ==\n framework::proto::VarType::LOD_TENSOR_ARRAY) {\n return; \/\/ skip runtime infershape when is tensor array;\n }\n\n auto x_var_types = ctx->GetInputsVarType(\"X\");\n auto x_dims = ctx->GetInputsDim(\"X\");\n\n size_t N = x_dims.size();\n PADDLE_ENFORCE_GT(N, 0, \"Input tensors count should > 0.\");\n if (N == 1) {\n VLOG(3) << \"Warning: sum have only one input, may waste memory\";\n }\n\n framework::DDim in_dim({0});\n for (size_t i = 0; i < x_dims.size(); ++i) {\n auto& x_dim = x_dims[i];\n \/\/ x_dim.size() == 1 means the real dim of selected rows is [0]\n if (x_var_types[i] == framework::proto::VarType::SELECTED_ROWS &&\n x_dim.size() == 1) {\n continue;\n }\n if (framework::product(x_dim) == 0) {\n continue;\n }\n if (framework::product(in_dim) == 0) {\n in_dim = x_dim;\n } else {\n PADDLE_ENFORCE_EQ(in_dim, x_dim, \"Input tensors must have same shape\");\n }\n }\n ctx->SetOutputDim(\"Out\", in_dim);\n ctx->ShareLoD(\"X\", \/*->*\/ \"Out\");\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n auto x_vars = ctx.MultiInputVar(\"X\");\n auto x_vars_name = ctx.Inputs(\"X\");\n\n framework::LibraryType library{framework::LibraryType::kPlain};\n framework::DataLayout layout{framework::DataLayout::kAnyLayout};\n\n#ifdef PADDLE_WITH_MKLDNN\n if (library == framework::LibraryType::kPlain &&\n platform::CanMKLDNNBeUsed(ctx)) {\n library = framework::LibraryType::kMKLDNN;\n layout = framework::DataLayout::kMKLDNN;\n }\n#endif\n\n if (x_vars[0]->IsType()) {\n int dtype = -1;\n for (size_t idx = 0; idx < x_vars.size(); ++idx) {\n PADDLE_ENFORCE(x_vars[idx] != nullptr,\n \"Input var[%s] should not be nullptr\", x_vars_name[idx]);\n auto tensor =\n framework::GetLoDTensorOrSelectedRowsValueFromVar(*x_vars[idx]);\n if (tensor->numel() == 0) {\n continue;\n }\n if (dtype == -1) {\n dtype = tensor->type();\n } else {\n PADDLE_ENFORCE_EQ(dtype, tensor->type());\n }\n }\n PADDLE_ENFORCE_NE(dtype, -1,\n \"Sum operator should have at least one tensor\");\n\n return framework::OpKernelType(\n static_cast(dtype), ctx.GetPlace(),\n layout, library);\n } else if (x_vars[0]->IsType()) {\n for (auto& var : x_vars) {\n auto& value = var->Get().value();\n if (value.IsInitialized()) {\n return framework::OpKernelType(value.type(), ctx.device_context(),\n layout, library);\n }\n }\n \/\/ if input sparse vars are not initialized, use an default kernel type.\n return framework::OpKernelType(framework::proto::VarType::FP32,\n ctx.device_context(), layout, library);\n } else if (x_vars[0]->IsType()) {\n for (auto& x_var : x_vars) {\n auto& array = x_var->Get();\n for (auto& each : array) {\n if (each.numel() != 0) {\n return framework::OpKernelType(each.type(), ctx.device_context(),\n layout, library);\n }\n }\n }\n PADDLE_THROW(\"Cannot find the input data type by all input data\");\n }\n PADDLE_THROW(\"Unexpected branch. Input type is %s\",\n framework::ToTypeName(x_vars[0]->Type()));\n }\n};\n\nclass SumOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"X\", \"(vector) The input tensors of sum operator.\")\n .AsDuplicable();\n AddOutput(\"Out\", \"(Tensor) The output tensor of sum operator.\");\n AddAttr(\"use_mkldnn\",\n \"(bool, default false) Only used in mkldnn kernel\")\n .SetDefault(false);\n AddComment(R\"DOC(\nSum operator.\n\nThis operators sums the input tensors. All the inputs can carry the\nLoD (Level of Details) information. However, the output only shares\nthe LoD information with the first input.\n)DOC\");\n }\n};\n\nclass SumOpVarTypeInference : public framework::VarTypeInference {\n public:\n void operator()(framework::InferVarTypeContext* ctx) const override {\n auto& inputs = ctx->Input(\"X\");\n auto var_type = framework::proto::VarType::SELECTED_ROWS;\n for (auto& name : ctx->Input(\"X\")) {\n VLOG(10) << name << \" \" << ctx->GetType(name);\n }\n\n bool any_input_is_lod_tensor = std::any_of(\n inputs.begin(), inputs.end(), [ctx](const std::string& name) {\n return ctx->GetType(name) == framework::proto::VarType::LOD_TENSOR;\n });\n\n auto is_tensor_array = [ctx](const std::string& name) {\n return ctx->GetType(name) == framework::proto::VarType::LOD_TENSOR_ARRAY;\n };\n\n bool any_input_is_tensor_array =\n std::any_of(inputs.begin(), inputs.end(), is_tensor_array);\n bool all_inputs_are_tensor_array =\n std::all_of(inputs.begin(), inputs.end(), is_tensor_array);\n\n if (any_input_is_tensor_array) {\n if (!all_inputs_are_tensor_array) {\n std::ostringstream os;\n for (auto& each : inputs) {\n os << \" \" << each << \" type is \" << ctx->GetType(each) << \"\\n\";\n }\n PADDLE_ENFORCE(all_inputs_are_tensor_array,\n \"Not all inputs are tensor array:\\n%s\", os.str());\n }\n var_type = framework::proto::VarType::LOD_TENSOR_ARRAY;\n } else if (any_input_is_lod_tensor) {\n var_type = framework::proto::VarType::LOD_TENSOR;\n }\n\n auto out_var_name = ctx->Output(\"Out\").front();\n ctx->SetType(out_var_name, var_type);\n ctx->SetDataType(out_var_name, ctx->GetDataType(inputs.front()));\n }\n};\n\nclass SumGradMaker : public framework::GradOpDescMakerBase {\n public:\n using framework::GradOpDescMakerBase::GradOpDescMakerBase;\n\n std::vector> operator()() const override {\n auto x_grads = InputGrad(\"X\", false);\n std::vector> grad_ops;\n grad_ops.reserve(x_grads.size());\n auto og = OutputGrad(\"Out\");\n std::transform(x_grads.begin(), x_grads.end(), std::back_inserter(grad_ops),\n [&og](const std::string& x_grad) {\n auto* grad_op = new framework::OpDesc();\n grad_op->SetType(\"scale\");\n grad_op->SetInput(\"X\", og);\n grad_op->SetOutput(\"Out\", {x_grad});\n grad_op->SetAttr(\"scale\", 1.0f);\n return std::unique_ptr(grad_op);\n });\n return grad_ops;\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(sum, ops::SumOp, ops::SumOpMaker, ops::SumGradMaker,\n ops::SumOpVarTypeInference);\n\nREGISTER_OP_CPU_KERNEL(\n sum, ops::SumKernel,\n ops::SumKernel,\n ops::SumKernel,\n ops::SumKernel);\nFix sum infershape issue\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/sum_op.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"paddle\/fluid\/framework\/var_type_inference.h\"\n#include \"paddle\/fluid\/operators\/detail\/safe_ref.h\"\n\n#ifdef PADDLE_WITH_MKLDNN\n#include \"paddle\/fluid\/platform\/mkldnn_helper.h\"\n#endif\n\nnamespace paddle {\nnamespace operators {\nusing framework::Tensor;\n\nclass SumOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE(ctx->HasInputs(\"X\"), \"Inputs(X) should not be null\");\n\n PADDLE_ENFORCE(ctx->HasOutput(\"Out\"),\n \"Output(Out) of SumOp should not be null.\");\n if (ctx->IsRuntime() &&\n ctx->GetOutputsVarType(\"Out\")[0] ==\n framework::proto::VarType::LOD_TENSOR_ARRAY) {\n return; \/\/ skip runtime infershape when is tensor array;\n }\n\n auto x_var_types = ctx->GetInputsVarType(\"X\");\n auto x_dims = ctx->GetInputsDim(\"X\");\n\n size_t N = x_dims.size();\n PADDLE_ENFORCE_GT(N, 0, \"Input tensors count should > 0.\");\n if (N == 1) {\n VLOG(3) << \"Warning: sum have only one input, may waste memory\";\n }\n\n framework::DDim in_dim({0});\n for (size_t i = 0; i < x_dims.size(); ++i) {\n auto& x_dim = x_dims[i];\n \/\/ x_dim.size() == 1 means the real dim of selected rows is [0]\n if (x_var_types[i] == framework::proto::VarType::SELECTED_ROWS &&\n x_dim.size() == 1) {\n continue;\n }\n if (framework::product(x_dim) == 0) {\n continue;\n }\n if (framework::product(in_dim) == 0) {\n in_dim = x_dim;\n } else {\n if (ctx->IsRuntime()) {\n PADDLE_ENFORCE_EQ(in_dim, x_dim,\n \"Input tensors must have same shape\");\n } else {\n PADDLE_ENFORCE_EQ(in_dim.size(), x_dim.size(),\n \"Input tensors must have same shape size\");\n \/\/ if in_dim or x_dim has -1, not check equal\n for (int i = 0; i < x_dim.size(); ++i) {\n if (x_dim[i] == -1 || in_dim[i] == -1) {\n continue;\n }\n PADDLE_ENFORCE_EQ(in_dim[i], x_dim[i],\n \"Input tensors must have same shape if not -1\");\n }\n }\n }\n }\n ctx->SetOutputDim(\"Out\", in_dim);\n ctx->ShareLoD(\"X\", \/*->*\/ \"Out\");\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n auto x_vars = ctx.MultiInputVar(\"X\");\n auto x_vars_name = ctx.Inputs(\"X\");\n\n framework::LibraryType library{framework::LibraryType::kPlain};\n framework::DataLayout layout{framework::DataLayout::kAnyLayout};\n\n#ifdef PADDLE_WITH_MKLDNN\n if (library == framework::LibraryType::kPlain &&\n platform::CanMKLDNNBeUsed(ctx)) {\n library = framework::LibraryType::kMKLDNN;\n layout = framework::DataLayout::kMKLDNN;\n }\n#endif\n\n if (x_vars[0]->IsType()) {\n int dtype = -1;\n for (size_t idx = 0; idx < x_vars.size(); ++idx) {\n PADDLE_ENFORCE(x_vars[idx] != nullptr,\n \"Input var[%s] should not be nullptr\", x_vars_name[idx]);\n auto tensor =\n framework::GetLoDTensorOrSelectedRowsValueFromVar(*x_vars[idx]);\n if (tensor->numel() == 0) {\n continue;\n }\n if (dtype == -1) {\n dtype = tensor->type();\n } else {\n PADDLE_ENFORCE_EQ(dtype, tensor->type());\n }\n }\n PADDLE_ENFORCE_NE(dtype, -1,\n \"Sum operator should have at least one tensor\");\n\n return framework::OpKernelType(\n static_cast(dtype), ctx.GetPlace(),\n layout, library);\n } else if (x_vars[0]->IsType()) {\n for (auto& var : x_vars) {\n auto& value = var->Get().value();\n if (value.IsInitialized()) {\n return framework::OpKernelType(value.type(), ctx.device_context(),\n layout, library);\n }\n }\n \/\/ if input sparse vars are not initialized, use an default kernel type.\n return framework::OpKernelType(framework::proto::VarType::FP32,\n ctx.device_context(), layout, library);\n } else if (x_vars[0]->IsType()) {\n for (auto& x_var : x_vars) {\n auto& array = x_var->Get();\n for (auto& each : array) {\n if (each.numel() != 0) {\n return framework::OpKernelType(each.type(), ctx.device_context(),\n layout, library);\n }\n }\n }\n PADDLE_THROW(\"Cannot find the input data type by all input data\");\n }\n PADDLE_THROW(\"Unexpected branch. Input type is %s\",\n framework::ToTypeName(x_vars[0]->Type()));\n }\n};\n\nclass SumOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"X\", \"(vector) The input tensors of sum operator.\")\n .AsDuplicable();\n AddOutput(\"Out\", \"(Tensor) The output tensor of sum operator.\");\n AddAttr(\"use_mkldnn\",\n \"(bool, default false) Only used in mkldnn kernel\")\n .SetDefault(false);\n AddComment(R\"DOC(\nSum operator.\n\nThis operators sums the input tensors. All the inputs can carry the\nLoD (Level of Details) information. However, the output only shares\nthe LoD information with the first input.\n)DOC\");\n }\n};\n\nclass SumOpVarTypeInference : public framework::VarTypeInference {\n public:\n void operator()(framework::InferVarTypeContext* ctx) const override {\n auto& inputs = ctx->Input(\"X\");\n auto var_type = framework::proto::VarType::SELECTED_ROWS;\n for (auto& name : ctx->Input(\"X\")) {\n VLOG(10) << name << \" \" << ctx->GetType(name);\n }\n\n bool any_input_is_lod_tensor = std::any_of(\n inputs.begin(), inputs.end(), [ctx](const std::string& name) {\n return ctx->GetType(name) == framework::proto::VarType::LOD_TENSOR;\n });\n\n auto is_tensor_array = [ctx](const std::string& name) {\n return ctx->GetType(name) == framework::proto::VarType::LOD_TENSOR_ARRAY;\n };\n\n bool any_input_is_tensor_array =\n std::any_of(inputs.begin(), inputs.end(), is_tensor_array);\n bool all_inputs_are_tensor_array =\n std::all_of(inputs.begin(), inputs.end(), is_tensor_array);\n\n if (any_input_is_tensor_array) {\n if (!all_inputs_are_tensor_array) {\n std::ostringstream os;\n for (auto& each : inputs) {\n os << \" \" << each << \" type is \" << ctx->GetType(each) << \"\\n\";\n }\n PADDLE_ENFORCE(all_inputs_are_tensor_array,\n \"Not all inputs are tensor array:\\n%s\", os.str());\n }\n var_type = framework::proto::VarType::LOD_TENSOR_ARRAY;\n } else if (any_input_is_lod_tensor) {\n var_type = framework::proto::VarType::LOD_TENSOR;\n }\n\n auto out_var_name = ctx->Output(\"Out\").front();\n ctx->SetType(out_var_name, var_type);\n ctx->SetDataType(out_var_name, ctx->GetDataType(inputs.front()));\n }\n};\n\nclass SumGradMaker : public framework::GradOpDescMakerBase {\n public:\n using framework::GradOpDescMakerBase::GradOpDescMakerBase;\n\n std::vector> operator()() const override {\n auto x_grads = InputGrad(\"X\", false);\n std::vector> grad_ops;\n grad_ops.reserve(x_grads.size());\n auto og = OutputGrad(\"Out\");\n std::transform(x_grads.begin(), x_grads.end(), std::back_inserter(grad_ops),\n [&og](const std::string& x_grad) {\n auto* grad_op = new framework::OpDesc();\n grad_op->SetType(\"scale\");\n grad_op->SetInput(\"X\", og);\n grad_op->SetOutput(\"Out\", {x_grad});\n grad_op->SetAttr(\"scale\", 1.0f);\n return std::unique_ptr(grad_op);\n });\n return grad_ops;\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OPERATOR(sum, ops::SumOp, ops::SumOpMaker, ops::SumGradMaker,\n ops::SumOpVarTypeInference);\n\nREGISTER_OP_CPU_KERNEL(\n sum, ops::SumKernel,\n ops::SumKernel,\n ops::SumKernel,\n ops::SumKernel);\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2009 Toni Gundogdu.\n *\n * This file is part of cclive.\n * \n * cclive is free software: you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or (at your option) any later\n * version.\n * \n * cclive is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU General Public License along with\n * this program. If not, see .\n *\/\n\n#include \"config.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef HAVE_UNISTD_H\n#include \n#endif\n\n#ifdef HAVE_FCNTL_H\n#include \n#endif\n\n#ifdef HAVE_SYS_STAT_H\n#include \n#endif\n\n#include \"except.h\"\n#include \"macros.h\"\n#include \"opts.h\"\n#include \"log.h\"\n\n\/\/ LogBuffer\n\nLogBuffer::LogBuffer(const int& fd, const bool& close_after)\n : fd(fd), verbose(true), close_after(close_after)\n{\n setp(buffer, buffer+(BufferSize-1));\n}\n\nLogBuffer::~LogBuffer() {\n sync();\n if (close_after)\n close(fd);\n}\n\nvoid\nLogBuffer::setVerbose(const bool& verbose) {\n this->verbose = verbose;\n}\n\nint\nLogBuffer::flushBuffer() {\n if (!verbose)\n return EOF;\n const int n = pptr() - pbase();\n if (write(fd,buffer,n) != n)\n return EOF;\n pbump(-n);\n return n;\n}\n\nstd::streambuf::int_type\nLogBuffer::overflow(std::streambuf::int_type c) {\n if (c != EOF) {\n *pptr() = c;\n pbump(1);\n }\n if (flushBuffer() == EOF)\n return EOF;\n return c;\n}\n\nint\nLogBuffer::sync() {\n if (flushBuffer() == EOF)\n return -1;\n return 0;\n}\n\n\/\/ LogMgr\n\nLogMgr::LogMgr()\n : lbout(NULL), lberr(NULL), oscout(NULL), oscerr(NULL),\n rc(CCLIVE_OK), fname(\"\")\n{\n _init();\n}\n\n \/\/ Keeps -Weffc++ happy.\nLogMgr::LogMgr(const LogMgr&)\n : lbout(NULL), lberr(NULL), oscout(NULL), oscerr(NULL),\n rc(CCLIVE_OK), fname(\"\")\n{\n _init();\n}\n\n \/\/ Ditto.\nLogMgr&\nLogMgr::operator=(const LogMgr&) {\n return *this;\n}\n\nvoid\nLogMgr::_init(const std::string& fname) {\n\n this->fname = fname;\n\n _DELETE(lbout);\n _DELETE(lberr);\n _DELETE(oscout);\n _DELETE(oscerr);\n\n int fdout = fileno(stdout),\n fderr = fileno(stderr);\n\n bool close_after = false;\n\n if (!fname.empty()) {\n const int fd = open(\n fname.c_str(),\n O_WRONLY|O_CREAT|O_TRUNC,\n S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH\n );\n if (fd == -1) {\n#ifdef HAVE_STRERROR\n fprintf(stderr, \"error: %s: %s\\n\",\n fname.c_str(), strerror(errno));\n#else\n perror(\"open\");\n#endif\n exit (CCLIVE_SYSTEM);\n }\n fderr = fdout = fd;\n close_after = true;\n }\n\n lbout = new LogBuffer(fdout, close_after);\n lberr = new LogBuffer(fderr, close_after);\n\n oscout = new std::ostream(lbout);\n oscerr = new std::ostream(lberr);\n}\n\nvoid\nLogMgr::init() {\n const Options opts = optsmgr.getOptions();\n\n if (opts.background_given)\n _init(opts.logfile_arg);\n else {\n lbout->setVerbose(!opts.quiet_given);\n lberr->setVerbose(!opts.quiet_given);\n }\n}\n\nLogMgr::~LogMgr() {\n _DELETE(oscerr);\n _DELETE(oscout);\n _DELETE(lberr);\n _DELETE(lbout);\n}\n\nstd::ostream&\nLogMgr::cout() const {\n return *oscout;\n}\n\nstd::ostream&\nLogMgr::cerr() const {\n return *oscerr;\n}\n\nstd::ostream&\nLogMgr::cerr(const RuntimeException& except,\n const bool& prepend_newline \/*=true*\/)\n{\n if (prepend_newline)\n *oscerr << \"\\n\";\n\n *oscerr << \"error: \" << except.what() << std::endl;\n\n rc = except.getReturnCode();\n\n return *oscerr;\n}\n\nstd::ostream&\nLogMgr::cerr(const std::string& what,\n const bool& prepend_newline, \/*=true*\/\n const bool& prepend_error, \/*=true*\/\n const bool& append_newline \/*=true*\/)\n{\n if (prepend_newline)\n *oscerr << \"\\n\";\n\n if (prepend_error)\n *oscerr << \"error: \";\n \n *oscerr << what;\n \n if (append_newline)\n *oscerr << std::endl;\n else\n *oscerr << std::flush;\n\n return *oscerr;\n}\n\nconst ReturnCode&\nLogMgr::getReturnCode() const {\n return rc;\n}\n\nvoid\nLogMgr::resetReturnCode() {\n rc = CCLIVE_OK;\n}\n\n\nadd ifdef-blocks for S_IRGRP and S_IROTH.\/*\n * Copyright (C) 2009 Toni Gundogdu.\n *\n * This file is part of cclive.\n * \n * cclive is free software: you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or (at your option) any later\n * version.\n * \n * cclive is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU General Public License along with\n * this program. If not, see .\n *\/\n\n#include \"config.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef HAVE_UNISTD_H\n#include \n#endif\n\n#ifdef HAVE_FCNTL_H\n#include \n#endif\n\n#ifdef HAVE_SYS_STAT_H\n#include \n#endif\n\n#ifndef S_IRGRP\n# define S_IRGRP S_IRUSR\n#endif\n\n#ifndef S_IROTH\n# define S_IROTH S_IRUSR\n#endif\n\n#include \"except.h\"\n#include \"macros.h\"\n#include \"opts.h\"\n#include \"log.h\"\n\n\/\/ LogBuffer\n\nLogBuffer::LogBuffer(const int& fd, const bool& close_after)\n : fd(fd), verbose(true), close_after(close_after)\n{\n setp(buffer, buffer+(BufferSize-1));\n}\n\nLogBuffer::~LogBuffer() {\n sync();\n if (close_after)\n close(fd);\n}\n\nvoid\nLogBuffer::setVerbose(const bool& verbose) {\n this->verbose = verbose;\n}\n\nint\nLogBuffer::flushBuffer() {\n if (!verbose)\n return EOF;\n const int n = pptr() - pbase();\n if (write(fd,buffer,n) != n)\n return EOF;\n pbump(-n);\n return n;\n}\n\nstd::streambuf::int_type\nLogBuffer::overflow(std::streambuf::int_type c) {\n if (c != EOF) {\n *pptr() = c;\n pbump(1);\n }\n if (flushBuffer() == EOF)\n return EOF;\n return c;\n}\n\nint\nLogBuffer::sync() {\n if (flushBuffer() == EOF)\n return -1;\n return 0;\n}\n\n\/\/ LogMgr\n\nLogMgr::LogMgr()\n : lbout(NULL), lberr(NULL), oscout(NULL), oscerr(NULL),\n rc(CCLIVE_OK), fname(\"\")\n{\n _init();\n}\n\n \/\/ Keeps -Weffc++ happy.\nLogMgr::LogMgr(const LogMgr&)\n : lbout(NULL), lberr(NULL), oscout(NULL), oscerr(NULL),\n rc(CCLIVE_OK), fname(\"\")\n{\n _init();\n}\n\n \/\/ Ditto.\nLogMgr&\nLogMgr::operator=(const LogMgr&) {\n return *this;\n}\n\nvoid\nLogMgr::_init(const std::string& fname) {\n\n this->fname = fname;\n\n _DELETE(lbout);\n _DELETE(lberr);\n _DELETE(oscout);\n _DELETE(oscerr);\n\n int fdout = fileno(stdout),\n fderr = fileno(stderr);\n\n bool close_after = false;\n\n if (!fname.empty()) {\n const int fd = open(\n fname.c_str(),\n O_WRONLY|O_CREAT|O_TRUNC,\n S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH\n );\n if (fd == -1) {\n#ifdef HAVE_STRERROR\n fprintf(stderr, \"error: %s: %s\\n\",\n fname.c_str(), strerror(errno));\n#else\n perror(\"open\");\n#endif\n exit (CCLIVE_SYSTEM);\n }\n fderr = fdout = fd;\n close_after = true;\n }\n\n lbout = new LogBuffer(fdout, close_after);\n lberr = new LogBuffer(fderr, close_after);\n\n oscout = new std::ostream(lbout);\n oscerr = new std::ostream(lberr);\n}\n\nvoid\nLogMgr::init() {\n const Options opts = optsmgr.getOptions();\n\n if (opts.background_given)\n _init(opts.logfile_arg);\n else {\n lbout->setVerbose(!opts.quiet_given);\n lberr->setVerbose(!opts.quiet_given);\n }\n}\n\nLogMgr::~LogMgr() {\n _DELETE(oscerr);\n _DELETE(oscout);\n _DELETE(lberr);\n _DELETE(lbout);\n}\n\nstd::ostream&\nLogMgr::cout() const {\n return *oscout;\n}\n\nstd::ostream&\nLogMgr::cerr() const {\n return *oscerr;\n}\n\nstd::ostream&\nLogMgr::cerr(const RuntimeException& except,\n const bool& prepend_newline \/*=true*\/)\n{\n if (prepend_newline)\n *oscerr << \"\\n\";\n\n *oscerr << \"error: \" << except.what() << std::endl;\n\n rc = except.getReturnCode();\n\n return *oscerr;\n}\n\nstd::ostream&\nLogMgr::cerr(const std::string& what,\n const bool& prepend_newline, \/*=true*\/\n const bool& prepend_error, \/*=true*\/\n const bool& append_newline \/*=true*\/)\n{\n if (prepend_newline)\n *oscerr << \"\\n\";\n\n if (prepend_error)\n *oscerr << \"error: \";\n \n *oscerr << what;\n \n if (append_newline)\n *oscerr << std::endl;\n else\n *oscerr << std::flush;\n\n return *oscerr;\n}\n\nconst ReturnCode&\nLogMgr::getReturnCode() const {\n return rc;\n}\n\nvoid\nLogMgr::resetReturnCode() {\n rc = CCLIVE_OK;\n}\n\n\n<|endoftext|>"} {"text":"\/\/ STL\n#include \n#include \n#include \n\/\/ CPPUNIT\n#include \n\/\/ StdAir\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ Trademgen\n#include \n#include \n\/\/ TraDemGen Test Suite\n#include \n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Test is based on ...\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid DemandGenerationTestSuite::simpleEventGenerationHelper() {\n\n \/\/ Input file name\n stdair::Filename_T lInputFilename (\"..\/samples\/demand01.csv\");\n\n \/\/ Output log File\n std::string lLogFilename (\"DemandGenerationTestSuite.log\");\n \n \/\/ Airline code\n stdair::AirlineCode_T lAirlineCode (\"BA\");\n \n \/\/ Set the log parameters\n std::ofstream logOutputFile;\n \/\/ open and clean the log outputfile\n logOutputFile.open (lLogFilename.c_str());\n logOutputFile.clear();\n \n \/\/ Initialise the TraDemGen service object\n const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);\n TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams, lInputFilename);\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Demand characteristics\n stdair::DemandCharacteristics demandCharacteristics1;\n stdair::DemandCharacteristics demandCharacteristics2;\n \/\/ Demand distribution\n stdair::DemandDistribution demandDistribution1;\n stdair::DemandDistribution demandDistribution2;\n\n \/\/ distribution of number of requests\n demandDistribution1.setMeanNumberOfRequests (10.0);\n demandDistribution1.setStandardDeviationNumberOfRequests (2.0);\n demandDistribution2.setMeanNumberOfRequests (12.0);\n demandDistribution2.setStandardDeviationNumberOfRequests (1.0);\n\n \/\/ origin\n demandCharacteristics1.setOrigin (\"LHR\");\n demandCharacteristics2.setOrigin (\"LHR\");\n \/\/ destination\n demandCharacteristics1.setDestination (\"JFK\");\n demandCharacteristics2.setDestination (\"JFK\");\n \/\/ preferred departure date\n demandCharacteristics1.setPreferredDepartureDate (boost::gregorian::date (2010,1,17));\n demandCharacteristics2.setPreferredDepartureDate (boost::gregorian::date (2010,1,18));\n \/\/ Passenger type\n demandCharacteristics1.setPaxType (\"L\");\n demandCharacteristics2.setPaxType (\"B\");\n \n \/\/ arrival pattern\n std::multimap arrivalPatternCumulativeDistribution1;\n arrivalPatternCumulativeDistribution1.\n insert ( std::pair (-365.0, 0) );\n arrivalPatternCumulativeDistribution1.\n insert ( std::pair (-67.0, 0.2) );\n arrivalPatternCumulativeDistribution1.\n insert ( std::pair (-17.0, 0.5) );\n arrivalPatternCumulativeDistribution1.\n insert ( std::pair (0.0, 1.0) );\n\n std::multimap arrivalPatternCumulativeDistribution2;\n arrivalPatternCumulativeDistribution2.\n insert ( std::pair (-365.0, 0) );\n arrivalPatternCumulativeDistribution2.\n insert ( std::pair (-300.0, 0.5) );\n arrivalPatternCumulativeDistribution2.\n insert ( std::pair (-200.0, 0.9) );\n arrivalPatternCumulativeDistribution2.\n insert ( std::pair (0.0, 1.0) );\n\n \/\/ When creating the ContinuousAttribute object, the mapping is\n \/\/ inverted, i.e., the inverse cumulative distribution can be\n \/\/ derived from the cumulative distribution\n const stdair::ContinuousAttribute arrivalPattern1 (arrivalPatternCumulativeDistribution1);\n demandCharacteristics1.setArrivalPattern (arrivalPattern1);\n const stdair::ContinuousAttribute arrivalPattern2 (arrivalPatternCumulativeDistribution2);\n demandCharacteristics2.setArrivalPattern (arrivalPattern2);\n \n \/\/ Display\n STDAIR_LOG_DEBUG (\"Demand 1: \" << demandCharacteristics1.display()\n << demandDistribution1.display()\n << std::endl << std::endl);\n\n STDAIR_LOG_DEBUG (\"Demand 2: \" << demandCharacteristics2.display()\n << demandDistribution2.display()\n << std::endl << std::endl);\n\n \/\/ Seeds\n stdair::RandomSeed_T seed = 2;\n \n \/\/ Key\n stdair::DemandStreamKey_T key1 = 1;\n stdair::DemandStreamKey_T key2 = 2;\n \n\n \/\/ Initialize the demand stream\n TRADEMGEN::DemandStream demandStream1 (key1, demandCharacteristics1,\n demandDistribution1, seed, seed, seed);\n TRADEMGEN::DemandStream demandStream2 (key2, demandCharacteristics2,\n demandDistribution2, seed, seed, seed);\n\n trademgenService.addDemandStream (demandStream1);\n trademgenService.addDemandStream (demandStream2);\n \n \/\/ Get the total number of requests to be generated\n stdair::Count_T totalNumberOfRequestsToBeGenerated1 =\n demandStream1.getTotalNumberOfRequestsToBeGenerated ();\n stdair::Count_T totalNumberOfRequestsToBeGenerated2 =\n demandStream2.getTotalNumberOfRequestsToBeGenerated ();\n\n STDAIR_LOG_DEBUG (\"Number of requests to be generated (demand 1): \"\n << totalNumberOfRequestsToBeGenerated1 << std::endl);\n STDAIR_LOG_DEBUG (\"Number of requests to be generated (demand 2): \"\n << totalNumberOfRequestsToBeGenerated2 << std::endl);\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Event queue\n stdair::EventQueue lEventQueue = stdair::EventQueue ();\n \n \/\/ Initialize by adding one request of each type\n const bool stillHavingRequestsToBeGenerated1 = \n demandStream1.stillHavingRequestsToBeGenerated ();\n if (stillHavingRequestsToBeGenerated1) {\n stdair::BookingRequestPtr_T lRequest1 = demandStream1.generateNext();\n assert (lRequest1 != NULL);\n stdair::DateTime_T lRequestDateTime = lRequest1->getRequestDateTime ();\n stdair::EventStruct lEventStruct (\"Request\", lRequestDateTime, key1,\n lRequest1);\n lEventQueue.addEvent (lEventStruct);\n }\n \n const bool stillHavingRequestsToBeGenerated2 = \n demandStream2.stillHavingRequestsToBeGenerated ();\n if (stillHavingRequestsToBeGenerated2) {\n stdair::BookingRequestPtr_T lRequest2 = demandStream2.generateNext();\n assert (lRequest2 != NULL);\n stdair::DateTime_T lRequestDateTime = lRequest2->getRequestDateTime ();\n stdair::EventStruct lEventStruct(\"Request\", lRequestDateTime, key2,\n lRequest2);\n lEventQueue.addEvent (lEventStruct);\n }\n \n \/\/ Pop requests, get type, and generate next request of same type\n int i = 0;\n while (lEventQueue.isQueueDone() == false && i < 20) {\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Before popping (\" << i << \")\" );\n STDAIR_LOG_DEBUG (\"Queue size: \" << lEventQueue.getQueueSize () );\n STDAIR_LOG_DEBUG (\"Is queue done? \" << lEventQueue.isQueueDone () );\n \n stdair::EventStruct& lEventStruct = lEventQueue.popEvent ();\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"After popping\" );\n STDAIR_LOG_DEBUG (\"Queue size: \" << lEventQueue.getQueueSize ());\n STDAIR_LOG_DEBUG (\"Is queue done? \" << lEventQueue.isQueueDone ());\n\n STDAIR_LOG_DEBUG (\"Popped request \" << i );\n \n const stdair::BookingRequestStruct& lPoppedRequest =\n lEventStruct.getBookingRequest ();\n \n \/\/ DEBUG\n STDAIR_LOG_DEBUG (lPoppedRequest.describe());\n \n \/\/ Retrieve the corresponding demand stream\n const stdair::DemandStreamKey_T& lDemandStreamKey =\n lEventStruct.getDemandStreamKey ();\n TRADEMGEN::DemandStream& lDemandStream =\n trademgenService.getDemandStream (lDemandStreamKey);\n \/\/ generate next request\n bool stillHavingRequestsToBeGenerated = \n lDemandStream.stillHavingRequestsToBeGenerated();\n STDAIR_LOG_DEBUG (\"stillHavingRequestsToBeGenerated: \" << stillHavingRequestsToBeGenerated );\n if (stillHavingRequestsToBeGenerated) {\n stdair::BookingRequestPtr_T lNextRequest = lDemandStream.generateNext();\n assert (lNextRequest != NULL);\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Added request: \" << lNextRequest->describe());\n \n stdair::DateTime_T lNextRequestDateTime =\n lNextRequest->getRequestDateTime ();\n stdair::EventStruct lNextEventStruct (\"Request\",\n lNextRequestDateTime,\n lDemandStreamKey,\n lNextRequest);\n lEventQueue.eraseLastUsedEvent ();\n lEventQueue.addEvent (lNextEventStruct);\n \n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"After adding\");\n STDAIR_LOG_DEBUG (\"Queue size: \" << lEventQueue.getQueueSize ());\n STDAIR_LOG_DEBUG (\"Is queue done? \" << lEventQueue.isQueueDone ());\n \n }\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (std::endl);\n \n \/\/ Iterate\n ++i;\n }\n}\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid DemandGenerationTestSuite::simpleEventGeneration () {\n \/\/ TODO: Check that the generated events follow the law given as input\n CPPUNIT_ASSERT_NO_THROW ( simpleEventGenerationHelper(););\n}\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ void DemandGenerationTestSuite::errorCase () {\n\/\/ CPPUNIT_ASSERT (false);\n\/\/ }\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDemandGenerationTestSuite::DemandGenerationTestSuite () {\n _describeKey << \"Running test on RMOL Optimisation function\"; \n}\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ M A I N \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCPPUNIT_MAIN()\n\n[test] Adapted the test suite.\/\/ STL\n#include \n#include \n#include \n\/\/ CPPUNIT\n#include \n\/\/ StdAir\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ Trademgen\n#include \n\/\/ TraDemGen Test Suite\n#include \n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Test is based on ...\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid DemandGenerationTestSuite::simpleEventGenerationHelper() {\n\n \/\/ Input file name\n stdair::Filename_T lInputFilename (\"..\/samples\/demand01.csv\");\n\n \/\/ Output log File\n std::string lLogFilename (\"DemandGenerationTestSuite.log\");\n \n \/\/ Airline code\n stdair::AirlineCode_T lAirlineCode (\"BA\");\n \n \/\/ Set the log parameters\n std::ofstream logOutputFile;\n \/\/ open and clean the log outputfile\n logOutputFile.open (lLogFilename.c_str());\n logOutputFile.clear();\n \n \/\/ Initialise the TraDemGen service object\n const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);\n TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams, lInputFilename);\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Demand characteristics\n stdair::DemandCharacteristics demandCharacteristics1;\n stdair::DemandCharacteristics demandCharacteristics2;\n \/\/ Demand distribution\n stdair::DemandDistribution demandDistribution1;\n stdair::DemandDistribution demandDistribution2;\n\n \/\/ distribution of number of requests\n demandDistribution1.setMeanNumberOfRequests (10.0);\n demandDistribution1.setStandardDeviationNumberOfRequests (2.0);\n demandDistribution2.setMeanNumberOfRequests (12.0);\n demandDistribution2.setStandardDeviationNumberOfRequests (1.0);\n\n \/\/ origin\n demandCharacteristics1.setOrigin (\"LHR\");\n demandCharacteristics2.setOrigin (\"LHR\");\n \/\/ destination\n demandCharacteristics1.setDestination (\"JFK\");\n demandCharacteristics2.setDestination (\"JFK\");\n \/\/ preferred departure date\n demandCharacteristics1.setPreferredDepartureDate (boost::gregorian::date (2010,1,17));\n demandCharacteristics2.setPreferredDepartureDate (boost::gregorian::date (2010,1,18));\n \/\/ Passenger type\n demandCharacteristics1.setPaxType (\"L\");\n demandCharacteristics2.setPaxType (\"B\");\n \n \/\/ arrival pattern\n std::multimap arrivalPatternCumulativeDistribution1;\n arrivalPatternCumulativeDistribution1.\n insert ( std::pair (-365.0, 0) );\n arrivalPatternCumulativeDistribution1.\n insert ( std::pair (-67.0, 0.2) );\n arrivalPatternCumulativeDistribution1.\n insert ( std::pair (-17.0, 0.5) );\n arrivalPatternCumulativeDistribution1.\n insert ( std::pair (0.0, 1.0) );\n\n std::multimap arrivalPatternCumulativeDistribution2;\n arrivalPatternCumulativeDistribution2.\n insert ( std::pair (-365.0, 0) );\n arrivalPatternCumulativeDistribution2.\n insert ( std::pair (-300.0, 0.5) );\n arrivalPatternCumulativeDistribution2.\n insert ( std::pair (-200.0, 0.9) );\n arrivalPatternCumulativeDistribution2.\n insert ( std::pair (0.0, 1.0) );\n\n \/\/ When creating the ContinuousAttribute object, the mapping is\n \/\/ inverted, i.e., the inverse cumulative distribution can be\n \/\/ derived from the cumulative distribution\n const stdair::ContinuousAttribute arrivalPattern1 (arrivalPatternCumulativeDistribution1);\n demandCharacteristics1.setArrivalPattern (arrivalPattern1);\n const stdair::ContinuousAttribute arrivalPattern2 (arrivalPatternCumulativeDistribution2);\n demandCharacteristics2.setArrivalPattern (arrivalPattern2);\n \n \/\/ Display\n STDAIR_LOG_DEBUG (\"Demand 1: \" << demandCharacteristics1.display()\n << demandDistribution1.display()\n << std::endl << std::endl);\n\n STDAIR_LOG_DEBUG (\"Demand 2: \" << demandCharacteristics2.display()\n << demandDistribution2.display()\n << std::endl << std::endl);\n\n \/\/ Seeds\n stdair::RandomSeed_T seed = 2;\n \n \/\/ Key\n stdair::DemandStreamKey_T key1 = 1;\n stdair::DemandStreamKey_T key2 = 2;\n \n\n \/\/ Initialize the demand stream\n trademgenService.addDemandStream (key1, demandCharacteristics1,\n demandDistribution1, seed, seed, seed);\n trademgenService.addDemandStream (key2, demandCharacteristics2,\n demandDistribution2, seed, seed, seed);\n \n \/\/ Get the total number of requests to be generated\n stdair::Count_T totalNumberOfRequestsToBeGenerated1 =\n trademgenService.getTotalNumberOfRequestsToBeGenerated (key1);\n stdair::Count_T totalNumberOfRequestsToBeGenerated2 =\n trademgenService.getTotalNumberOfRequestsToBeGenerated (key2);\n\n STDAIR_LOG_DEBUG (\"Number of requests to be generated (demand 1): \"\n << totalNumberOfRequestsToBeGenerated1 << std::endl);\n STDAIR_LOG_DEBUG (\"Number of requests to be generated (demand 2): \"\n << totalNumberOfRequestsToBeGenerated2 << std::endl);\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Event queue\n stdair::EventQueue lEventQueue = stdair::EventQueue ();\n \n \/\/ Initialize by adding one request of each type\n const bool stillHavingRequestsToBeGenerated1 = \n trademgenService.stillHavingRequestsToBeGenerated (key1);\n if (stillHavingRequestsToBeGenerated1) {\n stdair::BookingRequestPtr_T lRequest1 =\n trademgenService.generateNextRequest (key1);\n assert (lRequest1 != NULL);\n stdair::DateTime_T lRequestDateTime = lRequest1->getRequestDateTime ();\n stdair::EventStruct lEventStruct (\"Request\", lRequestDateTime, key1,\n lRequest1);\n lEventQueue.addEvent (lEventStruct);\n }\n \n const bool stillHavingRequestsToBeGenerated2 = \n trademgenService.stillHavingRequestsToBeGenerated (key2);\n if (stillHavingRequestsToBeGenerated2) {\n stdair::BookingRequestPtr_T lRequest2 =\n trademgenService.generateNextRequest (key2);\n assert (lRequest2 != NULL);\n stdair::DateTime_T lRequestDateTime = lRequest2->getRequestDateTime ();\n stdair::EventStruct lEventStruct(\"Request\", lRequestDateTime, key2,\n lRequest2);\n lEventQueue.addEvent (lEventStruct);\n }\n \n \/\/ Pop requests, get type, and generate next request of same type\n int i = 0;\n while (lEventQueue.isQueueDone() == false && i < 20) {\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Before popping (\" << i << \")\" );\n STDAIR_LOG_DEBUG (\"Queue size: \" << lEventQueue.getQueueSize () );\n STDAIR_LOG_DEBUG (\"Is queue done? \" << lEventQueue.isQueueDone () );\n \n stdair::EventStruct& lEventStruct = lEventQueue.popEvent ();\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"After popping\" );\n STDAIR_LOG_DEBUG (\"Queue size: \" << lEventQueue.getQueueSize ());\n STDAIR_LOG_DEBUG (\"Is queue done? \" << lEventQueue.isQueueDone ());\n\n STDAIR_LOG_DEBUG (\"Popped request \" << i );\n \n const stdair::BookingRequestStruct& lPoppedRequest =\n lEventStruct.getBookingRequest ();\n \n \/\/ DEBUG\n STDAIR_LOG_DEBUG (lPoppedRequest.describe());\n \n \/\/ Retrieve the corresponding demand stream\n const stdair::DemandStreamKey_T& lDemandStreamKey =\n lEventStruct.getDemandStreamKey ();\n \/\/ generate next request\n bool stillHavingRequestsToBeGenerated = \n trademgenService.stillHavingRequestsToBeGenerated(lDemandStreamKey);\n STDAIR_LOG_DEBUG (\"stillHavingRequestsToBeGenerated: \" << stillHavingRequestsToBeGenerated );\n if (stillHavingRequestsToBeGenerated) {\n stdair::BookingRequestPtr_T lNextRequest =\n trademgenService.generateNextRequest (lDemandStreamKey);\n assert (lNextRequest != NULL);\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Added request: \" << lNextRequest->describe());\n \n stdair::DateTime_T lNextRequestDateTime =\n lNextRequest->getRequestDateTime ();\n stdair::EventStruct lNextEventStruct (\"Request\",\n lNextRequestDateTime,\n lDemandStreamKey,\n lNextRequest);\n lEventQueue.eraseLastUsedEvent ();\n lEventQueue.addEvent (lNextEventStruct);\n \n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"After adding\");\n STDAIR_LOG_DEBUG (\"Queue size: \" << lEventQueue.getQueueSize ());\n STDAIR_LOG_DEBUG (\"Is queue done? \" << lEventQueue.isQueueDone ());\n \n }\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (std::endl);\n \n \/\/ Iterate\n ++i;\n }\n}\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid DemandGenerationTestSuite::simpleEventGeneration () {\n \/\/ TODO: Check that the generated events follow the law given as input\n CPPUNIT_ASSERT_NO_THROW ( simpleEventGenerationHelper(););\n}\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ void DemandGenerationTestSuite::errorCase () {\n\/\/ CPPUNIT_ASSERT (false);\n\/\/ }\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDemandGenerationTestSuite::DemandGenerationTestSuite () {\n _describeKey << \"Running test on RMOL Optimisation function\"; \n}\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ M A I N \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCPPUNIT_MAIN()\n\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \"libtorrent\/lsd.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::bind;\nusing namespace libtorrent;\n\nnamespace libtorrent\n{\n\t\/\/ defined in broadcast_socket.cpp\n\taddress guess_local_address(asio::io_service&);\n}\n\nlsd::lsd(io_service& ios, address const& listen_interface\n\t, peer_callback_t const& cb)\n\t: m_callback(cb)\n\t, m_retry_count(0)\n\t, m_socket(ios, udp::endpoint(address_v4::from_string(\"239.192.152.143\"), 6771)\n\t\t, bind(&lsd::on_announce, self(), _1, _2, _3))\n\t, m_broadcast_timer(ios)\n\t, m_disabled(false)\n{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log.open(\"lsd.log\", std::ios::in | std::ios::out | std::ios::trunc);\n#endif\n}\n\nlsd::~lsd() {}\n\nvoid lsd::announce(sha1_hash const& ih, int listen_port)\n{\n\tif (m_disabled) return;\n\n\tstd::stringstream btsearch;\n\tbtsearch << \"BT-SEARCH * HTTP\/1.1\\r\\n\"\n\t\t\"Host: 239.192.152.143:6771\\r\\n\"\n\t\t\"Port: \" << listen_port << \"\\r\\n\"\n\t\t\"Infohash: \" << ih << \"\\r\\n\"\n\t\t\"\\r\\n\\r\\n\";\n\tstd::string const& msg = btsearch.str();\n\n\tm_retry_count = 0;\n\tasio::error_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\tif (ec)\n\t{\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" ==> announce: ih: \" << ih << \" port: \" << listen_port << std::endl;\n#endif\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::resend_announce(asio::error_code const& e, std::string msg) try\n{\n\tif (e) return;\n\n\tasio::error_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\n\t++m_retry_count;\n\tif (m_retry_count >= 5)\n\t\treturn;\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count));\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\ncatch (std::exception&)\n{}\n\nvoid lsd::on_announce(udp::endpoint const& from, char* buffer\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\n\thttp_parser p;\n\n\tbool error = false;\n\tp.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)\n\t\t, error);\n\n\tif (!p.header_finished() || error)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: incomplete HTTP message\\n\";\n#endif\n\t\treturn;\n\t}\n\n\tif (p.method() != \"bt-search\")\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid HTTP method: \" << p.method() << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& port_str = p.header(\"port\");\n\tif (port_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing port\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& ih_str = p.header(\"infohash\");\n\tif (ih_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing infohash\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tsha1_hash ih(0);\n\tstd::istringstream ih_sstr(ih_str);\n\tih_sstr >> ih;\n\tint port = atoi(port_str.c_str());\n\n\tif (!ih.is_all_zeros() && port != 0)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << time_now_string()\n\t\t\t<< \" *** incoming local announce \" << from.address()\n\t\t\t<< \":\" << port << \" ih: \" << ih << std::endl;\n#endif\n\t\t\/\/ we got an announce, pass it on through the callback\n\t\ttry { m_callback(tcp::endpoint(from.address(), port), ih); }\n\t\tcatch (std::exception&) {}\n\t}\n}\n\nvoid lsd::close()\n{\n\tm_socket.close();\n\tm_broadcast_timer.cancel();\n\tm_disabled = true;\n\tm_callback.clear();\n}\n\nmade lsd build without exception support\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \"libtorrent\/lsd.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::bind;\nusing namespace libtorrent;\n\nnamespace libtorrent\n{\n\t\/\/ defined in broadcast_socket.cpp\n\taddress guess_local_address(asio::io_service&);\n}\n\nlsd::lsd(io_service& ios, address const& listen_interface\n\t, peer_callback_t const& cb)\n\t: m_callback(cb)\n\t, m_retry_count(0)\n\t, m_socket(ios, udp::endpoint(address_v4::from_string(\"239.192.152.143\"), 6771)\n\t\t, bind(&lsd::on_announce, self(), _1, _2, _3))\n\t, m_broadcast_timer(ios)\n\t, m_disabled(false)\n{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log.open(\"lsd.log\", std::ios::in | std::ios::out | std::ios::trunc);\n#endif\n}\n\nlsd::~lsd() {}\n\nvoid lsd::announce(sha1_hash const& ih, int listen_port)\n{\n\tif (m_disabled) return;\n\n\tstd::stringstream btsearch;\n\tbtsearch << \"BT-SEARCH * HTTP\/1.1\\r\\n\"\n\t\t\"Host: 239.192.152.143:6771\\r\\n\"\n\t\t\"Port: \" << listen_port << \"\\r\\n\"\n\t\t\"Infohash: \" << ih << \"\\r\\n\"\n\t\t\"\\r\\n\\r\\n\";\n\tstd::string const& msg = btsearch.str();\n\n\tm_retry_count = 0;\n\tasio::error_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\tif (ec)\n\t{\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" ==> announce: ih: \" << ih << \" port: \" << listen_port << std::endl;\n#endif\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::resend_announce(asio::error_code const& e, std::string msg)\n{\n\tif (e) return;\n\n\tasio::error_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\n\t++m_retry_count;\n\tif (m_retry_count >= 5)\n\t\treturn;\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::on_announce(udp::endpoint const& from, char* buffer\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\n\thttp_parser p;\n\n\tbool error = false;\n\tp.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)\n\t\t, error);\n\n\tif (!p.header_finished() || error)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: incomplete HTTP message\\n\";\n#endif\n\t\treturn;\n\t}\n\n\tif (p.method() != \"bt-search\")\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid HTTP method: \" << p.method() << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& port_str = p.header(\"port\");\n\tif (port_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing port\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& ih_str = p.header(\"infohash\");\n\tif (ih_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing infohash\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tsha1_hash ih(0);\n\tstd::istringstream ih_sstr(ih_str);\n\tih_sstr >> ih;\n\tint port = atoi(port_str.c_str());\n\n\tif (!ih.is_all_zeros() && port != 0)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << time_now_string()\n\t\t\t<< \" *** incoming local announce \" << from.address()\n\t\t\t<< \":\" << port << \" ih: \" << ih << std::endl;\n#endif\n\t\t\/\/ we got an announce, pass it on through the callback\n#ifndef BOOST_NO_EXCEPTIONS\n\t\ttry {\n#endif\n\t\t\tm_callback(tcp::endpoint(from.address(), port), ih);\n#ifndef BOOST_NO_EXCEPTIONS\n\t\t}\n\t\tcatch (std::exception&) {}\n#endif\n\t}\n}\n\nvoid lsd::close()\n{\n\tm_socket.close();\n\tasio::error_code ec;\n\tm_broadcast_timer.cancel(ec);\n\tm_disabled = true;\n\tm_callback.clear();\n}\n\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007-2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/lsd.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/random.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n#include \"libtorrent\/socket_io.hpp\" \/\/ for print_address\n\n#if defined TORRENT_ASIO_DEBUGGING\n#include \"libtorrent\/debug.hpp\"\n#endif\n\n#include \n#include \n#if BOOST_VERSION < 103500\n#include \n#include \n#else\n#include \n#include \n#endif\n#include \n#include \n#include \n\nusing namespace libtorrent;\n\nnamespace libtorrent\n{\n\t\/\/ defined in broadcast_socket.cpp\n\taddress guess_local_address(io_service&);\n}\n\nstatic error_code ec;\n\nlsd::lsd(io_service& ios, peer_callback_t const& cb\n#if defined TORRENT_LOGGING\n\t, log_callback_t const& log\n#endif\n\t)\n\t: m_callback(cb)\n\t, m_socket(udp::endpoint(address_v4::from_string(\"239.192.152.143\", ec), 6771))\n#if TORRENT_USE_IPV6\n\t, m_socket6(udp::endpoint(address_v6::from_string(\"ff15::efc0:988f\", ec), 6771))\n#endif\n#if defined TORRENT_LOGGING\n\t, m_log_cb(log)\n#endif\n\t, m_broadcast_timer(ios)\n\t, m_cookie(random())\n\t, m_disabled(false)\n#if TORRENT_USE_IPV6\n\t, m_disabled6(false)\n#endif\n{\n}\n\n#if defined TORRENT_LOGGING\nvoid lsd::debug_log(char const* fmt, ...) const\n{\n\tva_list v;\n\tva_start(v, fmt);\n\n\tchar buf[1024];\n\tvsnprintf(buf, sizeof(buf), fmt, v);\n\tva_end(v);\n\tm_log_cb(buf);\n}\n#endif\n\nvoid lsd::start(error_code& ec)\n{\n\tm_socket.open(boost::bind(&lsd::on_announce, self(), _1, _2, _3)\n\t\t, m_broadcast_timer.get_io_service(), ec);\n\tif (ec) return;\n\n#if TORRENT_USE_IPV6\n\tm_socket6.open(boost::bind(&lsd::on_announce, self(), _1, _2, _3)\n\t\t, m_broadcast_timer.get_io_service(), ec);\n#endif\n}\n\nlsd::~lsd() {}\n\nint render_lsd_packet(char* dst, int len, int listen_port\n\t, char const* info_hash_hex, int m_cookie, char const* host)\n{\n\treturn snprintf(dst, len,\n\t\t\"BT-SEARCH * HTTP\/1.1\\r\\n\"\n\t\t\"Host: %s:6771\\r\\n\"\n\t\t\"Port: %d\\r\\n\"\n\t\t\"Infohash: %s\\r\\n\"\n\t\t\"cookie: %x\\r\\n\"\n\t\t\"\\r\\n\\r\\n\", host, listen_port, info_hash_hex, m_cookie);\n}\n\nvoid lsd::announce(sha1_hash const& ih, int listen_port, bool broadcast)\n{\n\tannounce_impl(ih, listen_port, broadcast, 0);\n}\n\nvoid lsd::announce_impl(sha1_hash const& ih, int listen_port, bool broadcast\n\t, int retry_count)\n{\n#if TORRENT_USE_IPV6\n\tif (m_disabled && m_disabled6) return;\n#else\n\tif (m_disabled) return;\n#endif\n\n\tchar ih_hex[41];\n\tto_hex((char const*)&ih[0], 20, ih_hex);\n\tchar msg[200];\n\n#if defined TORRENT_LOGGING\n\tdebug_log(\"==> announce: ih: %s port: %u\\n\", ih_hex, listen_port);\n#endif\n\n\terror_code ec;\n\tif (!m_disabled)\n\t{\n\t\tint msg_len = render_lsd_packet(msg, sizeof(msg), listen_port, ih_hex\n\t\t\t, m_cookie, \"239.192.152.143\");\n\t\tm_socket.send(msg, msg_len, ec, broadcast ? broadcast_socket::broadcast : 0);\n\t\tif (ec)\n\t\t{\n\t\t\tm_disabled = true;\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"failed to send message: (%d) %s\", ec.value()\n\t\t\t\t, ec.message().c_str());\n#endif\n\t\t}\n\t}\n\n#if TORRENT_USE_IPV6\n\tif (!m_disabled6)\n\t{\n\t\tint msg_len = render_lsd_packet(msg, sizeof(msg), listen_port, ih_hex\n\t\t\t, m_cookie, \"[ff15::efc0:988f]\");\n\t\tm_socket6.send(msg, msg_len, ec, broadcast ? broadcast_socket::broadcast : 0);\n\t\tif (ec)\n\t\t{\n\t\t\tm_disabled6 = true;\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"failed to send message6: (%d) %s\", ec.value()\n\t\t\t\t, ec.message().c_str());\n#endif\n\t\t}\n\t}\n#endif\n\n\t++retry_count;\n\tif (retry_count >= 3) return;\n\n#if TORRENT_USE_IPV6\n\tif (m_disabled && m_disabled6) return;\n#else\n\tif (m_disabled) return;\n#endif\n\n#if defined TORRENT_ASIO_DEBUGGING\n\tadd_outstanding_async(\"lsd::resend_announce\");\n#endif\n\tm_broadcast_timer.expires_from_now(seconds(2 * retry_count), ec);\n\tm_broadcast_timer.async_wait(boost::bind(&lsd::resend_announce, self(), _1\n\t\t, ih, listen_port, retry_count));\n}\n\nvoid lsd::resend_announce(error_code const& e, sha1_hash const& info_hash\n\t, int listen_port, int retry_count)\n{\n#if defined TORRENT_ASIO_DEBUGGING\n\tcomplete_async(\"lsd::resend_announce\");\n#endif\n\tif (e) return;\n\n\tannounce_impl(info_hash, listen_port, false, retry_count);\n}\n\nvoid lsd::on_announce(udp::endpoint const& from, char* buffer\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\n\thttp_parser p;\n\n\tbool error = false;\n\tp.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)\n\t\t, error);\n\n\tif (!p.header_finished() || error)\n\t{\n#if defined TORRENT_LOGGING\n\t\tdebug_log(\"<== announce: incomplete HTTP message\\n\");\n#endif\n\t\treturn;\n\t}\n\n\tif (p.method() != \"bt-search\")\n\t{\n#if defined TORRENT_LOGGING\n\t\tdebug_log(\"<== announce: invalid HTTP method: %s\\n\", p.method().c_str());\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& port_str = p.header(\"port\");\n\tif (port_str.empty())\n\t{\n#if defined TORRENT_LOGGING\n\t\tdebug_log(\"<== announce: invalid BT-SEARCH, missing port\\n\");\n#endif\n\t\treturn;\n\t}\n\n\tint port = std::atoi(port_str.c_str());\n\n\ttypedef std::multimap headers_t;\n\theaders_t const& headers = p.headers();\n\n\theaders_t::const_iterator cookie_iter = headers.find(\"cookie\");\n\tif (cookie_iter != headers.end())\n\t{\n\t\t\/\/ we expect it to be hexadecimal\n\t\t\/\/ if it isn't, it's not our cookie anyway\n\t\tboost::int32_t cookie = strtol(cookie_iter->second.c_str(), NULL, 16);\n\t\tif (cookie == m_cookie)\n\t\t{\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"<== announce: ignoring packet (cookie matched our own): %x == %x\\n\"\n\t\t\t\t, cookie, m_cookie);\n#endif\n\t\t\treturn;\n\t\t}\n\t}\n\n\tstd::pair ihs\n\t\t= headers.equal_range(\"infohash\");\n\n\tfor (headers_t::const_iterator i = ihs.first; i != ihs.second; ++i)\n\t{\n\t\tstd::string const& ih_str = i->second;\n\t\tif (ih_str.size() != 40)\n\t\t{\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"<== announce: invalid BT-SEARCH, invalid infohash: %s\\n\"\n\t\t\t\t, ih_str.c_str());\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\tsha1_hash ih(0);\n\t\tfrom_hex(ih_str.c_str(), 40, (char*)&ih[0]);\n\n\t\tif (!ih.is_all_zeros() && port != 0)\n\t\t{\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"*** incoming local announce %s:%d ih: %s\\n\"\n\t\t\t\t, print_address(from.address()).c_str()\n\t\t\t\t, port, ih_str.c_str());\n#endif\n\t\t\t\/\/ we got an announce, pass it on through the callback\n\t\t\tTORRENT_TRY {\n\t\t\t\tm_callback(tcp::endpoint(from.address(), port), ih);\n\t\t\t} TORRENT_CATCH(std::exception&) {}\n\t\t}\n\t}\n}\n\nvoid lsd::close()\n{\n\tm_socket.close();\n#if TORRENT_USE_IPV6\n\tm_socket6.close();\n#endif\n\terror_code ec;\n\tm_broadcast_timer.cancel(ec);\n\tm_disabled = true;\n#if TORRENT_USE_IPV6\n\tm_disabled6 = true;\n#endif\n\tm_callback.clear();\n}\n\nclean up lsd logging\/*\n\nCopyright (c) 2007-2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/lsd.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/random.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n#include \"libtorrent\/socket_io.hpp\" \/\/ for print_address\n\n#if defined TORRENT_ASIO_DEBUGGING\n#include \"libtorrent\/debug.hpp\"\n#endif\n\n#include \n#include \n#if BOOST_VERSION < 103500\n#include \n#include \n#else\n#include \n#include \n#endif\n#include \n#include \n#include \n\nusing namespace libtorrent;\n\nnamespace libtorrent\n{\n\t\/\/ defined in broadcast_socket.cpp\n\taddress guess_local_address(io_service&);\n}\n\nstatic error_code ec;\n\nlsd::lsd(io_service& ios, peer_callback_t const& cb\n#if defined TORRENT_LOGGING\n\t, log_callback_t const& log\n#endif\n\t)\n\t: m_callback(cb)\n\t, m_socket(udp::endpoint(address_v4::from_string(\"239.192.152.143\", ec), 6771))\n#if TORRENT_USE_IPV6\n\t, m_socket6(udp::endpoint(address_v6::from_string(\"ff15::efc0:988f\", ec), 6771))\n#endif\n#if defined TORRENT_LOGGING\n\t, m_log_cb(log)\n#endif\n\t, m_broadcast_timer(ios)\n\t, m_cookie(random())\n\t, m_disabled(false)\n#if TORRENT_USE_IPV6\n\t, m_disabled6(false)\n#endif\n{\n}\n\n#if defined TORRENT_LOGGING\nvoid lsd::debug_log(char const* fmt, ...) const\n{\n\tva_list v;\n\tva_start(v, fmt);\n\n\tchar buf[1024];\n\tvsnprintf(buf, sizeof(buf), fmt, v);\n\tva_end(v);\n\tm_log_cb(buf);\n}\n#endif\n\nvoid lsd::start(error_code& ec)\n{\n\tm_socket.open(boost::bind(&lsd::on_announce, self(), _1, _2, _3)\n\t\t, m_broadcast_timer.get_io_service(), ec);\n\tif (ec) return;\n\n#if TORRENT_USE_IPV6\n\tm_socket6.open(boost::bind(&lsd::on_announce, self(), _1, _2, _3)\n\t\t, m_broadcast_timer.get_io_service(), ec);\n#endif\n}\n\nlsd::~lsd() {}\n\nint render_lsd_packet(char* dst, int len, int listen_port\n\t, char const* info_hash_hex, int m_cookie, char const* host)\n{\n\treturn snprintf(dst, len,\n\t\t\"BT-SEARCH * HTTP\/1.1\\r\\n\"\n\t\t\"Host: %s:6771\\r\\n\"\n\t\t\"Port: %d\\r\\n\"\n\t\t\"Infohash: %s\\r\\n\"\n\t\t\"cookie: %x\\r\\n\"\n\t\t\"\\r\\n\\r\\n\", host, listen_port, info_hash_hex, m_cookie);\n}\n\nvoid lsd::announce(sha1_hash const& ih, int listen_port, bool broadcast)\n{\n\tannounce_impl(ih, listen_port, broadcast, 0);\n}\n\nvoid lsd::announce_impl(sha1_hash const& ih, int listen_port, bool broadcast\n\t, int retry_count)\n{\n#if TORRENT_USE_IPV6\n\tif (m_disabled && m_disabled6) return;\n#else\n\tif (m_disabled) return;\n#endif\n\n\tchar ih_hex[41];\n\tto_hex((char const*)&ih[0], 20, ih_hex);\n\tchar msg[200];\n\n#if defined TORRENT_LOGGING\n\tdebug_log(\"==> LSD: ih: %s port: %u\\n\", ih_hex, listen_port);\n#endif\n\n\terror_code ec;\n\tif (!m_disabled)\n\t{\n\t\tint msg_len = render_lsd_packet(msg, sizeof(msg), listen_port, ih_hex\n\t\t\t, m_cookie, \"239.192.152.143\");\n\t\tm_socket.send(msg, msg_len, ec, broadcast ? broadcast_socket::broadcast : 0);\n\t\tif (ec)\n\t\t{\n\t\t\tm_disabled = true;\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"*** LSD: failed to send message: (%d) %s\", ec.value()\n\t\t\t\t, ec.message().c_str());\n#endif\n\t\t}\n\t}\n\n#if TORRENT_USE_IPV6\n\tif (!m_disabled6)\n\t{\n\t\tint msg_len = render_lsd_packet(msg, sizeof(msg), listen_port, ih_hex\n\t\t\t, m_cookie, \"[ff15::efc0:988f]\");\n\t\tm_socket6.send(msg, msg_len, ec, broadcast ? broadcast_socket::broadcast : 0);\n\t\tif (ec)\n\t\t{\n\t\t\tm_disabled6 = true;\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"*** LSD: failed to send message6: (%d) %s\", ec.value()\n\t\t\t\t, ec.message().c_str());\n#endif\n\t\t}\n\t}\n#endif\n\n\t++retry_count;\n\tif (retry_count >= 3) return;\n\n#if TORRENT_USE_IPV6\n\tif (m_disabled && m_disabled6) return;\n#else\n\tif (m_disabled) return;\n#endif\n\n#if defined TORRENT_ASIO_DEBUGGING\n\tadd_outstanding_async(\"lsd::resend_announce\");\n#endif\n\tm_broadcast_timer.expires_from_now(seconds(2 * retry_count), ec);\n\tm_broadcast_timer.async_wait(boost::bind(&lsd::resend_announce, self(), _1\n\t\t, ih, listen_port, retry_count));\n}\n\nvoid lsd::resend_announce(error_code const& e, sha1_hash const& info_hash\n\t, int listen_port, int retry_count)\n{\n#if defined TORRENT_ASIO_DEBUGGING\n\tcomplete_async(\"lsd::resend_announce\");\n#endif\n\tif (e) return;\n\n\tannounce_impl(info_hash, listen_port, false, retry_count);\n}\n\nvoid lsd::on_announce(udp::endpoint const& from, char* buffer\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\n\thttp_parser p;\n\n\tbool error = false;\n\tp.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)\n\t\t, error);\n\n\tif (!p.header_finished() || error)\n\t{\n#if defined TORRENT_LOGGING\n\t\tdebug_log(\"<== LSD: incomplete HTTP message\");\n#endif\n\t\treturn;\n\t}\n\n\tif (p.method() != \"bt-search\")\n\t{\n#if defined TORRENT_LOGGING\n\t\tdebug_log(\"<== LSD: invalid HTTP method: %s\", p.method().c_str());\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& port_str = p.header(\"port\");\n\tif (port_str.empty())\n\t{\n#if defined TORRENT_LOGGING\n\t\tdebug_log(\"<== LSD: invalid BT-SEARCH, missing port\");\n#endif\n\t\treturn;\n\t}\n\n\tint port = std::atoi(port_str.c_str());\n\n\ttypedef std::multimap headers_t;\n\theaders_t const& headers = p.headers();\n\n\theaders_t::const_iterator cookie_iter = headers.find(\"cookie\");\n\tif (cookie_iter != headers.end())\n\t{\n\t\t\/\/ we expect it to be hexadecimal\n\t\t\/\/ if it isn't, it's not our cookie anyway\n\t\tboost::int32_t cookie = strtol(cookie_iter->second.c_str(), NULL, 16);\n\t\tif (cookie == m_cookie)\n\t\t{\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"<== LSD: ignoring packet (cookie matched our own): %x == %x\"\n\t\t\t\t, cookie, m_cookie);\n#endif\n\t\t\treturn;\n\t\t}\n\t}\n\n\tstd::pair ihs\n\t\t= headers.equal_range(\"infohash\");\n\n\tfor (headers_t::const_iterator i = ihs.first; i != ihs.second; ++i)\n\t{\n\t\tstd::string const& ih_str = i->second;\n\t\tif (ih_str.size() != 40)\n\t\t{\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"<== LSD: invalid BT-SEARCH, invalid infohash: %s\"\n\t\t\t\t, ih_str.c_str());\n#endif\n\t\t\tcontinue;\n\t\t}\n\n\t\tsha1_hash ih(0);\n\t\tfrom_hex(ih_str.c_str(), 40, (char*)&ih[0]);\n\n\t\tif (!ih.is_all_zeros() && port != 0)\n\t\t{\n#if defined TORRENT_LOGGING\n\t\t\tdebug_log(\"<== LSD: %s:%d ih: %s\"\n\t\t\t\t, print_address(from.address()).c_str()\n\t\t\t\t, port, ih_str.c_str());\n#endif\n\t\t\t\/\/ we got an announce, pass it on through the callback\n\t\t\tTORRENT_TRY {\n\t\t\t\tm_callback(tcp::endpoint(from.address(), port), ih);\n\t\t\t} TORRENT_CATCH(std::exception&) {}\n\t\t}\n\t}\n}\n\nvoid lsd::close()\n{\n\tm_socket.close();\n#if TORRENT_USE_IPV6\n\tm_socket6.close();\n#endif\n\terror_code ec;\n\tm_broadcast_timer.cancel(ec);\n\tm_disabled = true;\n#if TORRENT_USE_IPV6\n\tm_disabled6 = true;\n#endif\n\tm_callback.clear();\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\n\/\/\n\/\/ Configuration include.\n\/\/\/\/ Included at first position before any other ones.\n#include \"ConfigureMonteverdi.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n#include \n#include \n\n#define USE_SPLASH_SCREEN ( ( !defined( OTB_DEBUG ) && 0 ) || 0 )\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\/\/ #include \"itksys\/SystemTools.hxx\"\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdApplication.h\"\n#include \"mvdMainWindow.h\"\n\nenum ERROR_CODE\n{\n ERROR_CODE_I18N = -1,\n ERROR_CODE_CACHE_DIR = -2,\n ERROR_CODE_DATABASE = -3,\n ERROR_CODE_GL_VERSION = -4,\n ERROR_CODE_USAGE = -5,\n};\n\n\nstruct Flags\n{\n Flags() :\n loadOTBApplications( false ),\n forceNoGLSL( false ),\n forceNoOverviews( false )\n {\n }\n\n bool loadOTBApplications: 1;\n bool forceNoGLSL: 1;\n bool forceNoOverviews: 1;\n};\n\n\n\/*****************************************************************************\/\n\/* FUNCTIONS DECLARATION *\/\n\/*****************************************************************************\/\n\n\n\/*****************************************************************************\/\n\/* MAIN *\/\n\/*****************************************************************************\/\nint\nmain( int argc, char* argv[] )\n{\n QApplication qtApp( argc, argv );\n Flags flags;\n\n \/\/\n \/\/ 0. Splash-screen.\n#if USE_SPLASH_SCREEN\n QPixmap pixmap(QLatin1String( \":\/images\/application_splash\" ));\n QSplashScreen splash(pixmap);\n splash.show();\n qtApp.processEvents();\/\/This is used to accept a click on the screen so that user can cancel the screen\n#endif\n\n \/\/\n \/\/ 0bis. Parse pre-initialization command-line arguments.\n QStringList args( qtApp.arguments() );\n {\n for( QStringList::iterator it( args.begin() );\n it!=args.end(); )\n if( it->compare( \"-h\" )==0 ||\n\tit->compare( \"--help\" )==0 )\n {\n std::cout\n\t<< mvd::ToLocalStdString(\n\t QCoreApplication::translate(\n\t PROJECT_NAME,\n\t \"Usage: %1 [-h|--help] [-a|--applications] [...]\\n\"\n\t \" -a, --applications load OTB-applications from OTB_APPLICATIONS_PATH.\"\n\t \" -h, --help display this help message.\\n\"\n\t \" -g, --no-glsl force OpenGL 1.x compatible rendering.\"\n\t \" -o, --no-overviews ignore build GDAL overviews step.\"\n#if 0\n\t \" -O, --force-overviews force build GDAL overviews step.\"\n#endif\n\t )\n\t .arg( QFileInfo( argv[ 0 ] ).baseName() )\n\t)\n\t<< std::endl;\n\n return ERROR_CODE_USAGE;\n }\n\n else if( it->compare( \"-a\" )==0 ||\n\t it->compare( \"--applications\" )==0 )\n {\n flags.loadOTBApplications = true;\n\n it = args.erase( it );\n }\n\n else if(it->compare( \"-o\" )==0 ||\n\t it->compare( \"--no-overviews\" )==0 )\n {\n flags.forceNoOverviews = true;\n\n it = args.erase( it );\n }\n\n else if(it->compare( \"-g\" )==0 ||\n\t it->compare( \"--no-glsl\" )==0 )\n {\n flags.forceNoGLSL = true;\n\n it = args.erase( it );\n }\n else\n ++ it;\n }\n\n \/\/\n \/\/ 1. Initialize application and sync settings.\n \/\/\n \/\/ Coverity-14835\n \/\/ {\n mvd::Application * application = NULL;\n\n try\n {\n application = new mvd::Application( &qtApp );\n assert( application!=NULL );\n\n application->Initialize();\n }\n catch( std::exception & exc )\n {\n QMessageBox::StandardButton button =\n QMessageBox::question(\n\tNULL,\n\tQCoreApplication::translate(\n\t PROJECT_NAME,\n\t \"Question!\"\n\t),\n\tQCoreApplication::translate(\n\t PROJECT_NAME,\n\t \"The following exception has been caught while initializing the software:\\n\\n\"\n\t \"%1\\n\\n\"\n\t \"The application may not function as expected. Do you want to continue?\"\n\t)\n\t.arg( exc.what() ),\n\tQMessageBox::Yes | QMessageBox::No,\n\tQMessageBox::Yes\n );\n\n if( button==QMessageBox::No )\n return ERROR_CODE_I18N;\n }\n \/\/ }\n \/\/ Coverity-14835\n\n \/\/\n \/\/ 2. Initialize main-window (UI).\n mvd::MainWindow mainWindow;\n mainWindow.Initialize();\n\n \/\/\n \/\/ 3. Show window.\n mainWindow.show();\n\n#if USE_SPLASH_SCREEN\n splash.finish( &mainWindow );\n#endif \/\/ USE_SPLASH_SCREEN\n\n \/\/\n \/\/ 4. Check OpenGL capabilities\n if( !mainWindow.CheckGLCapabilities( flags.forceNoGLSL ) )\n return ERROR_CODE_GL_VERSION;\n\n \/\/\n \/\/ 5. Load OTB-applications.\n if( flags.loadOTBApplications )\n#if USE_OTB_APPS\n mainWindow.SetupOTBApplications();\n#else \/\/ USE_OTB_APPS\n qWarning() << \"OTB-applications support is not included in this build.\";\n#endif \/\/ USE_OTB_APPS\n\n \/\/\n \/\/ 6. Load command-line filenames.\n args.pop_front();\n\n mainWindow.ImportImages( args, !flags.forceNoOverviews );\n\n \/\/\n \/\/ 6. Let's go: run the application and return exit code.\n int result = QCoreApplication::instance()->exec();\n\n \/\/ Coverity-14835\n \/\/ {\n delete application;\n application = NULL;\n \/\/ }\n \/\/ Coverity-14835\n\n return result;\n}\n\n\n\/*****************************************************************************\/\n\/* FUNCTIONS IMPLEMENTATION *\/\n\/*****************************************************************************\/\nAdded -t|--txt-file command-line option to Monteverdi.\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\n\/\/\n\/\/ Configuration include.\n\/\/\/\/ Included at first position before any other ones.\n#include \"ConfigureMonteverdi.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n#include \n#include \n#include \n#include \n\n#define USE_SPLASH_SCREEN ( ( !defined( OTB_DEBUG ) && 0 ) || 0 )\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\/\/ #include \"itksys\/SystemTools.hxx\"\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdAlgorithm.h\"\n#include \"mvdApplication.h\"\n#include \"mvdMainWindow.h\"\n\nenum ERROR_CODE\n{\n ERROR_CODE_I18N = -1,\n ERROR_CODE_CACHE_DIR = -2,\n ERROR_CODE_DATABASE = -3,\n ERROR_CODE_GL_VERSION = -4,\n ERROR_CODE_USAGE = -5,\n};\n\n\nstruct Flags\n{\n Flags() :\n loadOTBApplications( false ),\n forceNoGLSL( false ),\n forceNoOverviews( false )\n {\n }\n\n bool loadOTBApplications: 1;\n bool forceNoGLSL: 1;\n bool forceNoOverviews: 1;\n};\n\n\n\/*****************************************************************************\/\n\/* FUNCTIONS DECLARATION *\/\n\/*****************************************************************************\/\nvoid\nDisplayUsage( const char * );\n\nvoid\nAppendFromTextFile( QStringList &, const QString & );\n\n\/*****************************************************************************\/\n\/* MAIN *\/\n\/*****************************************************************************\/\nint\nmain( int argc, char * argv[] )\n{\n QApplication qtApp( argc, argv );\n\n \/\/\n \/\/ 0. Splash-screen.\n#if USE_SPLASH_SCREEN\n QPixmap pixmap( QLatin1String( \":\/images\/application_splash\" ) );\n QSplashScreen splash( pixmap );\n splash.show();\n qtApp.processEvents();\/\/This is used to accept a click on the screen so that user can cancel the screen\n#endif\n\n \/\/\n \/\/ 0bis. Parse pre-initialization command-line arguments.\n QStringList args( qtApp.arguments() );\n Flags flags;\n {\n QStringList filenames;\n\n for( QStringList::iterator it( args.begin() );\n it!=args.end(); )\n if( it->compare( \"-h\" )==0 ||\n\tit->compare( \"--help\" )==0 )\n {\n DisplayUsage( argv[ 0 ] );\n\n return ERROR_CODE_USAGE;\n }\n\n else if( it->compare( \"-a\" )==0 ||\n\t it->compare( \"--applications\" )==0 )\n {\n flags.loadOTBApplications = true;\n\n it = args.erase( it );\n }\n\n else if(it->compare( \"-g\" )==0 ||\n\t it->compare( \"--no-glsl\" )==0 )\n {\n flags.forceNoGLSL = true;\n\n it = args.erase( it );\n }\n\n else if(it->compare( \"-o\" )==0 ||\n\t it->compare( \"--no-overviews\" )==0 )\n {\n flags.forceNoOverviews = true;\n\n it = args.erase( it );\n }\n\n else if(it->compare( \"-t\" )==0 ||\n\t it->compare( \"--txt-file\" )==0 )\n {\n it = args.erase( it );\n\n if( it==args.end() ||\n\t it->startsWith( '-' ) )\n\t{\n\tDisplayUsage( argv[ 0 ] );\n\n\treturn ERROR_CODE_USAGE;\n\t}\n\n AppendFromTextFile( filenames, *it );\n\n it = args.erase( it );\n }\n\n else\n ++ it;\n\n args << filenames;\n }\n\n \/\/\n \/\/ 1. Initialize application and sync settings.\n \/\/\n \/\/ Coverity-14835\n \/\/ {\n mvd::Application * application = NULL;\n\n try\n {\n application = new mvd::Application( &qtApp );\n assert( application!=NULL );\n\n application->Initialize();\n }\n catch( std::exception & exc )\n {\n QMessageBox::StandardButton button =\n QMessageBox::question(\n\tNULL,\n\tQCoreApplication::translate(\n\t PROJECT_NAME,\n\t \"Question!\"\n\t),\n\tQCoreApplication::translate(\n\t PROJECT_NAME,\n\t \"The following exception has been caught while initializing the software:\\n\\n\"\n\t \"%1\\n\\n\"\n\t \"The application may not function as expected. Do you want to continue?\"\n\t)\n\t.arg( exc.what() ),\n\tQMessageBox::Yes | QMessageBox::No,\n\tQMessageBox::Yes\n );\n\n if( button==QMessageBox::No )\n return ERROR_CODE_I18N;\n }\n \/\/ }\n \/\/ Coverity-14835\n\n \/\/\n \/\/ 2. Initialize main-window (UI).\n mvd::MainWindow mainWindow;\n mainWindow.Initialize();\n\n \/\/\n \/\/ 3. Show window.\n mainWindow.show();\n\n#if USE_SPLASH_SCREEN\n splash.finish( &mainWindow );\n#endif \/\/ USE_SPLASH_SCREEN\n\n \/\/\n \/\/ 4. Check OpenGL capabilities\n if( !mainWindow.CheckGLCapabilities( flags.forceNoGLSL ) )\n return ERROR_CODE_GL_VERSION;\n\n \/\/\n \/\/ 5. Load OTB-applications.\n if( flags.loadOTBApplications )\n#if USE_OTB_APPS\n mainWindow.SetupOTBApplications();\n#else \/\/ USE_OTB_APPS\n qWarning() << \"OTB-applications support is not included in this build.\";\n#endif \/\/ USE_OTB_APPS\n\n \/\/\n \/\/ 6. Load command-line filenames.\n args.pop_front();\n\n mainWindow.ImportImages( args, !flags.forceNoOverviews );\n\n \/\/\n \/\/ 6. Let's go: run the application and return exit code.\n int result = QCoreApplication::instance()->exec();\n\n \/\/ Coverity-14835\n \/\/ {\n delete application;\n application = NULL;\n \/\/ }\n \/\/ Coverity-14835\n\n return result;\n}\n\n\n\/*****************************************************************************\/\n\/* FUNCTIONS IMPLEMENTATION *\/\n\/*****************************************************************************\/\nvoid\nDisplayUsage( const char * argv0 )\n{\n std::cout\n << mvd::ToLocalStdString(\n QCoreApplication::translate(\n\tPROJECT_NAME,\n\t\"Usage: %1 \"\n\t\"[-h|--help] \"\n\t\"[-a|--applications] \"\n\t\"[-g|--no-glsl] \"\n\t\"[-o|--no-overviews] \"\n\t\"[-t|--txt-file ] \"\n\t\"[...]\\n\"\n\t\" -a, --applications load OTB-applications from OTB_APPLICATIONS_PATH.\\n\"\n#if 0\n\t\" -f, --file load Monteverdi project file.\\n\"\n#endif\n\t\" -h, --help display this help message.\\n\"\n\t\" -g, --no-glsl force OpenGL 1.x compatible rendering.\\n\"\n\t\" -o, --no-overviews ignore build GDAL overviews step.\\n\"\n#if 0\n\t\" -O, --force-overviews force build GDAL overviews step.\\n\"\n#endif\n\t\" -t, --txt-file read layer filenames from text file.\\n\"\n#if 0\n\t\" -c, --csv-file read layer filenames & settings from CSV file.\\n\"\n\t\" -x, --xml-file read layer filenames & settings from XML file.\\n\"\n#endif\n )\n .arg( QFileInfo( argv0 ).baseName() )\n )\n << std::endl;\n}\n\n\/*****************************************************************************\/\nvoid\nAppendFromTextFile( QStringList & strings,\n\t\t const QString & filename )\n{\n QFile file( filename );\n\n if( !file.open( QFile::ReadOnly | QFile::Text ) )\n throw mvd::SystemError(\n mvd::ToStdString(\n\tQCoreApplication::translate( \"mvd::\", \"Failed to open '%1'\" )\n\t.arg( filename )\n )\n );\n\n QTextStream is( &file );\n\n while( !is.atEnd() )\n {\n QString line( is.readLine() );\n\n if( !line.isNull() )\n strings << line;\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n\nusing namespace llvm;\nusing namespace clang::tooling;\nusing std::string;\n\nstatic cl::OptionCategory OptionsCategory(\"Options\");\n\nint main(int argc, const char **argv) {\n CommonOptionsParser OptionsParser(argc, argv, OptionsCategory);\n for(auto s : OptionsParser.getSourcePathList()) {\n std::cout << s << std::endl;\n }\n return 0;\n}\nImplement action that prints file names#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace llvm;\nusing namespace clang;\nusing namespace clang::tooling;\nusing std::string;\n\nclass MyFrontendAction : public ASTFrontendAction {\n public:\n MyFrontendAction() {}\n\n std::unique_ptr CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {\n std::cout << InFile.str() << std::endl;\n return nullptr;\n }\n};\n\nstatic cl::OptionCategory OptionsCategory(\"skel options\");\n\nint main(int argc, const char **argv) {\n CommonOptionsParser op(argc, argv, OptionsCategory);\n ClangTool Tool(op.getCompilations(), op.getSourcePathList());\n return Tool.run(newFrontendActionFactory().get());\n}\n<|endoftext|>"} {"text":"#include \n#include \"vast.h\"\n\nint main(int argc, char *argv[])\n{\n auto cfg = vast::configuration::parse(argc, argv);\n if (! cfg)\n {\n std::cerr << cfg.error() << \", try -h or -z\" << std::endl;\n return 1;\n }\n\n if (argc < 2 || cfg->check(\"help\") || cfg->check(\"advanced\"))\n {\n cfg->usage(std::cerr, cfg->check(\"advanced\"));\n return 0;\n }\n else if (cfg->check(\"version\"))\n {\n std::cout << VAST_VERSION << std::endl;\n return 0;\n }\n\n vast::announce_builtin_types();\n\n auto initialized = vast::logger::instance()->init(\n *vast::logger::parse_level(*cfg->get(\"log.console\")),\n *vast::logger::parse_level(*cfg->get(\"log.file\")),\n ! cfg->check(\"log.no-colors\"),\n cfg->check(\"log.function-names\"),\n vast::path{*cfg->get(\"directory\")}.complete() \/ \"log\");\n\n if (! initialized)\n {\n std::cerr << \"failed to initialize logger\" << std::endl;\n return 1;\n }\n\n VAST_VERBOSE(\" _ _____ __________\");\n VAST_VERBOSE(\"| | \/ \/ _ | \/ __\/_ __\/\");\n VAST_VERBOSE(\"| |\/ \/ __ |_\\\\ \\\\ \/ \/ \");\n VAST_VERBOSE(\"|___\/_\/ |_\/___\/ \/_\/ \" << VAST_VERSION);\n VAST_VERBOSE(\"\");\n\n auto threads = std::thread::hardware_concurrency();\n if (auto t = cfg->as(\"caf.threads\"))\n threads = *t;\n\n auto throughput = std::numeric_limits::max();\n if (auto t = cfg->as(\"caf.throughput\"))\n throughput = *t;\n\n caf::set_scheduler<>(threads, throughput);\n VAST_VERBOSE(\"set scheduler threads to\", threads);\n VAST_VERBOSE(\"set scheduler maximum throughput to\",\n (throughput == std::numeric_limits::max()\n ? \"unlimited\" : std::to_string(throughput)));\n\n auto program = caf::spawn(std::move(*cfg));\n caf::anon_send(program, caf::atom(\"run\"));\n caf::await_all_actors_done();\n caf::shutdown();\n\n vast::cleanup();\n\n return 0;\n}\nReturn main() with exit-reason-specific value.#include \n#include \"vast.h\"\n\nint main(int argc, char *argv[])\n{\n auto cfg = vast::configuration::parse(argc, argv);\n if (! cfg)\n {\n std::cerr << cfg.error() << \", try -h or -z\" << std::endl;\n return 1;\n }\n\n if (argc < 2 || cfg->check(\"help\") || cfg->check(\"advanced\"))\n {\n cfg->usage(std::cerr, cfg->check(\"advanced\"));\n return 0;\n }\n else if (cfg->check(\"version\"))\n {\n std::cout << VAST_VERSION << std::endl;\n return 0;\n }\n\n vast::announce_builtin_types();\n\n auto initialized = vast::logger::instance()->init(\n *vast::logger::parse_level(*cfg->get(\"log.console\")),\n *vast::logger::parse_level(*cfg->get(\"log.file\")),\n ! cfg->check(\"log.no-colors\"),\n cfg->check(\"log.function-names\"),\n vast::path{*cfg->get(\"directory\")}.complete() \/ \"log\");\n\n if (! initialized)\n {\n std::cerr << \"failed to initialize logger\" << std::endl;\n return 1;\n }\n\n VAST_VERBOSE(\" _ _____ __________\");\n VAST_VERBOSE(\"| | \/ \/ _ | \/ __\/_ __\/\");\n VAST_VERBOSE(\"| |\/ \/ __ |_\\\\ \\\\ \/ \/ \");\n VAST_VERBOSE(\"|___\/_\/ |_\/___\/ \/_\/ \" << VAST_VERSION);\n VAST_VERBOSE(\"\");\n\n auto threads = std::thread::hardware_concurrency();\n if (auto t = cfg->as(\"caf.threads\"))\n threads = *t;\n\n auto throughput = std::numeric_limits::max();\n if (auto t = cfg->as(\"caf.throughput\"))\n throughput = *t;\n\n caf::set_scheduler<>(threads, throughput);\n VAST_VERBOSE(\"set scheduler threads to\", threads);\n VAST_VERBOSE(\"set scheduler maximum throughput to\",\n (throughput == std::numeric_limits::max()\n ? \"unlimited\" : std::to_string(throughput)));\n\n auto program = caf::spawn(std::move(*cfg));\n caf::anon_send(program, caf::atom(\"run\"));\n caf::await_all_actors_done();\n caf::shutdown();\n vast::cleanup();\n\n auto er = program->exit_reason();\n if (er == vast::exit::done || er == vast::exit::stop)\n return 0;\n else if (er == vast::exit::error)\n return 1;\n else if (er == vast::exit::kill)\n return 2;\n else\n return 255;\n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2017 Robert Ou \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct RecoverReduceCorePass : public Pass {\n enum GateType {\n And,\n Or,\n Xor\n };\n\n RecoverReduceCorePass() : Pass(\"recover_reduce_core\", \"converts gate chains into $reduce_*\") { }\n virtual void help()\n {\n \/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n log(\"\\n\");\n log(\" recover_reduce_core\\n\");\n log(\"\\n\");\n log(\"converts gate chains into $reduce_*\\n\");\n log(\"\\n\");\n log(\"This performs the core step of the recover_reduce command. This step recognizes\\n\");\n log(\"chains of gates found by the previous steps and converts these chains into one\\n\");\n log(\"logical cell.\\n\");\n log(\"\\n\");\n }\n virtual void execute(std::vector args, RTLIL::Design *design)\n {\n (void)args;\n\n for (auto module : design->selected_modules())\n {\n SigMap sigmap(module);\n\n \/\/ Index all of the nets in the module\n dict sig_to_driver;\n dict> sig_to_sink;\n for (auto cell : module->selected_cells())\n {\n for (auto &conn : cell->connections())\n {\n if (cell->output(conn.first))\n for (auto bit : sigmap(conn.second))\n sig_to_driver[bit] = cell;\n\n if (cell->input(conn.first))\n {\n for (auto bit : sigmap(conn.second))\n {\n if (sig_to_sink.count(bit) == 0)\n sig_to_sink[bit] = pool();\n sig_to_sink[bit].insert(cell);\n }\n }\n }\n }\n\n \/\/ Need to check if any wires connect to module ports\n pool port_sigs;\n for (auto wire : module->selected_wires())\n if (wire->port_input || wire->port_output)\n for (auto bit : sigmap(wire))\n port_sigs.insert(bit);\n\n \/\/ Actual logic starts here\n pool consumed_cells;\n for (auto cell : module->selected_cells())\n {\n if (consumed_cells.count(cell))\n continue;\n\n GateType gt;\n\n if (cell->type == \"$_AND_\")\n gt = GateType::And;\n else if (cell->type == \"$_OR_\")\n gt = GateType::Or;\n else if (cell->type == \"$_XOR_\")\n gt = GateType::Xor;\n else\n continue;\n\n log(\"Working on cell %s...\\n\", cell->name.c_str());\n\n \/\/ Go all the way to the sink\n Cell* head_cell = cell;\n Cell* x = cell;\n while (true)\n {\n if (!((x->type == \"$_AND_\" && gt == GateType::And) ||\n (x->type == \"$_OR_\" && gt == GateType::Or) ||\n (x->type == \"$_XOR_\" && gt == GateType::Xor)))\n break;\n\n head_cell = x;\n\n auto y = sigmap(x->getPort(\"\\\\Y\"));\n log_assert(y.size() == 1);\n\n \/\/ Should only continue if there is one fanout back into a cell (not to a port)\n if (sig_to_sink[y[0]].size() != 1)\n break;\n\n x = *sig_to_sink[y[0]].begin();\n }\n\n log(\" Head cell is %s\\n\", head_cell->name.c_str());\n\n pool cur_supercell;\n std::deque bfs_queue = {head_cell};\n while (bfs_queue.size())\n {\n Cell* x = bfs_queue.front();\n bfs_queue.pop_front();\n\n cur_supercell.insert(x);\n\n auto a = sigmap(x->getPort(\"\\\\A\"));\n log_assert(a.size() == 1);\n \/\/ Must have only one sink\n \/\/ XXX: Check that it is indeed this node?\n if (sig_to_sink[a[0]].size() + port_sigs.count(a[0]) == 1)\n {\n Cell* cell_a = sig_to_driver[a[0]];\n if (((cell_a->type == \"$_AND_\" && gt == GateType::And) ||\n (cell_a->type == \"$_OR_\" && gt == GateType::Or) ||\n (cell_a->type == \"$_XOR_\" && gt == GateType::Xor)))\n {\n \/\/ The cell here is the correct type, and it's definitely driving only\n \/\/ this current cell.\n bfs_queue.push_back(cell_a);\n }\n }\n\n auto b = sigmap(x->getPort(\"\\\\B\"));\n log_assert(b.size() == 1);\n \/\/ Must have only one sink\n \/\/ XXX: Check that it is indeed this node?\n if (sig_to_sink[b[0]].size() + port_sigs.count(b[0]) == 1)\n {\n Cell* cell_b = sig_to_driver[b[0]];\n if (((cell_b->type == \"$_AND_\" && gt == GateType::And) ||\n (cell_b->type == \"$_OR_\" && gt == GateType::Or) ||\n (cell_b->type == \"$_XOR_\" && gt == GateType::Xor)))\n {\n \/\/ The cell here is the correct type, and it's definitely driving only\n \/\/ this current cell.\n bfs_queue.push_back(cell_b);\n }\n }\n }\n\n log(\" Cells:\\n\");\n for (auto x : cur_supercell)\n log(\" %s\\n\", x->name.c_str());\n\n if (cur_supercell.size() > 1)\n {\n \/\/ Worth it to create reduce cell\n log(\" Creating $reduce_* cell!\\n\");\n\n pool input_pool;\n pool input_pool_intermed;\n for (auto x : cur_supercell)\n {\n input_pool.insert(sigmap(x->getPort(\"\\\\A\"))[0]);\n input_pool.insert(sigmap(x->getPort(\"\\\\B\"))[0]);\n input_pool_intermed.insert(sigmap(x->getPort(\"\\\\Y\"))[0]);\n }\n SigSpec input;\n for (auto b : input_pool)\n if (input_pool_intermed.count(b) == 0)\n input.append_bit(b);\n\n SigBit output = sigmap(head_cell->getPort(\"\\\\Y\")[0]);\n\n auto new_reduce_cell = module->addCell(NEW_ID, \n gt == GateType::And ? \"$reduce_and\" :\n gt == GateType::Or ? \"$reduce_or\" :\n gt == GateType::Xor ? \"$reduce_xor\" : \"\");\n new_reduce_cell->setParam(\"\\\\A_SIGNED\", 0);\n new_reduce_cell->setParam(\"\\\\A_WIDTH\", input.size());\n new_reduce_cell->setParam(\"\\\\Y_WIDTH\", 1);\n new_reduce_cell->setPort(\"\\\\A\", input);\n new_reduce_cell->setPort(\"\\\\Y\", output);\n\n for (auto x : cur_supercell)\n consumed_cells.insert(x);\n }\n }\n\n \/\/ Remove every cell that we've used up\n for (auto cell : consumed_cells)\n module->remove(cell);\n }\n }\n} RecoverReduceCorePass;\n\nPRIVATE_NAMESPACE_END\nrecover_reduce: Reindent using tabs\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2017 Robert Ou \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct RecoverReduceCorePass : public Pass {\n\tenum GateType {\n\t\tAnd,\n\t\tOr,\n\t\tXor\n\t};\n\n\tRecoverReduceCorePass() : Pass(\"recover_reduce_core\", \"converts gate chains into $reduce_*\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" recover_reduce_core\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"converts gate chains into $reduce_*\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This performs the core step of the recover_reduce command. This step recognizes\\n\");\n\t\tlog(\"chains of gates found by the previous steps and converts these chains into one\\n\");\n\t\tlog(\"logical cell.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\t(void)args;\n\n\t\tfor (auto module : design->selected_modules())\n\t\t{\n\t\t\tSigMap sigmap(module);\n\n\t\t\t\/\/ Index all of the nets in the module\n\t\t\tdict sig_to_driver;\n\t\t\tdict> sig_to_sink;\n\t\t\tfor (auto cell : module->selected_cells())\n\t\t\t{\n\t\t\t\tfor (auto &conn : cell->connections())\n\t\t\t\t{\n\t\t\t\t\tif (cell->output(conn.first))\n\t\t\t\t\t\tfor (auto bit : sigmap(conn.second))\n\t\t\t\t\t\t\tsig_to_driver[bit] = cell;\n\n\t\t\t\t\tif (cell->input(conn.first))\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (auto bit : sigmap(conn.second))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (sig_to_sink.count(bit) == 0)\n\t\t\t\t\t\t\t\tsig_to_sink[bit] = pool();\n\t\t\t\t\t\t\tsig_to_sink[bit].insert(cell);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Need to check if any wires connect to module ports\n\t\t\tpool port_sigs;\n\t\t\tfor (auto wire : module->selected_wires())\n\t\t\t\tif (wire->port_input || wire->port_output)\n\t\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\t\tport_sigs.insert(bit);\n\n\t\t\t\/\/ Actual logic starts here\n\t\t\tpool consumed_cells;\n\t\t\tfor (auto cell : module->selected_cells())\n\t\t\t{\n\t\t\t\tif (consumed_cells.count(cell))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tGateType gt;\n\n\t\t\t\tif (cell->type == \"$_AND_\")\n\t\t\t\t\tgt = GateType::And;\n\t\t\t\telse if (cell->type == \"$_OR_\")\n\t\t\t\t\tgt = GateType::Or;\n\t\t\t\telse if (cell->type == \"$_XOR_\")\n\t\t\t\t\tgt = GateType::Xor;\n\t\t\t\telse\n\t\t\t\t\tcontinue;\n\n\t\t\t\tlog(\"Working on cell %s...\\n\", cell->name.c_str());\n\n\t\t\t\t\/\/ Go all the way to the sink\n\t\t\t\tCell* head_cell = cell;\n\t\t\t\tCell* x = cell;\n\t\t\t\twhile (true)\n\t\t\t\t{\n\t\t\t\t\tif (!((x->type == \"$_AND_\" && gt == GateType::And) ||\n\t\t\t\t\t\t(x->type == \"$_OR_\" && gt == GateType::Or) ||\n\t\t\t\t\t\t(x->type == \"$_XOR_\" && gt == GateType::Xor)))\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\thead_cell = x;\n\n\t\t\t\t\tauto y = sigmap(x->getPort(\"\\\\Y\"));\n\t\t\t\t\tlog_assert(y.size() == 1);\n\n\t\t\t\t\t\/\/ Should only continue if there is one fanout back into a cell (not to a port)\n\t\t\t\t\tif (sig_to_sink[y[0]].size() != 1)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tx = *sig_to_sink[y[0]].begin();\n\t\t\t\t}\n\n\t\t\t\tlog(\" Head cell is %s\\n\", head_cell->name.c_str());\n\n\t\t\t\tpool cur_supercell;\n\t\t\t\tstd::deque bfs_queue = {head_cell};\n\t\t\t\twhile (bfs_queue.size())\n\t\t\t\t{\n\t\t\t\t\tCell* x = bfs_queue.front();\n\t\t\t\t\tbfs_queue.pop_front();\n\n\t\t\t\t\tcur_supercell.insert(x);\n\n\t\t\t\t\tauto a = sigmap(x->getPort(\"\\\\A\"));\n\t\t\t\t\tlog_assert(a.size() == 1);\n\t\t\t\t\t\/\/ Must have only one sink\n\t\t\t\t\t\/\/ XXX: Check that it is indeed this node?\n\t\t\t\t\tif (sig_to_sink[a[0]].size() + port_sigs.count(a[0]) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tCell* cell_a = sig_to_driver[a[0]];\n\t\t\t\t\t\tif (((cell_a->type == \"$_AND_\" && gt == GateType::And) ||\n\t\t\t\t\t\t\t(cell_a->type == \"$_OR_\" && gt == GateType::Or) ||\n\t\t\t\t\t\t\t(cell_a->type == \"$_XOR_\" && gt == GateType::Xor)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ The cell here is the correct type, and it's definitely driving only\n\t\t\t\t\t\t\t\/\/ this current cell.\n\t\t\t\t\t\t\tbfs_queue.push_back(cell_a);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tauto b = sigmap(x->getPort(\"\\\\B\"));\n\t\t\t\t\tlog_assert(b.size() == 1);\n\t\t\t\t\t\/\/ Must have only one sink\n\t\t\t\t\t\/\/ XXX: Check that it is indeed this node?\n\t\t\t\t\tif (sig_to_sink[b[0]].size() + port_sigs.count(b[0]) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tCell* cell_b = sig_to_driver[b[0]];\n\t\t\t\t\t\tif (((cell_b->type == \"$_AND_\" && gt == GateType::And) ||\n\t\t\t\t\t\t\t(cell_b->type == \"$_OR_\" && gt == GateType::Or) ||\n\t\t\t\t\t\t\t(cell_b->type == \"$_XOR_\" && gt == GateType::Xor)))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ The cell here is the correct type, and it's definitely driving only\n\t\t\t\t\t\t\t\/\/ this current cell.\n\t\t\t\t\t\t\tbfs_queue.push_back(cell_b);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlog(\" Cells:\\n\");\n\t\t\t\tfor (auto x : cur_supercell)\n\t\t\t\t\tlog(\" %s\\n\", x->name.c_str());\n\n\t\t\t\tif (cur_supercell.size() > 1)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Worth it to create reduce cell\n\t\t\t\t\tlog(\" Creating $reduce_* cell!\\n\");\n\n\t\t\t\t\tpool input_pool;\n\t\t\t\t\tpool input_pool_intermed;\n\t\t\t\t\tfor (auto x : cur_supercell)\n\t\t\t\t\t{\n\t\t\t\t\t\tinput_pool.insert(sigmap(x->getPort(\"\\\\A\"))[0]);\n\t\t\t\t\t\tinput_pool.insert(sigmap(x->getPort(\"\\\\B\"))[0]);\n\t\t\t\t\t\tinput_pool_intermed.insert(sigmap(x->getPort(\"\\\\Y\"))[0]);\n\t\t\t\t\t}\n\t\t\t\t\tSigSpec input;\n\t\t\t\t\tfor (auto b : input_pool)\n\t\t\t\t\t\tif (input_pool_intermed.count(b) == 0)\n\t\t\t\t\t\t\tinput.append_bit(b);\n\n\t\t\t\t\tSigBit output = sigmap(head_cell->getPort(\"\\\\Y\")[0]);\n\n\t\t\t\t\tauto new_reduce_cell = module->addCell(NEW_ID, \n\t\t\t\t\t\tgt == GateType::And ? \"$reduce_and\" :\n\t\t\t\t\t\tgt == GateType::Or ? \"$reduce_or\" :\n\t\t\t\t\t\tgt == GateType::Xor ? \"$reduce_xor\" : \"\");\n\t\t\t\t\tnew_reduce_cell->setParam(\"\\\\A_SIGNED\", 0);\n\t\t\t\t\tnew_reduce_cell->setParam(\"\\\\A_WIDTH\", input.size());\n\t\t\t\t\tnew_reduce_cell->setParam(\"\\\\Y_WIDTH\", 1);\n\t\t\t\t\tnew_reduce_cell->setPort(\"\\\\A\", input);\n\t\t\t\t\tnew_reduce_cell->setPort(\"\\\\Y\", output);\n\n\t\t\t\t\tfor (auto x : cur_supercell)\n\t\t\t\t\t\tconsumed_cells.insert(x);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\/\/ Remove every cell that we've used up\n\t\t\tfor (auto cell : consumed_cells)\n\t\t\t\tmodule->remove(cell);\n\t\t}\n\t}\n} RecoverReduceCorePass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n\n#ifndef _WIN32\n#include \n#endif\n\n#include \n\n#include \"clustering\/administration\/main\/command_line.hpp\"\n#include \"crypto\/initialization_guard.hpp\"\n#include \"utils.hpp\"\n#include \"config\/args.hpp\"\n#include \"extproc\/extproc_spawner.hpp\"\n\nint main(int argc, char *argv[]) {\n\n#if defined(_WIN32) && !defined(NDEBUG)\n extern int unittest_main(int, char**);\n if (argc >= 2 && !strcmp(argv[1], \"test\")) {\n return unittest_main(argc - 1, argv + 1);\n }\n#endif\n\n startup_shutdown_t startup_shutdown;\n crypto::initialization_guard_t crypto_initialization_guard;\n\n#ifdef _WIN32\n extproc_maybe_run_worker(argc, argv);\n#endif\n\n std::set subcommands_that_look_like_flags;\n subcommands_that_look_like_flags.insert(\"--version\");\n subcommands_that_look_like_flags.insert(\"-v\");\n subcommands_that_look_like_flags.insert(\"--help\");\n subcommands_that_look_like_flags.insert(\"-h\");\n\n if (argc == 1 || (argv[1][0] == '-' && subcommands_that_look_like_flags.count(argv[1]) == 0)) {\n return main_rethinkdb_porcelain(argc, argv);\n\n } else {\n std::string subcommand = argv[1];\n\n if (subcommand == \"create\") {\n return main_rethinkdb_create(argc, argv);\n } else if (subcommand == \"serve\") {\n return main_rethinkdb_serve(argc, argv);\n } else if (subcommand == \"proxy\") {\n return main_rethinkdb_proxy(argc, argv);\n } else if (subcommand == \"export\") {\n return main_rethinkdb_export(argc, argv);\n } else if (subcommand == \"import\") {\n return main_rethinkdb_import(argc, argv);\n } else if (subcommand == \"dump\") {\n return main_rethinkdb_dump(argc, argv);\n } else if (subcommand == \"restore\") {\n return main_rethinkdb_restore(argc, argv);\n } else if (subcommand == \"index-rebuild\") {\n return main_rethinkdb_index_rebuild(argc, argv);\n } else if (subcommand == \"--version\" || subcommand == \"-v\") {\n if (argc != 2) {\n printf(\"WARNING: Ignoring extra parameters after '%s'.\", subcommand.c_str());\n }\n print_version_message();\n return 0;\n\n } else if (subcommand == \"help\" || subcommand == \"-h\" || subcommand == \"--help\") {\n\n if (argc == 2) {\n help_rethinkdb_porcelain();\n return 0;\n } else if (argc == 3) {\n std::string subcommand2 = argv[2];\n if (subcommand2 == \"create\") {\n help_rethinkdb_create();\n return 0;\n } else if (subcommand2 == \"serve\") {\n help_rethinkdb_serve();\n return 0;\n } else if (subcommand2 == \"proxy\") {\n help_rethinkdb_proxy();\n } else if (subcommand2 == \"export\") {\n help_rethinkdb_export();\n } else if (subcommand2 == \"import\") {\n help_rethinkdb_import();\n } else if (subcommand2 == \"dump\") {\n help_rethinkdb_dump();\n } else if (subcommand2 == \"restore\") {\n help_rethinkdb_restore();\n } else if (subcommand2 == \"index-rebuild\") {\n help_rethinkdb_index_rebuild();\n } else {\n printf(\"ERROR: No help for '%s'\\n\", subcommand2.c_str());\n return 1;\n }\n\n } else {\n puts(\"ERROR: Too many parameters to 'rethinkdb help'. Try 'rethinkdb help [subcommand]'.\");\n return 1;\n }\n\n } else {\n printf(\"ERROR: Unrecognized subcommand '%s'. Try 'rethinkdb help'.\\n\", subcommand.c_str());\n return 1;\n }\n }\n}\nget rid of unittest_main\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n\n#ifndef _WIN32\n#include \n#endif\n\n#include \n\n#include \"clustering\/administration\/main\/command_line.hpp\"\n#include \"crypto\/initialization_guard.hpp\"\n#include \"utils.hpp\"\n#include \"config\/args.hpp\"\n#include \"extproc\/extproc_spawner.hpp\"\n\nint main(int argc, char *argv[]) {\n\n startup_shutdown_t startup_shutdown;\n crypto::initialization_guard_t crypto_initialization_guard;\n\n#ifdef _WIN32\n extproc_maybe_run_worker(argc, argv);\n#endif\n\n std::set subcommands_that_look_like_flags;\n subcommands_that_look_like_flags.insert(\"--version\");\n subcommands_that_look_like_flags.insert(\"-v\");\n subcommands_that_look_like_flags.insert(\"--help\");\n subcommands_that_look_like_flags.insert(\"-h\");\n\n if (argc == 1 || (argv[1][0] == '-' && subcommands_that_look_like_flags.count(argv[1]) == 0)) {\n return main_rethinkdb_porcelain(argc, argv);\n\n } else {\n std::string subcommand = argv[1];\n\n if (subcommand == \"create\") {\n return main_rethinkdb_create(argc, argv);\n } else if (subcommand == \"serve\") {\n return main_rethinkdb_serve(argc, argv);\n } else if (subcommand == \"proxy\") {\n return main_rethinkdb_proxy(argc, argv);\n } else if (subcommand == \"export\") {\n return main_rethinkdb_export(argc, argv);\n } else if (subcommand == \"import\") {\n return main_rethinkdb_import(argc, argv);\n } else if (subcommand == \"dump\") {\n return main_rethinkdb_dump(argc, argv);\n } else if (subcommand == \"restore\") {\n return main_rethinkdb_restore(argc, argv);\n } else if (subcommand == \"index-rebuild\") {\n return main_rethinkdb_index_rebuild(argc, argv);\n } else if (subcommand == \"--version\" || subcommand == \"-v\") {\n if (argc != 2) {\n printf(\"WARNING: Ignoring extra parameters after '%s'.\", subcommand.c_str());\n }\n print_version_message();\n return 0;\n\n } else if (subcommand == \"help\" || subcommand == \"-h\" || subcommand == \"--help\") {\n\n if (argc == 2) {\n help_rethinkdb_porcelain();\n return 0;\n } else if (argc == 3) {\n std::string subcommand2 = argv[2];\n if (subcommand2 == \"create\") {\n help_rethinkdb_create();\n return 0;\n } else if (subcommand2 == \"serve\") {\n help_rethinkdb_serve();\n return 0;\n } else if (subcommand2 == \"proxy\") {\n help_rethinkdb_proxy();\n } else if (subcommand2 == \"export\") {\n help_rethinkdb_export();\n } else if (subcommand2 == \"import\") {\n help_rethinkdb_import();\n } else if (subcommand2 == \"dump\") {\n help_rethinkdb_dump();\n } else if (subcommand2 == \"restore\") {\n help_rethinkdb_restore();\n } else if (subcommand2 == \"index-rebuild\") {\n help_rethinkdb_index_rebuild();\n } else {\n printf(\"ERROR: No help for '%s'\\n\", subcommand2.c_str());\n return 1;\n }\n\n } else {\n puts(\"ERROR: Too many parameters to 'rethinkdb help'. Try 'rethinkdb help [subcommand]'.\");\n return 1;\n }\n\n } else {\n printf(\"ERROR: Unrecognized subcommand '%s'. Try 'rethinkdb help'.\\n\", subcommand.c_str());\n return 1;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"napi.h\"\n#include \"uv.h\"\n#include \"async.h\"\n\nnamespace {\n\nNapi::Value SetPassword(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n if (!info[1].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'username' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string username = info[1].As();\n\n if (!info[2].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'password' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string password = info[2].As();\n\n SetPasswordWorker* worker = new SetPasswordWorker(\n service,\n username,\n password,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Value GetPassword(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n if (!info[1].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'username' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string username = info[1].As();\n\n GetPasswordWorker* worker = new GetPasswordWorker(\n service,\n username,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Value DeletePassword(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\");\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n if (!info[1].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'username' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string username = info[1].As();\n\n DeletePasswordWorker *worker = new DeletePasswordWorker(\n service,\n username,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Value FindPassword(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n FindPasswordWorker* worker = new FindPasswordWorker(\n service,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Value FindCredentials(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n FindCredentialsWorker* worker = new FindCredentialsWorker(\n service,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Object Init(Napi::Env env, Napi::Object exports) {\n exports.Set(\"getPassword\", Napi::Function::New(env, GetPassword));\n exports.Set(\"setPassword\", Napi::Function::New(env, SetPassword));\n exports.Set(\"deletePassword\", Napi::Function::New(env, DeletePassword));\n exports.Set(\"findPassword\", Napi::Function::New(env, FindPassword));\n exports.Set(\"findCredentials\", Napi::Function::New(env, FindCredentials));\n return exports;\n}\n\n} \/\/ namespace\n\nNODE_API_MODULE(keytar, Init)\nfixup deletePassword to properly throw an error if service isn't a string (#270)#include \"napi.h\"\n#include \"uv.h\"\n#include \"async.h\"\n\nnamespace {\n\nNapi::Value SetPassword(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n if (!info[1].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'username' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string username = info[1].As();\n\n if (!info[2].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'password' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string password = info[2].As();\n\n SetPasswordWorker* worker = new SetPasswordWorker(\n service,\n username,\n password,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Value GetPassword(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n if (!info[1].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'username' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string username = info[1].As();\n\n GetPasswordWorker* worker = new GetPasswordWorker(\n service,\n username,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Value DeletePassword(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n if (!info[1].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'username' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string username = info[1].As();\n\n DeletePasswordWorker *worker = new DeletePasswordWorker(\n service,\n username,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Value FindPassword(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n FindPasswordWorker* worker = new FindPasswordWorker(\n service,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Value FindCredentials(const Napi::CallbackInfo& info) {\n Napi::Env env = info.Env();\n if (!info[0].IsString()) {\n Napi::TypeError::New(env, \"Parameter 'service' must be a string\").\n ThrowAsJavaScriptException();\n return env.Null();\n }\n\n std::string service = info[0].As();\n\n FindCredentialsWorker* worker = new FindCredentialsWorker(\n service,\n env);\n worker->Queue();\n return worker->Promise();\n}\n\nNapi::Object Init(Napi::Env env, Napi::Object exports) {\n exports.Set(\"getPassword\", Napi::Function::New(env, GetPassword));\n exports.Set(\"setPassword\", Napi::Function::New(env, SetPassword));\n exports.Set(\"deletePassword\", Napi::Function::New(env, DeletePassword));\n exports.Set(\"findPassword\", Napi::Function::New(env, FindPassword));\n exports.Set(\"findCredentials\", Napi::Function::New(env, FindCredentials));\n return exports;\n}\n\n} \/\/ namespace\n\nNODE_API_MODULE(keytar, Init)\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace PGSTD;\nusing namespace pqxx;\n\n\n\/\/ Example program for libpqxx. Perform a query and enumerate its output\n\/\/ using array indexing.\n\/\/\n\/\/ Usage: test002 [connect-string]\n\/\/\n\/\/ Where connect-string is a set of connection options in Postgresql's\n\/\/ PQconnectdb() format, eg. \"dbname=template1\" to select from a database\n\/\/ called template1, or \"host=foo.bar.net user=smith\" to connect to a\n\/\/ backend running on host foo.bar.net, logging in as user smith.\n\nint main(int, char *argv[])\n{\n try\n {\n \/\/ Set up connection to database\n string ConnectString = (argv[1] ? argv[1] : \"\");\n connection C(ConnectString);\n\n \/\/ Start transaction within context of connection\n work T(C, \"test2\");\n\n \/\/ Perform query within transaction\n result R( T.exec(\"SELECT * FROM pg_tables\") );\n\n \/\/ Let's keep the database waiting as briefly as possible: commit now,\n \/\/ before we start processing results. We could do this later, or since\n \/\/ we're not making any changes in the database that need to be committed,\n \/\/ we could in this case even omit it altogether.\n T.commit();\n\n \/\/ Since we don't need the database anymore, we can be even more \n \/\/ considerate and close the connection now. This is optional.\n C.disconnect();\n\n#ifdef PQXX_HAVE_PQFTABLE\n \/\/ Ah, this version of postgres will tell you which table a column in a\n \/\/ result came from. Let's just test that functionality...\n const oid rtable = R.column_table(0);\n const string rcol = R.column_name(0);\n\n const oid crtable = R.column_table(rcol);\n if (crtable != rtable)\n throw logic_error(\"Field \" + rcol + \" comes from \"\n \"'\" + to_string(rtable) + \"', \"\n\t \t\t\"but by name, result says it's from \"\n \"'\" + to_string(crtable) + \"'\");\n#endif\n\n \/\/ Now we've got all that settled, let's process our results.\n for (result::size_type i = 0; i < R.size(); ++i)\n {\n cout << '\\t' << to_string(i) << '\\t' << R[i][0].c_str() << endl;\n\n#ifdef PQXX_HAVE_PQFTABLE\n const oid ftable = R[i][0].table();\n if (ftable != rtable)\n\tthrow logic_error(\"Field says it comes from \"\n \"'\" + to_string(ftable) + \"'; \"\n\t\t\t \"expected '\" + to_string(rtable) + \"'\");\n const oid ttable = R[i].column_table(0);\n if (ttable != rtable)\n\tthrow logic_error(\"Tuple says field comes from \"\n \"'\" + to_string(ttable) + \"'; \"\n\t \t\t \"expected '\" + to_string(rtable) + \"'\");\n const oid cttable = R[i].column_table(rcol);\n if (cttable != rtable)\n\tthrow logic_error(\"Field comes from '\" + to_string(rtable) + \"', \"\n\t \"but by name, tuple says it's from '\" + \n\t\t\t to_string(cttable) + \"'\");\n#endif\n }\n }\n catch (const sql_error &e)\n {\n \/\/ If we're interested in the text of a failed query, we can write separate\n \/\/ exception handling code for this type of exception\n cerr << \"SQL error: \" << e.what() << endl\n << \"Query was: '\" << e.query() << \"'\" << endl;\n return 1;\n }\n catch (const exception &e)\n {\n \/\/ All exceptions thrown by libpqxx are derived from std::exception\n cerr << \"Exception: \" << e.what() << endl;\n return 2;\n }\n catch (...)\n {\n \/\/ This is really unexpected (see above)\n cerr << \"Unhandled exception\" << endl;\n return 100;\n }\n\n return 0;\n}\n\nCheck result::column_name() for both int and size_type#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace PGSTD;\nusing namespace pqxx;\n\n\n\/\/ Example program for libpqxx. Perform a query and enumerate its output\n\/\/ using array indexing.\n\/\/\n\/\/ Usage: test002 [connect-string]\n\/\/\n\/\/ Where connect-string is a set of connection options in Postgresql's\n\/\/ PQconnectdb() format, eg. \"dbname=template1\" to select from a database\n\/\/ called template1, or \"host=foo.bar.net user=smith\" to connect to a\n\/\/ backend running on host foo.bar.net, logging in as user smith.\n\nint main(int, char *argv[])\n{\n try\n {\n \/\/ Set up connection to database\n string ConnectString = (argv[1] ? argv[1] : \"\");\n connection C(ConnectString);\n\n \/\/ Start transaction within context of connection\n work T(C, \"test2\");\n\n \/\/ Perform query within transaction\n result R( T.exec(\"SELECT * FROM pg_tables\") );\n\n \/\/ Let's keep the database waiting as briefly as possible: commit now,\n \/\/ before we start processing results. We could do this later, or since\n \/\/ we're not making any changes in the database that need to be committed,\n \/\/ we could in this case even omit it altogether.\n T.commit();\n\n \/\/ Since we don't need the database anymore, we can be even more \n \/\/ considerate and close the connection now. This is optional.\n C.disconnect();\n\n#ifdef PQXX_HAVE_PQFTABLE\n \/\/ Ah, this version of postgres will tell you which table a column in a\n \/\/ result came from. Let's just test that functionality...\n const oid rtable = R.column_table(0);\n if (rtable != R.column_table(result::tuple::size_type(0)))\n throw logic_error(\"Inconsistent result::column_table()\");\n\n const string rcol = R.column_name(0);\n const oid crtable = R.column_table(rcol);\n if (crtable != rtable)\n throw logic_error(\"Field \" + rcol + \" comes from \"\n \"'\" + to_string(rtable) + \"', \"\n\t \t\t\"but by name, result says it's from \"\n \"'\" + to_string(crtable) + \"'\");\n#endif\n\n \/\/ Now we've got all that settled, let's process our results.\n for (result::size_type i = 0; i < R.size(); ++i)\n {\n cout << '\\t' << to_string(i) << '\\t' << R[i][0].c_str() << endl;\n\n#ifdef PQXX_HAVE_PQFTABLE\n const oid ftable = R[i][0].table();\n if (ftable != rtable)\n\tthrow logic_error(\"Field says it comes from \"\n \"'\" + to_string(ftable) + \"'; \"\n\t\t\t \"expected '\" + to_string(rtable) + \"'\");\n const oid ttable = R[i].column_table(0);\n if (ttable != R[i].column_table(result::tuple::size_type(0)))\n\tthrow logic_error(\"Inconsistent result::tuple::column_table()\");\n if (ttable != rtable)\n\tthrow logic_error(\"Tuple says field comes from \"\n \"'\" + to_string(ttable) + \"'; \"\n\t \t\t \"expected '\" + to_string(rtable) + \"'\");\n const oid cttable = R[i].column_table(rcol);\n if (cttable != rtable)\n\tthrow logic_error(\"Field comes from '\" + to_string(rtable) + \"', \"\n\t \"but by name, tuple says it's from '\" + \n\t\t\t to_string(cttable) + \"'\");\n#endif\n }\n }\n catch (const sql_error &e)\n {\n \/\/ If we're interested in the text of a failed query, we can write separate\n \/\/ exception handling code for this type of exception\n cerr << \"SQL error: \" << e.what() << endl\n << \"Query was: '\" << e.query() << \"'\" << endl;\n return 1;\n }\n catch (const exception &e)\n {\n \/\/ All exceptions thrown by libpqxx are derived from std::exception\n cerr << \"Exception: \" << e.what() << endl;\n return 2;\n }\n catch (...)\n {\n \/\/ This is really unexpected (see above)\n cerr << \"Unhandled exception\" << endl;\n return 100;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*!\n * \\cond FILEINFO\n ******************************************************************************\n * \\file main.cpp\n ******************************************************************************\n *\n * Copyright (C) ATS Advanced Telematic Systems GmbH GmbH, 2016\n *\n * \\author Moritz Klinger\n *\n ******************************************************************************\n *\n * \\brief The main file of the project.\n *\n *\n ******************************************************************************\n *\n * \\endcond\n *\/\n\n\/*****************************************************************************\/\n#include \n#include \n#include \n\n#include \"aktualizr.h\"\n#include \"config.h\"\n#include \"logger.h\"\n#include \"utils.h\"\n\n\/*****************************************************************************\/\n\nnamespace bpo = boost::program_options;\n\nbpo::variables_map parse_options(int argc, char *argv[]) {\n bpo::options_description description(\"CommandLine Options\");\n \/\/ clang-format off\n description.add_options()\n (\"help,h\", \"help screen\")\n (\"version,v\", \"Current aktualizr version\")\n (\"loglevel\", bpo::value(), \"set log level 0-4 (trace, debug, warning, info, error)\")\n (\"config,c\", bpo::value()->required(), \"toml configuration file\")\n (\"gateway-http\", bpo::value(), \"enable the http gateway\")\n (\"gateway-rvi\", bpo::value(), \"enable the rvi gateway\")\n (\"gateway-socket\", bpo::value(), \"enable the socket gateway\")\n (\"gateway-dbus\", bpo::value(), \"enable the D-Bus gateway\")\n (\"dbus-system-bus\", \"Use the D-Bus system bus (rather than the session bus)\")\n (\"tls-server\", bpo::value(), \"url, used for auto provisioning\")\n (\"repo-server\", bpo::value(), \"url of the uptane repo repository\")\n (\"director-server\", bpo::value(), \"url of the uptane director repository\")\n (\"ostree-server\", bpo::value(), \"url of the ostree repository\")\n (\"primary-ecu-serial\", bpo::value(), \"serial number of primary ecu\")\n (\"primary-ecu-hardware-id\", bpo::value(), \"hardware id of primary ecu\")\n (\"disable-keyid-validation\", \"Disable keyid validation on client side\" )\n (\"poll-once\", \"Check for updates only once and exit\")\n (\"secondary-config\", bpo::value >()->composing(), \"set config for secondary\");\n \/\/ clang-format on\n\n bpo::variables_map vm;\n try {\n bpo::store(bpo::parse_command_line(argc, argv, description), vm);\n bpo::notify(vm);\n } catch (const bpo::required_option &ex) {\n if (vm.count(\"help\") != 0) {\n std::cout << description << '\\n';\n exit(EXIT_SUCCESS);\n }\n if (vm.count(\"version\") != 0) {\n std::cout << \"Current aktualizr version is: \" << AKTUALIZR_VERSION << \"\\n\";\n exit(EXIT_SUCCESS);\n }\n\n if (ex.get_option_name() == \"--config\") {\n std::cout << ex.get_option_name() << \" is missing.\\nYou have to provide a valid configuration \"\n \"file using toml format. See the example configuration file \"\n \"in config\/config.toml.example\"\n << std::endl;\n exit(EXIT_FAILURE);\n } else {\n \/\/ print the error and append the default commandline option description\n std::cout << ex.what() << std::endl << description;\n exit(EXIT_SUCCESS);\n }\n } catch (const bpo::error &ex) {\n \/\/ log boost error\n LOGGER_LOG(LVL_warning, \"boost command line option error: \" << ex.what());\n\n \/\/ print the error message to the standard output too, as the user provided\n \/\/ a non-supported commandline option\n std::cout << ex.what() << '\\n';\n\n \/\/ set the returnValue, thereby ctest will recognize\n \/\/ that something went wrong\n exit(EXIT_FAILURE);\n }\n\n return vm;\n}\n\n\/*****************************************************************************\/\nint main(int argc, char *argv[]) {\n loggerInit();\n\n bpo::variables_map commandline_map = parse_options(argc, argv);\n\n \/\/ check for loglevel\n if (commandline_map.count(\"loglevel\") != 0) {\n \/\/ set the log level from command line option\n LoggerLevels severity = static_cast(commandline_map[\"loglevel\"].as());\n if (severity < LVL_minimum) {\n LOGGER_LOG(LVL_debug, \"Invalid log level\");\n severity = LVL_trace;\n }\n if (LVL_maximum < severity) {\n LOGGER_LOG(LVL_warning, \"Invalid log level\");\n severity = LVL_error;\n }\n loggerSetSeverity(severity);\n }\n\n \/\/ Initialize config with default values, the update with config, then with cmd\n std::string filename = commandline_map[\"config\"].as();\n\n try {\n Config config(filename, commandline_map);\n Aktualizr aktualizr(config);\n return aktualizr.run();\n } catch (const std::exception &ex) {\n LOGGER_LOG(LVL_error, ex.what());\n return -1;\n }\n}\nmain.cc: Exit if configuration file doesn't exist\/*!\n * \\cond FILEINFO\n ******************************************************************************\n * \\file main.cpp\n ******************************************************************************\n *\n * Copyright (C) ATS Advanced Telematic Systems GmbH GmbH, 2016\n *\n * \\author Moritz Klinger\n *\n ******************************************************************************\n *\n * \\brief The main file of the project.\n *\n *\n ******************************************************************************\n *\n * \\endcond\n *\/\n\n\/*****************************************************************************\/\n#include \n#include \n#include \n#include \n\n#include \"aktualizr.h\"\n#include \"config.h\"\n#include \"logger.h\"\n#include \"utils.h\"\n\n\/*****************************************************************************\/\n\nnamespace bpo = boost::program_options;\n\nbpo::variables_map parse_options(int argc, char *argv[]) {\n bpo::options_description description(\"CommandLine Options\");\n \/\/ clang-format off\n description.add_options()\n (\"help,h\", \"help screen\")\n (\"version,v\", \"Current aktualizr version\")\n (\"loglevel\", bpo::value(), \"set log level 0-4 (trace, debug, warning, info, error)\")\n (\"config,c\", bpo::value()->required(), \"toml configuration file\")\n (\"gateway-http\", bpo::value(), \"enable the http gateway\")\n (\"gateway-rvi\", bpo::value(), \"enable the rvi gateway\")\n (\"gateway-socket\", bpo::value(), \"enable the socket gateway\")\n (\"gateway-dbus\", bpo::value(), \"enable the D-Bus gateway\")\n (\"dbus-system-bus\", \"Use the D-Bus system bus (rather than the session bus)\")\n (\"tls-server\", bpo::value(), \"url, used for auto provisioning\")\n (\"repo-server\", bpo::value(), \"url of the uptane repo repository\")\n (\"director-server\", bpo::value(), \"url of the uptane director repository\")\n (\"ostree-server\", bpo::value(), \"url of the ostree repository\")\n (\"primary-ecu-serial\", bpo::value(), \"serial number of primary ecu\")\n (\"primary-ecu-hardware-id\", bpo::value(), \"hardware id of primary ecu\")\n (\"disable-keyid-validation\", \"Disable keyid validation on client side\" )\n (\"poll-once\", \"Check for updates only once and exit\")\n (\"secondary-config\", bpo::value >()->composing(), \"set config for secondary\");\n \/\/ clang-format on\n\n bpo::variables_map vm;\n try {\n bpo::store(bpo::parse_command_line(argc, argv, description), vm);\n bpo::notify(vm);\n } catch (const bpo::required_option &ex) {\n if (vm.count(\"help\") != 0) {\n std::cout << description << '\\n';\n exit(EXIT_SUCCESS);\n }\n if (vm.count(\"version\") != 0) {\n std::cout << \"Current aktualizr version is: \" << AKTUALIZR_VERSION << \"\\n\";\n exit(EXIT_SUCCESS);\n }\n\n if (ex.get_option_name() == \"--config\") {\n std::cout << ex.get_option_name() << \" is missing.\\nYou have to provide a valid configuration \"\n \"file using toml format. See the example configuration file \"\n \"in config\/config.toml.example\"\n << std::endl;\n exit(EXIT_FAILURE);\n } else {\n \/\/ print the error and append the default commandline option description\n std::cout << ex.what() << std::endl << description;\n exit(EXIT_SUCCESS);\n }\n } catch (const bpo::error &ex) {\n \/\/ log boost error\n LOGGER_LOG(LVL_warning, \"boost command line option error: \" << ex.what());\n\n \/\/ print the error message to the standard output too, as the user provided\n \/\/ a non-supported commandline option\n std::cout << ex.what() << '\\n';\n\n \/\/ set the returnValue, thereby ctest will recognize\n \/\/ that something went wrong\n exit(EXIT_FAILURE);\n }\n\n return vm;\n}\n\n\/*****************************************************************************\/\nint main(int argc, char *argv[]) {\n loggerInit();\n\n bpo::variables_map commandline_map = parse_options(argc, argv);\n\n \/\/ check for loglevel\n if (commandline_map.count(\"loglevel\") != 0) {\n \/\/ set the log level from command line option\n LoggerLevels severity = static_cast(commandline_map[\"loglevel\"].as());\n if (severity < LVL_minimum) {\n LOGGER_LOG(LVL_debug, \"Invalid log level\");\n severity = LVL_trace;\n }\n if (LVL_maximum < severity) {\n LOGGER_LOG(LVL_warning, \"Invalid log level\");\n severity = LVL_error;\n }\n loggerSetSeverity(severity);\n }\n\n \/\/ Initialize config with default values, the update with config, then with cmd\n std::string sota_config_file = commandline_map[\"config\"].as();\n boost::filesystem::path sota_config_path(sota_config_file);\n if (false == boost::filesystem::exists(sota_config_path)) {\n std::cout << \"aktualizr: configuration file \" << boost::filesystem::absolute(sota_config_path)\n << \" not found. Exiting.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n try {\n Config config(sota_config_path.string(), commandline_map);\n Aktualizr aktualizr(config);\n return aktualizr.run();\n } catch (const std::exception &ex) {\n LOGGER_LOG(LVL_error, ex.what());\n return -1;\n }\n}\n<|endoftext|>"} {"text":"#include \"code_gen.h\"\n#include \"cpp.h\"\n#include \"error.h\"\n#include \"parser.h\"\n#include \"scanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nstd::string program;\nstd::string filename_in;\nstd::string filename_out;\nbool debug = false;\nstatic bool only_preprocess = false;\nstatic bool only_compile = false;\nstatic bool specified_out_name = false;\nstatic std::list filenames_in;\nstatic std::list gcc_filenames_in;\nstatic std::list gcc_args;\nstatic std::list defines;\nstatic std::list include_paths;\n\n\nstatic void Usage() {\n printf(\"Usage: wgtcc [options] file...\\n\"\n \"Options: \\n\"\n \" -h Display this information\\n\"\n \" -D Define object like macro\\n\"\n \" -I Add search path\\n\"\n \" -E Preprocess only; do not compile, assemble or link\\n\"\n \" -S Compile only; do not assemble or link\\n\"\n \" -o specify output file\\n\");\n\n exit(-2);\n}\n\n\nstatic std::string GetExtension(const std::string& filename) {\n return filename.substr(filename.size() >= 2 ? filename.size() - 2 : 0);\n}\n\n\nstatic void ValidateFileName(const std::string& filename) {\n auto ext = GetExtension(filename);\n if (ext != \".c\" && ext != \".s\" && ext != \".o\" && ext != \".a\")\n Error(\"bad file name format:'%s'\", filename.c_str());\n}\n\n\nstatic void DefineMacro(Preprocessor& cpp, const std::string& def) {\n auto pos = def.find('=');\n std::string macro;\n std::string* replace;\n if (pos == std::string::npos) {\n macro = def;\n replace = new std::string();\n } else {\n macro = def.substr(0, pos);\n replace = new std::string(def.substr(pos + 1));\n }\n cpp.AddMacro(macro, replace);\n}\n\n\nstatic std::string GetName(const std::string& path) {\n auto pos = path.rfind('\/');\n if (pos == std::string::npos)\n return path;\n return path.substr(pos + 1);\n}\n\nstatic int RunWgtcc() {\n if (GetExtension(filename_in) != \".c\")\n return 0;\n\n Preprocessor cpp(&filename_in);\n for (auto& def: defines)\n DefineMacro(cpp, def);\n for (auto& path: include_paths)\n cpp.AddSearchPath(path);\n\n FILE* fp = stdout;\n if (specified_out_name) {\n fp = fopen(filename_out.c_str(), \"w\");\n }\n TokenSequence ts;\n cpp.Process(ts);\n if (only_preprocess) {\n ts.Print(fp);\n return 0;\n }\n\n if (!only_compile || !specified_out_name) {\n filename_out = GetName(filename_in);\n filename_out.back() = 's';\n }\n fp = fopen(filename_out.c_str(), \"w\");\n\n Parser parser(ts);\n parser.Parse();\n Generator::SetInOut(&parser, fp);\n Generator().Gen();\n fclose(fp);\n return 0;\n}\n\n\nstatic int RunGcc() {\n \/\/ Froce C11\n bool spec_std = false;\n for (auto& arg: gcc_args) {\n if (arg.substr(0, 4) == \"-std\") {\n arg = \"-std=c11\";\n spec_std = true;\n }\n }\n if (!spec_std) {\n gcc_args.push_front(\"-std=c11\");\n }\n\n std::string systemArg = \"gcc\";\n for (const auto& arg: gcc_args) {\n systemArg += \" \" + arg;\n }\n auto ret = system(systemArg.c_str());\n return ret;\n}\n\n\nstatic void ParseInclude(int argc, char* argv[], int& i) {\n if (argv[i][2]) {\n include_paths.push_front(&argv[i][2]);\n return;\n }\n\n if (i == argc - 1) {\n Error(\"missing argument to '%s'\", argv[i]);\n }\n include_paths.push_front(argv[++i]);\n gcc_args.push_back(argv[i]);\n}\n\n\nstatic void ParseDefine(int argc, char* argv[], int& i) {\n if (argv[i][2]) {\n defines.push_back(&argv[i][2]);\n return;\n }\n\n if (i == argc - 1)\n Error(\"missing argument to '%s'\", argv[i]);\n defines.push_back(argv[++i]);\n gcc_args.push_back(argv[i]);\n}\n\n\nstatic void ParseOut(int argc, char* argv[], int& i) {\n if (i == argc - 1)\n Error(\"missing argument to '%s'\", argv[i]);\n filename_out = argv[++i];\n gcc_args.push_back(argv[i]);\n}\n\n\n\/* Use:\n * wgtcc: compile\n * gcc: assemble and link\n * Allowing multi file may not be a good idea...\n *\/\nint main(int argc, char* argv[]) {\n if (argc < 2)\n Usage();\n\n program = std::string(argv[0]);\n for (auto i = 1; i < argc; ++i) {\n if (argv[i][0] != '-') {\n filename_in = std::string(argv[i]);\n ValidateFileName(filename_in);\n filenames_in.push_back(filename_in);\n continue;\n }\n\n gcc_args.push_back(argv[i]);\n switch (argv[i][1]) {\n case 'h': Usage(); break;\n case 'E': only_preprocess = true; break;\n case 'S': only_compile = true; break;\n case 'I': ParseInclude(argc, argv, i); break;\n case 'D': ParseDefine(argc, argv, i); break;\n case 'o':\n specified_out_name = true;\n ParseOut(argc, argv, i); break;\n case 'g': gcc_args.pop_back(); debug = true; break;\n default:;\n }\n }\n\n#ifdef DEBUG\n RunWgtcc();\n#else\n for (const auto& filename: filenames_in) {\n filename_in = filename;\n bool has_error = false;\n pid_t pid = fork();\n if (pid < 0) {\n Error(\"fork error\");\n } else if (pid == 0) {\n \/\/ Do work in child process\n return RunWgtcc();\n } else {\n int stat;\n wait(&stat);\n has_error = has_error || (WIFEXITED(stat) && WEXITSTATUS(stat) != 0);\n }\n\n if (has_error)\n return 0;\n }\n#endif\n\n if (only_preprocess || only_compile) {\n if (specified_out_name && filenames_in.size() > 1)\n Error(\"cannot specifier output filename with multiple input file\");\n return 0;\n }\n\n std::list filenames_out;\n for (auto& filename: filenames_in) {\n if (GetExtension(filename) == \".c\") {\n gcc_args.push_back(GetName(filename));\n gcc_args.back().back() = 's';\n } else {\n gcc_args.clear();\n for (int i = 1; i < argc; ++i)\n gcc_args.push_back(argv[i]);\n break;\n }\n }\n auto ret = RunGcc();\n auto cmd = \"rm -f \" + filename_out;\n if (system(cmd.c_str())) {}\n return ret;\n}\nfix multithread compiling#include \"code_gen.h\"\n#include \"cpp.h\"\n#include \"error.h\"\n#include \"parser.h\"\n#include \"scanner.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nstd::string program;\nstd::string filename_in;\nstd::string filename_out;\nbool debug = false;\nstatic bool only_preprocess = false;\nstatic bool only_compile = false;\nstatic bool specified_out_name = false;\nstatic std::list filenames_in;\nstatic std::list gcc_filenames_in;\nstatic std::list gcc_args;\nstatic std::list defines;\nstatic std::list include_paths;\n\n\nstatic void Usage() {\n printf(\"Usage: wgtcc [options] file...\\n\"\n \"Options: \\n\"\n \" -h Display this information\\n\"\n \" -D Define object like macro\\n\"\n \" -I Add search path\\n\"\n \" -E Preprocess only; do not compile, assemble or link\\n\"\n \" -S Compile only; do not assemble or link\\n\"\n \" -o specify output file\\n\");\n\n exit(-2);\n}\n\n\nstatic std::string GetExtension(const std::string& filename) {\n return filename.substr(filename.size() >= 2 ? filename.size() - 2 : 0);\n}\n\n\nstatic void ValidateFileName(const std::string& filename) {\n auto ext = GetExtension(filename);\n if (ext != \".c\" && ext != \".s\" && ext != \".o\" && ext != \".a\")\n Error(\"bad file name format:'%s'\", filename.c_str());\n}\n\n\nstatic void DefineMacro(Preprocessor& cpp, const std::string& def) {\n auto pos = def.find('=');\n std::string macro;\n std::string* replace;\n if (pos == std::string::npos) {\n macro = def;\n replace = new std::string();\n } else {\n macro = def.substr(0, pos);\n replace = new std::string(def.substr(pos + 1));\n }\n cpp.AddMacro(macro, replace);\n}\n\n\nstatic std::string GetName(const std::string& path) {\n auto pos = path.rfind('\/');\n if (pos == std::string::npos)\n return path;\n return path.substr(pos + 1);\n}\n\nstatic int RunWgtcc() {\n if (GetExtension(filename_in) != \".c\")\n return 0;\n\n Preprocessor cpp(&filename_in);\n for (auto& def: defines)\n DefineMacro(cpp, def);\n for (auto& path: include_paths)\n cpp.AddSearchPath(path);\n\n FILE* fp = stdout;\n if (specified_out_name) {\n fp = fopen(filename_out.c_str(), \"w\");\n }\n TokenSequence ts;\n cpp.Process(ts);\n if (only_preprocess) {\n ts.Print(fp);\n return 0;\n }\n\n if (!only_compile || !specified_out_name) {\n filename_out = GetName(filename_in);\n filename_out.back() = 's';\n }\n fp = fopen(filename_out.c_str(), \"w\");\n\n Parser parser(ts);\n parser.Parse();\n Generator::SetInOut(&parser, fp);\n Generator().Gen();\n fclose(fp);\n return 0;\n}\n\n\nstatic int RunGcc() {\n \/\/ Froce C11\n bool spec_std = false;\n for (auto& arg: gcc_args) {\n if (arg.substr(0, 4) == \"-std\") {\n arg = \"-std=c11\";\n spec_std = true;\n }\n }\n if (!spec_std) {\n gcc_args.push_front(\"-std=c11\");\n }\n\n std::string systemArg = \"gcc\";\n for (const auto& arg: gcc_args) {\n systemArg += \" \" + arg;\n }\n auto ret = system(systemArg.c_str());\n return ret;\n}\n\n\nstatic void ParseInclude(int argc, char* argv[], int& i) {\n if (argv[i][2]) {\n include_paths.push_front(&argv[i][2]);\n return;\n }\n\n if (i == argc - 1) {\n Error(\"missing argument to '%s'\", argv[i]);\n }\n include_paths.push_front(argv[++i]);\n gcc_args.push_back(argv[i]);\n}\n\n\nstatic void ParseDefine(int argc, char* argv[], int& i) {\n if (argv[i][2]) {\n defines.push_back(&argv[i][2]);\n return;\n }\n\n if (i == argc - 1)\n Error(\"missing argument to '%s'\", argv[i]);\n defines.push_back(argv[++i]);\n gcc_args.push_back(argv[i]);\n}\n\n\nstatic void ParseOut(int argc, char* argv[], int& i) {\n if (i == argc - 1)\n Error(\"missing argument to '%s'\", argv[i]);\n filename_out = argv[++i];\n gcc_args.push_back(argv[i]);\n}\n\n\n\/* Use:\n * wgtcc: compile\n * gcc: assemble and link\n * Allowing multi file may not be a good idea...\n *\/\nint main(int argc, char* argv[]) {\n if (argc < 2)\n Usage();\n\n program = std::string(argv[0]);\n for (auto i = 1; i < argc; ++i) {\n if (argv[i][0] != '-') {\n filename_in = std::string(argv[i]);\n ValidateFileName(filename_in);\n filenames_in.push_back(filename_in);\n continue;\n }\n\n gcc_args.push_back(argv[i]);\n switch (argv[i][1]) {\n case 'h': Usage(); break;\n case 'E': only_preprocess = true; break;\n case 'S': only_compile = true; break;\n case 'I': ParseInclude(argc, argv, i); break;\n case 'D': ParseDefine(argc, argv, i); break;\n case 'o':\n specified_out_name = true;\n ParseOut(argc, argv, i); break;\n case 'g': gcc_args.pop_back(); debug = true; break;\n default:;\n }\n }\n\n#ifdef DEBUG\n RunWgtcc();\n#else\n for (const auto& filename: filenames_in) {\n filename_in = filename;\n pid_t pid = fork();\n if (pid < 0) {\n Error(\"fork error\");\n } else if (pid == 0) {\n \/\/ Do work in child process\n return RunWgtcc();\n }\n }\n\n int stat; \n bool has_error = false;\n for (int i = 0; i < filenames_in.size(); i++) {\n wait(&stat);\n has_error = has_error || (WIFEXITED(stat) && WEXITSTATUS(stat) != 0);\n if (has_error)\n return 0;\n }\n#endif\n\n if (only_preprocess || only_compile) {\n if (specified_out_name && filenames_in.size() > 1)\n Error(\"cannot specifier output filename with multiple input file\");\n return 0;\n }\n\n std::list filenames_out;\n for (auto& filename: filenames_in) {\n if (GetExtension(filename) == \".c\") {\n gcc_args.push_back(GetName(filename));\n gcc_args.back().back() = 's';\n } else {\n gcc_args.clear();\n for (int i = 1; i < argc; ++i)\n gcc_args.push_back(argv[i]);\n break;\n }\n }\n auto ret = RunGcc();\n auto cmd = \"rm -f \" + filename_out;\n if (system(cmd.c_str())) {}\n return ret;\n}\n<|endoftext|>"} {"text":"\/*=====================================================================\n\nQGroundControl Open Source Ground Control Station\n\n(c) 2009 - 2011 QGROUNDCONTROL PROJECT \n\nThis file is part of the QGROUNDCONTROL project\n\n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see .\n\n======================================================================*\/\n\n\/**\n * @file\n * @brief Main executable\n * @author Lorenz Meier \n *\n *\/\n\n#include \"QGCCore.h\"\n#include \"MainWindow.h\"\n#include \"configuration.h\"\n#include \"logging.h\"\n#include \n#include \n\n\/* SDL does ugly things to main() *\/\n#ifdef main\n#undef main\n#endif\n\n\n\/\/ Install a message handler so you do not need\n\/\/ the MSFT debug tools installed to se\n\/\/ qDebug(), qWarning(), qCritical and qAbort\n#ifdef Q_OS_WIN\nvoid msgHandler( QtMsgType type, const char* msg )\n{\n const char symbols[] = { 'I', 'E', '!', 'X' };\n QString output = QString(\"[%1] %2\").arg( symbols[type] ).arg( msg );\n std::cerr << output.toStdString() << std::endl;\n if( type == QtFatalMsg ) abort();\n}\n#endif\n\n\/\/ Path for file logging\nstatic QString sLogPath;\n\n\/\/ Message handler for logging provides console and file output\n\/\/ The handler itself has to be reentrant and threadsafe!\nvoid loggingMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)\n{\n \/\/ The message handler has to be thread safe\n static QMutex mutex;\n QMutexLocker localLoc(&mutex);\n\n static std::ofstream logFile(sLogPath.toStdString().c_str(), std::ofstream::out | std::ofstream::app);\n\n QString outMessage(qFormatLogMessage(type, context, message)); \/\/ just format only once\n if(logFile)\n {\n logFile << qPrintable(outMessage) << std::endl; \/\/ log to file\n }\n\n LogWindowSingleton::instance().write(outMessage); \/\/ log to debug window\n\n fprintf(stderr, \"%s\\n\", qPrintable(outMessage)); \/\/ log to console\n}\n\n\n\/**\n * @brief Starts the application\n *\n * @param argc Number of commandline arguments\n * @param argv Commandline arguments\n * @return exit code, 0 for normal exit and !=0 for error cases\n *\/\nint main(int argc, char *argv[])\n{\n\/\/ install the message handler\n#ifdef Q_OS_WIN\n \/\/qInstallMsgHandler( msgHandler );\n#endif\n\n \/\/ Init logging\n \/\/ create filename and path for logfile like \"apmlog_20160529.txt\"\n \/\/ one logfile for every day. Size is not limited\n QString logFileName(\"apmlog_\");\n logFileName.append(QDateTime::currentDateTime().toString(\"yyyyMMdd\"));\n logFileName.append(\".txt\");\n sLogPath = QString(QDir(QGC::appDataDirectory()).filePath(logFileName));\n\n \/\/ Just keep the 5 recent logfiles and delete the rest.\n QDir logDirectory(QGC::appDataDirectory(), \"apmlog*\", QDir::Name, QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);\n QStringList logFileList(logDirectory.entryList());\n \/\/ As the file list is sorted we can delete index 0 cause its the oldest one\n while(logFileList.size() > 5)\n {\n logDirectory.remove(logFileList.at(0));\n logFileList.pop_front();\n }\n\n \/\/ Add sperator for better orientation in Logfiles\n std::ofstream logFile(sLogPath.toStdString().c_str(), std::ofstream::out | std::ofstream::app);\n if (logFile)\n {\n logFile << std::endl << std::endl << \"**************************************************\" << std::endl << std::endl;\n logFile.close();\n }\n\n \/\/ set up logging pattern\n#if QT_VERSION < QT_VERSION_CHECK(5, 5, 0)\n \/\/ QT < 5.5.x does not support qInfo() logging macro and no info-formatting too\n QString logPattern(\"[%{time yyyyMMdd h:mm:ss.zzz} %{if-debug}DEBUG%{endif}%{if-warning}WARN %{endif}%{if-critical}ERROR%{endif}%{if-fatal}FATAL%{endif}] - %{message}\");\n#else\n QString logPattern(\"[%{time yyyyMMdd h:mm:ss.zzz} %{if-debug}DEBUG%{endif}%{if-info}INFO %{endif}%{if-warning}WARN %{endif}%{if-critical}ERROR%{endif}%{if-fatal}FATAL%{endif}] - %{message}\");\n#endif\n\n qSetMessagePattern(logPattern);\n\n \/\/ install the message handler for logging\n qInstallMessageHandler(loggingMessageHandler);\n\n \/\/ start the application\n QGCCore core(argc, argv);\n core.initialize();\n return core.exec();\n}\nConfig: BugFix for loading global settings #730\/*=====================================================================\n\nQGroundControl Open Source Ground Control Station\n\n(c) 2009 - 2011 QGROUNDCONTROL PROJECT \n\nThis file is part of the QGROUNDCONTROL project\n\n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see .\n\n======================================================================*\/\n\n\/**\n * @file\n * @brief Main executable\n * @author Lorenz Meier \n *\n *\/\n\n#include \"QGCCore.h\"\n#include \"MainWindow.h\"\n#include \"configuration.h\"\n#include \"logging.h\"\n#include \n#include \n\n\/* SDL does ugly things to main() *\/\n#ifdef main\n#undef main\n#endif\n\n\n\/\/ Install a message handler so you do not need\n\/\/ the MSFT debug tools installed to se\n\/\/ qDebug(), qWarning(), qCritical and qAbort\n#ifdef Q_OS_WIN\nvoid msgHandler( QtMsgType type, const char* msg )\n{\n const char symbols[] = { 'I', 'E', '!', 'X' };\n QString output = QString(\"[%1] %2\").arg( symbols[type] ).arg( msg );\n std::cerr << output.toStdString() << std::endl;\n if( type == QtFatalMsg ) abort();\n}\n#endif\n\n\/\/ Path for file logging\nstatic QString sLogPath;\n\n\/\/ Message handler for logging provides console and file output\n\/\/ The handler itself has to be reentrant and threadsafe!\nvoid loggingMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)\n{\n \/\/ The message handler has to be thread safe\n static QMutex mutex;\n QMutexLocker localLoc(&mutex);\n\n static std::ofstream logFile(sLogPath.toStdString().c_str(), std::ofstream::out | std::ofstream::app);\n\n QString outMessage(qFormatLogMessage(type, context, message)); \/\/ just format only once\n if(logFile)\n {\n logFile << qPrintable(outMessage) << std::endl; \/\/ log to file\n }\n\n LogWindowSingleton::instance().write(outMessage); \/\/ log to debug window\n\n fprintf(stderr, \"%s\\n\", qPrintable(outMessage)); \/\/ log to console\n}\n\n\n\/**\n * @brief Starts the application\n *\n * @param argc Number of commandline arguments\n * @param argv Commandline arguments\n * @return exit code, 0 for normal exit and !=0 for error cases\n *\/\nint main(int argc, char *argv[])\n{\n\/\/ install the message handler\n#ifdef Q_OS_WIN\n \/\/qInstallMsgHandler( msgHandler );\n#endif\n \/\/ Init application\n QGCCore core(argc, argv);\n\n \/\/ Init logging\n \/\/ create filename and path for logfile like \"apmlog_20160529.txt\"\n \/\/ one logfile for every day. Size is not limited\n QString logFileName(\"apmlog_\");\n logFileName.append(QDateTime::currentDateTime().toString(\"yyyyMMdd\"));\n logFileName.append(\".txt\");\n sLogPath = QString(QDir(QGC::appDataDirectory()).filePath(logFileName));\n\n \/\/ Just keep the 5 recent logfiles and delete the rest.\n QDir logDirectory(QGC::appDataDirectory(), \"apmlog*\", QDir::Name, QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);\n QStringList logFileList(logDirectory.entryList());\n \/\/ As the file list is sorted we can delete index 0 cause its the oldest one\n while(logFileList.size() > 5)\n {\n logDirectory.remove(logFileList.at(0));\n logFileList.pop_front();\n }\n\n \/\/ Add sperator for better orientation in Logfiles\n std::ofstream logFile(sLogPath.toStdString().c_str(), std::ofstream::out | std::ofstream::app);\n if (logFile)\n {\n logFile << std::endl << std::endl << \"**************************************************\" << std::endl << std::endl;\n logFile.close();\n }\n\n \/\/ set up logging pattern\n#if QT_VERSION < QT_VERSION_CHECK(5, 5, 0)\n \/\/ QT < 5.5.x does not support qInfo() logging macro and no info-formatting too\n QString logPattern(\"[%{time yyyyMMdd h:mm:ss.zzz} %{if-debug}DEBUG%{endif}%{if-warning}WARN %{endif}%{if-critical}ERROR%{endif}%{if-fatal}FATAL%{endif}] - %{message}\");\n#else\n QString logPattern(\"[%{time yyyyMMdd h:mm:ss.zzz} %{if-debug}DEBUG%{endif}%{if-info}INFO %{endif}%{if-warning}WARN %{endif}%{if-critical}ERROR%{endif}%{if-fatal}FATAL%{endif}] - %{message}\");\n#endif\n\n qSetMessagePattern(logPattern);\n\n \/\/ install the message handler for logging\n qInstallMessageHandler(loggingMessageHandler);\n\n \/\/ start the application\n core.initialize();\n return core.exec();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"include\/dart_api.h\"\n#include \"include\/dart_native_api.h\"\n\n#include \"vm\/unit_test.h\"\n\n\/\/ Custom Isolate Test.\n\/\/\n\/\/ This mid-size test uses the Dart Embedding Api to create a custom\n\/\/ isolate abstraction. Instead of having a dedicated thread for each\n\/\/ isolate, as is the case normally, this implementation shares a\n\/\/ single thread among the isolates using an event queue.\n\nnamespace dart {\n\nDECLARE_FLAG(bool, trace_shutdown);\n\nstatic void native_echo(Dart_NativeArguments args);\nstatic void CustomIsolateImpl_start(Dart_NativeArguments args);\nstatic Dart_NativeFunction NativeLookup(Dart_Handle name,\n int argc,\n bool* auto_setup_scope);\n\n\nstatic const char* kCustomIsolateScriptChars =\n \"import 'dart:isolate';\\n\"\n \"\\n\"\n \"final RawReceivePort mainPort = new RawReceivePort();\\n\"\n \"final SendPort mainSendPort = mainPort.sendPort;\\n\"\n \"\\n\"\n \"echo(arg) native \\\"native_echo\\\";\\n\"\n \"\\n\"\n \"class CustomIsolateImpl implements CustomIsolate {\\n\"\n \" CustomIsolateImpl(String entry) : _entry = entry{\\n\"\n \" echo('Constructing isolate');\\n\"\n \" }\\n\"\n \"\\n\"\n \" SendPort spawn() {\\n\"\n \" return _start(_entry);\\n\"\n \" }\\n\"\n \"\\n\"\n \" static SendPort _start(entry)\\n\"\n \" native \\\"CustomIsolateImpl_start\\\";\\n\"\n \"\\n\"\n \" String _entry;\\n\"\n \"}\\n\"\n \"\\n\"\n \"abstract class CustomIsolate {\\n\"\n \" factory CustomIsolate(String entry) = CustomIsolateImpl;\\n\"\n \"\\n\"\n \" SendPort spawn();\\n\"\n \"}\\n\"\n \"\\n\"\n \"isolateMain() {\\n\"\n \" echo('Running isolateMain');\\n\"\n \" mainPort.handler = (message) {\\n\"\n \" var data = message[0];\\n\"\n \" var replyTo = message[1];\\n\"\n \" echo('Received: $data');\\n\"\n \" replyTo.send(data + 1);\\n\"\n \" mainPort.close();\\n\"\n \" };\\n\"\n \"}\\n\"\n \"\\n\"\n \"main() {\\n\"\n \" var isolate = new CustomIsolate(\\\"isolateMain\\\");\\n\"\n \" var receivePort = new RawReceivePort();\\n\"\n \" SendPort port = isolate.spawn();\\n\"\n \" port.send([42, receivePort.sendPort]);\\n\"\n \" receivePort.handler = (message) {\\n\"\n \" receivePort.close();\\n\"\n \" echo('Received: $message');\\n\"\n \" };\\n\"\n \" return 'success';\\n\"\n \"}\\n\";\n\n\n\/\/ An entry in our event queue.\nclass Event {\n protected:\n explicit Event(Dart_Isolate isolate) : isolate_(isolate), next_(NULL) {}\n\n public:\n virtual ~Event() {}\n virtual void Process() = 0;\n\n Dart_Isolate isolate() const { return isolate_; }\n\n private:\n friend class EventQueue;\n Dart_Isolate isolate_;\n Event* next_;\n};\n\n\n\/\/ A simple event queue for our test.\nclass EventQueue {\n public:\n EventQueue() {\n head_ = NULL;\n }\n\n void Add(Event* event) {\n if (head_ == NULL) {\n head_ = event;\n tail_ = event;\n } else {\n tail_->next_ = event;\n tail_ = event;\n }\n }\n\n Event* Get() {\n if (head_ == NULL) {\n return NULL;\n }\n Event* tmp = head_;\n head_ = head_->next_;\n if (head_ == NULL) {\n \/\/ Not necessary, but why not.\n tail_ = NULL;\n }\n\n return tmp;\n }\n\n void RemoveEventsForIsolate(Dart_Isolate isolate) {\n Event* cur = head_;\n Event* prev = NULL;\n while (cur != NULL) {\n Event* next = cur->next_;\n if (cur->isolate() == isolate) {\n \/\/ Remove matching event.\n if (prev != NULL) {\n prev->next_ = next;\n } else {\n head_ = next;\n }\n delete cur;\n } else {\n \/\/ Advance.\n prev = cur;\n }\n cur = next;\n }\n tail_ = prev;\n }\n\n private:\n Event* head_;\n Event* tail_;\n};\nEventQueue* event_queue;\n\n\n\/\/ Start an isolate.\nclass StartEvent : public Event {\n public:\n StartEvent(Dart_Isolate isolate, const char* main)\n : Event(isolate), main_(main) {}\n\n virtual void Process();\n private:\n const char* main_;\n};\n\n\nvoid StartEvent::Process() {\n OS::Print(\">> StartEvent with isolate(%p)--\\n\", isolate());\n Dart_EnterIsolate(isolate());\n Dart_EnterScope();\n Dart_Handle result;\n\n Dart_Handle lib = Dart_LookupLibrary(NewString(TestCase::url()));\n EXPECT_VALID(lib);\n\n result = Dart_Invoke(lib, NewString(main_), 0, NULL);\n EXPECT_VALID(result);\n free(const_cast(main_));\n main_ = NULL;\n\n Dart_SetMessageNotifyCallback(NULL);\n Dart_ExitScope();\n Dart_ExitIsolate();\n}\n\n\n\/\/ Notify an isolate of a pending message.\nclass MessageEvent : public Event {\n public:\n explicit MessageEvent(Dart_Isolate isolate) : Event(isolate) {}\n\n ~MessageEvent() {\n }\n\n virtual void Process();\n};\n\n\nvoid MessageEvent::Process() {\n OS::Print(\"$$ MessageEvent with isolate(%p)\\n\", isolate());\n Dart_EnterIsolate(isolate());\n Dart_EnterScope();\n\n Dart_Handle result = Dart_HandleMessage();\n EXPECT_VALID(result);\n\n if (!Dart_HasLivePorts()) {\n OS::Print(\"<< Shutting down isolate(%p)\\n\", isolate());\n event_queue->RemoveEventsForIsolate(isolate());\n Dart_SetMessageNotifyCallback(NULL);\n Dart_ExitScope();\n Dart_ShutdownIsolate();\n } else {\n Dart_ExitScope();\n Dart_ExitIsolate();\n }\n ASSERT(Dart_CurrentIsolate() == NULL);\n}\n\n\nstatic void NotifyMessage(Dart_Isolate dest_isolate) {\n OS::Print(\"-- Notify isolate(%p) of pending message --\\n\", dest_isolate);\n OS::Print(\"-- Adding MessageEvent to queue --\\n\");\n event_queue->Add(new MessageEvent(dest_isolate));\n}\n\n\nstatic Dart_NativeFunction NativeLookup(Dart_Handle name,\n int argc,\n bool* auto_setup_scope) {\n ASSERT(auto_setup_scope != NULL);\n *auto_setup_scope = true;\n const char* name_str = NULL;\n EXPECT(Dart_IsString(name));\n EXPECT_VALID(Dart_StringToCString(name, &name_str));\n if (strcmp(name_str, \"native_echo\") == 0) {\n return &native_echo;\n } else if (strcmp(name_str, \"CustomIsolateImpl_start\") == 0) {\n return &CustomIsolateImpl_start;\n }\n return NULL;\n}\n\n\nchar* saved_echo = NULL;\nstatic void native_echo(Dart_NativeArguments args) {\n Dart_EnterScope();\n Dart_Handle arg = Dart_GetNativeArgument(args, 0);\n Dart_Handle toString = Dart_ToString(arg);\n EXPECT_VALID(toString);\n const char* c_str = NULL;\n EXPECT_VALID(Dart_StringToCString(toString, &c_str));\n if (saved_echo) {\n free(saved_echo);\n }\n saved_echo = strdup(c_str);\n OS::Print(\"-- (isolate=%p) %s\\n\", Dart_CurrentIsolate(), c_str);\n Dart_ExitScope();\n}\n\n\nstatic void CustomIsolateImpl_start(Dart_NativeArguments args) {\n OS::Print(\"-- Enter: CustomIsolateImpl_start --\\n\");\n\n \/\/ We would probably want to pass in the this pointer too, so we\n \/\/ could associate the CustomIsolateImpl instance with the\n \/\/ Dart_Isolate by storing it in a native field.\n EXPECT_EQ(1, Dart_GetNativeArgumentCount(args));\n Dart_Handle param = Dart_GetNativeArgument(args, 0);\n EXPECT_VALID(param);\n EXPECT(Dart_IsString(param));\n const char* isolate_main = NULL;\n EXPECT_VALID(Dart_StringToCString(param, &isolate_main));\n isolate_main = strdup(isolate_main);\n\n \/\/ Save current isolate.\n Dart_Isolate saved_isolate = Dart_CurrentIsolate();\n Dart_ExitIsolate();\n\n \/\/ Create a new Dart_Isolate.\n Dart_Isolate new_isolate = TestCase::CreateTestIsolate();\n EXPECT(new_isolate != NULL);\n Dart_SetMessageNotifyCallback(&NotifyMessage);\n Dart_EnterScope();\n \/\/ Reload all the test classes here.\n \/\/\n \/\/ TODO(turnidge): Use the create isolate callback instead?\n Dart_Handle lib = TestCase::LoadTestScript(kCustomIsolateScriptChars,\n NativeLookup);\n EXPECT_VALID(lib);\n\n Dart_Handle main_send_port = Dart_GetField(lib, NewString(\"mainSendPort\"));\n EXPECT_VALID(main_send_port);\n Dart_Port main_port_id;\n Dart_Handle err = Dart_SendPortGetId(main_send_port, &main_port_id);\n EXPECT_VALID(err);\n\n OS::Print(\"-- Adding StartEvent to queue --\\n\");\n event_queue->Add(new StartEvent(new_isolate, isolate_main));\n\n \/\/ Restore the original isolate.\n Dart_ExitScope();\n Dart_ExitIsolate();\n Dart_EnterIsolate(saved_isolate);\n Dart_EnterScope();\n\n Dart_Handle send_port = Dart_NewSendPort(main_port_id);\n EXPECT_VALID(send_port);\n Dart_SetReturnValue(args, send_port);\n\n OS::Print(\"-- Exit: CustomIsolateImpl_start --\\n\");\n Dart_ExitScope();\n}\n\n\nUNIT_TEST_CASE(CustomIsolates) {\n bool saved_flag = FLAG_trace_shutdown;\n FLAG_trace_shutdown = true;\n FLAG_verify_handles = true;\n#ifdef DEBUG\n FLAG_verify_on_transition = true;\n#endif\n event_queue = new EventQueue();\n\n Dart_Isolate dart_isolate = TestCase::CreateTestIsolate();\n EXPECT(dart_isolate != NULL);\n Dart_SetMessageNotifyCallback(&NotifyMessage);\n Dart_EnterScope();\n Dart_Handle result;\n\n \/\/ Create a test library.\n Dart_Handle lib = TestCase::LoadTestScript(kCustomIsolateScriptChars,\n NativeLookup);\n EXPECT_VALID(lib);\n\n \/\/ Run main.\n result = Dart_Invoke(lib, NewString(\"main\"), 0, NULL);\n EXPECT_VALID(result);\n EXPECT(Dart_IsString(result));\n const char* result_str = NULL;\n EXPECT_VALID(Dart_StringToCString(result, &result_str));\n EXPECT_STREQ(\"success\", result_str);\n\n Dart_ExitScope();\n Dart_ExitIsolate();\n\n OS::Print(\"-- Starting event loop --\\n\");\n Event* event = event_queue->Get();\n while (event) {\n event->Process();\n delete event;\n event = event_queue->Get();\n }\n OS::Print(\"-- Finished event loop --\\n\");\n EXPECT_STREQ(\"Received: 43\", saved_echo);\n free(saved_echo);\n\n delete event_queue;\n event_queue = NULL;\n FLAG_trace_shutdown = saved_flag;\n}\n\n} \/\/ namespace dart\nFix crash by disabling problematic functionalitie (VerifyPointers)\/\/ Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"include\/dart_api.h\"\n#include \"include\/dart_native_api.h\"\n\n#include \"vm\/unit_test.h\"\n\n\/\/ Custom Isolate Test.\n\/\/\n\/\/ This mid-size test uses the Dart Embedding Api to create a custom\n\/\/ isolate abstraction. Instead of having a dedicated thread for each\n\/\/ isolate, as is the case normally, this implementation shares a\n\/\/ single thread among the isolates using an event queue.\n\nnamespace dart {\n\nDECLARE_FLAG(bool, trace_shutdown);\n\nstatic void native_echo(Dart_NativeArguments args);\nstatic void CustomIsolateImpl_start(Dart_NativeArguments args);\nstatic Dart_NativeFunction NativeLookup(Dart_Handle name,\n int argc,\n bool* auto_setup_scope);\n\n\nstatic const char* kCustomIsolateScriptChars =\n \"import 'dart:isolate';\\n\"\n \"\\n\"\n \"final RawReceivePort mainPort = new RawReceivePort();\\n\"\n \"final SendPort mainSendPort = mainPort.sendPort;\\n\"\n \"\\n\"\n \"echo(arg) native \\\"native_echo\\\";\\n\"\n \"\\n\"\n \"class CustomIsolateImpl implements CustomIsolate {\\n\"\n \" CustomIsolateImpl(String entry) : _entry = entry{\\n\"\n \" echo('Constructing isolate');\\n\"\n \" }\\n\"\n \"\\n\"\n \" SendPort spawn() {\\n\"\n \" return _start(_entry);\\n\"\n \" }\\n\"\n \"\\n\"\n \" static SendPort _start(entry)\\n\"\n \" native \\\"CustomIsolateImpl_start\\\";\\n\"\n \"\\n\"\n \" String _entry;\\n\"\n \"}\\n\"\n \"\\n\"\n \"abstract class CustomIsolate {\\n\"\n \" factory CustomIsolate(String entry) = CustomIsolateImpl;\\n\"\n \"\\n\"\n \" SendPort spawn();\\n\"\n \"}\\n\"\n \"\\n\"\n \"isolateMain() {\\n\"\n \" echo('Running isolateMain');\\n\"\n \" mainPort.handler = (message) {\\n\"\n \" var data = message[0];\\n\"\n \" var replyTo = message[1];\\n\"\n \" echo('Received: $data');\\n\"\n \" replyTo.send(data + 1);\\n\"\n \" mainPort.close();\\n\"\n \" };\\n\"\n \"}\\n\"\n \"\\n\"\n \"main() {\\n\"\n \" var isolate = new CustomIsolate(\\\"isolateMain\\\");\\n\"\n \" var receivePort = new RawReceivePort();\\n\"\n \" SendPort port = isolate.spawn();\\n\"\n \" port.send([42, receivePort.sendPort]);\\n\"\n \" receivePort.handler = (message) {\\n\"\n \" receivePort.close();\\n\"\n \" echo('Received: $message');\\n\"\n \" };\\n\"\n \" return 'success';\\n\"\n \"}\\n\";\n\n\n\/\/ An entry in our event queue.\nclass Event {\n protected:\n explicit Event(Dart_Isolate isolate) : isolate_(isolate), next_(NULL) {}\n\n public:\n virtual ~Event() {}\n virtual void Process() = 0;\n\n Dart_Isolate isolate() const { return isolate_; }\n\n private:\n friend class EventQueue;\n Dart_Isolate isolate_;\n Event* next_;\n};\n\n\n\/\/ A simple event queue for our test.\nclass EventQueue {\n public:\n EventQueue() {\n head_ = NULL;\n }\n\n void Add(Event* event) {\n if (head_ == NULL) {\n head_ = event;\n tail_ = event;\n } else {\n tail_->next_ = event;\n tail_ = event;\n }\n }\n\n Event* Get() {\n if (head_ == NULL) {\n return NULL;\n }\n Event* tmp = head_;\n head_ = head_->next_;\n if (head_ == NULL) {\n \/\/ Not necessary, but why not.\n tail_ = NULL;\n }\n\n return tmp;\n }\n\n void RemoveEventsForIsolate(Dart_Isolate isolate) {\n Event* cur = head_;\n Event* prev = NULL;\n while (cur != NULL) {\n Event* next = cur->next_;\n if (cur->isolate() == isolate) {\n \/\/ Remove matching event.\n if (prev != NULL) {\n prev->next_ = next;\n } else {\n head_ = next;\n }\n delete cur;\n } else {\n \/\/ Advance.\n prev = cur;\n }\n cur = next;\n }\n tail_ = prev;\n }\n\n private:\n Event* head_;\n Event* tail_;\n};\nEventQueue* event_queue;\n\n\n\/\/ Start an isolate.\nclass StartEvent : public Event {\n public:\n StartEvent(Dart_Isolate isolate, const char* main)\n : Event(isolate), main_(main) {}\n\n virtual void Process();\n private:\n const char* main_;\n};\n\n\nvoid StartEvent::Process() {\n OS::Print(\">> StartEvent with isolate(%p)--\\n\", isolate());\n Dart_EnterIsolate(isolate());\n Dart_EnterScope();\n Dart_Handle result;\n\n Dart_Handle lib = Dart_LookupLibrary(NewString(TestCase::url()));\n EXPECT_VALID(lib);\n\n result = Dart_Invoke(lib, NewString(main_), 0, NULL);\n EXPECT_VALID(result);\n free(const_cast(main_));\n main_ = NULL;\n\n Dart_SetMessageNotifyCallback(NULL);\n Dart_ExitScope();\n Dart_ExitIsolate();\n}\n\n\n\/\/ Notify an isolate of a pending message.\nclass MessageEvent : public Event {\n public:\n explicit MessageEvent(Dart_Isolate isolate) : Event(isolate) {}\n\n ~MessageEvent() {\n }\n\n virtual void Process();\n};\n\n\nvoid MessageEvent::Process() {\n OS::Print(\"$$ MessageEvent with isolate(%p)\\n\", isolate());\n Dart_EnterIsolate(isolate());\n Dart_EnterScope();\n\n Dart_Handle result = Dart_HandleMessage();\n EXPECT_VALID(result);\n\n if (!Dart_HasLivePorts()) {\n OS::Print(\"<< Shutting down isolate(%p)\\n\", isolate());\n event_queue->RemoveEventsForIsolate(isolate());\n Dart_SetMessageNotifyCallback(NULL);\n Dart_ExitScope();\n Dart_ShutdownIsolate();\n } else {\n Dart_ExitScope();\n Dart_ExitIsolate();\n }\n ASSERT(Dart_CurrentIsolate() == NULL);\n}\n\n\nstatic void NotifyMessage(Dart_Isolate dest_isolate) {\n OS::Print(\"-- Notify isolate(%p) of pending message --\\n\", dest_isolate);\n OS::Print(\"-- Adding MessageEvent to queue --\\n\");\n event_queue->Add(new MessageEvent(dest_isolate));\n}\n\n\nstatic Dart_NativeFunction NativeLookup(Dart_Handle name,\n int argc,\n bool* auto_setup_scope) {\n ASSERT(auto_setup_scope != NULL);\n *auto_setup_scope = true;\n const char* name_str = NULL;\n EXPECT(Dart_IsString(name));\n EXPECT_VALID(Dart_StringToCString(name, &name_str));\n if (strcmp(name_str, \"native_echo\") == 0) {\n return &native_echo;\n } else if (strcmp(name_str, \"CustomIsolateImpl_start\") == 0) {\n return &CustomIsolateImpl_start;\n }\n return NULL;\n}\n\n\nchar* saved_echo = NULL;\nstatic void native_echo(Dart_NativeArguments args) {\n Dart_EnterScope();\n Dart_Handle arg = Dart_GetNativeArgument(args, 0);\n Dart_Handle toString = Dart_ToString(arg);\n EXPECT_VALID(toString);\n const char* c_str = NULL;\n EXPECT_VALID(Dart_StringToCString(toString, &c_str));\n if (saved_echo) {\n free(saved_echo);\n }\n saved_echo = strdup(c_str);\n OS::Print(\"-- (isolate=%p) %s\\n\", Dart_CurrentIsolate(), c_str);\n Dart_ExitScope();\n}\n\n\nstatic void CustomIsolateImpl_start(Dart_NativeArguments args) {\n OS::Print(\"-- Enter: CustomIsolateImpl_start --\\n\");\n\n \/\/ We would probably want to pass in the this pointer too, so we\n \/\/ could associate the CustomIsolateImpl instance with the\n \/\/ Dart_Isolate by storing it in a native field.\n EXPECT_EQ(1, Dart_GetNativeArgumentCount(args));\n Dart_Handle param = Dart_GetNativeArgument(args, 0);\n EXPECT_VALID(param);\n EXPECT(Dart_IsString(param));\n const char* isolate_main = NULL;\n EXPECT_VALID(Dart_StringToCString(param, &isolate_main));\n isolate_main = strdup(isolate_main);\n\n \/\/ Save current isolate.\n Dart_Isolate saved_isolate = Dart_CurrentIsolate();\n Dart_ExitIsolate();\n\n \/\/ Create a new Dart_Isolate.\n Dart_Isolate new_isolate = TestCase::CreateTestIsolate();\n EXPECT(new_isolate != NULL);\n Dart_SetMessageNotifyCallback(&NotifyMessage);\n Dart_EnterScope();\n \/\/ Reload all the test classes here.\n \/\/\n \/\/ TODO(turnidge): Use the create isolate callback instead?\n Dart_Handle lib = TestCase::LoadTestScript(kCustomIsolateScriptChars,\n NativeLookup);\n EXPECT_VALID(lib);\n\n Dart_Handle main_send_port = Dart_GetField(lib, NewString(\"mainSendPort\"));\n EXPECT_VALID(main_send_port);\n Dart_Port main_port_id;\n Dart_Handle err = Dart_SendPortGetId(main_send_port, &main_port_id);\n EXPECT_VALID(err);\n\n OS::Print(\"-- Adding StartEvent to queue --\\n\");\n event_queue->Add(new StartEvent(new_isolate, isolate_main));\n\n \/\/ Restore the original isolate.\n Dart_ExitScope();\n Dart_ExitIsolate();\n Dart_EnterIsolate(saved_isolate);\n Dart_EnterScope();\n\n Dart_Handle send_port = Dart_NewSendPort(main_port_id);\n EXPECT_VALID(send_port);\n Dart_SetReturnValue(args, send_port);\n\n OS::Print(\"-- Exit: CustomIsolateImpl_start --\\n\");\n Dart_ExitScope();\n}\n\n\nUNIT_TEST_CASE(CustomIsolates) {\n bool saved_flag = FLAG_trace_shutdown;\n FLAG_trace_shutdown = true;\n FLAG_verify_handles = true;\n#ifdef DEBUG\n FLAG_verify_on_transition = true;\n#endif\n \/\/ Cannot verify heap while running compilation in background.\n \/\/ Issue #26149.\n FLAG_background_compilation = false;\n \/\/ Issue #26150.\n FLAG_use_osr = false;\n\n event_queue = new EventQueue();\n\n Dart_Isolate dart_isolate = TestCase::CreateTestIsolate();\n EXPECT(dart_isolate != NULL);\n Dart_SetMessageNotifyCallback(&NotifyMessage);\n Dart_EnterScope();\n Dart_Handle result;\n\n \/\/ Create a test library.\n Dart_Handle lib = TestCase::LoadTestScript(kCustomIsolateScriptChars,\n NativeLookup);\n EXPECT_VALID(lib);\n\n \/\/ Run main.\n result = Dart_Invoke(lib, NewString(\"main\"), 0, NULL);\n EXPECT_VALID(result);\n EXPECT(Dart_IsString(result));\n const char* result_str = NULL;\n EXPECT_VALID(Dart_StringToCString(result, &result_str));\n EXPECT_STREQ(\"success\", result_str);\n\n Dart_ExitScope();\n Dart_ExitIsolate();\n\n OS::Print(\"-- Starting event loop --\\n\");\n Event* event = event_queue->Get();\n while (event) {\n event->Process();\n delete event;\n event = event_queue->Get();\n }\n OS::Print(\"-- Finished event loop --\\n\");\n EXPECT_STREQ(\"Received: 43\", saved_echo);\n free(saved_echo);\n\n delete event_queue;\n event_queue = NULL;\n FLAG_trace_shutdown = saved_flag;\n}\n\n} \/\/ namespace dart\n<|endoftext|>"} {"text":"\/* -------------------------------------------------------------------------- *\n * OpenSim: testExampleMain.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2012 Stanford University and the Authors *\n * Author(s): Cassidy Kelly *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n\/\/ Author: Cassidy Kelly\n\n\/\/==============================================================================\n\/\/==============================================================================\n\n#include \n#include \n\nusing namespace OpenSim;\nusing namespace std;\n\nint main()\n{\n try {\n Storage result1(\"tugOfWar_states.mot\"), \n standard1(\"std_tugOfWar_states.sto\");\n CHECK_STORAGE_AGAINST_STANDARD(result1, standard1, \n Array(0.1, 16), \n __FILE__, \n __LINE__, \n \"tugOfWar states failed\");\n cout << \"tugOfWar states passed\\n\";\n\n Storage result3(\"tugOfWar_forces.mot\"), \n standard3(\"std_tugOfWar_forces.mot\");\n \n Array tols(1.0, 20);\n \/\/ 10N is 1% of the muscles maximum isometric force\n tols[0] = tols[1] = 10;\n\n CHECK_STORAGE_AGAINST_STANDARD(result3, standard3, \n tols, \n __FILE__, \n __LINE__, \n \"tugOfWar forces failed\");\n cout << \"tugOfWar forces passed\\n\";\n }\n catch (const Exception& e) {\n e.print(cerr);\n return 1;\n }\n cout << \"Done\" << endl;\n return 0;\n}\nFix file extensions. Should be sto.\/* -------------------------------------------------------------------------- *\n * OpenSim: testExampleMain.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2012 Stanford University and the Authors *\n * Author(s): Cassidy Kelly *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n\/\/ Author: Cassidy Kelly\n\n\/\/==============================================================================\n\/\/==============================================================================\n\n#include \n#include \n\nusing namespace OpenSim;\nusing namespace std;\n\nint main()\n{\n try {\n Storage result1(\"tugOfWar_states.sto\"), \n standard1(\"std_tugOfWar_states.sto\");\n CHECK_STORAGE_AGAINST_STANDARD(result1, standard1, \n Array(0.1, 16), \n __FILE__, \n __LINE__, \n \"tugOfWar states failed\");\n cout << \"tugOfWar states passed\\n\";\n\n Storage result3(\"tugOfWar_forces.sto\"), \n standard3(\"std_tugOfWar_forces.mot\");\n \n Array tols(1.0, 20);\n \/\/ 10N is 1% of the muscles maximum isometric force\n tols[0] = tols[1] = 10;\n\n CHECK_STORAGE_AGAINST_STANDARD(result3, standard3, \n tols, \n __FILE__, \n __LINE__, \n \"tugOfWar forces failed\");\n cout << \"tugOfWar forces passed\\n\";\n }\n catch (const Exception& e) {\n e.print(cerr);\n return 1;\n }\n cout << \"Done\" << endl;\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ $Id$\n\/\/\n\/\/ Emcal physics selection class.\n\/\/\n\/\/ Author: C.Loizides\n\n#include \"AliEmcalPhysicsSelection.h\"\n#include \"AliAODEvent.h\"\n#include \"AliESDEvent.h\"\n#include \"AliLog.h\"\n\nClassImp(AliEmcalPhysicsSelection)\n\nAliEmcalPhysicsSelection::AliEmcalPhysicsSelection() : \n AliPhysicsSelection(), \n fMarkFastOnly(0), \n fMarkLedEvent(0),\n fSkipFastOnly(0), \n fSkipLedEvent(0),\n fCellMinE(-1), \n fClusMinE(-1),\n fTrackMinPt(-1), \n fTriggers(0),\n fZvertex(-1),\n fZvertexDiff(0),\n fCentMin(-1),\n fCentMax(-1),\n fIsFastOnly(0),\n fIsLedEvent(0),\n fIsGoodEvent(0),\n fCellMaxE(0), \n fClusMaxE(0),\n fTrackMaxPt(0)\n{\n \/\/ Default constructor.\n}\n\n\/\/__________________________________________________________________________________________________\nUInt_t AliEmcalPhysicsSelection::GetSelectionMask(const TObject* obj) \n{ \n \/\/ Calculate selection mask.\n \n const AliVEvent *ev = dynamic_cast(obj);\n if (!ev) {\n return 0;\n }\n\n UInt_t res = 0;\n const AliESDEvent *eev = dynamic_cast(obj);\n const AliAODEvent *aev = 0;\n if (eev) {\n res = IsCollisionCandidate(eev); \n } else {\n aev = dynamic_cast(obj);\n res = aev->GetHeader()->GetOfflineTrigger();\n }\n\n \/\/ return 0, if 0 found\n if (res==0)\n return 0;\n\n \/\/ return 0, if ptrs are not set\n if ((eev==0) && (aev==0))\n return 0;\n\n if (fTriggers) { \/\/ only process given triggers\n if ((res & fTriggers) == 0)\n return res;\n }\n\n AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();\n\n fIsFastOnly = kFALSE;\n fIsGoodEvent = kFALSE;\n fIsLedEvent = kFALSE;\n fCellMaxE = -1;\n fClusMaxE = -1;\n fTrackMaxPt = -1;\n\n if ((res & AliVEvent::kAnyINT) || \n (res & AliVEvent::kSemiCentral) || \n (res & AliVEvent::kCentral) || \n (res & AliVEvent::kEMC1) || \n (res & AliVEvent::kEMC7) || \n (res & AliVEvent::kEMCEJE) || \n (res & AliVEvent::kEMCEGA))\n fIsGoodEvent = kTRUE;\n\n if (fZvertexDiff || (fZvertex>0)) {\n Double_t vzPRI = +999;\n Double_t vzSPD = -999;\n const AliVVertex *pv = 0;\n if (eev)\n pv = eev->GetPrimaryVertex();\n else\n pv = aev->GetPrimaryVertex();\n if (pv && pv->GetNContributors()>0) {\n vzPRI = pv->GetZ();\n }\n const AliVVertex *sv = 0;\n if (eev)\n sv = eev->GetPrimaryVertexSPD();\n else \n sv = aev->GetPrimaryVertexSPD();\n if (sv && sv->GetNContributors()>0) {\n vzSPD = sv->GetZ();\n }\n Double_t dvertex = TMath::Abs(vzPRI-vzSPD);\n \/\/ skip events with dvertex<1mm if requested\n \/\/ https:\/\/indico.cern.ch\/getFile.py\/access?contribId=4&resId=0&materialId=slides&confId=189624\n \/\/ also check on vertex z if requested\n if (fZvertexDiff && (dvertex<0.1))\n fIsGoodEvent = kFALSE;\n if ((fZvertex>0) && (TMath::Abs(dvertex)>fZvertex))\n fIsGoodEvent = kFALSE;\n }\n\n if ((fCentMin>-1) && (fCentMax>-1)) {\n Double_t v0mcent = -1;\n AliCentrality *centin = 0;\n if (eev) {\n am->LoadBranch(\"Centrality.\");\n centin = dynamic_cast(eev->FindListObject(\"Centrality\"));\n } else {\n centin = const_cast(aev)->GetCentrality();\n }\n if (centin)\n v0mcent = centin->GetCentralityPercentileUnchecked(\"V0M\");\n if ((v0mcentfCentMax))\n fIsGoodEvent = kFALSE;\n }\n\n AliVCaloCells *cells = ev->GetEMCALCells();\n const Short_t nCells = cells->GetNumberOfCells();\n \n \/\/ mark LHC11a fast only partition if requested \n if (res & AliVEvent::kFastOnly) {\n fIsFastOnly = kTRUE;\n if (fMarkFastOnly||fSkipFastOnly) {\n if (nCells>0) {\n AliFatal(Form(\"Number of cells %d, even though EMCAL should not be in fast only partition.\",nCells));\n }\n fIsGoodEvent = kFALSE;\n }\n }\n\n if (fCellMinE>0) {\n if (eev)\n am->LoadBranch(\"EMCALCells.\");\n for(Int_t iCell=0; iCellGetCellNumber(iCell);\n Double_t cellE = cells->GetCellAmplitude(cellId);\n if (cellE>fCellMaxE)\n fCellMaxE = cellE;\n }\n }\n\n if (fClusMinE>0) {\n if (eev)\n am->LoadBranch(\"CaloClusters\");\n\n const Int_t nCaloClusters = ev->GetNumberOfCaloClusters();\n for(Int_t iClus = 0; iClusGetCaloCluster(iClus);\n if (!cl->IsEMCAL()) \n continue;\n Double_t e = cl->E();\n if (e>fClusMaxE)\n fClusMaxE = e;\n }\n }\n\n if (fTrackMinPt>0) {\n TClonesArray *trks = 0;\n if (eev) {\n am->LoadBranch(\"PicoTracks\");\n trks = dynamic_cast(eev->FindListObject(\"PicoTracks\"));\n if (!trks) {\n am->LoadBranch(\"Tracks\");\n trks = dynamic_cast(eev->FindListObject(\"Tracks\"));\n }\n } else {\n trks = dynamic_cast(aev->FindListObject(\"tracks\"));\n }\n const Int_t Ntracks = trks->GetEntriesFast();\n for (Int_t iTracks = 0; iTracks < Ntracks; ++iTracks) {\n AliVTrack *track = static_cast(trks->At(iTracks));\n if (!track)\n continue;\n if (aev) { \/\/ a bit ugly since cuts are hard coded for now\n AliAODTrack *aodtrack = static_cast(track);\n if (!aodtrack->TestFilterBit(256) && !aodtrack->TestFilterBit(512))\n continue;\n }\n Double_t pt = track->Pt();\n if (pt>fTrackMaxPt)\n fTrackMaxPt = pt;\n }\n }\n\n \/\/ bad cell criterion for LHC11a from \n \/\/ https:\/\/indico.cern.ch\/materialDisplay.py?contribId=4&materialId=slides&confId=147067\n const Int_t runN = ev->GetRunNumber();\n if ((runN>=144871) && (runN<=146860)) { \n\n if (eev)\n am->LoadBranch(\"EMCALCells.\");\n\n \/\/ count cells above threshold\n Int_t nCellCount[12] = {0,0,0,0,0,0,0,0,0,0,0,0};\n for(Int_t iCell=0; iCellGetCellNumber(iCell);\n Double_t cellE = cells->GetCellAmplitude(cellId);\n Int_t sm = cellId \/ (24*48);\n if (cellE>0.1)\n ++nCellCount[sm];\n }\n\n if (nCellCount[4] > 100)\n fIsLedEvent = kTRUE;\n else {\n if ((runN>=146858) && (runN<=146860)) {\n if ((res&AliVEvent::kMB) && (nCellCount[3]>=21))\n fIsLedEvent = kTRUE;\n else if ((res&AliVEvent::kEMC1) && (nCellCount[3]>=35))\n fIsLedEvent = kTRUE;\n }\n }\n if (fIsLedEvent) {\n fIsGoodEvent = kFALSE;\n }\n }\n\n if (fCellMaxE>fCellMinE)\n res |= kEmcalHC;\n\n if ((fClusMaxE>fClusMinE) || (fTrackMaxPt>fTrackMinPt))\n res |= kEmcalHT;\n\n if (fIsGoodEvent)\n res |= kEmcalOk;\n\n if ((fSkipLedEvent && fIsLedEvent) ||\n (fSkipFastOnly && fIsFastOnly))\n res = 0;\n\n return res;\n}\nfix to get emcalok working\/\/ $Id$\n\/\/\n\/\/ Emcal physics selection class.\n\/\/\n\/\/ Author: C.Loizides\n\n#include \"AliEmcalPhysicsSelection.h\"\n#include \"AliAODEvent.h\"\n#include \"AliESDEvent.h\"\n#include \"AliLog.h\"\n\nClassImp(AliEmcalPhysicsSelection)\n\nAliEmcalPhysicsSelection::AliEmcalPhysicsSelection() : \n AliPhysicsSelection(), \n fMarkFastOnly(0), \n fMarkLedEvent(0),\n fSkipFastOnly(0), \n fSkipLedEvent(0),\n fCellMinE(-1), \n fClusMinE(-1),\n fTrackMinPt(-1), \n fTriggers(0),\n fZvertex(-1),\n fZvertexDiff(0),\n fCentMin(-1),\n fCentMax(-1),\n fIsFastOnly(0),\n fIsLedEvent(0),\n fIsGoodEvent(0),\n fCellMaxE(0), \n fClusMaxE(0),\n fTrackMaxPt(0)\n{\n \/\/ Default constructor.\n}\n\n\/\/__________________________________________________________________________________________________\nUInt_t AliEmcalPhysicsSelection::GetSelectionMask(const TObject* obj) \n{ \n \/\/ Calculate selection mask.\n \n const AliVEvent *ev = dynamic_cast(obj);\n if (!ev) {\n return 0;\n }\n\n UInt_t res = 0;\n const AliESDEvent *eev = dynamic_cast(obj);\n const AliAODEvent *aev = 0;\n if (eev) {\n res = IsCollisionCandidate(eev); \n } else {\n aev = dynamic_cast(obj);\n res = aev->GetHeader()->GetOfflineTrigger();\n }\n\n \/\/ return 0, if 0 found\n if (res==0)\n return 0;\n\n \/\/ return 0, if ptrs are not set\n if ((eev==0) && (aev==0))\n return 0;\n\n if (fTriggers) { \/\/ only process given triggers\n if ((res & fTriggers) == 0)\n return res;\n }\n\n AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();\n\n fIsFastOnly = kFALSE;\n fIsGoodEvent = kFALSE;\n fIsLedEvent = kFALSE;\n fCellMaxE = -1;\n fClusMaxE = -1;\n fTrackMaxPt = -1;\n\n if ((res & AliVEvent::kAnyINT) || \n (res & AliVEvent::kSemiCentral) || \n (res & AliVEvent::kCentral) || \n (res & AliVEvent::kEMC1) || \n (res & AliVEvent::kEMC7) || \n (res & AliVEvent::kEMCEJE) || \n (res & AliVEvent::kEMCEGA))\n fIsGoodEvent = kTRUE;\n\n if (fZvertexDiff || (fZvertex>0)) {\n Double_t vzPRI = +999;\n Double_t vzSPD = -999;\n const AliVVertex *pv = 0;\n if (eev)\n pv = eev->GetPrimaryVertex();\n else\n pv = aev->GetPrimaryVertex();\n if (pv && pv->GetNContributors()>0) {\n vzPRI = pv->GetZ();\n }\n const AliVVertex *sv = 0;\n if (eev)\n sv = eev->GetPrimaryVertexSPD();\n else \n sv = aev->GetPrimaryVertexSPD();\n if (sv && sv->GetNContributors()>0) {\n vzSPD = sv->GetZ();\n }\n Double_t dvertex = TMath::Abs(vzPRI-vzSPD);\n \/\/ skip events with dvertex<1mm if requested\n \/\/ https:\/\/indico.cern.ch\/getFile.py\/access?contribId=4&resId=0&materialId=slides&confId=189624\n \/\/ also check on vertex z if requested\n if (fZvertexDiff && (dvertex<0.1))\n fIsGoodEvent = kFALSE;\n if ((fZvertex>0) && (TMath::Abs(dvertex)>fZvertex))\n fIsGoodEvent = kFALSE;\n }\n\n if ((fCentMin>-1) && (fCentMax>-1)) {\n Double_t v0mcent = -1;\n AliCentrality *centin = 0;\n if (eev) {\n am->LoadBranch(\"Centrality.\");\n centin = dynamic_cast(eev->FindListObject(\"Centrality\"));\n } else {\n centin = const_cast(aev)->GetCentrality();\n }\n if (centin)\n v0mcent = centin->GetCentralityPercentileUnchecked(\"V0M\");\n if ((v0mcentfCentMax))\n fIsGoodEvent = kFALSE;\n }\n\n AliVCaloCells *cells = ev->GetEMCALCells();\n const Short_t nCells = cells->GetNumberOfCells();\n \n \/\/ mark LHC11a fast only partition if requested \n if (res & AliVEvent::kFastOnly) {\n fIsFastOnly = kTRUE;\n if (fMarkFastOnly||fSkipFastOnly) {\n if (nCells>0) {\n AliFatal(Form(\"Number of cells %d, even though EMCAL should not be in fast only partition.\",nCells));\n }\n fIsGoodEvent = kFALSE;\n }\n }\n\n if (fCellMinE>0) {\n if (eev)\n am->LoadBranch(\"EMCALCells.\");\n for(Int_t iCell=0; iCellGetCellNumber(iCell);\n Double_t cellE = cells->GetCellAmplitude(cellId);\n if (cellE>fCellMaxE)\n fCellMaxE = cellE;\n }\n }\n\n if (fClusMinE>0) {\n if (eev)\n am->LoadBranch(\"CaloClusters\");\n\n const Int_t nCaloClusters = ev->GetNumberOfCaloClusters();\n for(Int_t iClus = 0; iClusGetCaloCluster(iClus);\n if (!cl->IsEMCAL()) \n continue;\n Double_t e = cl->E();\n if (e>fClusMaxE)\n fClusMaxE = e;\n }\n }\n\n if (fTrackMinPt>0) {\n TClonesArray *trks = 0;\n if (eev) {\n am->LoadBranch(\"PicoTracks\");\n trks = dynamic_cast(eev->FindListObject(\"PicoTracks\"));\n if (!trks) {\n am->LoadBranch(\"Tracks\");\n trks = dynamic_cast(eev->FindListObject(\"Tracks\"));\n }\n } else {\n trks = dynamic_cast(aev->FindListObject(\"tracks\"));\n }\n const Int_t Ntracks = trks->GetEntriesFast();\n for (Int_t iTracks = 0; iTracks < Ntracks; ++iTracks) {\n AliVTrack *track = static_cast(trks->At(iTracks));\n if (!track)\n continue;\n if (aev) { \/\/ a bit ugly since cuts are hard coded for now\n AliAODTrack *aodtrack = static_cast(track);\n if (!aodtrack->TestFilterBit(256) && !aodtrack->TestFilterBit(512))\n continue;\n }\n Double_t pt = track->Pt();\n if (pt>fTrackMaxPt)\n fTrackMaxPt = pt;\n }\n }\n\n \/\/ bad cell criterion for LHC11a from \n \/\/ https:\/\/indico.cern.ch\/materialDisplay.py?contribId=4&materialId=slides&confId=147067\n const Int_t runN = ev->GetRunNumber();\n if ((runN>=144871) && (runN<=146860)) { \n\n if (eev)\n am->LoadBranch(\"EMCALCells.\");\n\n \/\/ count cells above threshold\n Int_t nCellCount[12] = {0,0,0,0,0,0,0,0,0,0,0,0};\n for(Int_t iCell=0; iCellGetCellNumber(iCell);\n Double_t cellE = cells->GetCellAmplitude(cellId);\n Int_t sm = cellId \/ (24*48);\n if (cellE>0.1)\n ++nCellCount[sm];\n }\n\n if (nCellCount[4] > 100)\n fIsLedEvent = kTRUE;\n else {\n if ((runN>=146858) && (runN<=146860)) {\n if ((res&AliVEvent::kMB) && (nCellCount[3]>=21))\n fIsLedEvent = kTRUE;\n else if ((res&AliVEvent::kEMC1) && (nCellCount[3]>=35))\n fIsLedEvent = kTRUE;\n }\n }\n if (fIsLedEvent) {\n fIsGoodEvent = kFALSE;\n }\n }\n\n if (fIsGoodEvent) {\n if (fCellMaxE>fCellMinE)\n res |= kEmcalHC;\n if ((fClusMaxE>fClusMinE) || (fTrackMaxPt>fTrackMinPt))\n res |= kEmcalHT;\n res |= kEmcalOk;\n }\n\n if ((fSkipLedEvent && fIsLedEvent) ||\n (fSkipFastOnly && fIsFastOnly))\n res = 0;\n\n return res;\n}\n<|endoftext|>"} {"text":"#include \"bitcoinunits.h\"\n\n#include \n\nBitcoinUnits::BitcoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList BitcoinUnits::availableUnits()\n{\n QList unitlist;\n unitlist.append(BTC);\n unitlist.append(mBTC);\n unitlist.append(uBTC);\n return unitlist;\n}\n\nbool BitcoinUnits::valid(int unit)\n{\n switch(unit)\n {\n case BTC:\n case mBTC:\n case uBTC:\n return true;\n default:\n return false;\n }\n}\n\nQString BitcoinUnits::name(int unit)\n{\n switch(unit)\n {\n case BTC: return QString(\"BTC\");\n case mBTC: return QString(\"mBTC\");\n case uBTC: return QString::fromUtf8(\"μBTC\");\n default: return QString(\"???\");\n }\n}\n\nQString BitcoinUnits::description(int unit)\n{\n switch(unit)\n {\n case BTC: return QString(\"Bitcoins\");\n case mBTC: return QString(\"Milli-Bitcoins (1 \/ 1,000)\");\n case uBTC: return QString(\"Micro-Bitcoins (1 \/ 1,000,000)\");\n default: return QString(\"???\");\n }\n}\n\nqint64 BitcoinUnits::factor(int unit)\n{\n switch(unit)\n {\n case BTC: return 100000000;\n case mBTC: return 100000;\n case uBTC: return 100;\n default: return 100000000;\n }\n}\n\nint BitcoinUnits::amountDigits(int unit)\n{\n switch(unit)\n {\n case BTC: return 8; \/\/ 21,000,000 (# digits, without commas)\n case mBTC: return 11; \/\/ 21,000,000,000\n case uBTC: return 14; \/\/ 21,000,000,000,000\n default: return 0;\n }\n}\n\nint BitcoinUnits::decimals(int unit)\n{\n switch(unit)\n {\n case BTC: return 8;\n case mBTC: return 5;\n case uBTC: return 2;\n default: return 0;\n }\n}\n\nQString BitcoinUnits::format(int unit, qint64 n, bool fPlus)\n{\n \/\/ Note: not using straight sprintf here because we do NOT want\n \/\/ localized number formatting.\n if(!valid(unit))\n return QString(); \/\/ Refuse to format invalid unit\n qint64 coin = factor(unit);\n int num_decimals = decimals(unit);\n qint64 n_abs = (n > 0 ? n : -n);\n qint64 quotient = n_abs \/ coin;\n qint64 remainder = n_abs % coin;\n QString quotient_str = QString::number(quotient);\n QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n \/\/ Right-trim excess 0's after the decimal point\n int nTrim = 0;\n for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)\n ++nTrim;\n remainder_str.chop(nTrim);\n\n if (n < 0)\n quotient_str.insert(0, '-');\n else if (fPlus && n > 0)\n quotient_str.insert(0, '+');\n return quotient_str + QString(\".\") + remainder_str;\n}\n\nQString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)\n{\n return format(unit, amount, plussign) + QString(\" \") + name(unit);\n}\n\nbool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)\n{\n if(!valid(unit))\n return false; \/\/ Refuse to parse invalid unit\n int num_decimals = decimals(unit);\n QStringList parts = value.split(\".\");\n if(parts.size() != 2 || parts.at(1).size() > num_decimals)\n return false; \/\/ Max num decimals\n bool ok = false;\n QString str = parts[0] + parts[1].leftJustified(num_decimals, '0');\n if(str.size()>18)\n return false; \/\/ Bounds check\n\n qint64 retvalue = str.toLongLong(&ok);\n if(val_out)\n {\n *val_out = retvalue;\n }\n return ok;\n}\n\nint BitcoinUnits::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return unitlist.size();\n}\n\nQVariant BitcoinUnits::data(const QModelIndex &index, int role) const\n{\n int row = index.row();\n if(row >= 0 && row < unitlist.size())\n {\n Unit unit = unitlist.at(row);\n switch(role)\n {\n case Qt::EditRole:\n case Qt::DisplayRole:\n return QVariant(name(unit));\n case Qt::ToolTipRole:\n return QVariant(description(unit));\n case UnitRole:\n return QVariant(static_cast(unit));\n }\n }\n return QVariant();\n}\nalso accept numbers without dot\/decimals for parsing, fixes transaction filter row#include \"bitcoinunits.h\"\n\n#include \n\nBitcoinUnits::BitcoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList BitcoinUnits::availableUnits()\n{\n QList unitlist;\n unitlist.append(BTC);\n unitlist.append(mBTC);\n unitlist.append(uBTC);\n return unitlist;\n}\n\nbool BitcoinUnits::valid(int unit)\n{\n switch(unit)\n {\n case BTC:\n case mBTC:\n case uBTC:\n return true;\n default:\n return false;\n }\n}\n\nQString BitcoinUnits::name(int unit)\n{\n switch(unit)\n {\n case BTC: return QString(\"BTC\");\n case mBTC: return QString(\"mBTC\");\n case uBTC: return QString::fromUtf8(\"μBTC\");\n default: return QString(\"???\");\n }\n}\n\nQString BitcoinUnits::description(int unit)\n{\n switch(unit)\n {\n case BTC: return QString(\"Bitcoins\");\n case mBTC: return QString(\"Milli-Bitcoins (1 \/ 1,000)\");\n case uBTC: return QString(\"Micro-Bitcoins (1 \/ 1,000,000)\");\n default: return QString(\"???\");\n }\n}\n\nqint64 BitcoinUnits::factor(int unit)\n{\n switch(unit)\n {\n case BTC: return 100000000;\n case mBTC: return 100000;\n case uBTC: return 100;\n default: return 100000000;\n }\n}\n\nint BitcoinUnits::amountDigits(int unit)\n{\n switch(unit)\n {\n case BTC: return 8; \/\/ 21,000,000 (# digits, without commas)\n case mBTC: return 11; \/\/ 21,000,000,000\n case uBTC: return 14; \/\/ 21,000,000,000,000\n default: return 0;\n }\n}\n\nint BitcoinUnits::decimals(int unit)\n{\n switch(unit)\n {\n case BTC: return 8;\n case mBTC: return 5;\n case uBTC: return 2;\n default: return 0;\n }\n}\n\nQString BitcoinUnits::format(int unit, qint64 n, bool fPlus)\n{\n \/\/ Note: not using straight sprintf here because we do NOT want\n \/\/ localized number formatting.\n if(!valid(unit))\n return QString(); \/\/ Refuse to format invalid unit\n qint64 coin = factor(unit);\n int num_decimals = decimals(unit);\n qint64 n_abs = (n > 0 ? n : -n);\n qint64 quotient = n_abs \/ coin;\n qint64 remainder = n_abs % coin;\n QString quotient_str = QString::number(quotient);\n QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n \/\/ Right-trim excess 0's after the decimal point\n int nTrim = 0;\n for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)\n ++nTrim;\n remainder_str.chop(nTrim);\n\n if (n < 0)\n quotient_str.insert(0, '-');\n else if (fPlus && n > 0)\n quotient_str.insert(0, '+');\n return quotient_str + QString(\".\") + remainder_str;\n}\n\nQString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)\n{\n return format(unit, amount, plussign) + QString(\" \") + name(unit);\n}\n\nbool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)\n{\n if(!valid(unit) || value.isEmpty())\n return false; \/\/ Refuse to parse invalid unit or empty string\n int num_decimals = decimals(unit);\n QStringList parts = value.split(\".\");\n\n if(parts.size() > 2)\n {\n return false; \/\/ More than one dot\n }\n QString whole = parts[0];\n QString decimals;\n\n if(parts.size() > 1)\n {\n decimals = parts[1];\n }\n if(decimals.size() > num_decimals)\n {\n return false; \/\/ Exceeds max precision\n }\n bool ok = false;\n QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n if(str.size() > 18)\n {\n return false; \/\/ Longer numbers will exceed 63 bits\n }\n qint64 retvalue = str.toLongLong(&ok);\n if(val_out)\n {\n *val_out = retvalue;\n }\n return ok;\n}\n\nint BitcoinUnits::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return unitlist.size();\n}\n\nQVariant BitcoinUnits::data(const QModelIndex &index, int role) const\n{\n int row = index.row();\n if(row >= 0 && row < unitlist.size())\n {\n Unit unit = unitlist.at(row);\n switch(role)\n {\n case Qt::EditRole:\n case Qt::DisplayRole:\n return QVariant(name(unit));\n case Qt::ToolTipRole:\n return QVariant(description(unit));\n case UnitRole:\n return QVariant(static_cast(unit));\n }\n }\n return QVariant();\n}\n<|endoftext|>"} {"text":"\/* Copyright The kNet Project.\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License. *\/\r\n\r\n\/** @file SimpleChat.cpp\r\n\t@brief *\/\r\n\r\n#include \r\n#include \r\n\r\n#include \"kNet.h\"\r\n#include \"kNet\/DebugMemoryLeakCheck.h\"\r\n\r\n\/\/#undef _MSC_VER\r\n\r\nusing namespace std;\r\nusing namespace kNet;\r\n\r\nconst unsigned long cChatMessageID = 42;\r\n\r\nclass NetworkApp : public INetworkServerListener, public IMessageHandler\r\n{\r\n\tNetwork network;\r\n\t\/\/ If we are the server, this pointer will be nonzero.\r\n\tNetworkServer *server;\r\n\t\/\/ If we are the client, this pointer will be nonzero.\r\n\tPtr(MessageConnection) connection;\r\n\r\n\t\/\/ Will contain the chat message as it is being typed on the command line.\r\n\tstd::string inputText;\r\n\r\npublic:\r\n\tNetworkApp()\r\n\t:server(0)\r\n\t{\r\n\t}\r\n\r\n\t\/\/ The server must implement this message.\r\n\tbool NewConnectionAttempt(const EndPoint &\/*endPoint*\/, Datagram &\/*datagram*\/)\r\n\t{\r\n\t\t\/\/ Allow the client to connect.\r\n\t\treturn true;\r\n\t}\r\n\r\n\t\/\/\/ Called to notify the listener that a new connection has been established.\r\n\tvoid NewConnectionEstablished(MessageConnection *connection)\r\n\t{\r\n\t\tcout << \"New connection from \" << connection->ToString() << \".\" << endl;\r\n\t\tconnection->RegisterInboundMessageHandler(this);\r\n\t}\r\n\r\n\tvoid HandleMessage(MessageConnection *source, packet_id_t \/*packetId*\/, message_id_t messageId, const char *data, size_t numBytes)\r\n\t{\r\n\t\tif (messageId == cChatMessageID)\r\n\t\t\tOnChatMessageReceived(source, data, numBytes);\r\n\t}\r\n\r\n\tvoid RunServer(unsigned short port, SocketTransportLayer transport)\r\n\t{\r\n\t\t\/\/ Start the server either in TCP or UDP mode.\r\n\t\tserver = network.StartServer(port, transport, this, true);\r\n\t\tif (!server)\r\n\t\t{\r\n\t\t\tcout << \"Unable to start server in port \" << port << \"!\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Server waiting for connection in port \" << port << \".\" << endl;\r\n\r\n\t\twhile(server->GetConnections().size() == 0)\r\n\t\t{\r\n\t\t\tserver->Process();\r\n\t\t\tClock::Sleep(100);\r\n\t\t}\r\n\r\n\t\tPtr(MessageConnection) clientConnection = server->GetConnections().begin()->second;\r\n\r\n\t\t\/\/ Stop accepting any further connections.\r\n\/\/\t\tserver->SetAcceptNewConnections(false);\r\n\r\n\t\tRunChat(clientConnection);\r\n\t}\r\n\r\n\tvoid RunClient(const char *address, unsigned short port, SocketTransportLayer transport)\r\n\t{\r\n\t\tconnection = network.Connect(address, port, transport, 0);\r\n\t\tif (!connection)\r\n\t\t{\r\n\t\t\tcout << \"Unable to connect to \" << address << \":\" << port << \".\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Waiting for connection..\" << endl;\r\n\t\tbool success = connection->WaitToEstablishConnection();\r\n\t\tif (!success)\r\n\t\t{\r\n\t\t\tcout << \"Failed to connect to server!\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Connected to \" << connection->GetSocket()->ToString() << \".\" << endl;\r\n\r\n\t\tRunChat(connection);\r\n\t}\r\n\r\n\tvoid OnChatMessageReceived(MessageConnection *connection, const char *message, int numBytes)\r\n\t{\r\n\t\tchar str[1025] = {};\r\n\t\tstrncpy(str, message, numBytes-1); \/\/ '-1' to take into account the null byte in the message.\r\n\t\t\/\/ Note: We can't assume the sender sent the null byte in the message, it might be an ill-crafted message!\r\n\t\tif (inputText.length() > 0)\r\n\t\t\tcout << endl;\r\n\t\tcout << connection->RemoteEndPoint().ToString() << \" says: \" << str << endl;\r\n\t\tif (inputText.length() > 0)\r\n\t\t\tcout << \"> \" << inputText;\r\n\r\n\t\t\/\/ If we are the server, make the received message go to all other connected clients as well.\r\n\t\tif (server)\r\n\t\t\tserver->BroadcastMessage(cChatMessageID, true, true, 100, 0, message, numBytes, connection);\r\n\t}\r\n\r\n\tvoid SendChatMessage(const char *message)\r\n\t{\r\n\t\t\/\/ Always remember to sanitize data at both ends.\r\n\t\tconst unsigned long cMaxMsgSize = 1024;\r\n\t\tif (strlen(message) >= cMaxMsgSize)\r\n\t\t\tthrow NetException(\"Tried to send too large chat message!\");\r\n\r\n\t\tconst size_t messageLength = strlen(message)+1; \/\/ Add one to the length to guarantee a null byte to the stream.\r\n\t\tif (server)\r\n\t\t\tserver->BroadcastMessage(cChatMessageID, true, true, 100, 0, message, messageLength);\r\n\t\telse if (connection && connection->IsWriteOpen())\r\n\t\t\tconnection->SendMessage(cChatMessageID, true, true, 100, 0, message, messageLength);\r\n\t}\r\n\r\n#ifdef _MSC_VER \/\/ On windows, poll for new messages to send from the console instead of blocking.\r\n\tvoid Win32PeekConsoleInput()\r\n\t{\r\n\t\t\/\/ Get the standard input handle.\r\n\t\tHANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);\r\n\t\tif (hStdin == INVALID_HANDLE_VALUE)\r\n\t\t\tthrow std::exception(\"Failed to get stdin handle!\");\r\n\r\n\t\t\/\/ Wait for the events. \r\n\t\tINPUT_RECORD irInBuf[128];\r\n\t\tDWORD numRead = 0;\r\n\t\tif (!PeekConsoleInput(hStdin, irInBuf, 1, &numRead))\r\n\t\t\tthrow std::exception(\"PeekConsoleInput failed!\"); \r\n\t\tif (numRead > 0)\r\n\t\t{\r\n\t\t\tif (!ReadConsoleInput(hStdin, irInBuf, 128, &numRead))\r\n\t\t\t\tthrow std::exception(\"ReadConsoleInput failed!\"); \r\n\t\t\tfor (DWORD i = 0; i < numRead; i++) \r\n\t\t\t\tif (irInBuf[i].EventType == KEY_EVENT && irInBuf[i].Event.KeyEvent.bKeyDown == TRUE)\r\n\t\t\t\t\tif (irInBuf[i].Event.KeyEvent.wVirtualKeyCode == VK_RETURN) \/\/ Enter key\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (inputText == \"exit\" || inputText == \"quit\" || inputText == \"q\")\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (connection)\r\n\t\t\t\t\t\t\t\tconnection->Close();\r\n\t\t\t\t\t\t\tif (server)\r\n\t\t\t\t\t\t\t\tserver->Close(500);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (inputText.length() > 0)\r\n\t\t\t\t\t\t\tSendChatMessage(inputText.c_str());\r\n\t\t\t\t\t\tinputText = \"\";\r\n\t\t\t\t\t\tcout << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tchar str[2] = {};\r\n\t\t\t\t\t\tstr[0] = irInBuf[i].Event.KeyEvent.uChar.AsciiChar;\r\n\t\t\t\t\t\tif (str[0] >= 32 && str[0] <= 127)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (inputText.length() == 0)\r\n\t\t\t\t\t\t\t\tcout << \"> \";\r\n\t\t\t\t\t\t\tcout << str[0]; \/\/ Echo the character we inputted back to console (yes, there might be a flag for this)\r\n\t\t\t\t\t\t\tinputText += std::string(str);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t}\r\n\t}\r\n#endif\r\n\r\n\tvoid RunChat(Ptr(MessageConnection) connection)\r\n\t{\r\n#ifdef _MSC_VER\r\n\t\t\/\/ Get the standard input handle.\r\n\t\tHANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);\r\n\t\tif (hStdin == INVALID_HANDLE_VALUE)\r\n\t\t\tthrow std::exception(\"Failed to get stdin handle!\");\r\n\r\n\t\t\/\/ Save the current input mode, to be restored on exit. \r\n\t\tDWORD oldInputMode;\r\n\t\tif (!GetConsoleMode(hStdin, &oldInputMode)) \r\n\t\t\tthrow std::exception(\"GetConsoleMode failed!\"); \r\n \r\n\t\t\/\/ Enable the window and mouse input events. \r\n\t\tif (!SetConsoleMode(hStdin, ENABLE_WINDOW_INPUT)) \r\n\t\t\tthrow std::exception(\"SetConsoleMode failed!\");\r\n#endif\r\n\r\n\t\tcout << \"Chat running. Type messages and send them by pressing Enter. Type 'q'\/'exit'\/'quit' to disconnect.\" << endl;\r\n\r\n\t\twhile((server && server->GetConnections().size() > 0) || (connection && connection->IsReadOpen()))\r\n\t\t{\r\n\t\t\tif (server)\r\n\t\t\t\tserver->Process();\r\n\r\n\t\t\tif (!connection->IsReadOpen())\r\n\t\t\t\tconnection->Disconnect();\r\n\r\n\t\t\tfor(int i = 0; i < 100; ++i) \/\/ Process a maximum of 100 messages at one go.\r\n\t\t\t{\r\n\t\t\t\tNetworkMessage *msg = connection->ReceiveMessage(50);\r\n\t\t\t\tif (!msg)\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tif (msg->id == cChatMessageID && msg->Size() > 0)\r\n\t\t\t\t\tOnChatMessageReceived(connection, &msg->data[0], msg->Size());\r\n\t\t\t\tconnection->FreeMessage(msg);\r\n\t\t\t}\r\n\r\n#ifdef _MSC_VER\r\n\t\t\tWin32PeekConsoleInput();\r\n#else\r\n\t\t\tchar inputText[256] = {};\r\n\t\t\tcout << \"Enter a text to say: \";\r\n\t\t\tcin.getline(inputText, 255, '\\n');\r\n\t\t\tif (strlen(inputText) > 0)\r\n\t\t\t{\r\n\t\t\t\tif (!strcmp(inputText, \"quit\") || !strcmp(inputText, \"exit\") || !strcmp(inputText, \"q\"))\r\n\t\t\t\t\tconnection->Close();\r\n\t\t\t\telse\r\n\t\t\t\t\tSendChatMessage(inputText);\r\n\t\t\t}\r\n#endif\r\n\t\t\t\/\/ Nothing in the above sleeps or blocks to wait for any events. Sleep() to keep the CPU use down.\r\n\t\t\tkNet::Clock::Sleep(1);\r\n\t\t}\r\n\t\tcout << \"Disconnected.\" << endl;\r\n\t}\r\n};\r\n\r\nvoid PrintUsage()\r\n{\r\n\tcout << \"Usage: \" << endl;\r\n\tcout << \" tcp|udp server port\" << endl;\r\n\tcout << \" tcp|udp client hostname port\" << endl;\r\n}\r\n\r\nBottomMemoryAllocator bma;\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tif (argc < 4)\r\n\t{\r\n\t\tPrintUsage();\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tkNet::SetLogChannels(LogUser | LogInfo | LogError);\r\n\r\n\tEnableMemoryLeakLoggingAtExit();\r\n\r\n\tSocketTransportLayer transport = StringToSocketTransportLayer(argv[1]);\r\n\tif (transport == InvalidTransportLayer)\r\n\t{\r\n\t\tcout << \"The first parameter is either 'tcp' or 'udp'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n\tNetworkApp app;\r\n\tif (!_stricmp(argv[2], \"server\"))\r\n\t{\r\n\t\tunsigned short port = (unsigned short)atoi(argv[3]);\r\n\r\n\t\tapp.RunServer(port, transport);\r\n\t}\r\n\telse if (!_stricmp(argv[2], \"client\"))\r\n\t{\r\n\t\tif (argc < 5)\r\n\t\t{\r\n\t\t\tPrintUsage();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tunsigned short port = (unsigned short)atoi(argv[4]);\r\n\t\tapp.RunClient(argv[3], port, transport);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcout << \"The second parameter is either 'server' or 'client'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n}Fix bad signature in overriding virtual function in SimpleChat sample.\/* Copyright The kNet Project.\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License. *\/\r\n\r\n\/** @file SimpleChat.cpp\r\n\t@brief *\/\r\n\r\n#include \r\n#include \r\n\r\n#include \"kNet.h\"\r\n#include \"kNet\/DebugMemoryLeakCheck.h\"\r\n\r\n\/\/#undef _MSC_VER\r\n\r\nusing namespace std;\r\nusing namespace kNet;\r\n\r\nconst unsigned long cChatMessageID = 42;\r\n\r\nclass NetworkApp : public INetworkServerListener, public IMessageHandler\r\n{\r\n\tNetwork network;\r\n\t\/\/ If we are the server, this pointer will be nonzero.\r\n\tNetworkServer *server;\r\n\t\/\/ If we are the client, this pointer will be nonzero.\r\n\tPtr(MessageConnection) connection;\r\n\r\n\t\/\/ Will contain the chat message as it is being typed on the command line.\r\n\tstd::string inputText;\r\n\r\npublic:\r\n\tNetworkApp()\r\n\t:server(0)\r\n\t{\r\n\t}\r\n\r\n\t\/\/ The server must implement this message.\r\n\tbool NewConnectionAttempt(const EndPoint & UNUSED(endPoint), const char * UNUSED(data), size_t UNUSED(numBytes))\r\n\t{\r\n\t\t\/\/ Allow the client to connect.\r\n\t\treturn true;\r\n\t}\r\n\r\n\t\/\/\/ Called to notify the listener that a new connection has been established.\r\n\tvoid NewConnectionEstablished(MessageConnection *connection)\r\n\t{\r\n\t\tcout << \"New connection from \" << connection->ToString() << \".\" << endl;\r\n\t\tconnection->RegisterInboundMessageHandler(this);\r\n\t}\r\n\r\n\tvoid HandleMessage(MessageConnection *source, packet_id_t \/*packetId*\/, message_id_t messageId, const char *data, size_t numBytes)\r\n\t{\r\n\t\tif (messageId == cChatMessageID)\r\n\t\t\tOnChatMessageReceived(source, data, numBytes);\r\n\t}\r\n\r\n\tvoid RunServer(unsigned short port, SocketTransportLayer transport)\r\n\t{\r\n\t\t\/\/ Start the server either in TCP or UDP mode.\r\n\t\tserver = network.StartServer(port, transport, this, true);\r\n\t\tif (!server)\r\n\t\t{\r\n\t\t\tcout << \"Unable to start server in port \" << port << \"!\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Server waiting for connection in port \" << port << \".\" << endl;\r\n\r\n\t\twhile(server->GetConnections().size() == 0)\r\n\t\t{\r\n\t\t\tserver->Process();\r\n\t\t\tClock::Sleep(100);\r\n\t\t}\r\n\r\n\t\tPtr(MessageConnection) clientConnection = server->GetConnections().begin()->second;\r\n\r\n\t\t\/\/ Stop accepting any further connections.\r\n\/\/\t\tserver->SetAcceptNewConnections(false);\r\n\r\n\t\tRunChat(clientConnection);\r\n\t}\r\n\r\n\tvoid RunClient(const char *address, unsigned short port, SocketTransportLayer transport)\r\n\t{\r\n\t\tconnection = network.Connect(address, port, transport, 0);\r\n\t\tif (!connection)\r\n\t\t{\r\n\t\t\tcout << \"Unable to connect to \" << address << \":\" << port << \".\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Waiting for connection..\" << endl;\r\n\t\tbool success = connection->WaitToEstablishConnection();\r\n\t\tif (!success)\r\n\t\t{\r\n\t\t\tcout << \"Failed to connect to server!\" << endl;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tcout << \"Connected to \" << connection->GetSocket()->ToString() << \".\" << endl;\r\n\r\n\t\tRunChat(connection);\r\n\t}\r\n\r\n\tvoid OnChatMessageReceived(MessageConnection *connection, const char *message, int numBytes)\r\n\t{\r\n\t\tchar str[1025] = {};\r\n\t\tstrncpy(str, message, numBytes-1); \/\/ '-1' to take into account the null byte in the message.\r\n\t\t\/\/ Note: We can't assume the sender sent the null byte in the message, it might be an ill-crafted message!\r\n\t\tif (inputText.length() > 0)\r\n\t\t\tcout << endl;\r\n\t\tcout << connection->RemoteEndPoint().ToString() << \" says: \" << str << endl;\r\n\t\tif (inputText.length() > 0)\r\n\t\t\tcout << \"> \" << inputText;\r\n\r\n\t\t\/\/ If we are the server, make the received message go to all other connected clients as well.\r\n\t\tif (server)\r\n\t\t\tserver->BroadcastMessage(cChatMessageID, true, true, 100, 0, message, numBytes, connection);\r\n\t}\r\n\r\n\tvoid SendChatMessage(const char *message)\r\n\t{\r\n\t\t\/\/ Always remember to sanitize data at both ends.\r\n\t\tconst unsigned long cMaxMsgSize = 1024;\r\n\t\tif (strlen(message) >= cMaxMsgSize)\r\n\t\t\tthrow NetException(\"Tried to send too large chat message!\");\r\n\r\n\t\tconst size_t messageLength = strlen(message)+1; \/\/ Add one to the length to guarantee a null byte to the stream.\r\n\t\tif (server)\r\n\t\t\tserver->BroadcastMessage(cChatMessageID, true, true, 100, 0, message, messageLength);\r\n\t\telse if (connection && connection->IsWriteOpen())\r\n\t\t\tconnection->SendMessage(cChatMessageID, true, true, 100, 0, message, messageLength);\r\n\t}\r\n\r\n#ifdef _MSC_VER \/\/ On windows, poll for new messages to send from the console instead of blocking.\r\n\tvoid Win32PeekConsoleInput()\r\n\t{\r\n\t\t\/\/ Get the standard input handle.\r\n\t\tHANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);\r\n\t\tif (hStdin == INVALID_HANDLE_VALUE)\r\n\t\t\tthrow std::exception(\"Failed to get stdin handle!\");\r\n\r\n\t\t\/\/ Wait for the events. \r\n\t\tINPUT_RECORD irInBuf[128];\r\n\t\tDWORD numRead = 0;\r\n\t\tif (!PeekConsoleInput(hStdin, irInBuf, 1, &numRead))\r\n\t\t\tthrow std::exception(\"PeekConsoleInput failed!\"); \r\n\t\tif (numRead > 0)\r\n\t\t{\r\n\t\t\tif (!ReadConsoleInput(hStdin, irInBuf, 128, &numRead))\r\n\t\t\t\tthrow std::exception(\"ReadConsoleInput failed!\"); \r\n\t\t\tfor (DWORD i = 0; i < numRead; i++) \r\n\t\t\t\tif (irInBuf[i].EventType == KEY_EVENT && irInBuf[i].Event.KeyEvent.bKeyDown == TRUE)\r\n\t\t\t\t\tif (irInBuf[i].Event.KeyEvent.wVirtualKeyCode == VK_RETURN) \/\/ Enter key\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (inputText == \"exit\" || inputText == \"quit\" || inputText == \"q\")\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (connection)\r\n\t\t\t\t\t\t\t\tconnection->Close();\r\n\t\t\t\t\t\t\tif (server)\r\n\t\t\t\t\t\t\t\tserver->Close(500);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (inputText.length() > 0)\r\n\t\t\t\t\t\t\tSendChatMessage(inputText.c_str());\r\n\t\t\t\t\t\tinputText = \"\";\r\n\t\t\t\t\t\tcout << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tchar str[2] = {};\r\n\t\t\t\t\t\tstr[0] = irInBuf[i].Event.KeyEvent.uChar.AsciiChar;\r\n\t\t\t\t\t\tif (str[0] >= 32 && str[0] <= 127)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (inputText.length() == 0)\r\n\t\t\t\t\t\t\t\tcout << \"> \";\r\n\t\t\t\t\t\t\tcout << str[0]; \/\/ Echo the character we inputted back to console (yes, there might be a flag for this)\r\n\t\t\t\t\t\t\tinputText += std::string(str);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t}\r\n\t}\r\n#endif\r\n\r\n\tvoid RunChat(Ptr(MessageConnection) connection)\r\n\t{\r\n#ifdef _MSC_VER\r\n\t\t\/\/ Get the standard input handle.\r\n\t\tHANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);\r\n\t\tif (hStdin == INVALID_HANDLE_VALUE)\r\n\t\t\tthrow std::exception(\"Failed to get stdin handle!\");\r\n\r\n\t\t\/\/ Save the current input mode, to be restored on exit. \r\n\t\tDWORD oldInputMode;\r\n\t\tif (!GetConsoleMode(hStdin, &oldInputMode)) \r\n\t\t\tthrow std::exception(\"GetConsoleMode failed!\"); \r\n \r\n\t\t\/\/ Enable the window and mouse input events. \r\n\t\tif (!SetConsoleMode(hStdin, ENABLE_WINDOW_INPUT)) \r\n\t\t\tthrow std::exception(\"SetConsoleMode failed!\");\r\n#endif\r\n\r\n\t\tcout << \"Chat running. Type messages and send them by pressing Enter. Type 'q'\/'exit'\/'quit' to disconnect.\" << endl;\r\n\r\n\t\twhile((server && server->GetConnections().size() > 0) || (connection && connection->IsReadOpen()))\r\n\t\t{\r\n\t\t\tif (server)\r\n\t\t\t\tserver->Process();\r\n\r\n\t\t\tif (!connection->IsReadOpen())\r\n\t\t\t\tconnection->Disconnect();\r\n\r\n\t\t\tfor(int i = 0; i < 100; ++i) \/\/ Process a maximum of 100 messages at one go.\r\n\t\t\t{\r\n\t\t\t\tNetworkMessage *msg = connection->ReceiveMessage(50);\r\n\t\t\t\tif (!msg)\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tif (msg->id == cChatMessageID && msg->Size() > 0)\r\n\t\t\t\t\tOnChatMessageReceived(connection, &msg->data[0], msg->Size());\r\n\t\t\t\tconnection->FreeMessage(msg);\r\n\t\t\t}\r\n\r\n#ifdef _MSC_VER\r\n\t\t\tWin32PeekConsoleInput();\r\n#else\r\n\t\t\tchar inputText[256] = {};\r\n\t\t\tcout << \"Enter a text to say: \";\r\n\t\t\tcin.getline(inputText, 255, '\\n');\r\n\t\t\tif (strlen(inputText) > 0)\r\n\t\t\t{\r\n\t\t\t\tif (!strcmp(inputText, \"quit\") || !strcmp(inputText, \"exit\") || !strcmp(inputText, \"q\"))\r\n\t\t\t\t\tconnection->Close();\r\n\t\t\t\telse\r\n\t\t\t\t\tSendChatMessage(inputText);\r\n\t\t\t}\r\n#endif\r\n\t\t\t\/\/ Nothing in the above sleeps or blocks to wait for any events. Sleep() to keep the CPU use down.\r\n\t\t\tkNet::Clock::Sleep(1);\r\n\t\t}\r\n\t\tcout << \"Disconnected.\" << endl;\r\n\t}\r\n};\r\n\r\nvoid PrintUsage()\r\n{\r\n\tcout << \"Usage: \" << endl;\r\n\tcout << \" tcp|udp server port\" << endl;\r\n\tcout << \" tcp|udp client hostname port\" << endl;\r\n}\r\n\r\nBottomMemoryAllocator bma;\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tif (argc < 4)\r\n\t{\r\n\t\tPrintUsage();\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tkNet::SetLogChannels(LogUser | LogInfo | LogError);\r\n\r\n\tEnableMemoryLeakLoggingAtExit();\r\n\r\n\tSocketTransportLayer transport = StringToSocketTransportLayer(argv[1]);\r\n\tif (transport == InvalidTransportLayer)\r\n\t{\r\n\t\tcout << \"The first parameter is either 'tcp' or 'udp'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n\tNetworkApp app;\r\n\tif (!_stricmp(argv[2], \"server\"))\r\n\t{\r\n\t\tunsigned short port = (unsigned short)atoi(argv[3]);\r\n\r\n\t\tapp.RunServer(port, transport);\r\n\t}\r\n\telse if (!_stricmp(argv[2], \"client\"))\r\n\t{\r\n\t\tif (argc < 5)\r\n\t\t{\r\n\t\t\tPrintUsage();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tunsigned short port = (unsigned short)atoi(argv[4]);\r\n\t\tapp.RunClient(argv[3], port, transport);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcout << \"The second parameter is either 'server' or 'client'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"navcoinunits.h\"\n\n#include \"primitives\/transaction.h\"\n#include \"util.h\"\n\n#include \n#include \n\nNavCoinUnits::NavCoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList NavCoinUnits::availableUnits()\n{\n QList unitlist;\n unitlist.append(NAV);\n unitlist.append(mNAV);\n unitlist.append(uNAV);\n unitlist.append(BTC);\n unitlist.append(EUR);\n unitlist.append(USD);\n return unitlist;\n}\n\nbool NavCoinUnits::valid(int unit)\n{\n switch(unit)\n {\n case NAV:\n case mNAV:\n case uNAV:\n case BTC:\n case EUR:\n case USD:\n return true;\n default:\n return false;\n }\n}\n\nQString NavCoinUnits::name(int unit)\n{\n switch(unit)\n {\n case NAV: return QString(\"NAV\");\n case mNAV: return QString(\"mNAV\");\n case uNAV: return QString::fromUtf8(\"μNAV\");\n case BTC: return QString::fromUtf8(\"BTC\");\n case EUR: return QString::fromUtf8(\"EUR\");\n case USD: return QString::fromUtf8(\"USD\");\n default: return QString(\"???\");\n }\n}\n\nQString NavCoinUnits::description(int unit)\n{\n switch(unit)\n {\n case NAV: return QString(\"NavCoins\");\n case mNAV: return QString(\"Milli-NavCoins (1 \/ 1\" THIN_SP_UTF8 \"000)\");\n case uNAV: return QString(\"Micro-NavCoins (1 \/ 1\" THIN_SP_UTF8 \"000\" THIN_SP_UTF8 \"000)\");\n case BTC: return QString(\"BTC\");\n case EUR: return QString(\"Euro\");\n case USD: return QString(\"US Dolar\");\n default: return QString(\"???\");\n }\n}\n\nqint64 NavCoinUnits::factor(int unit)\n{\n\n QSettings settings;\n\n switch(unit)\n {\n case NAV: return 100000000;\n case mNAV: return 100000;\n case uNAV: return 100;\n case BTC: return settings.value(\"btcFactor\", 0).toFloat();\n case EUR: return settings.value(\"eurFactor\", 0).toFloat();\n case USD: return settings.value(\"usdFactor\", 0).toFloat();\n default: return 100000000;\n }\n}\n\nint NavCoinUnits::decimals(int unit)\n{\n switch(unit)\n {\n case NAV: return 8;\n case mNAV: return 5;\n case uNAV: return 2;\n case BTC: return 8;\n case EUR: return 2;\n case USD: return 2;\n default: return 0;\n }\n}\n\nQString NavCoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)\n{\n \/\/ Note: not using straight sprintf here because we do NOT want\n \/\/ localized number formatting.\n if(!valid(unit))\n return QString(); \/\/ Refuse to format invalid unit\n qint64 n = (qint64)nIn;\n qint64 coin = factor(unit);\n int num_decimals = decimals(unit);\n qint64 n_abs = (n > 0 ? n : -n);\n qint64 quotient;\n qint64 remainder;\n\n quotient = n_abs \/ coin;\n remainder = n_abs % coin;\n QString quotient_str = QString::number(quotient);\n QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n \/\/ Use SI-style thin space separators as these are locale independent and can't be\n \/\/ confused with the decimal marker.\n QChar thin_sp(THIN_SP_CP);\n int q_size = quotient_str.size();\n if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))\n for (int i = 3; i < q_size; i += 3)\n quotient_str.insert(q_size - i, thin_sp);\n\n if (n < 0)\n quotient_str.insert(0, '-');\n else if (fPlus && n > 0)\n quotient_str.insert(0, '+');\n return quotient_str + QString(\".\") + remainder_str;\n}\n\n\n\/\/ NOTE: Using formatWithUnit in an HTML context risks wrapping\n\/\/ quantities at the thousands separator. More subtly, it also results\n\/\/ in a standard space rather than a thin space, due to a bug in Qt's\n\/\/ XML whitespace canonicalisation\n\/\/\n\/\/ Please take care to use formatHtmlWithUnit instead, when\n\/\/ appropriate.\n\nQString NavCoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)\n{\n return format(unit, amount, plussign, separators) + QString(\" \") + name(unit);\n}\n\nQString NavCoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)\n{\n QString str(formatWithUnit(unit, amount, plussign, separators));\n str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));\n return QString(\"%1<\/span>\").arg(str);\n}\n\n\nbool NavCoinUnits::parse(int unit, const QString &value, CAmount *val_out)\n{\n if(!valid(unit) || value.isEmpty())\n return false; \/\/ Refuse to parse invalid unit or empty string\n int num_decimals = decimals(unit);\n\n \/\/ Ignore spaces and thin spaces when parsing\n QStringList parts = removeSpaces(value).split(\".\");\n\n if(parts.size() > 2)\n {\n return false; \/\/ More than one dot\n }\n QString whole = parts[0];\n QString decimals;\n\n if(parts.size() > 1)\n {\n decimals = parts[1];\n }\n if(decimals.size() > num_decimals)\n {\n return false; \/\/ Exceeds max precision\n }\n bool ok = false;\n QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n if(str.size() > 18)\n {\n return false; \/\/ Longer numbers will exceed 63 bits\n }\n CAmount retvalue(str.toLongLong(&ok));\n if(val_out)\n {\n *val_out = retvalue;\n }\n return ok;\n}\n\nQString NavCoinUnits::getAmountColumnTitle(int unit)\n{\n QString amountTitle = QObject::tr(\"Amount\");\n if (NavCoinUnits::valid(unit))\n {\n amountTitle += \" (\"+NavCoinUnits::name(unit) + \")\";\n }\n return amountTitle;\n}\n\nint NavCoinUnits::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return unitlist.size();\n}\n\nQVariant NavCoinUnits::data(const QModelIndex &index, int role) const\n{\n int row = index.row();\n if(row >= 0 && row < unitlist.size())\n {\n Unit unit = unitlist.at(row);\n switch(role)\n {\n case Qt::EditRole:\n case Qt::DisplayRole:\n return QVariant(name(unit));\n case Qt::ToolTipRole:\n return QVariant(description(unit));\n case UnitRole:\n return QVariant(static_cast(unit));\n }\n }\n return QVariant();\n}\n\nCAmount NavCoinUnits::maxMoney()\n{\n return MAX_MONEY;\n}\ngui: fixed conversion to fiat for little amounts\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"navcoinunits.h\"\n\n#include \"primitives\/transaction.h\"\n#include \"util.h\"\n\n#include \n\n#include \n#include \n\nNavCoinUnits::NavCoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList NavCoinUnits::availableUnits()\n{\n QList unitlist;\n unitlist.append(NAV);\n unitlist.append(mNAV);\n unitlist.append(uNAV);\n unitlist.append(BTC);\n unitlist.append(EUR);\n unitlist.append(USD);\n return unitlist;\n}\n\nbool NavCoinUnits::valid(int unit)\n{\n switch(unit)\n {\n case NAV:\n case mNAV:\n case uNAV:\n case BTC:\n case EUR:\n case USD:\n return true;\n default:\n return false;\n }\n}\n\nQString NavCoinUnits::name(int unit)\n{\n switch(unit)\n {\n case NAV: return QString(\"NAV\");\n case mNAV: return QString(\"mNAV\");\n case uNAV: return QString::fromUtf8(\"μNAV\");\n case BTC: return QString::fromUtf8(\"BTC\");\n case EUR: return QString::fromUtf8(\"EUR\");\n case USD: return QString::fromUtf8(\"USD\");\n default: return QString(\"???\");\n }\n}\n\nQString NavCoinUnits::description(int unit)\n{\n switch(unit)\n {\n case NAV: return QString(\"NavCoins\");\n case mNAV: return QString(\"Milli-NavCoins (1 \/ 1\" THIN_SP_UTF8 \"000)\");\n case uNAV: return QString(\"Micro-NavCoins (1 \/ 1\" THIN_SP_UTF8 \"000\" THIN_SP_UTF8 \"000)\");\n case BTC: return QString(\"BTC\");\n case EUR: return QString(\"Euro\");\n case USD: return QString(\"US Dolar\");\n default: return QString(\"???\");\n }\n}\n\nqint64 NavCoinUnits::factor(int unit)\n{\n\n QSettings settings;\n\n switch(unit)\n {\n case NAV: return 100000000;\n case mNAV: return 100000;\n case uNAV: return 100;\n case BTC: return settings.value(\"btcFactor\", 0).toFloat();\n case EUR: return settings.value(\"eurFactor\", 0).toFloat();\n case USD: return settings.value(\"usdFactor\", 0).toFloat();\n default: return 100000000;\n }\n}\n\nint NavCoinUnits::decimals(int unit)\n{\n switch(unit)\n {\n case NAV: return 8;\n case mNAV: return 5;\n case uNAV: return 2;\n case BTC: return 8;\n case EUR: return 6;\n case USD: return 6;\n default: return 0;\n }\n}\n\nQString NavCoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)\n{\n \/\/ Note: not using straight sprintf here because we do NOT want\n \/\/ localized number formatting.\n if(!valid(unit))\n return QString(); \/\/ Refuse to format invalid unit\n qint64 n = (qint64)nIn;\n qint64 coin = factor(unit);\n int num_decimals = decimals(unit);\n qint64 n_abs = (n > 0 ? n : -n);\n double quotient;\n qint64 remainder;\n\n\n if(n < coin)\n {\n double q;\n double r = modf((double)n_abs \/ (double)coin, &q);\n quotient = q;\n remainder = r * (double)pow(10,num_decimals);\n }\n else\n {\n quotient = n_abs \/ coin;\n double q;\n double r = modf((double)n_abs \/ (double)coin, &q);\n remainder = r * (double)pow(10,num_decimals);\n }\n\n\n QString quotient_str = QString::number((qint64)quotient);\n QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n \/\/ Use SI-style thin space separators as these are locale independent and can't be\n \/\/ confused with the decimal marker.\n QChar thin_sp(THIN_SP_CP);\n int q_size = quotient_str.size();\n if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))\n for (int i = 3; i < q_size; i += 3)\n quotient_str.insert(q_size - i, thin_sp);\n\n if (n < 0)\n quotient_str.insert(0, '-');\n else if (fPlus && n > 0)\n quotient_str.insert(0, '+');\n\n return quotient_str + QString(\".\") + remainder_str;\n}\n\n\n\/\/ NOTE: Using formatWithUnit in an HTML context risks wrapping\n\/\/ quantities at the thousands separator. More subtly, it also results\n\/\/ in a standard space rather than a thin space, due to a bug in Qt's\n\/\/ XML whitespace canonicalisation\n\/\/\n\/\/ Please take care to use formatHtmlWithUnit instead, when\n\/\/ appropriate.\n\nQString NavCoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)\n{\n return format(unit, amount, plussign, separators) + QString(\" \") + name(unit);\n}\n\nQString NavCoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)\n{\n QString str(formatWithUnit(unit, amount, plussign, separators));\n str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));\n return QString(\"%1<\/span>\").arg(str);\n}\n\n\nbool NavCoinUnits::parse(int unit, const QString &value, CAmount *val_out)\n{\n if(!valid(unit) || value.isEmpty())\n return false; \/\/ Refuse to parse invalid unit or empty string\n int num_decimals = decimals(unit);\n\n \/\/ Ignore spaces and thin spaces when parsing\n QStringList parts = removeSpaces(value).split(\".\");\n\n if(parts.size() > 2)\n {\n return false; \/\/ More than one dot\n }\n QString whole = parts[0];\n QString decimals;\n\n if(parts.size() > 1)\n {\n decimals = parts[1];\n }\n if(decimals.size() > num_decimals)\n {\n return false; \/\/ Exceeds max precision\n }\n bool ok = false;\n QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n if(str.size() > 18)\n {\n return false; \/\/ Longer numbers will exceed 63 bits\n }\n CAmount retvalue(str.toLongLong(&ok));\n if(val_out)\n {\n *val_out = retvalue;\n }\n return ok;\n}\n\nQString NavCoinUnits::getAmountColumnTitle(int unit)\n{\n QString amountTitle = QObject::tr(\"Amount\");\n if (NavCoinUnits::valid(unit))\n {\n amountTitle += \" (\"+NavCoinUnits::name(unit) + \")\";\n }\n return amountTitle;\n}\n\nint NavCoinUnits::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return unitlist.size();\n}\n\nQVariant NavCoinUnits::data(const QModelIndex &index, int role) const\n{\n int row = index.row();\n if(row >= 0 && row < unitlist.size())\n {\n Unit unit = unitlist.at(row);\n switch(role)\n {\n case Qt::EditRole:\n case Qt::DisplayRole:\n return QVariant(name(unit));\n case Qt::ToolTipRole:\n return QVariant(description(unit));\n case UnitRole:\n return QVariant(static_cast(unit));\n }\n }\n return QVariant();\n}\n\nCAmount NavCoinUnits::maxMoney()\n{\n return MAX_MONEY;\n}\n<|endoftext|>"} {"text":"#include \"overviewpage.h\"\n#include \"ui_overviewpage.h\"\n\n#include \"init.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"optionsmodel.h\"\n#include \"transactiontablemodel.h\"\n#include \"transactionfilterproxy.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n\n#include \n#include \n#include \n\n#define DECORATION_SIZE 64\n#define NUM_ITEMS 3\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n Q_OBJECT\npublic:\n TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)\n {\n\n }\n\n inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n const QModelIndex &index ) const\n {\n painter->save();\n\n QIcon icon = qvariant_cast(index.data(Qt::DecorationRole));\n QRect mainRect = option.rect;\n QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n int xspace = DECORATION_SIZE + 8;\n int ypad = 6;\n int halfheight = (mainRect.height() - 2*ypad)\/2;\n QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);\n QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);\n icon.paint(painter, decorationRect);\n\n QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n QString address = index.data(Qt::DisplayRole).toString();\n qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n QVariant value = index.data(Qt::ForegroundRole);\n QColor foreground = option.palette.color(QPalette::Text);\n if(value.canConvert())\n {\n QBrush brush = qvariant_cast(value);\n foreground = brush.color();\n }\n\n painter->setPen(foreground);\n painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);\n\n if(amount < 0)\n {\n foreground = COLOR_NEGATIVE;\n }\n else if(!confirmed)\n {\n foreground = COLOR_UNCONFIRMED;\n }\n else\n {\n foreground = option.palette.color(QPalette::Text);\n }\n painter->setPen(foreground);\n QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);\n if(!confirmed)\n {\n amountText = QString(\"[\") + amountText + QString(\"]\");\n }\n painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);\n\n painter->setPen(option.palette.color(QPalette::Text));\n painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));\n\n painter->restore();\n }\n\n inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n {\n return QSize(DECORATION_SIZE, DECORATION_SIZE);\n }\n\n int unit;\n\n};\n#include \"overviewpage.moc\"\n\nOverviewPage::OverviewPage(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::OverviewPage),\n clientModel(0),\n walletModel(0),\n currentBalance(-1),\n currentUnconfirmedBalance(-1),\n currentImmatureBalance(-1),\n txdelegate(new TxViewDelegate()),\n filter(0)\n{\n ui->setupUi(this);\n\n \/\/ Recent transactions\n ui->listTransactions->setItemDelegate(txdelegate);\n ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n\n connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));\n\n timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), this, SLOT(darkSendStatus()));\n timer->start(333);\n\n \/\/ init \"out of sync\" warning labels\n ui->labelWalletStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n ui->labelTransactionsStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n\n showingDarkSendMessage = 0;\n darksendActionCheck = 0;\n\n \/\/ start with displaying the \"out of sync\" warnings\n showOutOfSyncWarning(true);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex &index)\n{\n if(filter)\n emit transactionClicked(filter->mapToSource(index));\n}\n\nOverviewPage::~OverviewPage()\n{\n delete ui;\n}\n\nvoid OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance)\n{\n int unit = walletModel->getOptionsModel()->getDisplayUnit();\n currentBalance = balance;\n currentUnconfirmedBalance = unconfirmedBalance;\n currentImmatureBalance = immatureBalance;\n currentAnonymizedBalance = anonymizedBalance;\n ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));\n ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));\n ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));\n ui->labelAnonymized->setText(BitcoinUnits::formatWithUnit(unit, anonymizedBalance));\n\n \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n \/\/ for the non-mining users\n bool showImmature = immatureBalance != 0;\n ui->labelImmature->setVisible(showImmature);\n ui->labelImmatureText->setVisible(showImmature);\n}\n\nvoid OverviewPage::setClientModel(ClientModel *model)\n{\n this->clientModel = model;\n if(model)\n {\n \/\/ Show warning if this is a prerelease version\n connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));\n updateAlerts(model->getStatusBarWarnings());\n }\n}\n\nvoid OverviewPage::setWalletModel(WalletModel *model)\n{\n this->walletModel = model;\n if(model && model->getOptionsModel())\n {\n \/\/ Set up transaction list\n filter = new TransactionFilterProxy();\n filter->setSourceModel(model->getTransactionTableModel());\n filter->setLimit(NUM_ITEMS);\n filter->setDynamicSortFilter(true);\n filter->setSortRole(Qt::EditRole);\n filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);\n\n ui->listTransactions->setModel(filter);\n ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n\n \/\/ Keep up to date with wallet\n setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance());\n connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));\n\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n }\n\n \/\/ update the display unit, to not use the default (\"BTC\")\n updateDisplayUnit();\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n if(walletModel && walletModel->getOptionsModel())\n {\n if(currentBalance != -1)\n setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentAnonymizedBalance);\n\n \/\/ Update txdelegate->unit with the current unit\n txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();\n\n ui->listTransactions->update();\n }\n}\n\nvoid OverviewPage::updateAlerts(const QString &warnings)\n{\n this->ui->labelAlerts->setVisible(!warnings.isEmpty());\n this->ui->labelAlerts->setText(warnings);\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n ui->labelWalletStatus->setVisible(fShow);\n ui->labelTransactionsStatus->setVisible(fShow);\n}\n\nvoid OverviewPage::darkSendStatus()\n{\n if(fDisableDarksend) {\n if(nBestHeight != cachedNumBlocks)\n {\n cachedNumBlocks = nBestHeight;\n\n ui->darksendEnabled->setText(\"Disabled\");\n ui->darksendStatus->setText(\"\");\n\n std::ostringstream convert;\n convert << pwalletMain->GetAverageAnonymizedRounds() << \"\/\" << nDarksendRounds;\n QString s(convert.str().c_str());\n ui->darksendAvgRounds->setText(s);\n }\n\n return;\n }\n\n \/\/ check darksend status and unlock if needed\n if(nBestHeight != cachedNumBlocks)\n {\n \/\/ Balance and number of transactions might have changed\n cachedNumBlocks = nBestHeight;\n\n if (pwalletMain->GetBalance() - pwalletMain->GetAnonymizedBalance() > 2*COIN){\n if (walletModel->getEncryptionStatus() != WalletModel::Unencrypted){\n if((nAnonymizeDarkcoinAmount*COIN)-pwalletMain->GetAnonymizedBalance() > 1.1*COIN && walletModel->getEncryptionStatus() == WalletModel::Locked){\n WalletModel::UnlockContext ctx(walletModel->requestUnlock());\n if(!ctx.isValid()){\n \/\/unlock was cancelled\n fDisableDarksend = true;\n LogPrintf(\"Wallet is locked and user declined to unlock. Disabling Darksend.\\n\");\n }\n }\n if((nAnonymizeDarkcoinAmount*COIN)-pwalletMain->GetAnonymizedBalance() <= 1.1*COIN && \n walletModel->getEncryptionStatus() == WalletModel::Unlocked && \n darkSendPool.GetMyTransactionCount() == 0){\n LogPrintf(\"Darksend is complete, locking wallet.\\n\");\n walletModel->Lock();\n }\n }\n }\n\n ui->darksendEnabled->setText(\"Enabled\");\n\n std::ostringstream convert;\n convert << pwalletMain->GetAverageAnonymizedRounds() << \"\/\" << nDarksendRounds;\n QString s(convert.str().c_str());\n ui->darksendAvgRounds->setText(s);\n\n }\n\n \/\/if(!darkSendPool.sessionFoundMasternode) return;\n\n int state = darkSendPool.GetState();\n int entries = darkSendPool.GetEntriesCount();\n int accepted = darkSendPool.GetLastEntryAccepted();\n \/\/int countAccepted = darkSendPool.GetCountEntriesAccepted();\n\n std::ostringstream convert;\n\n if(state == POOL_STATUS_ACCEPTING_ENTRIES) {\n if(entries == 0) {\n convert << \"darkSend Status => Idle\";\n showingDarkSendMessage = 0;\n } else if (accepted == 1) {\n convert << \"darkSend Status => Your transaction was accepted into the pool!\";\n if(showingDarkSendMessage % 10 > 8) {\n darkSendPool.lastEntryAccepted = 0;\n showingDarkSendMessage = 0;\n }\n } else {\n if(showingDarkSendMessage % 70 <= 40) convert << \"darkSend Status => ( Entries \" << entries << \"\/\" << POOL_MAX_TRANSACTIONS << \" )\";\n else if(showingDarkSendMessage % 70 <= 50) convert << \"darkSend Status => Waiting for more entries (\" << entries << \"\/\" << POOL_MAX_TRANSACTIONS << \" ) .\";\n else if(showingDarkSendMessage % 70 <= 60) convert << \"darkSend Status => Waiting for more entries (\" << entries << \"\/\" << POOL_MAX_TRANSACTIONS << \" ) ..\";\n else if(showingDarkSendMessage % 70 <= 70) convert << \"darkSend Status => Waiting for more entries (\" << entries << \"\/\" << POOL_MAX_TRANSACTIONS << \" ) ...\";\n }\n } else if(state == POOL_STATUS_SIGNING) {\n if(showingDarkSendMessage % 70 <= 10) convert << \"darkSend Status => SIGNING\";\n else if(showingDarkSendMessage % 70 <= 20) convert << \"darkSend Status => SIGNING ( waiting. )\";\n else if(showingDarkSendMessage % 70 <= 30) convert << \"darkSend Status => SIGNING ( waiting.. )\";\n else if(showingDarkSendMessage % 70 <= 40) convert << \"darkSend Status => SIGNING ( waiting... )\";\n } else if(state == POOL_STATUS_TRANSMISSION) {\n convert << \"darkSend Status => TRANSMISSION\";\n } else if (state == POOL_STATUS_IDLE) {\n convert << \"darkSend Status => POOL_STATUS_IDLE\";\n } else if (state == POOL_STATUS_FINALIZE_TRANSACTION) {\n convert << \"darkSend Status => POOL_STATUS_FINALIZE_TRANSACTION\";\n } else if(state == POOL_STATUS_ERROR) {\n convert << \"darkSend Status => ERROR : \" << darkSendPool.lastMessage;\n } else if(state == POOL_STATUS_SUCCESS) {\n convert << \"darkSend Status => SUCCESS : \" << darkSendPool.lastMessage;\n } else {\n convert << \"darkSend Status => UNKNOWN STATE : ID=\" << state;\n }\n\n if(state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) darkSendPool.Check();\n \n\n QString s(convert.str().c_str());\n\n if(s != ui->darksendStatus->text())\n LogPrintf(\"%s\\n\", convert.str().c_str());\n \n ui->darksendStatus->setText(s);\n\n showingDarkSendMessage++;\n darksendActionCheck++;\n\n \/\/ Get DarkSend Denomination Status\n}\nchanged some text around#include \"overviewpage.h\"\n#include \"ui_overviewpage.h\"\n\n#include \"init.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"optionsmodel.h\"\n#include \"transactiontablemodel.h\"\n#include \"transactionfilterproxy.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n\n#include \n#include \n#include \n\n#define DECORATION_SIZE 64\n#define NUM_ITEMS 3\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n Q_OBJECT\npublic:\n TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)\n {\n\n }\n\n inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n const QModelIndex &index ) const\n {\n painter->save();\n\n QIcon icon = qvariant_cast(index.data(Qt::DecorationRole));\n QRect mainRect = option.rect;\n QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n int xspace = DECORATION_SIZE + 8;\n int ypad = 6;\n int halfheight = (mainRect.height() - 2*ypad)\/2;\n QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);\n QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);\n icon.paint(painter, decorationRect);\n\n QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n QString address = index.data(Qt::DisplayRole).toString();\n qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n QVariant value = index.data(Qt::ForegroundRole);\n QColor foreground = option.palette.color(QPalette::Text);\n if(value.canConvert())\n {\n QBrush brush = qvariant_cast(value);\n foreground = brush.color();\n }\n\n painter->setPen(foreground);\n painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);\n\n if(amount < 0)\n {\n foreground = COLOR_NEGATIVE;\n }\n else if(!confirmed)\n {\n foreground = COLOR_UNCONFIRMED;\n }\n else\n {\n foreground = option.palette.color(QPalette::Text);\n }\n painter->setPen(foreground);\n QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);\n if(!confirmed)\n {\n amountText = QString(\"[\") + amountText + QString(\"]\");\n }\n painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);\n\n painter->setPen(option.palette.color(QPalette::Text));\n painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));\n\n painter->restore();\n }\n\n inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n {\n return QSize(DECORATION_SIZE, DECORATION_SIZE);\n }\n\n int unit;\n\n};\n#include \"overviewpage.moc\"\n\nOverviewPage::OverviewPage(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::OverviewPage),\n clientModel(0),\n walletModel(0),\n currentBalance(-1),\n currentUnconfirmedBalance(-1),\n currentImmatureBalance(-1),\n txdelegate(new TxViewDelegate()),\n filter(0)\n{\n ui->setupUi(this);\n\n \/\/ Recent transactions\n ui->listTransactions->setItemDelegate(txdelegate);\n ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n\n connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));\n\n timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), this, SLOT(darkSendStatus()));\n timer->start(333);\n\n \/\/ init \"out of sync\" warning labels\n ui->labelWalletStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n ui->labelTransactionsStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n\n showingDarkSendMessage = 0;\n darksendActionCheck = 0;\n\n \/\/ start with displaying the \"out of sync\" warnings\n showOutOfSyncWarning(true);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex &index)\n{\n if(filter)\n emit transactionClicked(filter->mapToSource(index));\n}\n\nOverviewPage::~OverviewPage()\n{\n delete ui;\n}\n\nvoid OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance)\n{\n int unit = walletModel->getOptionsModel()->getDisplayUnit();\n currentBalance = balance;\n currentUnconfirmedBalance = unconfirmedBalance;\n currentImmatureBalance = immatureBalance;\n currentAnonymizedBalance = anonymizedBalance;\n ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));\n ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));\n ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));\n ui->labelAnonymized->setText(BitcoinUnits::formatWithUnit(unit, anonymizedBalance));\n\n \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n \/\/ for the non-mining users\n bool showImmature = immatureBalance != 0;\n ui->labelImmature->setVisible(showImmature);\n ui->labelImmatureText->setVisible(showImmature);\n}\n\nvoid OverviewPage::setClientModel(ClientModel *model)\n{\n this->clientModel = model;\n if(model)\n {\n \/\/ Show warning if this is a prerelease version\n connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));\n updateAlerts(model->getStatusBarWarnings());\n }\n}\n\nvoid OverviewPage::setWalletModel(WalletModel *model)\n{\n this->walletModel = model;\n if(model && model->getOptionsModel())\n {\n \/\/ Set up transaction list\n filter = new TransactionFilterProxy();\n filter->setSourceModel(model->getTransactionTableModel());\n filter->setLimit(NUM_ITEMS);\n filter->setDynamicSortFilter(true);\n filter->setSortRole(Qt::EditRole);\n filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);\n\n ui->listTransactions->setModel(filter);\n ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n\n \/\/ Keep up to date with wallet\n setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance());\n connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));\n\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n }\n\n \/\/ update the display unit, to not use the default (\"BTC\")\n updateDisplayUnit();\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n if(walletModel && walletModel->getOptionsModel())\n {\n if(currentBalance != -1)\n setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentAnonymizedBalance);\n\n \/\/ Update txdelegate->unit with the current unit\n txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();\n\n ui->listTransactions->update();\n }\n}\n\nvoid OverviewPage::updateAlerts(const QString &warnings)\n{\n this->ui->labelAlerts->setVisible(!warnings.isEmpty());\n this->ui->labelAlerts->setText(warnings);\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n ui->labelWalletStatus->setVisible(fShow);\n ui->labelTransactionsStatus->setVisible(fShow);\n}\n\nvoid OverviewPage::darkSendStatus()\n{\n if(fDisableDarksend) {\n if(nBestHeight != cachedNumBlocks)\n {\n cachedNumBlocks = nBestHeight;\n\n ui->darksendEnabled->setText(\"Disabled\");\n ui->darksendStatus->setText(\"\");\n\n std::ostringstream convert;\n convert << pwalletMain->GetAverageAnonymizedRounds() << \"\/\" << nDarksendRounds;\n QString s(convert.str().c_str());\n ui->darksendAvgRounds->setText(s);\n }\n\n return;\n }\n\n \/\/ check darksend status and unlock if needed\n if(nBestHeight != cachedNumBlocks)\n {\n \/\/ Balance and number of transactions might have changed\n cachedNumBlocks = nBestHeight;\n\n if (pwalletMain->GetBalance() - pwalletMain->GetAnonymizedBalance() > 2*COIN){\n if (walletModel->getEncryptionStatus() != WalletModel::Unencrypted){\n if((nAnonymizeDarkcoinAmount*COIN)-pwalletMain->GetAnonymizedBalance() > 1.1*COIN && walletModel->getEncryptionStatus() == WalletModel::Locked){\n WalletModel::UnlockContext ctx(walletModel->requestUnlock());\n if(!ctx.isValid()){\n \/\/unlock was cancelled\n fDisableDarksend = true;\n LogPrintf(\"Wallet is locked and user declined to unlock. Disabling Darksend.\\n\");\n }\n }\n if((nAnonymizeDarkcoinAmount*COIN)-pwalletMain->GetAnonymizedBalance() <= 1.1*COIN && \n walletModel->getEncryptionStatus() == WalletModel::Unlocked && \n darkSendPool.GetMyTransactionCount() == 0){\n LogPrintf(\"Darksend is complete, locking wallet.\\n\");\n walletModel->Lock();\n }\n }\n }\n\n ui->darksendEnabled->setText(\"Enabled\");\n\n std::ostringstream convert;\n convert << pwalletMain->GetAverageAnonymizedRounds() << \"\/\" << nDarksendRounds;\n QString s(convert.str().c_str());\n ui->darksendAvgRounds->setText(s);\n\n }\n\n \/\/if(!darkSendPool.sessionFoundMasternode) return;\n\n int state = darkSendPool.GetState();\n int entries = darkSendPool.GetEntriesCount();\n int accepted = darkSendPool.GetLastEntryAccepted();\n \/\/int countAccepted = darkSendPool.GetCountEntriesAccepted();\n\n std::ostringstream convert;\n\n if(state == POOL_STATUS_ACCEPTING_ENTRIES) {\n if(entries == 0) {\n convert << \"Idle\";\n showingDarkSendMessage = 0;\n } else if (accepted == 1) {\n convert << \"Your transaction was accepted into the pool!\";\n if(showingDarkSendMessage % 10 > 8) {\n darkSendPool.lastEntryAccepted = 0;\n showingDarkSendMessage = 0;\n }\n } else {\n if(showingDarkSendMessage % 70 <= 40) convert << \"Submitted to masternode => ( Entries \" << entries << \"\/\" << POOL_MAX_TRANSACTIONS << \" )\";\n else if(showingDarkSendMessage % 70 <= 50) convert << \"Submitted to masternode => Waiting for more entries (\" << entries << \"\/\" << POOL_MAX_TRANSACTIONS << \" ) .\";\n else if(showingDarkSendMessage % 70 <= 60) convert << \"Submitted to masternode => Waiting for more entries (\" << entries << \"\/\" << POOL_MAX_TRANSACTIONS << \" ) ..\";\n else if(showingDarkSendMessage % 70 <= 70) convert << \"Submitted to masternode => Waiting for more entries (\" << entries << \"\/\" << POOL_MAX_TRANSACTIONS << \" ) ...\";\n }\n } else if(state == POOL_STATUS_SIGNING) {\n if(showingDarkSendMessage % 70 <= 10) convert << \"Found enough users => SIGNING\";\n else if(showingDarkSendMessage % 70 <= 20) convert << \"Found enough users => SIGNING ( waiting. )\";\n else if(showingDarkSendMessage % 70 <= 30) convert << \"Found enough users => SIGNING ( waiting.. )\";\n else if(showingDarkSendMessage % 70 <= 40) convert << \"Found enough users => SIGNING ( waiting... )\";\n } else if(state == POOL_STATUS_TRANSMISSION) {\n convert << \"Found enough users => TRANSMISSION\";\n } else if (state == POOL_STATUS_IDLE) {\n convert << \"Found enough users => POOL_STATUS_IDLE\";\n } else if (state == POOL_STATUS_FINALIZE_TRANSACTION) {\n convert << \"Found enough users => POOL_STATUS_FINALIZE_TRANSACTION\";\n } else if(state == POOL_STATUS_ERROR) {\n convert << \"Found enough users => ERROR : \" << darkSendPool.lastMessage;\n } else if(state == POOL_STATUS_SUCCESS) {\n convert << \"Found enough users => SUCCESS : \" << darkSendPool.lastMessage;\n } else {\n convert << \"Found enough users => UNKNOWN STATE : ID=\" << state;\n }\n\n if(state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) darkSendPool.Check();\n \n\n QString s(convert.str().c_str());\n\n if(s != ui->darksendStatus->text())\n LogPrintf(\"%s\\n\", convert.str().c_str());\n \n ui->darksendStatus->setText(s);\n\n showingDarkSendMessage++;\n darksendActionCheck++;\n\n \/\/ Get DarkSend Denomination Status\n}\n<|endoftext|>"} {"text":"#include \"guardian.h\"\n#include \"device_setup.h\"\n#include \"prefs_link.h\"\n#include \"ltr_model.h\"\n#include \n#include \n\nGuardian::Guardian(QWidget *parent) : parentWidget(parent), mdlType(-1), devType(-1), \n devDesc(QString::fromUtf8(\"\"))\n{\n}\n\nvoid Guardian::regTgt(ModelEdit *me)\n{\n QObject::connect(me, SIGNAL(modelSelected(int)), this, SLOT(modelSelected(int)));\n}\n\nvoid Guardian::regTgt(DeviceSetup *ds)\n{\n QObject::connect(ds, SIGNAL(deviceTypeChanged(int, const QString &)), \n this, SLOT(deviceTypeChanged(int, const QString &)));\n}\n\nvoid Guardian::checkDeviceNModel()\n{\n if((devType == WEBCAM_FT) || (devType == MACWEBCAM_FT)){\n \/\/face tracker needs face model\n if(mdlType != MDL_FACE){\n QMessageBox::warning(parentWidget, QString::fromUtf8(\"Linuxtrack\"),\n devDesc + QString::fromUtf8(\" requires Face type Model!\"), QMessageBox::Ok);\n }\n }else if(devType == JOYSTICK){\n \/\/face tracker needs face model\n if(mdlType != MDL_ABSOLUTE){\n QMessageBox::warning(parentWidget, QString::fromUtf8(\"Linuxtrack\"),\n devDesc + QString::fromUtf8(\" requires Absolute type Model!\"), QMessageBox::Ok);\n }\n }else{\n \/\/ordinary tracker needs other than face model\n if(mdlType == MDL_FACE){\n QMessageBox::warning(parentWidget, QString::fromUtf8(\"Linuxtrack\"),\n devDesc + QString::fromUtf8(\" won't work correctly with Face type Model!\"), \n QMessageBox::Ok);\n }else if(mdlType == MDL_ABSOLUTE){\n QMessageBox::warning(parentWidget, QString::fromUtf8(\"Linuxtrack\"),\n devDesc + QString::fromUtf8(\" won't work correctly with Absolute type Model!\"), \n QMessageBox::Ok);\n }\n }\n}\n\nvoid Guardian::modelSelected(int modelType)\n{\n mdlType = modelType;\n if(devType == -1){\n return;\n }\n checkDeviceNModel();\n}\n \nvoid Guardian::deviceTypeChanged(int deviceType, const QString &desc)\n{\n devType = deviceType;\n devDesc = desc;\n if(mdlType == -1){\n return;\n }\n checkDeviceNModel();\n}\n \n\n\n\n\nPs3Eye facetracker won't get model warning anymore.#include \"guardian.h\"\n#include \"device_setup.h\"\n#include \"prefs_link.h\"\n#include \"ltr_model.h\"\n#include \n#include \n\nGuardian::Guardian(QWidget *parent) : parentWidget(parent), mdlType(-1), devType(-1), \n devDesc(QString::fromUtf8(\"\"))\n{\n}\n\nvoid Guardian::regTgt(ModelEdit *me)\n{\n QObject::connect(me, SIGNAL(modelSelected(int)), this, SLOT(modelSelected(int)));\n}\n\nvoid Guardian::regTgt(DeviceSetup *ds)\n{\n QObject::connect(ds, SIGNAL(deviceTypeChanged(int, const QString &)), \n this, SLOT(deviceTypeChanged(int, const QString &)));\n}\n\nvoid Guardian::checkDeviceNModel()\n{\n if((devType == WEBCAM_FT) || (devType == MACWEBCAM_FT) || (devType == MACPS3EYE_FT)){\n \/\/face tracker needs face model\n if(mdlType != MDL_FACE){\n QMessageBox::warning(parentWidget, QString::fromUtf8(\"Linuxtrack\"),\n devDesc + QString::fromUtf8(\" requires Face type Model!\"), QMessageBox::Ok);\n }\n }else if(devType == JOYSTICK){\n \/\/face tracker needs face model\n if(mdlType != MDL_ABSOLUTE){\n QMessageBox::warning(parentWidget, QString::fromUtf8(\"Linuxtrack\"),\n devDesc + QString::fromUtf8(\" requires Absolute type Model!\"), QMessageBox::Ok);\n }\n }else{\n \/\/ordinary tracker needs other than face model\n if(mdlType == MDL_FACE){\n QMessageBox::warning(parentWidget, QString::fromUtf8(\"Linuxtrack\"),\n devDesc + QString::fromUtf8(\" won't work correctly with Face type Model!\"), \n QMessageBox::Ok);\n }else if(mdlType == MDL_ABSOLUTE){\n QMessageBox::warning(parentWidget, QString::fromUtf8(\"Linuxtrack\"),\n devDesc + QString::fromUtf8(\" won't work correctly with Absolute type Model!\"), \n QMessageBox::Ok);\n }\n }\n}\n\nvoid Guardian::modelSelected(int modelType)\n{\n mdlType = modelType;\n if(devType == -1){\n return;\n }\n checkDeviceNModel();\n}\n \nvoid Guardian::deviceTypeChanged(int deviceType, const QString &desc)\n{\n devType = deviceType;\n devDesc = desc;\n if(mdlType == -1){\n return;\n }\n checkDeviceNModel();\n}\n \n\n\n\n\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2002 by Frank Richter\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \n#include \n#include \n\n#include \"cssysdef.h\"\n#include \"csutil\/util.h\"\n#include \"csutil\/nulcache.h\"\n\n\/\/------------------------------------------------------------------------\n\nSCF_IMPLEMENT_IBASE (csNullCacheManager)\n SCF_IMPLEMENTS_INTERFACE (iCacheManager)\nSCF_IMPLEMENT_IBASE_END\n\ncsNullCacheManager::csNullCacheManager ()\n{\n SCF_CONSTRUCT_IBASE (NULL);\n}\n\ncsNullCacheManager::~csNullCacheManager ()\n{\n}\n\nvoid csNullCacheManager::SetCurrentType (const char* type)\n{\n}\n\nvoid csNullCacheManager::SetCurrentScope (const char* scope)\n{\n}\n\nbool csNullCacheManager::CacheData (void*, uint32,\n \tconst char*, const char*, uint32)\n{\n return false;\n}\n\niDataBuffer* csNullCacheManager::ReadCache (\n \tconst char* type, const char* scope, uint32 id)\n{\n return NULL;\n}\n\nbool csNullCacheManager::ClearCache (const char*, const char*,\n \tconst uint32*)\n{\n return false;\n}\n\nEliminated copilation warnings.\/*\n Copyright (C) 2002 by Frank Richter\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \n#include \n#include \n\n#include \"cssysdef.h\"\n#include \"csutil\/util.h\"\n#include \"csutil\/nulcache.h\"\n\n\/\/------------------------------------------------------------------------\n\nSCF_IMPLEMENT_IBASE (csNullCacheManager)\n SCF_IMPLEMENTS_INTERFACE (iCacheManager)\nSCF_IMPLEMENT_IBASE_END\n\ncsNullCacheManager::csNullCacheManager ()\n{\n SCF_CONSTRUCT_IBASE (NULL);\n}\n\ncsNullCacheManager::~csNullCacheManager ()\n{\n}\n\nvoid csNullCacheManager::SetCurrentType (const char*)\n{\n}\n\nvoid csNullCacheManager::SetCurrentScope (const char*)\n{\n}\n\nbool csNullCacheManager::CacheData (void*, uint32,\n \tconst char*, const char*, uint32)\n{\n return false;\n}\n\niDataBuffer* csNullCacheManager::ReadCache (\n \tconst char* \/*type*\/, const char* \/*scope*\/, uint32 \/*id*\/)\n{\n return NULL;\n}\n\nbool csNullCacheManager::ClearCache (const char*, const char*,\n \tconst uint32*)\n{\n return false;\n}\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n#include \"otbCoordinateToName.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass ReadImageInfo : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef ReadImageInfo Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(ReadImageInfo, otb::Application);\n\nprivate:\n ReadImageInfo()\n {\n SetName(\"ReadImageInfo\");\n SetDescription(\"Get information about the image\");\n\n \/\/ Documentation\n SetDocName(\"Read image information Application\");\n SetDocLongDescription(\"Display informations about the input image like: image size, metadata, projections...\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(\"Utilities\");\n AddDocTag(Tags::Meta);\n }\n\n virtual ~ReadImageInfo()\n {\n }\n\n void DoCreateParameters()\n {\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n \n \/\/Create output parameters to store image informations\n AddParameter(ParameterType_Int,\"sizex\",\"Size X\");\n GetParameterByKey(\"sizex\")->SetRole(Role_Output);\n AddParameter(ParameterType_Int,\"sizey\",\"Size Y\");\n GetParameterByKey(\"sizey\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_Int,\"spacingx\",\"Pixel Size X\");\n GetParameterByKey(\"spacingx\")->SetRole(Role_Output);\n AddParameter(ParameterType_Int,\"spacingy\",\"Pixel Size Y\");\n GetParameterByKey(\"spacingy\")->SetRole(Role_Output);\n AddParameter(ParameterType_Int,\"numberbands\",\"Number Of Bands\");\n GetParameterByKey(\"numberbands\")->SetRole(Role_Output);\n \n \n AddParameter(ParameterType_String,\"sensor\",\"Sensor id\");\n GetParameterByKey(\"sensor\")->SetRole(Role_Output);\n MandatoryOff(\"sensor\");\n \n AddParameter(ParameterType_String,\"id\",\"Id of the image\");\n GetParameterByKey(\"id\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_String,\"time\",\"Acquisition time\");\n GetParameterByKey(\"time\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_Float,\"ullat\",\"Upper left lattitude\");\n GetParameterByKey(\"ullat\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"ullat\", 0);\n AddParameter(ParameterType_Float,\"ullon\",\"Upper left longitude\");\n GetParameterByKey(\"ullon\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"ullon\", 0);\n AddParameter(ParameterType_Float,\"urlat\",\"Upper right lattitude\");\n GetParameterByKey(\"urlat\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"urlat\", 0);\n AddParameter(ParameterType_Float,\"urlon\",\"Upper right longitude\");\n GetParameterByKey(\"urlon\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"urlon\", 0);\n AddParameter(ParameterType_Float,\"lrlat\",\"Lower right lattitude\");\n GetParameterByKey(\"lrlat\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"lrlat\", 0);\n AddParameter(ParameterType_Float,\"lrlon\",\"Lower right longitude\");\n GetParameterByKey(\"lrlon\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"lrlon\", 0);\n AddParameter(ParameterType_Float,\"lllat\",\"Lower left lattitude\");\n GetParameterByKey(\"lllat\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"lllat\", 0);\n AddParameter(ParameterType_Float,\"lllon\",\"Lower left longitude\");\n GetParameterByKey(\"lllon\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"lllon\", 0);\n \n AddParameter(ParameterType_String,\"town\",\"Main town near center of image\");\n GetParameterByKey(\"town\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_String,\"country\",\"Country of the image\");\n GetParameterByKey(\"country\")->SetRole(Role_Output);\n\n AddParameter(ParameterType_Group, \"rgb\", \"Default RGB Display\");\n SetParameterDescription(\"rgb\",\"This group of parameters allows to access to the default rgb composition.\");\n GetParameterByKey(\"rgb\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_Int, \"rgb.r\", \"Red Band\");\n SetParameterDescription(\"rgb.r\",\"Red band Number\");\n SetDefaultParameterInt(\"rgb.r\", 1);\n \n AddParameter(ParameterType_Int, \"rgb.g\", \"Green Band\");\n SetParameterDescription(\"rgb.g\",\"Green band Number\");\n SetDefaultParameterInt(\"rgb.g\", 2);\n\n AddParameter(ParameterType_Int, \"rgb.b\", \"Blue Band\");\n SetParameterDescription(\"rgb.b\",\"Blue band Number\");\n SetDefaultParameterInt(\"rgb.b\", 3);\n \n AddParameter(ParameterType_String,\"projectionref\",\"Projection Coordinate System\"); \n GetParameterByKey(\"projectionref\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_String,\"keywordlist\",\"Image Keywordlist\");\n GetParameterByKey(\"keywordlist\")->SetRole(Role_Output);\n\n AddParameter(ParameterType_Group, \"gcp\", \"Ground Control Points informations\");\n SetParameterDescription(\"gcp\",\"This group of parameters allows to access to the GCPs informations.\");\n GetParameterByKey(\"gcp\")->SetRole(Role_Output);\n\n AddParameter(ParameterType_Int, \"gcp.count\", \"GCPs Number\");\n SetParameterDescription(\"gcp.count\",\"Number of GCPs\");\n SetDefaultParameterInt(\"gcp.count\", 0);\n\n AddParameter(ParameterType_String,\"gcp.proj\",\"GCP Projection System\");\n\n AddParameter(ParameterType_StringList,\"gcp.ids\",\"GCPs Id\");\n AddParameter(ParameterType_StringList,\"gcp.info\",\"GCPs Info\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"QB_Toulouse_Ortho_XS.tif\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n void DoExecute()\n {\n try \n {\n FloatVectorImageType::Pointer inImage = GetParameterImage(\"in\");\n \/\/ Read informations\n typedef otb::ImageMetadataInterfaceBase ImageMetadataInterfaceType;\n ImageMetadataInterfaceType::Pointer metadataInterface = ImageMetadataInterfaceFactory::CreateIMI(inImage->GetMetaDataDictionary());\n\n \/\/Get image size\n SetParameterInt(\"sizex\",inImage->GetLargestPossibleRegion().GetSize()[0]);\n SetParameterInt(\"sizey\",inImage->GetLargestPossibleRegion().GetSize()[1]);\n\n \/\/Get image spacing\n SetParameterInt(\"spacingx\",inImage->GetSpacing()[0]);\n SetParameterInt(\"spacingy\",inImage->GetSpacing()[1]);\n \n SetParameterInt(\"numberbands\",inImage->GetNumberOfComponentsPerPixel());\n\n \/\/std::cout << \"metadata \" << metadataInterface << std::endl;\n SetParameterString(\"sensor\",metadataInterface->GetSensorID());\n SetParameterString(\"id\",metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"image_id\"));\n SetParameterString(\"projectionref\",metadataInterface->GetProjectionRef());\n \n \/\/ Format acquisition time\n itk::OStringStream osstime;\n osstime<GetYear()<<\"-\";\n if(metadataInterface->GetMonth()<10)\n\tosstime<<\"0\";\n osstime<GetMonth()<<\"-\";\n if(metadataInterface->GetDay()<10)\n\tosstime<<\"0\";\n osstime<GetDay()<<\"T\";\n if(metadataInterface->GetHour()<10)\n\tosstime<<\"0\";\n osstime<GetHour()<<\":\";\n if(metadataInterface->GetMinute()<10)\n\tosstime<<\"0\";\n osstime<GetMinute();\n osstime<<\":00\";\n SetParameterString(\"time\",osstime.str());\n\n itk::OStringStream osskeywordlist;\n osskeywordlist<GetImageKeywordlist() << std::endl;\t\n SetParameterString(\"keywordlist\",osskeywordlist.str());\n\n double ullat = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ul_lat\").c_str());\n double ullon = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ul_lon\").c_str());\n double urlat = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ur_lat\").c_str());\n double urlon = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ur_lon\").c_str());\n double lrlat = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"lr_lat\").c_str());\n double lrlon = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"lr_lon\").c_str());\n double lllat = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ll_lat\").c_str());\n double lllon = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ll_lon\").c_str());\n \n SetParameterInt(\"rgb.r\",metadataInterface->GetDefaultDisplay()[0]);\n SetParameterInt(\"rgb.g\",metadataInterface->GetDefaultDisplay()[1]);\n SetParameterInt(\"rgb.b\",metadataInterface->GetDefaultDisplay()[2]);\n \n SetParameterInt(\"gcp.count\",metadataInterface->GetGCPCount());\n SetParameterString(\"gcp.proj\",metadataInterface->GetGCPProjection());\n \n std::vector gcp_ids;\n std::vector gcp_infos;\n\n for(int gcpIdx = 0; gcpIdx < GetParameterInt(\"gcp.count\"); ++ gcpIdx)\n\t{\n\tgcp_ids.push_back(metadataInterface->GetGCPId(gcpIdx));\n\tgcp_infos.push_back(metadataInterface->GetGCPInfo(gcpIdx));\n\t}\n \n SetParameterStringList(\"gcp.ids\",gcp_ids);\n SetParameterStringList(\"gcp.info\",gcp_infos);\n \n \/\/ Retrieve footprint\n SetParameterFloat(\"ullat\",ullat);\n SetParameterFloat(\"ullon\",ullon);\n SetParameterFloat(\"urlat\",urlat);\n SetParameterFloat(\"urlon\",urlon);\n SetParameterFloat(\"lrlat\",lrlat);\n SetParameterFloat(\"lrlon\",lrlon);\n SetParameterFloat(\"lllat\",lllat);\n SetParameterFloat(\"lllon\",lllon);\n\n double centerlat = 0.25*(ullat+urlat+lrlat+lllat);\n double centerlon = 0.25*(ullon+urlon+lrlon+lllon);\n\n CoordinateToName::Pointer coord2name = CoordinateToName::New();\n coord2name->SetLat(centerlat);\n coord2name->SetLon(centerlon);\n coord2name->Evaluate();\n\n SetParameterString(\"town\",coord2name->GetPlaceName());\n SetParameterString(\"country\",coord2name->GetCountryName());\n }\n catch ( itk::ExceptionObject & err )\n {\n \/\/Do nothing at all\n }\n \/\/FIXME Logger must output also parameter groups\n this->GetLogger()->Info(\"\");\n }\n\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::ReadImageInfo)\n\nSTYLE:kwstyle\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n#include \"otbCoordinateToName.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass ReadImageInfo : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef ReadImageInfo Self;\n typedef Application Superclass;\n typedef itk::SmartPointer Pointer;\n typedef itk::SmartPointer ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(ReadImageInfo, otb::Application);\n\nprivate:\n ReadImageInfo()\n {\n SetName(\"ReadImageInfo\");\n SetDescription(\"Get information about the image\");\n\n \/\/ Documentation\n SetDocName(\"Read image information Application\");\n SetDocLongDescription(\"Display informations about the input image like: image size, metadata, projections...\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(\"Utilities\");\n AddDocTag(Tags::Meta);\n }\n\n virtual ~ReadImageInfo()\n {\n }\n\n void DoCreateParameters()\n {\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n \n \/\/Create output parameters to store image informations\n AddParameter(ParameterType_Int,\"sizex\",\"Size X\");\n GetParameterByKey(\"sizex\")->SetRole(Role_Output);\n AddParameter(ParameterType_Int,\"sizey\",\"Size Y\");\n GetParameterByKey(\"sizey\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_Int,\"spacingx\",\"Pixel Size X\");\n GetParameterByKey(\"spacingx\")->SetRole(Role_Output);\n AddParameter(ParameterType_Int,\"spacingy\",\"Pixel Size Y\");\n GetParameterByKey(\"spacingy\")->SetRole(Role_Output);\n AddParameter(ParameterType_Int,\"numberbands\",\"Number Of Bands\");\n GetParameterByKey(\"numberbands\")->SetRole(Role_Output);\n \n \n AddParameter(ParameterType_String,\"sensor\",\"Sensor id\");\n GetParameterByKey(\"sensor\")->SetRole(Role_Output);\n MandatoryOff(\"sensor\");\n \n AddParameter(ParameterType_String,\"id\",\"Id of the image\");\n GetParameterByKey(\"id\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_String,\"time\",\"Acquisition time\");\n GetParameterByKey(\"time\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_Float,\"ullat\",\"Upper left lattitude\");\n GetParameterByKey(\"ullat\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"ullat\", 0);\n AddParameter(ParameterType_Float,\"ullon\",\"Upper left longitude\");\n GetParameterByKey(\"ullon\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"ullon\", 0);\n AddParameter(ParameterType_Float,\"urlat\",\"Upper right lattitude\");\n GetParameterByKey(\"urlat\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"urlat\", 0);\n AddParameter(ParameterType_Float,\"urlon\",\"Upper right longitude\");\n GetParameterByKey(\"urlon\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"urlon\", 0);\n AddParameter(ParameterType_Float,\"lrlat\",\"Lower right lattitude\");\n GetParameterByKey(\"lrlat\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"lrlat\", 0);\n AddParameter(ParameterType_Float,\"lrlon\",\"Lower right longitude\");\n GetParameterByKey(\"lrlon\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"lrlon\", 0);\n AddParameter(ParameterType_Float,\"lllat\",\"Lower left lattitude\");\n GetParameterByKey(\"lllat\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"lllat\", 0);\n AddParameter(ParameterType_Float,\"lllon\",\"Lower left longitude\");\n GetParameterByKey(\"lllon\")->SetRole(Role_Output);\n SetDefaultParameterFloat(\"lllon\", 0);\n \n AddParameter(ParameterType_String,\"town\",\"Main town near center of image\");\n GetParameterByKey(\"town\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_String,\"country\",\"Country of the image\");\n GetParameterByKey(\"country\")->SetRole(Role_Output);\n\n AddParameter(ParameterType_Group, \"rgb\", \"Default RGB Display\");\n SetParameterDescription(\"rgb\",\"This group of parameters allows to access to the default rgb composition.\");\n GetParameterByKey(\"rgb\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_Int, \"rgb.r\", \"Red Band\");\n SetParameterDescription(\"rgb.r\",\"Red band Number\");\n SetDefaultParameterInt(\"rgb.r\", 1);\n \n AddParameter(ParameterType_Int, \"rgb.g\", \"Green Band\");\n SetParameterDescription(\"rgb.g\",\"Green band Number\");\n SetDefaultParameterInt(\"rgb.g\", 2);\n\n AddParameter(ParameterType_Int, \"rgb.b\", \"Blue Band\");\n SetParameterDescription(\"rgb.b\",\"Blue band Number\");\n SetDefaultParameterInt(\"rgb.b\", 3);\n \n AddParameter(ParameterType_String,\"projectionref\",\"Projection Coordinate System\"); \n GetParameterByKey(\"projectionref\")->SetRole(Role_Output);\n \n AddParameter(ParameterType_String,\"keywordlist\",\"Image Keywordlist\");\n GetParameterByKey(\"keywordlist\")->SetRole(Role_Output);\n\n AddParameter(ParameterType_Group, \"gcp\", \"Ground Control Points informations\");\n SetParameterDescription(\"gcp\",\"This group of parameters allows to access to the GCPs informations.\");\n GetParameterByKey(\"gcp\")->SetRole(Role_Output);\n\n AddParameter(ParameterType_Int, \"gcp.count\", \"GCPs Number\");\n SetParameterDescription(\"gcp.count\",\"Number of GCPs\");\n SetDefaultParameterInt(\"gcp.count\", 0);\n\n AddParameter(ParameterType_String,\"gcp.proj\",\"GCP Projection System\");\n\n AddParameter(ParameterType_StringList,\"gcp.ids\",\"GCPs Id\");\n AddParameter(ParameterType_StringList,\"gcp.info\",\"GCPs Info\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"QB_Toulouse_Ortho_XS.tif\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n void DoExecute()\n {\n try \n {\n FloatVectorImageType::Pointer inImage = GetParameterImage(\"in\");\n \/\/ Read informations\n typedef otb::ImageMetadataInterfaceBase ImageMetadataInterfaceType;\n ImageMetadataInterfaceType::Pointer metadataInterface = ImageMetadataInterfaceFactory::CreateIMI(inImage->GetMetaDataDictionary());\n\n \/\/Get image size\n SetParameterInt(\"sizex\",inImage->GetLargestPossibleRegion().GetSize()[0]);\n SetParameterInt(\"sizey\",inImage->GetLargestPossibleRegion().GetSize()[1]);\n\n \/\/Get image spacing\n SetParameterInt(\"spacingx\",inImage->GetSpacing()[0]);\n SetParameterInt(\"spacingy\",inImage->GetSpacing()[1]);\n \n SetParameterInt(\"numberbands\",inImage->GetNumberOfComponentsPerPixel());\n\n \/\/std::cout << \"metadata \" << metadataInterface << std::endl;\n SetParameterString(\"sensor\",metadataInterface->GetSensorID());\n SetParameterString(\"id\",metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"image_id\"));\n SetParameterString(\"projectionref\",metadataInterface->GetProjectionRef());\n \n \/\/ Format acquisition time\n itk::OStringStream osstime;\n osstime<GetYear()<<\"-\";\n if(metadataInterface->GetMonth()<10)\n osstime<<\"0\";\n osstime<GetMonth()<<\"-\";\n if(metadataInterface->GetDay()<10)\n osstime<<\"0\";\n osstime<GetDay()<<\"T\";\n if(metadataInterface->GetHour()<10)\n osstime<<\"0\";\n osstime<GetHour()<<\":\";\n if(metadataInterface->GetMinute()<10)\n osstime<<\"0\";\n osstime<GetMinute();\n osstime<<\":00\";\n SetParameterString(\"time\",osstime.str());\n\n itk::OStringStream osskeywordlist;\n osskeywordlist<GetImageKeywordlist() << std::endl; \n SetParameterString(\"keywordlist\",osskeywordlist.str());\n\n double ullat = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ul_lat\").c_str());\n double ullon = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ul_lon\").c_str());\n double urlat = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ur_lat\").c_str());\n double urlon = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ur_lon\").c_str());\n double lrlat = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"lr_lat\").c_str());\n double lrlon = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"lr_lon\").c_str());\n double lllat = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ll_lat\").c_str());\n double lllon = atof(metadataInterface->GetImageKeywordlist().GetMetadataByKey(\"ll_lon\").c_str());\n \n SetParameterInt(\"rgb.r\",metadataInterface->GetDefaultDisplay()[0]);\n SetParameterInt(\"rgb.g\",metadataInterface->GetDefaultDisplay()[1]);\n SetParameterInt(\"rgb.b\",metadataInterface->GetDefaultDisplay()[2]);\n \n SetParameterInt(\"gcp.count\",metadataInterface->GetGCPCount());\n SetParameterString(\"gcp.proj\",metadataInterface->GetGCPProjection());\n \n std::vector gcp_ids;\n std::vector gcp_infos;\n\n for(int gcpIdx = 0; gcpIdx < GetParameterInt(\"gcp.count\"); ++ gcpIdx)\n {\n gcp_ids.push_back(metadataInterface->GetGCPId(gcpIdx));\n gcp_infos.push_back(metadataInterface->GetGCPInfo(gcpIdx));\n }\n \n SetParameterStringList(\"gcp.ids\",gcp_ids);\n SetParameterStringList(\"gcp.info\",gcp_infos);\n \n \/\/ Retrieve footprint\n SetParameterFloat(\"ullat\",ullat);\n SetParameterFloat(\"ullon\",ullon);\n SetParameterFloat(\"urlat\",urlat);\n SetParameterFloat(\"urlon\",urlon);\n SetParameterFloat(\"lrlat\",lrlat);\n SetParameterFloat(\"lrlon\",lrlon);\n SetParameterFloat(\"lllat\",lllat);\n SetParameterFloat(\"lllon\",lllon);\n\n double centerlat = 0.25*(ullat+urlat+lrlat+lllat);\n double centerlon = 0.25*(ullon+urlon+lrlon+lllon);\n\n CoordinateToName::Pointer coord2name = CoordinateToName::New();\n coord2name->SetLat(centerlat);\n coord2name->SetLon(centerlon);\n coord2name->Evaluate();\n\n SetParameterString(\"town\",coord2name->GetPlaceName());\n SetParameterString(\"country\",coord2name->GetCountryName());\n }\n catch ( itk::ExceptionObject & err )\n {\n \/\/Do nothing at all\n }\n \/\/FIXME Logger must output also parameter groups\n this->GetLogger()->Info(\"\");\n }\n\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::ReadImageInfo)\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"disk.h\"\n#include \"command.h\"\n#include \"error_handling.h\"\n#include \"os.h\"\n#include \"potions.h\"\n#include \"scrolls.h\"\n#include \"io.h\"\n#include \"armor.h\"\n#include \"daemons.h\"\n#include \"colors.h\"\n#include \"level.h\"\n#include \"rings.h\"\n#include \"misc.h\"\n#include \"player.h\"\n#include \"weapons.h\"\n#include \"wand.h\"\n#include \"options.h\"\n#include \"rogue.h\"\n#include \"traps.h\"\n\n#include \"game.h\"\n\nusing namespace std;\n\nGame* Game::game_ptr = nullptr;\nIO* Game::io = nullptr;\nLevel* Game::level = nullptr;\nstring* Game::whoami = nullptr;\nstring* Game::save_game_path = nullptr;\nint Game::current_level = 1;\nint Game::levels_without_food = 0;\n\nvoid Game::exit() {\n if (game_ptr != nullptr) {\n delete game_ptr;\n }\n ::exit(0);\n}\n\nvoid Game::new_level(int dungeon_level) {\n\n Game::current_level = dungeon_level;\n\n if (Game::level != nullptr) {\n delete Game::level;\n }\n\n Game::level = new Level();\n\n \/\/ Drop player in the new dungeon level\n if (player == nullptr) {\n player = new Player(true);\n }\n\n Coordinate new_player_pos = player->get_position();\n Game::level->get_random_room_coord(nullptr, &new_player_pos, 0, true);\n player->set_position(new_player_pos);\n\n \/\/ Unhold player just in case\n player->set_not_held();\n}\n\nint Game::run() {\n\n \/\/ Try to crash cleanly, and autosave if possible\n \/\/ Unless we are debugging, since that messes with gdb\/lldb\n#ifdef NDEBUG\n signal(SIGHUP, save_auto);\n signal(SIGQUIT, command_signal_endit);\n signal(SIGILL, save_auto);\n signal(SIGTRAP, save_auto);\n signal(SIGIOT, save_auto);\n signal(SIGFPE, save_auto);\n signal(SIGBUS, save_auto);\n signal(SIGSEGV, save_auto);\n signal(SIGSYS, save_auto);\n signal(SIGTERM, save_auto);\n signal(SIGINT, command_signal_quit);\n#else\n Game::io->message(\"Seed: #\" + to_string(starting_seed));\n#endif\n\n player->set_previous_room(Game::level->get_room(player->get_position()));\n\n#ifdef NDEBUG\n try {\n for (;;) command();\n } catch (const std::runtime_error &ex) {\n endwin();\n cout << ex.what() << endl;\n return 1;\n }\n#else\n for (;;) command();\n#endif\n\n \/\/ CODE NOT REACHED\n}\n\nGame::Game(string const& whoami_, string const& save_path_)\n : starting_seed(os_rand_seed) {\n Game::whoami = new string(whoami_);\n Game::save_game_path = new string(save_path_);\n\n if (game_ptr != nullptr) {\n error(\"Game is a singleton class\");\n }\n game_ptr = this;\n cout << \"Hello \" << *whoami << \", just a moment while I dig the dungeon...\" << flush;\n\n \/\/ Init stuff\n Game::io = new IO(); \/\/ Graphics\n Scroll::init_scrolls(); \/\/ Names of scrolls\n Color::init_colors(); \/\/ Colors for potions and stuff\n Potion::init_potions(); \/\/ Colors of potions\n Ring::init_rings(); \/\/ Stone settings of rings\n Wand::init_wands(); \/\/ Materials of wands\n Daemons::init_daemons(); \/\/ Over-time-effects\n Monster::init_monsters(); \/\/ Monster types\n Trap::init_traps(); \/\/ Trap types\n Game::new_level(Game::current_level); \/\/ Level (and player)\n\n \/\/ Start up daemons and fuses\n Daemons::daemon_start(Daemons::runners_move, AFTER);\n Daemons::daemon_start(Daemons::doctor, AFTER);\n Daemons::daemon_start(Daemons::ring_abilities, AFTER);\n}\n\nGame::~Game() {\n Trap::free_traps();\n Monster::free_monsters();\n Daemons::free_daemons();\n Wand::free_wands();\n Ring::free_rings();\n Potion::free_potions();\n Color::free_colors();\n Scroll::free_scrolls();\n\n delete Game::io;\n Game::io = nullptr;\n\n delete Game::whoami;\n Game::whoami = nullptr;\n}\n\n\nGame::Game(ifstream& savefile) {\n\n if (game_ptr != nullptr) {\n error(\"Game is a singleton class\");\n }\n game_ptr = this;\n\n Game::io = new IO();\n\n try {\n Scroll::load_scrolls(savefile);\n Color::init_colors();\n Potion::load_potions(savefile);\n Ring::load_rings(savefile);\n Wand::load_wands(savefile);\n Daemons::load_daemons(savefile);\n Monster::init_monsters();\n Trap::init_traps();\n Player::load_player(savefile);\n\n Disk::load_tag(TAG_GAME, savefile);\n Disk::load(TAG_WHOAMI, Game::whoami, savefile);\n Disk::load(TAG_SAVEPATH, Game::save_game_path, savefile);\n Disk::load(TAG_LEVEL, Game::current_level, savefile);\n Disk::load(TAG_FOODLESS, Game::levels_without_food, savefile);\n } catch (fatal_error &e) {\n Game::io->stop_curses();\n cout << \"Failed to load game, corrupt save file (\" << e.what() << \")\\n\";\n exit();\n }\n\n\n \/\/Game::new_level(Game::current_level);\n Game::new_level(1);\n}\n\nbool Game::save() {\n ofstream savefile(*save_game_path, fstream::out | fstream::trunc);\n if (!savefile) {\n Game::io->message(\"Failed to save file \" + *save_game_path);\n return false;\n }\n\n Scroll::save_scrolls(savefile);\n Potion::save_potions(savefile);\n Ring::save_rings(savefile);\n Wand::save_wands(savefile);\n Daemons::save_daemons(savefile);\n Player::save_player(savefile);\n\n Disk::save_tag(TAG_GAME, savefile);\n Disk::save(TAG_WHOAMI, Game::whoami, savefile);\n Disk::save(TAG_SAVEPATH, Game::save_game_path, savefile);\n Disk::save(TAG_LEVEL, Game::current_level, savefile);\n Disk::save(TAG_FOODLESS, Game::levels_without_food, savefile);\n\n savefile.close();\n return true;\n}\ncleanup#include \n#include \n#include \n\n#include \"disk.h\"\n#include \"command.h\"\n#include \"error_handling.h\"\n#include \"os.h\"\n#include \"potions.h\"\n#include \"scrolls.h\"\n#include \"io.h\"\n#include \"armor.h\"\n#include \"daemons.h\"\n#include \"colors.h\"\n#include \"level.h\"\n#include \"rings.h\"\n#include \"misc.h\"\n#include \"player.h\"\n#include \"weapons.h\"\n#include \"wand.h\"\n#include \"options.h\"\n#include \"rogue.h\"\n#include \"traps.h\"\n\n#include \"game.h\"\n\nusing namespace std;\n\nGame* Game::game_ptr = nullptr;\nIO* Game::io = nullptr;\nLevel* Game::level = nullptr;\nstring* Game::whoami = nullptr;\nstring* Game::save_game_path = nullptr;\nint Game::current_level = 1;\nint Game::levels_without_food = 0;\n\nvoid Game::exit() {\n if (game_ptr != nullptr) {\n delete game_ptr;\n }\n ::exit(0);\n}\n\nvoid Game::new_level(int dungeon_level) {\n\n current_level = dungeon_level;\n\n if (level != nullptr) {\n delete level;\n }\n\n level = new Level();\n\n \/\/ Drop player in the new dungeon level\n if (player == nullptr) {\n player = new Player(true);\n }\n\n Coordinate new_player_pos = player->get_position();\n level->get_random_room_coord(nullptr, &new_player_pos, 0, true);\n player->set_position(new_player_pos);\n\n \/\/ Unhold player just in case\n player->set_not_held();\n}\n\nint Game::run() {\n\n \/\/ Try to crash cleanly, and autosave if possible\n \/\/ Unless we are debugging, since that messes with gdb\/lldb\n#ifdef NDEBUG\n signal(SIGHUP, save_auto);\n signal(SIGQUIT, command_signal_endit);\n signal(SIGILL, save_auto);\n signal(SIGTRAP, save_auto);\n signal(SIGIOT, save_auto);\n signal(SIGFPE, save_auto);\n signal(SIGBUS, save_auto);\n signal(SIGSEGV, save_auto);\n signal(SIGSYS, save_auto);\n signal(SIGTERM, save_auto);\n signal(SIGINT, command_signal_quit);\n#else\n io->message(\"Seed: #\" + to_string(starting_seed));\n#endif\n\n player->set_previous_room(level->get_room(player->get_position()));\n\n#ifdef NDEBUG\n try {\n for (;;) command();\n } catch (const std::runtime_error &ex) {\n endwin();\n cout << ex.what() << endl;\n return 1;\n }\n#else\n for (;;) command();\n#endif\n\n \/\/ CODE NOT REACHED\n}\n\nGame::Game(string const& whoami_, string const& save_path_)\n : starting_seed(os_rand_seed) {\n whoami = new string(whoami_);\n save_game_path = new string(save_path_);\n\n if (game_ptr != nullptr) {\n error(\"Game is a singleton class\");\n }\n game_ptr = this;\n cout << \"Hello \" << *whoami << \", just a moment while I dig the dungeon...\" << flush;\n\n \/\/ Init stuff\n io = new IO(); \/\/ Graphics\n Scroll::init_scrolls(); \/\/ Names of scrolls\n Color::init_colors(); \/\/ Colors for potions and stuff\n Potion::init_potions(); \/\/ Colors of potions\n Ring::init_rings(); \/\/ Stone settings of rings\n Wand::init_wands(); \/\/ Materials of wands\n Daemons::init_daemons(); \/\/ Over-time-effects\n Monster::init_monsters(); \/\/ Monster types\n Trap::init_traps(); \/\/ Trap types\n new_level(current_level); \/\/ Level (and player)\n\n \/\/ Start up daemons and fuses\n Daemons::daemon_start(Daemons::runners_move, AFTER);\n Daemons::daemon_start(Daemons::doctor, AFTER);\n Daemons::daemon_start(Daemons::ring_abilities, AFTER);\n}\n\nGame::~Game() {\n Trap::free_traps();\n Monster::free_monsters();\n Daemons::free_daemons();\n Wand::free_wands();\n Ring::free_rings();\n Potion::free_potions();\n Color::free_colors();\n Scroll::free_scrolls();\n\n delete io;\n io = nullptr;\n\n delete whoami;\n whoami = nullptr;\n}\n\n\nGame::Game(ifstream& savefile) {\n\n if (game_ptr != nullptr) {\n error(\"Game is a singleton class\");\n }\n game_ptr = this;\n\n io = new IO();\n\n try {\n Scroll::load_scrolls(savefile);\n Color::init_colors();\n Potion::load_potions(savefile);\n Ring::load_rings(savefile);\n Wand::load_wands(savefile);\n Daemons::load_daemons(savefile);\n Monster::init_monsters();\n Trap::init_traps();\n Player::load_player(savefile);\n \/\/level = new Level(savefile);\n\n Disk::load_tag(TAG_GAME, savefile);\n\n Disk::load(TAG_WHOAMI, whoami, savefile);\n Disk::load(TAG_SAVEPATH, save_game_path, savefile);\n Disk::load(TAG_LEVEL, current_level, savefile);\n Disk::load(TAG_FOODLESS, levels_without_food, savefile);\n\n Game::new_level(1);\n\n\n Disk::load_tag(TAG_GAME, savefile);\n } catch (fatal_error &e) {\n io->stop_curses();\n cout << \"Failed to load game, corrupt save file (\" << e.what() << \")\\n\";\n exit();\n }\n\n}\n\nbool Game::save() {\n ofstream savefile(*save_game_path, fstream::out | fstream::trunc);\n if (!savefile) {\n io->message(\"Failed to save file \" + *save_game_path);\n return false;\n }\n\n Scroll::save_scrolls(savefile);\n Potion::save_potions(savefile);\n Ring::save_rings(savefile);\n Wand::save_wands(savefile);\n Daemons::save_daemons(savefile);\n Player::save_player(savefile);\n \/\/level->save(savefile);\n\n Disk::save_tag(TAG_GAME, savefile);\n\n Disk::save(TAG_WHOAMI, whoami, savefile);\n Disk::save(TAG_SAVEPATH, save_game_path, savefile);\n Disk::save(TAG_LEVEL, current_level, savefile);\n Disk::save(TAG_FOODLESS, levels_without_food, savefile);\n\n Disk::save_tag(TAG_GAME, savefile);\n\n savefile.close();\n return true;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include \n#include \n\n#include \"vast\/detail\/mmapbuf.hpp\"\n#include \"vast\/detail\/system.hpp\"\n\n#define SUITE streambuf\n#include \"test.hpp\"\n#include \"fixtures\/filesystem.hpp\"\n\nusing namespace std::string_literals;\nusing namespace vast;\n\nFIXTURE_SCOPE(fixture_tests, fixtures::filesystem)\n\nTEST(memory-mapped streambuffer) {\n MESSAGE(\"create a dummy file\");\n auto filename = directory \/ \"dummy.txt\";\n std::ofstream ofs{filename.str()};\n auto data = \"foobarbazqux\"s;\n ofs << data;\n ofs.close();\n MESSAGE(\"performing streambuffer tests\");\n detail::mmapbuf sb{filename.str()};\n CHECK_EQUAL(sb.size(), data.size());\n CHECK_EQUAL(sb.in_avail(), static_cast(sb.size()));\n std::string buf;\n buf.resize(3);\n auto n = sb.sgetn(&buf[0], 3);\n CHECK_EQUAL(n, 3);\n CHECK_EQUAL(buf, \"foo\");\n CHECK_EQUAL(sb.in_avail(), 9);\n buf.resize(data.size());\n n = sb.sgetn(&buf[3], 100);\n CHECK_EQUAL(n, 9);\n CHECK_EQUAL(buf, data);\n CHECK_EQUAL(sb.in_avail(), 0);\n \/\/ Seek back to beginning.\n sb.pubseekpos(0, std::ios::in);\n CHECK_EQUAL(sb.in_avail(), static_cast(sb.size()));\n data = \"corge \";\n n = sb.sputn(data.data(), data.size());\n CHECK_EQUAL(n, static_cast(data.size()));\n CHECK_EQUAL(std::string(sb.data(), sb.size()), \"corge bazqux\");\n CHECK(sb.resize(data.size() - 1));\n \/\/ Figure out current position.\n size_t cur = sb.pubseekoff(0, std::ios::cur, std::ios::out);\n CHECK_EQUAL(cur, sb.size()); \/\/ we're at the end!\n}\n\nnamespace {\n\nvoid aligned_resize_test_impl(const vast::path& filename, size_t size) {\n detail::mmapbuf sb{filename.str(), size};\n REQUIRE(sb.data() != nullptr);\n CHECK_EQUAL(sb.size(), size);\n sb.sputn(\"Here be content\", 15);\n \/\/ Aligned resizing.\n REQUIRE(sb.resize(size * 2));\n CHECK_EQUAL(sb.size(), size * 2);\n CHECK_EQUAL(std::string(sb.data() + 3, 9), \"e be cont\");\n \/\/ Seek in the middle and perform a random write.\n sb.pubseekpos(size, std::ios::out);\n sb.sputc('x');\n \/\/ Unaligned resizing.\n REQUIRE(sb.resize(size \/ 2));\n CHECK_EQUAL(sb.size(), size \/ 2);\n REQUIRE(sb.resize(sb.size() * 8));\n CHECK_EQUAL(sb.size(), size * 4);\n CHECK_EQUAL(std::string(sb.data() + 3, 9), \"e be cont\");\n sb.pubseekpos(size * 3, std::ios::out);\n sb.sputc('x');\n}\n\n}\n\nTEST(memory-mapped streambuffer aligned resize) {\n auto filename = directory \/ \"aligned\";\n aligned_resize_test_impl(filename, detail::page_size());\n}\n\nTEST(memory-mapped streambuffer aligned resize large) {\n auto filename = directory \/ \"aligned_large\";\n auto page_size = detail::page_size();\n auto hundred_mb = size_t{100 * (1 << 20)};\n auto size = hundred_mb - (hundred_mb % page_size);\n aligned_resize_test_impl(filename, size);\n}\n\nFIXTURE_SCOPE_END()\nAdd missing end-of-namespace comment\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include \n#include \n\n#include \"vast\/detail\/mmapbuf.hpp\"\n#include \"vast\/detail\/system.hpp\"\n\n#define SUITE streambuf\n#include \"test.hpp\"\n#include \"fixtures\/filesystem.hpp\"\n\nusing namespace std::string_literals;\nusing namespace vast;\n\nFIXTURE_SCOPE(fixture_tests, fixtures::filesystem)\n\nTEST(memory-mapped streambuffer) {\n MESSAGE(\"create a dummy file\");\n auto filename = directory \/ \"dummy.txt\";\n std::ofstream ofs{filename.str()};\n auto data = \"foobarbazqux\"s;\n ofs << data;\n ofs.close();\n MESSAGE(\"performing streambuffer tests\");\n detail::mmapbuf sb{filename.str()};\n CHECK_EQUAL(sb.size(), data.size());\n CHECK_EQUAL(sb.in_avail(), static_cast(sb.size()));\n std::string buf;\n buf.resize(3);\n auto n = sb.sgetn(&buf[0], 3);\n CHECK_EQUAL(n, 3);\n CHECK_EQUAL(buf, \"foo\");\n CHECK_EQUAL(sb.in_avail(), 9);\n buf.resize(data.size());\n n = sb.sgetn(&buf[3], 100);\n CHECK_EQUAL(n, 9);\n CHECK_EQUAL(buf, data);\n CHECK_EQUAL(sb.in_avail(), 0);\n \/\/ Seek back to beginning.\n sb.pubseekpos(0, std::ios::in);\n CHECK_EQUAL(sb.in_avail(), static_cast(sb.size()));\n data = \"corge \";\n n = sb.sputn(data.data(), data.size());\n CHECK_EQUAL(n, static_cast(data.size()));\n CHECK_EQUAL(std::string(sb.data(), sb.size()), \"corge bazqux\");\n CHECK(sb.resize(data.size() - 1));\n \/\/ Figure out current position.\n size_t cur = sb.pubseekoff(0, std::ios::cur, std::ios::out);\n CHECK_EQUAL(cur, sb.size()); \/\/ we're at the end!\n}\n\nnamespace {\n\nvoid aligned_resize_test_impl(const vast::path& filename, size_t size) {\n detail::mmapbuf sb{filename.str(), size};\n REQUIRE(sb.data() != nullptr);\n CHECK_EQUAL(sb.size(), size);\n sb.sputn(\"Here be content\", 15);\n \/\/ Aligned resizing.\n REQUIRE(sb.resize(size * 2));\n CHECK_EQUAL(sb.size(), size * 2);\n CHECK_EQUAL(std::string(sb.data() + 3, 9), \"e be cont\");\n \/\/ Seek in the middle and perform a random write.\n sb.pubseekpos(size, std::ios::out);\n sb.sputc('x');\n \/\/ Unaligned resizing.\n REQUIRE(sb.resize(size \/ 2));\n CHECK_EQUAL(sb.size(), size \/ 2);\n REQUIRE(sb.resize(sb.size() * 8));\n CHECK_EQUAL(sb.size(), size * 4);\n CHECK_EQUAL(std::string(sb.data() + 3, 9), \"e be cont\");\n sb.pubseekpos(size * 3, std::ios::out);\n sb.sputc('x');\n}\n\n} \/\/ namespace \n\nTEST(memory-mapped streambuffer aligned resize) {\n auto filename = directory \/ \"aligned\";\n aligned_resize_test_impl(filename, detail::page_size());\n}\n\nTEST(memory-mapped streambuffer aligned resize large) {\n auto filename = directory \/ \"aligned_large\";\n auto page_size = detail::page_size();\n auto hundred_mb = size_t{100 * (1 << 20)};\n auto size = hundred_mb - (hundred_mb % page_size);\n aligned_resize_test_impl(filename, size);\n}\n\nFIXTURE_SCOPE_END()\n<|endoftext|>"} {"text":"#include \"neo.h\"\n#include \"protocol.h\"\n#include \"serial.h\"\n\n#include \n#include \n\nint32_t neo_get_version(void) { return NEO_VERSION; }\nbool neo_is_abi_compatible(void) { return neo_get_version() >> 16u == NEO_VERSION_MAJOR; }\n\ntypedef struct neo_error {\n const char* what; \/\/ always literal, do not deallocate\n} neo_error;\n\ntypedef struct neo_device {\n neo::serial::device_s serial; \/\/ serial port communication\n bool is_scanning;\n} neo_device;\n\n#define NEO_MAX_SAMPLES 4096\n\ntypedef struct neo_scan {\n int32_t angle[NEO_MAX_SAMPLES]; \/\/ in millidegrees\n int32_t distance[NEO_MAX_SAMPLES]; \/\/ in cm\n int32_t signal_strength[NEO_MAX_SAMPLES]; \/\/ range 0:255\n int32_t count;\n} neo_scan;\n\n\/\/ Constructor hidden from users\nstatic neo_error_s neo_error_construct(const char* what) {\n NEO_ASSERT(what);\n\n auto out = new neo_error{what};\n return out;\n}\n\nconst char* neo_error_message(neo_error_s error) {\n NEO_ASSERT(error);\n\n return error->what;\n}\n\nvoid neo_error_destruct(neo_error_s error) {\n NEO_ASSERT(error);\n\n delete error;\n}\n\nneo_device_s neo_device_construct_simple(const char* port, neo_error_s* error) {\n NEO_ASSERT(error);\n\n return neo_device_construct(port, 115200, error);\n}\n\nneo_device_s neo_device_construct(const char* port, int32_t bitrate, neo_error_s* error) {\n NEO_ASSERT(port);\n NEO_ASSERT(bitrate > 0);\n NEO_ASSERT(error);\n\n neo::serial::error_s serialerror = nullptr;\n neo::serial::device_s serial = neo::serial::device_construct(port, bitrate, &serialerror);\n\n if (serialerror) {\n *error = neo_error_construct(neo::serial::error_message(serialerror));\n neo::serial::error_destruct(serialerror);\n return nullptr;\n }\n\n auto out = new neo_device{serial, \/*is_scanning=*\/true};\n\n neo_error_s stoperror = nullptr;\n neo_device_stop_scanning(out, &stoperror);\n\n if (stoperror) {\n *error = stoperror;\n neo_device_destruct(out);\n return nullptr;\n }\n\n return out;\n}\n\nvoid neo_device_destruct(neo_device_s device) {\n NEO_ASSERT(device);\n\n neo_error_s ignore = nullptr;\n neo_device_stop_scanning(device, &ignore);\n (void)ignore; \/\/ nothing we can do here\n\n neo::serial::device_destruct(device->serial);\n\n delete device;\n}\n\nvoid neo_device_start_scanning(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n if (device->is_scanning)\n return;\n\n neo::protocol::error_s protocolerror = nullptr;\n neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_START, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send start scanning command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n neo::protocol::response_header_s response;\n neo::protocol::read_response_header(device->serial, neo::protocol::DATA_ACQUISITION_START, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive start scanning command response\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n device->is_scanning = true;\n}\n\nvoid neo_device_stop_scanning(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n\n if (!device->is_scanning)\n return;\n\n neo::protocol::error_s protocolerror = nullptr;\n neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send stop scanning command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n \/\/ Wait until device stopped sending\n std::this_thread::sleep_for(std::chrono::milliseconds(20));\n\n neo::serial::error_s serialerror = nullptr;\n neo::serial::device_flush(device->serial, &serialerror);\n\n if (serialerror) {\n *error = neo_error_construct(\"unable to flush serial device for stopping scanning command\");\n neo::serial::error_destruct(serialerror);\n return;\n }\n\n neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send stop scanning command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n neo::protocol::response_header_s response;\n neo::protocol::read_response_header(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive stop scanning command response\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n device->is_scanning = false;\n}\n\nneo_scan_s neo_device_get_scan(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(device->is_scanning);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::response_scan_packet_s responses[NEO_MAX_SAMPLES];\n\n int32_t received = 0;\n\n while (received < NEO_MAX_SAMPLES) {\n neo::protocol::read_response_scan(device->serial, &responses[received], &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive neo scan response\");\n neo::protocol::error_destruct(protocolerror);\n return nullptr;\n }\n\n const bool is_sync = responses[received].sync_error & neo::protocol::response_scan_packet_sync::sync;\n const bool has_error = (responses[received].sync_error >> 1) != 0; \/\/ shift out sync bit, others are errors\n\n if (!has_error) {\n received++;\n }\n\n if (is_sync) {\n break;\n }\n }\n\n auto out = new neo_scan;\n\n out->count = received;\n\n for (int32_t it = 0; it < received; ++it) {\n \/\/ Convert angle from compact serial format to float (in degrees).\n \/\/ In addition convert from degrees to milli-degrees.\n out->angle[it] = static_cast(neo::protocol::u16_to_f32(responses[it].angle) * 1000.f);\n out->distance[it] = responses[it].distance;\n out->signal_strength[it] = responses[it].signal_strength;\n }\n\n return out;\n}\n\nint32_t neo_scan_get_number_of_samples(neo_scan_s scan) {\n NEO_ASSERT(scan);\n NEO_ASSERT(scan->count >= 0);\n\n return scan->count;\n}\n\nint32_t neo_scan_get_angle(neo_scan_s scan, int32_t sample) {\n NEO_ASSERT(scan);\n NEO_ASSERT(sample >= 0 && sample < scan->count && \"sample index out of bounds\");\n\n return scan->angle[sample];\n}\n\nint32_t neo_scan_get_distance(neo_scan_s scan, int32_t sample) {\n NEO_ASSERT(scan);\n NEO_ASSERT(sample >= 0 && sample < scan->count && \"sample index out of bounds\");\n\n return scan->distance[sample];\n}\n\nint32_t neo_scan_get_signal_strength(neo_scan_s scan, int32_t sample) {\n NEO_ASSERT(scan);\n NEO_ASSERT(sample >= 0 && sample < scan->count && \"sample index out of bounds\");\n\n return scan->signal_strength[sample];\n}\n\nvoid neo_scan_destruct(neo_scan_s scan) {\n NEO_ASSERT(scan);\n\n delete scan;\n}\n\nint32_t neo_device_get_motor_speed(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command(device->serial, neo::protocol::MOTOR_INFORMATION, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send motor speed command\");\n neo::protocol::error_destruct(protocolerror);\n return 0;\n }\n\n neo::protocol::response_info_motor_s response;\n neo::protocol::read_response_info_motor(device->serial, neo::protocol::MOTOR_INFORMATION, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive motor speed command response\");\n neo::protocol::error_destruct(protocolerror);\n return 0;\n }\n\n int32_t speed = neo::protocol::ascii_bytes_to_integral(response.motor_speed);\n NEO_ASSERT(speed >= 0);\n\n return speed;\n}\n\nvoid neo_device_set_motor_speed(neo_device_s device, int32_t hz, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(hz >= 0 && hz <= 10);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n uint8_t args[2] = {0};\n neo::protocol::integral_to_ascii_bytes(hz, args);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command_with_arguments(device->serial, neo::protocol::MOTOR_SPEED_ADJUST, args, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send motor speed command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n neo::protocol::response_param_s response;\n neo::protocol::read_response_param(device->serial, neo::protocol::MOTOR_SPEED_ADJUST, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive motor speed command response\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n}\n\nint32_t neo_device_get_sample_rate(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command(device->serial, neo::protocol::SAMPLE_RATE_INFORMATION, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send sample rate command\");\n neo::protocol::error_destruct(protocolerror);\n return 0;\n }\n\n neo::protocol::response_info_sample_rate_s response;\n neo::protocol::read_response_info_sample_rate(device->serial, neo::protocol::SAMPLE_RATE_INFORMATION, &response,\n &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive sample rate command response\");\n neo::protocol::error_destruct(protocolerror);\n return 0;\n }\n\n \/\/ 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz\n int32_t code = neo::protocol::ascii_bytes_to_integral(response.sample_rate);\n int32_t rate = 0;\n\n switch (code) {\n case 1:\n rate = 500;\n break;\n case 2:\n rate = 750;\n break;\n case 3:\n rate = 1000;\n break;\n default:\n NEO_ASSERT(false && \"sample rate code unknown\");\n }\n\n return rate;\n}\n\nvoid neo_device_set_sample_rate(neo_device_s device, int32_t hz, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(hz == 500 || hz == 750 || hz == 1000);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n \/\/ 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz\n int32_t code = 1;\n\n switch (hz) {\n case 500:\n code = 1;\n break;\n case 750:\n code = 2;\n break;\n case 1000:\n code = 3;\n break;\n default:\n NEO_ASSERT(false && \"sample rate unknown\");\n }\n\n uint8_t args[2] = {0};\n neo::protocol::integral_to_ascii_bytes(code, args);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command_with_arguments(device->serial, neo::protocol::SAMPLE_RATE_ADJUST, args, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send sample rate command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n neo::protocol::response_param_s response;\n neo::protocol::read_response_param(device->serial, neo::protocol::SAMPLE_RATE_ADJUST, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive sample rate command response\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n}\n\nvoid neo_device_reset(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command(device->serial, neo::protocol::RESET_DEVICE, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send device reset command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n}\nfix(the angle of the last one is large than the first one). 1. I' the data is not sort in ascending order, it's confusion; 2. II & III scan data the last data is small than the first(in angle), and this change is to fix it.#include \"neo.h\"\n#include \"protocol.h\"\n#include \"serial.h\"\n\n#include \n#include \n\nint32_t neo_get_version(void) { return NEO_VERSION; }\nbool neo_is_abi_compatible(void) { return neo_get_version() >> 16u == NEO_VERSION_MAJOR; }\n\ntypedef struct neo_error {\n const char* what; \/\/ always literal, do not deallocate\n} neo_error;\n\ntypedef struct neo_device {\n neo::serial::device_s serial; \/\/ serial port communication\n bool is_scanning;\n} neo_device;\n\n#define NEO_MAX_SAMPLES 4096\n\ntypedef struct neo_scan {\n int32_t angle[NEO_MAX_SAMPLES]; \/\/ in millidegrees\n int32_t distance[NEO_MAX_SAMPLES]; \/\/ in cm\n int32_t signal_strength[NEO_MAX_SAMPLES]; \/\/ range 0:255\n int32_t count;\n} neo_scan;\n\n\/\/ Constructor hidden from users\nstatic neo_error_s neo_error_construct(const char* what) {\n NEO_ASSERT(what);\n\n auto out = new neo_error{what};\n return out;\n}\n\nconst char* neo_error_message(neo_error_s error) {\n NEO_ASSERT(error);\n\n return error->what;\n}\n\nvoid neo_error_destruct(neo_error_s error) {\n NEO_ASSERT(error);\n\n delete error;\n}\n\nneo_device_s neo_device_construct_simple(const char* port, neo_error_s* error) {\n NEO_ASSERT(error);\n\n return neo_device_construct(port, 115200, error);\n}\n\nneo_device_s neo_device_construct(const char* port, int32_t bitrate, neo_error_s* error) {\n NEO_ASSERT(port);\n NEO_ASSERT(bitrate > 0);\n NEO_ASSERT(error);\n\n neo::serial::error_s serialerror = nullptr;\n neo::serial::device_s serial = neo::serial::device_construct(port, bitrate, &serialerror);\n\n if (serialerror) {\n *error = neo_error_construct(neo::serial::error_message(serialerror));\n neo::serial::error_destruct(serialerror);\n return nullptr;\n }\n\n auto out = new neo_device{serial, \/*is_scanning=*\/true};\n\n neo_error_s stoperror = nullptr;\n neo_device_stop_scanning(out, &stoperror);\n\n if (stoperror) {\n *error = stoperror;\n neo_device_destruct(out);\n return nullptr;\n }\n\n return out;\n}\n\nvoid neo_device_destruct(neo_device_s device) {\n NEO_ASSERT(device);\n\n neo_error_s ignore = nullptr;\n neo_device_stop_scanning(device, &ignore);\n (void)ignore; \/\/ nothing we can do here\n\n neo::serial::device_destruct(device->serial);\n\n delete device;\n}\n\nvoid neo_device_start_scanning(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n if (device->is_scanning)\n return;\n\n neo::protocol::error_s protocolerror = nullptr;\n neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_START, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send start scanning command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n neo::protocol::response_header_s response;\n neo::protocol::read_response_header(device->serial, neo::protocol::DATA_ACQUISITION_START, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive start scanning command response\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n device->is_scanning = true;\n}\n\nvoid neo_device_stop_scanning(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n\n if (!device->is_scanning)\n return;\n\n neo::protocol::error_s protocolerror = nullptr;\n neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send stop scanning command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n \/\/ Wait until device stopped sending\n std::this_thread::sleep_for(std::chrono::milliseconds(20));\n\n neo::serial::error_s serialerror = nullptr;\n neo::serial::device_flush(device->serial, &serialerror);\n\n if (serialerror) {\n *error = neo_error_construct(\"unable to flush serial device for stopping scanning command\");\n neo::serial::error_destruct(serialerror);\n return;\n }\n\n neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send stop scanning command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n neo::protocol::response_header_s response;\n neo::protocol::read_response_header(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive stop scanning command response\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n device->is_scanning = false;\n}\n\nneo_scan_s neo_device_get_scan(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(device->is_scanning);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::response_scan_packet_s responses[NEO_MAX_SAMPLES];\n\n int32_t received = 1;\n\n while (received < NEO_MAX_SAMPLES) {\n neo::protocol::read_response_scan(device->serial, &responses[received], &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive neo scan response\");\n neo::protocol::error_destruct(protocolerror);\n return nullptr;\n }\n\n const bool is_sync = responses[received].sync_error & neo::protocol::response_scan_packet_sync::sync;\n const bool has_error = (responses[received].sync_error >> 1) != 0; \/\/ shift out sync bit, others are errors\n\n if (!has_error) {\n received++;\n }\n\n if (is_sync) {\n responses[0] = responses[received];\n break;\n }\n }\n\n auto out = new neo_scan;\n\n out->count = received - 1;\n\n for (int32_t it = 0; it < received; ++it) {\n \/\/ Convert angle from compact serial format to float (in degrees).\n \/\/ In addition convert from degrees to milli-degrees.\n out->angle[it] = static_cast(neo::protocol::u16_to_f32(responses[it].angle) * 1000.f);\n out->distance[it] = responses[it].distance;\n out->signal_strength[it] = responses[it].signal_strength;\n }\n\n return out;\n}\n\nint32_t neo_scan_get_number_of_samples(neo_scan_s scan) {\n NEO_ASSERT(scan);\n NEO_ASSERT(scan->count >= 0);\n\n return scan->count;\n}\n\nint32_t neo_scan_get_angle(neo_scan_s scan, int32_t sample) {\n NEO_ASSERT(scan);\n NEO_ASSERT(sample >= 0 && sample < scan->count && \"sample index out of bounds\");\n\n return scan->angle[sample];\n}\n\nint32_t neo_scan_get_distance(neo_scan_s scan, int32_t sample) {\n NEO_ASSERT(scan);\n NEO_ASSERT(sample >= 0 && sample < scan->count && \"sample index out of bounds\");\n\n return scan->distance[sample];\n}\n\nint32_t neo_scan_get_signal_strength(neo_scan_s scan, int32_t sample) {\n NEO_ASSERT(scan);\n NEO_ASSERT(sample >= 0 && sample < scan->count && \"sample index out of bounds\");\n\n return scan->signal_strength[sample];\n}\n\nvoid neo_scan_destruct(neo_scan_s scan) {\n NEO_ASSERT(scan);\n\n delete scan;\n}\n\nint32_t neo_device_get_motor_speed(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command(device->serial, neo::protocol::MOTOR_INFORMATION, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send motor speed command\");\n neo::protocol::error_destruct(protocolerror);\n return 0;\n }\n\n neo::protocol::response_info_motor_s response;\n neo::protocol::read_response_info_motor(device->serial, neo::protocol::MOTOR_INFORMATION, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive motor speed command response\");\n neo::protocol::error_destruct(protocolerror);\n return 0;\n }\n\n int32_t speed = neo::protocol::ascii_bytes_to_integral(response.motor_speed);\n NEO_ASSERT(speed >= 0);\n\n return speed;\n}\n\nvoid neo_device_set_motor_speed(neo_device_s device, int32_t hz, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(hz >= 0 && hz <= 10);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n uint8_t args[2] = {0};\n neo::protocol::integral_to_ascii_bytes(hz, args);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command_with_arguments(device->serial, neo::protocol::MOTOR_SPEED_ADJUST, args, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send motor speed command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n neo::protocol::response_param_s response;\n neo::protocol::read_response_param(device->serial, neo::protocol::MOTOR_SPEED_ADJUST, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive motor speed command response\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n}\n\nint32_t neo_device_get_sample_rate(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command(device->serial, neo::protocol::SAMPLE_RATE_INFORMATION, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send sample rate command\");\n neo::protocol::error_destruct(protocolerror);\n return 0;\n }\n\n neo::protocol::response_info_sample_rate_s response;\n neo::protocol::read_response_info_sample_rate(device->serial, neo::protocol::SAMPLE_RATE_INFORMATION, &response,\n &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive sample rate command response\");\n neo::protocol::error_destruct(protocolerror);\n return 0;\n }\n\n \/\/ 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz\n int32_t code = neo::protocol::ascii_bytes_to_integral(response.sample_rate);\n int32_t rate = 0;\n\n switch (code) {\n case 1:\n rate = 500;\n break;\n case 2:\n rate = 750;\n break;\n case 3:\n rate = 1000;\n break;\n default:\n NEO_ASSERT(false && \"sample rate code unknown\");\n }\n\n return rate;\n}\n\nvoid neo_device_set_sample_rate(neo_device_s device, int32_t hz, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(hz == 500 || hz == 750 || hz == 1000);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n \/\/ 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz\n int32_t code = 1;\n\n switch (hz) {\n case 500:\n code = 1;\n break;\n case 750:\n code = 2;\n break;\n case 1000:\n code = 3;\n break;\n default:\n NEO_ASSERT(false && \"sample rate unknown\");\n }\n\n uint8_t args[2] = {0};\n neo::protocol::integral_to_ascii_bytes(code, args);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command_with_arguments(device->serial, neo::protocol::SAMPLE_RATE_ADJUST, args, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send sample rate command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n\n neo::protocol::response_param_s response;\n neo::protocol::read_response_param(device->serial, neo::protocol::SAMPLE_RATE_ADJUST, &response, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to receive sample rate command response\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n}\n\nvoid neo_device_reset(neo_device_s device, neo_error_s* error) {\n NEO_ASSERT(device);\n NEO_ASSERT(error);\n NEO_ASSERT(!device->is_scanning);\n\n neo::protocol::error_s protocolerror = nullptr;\n\n neo::protocol::write_command(device->serial, neo::protocol::RESET_DEVICE, &protocolerror);\n\n if (protocolerror) {\n *error = neo_error_construct(\"unable to send device reset command\");\n neo::protocol::error_destruct(protocolerror);\n return;\n }\n}\n<|endoftext|>"} {"text":"\/* Copyright (C) 2013, David Eklov\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#include \"gdbserver.hh\"\n\nusing namespace std;\nusing namespace gdb;\n\nclass FakeARMv7Context : public Context {\npublic:\n FakeARMv7Context()\n {\n#define ADDR_START 0x8394\n#define ADDR_TARGET 0x83a0\n#define ADDR_BRANCH 0x83b0\n static char mem_[] = {\n 0x04, 0xb0, 0x2d, 0xe5, \/* 8394: push {fp} *\/\n 0x00, 0xb0, 0x8d, 0xe2, \/* 8398: add fp, sp, #0 *\/\n 0x14, 0xd0, 0x4d, 0xe2, \/* 839c: sub sp, sp, #20 *\/\n 0x08, 0x20, 0x1b, 0xe5, \/* 83a0: ldr r2, [fp, #-8] *\/\n 0x0c, 0x30, 0x1b, 0xe5, \/* 83a4: ldr r3, [fp, #-12] *\/\n 0x03, 0x30, 0x82, 0xe0, \/* 83a8: add r3, r2, r3 *\/\n 0x10, 0x30, 0x0b, 0x50, \/* 83ac: str r3, [fp, #-16] *\/\n 0xfa, 0xff, 0xff, 0xea, \/* 83b0: b 83a0 *\/\n };\n mem = mem_;\n\n regs[ARMv7_REG_PC] = ADDR_START;\n }\n\n void rd_reg(int reg_no)\n {\n put_reg(regs[reg_no]);\n }\n\n void rd_mem(uint64_t addr)\n {\n if (ADDR_START <= addr && addr < ADDR_BRANCH) {\n addr -= ADDR_START;\n put_mem(mem[addr]);\n } else\n put_mem(0);\n }\n\n int num_regs(void)\n {\n return ARMv7_NUM_REGS;\n }\n\npublic:\n uint32_t regs[ARMv7_NUM_REGS];\n char *mem;\n};\n\nint\nmain(int argc, char **argv)\n{\n FakeARMv7Context *ctx = new FakeARMv7Context();\n context_ptr ctx_ptr = context_ptr(ctx);\n\n Server server(ctx_ptr);\n\n try {\n uint64_t pc = ADDR_START;\n\n do {\n ctx->mem[ARMv7_REG_PC] = pc;\n server.update(pc);\n pc += 4;\n if (pc == ADDR_BRANCH)\n pc = ADDR_TARGET;\n } while (1);\n\n } catch (gdb::exception &e) {\n cerr << e.what() << endl;\n exit(EXIT_FAILURE);\n }\n\n return 0;\n}\nFixed errors in the memory emulation of the test program\/* Copyright (C) 2013, David Eklov\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#include \"gdbserver.hh\"\n\nusing namespace std;\nusing namespace gdb;\n\nclass FakeARMv7Context : public Context {\npublic:\n FakeARMv7Context()\n {\n#define ADDR_START (0x8394)\n#define ADDR_TARGET (0x83a0)\n#define ADDR_BRANCH (0x83b0 + 4)\n static char mem_[] = {\n 0x04, 0xb0, 0x2d, 0xe5, \/* 8394: push {fp} *\/\n 0x00, 0xb0, 0x8d, 0xe2, \/* 8398: add fp, sp, #0 *\/\n 0x14, 0xd0, 0x4d, 0xe2, \/* 839c: sub sp, sp, #20 *\/\n 0x08, 0x20, 0x1b, 0xe5, \/* 83a0: ldr r2, [fp, #-8] *\/\n 0x0c, 0x30, 0x1b, 0xe5, \/* 83a4: ldr r3, [fp, #-12] *\/\n 0x03, 0x30, 0x82, 0xe0, \/* 83a8: add r3, r2, r3 *\/\n 0x10, 0x30, 0x0b, 0xe5, \/* 83ac: str r3, [fp, #-16] *\/\n 0xfa, 0xff, 0xff, 0xea, \/* 83b0: b 83a0 *\/\n };\n mem = mem_;\n\n regs[ARMv7_REG_PC] = ADDR_START;\n }\n\n void rd_reg(int reg_no)\n {\n put_reg(regs[reg_no]);\n }\n\n void rd_mem(uint64_t addr)\n {\n if (ADDR_START <= addr && addr <= ADDR_BRANCH) {\n addr -= ADDR_START;\n put_mem(mem[addr]);\n } else\n put_mem(0);\n }\n\n int num_regs(void)\n {\n return ARMv7_NUM_REGS;\n }\n\npublic:\n uint32_t regs[ARMv7_NUM_REGS];\n char *mem;\n};\n\nint\nmain(int argc, char **argv)\n{\n FakeARMv7Context *ctx = new FakeARMv7Context();\n context_ptr ctx_ptr = context_ptr(ctx);\n\n Server server(ctx_ptr);\n\n try {\n uint64_t pc = ADDR_START;\n\n do {\n ctx->regs[ARMv7_REG_PC] = pc;\n server.update(pc);\n pc += 4;\n if (pc == ADDR_BRANCH)\n pc = ADDR_TARGET;\n } while (1);\n\n } catch (gdb::exception &e) {\n cerr << e.what() << endl;\n exit(EXIT_FAILURE);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n*\n* Copyright Marius Staring, Stefan Klein, David Doria. 2011.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n\/** \\file\n \\brief Reshape an image.\n \n \\verbinclude reshape.help\n *\/\n#include \"itkCommandLineArgumentParser.h\"\n#include \"CommandLineArgumentHelper.h\"\n\n#include \"itkImageFileReader.h\"\n#include \"itkReshapeImageToImageFilter.h\"\n#include \"itkImageFileWriter.h\"\n#include \n\/\/-------------------------------------------------------------------------------------\n\n\/** run: A macro to call a function. *\/\n#define run(function,type,dim) \\\nif ( ComponentTypeIn == #type && Dimension == dim ) \\\n{ \\\n typedef itk::Image< type, dim > ImageType; \\\n function< ImageType >( inputFilename, outputFilename, outputSize ); \\\n supported = true; \\\n}\n\n\/\/-------------------------------------------------------------------------------------\n\n\/* Declare PerformPCA. *\/\ntemplate< class ImageType >\nvoid Reshape(\n const std::string & inputFileName,\n const std::string & outputFileName,\n const std::vector & outputSize );\n\n\/** Declare other functions. *\/\nstd::string GetHelpString( void );\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char **argv )\n{\n \/** Create a command line argument parser. *\/\n itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();\n parser->SetCommandLineArguments( argc, argv );\n parser->SetProgramHelpText( GetHelpString() );\n\n parser->MarkArgumentAsRequired( \"-in\", \"The input filename.\" );\n parser->MarkArgumentAsRequired( \"-s\", \"Output size.\" );\n\n itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();\n\n if(validateArguments == itk::CommandLineArgumentParser::FAILED)\n {\n return EXIT_FAILURE;\n }\n else if(validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED)\n {\n return EXIT_SUCCESS;\n }\n\n \/** Get arguments. *\/\n std::string inputFilename = \"\";\n parser->GetCommandLineArgument( \"-in\", inputFilename );\n\n std::string base = itksys::SystemTools::GetFilenameWithoutLastExtension(\n inputFilename );\n std::string ext = itksys::SystemTools::GetFilenameLastExtension(\n inputFilename );\n std::string outputFilename = base + \"_reshaped\" + ext;\n parser->GetCommandLineArgument( \"-out\", outputFilename );\n\n std::vector outputSize;\n parser->GetCommandLineArgument( \"-s\", outputSize );\n\n \/** Determine image properties. *\/\n std::string ComponentTypeIn = \"short\";\n std::string PixelType; \/\/we don't use this\n unsigned int Dimension = 3;\n unsigned int NumberOfComponents = 1;\n std::vector inputSize( Dimension, 0 );\n int retgip = GetImageProperties(\n inputFilename,\n PixelType,\n ComponentTypeIn,\n Dimension,\n NumberOfComponents,\n inputSize );\n if ( retgip != 0 )\n {\n return 1;\n }\n\n \/** Check for vector images. *\/\n if ( NumberOfComponents > 1 )\n {\n std::cerr << \"ERROR: The NumberOfComponents is larger than 1!\" << std::endl;\n std::cerr << \" Vector images are not supported.\" << std::endl;\n return 1;\n }\n\n \/** Get rid of the possible \"_\" in ComponentType. *\/\n ReplaceUnderscoreWithSpace( ComponentTypeIn );\n\n \/** Check dimensions. *\/\n if ( inputSize.size() != outputSize.size() )\n {\n std::cerr << \"ERROR: input and output dimension should be the same.\\n\";\n std::cerr << \" Please, specify only \" << Dimension\n << \"numbers with \\\"-s\\\".\" << std::endl;\n return 1;\n }\n\n \/** Run the program. *\/\n bool supported = false;\n try\n {\n run( Reshape, unsigned char, 2 );\n run( Reshape, char, 2 );\n run( Reshape, unsigned short, 2 );\n run( Reshape, short, 2 );\n run( Reshape, unsigned int, 2 );\n run( Reshape, int, 2 );\n run( Reshape, unsigned long, 2 );\n run( Reshape, long, 2 );\n run( Reshape, float, 2 );\n run( Reshape, double, 2 );\n\n \/*run( Reshape, unsigned char, 3 );\n run( Reshape, char, 3 );\n run( Reshape, unsigned short, 3 );\n run( Reshape, short, 3 );\n run( Reshape, unsigned int, 3 );\n run( Reshape, int, 3 );\n run( Reshape, unsigned long, 3 );\n run( Reshape, long, 3 );\n run( Reshape, float, 3 );\n run( Reshape, double, 3 );*\/\n }\n catch ( itk::ExceptionObject & e )\n {\n std::cerr << \"Caught ITK exception: \" << e << std::endl;\n return 1;\n }\n if ( !supported )\n {\n std::cerr << \"ERROR: this combination of pixeltype and dimension is not supported!\" << std::endl;\n std::cerr\n << \"pixel (component) type = \" << ComponentTypeIn\n << \" ; dimension = \" << Dimension\n << std::endl;\n return 1;\n }\n\n \/** End program. *\/\n return 0;\n\n} \/\/ end main()\n\n\n\/*\n * ******************* Reshape *******************\n *\/\n\ntemplate< class ImageType >\nvoid Reshape(\n const std::string & inputFilename,\n const std::string & outputFilename,\n const std::vector & outputSize )\n{\n \/** Typedefs. *\/\n typedef itk::ImageFileReader< ImageType > ReaderType;\n typedef itk::ReshapeImageToImageFilter< ImageType > ReshapeFilterType;\n typedef itk::ImageFileWriter< ImageType > WriterType;\n typedef typename ReshapeFilterType::SizeType SizeType;\n\n \/** Translate vector to SizeType. *\/\n SizeType size;\n for ( unsigned int i = 0; i < outputSize.size(); ++i )\n {\n size[ i ] = outputSize[ i ];\n }\n\n\n \/** Reader. *\/\n typename ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( inputFilename.c_str() );\n\n \/** Reshaper. *\/\n typename ReshapeFilterType::Pointer reshaper = ReshapeFilterType::New();\n reshaper->SetInput( reader->GetOutput() );\n reshaper->SetOutputSize( size );\n reshaper->Update();\n\n \/** Writer. *\/\n typename WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( outputFilename.c_str() );\n writer->SetInput( reshaper->GetOutput() );\n writer->Update();\n\n} \/\/ end Reshape()\n\n\n\/**\n * ******************* GetHelpString *******************\n *\/\n\nstd::string GetHelpString( void )\n{\n std::stringstream ss;\n ss << \"Usage:\" << std::endl\n << \"pxpca\" << std::endl\n << \" -in inputFilename\" << std::endl\n << \" [-out] outputFileName, default inputFileName_reshaped\" << std::endl\n << \" -s size of the output image\" << std::endl\n << \"Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double.\";\n\n return ss.str();\n\n} \/\/ end GetHelpString()\n\nENH: converted RescaleIntensityImageFilter to template\/*=========================================================================\n*\n* Copyright Marius Staring, Stefan Klein, David Doria. 2011.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n\/** \\file\n \\brief Reshape an image.\n \n \\verbinclude reshape.help\n *\/\n#include \"itkCommandLineArgumentParser.h\"\n#include \"CommandLineArgumentHelper.h\"\n\n#include \"itkImageFileReader.h\"\n#include \"itkReshapeImageToImageFilter.h\"\n#include \"itkImageFileWriter.h\"\n#include \n\/\/-------------------------------------------------------------------------------------\n\n\nclass ReshapeBase : public itktools::ITKToolsBase\n{ \npublic:\n ReshapeBase(){};\n ~ReshapeBase(){};\n\n \/** Input parameters *\/\n std::string m_InputFileName;\n std::string m_OutputFileName;\n std::vector m_OutputSize;\n\n \n}; \/\/ end ReshapeBase\n\n\ntemplate< class TComponentType, unsigned int VDimension >\nclass Reshape : public ReshapeBase\n{\npublic:\n typedef Reshape Self;\n\n Reshape(){};\n ~Reshape(){};\n\n static Self * New( itktools::EnumComponentType componentType, unsigned int dim )\n {\n if ( itktools::IsType( componentType ) && VDimension == dim )\n {\n return new Self;\n }\n return 0;\n }\n\n void Run(void)\n {\n \/** Typedefs. *\/\n typedef itk::Image ImageType;\n typedef itk::ImageFileReader< ImageType > ReaderType;\n typedef itk::ReshapeImageToImageFilter< ImageType > ReshapeFilterType;\n typedef itk::ImageFileWriter< ImageType > WriterType;\n typedef typename ReshapeFilterType::SizeType SizeType;\n\n \/** Translate vector to SizeType. *\/\n SizeType size;\n for ( unsigned int i = 0; i < m_OutputSize.size(); ++i )\n {\n size[ i ] = m_OutputSize[ i ];\n }\n\n\n \/** Reader. *\/\n typename ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( m_InputFileName.c_str() );\n\n \/** Reshaper. *\/\n typename ReshapeFilterType::Pointer reshaper = ReshapeFilterType::New();\n reshaper->SetInput( reader->GetOutput() );\n reshaper->SetOutputSize( size );\n reshaper->Update();\n\n \/** Writer. *\/\n typename WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( m_OutputFileName.c_str() );\n writer->SetInput( reshaper->GetOutput() );\n writer->Update();\n }\n\n}; \/\/ end Reshape\n\n\/\/-------------------------------------------------------------------------------------\n\n\/** Declare other functions. *\/\nstd::string GetHelpString( void );\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char **argv )\n{\n \/** Create a command line argument parser. *\/\n itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();\n parser->SetCommandLineArguments( argc, argv );\n parser->SetProgramHelpText( GetHelpString() );\n\n parser->MarkArgumentAsRequired( \"-in\", \"The input filename.\" );\n parser->MarkArgumentAsRequired( \"-s\", \"Output size.\" );\n\n itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();\n\n if(validateArguments == itk::CommandLineArgumentParser::FAILED)\n {\n return EXIT_FAILURE;\n }\n else if(validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED)\n {\n return EXIT_SUCCESS;\n }\n\n \/** Get arguments. *\/\n std::string inputFilename = \"\";\n parser->GetCommandLineArgument( \"-in\", inputFilename );\n\n std::string base = itksys::SystemTools::GetFilenameWithoutLastExtension(\n inputFilename );\n std::string ext = itksys::SystemTools::GetFilenameLastExtension(\n inputFilename );\n std::string outputFilename = base + \"_reshaped\" + ext;\n parser->GetCommandLineArgument( \"-out\", outputFilename );\n\n std::vector outputSize;\n parser->GetCommandLineArgument( \"-s\", outputSize );\n\n \/** Determine image properties. *\/\n std::string ComponentTypeIn = \"short\";\n std::string PixelType; \/\/we don't use this\n unsigned int Dimension = 3;\n unsigned int NumberOfComponents = 1;\n std::vector inputSize( Dimension, 0 );\n int retgip = GetImageProperties(\n inputFilename,\n PixelType,\n ComponentTypeIn,\n Dimension,\n NumberOfComponents,\n inputSize );\n if ( retgip != 0 )\n {\n return 1;\n }\n\n \/** Check for vector images. *\/\n if ( NumberOfComponents > 1 )\n {\n std::cerr << \"ERROR: The NumberOfComponents is larger than 1!\" << std::endl;\n std::cerr << \" Vector images are not supported.\" << std::endl;\n return 1;\n }\n\n \/** Get rid of the possible \"_\" in ComponentType. *\/\n ReplaceUnderscoreWithSpace( ComponentTypeIn );\n\n \/** Check dimensions. *\/\n if ( inputSize.size() != outputSize.size() )\n {\n std::cerr << \"ERROR: input and output dimension should be the same.\\n\";\n std::cerr << \" Please, specify only \" << Dimension\n << \"numbers with \\\"-s\\\".\" << std::endl;\n return 1;\n }\n\n\n \/** Class that does the work *\/\n ReshapeBase * reshape = 0; \n\n \/** Short alias *\/\n unsigned int imageDimension = Dimension;\n \n \/** \\todo some progs allow user to override the pixel type, \n * so we need a method to convert string to EnumComponentType *\/\n itktools::EnumComponentType componentType = itktools::GetImageComponentType(inputFilename);\n \n std::cout << \"Detected component type: \" << \n componentType << std::endl;\n \n try\n { \n if (!reshape) reshape = Reshape< unsigned char, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< char, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< unsigned short, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< short, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< unsigned int, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< int, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< unsigned long, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< long, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< float, 2 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< double, 2 >::New( componentType, imageDimension );\n#ifdef ITKTOOLS_3D_SUPPORT\n if (!reshape) reshape = Reshape< unsigned char, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< char, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< unsigned short, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< short, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< unsigned int, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< int, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< unsigned long, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< long, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< float, 3 >::New( componentType, imageDimension );\n if (!reshape) reshape = Reshape< double, 3 >::New( componentType, imageDimension );\n#endif\n if (!reshape) \n {\n std::cerr << \"ERROR: this combination of pixeltype and dimension is not supported!\" << std::endl;\n std::cerr\n << \"pixel (component) type = \" << componentType\n << \" ; dimension = \" << Dimension\n << std::endl;\n return 1;\n }\n\n reshape->m_InputFileName = inputFilename;\n reshape->m_OutputFileName = outputFilename;\n reshape->m_OutputSize = outputSize;\n\n reshape->Run();\n \n delete reshape; \n }\n catch( itk::ExceptionObject &e )\n {\n std::cerr << \"Caught ITK exception: \" << e << std::endl;\n delete reshape;\n return 1;\n }\n \n \/** End program. *\/\n return 0;\n\n} \/\/ end main()\n\n\n\n\/**\n * ******************* GetHelpString *******************\n *\/\n\nstd::string GetHelpString( void )\n{\n std::stringstream ss;\n ss << \"Usage:\" << std::endl\n << \"pxpca\" << std::endl\n << \" -in inputFilename\" << std::endl\n << \" [-out] outputFileName, default inputFileName_reshaped\" << std::endl\n << \" -s size of the output image\" << std::endl\n << \"Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double.\";\n\n return ss.str();\n\n} \/\/ end GetHelpString()\n\n<|endoftext|>"} {"text":"\/*\n * Adplug - Replayer for many OPL2\/OPL3 audio file formats.\n * Copyright (C) 1999 - 2004 Simon Peter, , et al.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * hsc.cpp - HSC Player by Simon Peter \n *\/\n\n#include \n\n#include \"hsc.h\"\n#include \"debug.h\"\n\n\/*** public methods **************************************\/\n\nCPlayer *ChscPlayer::factory(Copl *newopl)\n{\n return new ChscPlayer(newopl);\n}\n\nbool ChscPlayer::load(const std::string &filename, const CFileProvider &fp)\n{\n binistream\t*f = fp.open(filename);\n int\t\ti;\n\n \/\/ file validation section\n if(!f || !fp.extension(filename, \".hsc\") || fp.filesize(f) > 59187) {\n AdPlug_LogWrite(\"ChscPlayer::load(\\\"%s\\\"): Not a HSC file!\\n\", filename.c_str());\n fp.close(f);\n return false;\n }\n\n \/\/ load section\n for(i=0;i<128*12;i++)\t\t\/\/ load instruments\n *((unsigned char *)instr + i) = f->readInt(1);\n for (i=0;i<128;i++) {\t\t\t\/\/ correct instruments\n instr[i][2] ^= (instr[i][2] & 0x40) << 1;\n instr[i][3] ^= (instr[i][3] & 0x40) << 1;\n instr[i][11] >>= 4;\t\t\t\/\/ slide\n }\n for(i=0;i<51;i++) song[i] = f->readInt(1);\t\/\/ load tracklist\n for(i=0;i<50*64*9;i++)\t\t\t\/\/ load patterns\n *((char *)patterns + i) = f->readInt(1);\n\n fp.close(f);\n rewind(0);\t\t\t\t\t\/\/ rewind module\n return true;\n}\n\nbool ChscPlayer::update()\n{\n \/\/ general vars\n unsigned char\t\tchan,pattnr,note,effect,eff_op,inst,vol,Okt,db;\n unsigned short\tFnr;\n unsigned long\t\tpattoff;\n\n del--; \/\/ player speed handling\n if(del)\n return !songend;\t\t\/\/ nothing done\n\n if(fadein)\t\t\t\t\t\/\/ fade-in handling\n fadein--;\n\n pattnr = song[songpos];\n \/\/ 0xff indicates song end, but this prevents a crash for some songs that\n \/\/ use other weird values, like 0xbf\n if(pattnr >= 0xb2) {\t\t\t\/\/ arrangement handling\n songend = 1;\t\t\t\t\/\/ set end-flag\n songpos = 0;\n pattnr = song[songpos];\n } else\n if ((pattnr & 128) && (pattnr <= 0xb1)) { \/\/ goto pattern \"nr\"\n songpos = song[songpos] & 127;\n pattpos = 0;\n pattnr = song[songpos];\n songend = 1;\n }\n\n pattoff = pattpos*9;\n for (chan=0;chan<9;chan++) {\t\t\t\/\/ handle all channels\n note = patterns[pattnr][pattoff].note;\n effect = patterns[pattnr][pattoff].effect;\n pattoff++;\n\n if(note & 128) { \/\/ set instrument\n setinstr(chan,effect);\n continue;\n }\n eff_op = effect & 0x0f;\n inst = channel[chan].inst;\n if(note)\n channel[chan].slide = 0;\n\n switch (effect & 0xf0) {\t\t\t\/\/ effect handling\n case 0:\t\t\t\t\t\t\t\t\/\/ global effect\n \/* The following fx are unimplemented on purpose:\n * 02 - Slide Mainvolume up\n * 03 - Slide Mainvolume down (here: fade in)\n * 04 - Set Mainvolume to 0\n *\n * This is because i've never seen any HSC modules using the fx this way.\n * All modules use the fx the way, i've implemented it.\n *\/\n switch(eff_op) {\n case 1: pattbreak++; break;\t\/\/ jump to next pattern\n case 3: fadein = 31; break;\t\/\/ fade in (divided by 2)\n case 5: mode6 = 1; break;\t\/\/ 6 voice mode on\n case 6: mode6 = 0; break;\t\/\/ 6 voice mode off\n }\n break;\n case 0x20:\n case 0x10:\t\t \/\/ manual slides\n if (effect & 0x10) {\n\tchannel[chan].freq += eff_op;\n\tchannel[chan].slide += eff_op;\n } else {\n\tchannel[chan].freq -= eff_op;\n\tchannel[chan].slide -= eff_op;\n }\n if(!note)\n\tsetfreq(chan,channel[chan].freq);\n break;\n case 0x50:\t\t\t\t\t\t\t\/\/ set percussion instrument (unimplemented)\n break;\n case 0x60:\t\t\t\t\t\t\t\/\/ set feedback\n opl->write(0xc0 + chan, (instr[channel[chan].inst][8] & 1) + (eff_op << 1));\n break;\n case 0xa0:\t\t \/\/ set carrier volume\n vol = eff_op << 2;\n opl->write(0x43 + op_table[chan], vol | (instr[channel[chan].inst][2] & ~63));\n break;\n case 0xb0:\t\t \/\/ set modulator volume\n vol = eff_op << 2;\n if (instr[inst][8] & 1)\n\topl->write(0x40 + op_table[chan], vol | (instr[channel[chan].inst][3] & ~63));\n else\n\topl->write(0x40 + op_table[chan],vol | (instr[inst][3] & ~63));\n break;\n case 0xc0:\t\t \/\/ set instrument volume\n db = eff_op << 2;\n opl->write(0x43 + op_table[chan], db | (instr[channel[chan].inst][2] & ~63));\n if (instr[inst][8] & 1)\n\topl->write(0x40 + op_table[chan], db | (instr[channel[chan].inst][3] & ~63));\n break;\n case 0xd0: pattbreak++; songpos = eff_op; songend = 1; break;\t\/\/ position jump\n case 0xf0:\t\t\t\t\t\t\t\/\/ set speed\n speed = eff_op;\n del = ++speed;\n break;\n }\n\n if(fadein)\t\t\t\t\t\t\/\/ fade-in volume setting\n setvolume(chan,fadein*2,fadein*2);\n\n if(!note)\t\t\t\t\t\t\/\/ note handling\n continue;\n note--;\n\n if ((note == 0x7f-1) || ((note\/12) & ~7)) { \/\/ pause (7fh)\n adl_freq[chan] &= ~32;\n opl->write(0xb0 + chan,adl_freq[chan]);\n continue;\n }\n\n \/\/ play the note\n if(mtkmode)\t\t\/\/ imitate MPU-401 Trakker bug\n note--;\n Okt = ((note\/12) & 7) << 2;\n Fnr = note_table[(note % 12)] + instr[inst][11] + channel[chan].slide;\n channel[chan].freq = Fnr;\n if(!mode6 || chan < 6)\n adl_freq[chan] = Okt | 32;\n else\n adl_freq[chan] = Okt;\t\t\/\/ never set key for drums\n opl->write(0xb0 + chan, 0);\n setfreq(chan,Fnr);\n if(mode6) {\n switch(chan) {\t\t\/\/ play drums\n case 6: opl->write(0xbd,bd & ~16); bd |= 48; break;\t\/\/ bass drum\n case 7: opl->write(0xbd,bd & ~1); bd |= 33; break;\t\/\/ hihat\n case 8: opl->write(0xbd,bd & ~2); bd |= 34; break;\t\/\/ cymbal\n }\n opl->write(0xbd,bd);\n }\n }\n\n del = speed;\t\t\/\/ player speed-timing\n if(pattbreak) {\t\t\/\/ do post-effect handling\n pattpos=0;\t\t\t\/\/ pattern break!\n pattbreak=0;\n songpos++;\n songpos %= 50;\n if(!songpos)\n songend = 1;\n } else {\n pattpos++;\n pattpos &= 63;\t\t\/\/ advance in pattern data\n if (!pattpos) {\n songpos++;\n songpos %= 50;\n if(!songpos)\n\tsongend = 1;\n }\n }\n return !songend;\t\t\/\/ still playing\n}\n\nvoid ChscPlayer::rewind(int subsong)\n{\n int i;\t\t\t\t\t\t\t\t\/\/ counter\n\n \/\/ rewind HSC player\n pattpos = 0; songpos = 0; pattbreak = 0; speed = 2;\n del = 1; songend = 0; mode6 = 0; bd = 0; fadein = 0;\n\n opl->init();\t\t\t\t\t\t\/\/ reset OPL chip\n opl->write(1,32); opl->write(8,128); opl->write(0xbd,0);\n\n for(i=0;i<9;i++)\n setinstr((char) i,(char) i);\t\/\/ init channels\n}\n\nunsigned int ChscPlayer::getpatterns()\n{\n unsigned char\tposcnt,pattcnt=0;\n\n \/\/ count patterns\n for(poscnt=0;poscnt<51 && song[poscnt] != 0xff;poscnt++)\n if(song[poscnt] > pattcnt)\n pattcnt = song[poscnt];\n\n return (pattcnt+1);\n}\n\nunsigned int ChscPlayer::getorders()\n{\n unsigned char poscnt;\n\n \/\/ count positions\n for(poscnt=0;poscnt<51;poscnt++)\n if(song[poscnt] == 0xff)\n break;\n\n return poscnt;\n}\n\nunsigned int ChscPlayer::getinstruments()\n{\n unsigned char\tinstcnt,instnum=0,i;\n bool\t\tisinst;\n\n \/\/ count instruments\n for(instcnt=0;instcnt<128;instcnt++) {\n isinst = false;\n for(i=0;i<12;i++)\n if(instr[instcnt][i])\n\tisinst = true;\n if(isinst)\n instnum++;\n }\n\n return instnum;\n}\n\n\/*** private methods *************************************\/\n\nvoid ChscPlayer::setfreq(unsigned char chan, unsigned short freq)\n{\n adl_freq[chan] = (adl_freq[chan] & ~3) | (freq >> 8);\n\n opl->write(0xa0 + chan, freq & 0xff);\n opl->write(0xb0 + chan, adl_freq[chan]);\n}\n\nvoid ChscPlayer::setvolume(unsigned char chan, int volc, int volm)\n{\n unsigned char\t*ins = instr[channel[chan].inst];\n char\t\top = op_table[chan];\n\n opl->write(0x43 + op,volc | (ins[2] & ~63));\n if (ins[8] & 1)\t\t\t\t\t\t\t\/\/ carrier\n opl->write(0x40 + op,volm | (ins[3] & ~63));\n else\n opl->write(0x40 + op, ins[3]);\t\t\/\/ modulator\n}\n\nvoid ChscPlayer::setinstr(unsigned char chan, unsigned char insnr)\n{\n unsigned char\t*ins = instr[insnr];\n char\t\top = op_table[chan];\n\n channel[chan].inst = insnr;\t\t\/\/ set internal instrument\n opl->write(0xb0 + chan,0);\t\t\t\/\/ stop old note\n\n \/\/ set instrument\n opl->write(0xc0 + chan, ins[8]);\n opl->write(0x23 + op, ins[0]); \/\/ carrier\n opl->write(0x20 + op, ins[1]); \/\/ modulator\n opl->write(0x63 + op, ins[4]); \/\/ bits 0..3 = decay; 4..7 = attack\n opl->write(0x60 + op, ins[5]);\n opl->write(0x83 + op, ins[6]); \/\/ 0..3 = release; 4..7 = sustain\n opl->write(0x80 + op, ins[7]);\n opl->write(0xe3 + op, ins[9]); \/\/ bits 0..1 = Wellenform\n opl->write(0xe0 + op, ins[10]);\n setvolume(chan, ins[2] & 63, ins[3] & 63);\n}\nhsc: Handle out of range patterns more gracefully\/*\n * Adplug - Replayer for many OPL2\/OPL3 audio file formats.\n * Copyright (C) 1999 - 2004 Simon Peter, , et al.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * hsc.cpp - HSC Player by Simon Peter \n *\/\n\n#include \n\n#include \"hsc.h\"\n#include \"debug.h\"\n\n\/*** public methods **************************************\/\n\nCPlayer *ChscPlayer::factory(Copl *newopl)\n{\n return new ChscPlayer(newopl);\n}\n\nbool ChscPlayer::load(const std::string &filename, const CFileProvider &fp)\n{\n binistream\t*f = fp.open(filename);\n int\t\ti;\n\n \/\/ file validation section\n if(!f || !fp.extension(filename, \".hsc\") || fp.filesize(f) > 59187) {\n AdPlug_LogWrite(\"ChscPlayer::load(\\\"%s\\\"): Not a HSC file!\\n\", filename.c_str());\n fp.close(f);\n return false;\n }\n\n int total_patterns_in_hsc = (fp.filesize(f) - 1587) \/ 1152;\n\n \/\/ load section\n for(i=0;i<128*12;i++)\t\t\/\/ load instruments\n *((unsigned char *)instr + i) = f->readInt(1);\n for (i=0;i<128;i++) {\t\t\t\/\/ correct instruments\n instr[i][2] ^= (instr[i][2] & 0x40) << 1;\n instr[i][3] ^= (instr[i][3] & 0x40) << 1;\n instr[i][11] >>= 4;\t\t\t\/\/ slide\n }\n for(i=0;i<51;i++) {\t\/\/ load tracklist\n song[i] = f->readInt(1);\n \/\/ if out of range, song ends here\n if (\n ((song[i] & 0x7F) > 0x31)\n || ((song[i] & 0x7F) >= total_patterns_in_hsc)\n ) song[i] = 0xFF;\n }\n for(i=0;i<50*64*9;i++)\t\t\t\/\/ load patterns\n *((char *)patterns + i) = f->readInt(1);\n\n fp.close(f);\n rewind(0);\t\t\t\t\t\/\/ rewind module\n return true;\n}\n\nbool ChscPlayer::update()\n{\n \/\/ general vars\n unsigned char\t\tchan,pattnr,note,effect,eff_op,inst,vol,Okt,db;\n unsigned short\tFnr;\n unsigned long\t\tpattoff;\n\n del--; \/\/ player speed handling\n if(del)\n return !songend;\t\t\/\/ nothing done\n\n if(fadein)\t\t\t\t\t\/\/ fade-in handling\n fadein--;\n\n pattnr = song[songpos];\n \/\/ 0xff indicates song end, but this prevents a crash for some songs that\n \/\/ use other weird values, like 0xbf\n if(pattnr >= 0xb2) {\t\t\t\/\/ arrangement handling\n songend = 1;\t\t\t\t\/\/ set end-flag\n songpos = 0;\n pattnr = song[songpos];\n } else\n if ((pattnr & 128) && (pattnr <= 0xb1)) { \/\/ goto pattern \"nr\"\n songpos = song[songpos] & 127;\n pattpos = 0;\n pattnr = song[songpos];\n songend = 1;\n }\n\n pattoff = pattpos*9;\n for (chan=0;chan<9;chan++) {\t\t\t\/\/ handle all channels\n note = patterns[pattnr][pattoff].note;\n effect = patterns[pattnr][pattoff].effect;\n pattoff++;\n\n if(note & 128) { \/\/ set instrument\n setinstr(chan,effect);\n continue;\n }\n eff_op = effect & 0x0f;\n inst = channel[chan].inst;\n if(note)\n channel[chan].slide = 0;\n\n switch (effect & 0xf0) {\t\t\t\/\/ effect handling\n case 0:\t\t\t\t\t\t\t\t\/\/ global effect\n \/* The following fx are unimplemented on purpose:\n * 02 - Slide Mainvolume up\n * 03 - Slide Mainvolume down (here: fade in)\n * 04 - Set Mainvolume to 0\n *\n * This is because i've never seen any HSC modules using the fx this way.\n * All modules use the fx the way, i've implemented it.\n *\/\n switch(eff_op) {\n case 1: pattbreak++; break;\t\/\/ jump to next pattern\n case 3: fadein = 31; break;\t\/\/ fade in (divided by 2)\n case 5: mode6 = 1; break;\t\/\/ 6 voice mode on\n case 6: mode6 = 0; break;\t\/\/ 6 voice mode off\n }\n break;\n case 0x20:\n case 0x10:\t\t \/\/ manual slides\n if (effect & 0x10) {\n\tchannel[chan].freq += eff_op;\n\tchannel[chan].slide += eff_op;\n } else {\n\tchannel[chan].freq -= eff_op;\n\tchannel[chan].slide -= eff_op;\n }\n if(!note)\n\tsetfreq(chan,channel[chan].freq);\n break;\n case 0x50:\t\t\t\t\t\t\t\/\/ set percussion instrument (unimplemented)\n break;\n case 0x60:\t\t\t\t\t\t\t\/\/ set feedback\n opl->write(0xc0 + chan, (instr[channel[chan].inst][8] & 1) + (eff_op << 1));\n break;\n case 0xa0:\t\t \/\/ set carrier volume\n vol = eff_op << 2;\n opl->write(0x43 + op_table[chan], vol | (instr[channel[chan].inst][2] & ~63));\n break;\n case 0xb0:\t\t \/\/ set modulator volume\n vol = eff_op << 2;\n if (instr[inst][8] & 1)\n\topl->write(0x40 + op_table[chan], vol | (instr[channel[chan].inst][3] & ~63));\n else\n\topl->write(0x40 + op_table[chan],vol | (instr[inst][3] & ~63));\n break;\n case 0xc0:\t\t \/\/ set instrument volume\n db = eff_op << 2;\n opl->write(0x43 + op_table[chan], db | (instr[channel[chan].inst][2] & ~63));\n if (instr[inst][8] & 1)\n\topl->write(0x40 + op_table[chan], db | (instr[channel[chan].inst][3] & ~63));\n break;\n case 0xd0: pattbreak++; songpos = eff_op; songend = 1; break;\t\/\/ position jump\n case 0xf0:\t\t\t\t\t\t\t\/\/ set speed\n speed = eff_op;\n del = ++speed;\n break;\n }\n\n if(fadein)\t\t\t\t\t\t\/\/ fade-in volume setting\n setvolume(chan,fadein*2,fadein*2);\n\n if(!note)\t\t\t\t\t\t\/\/ note handling\n continue;\n note--;\n\n if ((note == 0x7f-1) || ((note\/12) & ~7)) { \/\/ pause (7fh)\n adl_freq[chan] &= ~32;\n opl->write(0xb0 + chan,adl_freq[chan]);\n continue;\n }\n\n \/\/ play the note\n if(mtkmode)\t\t\/\/ imitate MPU-401 Trakker bug\n note--;\n Okt = ((note\/12) & 7) << 2;\n Fnr = note_table[(note % 12)] + instr[inst][11] + channel[chan].slide;\n channel[chan].freq = Fnr;\n if(!mode6 || chan < 6)\n adl_freq[chan] = Okt | 32;\n else\n adl_freq[chan] = Okt;\t\t\/\/ never set key for drums\n opl->write(0xb0 + chan, 0);\n setfreq(chan,Fnr);\n if(mode6) {\n switch(chan) {\t\t\/\/ play drums\n case 6: opl->write(0xbd,bd & ~16); bd |= 48; break;\t\/\/ bass drum\n case 7: opl->write(0xbd,bd & ~1); bd |= 33; break;\t\/\/ hihat\n case 8: opl->write(0xbd,bd & ~2); bd |= 34; break;\t\/\/ cymbal\n }\n opl->write(0xbd,bd);\n }\n }\n\n del = speed;\t\t\/\/ player speed-timing\n if(pattbreak) {\t\t\/\/ do post-effect handling\n pattpos=0;\t\t\t\/\/ pattern break!\n pattbreak=0;\n songpos++;\n songpos %= 50;\n if(!songpos)\n songend = 1;\n } else {\n pattpos++;\n pattpos &= 63;\t\t\/\/ advance in pattern data\n if (!pattpos) {\n songpos++;\n songpos %= 50;\n if(!songpos)\n\tsongend = 1;\n }\n }\n return !songend;\t\t\/\/ still playing\n}\n\nvoid ChscPlayer::rewind(int subsong)\n{\n int i;\t\t\t\t\t\t\t\t\/\/ counter\n\n \/\/ rewind HSC player\n pattpos = 0; songpos = 0; pattbreak = 0; speed = 2;\n del = 1; songend = 0; mode6 = 0; bd = 0; fadein = 0;\n\n opl->init();\t\t\t\t\t\t\/\/ reset OPL chip\n opl->write(1,32); opl->write(8,128); opl->write(0xbd,0);\n\n for(i=0;i<9;i++)\n setinstr((char) i,(char) i);\t\/\/ init channels\n}\n\nunsigned int ChscPlayer::getpatterns()\n{\n unsigned char\tposcnt,pattcnt=0;\n\n \/\/ count patterns\n for(poscnt=0;poscnt<51 && song[poscnt] != 0xff;poscnt++)\n if(song[poscnt] > pattcnt)\n pattcnt = song[poscnt];\n\n return (pattcnt+1);\n}\n\nunsigned int ChscPlayer::getorders()\n{\n unsigned char poscnt;\n\n \/\/ count positions\n for(poscnt=0;poscnt<51;poscnt++)\n if(song[poscnt] == 0xff)\n break;\n\n return poscnt;\n}\n\nunsigned int ChscPlayer::getinstruments()\n{\n unsigned char\tinstcnt,instnum=0,i;\n bool\t\tisinst;\n\n \/\/ count instruments\n for(instcnt=0;instcnt<128;instcnt++) {\n isinst = false;\n for(i=0;i<12;i++)\n if(instr[instcnt][i])\n\tisinst = true;\n if(isinst)\n instnum++;\n }\n\n return instnum;\n}\n\n\/*** private methods *************************************\/\n\nvoid ChscPlayer::setfreq(unsigned char chan, unsigned short freq)\n{\n adl_freq[chan] = (adl_freq[chan] & ~3) | (freq >> 8);\n\n opl->write(0xa0 + chan, freq & 0xff);\n opl->write(0xb0 + chan, adl_freq[chan]);\n}\n\nvoid ChscPlayer::setvolume(unsigned char chan, int volc, int volm)\n{\n unsigned char\t*ins = instr[channel[chan].inst];\n char\t\top = op_table[chan];\n\n opl->write(0x43 + op,volc | (ins[2] & ~63));\n if (ins[8] & 1)\t\t\t\t\t\t\t\/\/ carrier\n opl->write(0x40 + op,volm | (ins[3] & ~63));\n else\n opl->write(0x40 + op, ins[3]);\t\t\/\/ modulator\n}\n\nvoid ChscPlayer::setinstr(unsigned char chan, unsigned char insnr)\n{\n unsigned char\t*ins = instr[insnr];\n char\t\top = op_table[chan];\n\n channel[chan].inst = insnr;\t\t\/\/ set internal instrument\n opl->write(0xb0 + chan,0);\t\t\t\/\/ stop old note\n\n \/\/ set instrument\n opl->write(0xc0 + chan, ins[8]);\n opl->write(0x23 + op, ins[0]); \/\/ carrier\n opl->write(0x20 + op, ins[1]); \/\/ modulator\n opl->write(0x63 + op, ins[4]); \/\/ bits 0..3 = decay; 4..7 = attack\n opl->write(0x60 + op, ins[5]);\n opl->write(0x83 + op, ins[6]); \/\/ 0..3 = release; 4..7 = sustain\n opl->write(0x80 + op, ins[7]);\n opl->write(0xe3 + op, ins[9]); \/\/ bits 0..1 = Wellenform\n opl->write(0xe0 + op, ins[10]);\n setvolume(chan, ins[2] & 63, ins[3] & 63);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkInterpolatedVelocityField.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkInterpolatedVelocityField.h\"\n\n#include \"vtkDataArray.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkGenericCell.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n\n#include \n\nvtkCxxRevisionMacro(vtkInterpolatedVelocityField, \"1.29\");\nvtkStandardNewMacro(vtkInterpolatedVelocityField);\n\ntypedef vtkstd::vector< vtkDataSet* > DataSetsTypeBase;\nclass vtkInterpolatedVelocityFieldDataSetsType: public DataSetsTypeBase {};\n\nvtkInterpolatedVelocityField::vtkInterpolatedVelocityField()\n{\n this->NumFuncs = 3; \/\/ u, v, w\n this->NumIndepVars = 4; \/\/ x, y, z, t\n this->Weights = 0;\n this->WeightsSize = 0;\n this->GenCell = vtkGenericCell::New();\n this->LastCellId = -1;\n this->CacheHit = 0;\n this->CacheMiss = 0;\n this->Caching = 1; \/\/ Caching on by default\n\n this->Cell = vtkGenericCell::New();\n this->VectorsSelection = 0;\n\n this->DataSets = new vtkInterpolatedVelocityFieldDataSetsType;\n this->LastDataSet = 0;\n}\n\nvtkInterpolatedVelocityField::~vtkInterpolatedVelocityField()\n{\n this->NumFuncs = 0;\n this->NumIndepVars = 0;\n this->GenCell->Delete();\n delete[] this->Weights;\n this->Weights = 0;\n\n this->Cell->Delete();\n this->SetVectorsSelection(0);\n\n delete this->DataSets;\n}\n\nstatic int tmp_count=0;\n\/\/ Evaluate u,v,w at x,y,z,t\nint vtkInterpolatedVelocityField::FunctionValues(float* x, float* f)\n{\n vtkDataSet* ds=0;\n if(!this->LastDataSet && !this->DataSets->empty())\n {\n ds = (*this->DataSets)[0];\n this->LastDataSet = ds;\n }\n else\n {\n ds = this->LastDataSet;\n }\n int retVal = this->FunctionValues(ds, x, f);\n if (!retVal)\n {\n tmp_count = 0;\n for(DataSetsTypeBase::iterator i = this->DataSets->begin();\n i != this->DataSets->end(); ++i)\n {\n ds = *i;\n if(ds && ds != this->LastDataSet)\n {\n this->ClearLastCellId();\n retVal = this->FunctionValues(ds, x, f);\n if (retVal) \n {\n this->LastDataSet = ds;\n return retVal;\n }\n }\n }\n this->ClearLastCellId();\n return 0;\n }\n tmp_count++;\n return retVal;\n}\n\nconst float vtkInterpolatedVelocityField::TOLERANCE_SCALE = 1.0E-10;\n\n\/\/ Evaluate u,v,w at x,y,z,t\nint vtkInterpolatedVelocityField::FunctionValues(vtkDataSet* dataset,\n float* x, \n float* f)\n{\n int i, j, subId , numPts, id;\n vtkDataArray* vectors;\n float vec[3];\n float dist2;\n int ret;\n\n for(i=0; i<3; i++)\n {\n f[i] = 0;\n }\n\n \/\/ See if a dataset has been specified and if there are input vectors\n if (!dataset || \n !(vectors = dataset->GetPointData()->GetVectors(this->VectorsSelection)))\n {\n vtkErrorMacro(<<\"Can't evaluate dataset!\");\n return 0;\n }\n\n float tol2 = \n dataset->GetLength() * vtkInterpolatedVelocityField::TOLERANCE_SCALE;\n\n int found = 0;\n\n if (this->Caching)\n {\n \/\/ See if the point is in the cached cell\n if (this->LastCellId == -1 || \n !(ret=this->GenCell->EvaluatePosition(x, 0, subId,\n this->LastPCoords, dist2, \n this->Weights))\n || ret == -1)\n {\n \/\/ if not, find and get it\n if (this->LastCellId != - 1 )\n {\n this->CacheMiss++;\n\n dataset->GetCell(this->LastCellId, this->Cell);\n \n this->LastCellId = \n dataset->FindCell(x, this->Cell, this->GenCell, -1, tol2, \n subId, this->LastPCoords, this->Weights);\n if (this->LastCellId != - 1)\n {\n dataset->GetCell(this->LastCellId, this->GenCell);\n found = 1;\n }\n }\n }\n else\n {\n this->CacheHit++;\n found = 1;\n }\n }\n\n if (!found)\n {\n \/\/ if the cell is not found, do a global search (ignore initial\n \/\/ cell if there is one)\n this->LastCellId = \n dataset->FindCell(x, 0, this->GenCell, -1, tol2, \n subId, this->LastPCoords, this->Weights);\n if (this->LastCellId != - 1)\n {\n dataset->GetCell(this->LastCellId, this->GenCell);\n }\n else\n {\n return 0;\n }\n }\n\n \/\/ if the cell is valid\n if (this->LastCellId >= 0)\n {\n numPts = this->GenCell->GetNumberOfPoints();\n \/\/ interpolate the vectors\n for (j=0; j < numPts; j++)\n {\n id = this->GenCell->PointIds->GetId(j);\n vectors->GetTuple(id, vec);\n for (i=0; i < 3; i++)\n {\n f[i] += vec[i] * this->Weights[j];\n }\n }\n }\n \/\/ if not, return false\n else\n {\n return 0;\n }\n\n return 1;\n}\n\nvoid vtkInterpolatedVelocityField::AddDataSet(vtkDataSet* dataset)\n{\n if (!dataset)\n {\n return;\n }\n\n this->DataSets->push_back(dataset);\n\n int size = dataset->GetMaxCellSize();\n if (size > this->WeightsSize)\n {\n this->WeightsSize = size;\n delete[] this->Weights;\n this->Weights = new float[size]; \n }\n}\n\nint vtkInterpolatedVelocityField::GetLastWeights(float* w)\n{\n int j, numPts;\n\n \/\/ If last cell is valid, fill w with the interpolation weights\n \/\/ and return true\n if (this->LastCellId >= 0)\n {\n numPts = this->GenCell->GetNumberOfPoints();\n for (j=0; j < numPts; j++)\n {\n w[j] = this->Weights[j];\n }\n return 1;\n }\n \/\/ otherwise, return false\n else\n {\n return 0;\n }\n}\n\nint vtkInterpolatedVelocityField::GetLastLocalCoordinates(float pcoords[3])\n{\n int j;\n\n \/\/ If last cell is valid, fill p with the local coordinates\n \/\/ and return true\n if (this->LastCellId >= 0)\n {\n for (j=0; j < 3; j++)\n {\n pcoords[j] = this->LastPCoords[j];\n }\n return 1;\n }\n \/\/ otherwise, return false\n else\n {\n return 0;\n }\n}\n\nvoid vtkInterpolatedVelocityField::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n if ( this->VectorsSelection )\n {\n os << indent << \"VectorsSelection: \" << this->VectorsSelection << endl;\n }\n else\n {\n os << indent << \"VectorsSelection: (none)\" << endl;\n }\n if ( this->GenCell )\n {\n os << indent << \"Last cell: \" << this->GenCell << endl;\n }\n else\n {\n os << indent << \"Last cell: (none)\" << endl;\n }\n os << indent << \"Weights: \" << this->Weights << endl;\n os << indent << \"Last cell Id: \" << this->LastCellId << endl;\n os << indent << \"Cache hit: \" << this->CacheHit << endl;\n os << indent << \"Cache miss: \" << this->CacheMiss << endl;\n os << indent << \"Caching: \";\n if ( this->Caching )\n {\n os << \"on.\" << endl;\n }\n else\n {\n os << \"off.\" << endl;\n }\n\n os << indent << \"VectorsSelection: \" \n << (this->VectorsSelection?this->VectorsSelection:\"(none)\") << endl;\n os << indent << \"LastDataSet : \"\n << this->LastDataSet << endl;\n\n}\n\nThe tolerance was too low. In certain 2D cases, streamline integration was terminating too early\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkInterpolatedVelocityField.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkInterpolatedVelocityField.h\"\n\n#include \"vtkDataArray.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkGenericCell.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n\n#include \n\nvtkCxxRevisionMacro(vtkInterpolatedVelocityField, \"1.30\");\nvtkStandardNewMacro(vtkInterpolatedVelocityField);\n\ntypedef vtkstd::vector< vtkDataSet* > DataSetsTypeBase;\nclass vtkInterpolatedVelocityFieldDataSetsType: public DataSetsTypeBase {};\n\nvtkInterpolatedVelocityField::vtkInterpolatedVelocityField()\n{\n this->NumFuncs = 3; \/\/ u, v, w\n this->NumIndepVars = 4; \/\/ x, y, z, t\n this->Weights = 0;\n this->WeightsSize = 0;\n this->GenCell = vtkGenericCell::New();\n this->LastCellId = -1;\n this->CacheHit = 0;\n this->CacheMiss = 0;\n this->Caching = 1; \/\/ Caching on by default\n\n this->Cell = vtkGenericCell::New();\n this->VectorsSelection = 0;\n\n this->DataSets = new vtkInterpolatedVelocityFieldDataSetsType;\n this->LastDataSet = 0;\n}\n\nvtkInterpolatedVelocityField::~vtkInterpolatedVelocityField()\n{\n this->NumFuncs = 0;\n this->NumIndepVars = 0;\n this->GenCell->Delete();\n delete[] this->Weights;\n this->Weights = 0;\n\n this->Cell->Delete();\n this->SetVectorsSelection(0);\n\n delete this->DataSets;\n}\n\nstatic int tmp_count=0;\n\/\/ Evaluate u,v,w at x,y,z,t\nint vtkInterpolatedVelocityField::FunctionValues(float* x, float* f)\n{\n vtkDataSet* ds=0;\n if(!this->LastDataSet && !this->DataSets->empty())\n {\n ds = (*this->DataSets)[0];\n this->LastDataSet = ds;\n }\n else\n {\n ds = this->LastDataSet;\n }\n int retVal = this->FunctionValues(ds, x, f);\n if (!retVal)\n {\n tmp_count = 0;\n for(DataSetsTypeBase::iterator i = this->DataSets->begin();\n i != this->DataSets->end(); ++i)\n {\n ds = *i;\n if(ds && ds != this->LastDataSet)\n {\n this->ClearLastCellId();\n retVal = this->FunctionValues(ds, x, f);\n if (retVal) \n {\n this->LastDataSet = ds;\n return retVal;\n }\n }\n }\n this->ClearLastCellId();\n return 0;\n }\n tmp_count++;\n return retVal;\n}\n\nconst float vtkInterpolatedVelocityField::TOLERANCE_SCALE = 1.0E-8;\n\n\/\/ Evaluate u,v,w at x,y,z,t\nint vtkInterpolatedVelocityField::FunctionValues(vtkDataSet* dataset,\n float* x, \n float* f)\n{\n int i, j, subId , numPts, id;\n vtkDataArray* vectors;\n float vec[3];\n float dist2;\n int ret;\n\n for(i=0; i<3; i++)\n {\n f[i] = 0;\n }\n\n \/\/ See if a dataset has been specified and if there are input vectors\n if (!dataset || \n !(vectors = dataset->GetPointData()->GetVectors(this->VectorsSelection)))\n {\n vtkErrorMacro(<<\"Can't evaluate dataset!\");\n return 0;\n }\n\n float tol2 = \n dataset->GetLength() * vtkInterpolatedVelocityField::TOLERANCE_SCALE;\n\n int found = 0;\n\n if (this->Caching)\n {\n \/\/ See if the point is in the cached cell\n if (this->LastCellId == -1 || \n !(ret=this->GenCell->EvaluatePosition(x, 0, subId,\n this->LastPCoords, dist2, \n this->Weights))\n || ret == -1)\n {\n \/\/ if not, find and get it\n if (this->LastCellId != - 1 )\n {\n this->CacheMiss++;\n\n dataset->GetCell(this->LastCellId, this->Cell);\n \n this->LastCellId = \n dataset->FindCell(x, this->Cell, this->GenCell, -1, tol2, \n subId, this->LastPCoords, this->Weights);\n if (this->LastCellId != - 1)\n {\n dataset->GetCell(this->LastCellId, this->GenCell);\n found = 1;\n }\n }\n }\n else\n {\n this->CacheHit++;\n found = 1;\n }\n }\n\n if (!found)\n {\n \/\/ if the cell is not found, do a global search (ignore initial\n \/\/ cell if there is one)\n this->LastCellId = \n dataset->FindCell(x, 0, this->GenCell, -1, tol2, \n subId, this->LastPCoords, this->Weights);\n if (this->LastCellId != - 1)\n {\n dataset->GetCell(this->LastCellId, this->GenCell);\n }\n else\n {\n return 0;\n }\n }\n\n \/\/ if the cell is valid\n if (this->LastCellId >= 0)\n {\n numPts = this->GenCell->GetNumberOfPoints();\n \/\/ interpolate the vectors\n for (j=0; j < numPts; j++)\n {\n id = this->GenCell->PointIds->GetId(j);\n vectors->GetTuple(id, vec);\n for (i=0; i < 3; i++)\n {\n f[i] += vec[i] * this->Weights[j];\n }\n }\n }\n \/\/ if not, return false\n else\n {\n return 0;\n }\n\n return 1;\n}\n\nvoid vtkInterpolatedVelocityField::AddDataSet(vtkDataSet* dataset)\n{\n if (!dataset)\n {\n return;\n }\n\n this->DataSets->push_back(dataset);\n\n int size = dataset->GetMaxCellSize();\n if (size > this->WeightsSize)\n {\n this->WeightsSize = size;\n delete[] this->Weights;\n this->Weights = new float[size]; \n }\n}\n\nint vtkInterpolatedVelocityField::GetLastWeights(float* w)\n{\n int j, numPts;\n\n \/\/ If last cell is valid, fill w with the interpolation weights\n \/\/ and return true\n if (this->LastCellId >= 0)\n {\n numPts = this->GenCell->GetNumberOfPoints();\n for (j=0; j < numPts; j++)\n {\n w[j] = this->Weights[j];\n }\n return 1;\n }\n \/\/ otherwise, return false\n else\n {\n return 0;\n }\n}\n\nint vtkInterpolatedVelocityField::GetLastLocalCoordinates(float pcoords[3])\n{\n int j;\n\n \/\/ If last cell is valid, fill p with the local coordinates\n \/\/ and return true\n if (this->LastCellId >= 0)\n {\n for (j=0; j < 3; j++)\n {\n pcoords[j] = this->LastPCoords[j];\n }\n return 1;\n }\n \/\/ otherwise, return false\n else\n {\n return 0;\n }\n}\n\nvoid vtkInterpolatedVelocityField::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n if ( this->VectorsSelection )\n {\n os << indent << \"VectorsSelection: \" << this->VectorsSelection << endl;\n }\n else\n {\n os << indent << \"VectorsSelection: (none)\" << endl;\n }\n if ( this->GenCell )\n {\n os << indent << \"Last cell: \" << this->GenCell << endl;\n }\n else\n {\n os << indent << \"Last cell: (none)\" << endl;\n }\n os << indent << \"Weights: \" << this->Weights << endl;\n os << indent << \"Last cell Id: \" << this->LastCellId << endl;\n os << indent << \"Cache hit: \" << this->CacheHit << endl;\n os << indent << \"Cache miss: \" << this->CacheMiss << endl;\n os << indent << \"Caching: \";\n if ( this->Caching )\n {\n os << \"on.\" << endl;\n }\n else\n {\n os << \"off.\" << endl;\n }\n\n os << indent << \"VectorsSelection: \" \n << (this->VectorsSelection?this->VectorsSelection:\"(none)\") << endl;\n os << indent << \"LastDataSet : \"\n << this->LastDataSet << endl;\n\n}\n\n<|endoftext|>"} {"text":"\/\/ Gao Wang and Kushal K. Dey (c) 2016\n\/\/ code format configuration: clang-format -style=Google -dump-config >\n\/\/ ~\/.clang-format\n#include \"pfa.hpp\"\n#include \n#include \n#include \n#include \n\n\/\/! EM algorithm for paired factor analysis\n\/\/ @param X [N, J] observed data matrix\n\/\/ @param F [K, J] initial factor matrix\n\/\/ @param P [K, K] initial frequency matrix of factor pairs, an upper diagonal\n\/\/ matrix\n\/\/ @param q [C, 1] initial vector of possible membership loadings, a discrete\n\/\/ set\n\/\/ @param N [int_pt] number of rows of matrix X\n\/\/ @param J [int_pt] number of columns of matrix X and F\n\/\/ @param K [int_pt] number of rows of matrix F and P\n\/\/ @param C [int_pt] number of elements in q\n\/\/ @param alpha0 [double_pt] Dirichlet prior for factor weights\n\/\/ @param beta0 [double_pt] Dirichlet prior for grid weights\n\/\/ @param tol [double_pt] tolerance for convergence\n\/\/ @param maxiter [int_pt] maximum number of iterations\n\/\/ @param niter [int_pt] number of iterations\n\/\/ @param loglik [maxiter, 1] log likelihood, track of convergence (return)\n\/\/ @param L [N, K] Loading matrix (return)\n\/\/ @param alpha [K, K] Dirichlet posterior parameter matrix for factor pair\n\/\/ weights (return)\n\/\/ @param beta [C, 1] Dirichlet posterior parameter vector for grid weights\n\/\/ (return)\n\/\/ @param status [int_pt] return status, 0 for good, 1 for error (return)\n\/\/ @param logfn_1 [int_pt] log file 1 name as integer converted from character\n\/\/ array\n\/\/ @param nlf_1 [int_pt] length of above\n\/\/ @param logfn_2 [int_pt] log file 2 name as integer converted from character\n\/\/ array\n\/\/ @param nlf_2 [int_pt] length of above\n\/\/ @param n_threads [int_pt] number of threads for parallel processing\n\nint pfa_em(double* X, double* F, double* P, double* q, int* N, int* J, int* K,\n int* C, double* alpha0, double* beta0, double* tol, int* maxiter,\n int* niter, double* loglik, double* L, double* alpha, double* beta,\n int* status, int* logfn_1, int* nlf_1, int* logfn_2, int* nlf_2,\n int* n_threads) {\n \/\/\n \/\/ Set up logfiles\n \/\/\n std::fstream f1;\n std::fstream f2;\n if (*nlf_1 > 0) {\n char f1_log[(*nlf_1) + 1];\n char f2_log[(*nlf_2) + 1];\n for (int i = 0; i < *nlf_1; i++) f1_log[i] = (char)*(logfn_1 + i);\n for (int i = 0; i < *nlf_2; i++) f2_log[i] = (char)*(logfn_2 + i);\n f1_log[*nlf_1] = '\\0';\n f2_log[*nlf_2] = '\\0';\n \/\/ log file\n f1.open(f1_log, std::fstream::out);\n time_t now;\n time(&now);\n f1 << \"#\\n# \" << asctime(localtime(&now)) << \"#\\n\\n\";\n f1.close();\n f1.open(f1_log, std::fstream::app);\n \/\/ debug file\n if (*nlf_2 > 0) {\n f2.open(f2_log, std::fstream::out);\n f2 << \"#\\n# \" << asctime(localtime(&now)) << \"#\\n\\n\";\n f2.close();\n f2.open(f2_log, std::fstream::app);\n }\n }\n \/\/\n \/\/ Fit model\n \/\/\n *niter = 0;\n PFA_EM model(X, F, P, q, L, *N, *J, *K, *C);\n model.set_threads(*n_threads);\n model.write(f1, 0);\n while (*niter <= *maxiter) {\n if (f1.is_open()) {\n f1 << \"#----------------------------------\\n\";\n f1 << \"# Iteration \" << *niter << \"\\n\";\n f1 << \"#----------------------------------\\n\";\n model.write(f1, 1);\n if (f2.is_open()) {\n f2 << \"#----------------------------------\\n\";\n f2 << \"# Iteration \" << *niter << \"\\n\";\n f2 << \"#----------------------------------\\n\";\n model.write(f2, 2);\n }\n }\n int e_status = model.E_step();\n if (e_status != 0) {\n std::cerr << \"[ERROR] E step failed!\" << std::endl;\n *status = 1;\n break;\n }\n loglik[*niter] = model.get_loglik();\n if (loglik[*niter] != loglik[*niter]) {\n std::cerr << \"[ERROR] likelihood nan produced!\" << std::endl;\n *status = 1;\n break;\n }\n if (f1.is_open()) {\n f1 << \"Loglik:\\n\" << loglik[*niter] << \"\\n\";\n }\n (*niter)++;\n \/\/ check convergence\n if (*niter > 1) {\n double diff = loglik[(*niter) - 1] - loglik[(*niter) - 2];\n \/\/ check monotonicity\n if (diff < 0.0) {\n std::cerr << \"[ERROR] likelihood decreased in EM algorithm!\"\n << std::endl;\n *status = 1;\n break;\n }\n \/\/ converged\n if (diff < *tol) break;\n }\n if (*niter == *maxiter) {\n \/\/ did not converge\n *status = 1;\n break;\n }\n \/\/ continue with more iterations\n model.M_step();\n }\n if (*status)\n std::cerr << \"[WARNING] PFA failed to converge after \" << *niter\n << \" iterations!\" << std::endl;\n if (f1.is_open()) f1.close();\n if (f2.is_open()) f2.close();\n return 0;\n}\n\n\/\/ this computes log delta\n\/\/ return: k1k2 by q by N tensor of log delta\nvoid PFA_EM::update_ldelta() {\n#pragma omp parallel for num_threads(n_threads)\n for (size_t k1 = 0; k1 < F.n_rows; k1++) {\n for (size_t k2 = 0; k2 <= k1; k2++) {\n \/\/ given k1, k2 and q, density is a N-vector\n for (size_t qq = 0; qq < q.n_elem; qq++) {\n if ((k1 != k2) | (k1 == k2 & qq == 0)) {\n arma::vec Dn_delta = arma::zeros(D.n_rows);\n for (size_t j = 0; j < D.n_cols; j++) {\n arma::vec density = D.col(j);\n double m =\n (k2 < k1)\n ? q.at(qq) * F.at(k2, j) + (1 - q.at(qq)) * F.at(k1, j)\n : F.at(k1, j);\n Dn_delta += density.transform(\n [=](double x) { return (normal_pdf_log(x, m, s.at(j))); });\n }\n Dn_delta += std::log(P.at(k1, k2));\n \/\/ FIXME: this is slow, due to the cube\/slice structure\n for (size_t n = 0; n < D.n_rows; n++)\n delta.slice(n).at(F_pair_coord[std::make_pair(k1, k2)], qq) = Dn_delta.at(n);\n }\n }\n }\n }\n}\n\n\/\/ this computes loglik and delta\n\/\/ this results in a N by k1k2 matrix of loglik\n\/\/ and the delta tensor on its original (exp) scale, with each slice summing to one\nvoid PFA_EM::update_loglik_and_delta() {\n arma::vec loglik_vec;\n loglik_vec.set_size(D.n_rows);\n#pragma omp parallel for num_threads(n_threads)\n for (size_t qq = 0; qq < q.n_elem; qq++) {\n \/\/ 1. for each N by k1k2 matrix slice from the log of sum of \n }\n for (size_t n = 0; n < D.n_rows; n++) {\n \/\/ 1. find the log of sum of exp(delta.slice(n))\n \/\/ 2. exp transform delta to its proper scale: set delta prop to exp(delta)\n \/\/ 3. scale delta.slice(n) to sum to 1\n \/\/ a numeric trick is used to calculate log(sum(exp(x)))\n \/\/ lsum=function(lx){\n \/\/ m = max(lx)\n \/\/ m + log(sum(exp(lx-m)))\n \/\/ }\n \/\/ see gaow\/pfar\/issue\/2 for a discussion\n double delta_n_max = delta.slice(n).max();\n delta.slice(n) = arma::exp(delta.slice(n) - delta_n_max);\n for (size_t k = 0; k < F.n_rows; k++) {\n \/\/ reset single factor case: has to be zero for all but the first grid\n double tmp = delta.slice(n).at(F_pair_coord[std::make_pair(k, k)], 0);\n delta.slice(n).row(F_pair_coord[std::make_pair(k, k)]).fill(0);\n delta.slice(n).at(F_pair_coord[std::make_pair(k, k)], 0) = tmp;\n }\n double sum_delta_n = arma::accu(delta.slice(n));\n loglik_vec.at(n) = std::log(sum_delta_n) + delta_n_max;\n delta.slice(n) = delta.slice(n) \/ sum_delta_n;\n }\n loglik = arma::accu(loglik_vec);\n}\n\n\/\/ update factor pair weights\nvoid PFA_EM::update_paired_factor_weights() {\n arma::vec pik1k2 = arma::vectorise(arma::mean(arma::sum(delta, 1), 2));\n#pragma omp parallel for num_threads(n_threads)\n for (size_t k1 = 0; k1 < P.n_rows; k1++) {\n for (size_t k2 = 0; k2 <= k1; k2++) {\n P.at(k1, k2) = pik1k2.at(F_pair_coord[std::make_pair(k1, k2)]);\n }\n }\n}\n\nvoid PFA_EM::update_factor_model() {\n \/\/ Factors F and loadings L are to be updated here\n \/\/ Need to compute 2 matrices in order to solve F\n L.fill(0);\n arma::mat L2 = L;\n#pragma omp parallel for num_threads(n_threads) collapse(2)\n for (size_t k = 0; k < F.n_rows; k++) {\n \/\/ I. Compute the k-th column for E(L), the N X K matrix:\n \/\/ and II. the diagonal elements for E(W), the K X K matrix\n for (size_t i = 0; i < F.n_rows; i++) {\n#pragma omp critical\n {\n if (k < i) {\n \/\/ I.\n L.col(k) += delta.col(F_pair_coord[std::make_pair(k, i)]) * avg_q;\n \/\/ II.\n L2.col(k) += delta.col(F_pair_coord[std::make_pair(k, i)]) * avg_q2;\n }\n if (k > i) {\n L.col(k) += delta.col(F_pair_coord[std::make_pair(k, i)]) * avg_1q;\n L2.col(k) += delta.col(F_pair_coord[std::make_pair(k, i)]) * avg_1q2;\n }\n if (k == i) {\n L.col(k) += delta.col(F_pair_coord[std::make_pair(k, i)]);\n L2.col(k) += delta.col(F_pair_coord[std::make_pair(k, i)]);\n }\n }\n }\n }\n \/\/ II. diagonal elements for E(W)\n W.diag() = arma::sum(L2);\n\/\/ III. Compute off-diagonal elements for E(W), the K X K matrix\n#pragma omp parallel for num_threads(n_threads)\n for (size_t k1 = 0; k1 < F.n_rows; k1++) {\n for (size_t k2 = 0; k2 < k1; k2++) {\n W.at(k1, k2) =\n arma::sum(delta.col(F_pair_coord[std::make_pair(k1, k2)]) * avg_q1q);\n W.at(k2, k1) = W.at(k1, k2);\n }\n }\n \/\/ IV. Solve F\n F = arma::solve(W, L.t() * D);\n}\n\n\/\/ S is the residual standard error vector to be updated for each feature\nvoid PFA_EM::update_residual_error() {\n#pragma omp parallel for num_threads(n_threads)\n for (size_t j = 0; j < D.n_cols; j++) {\n s.at(j) = 0;\n for (size_t k1 = 0; k1 < F.n_rows; k1++) {\n for (size_t k2 = 0; k2 <= k1; k2++) {\n if (k2 < k1) {\n arma::vec tmp = arma::zeros(D.n_rows);\n for (size_t qq = 0; qq < q.n_elem; qq++) {\n tmp += arma::pow(D.col(j) - q.at(qq) * F.at(k2, j) -\n (1 - q.at(qq)) * F.at(k1, j),\n 2);\n }\n s.at(j) +=\n arma::accu(delta.col(F_pair_coord[std::make_pair(k1, k2)]) \/\n double(q.n_elem) % tmp);\n } else {\n s.at(j) +=\n arma::accu(delta.col(F_pair_coord[std::make_pair(k1, k2)]) %\n arma::pow(D.col(j) - F.at(k1, j), 2));\n }\n }\n }\n s.at(j) = std::sqrt(s.at(j) \/ double(D.n_rows));\n }\n}\nFinishing up the previous patch\/\/ Gao Wang and Kushal K. Dey (c) 2016\n\/\/ code format configuration: clang-format -style=Google -dump-config >\n\/\/ ~\/.clang-format\n#include \"pfa.hpp\"\n#include \n#include \n#include \n#include \n\n\/\/! EM algorithm for paired factor analysis\n\/\/ @param X [N, J] observed data matrix\n\/\/ @param F [K, J] initial factor matrix\n\/\/ @param P [K, K] initial frequency matrix of factor pairs, an upper diagonal\n\/\/ matrix\n\/\/ @param q [C, 1] initial vector of possible membership loadings, a discrete\n\/\/ set\n\/\/ @param N [int_pt] number of rows of matrix X\n\/\/ @param J [int_pt] number of columns of matrix X and F\n\/\/ @param K [int_pt] number of rows of matrix F and P\n\/\/ @param C [int_pt] number of elements in q\n\/\/ @param alpha0 [double_pt] Dirichlet prior for factor weights\n\/\/ @param beta0 [double_pt] Dirichlet prior for grid weights\n\/\/ @param tol [double_pt] tolerance for convergence\n\/\/ @param maxiter [int_pt] maximum number of iterations\n\/\/ @param niter [int_pt] number of iterations\n\/\/ @param loglik [maxiter, 1] log likelihood, track of convergence (return)\n\/\/ @param L [N, K] Loading matrix (return)\n\/\/ @param alpha [K, K] Dirichlet posterior parameter matrix for factor pair\n\/\/ weights (return)\n\/\/ @param beta [C, 1] Dirichlet posterior parameter vector for grid weights\n\/\/ (return)\n\/\/ @param status [int_pt] return status, 0 for good, 1 for error (return)\n\/\/ @param logfn_1 [int_pt] log file 1 name as integer converted from character\n\/\/ array\n\/\/ @param nlf_1 [int_pt] length of above\n\/\/ @param logfn_2 [int_pt] log file 2 name as integer converted from character\n\/\/ array\n\/\/ @param nlf_2 [int_pt] length of above\n\/\/ @param n_threads [int_pt] number of threads for parallel processing\n\nint pfa_em(double* X, double* F, double* P, double* q, int* N, int* J, int* K,\n int* C, double* alpha0, double* beta0, double* tol, int* maxiter,\n int* niter, double* loglik, double* L, double* alpha, double* beta,\n int* status, int* logfn_1, int* nlf_1, int* logfn_2, int* nlf_2,\n int* n_threads) {\n \/\/\n \/\/ Set up logfiles\n \/\/\n std::fstream f1;\n std::fstream f2;\n if (*nlf_1 > 0) {\n char f1_log[(*nlf_1) + 1];\n char f2_log[(*nlf_2) + 1];\n for (int i = 0; i < *nlf_1; i++) f1_log[i] = (char)*(logfn_1 + i);\n for (int i = 0; i < *nlf_2; i++) f2_log[i] = (char)*(logfn_2 + i);\n f1_log[*nlf_1] = '\\0';\n f2_log[*nlf_2] = '\\0';\n \/\/ log file\n f1.open(f1_log, std::fstream::out);\n time_t now;\n time(&now);\n f1 << \"#\\n# \" << asctime(localtime(&now)) << \"#\\n\\n\";\n f1.close();\n f1.open(f1_log, std::fstream::app);\n \/\/ debug file\n if (*nlf_2 > 0) {\n f2.open(f2_log, std::fstream::out);\n f2 << \"#\\n# \" << asctime(localtime(&now)) << \"#\\n\\n\";\n f2.close();\n f2.open(f2_log, std::fstream::app);\n }\n }\n \/\/\n \/\/ Fit model\n \/\/\n *niter = 0;\n PFA_EM model(X, F, P, q, L, *N, *J, *K, *C);\n model.set_threads(*n_threads);\n model.write(f1, 0);\n while (*niter <= *maxiter) {\n if (f1.is_open()) {\n f1 << \"#----------------------------------\\n\";\n f1 << \"# Iteration \" << *niter << \"\\n\";\n f1 << \"#----------------------------------\\n\";\n model.write(f1, 1);\n if (f2.is_open()) {\n f2 << \"#----------------------------------\\n\";\n f2 << \"# Iteration \" << *niter << \"\\n\";\n f2 << \"#----------------------------------\\n\";\n model.write(f2, 2);\n }\n }\n int e_status = model.E_step();\n if (e_status != 0) {\n std::cerr << \"[ERROR] E step failed!\" << std::endl;\n *status = 1;\n break;\n }\n loglik[*niter] = model.get_loglik();\n if (loglik[*niter] != loglik[*niter]) {\n std::cerr << \"[ERROR] likelihood nan produced!\" << std::endl;\n *status = 1;\n break;\n }\n if (f1.is_open()) {\n f1 << \"Loglik:\\n\" << loglik[*niter] << \"\\n\";\n }\n (*niter)++;\n \/\/ check convergence\n if (*niter > 1) {\n double diff = loglik[(*niter) - 1] - loglik[(*niter) - 2];\n \/\/ check monotonicity\n if (diff < 0.0) {\n std::cerr << \"[ERROR] likelihood decreased in EM algorithm!\"\n << std::endl;\n *status = 1;\n break;\n }\n \/\/ converged\n if (diff < *tol) break;\n }\n if (*niter == *maxiter) {\n \/\/ did not converge\n *status = 1;\n break;\n }\n \/\/ continue with more iterations\n model.M_step();\n }\n if (*status)\n std::cerr << \"[WARNING] PFA failed to converge after \" << *niter\n << \" iterations!\" << std::endl;\n if (f1.is_open()) f1.close();\n if (f2.is_open()) f2.close();\n return 0;\n}\n\n\/\/ this computes log delta\n\/\/ return: k1k2 by q by N tensor of log delta\nvoid PFA_EM::update_ldelta() {\n#pragma omp parallel for num_threads(n_threads)\n for (size_t k1 = 0; k1 < F.n_rows; k1++) {\n for (size_t k2 = 0; k2 <= k1; k2++) {\n \/\/ given k1, k2 and q, density is a N-vector\n for (size_t qq = 0; qq < q.n_elem; qq++) {\n if ((k1 != k2) | (k1 == k2 & qq == 0)) {\n arma::vec Dn_delta = arma::zeros(D.n_rows);\n for (size_t j = 0; j < D.n_cols; j++) {\n arma::vec density = D.col(j);\n double m =\n (k2 < k1)\n ? q.at(qq) * F.at(k2, j) + (1 - q.at(qq)) * F.at(k1, j)\n : F.at(k1, j);\n Dn_delta += density.transform(\n [=](double x) { return (normal_pdf_log(x, m, s.at(j))); });\n }\n Dn_delta += std::log(P.at(k1, k2));\n \/\/ FIXME: this is slow, due to the cube\/slice structure\n for (size_t n = 0; n < D.n_rows; n++)\n delta.slice(n).at(F_pair_coord[std::make_pair(k1, k2)], qq) =\n Dn_delta.at(n);\n }\n }\n }\n }\n}\n\n\/\/ this computes loglik and delta\n\/\/ this results in a N by k1k2 matrix of loglik\n\/\/ and the delta tensor on its original (exp) scale, with each slice summing to\n\/\/ one\nvoid PFA_EM::update_loglik_and_delta() {\n arma::vec loglik_vec;\n loglik_vec.set_size(D.n_rows);\n#pragma omp parallel for num_threads(n_threads)\n for (size_t n = 0; n < D.n_rows; n++) {\n \/\/ 1. find the log of sum of exp(delta.slice(n))\n \/\/ 2. exp transform delta to its proper scale: set delta prop to exp(delta)\n \/\/ 3. scale delta.slice(n) to sum to 1\n \/\/ a numeric trick is used to calculate log(sum(exp(x)))\n \/\/ lsum=function(lx){\n \/\/ m = max(lx)\n \/\/ m + log(sum(exp(lx-m)))\n \/\/ }\n \/\/ see gaow\/pfar\/issue\/2 for a discussion\n double delta_n_max = delta.slice(n).max();\n delta.slice(n) = arma::exp(delta.slice(n) - delta_n_max);\n for (size_t k = 0; k < F.n_rows; k++) {\n \/\/ reset single factor case: has to be zero for all but the first grid\n double tmp = delta.slice(n).at(F_pair_coord[std::make_pair(k, k)], 0);\n delta.slice(n).row(F_pair_coord[std::make_pair(k, k)]).fill(0);\n delta.slice(n).at(F_pair_coord[std::make_pair(k, k)], 0) = tmp;\n }\n double sum_delta_n = arma::accu(delta.slice(n));\n loglik_vec.at(n) = std::log(sum_delta_n) + delta_n_max;\n delta.slice(n) = delta.slice(n) \/ sum_delta_n;\n }\n loglik = arma::accu(loglik_vec);\n}\n\n\/\/ update factor pair weights\nvoid PFA_EM::update_paired_factor_weights() {\n arma::vec pik1k2 = arma::vectorise(arma::mean(arma::sum(delta, 1), 2));\n#pragma omp parallel for num_threads(n_threads)\n for (size_t k1 = 0; k1 < P.n_rows; k1++) {\n for (size_t k2 = 0; k2 <= k1; k2++) {\n P.at(k1, k2) = pik1k2.at(F_pair_coord[std::make_pair(k1, k2)]);\n }\n }\n}\n\nvoid PFA_EM::update_factor_model() {\n \/\/ Factors F and loadings L are to be updated here\n \/\/ Need to compute 2 matrices in order to solve F\n L.fill(0);\n arma::mat L2 = L;\n#pragma omp parallel for num_threads(n_threads) collapse(2)\n for (size_t k = 0; k < F.n_rows; k++) {\n \/\/ I. First we compute the k-th column for E(L), the N X K matrix:\n \/\/ generate the proper input for N X Q %*% Q X 1\n \/\/ where the N X Q matrix is taken from delta given K1K2\n \/\/ and the Q X 1 matrix correspond to the grid of q\n \/\/ II. Then we compute the diagonal elements for E(W), the K X K matrix\n \/\/ First we still compute a N X K matrix like above but replacing q \/ 1 - q\n \/\/ with q^2 \/ (1 - q)^2\n \/\/ then take colsum to get the K vector as the diagonal\n for (size_t i = 0; i < F.n_rows; i++) {\n \/\/ create the LHS Dk1k2, N X Q matrix from delta given k1, k2\n arma::mat Dk1k2(D.n_rows, q.n_elem, arma::fill::zeros);\n for (size_t n = 0; n < D.n_rows; n++) {\n Dk1k2.row(n) = delta.slice(n).row(F_pair_coord[std::make_pair(k, i)]);\n }\n#pragma omp critical\n {\n if (k < i) {\n \/\/ I.\n L.col(k) += Dk1k2 * q;\n \/\/ II.\n L2.col(k) += Dk1k2 * (q % q);\n }\n if (k > i) {\n L.col(k) += Dk1k2 * (1 - q);\n L2.col(k) += Dk1k2 * ((1 - q) % (1 - q));\n }\n if (k == i) {\n L.col(k) += Dk1k2.col(0);\n L2.col(k) += Dk1k2.col(0);\n }\n }\n }\n }\n \/\/ II. diagonal elements for E(W)\n W.diag() = arma::sum(L2);\n \/\/ III. Compute off-diagonal elements for E(W), the K X K matrix\n \/\/ for k1 != k2\n \/\/ it involves on the LHS a vector of [q1(1-q1), q2(1-q2) ...]\n \/\/ and on the RHS for each pair of (k1, k2) the corresponding row from delta\n \/\/ summing over samples\n arma::vec LHS = q % (1 - q);\n arma::mat RHS = arma::sum(delta, 2);\n RHS = RHS.t();\n#pragma omp parallel for num_threads(n_threads)\n for (size_t k1 = 0; k1 < F.n_rows; k1++) {\n for (size_t k2 = 0; k2 < k1; k2++) {\n W.at(k1, k2) =\n arma::dot(LHS, RHS.col(F_pair_coord[std::make_pair(k1, k2)]));\n W.at(k2, k1) = W.at(k1, k2);\n }\n }\n \/\/ IV. Solve F\n F = arma::solve(W, L.t() * D);\n}\n\n\/\/ S is the residual standard error vector to be updated for each feature\n\/\/ FIXME: can this be optimized via transposing the tensor delta?\nvoid PFA_EM::update_residual_error() {\n#pragma omp parallel for num_threads(n_threads)\n for (size_t j = 0; j < D.n_cols; j++) {\n s.at(j) = 0;\n for (size_t k1 = 0; k1 < F.n_rows; k1++) {\n for (size_t k2 = 0; k2 <= k1; k2++) {\n for (size_t n = 0; n < D.n_rows; n++) {\n if (k2 < k1) {\n for (size_t qq = 0; qq < q.n_elem; qq++) {\n s.at(j) +=\n delta.slice(n).at(F_pair_coord[std::make_pair(k1, k2)], qq) *\n std::pow(D.at(n, j) - q.at(qq) * F.at(k2, j) -\n (1 - q.at(qq)) * F.at(k1, j),\n 2);\n }\n } else {\n s.at(j) +=\n delta.slice(n).at(F_pair_coord[std::make_pair(k1, k2)], 0) *\n std::pow(D.at(n, j) - F.at(k1, j), 2);\n }\n }\n }\n }\n s.at(j) = std::sqrt(s.at(j) \/ double(D.n_rows));\n }\n}\n<|endoftext|>"} {"text":"\/\/ Main.cc\n\/\/ This will start a WDE session.\n\n#include \"Renderer.h\"\n\nint main()\n{\n\tWDE::Renderer* renderer = new WDE::Renderer(1280, 720);\n\trenderer->RenderHTML();\n\trenderer->MainLoop();\n\tdelete renderer;\n\t\n\treturn 0;\n}\nChanged source filenames to lowercase\/\/ main.cc\n\/\/ This will start a WDE session.\n\n#include \"renderer.h\"\n\nint main()\n{\n\tWDE::Renderer* renderer = new WDE::Renderer(1280, 720);\n\trenderer->RenderHTML();\n\trenderer->MainLoop();\n\tdelete renderer;\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2015 - The CM Authors \n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \n#include \n#include \"fnord\/base\/random.h\"\n#include \"fnord\/net\/http\/httprouter.h\"\n#include \"fnord\/net\/http\/httpserver.h\"\n#include \"fnord\/thread\/eventloop.h\"\n#include \"fnord\/thread\/threadpool.h\"\n#include \"fnord\/system\/signalhandler.h\"\n#include \"fnord\/logging\/logoutputstream.h\"\n#include \"customernamespace.h\"\n#include \"tracker\/tracker.h\"\n\nint main() {\n fnord::system::SignalHandler::ignoreSIGHUP();\n fnord::system::SignalHandler::ignoreSIGPIPE();\n\n fnord::CatchAndAbortExceptionHandler ehandler;\n ehandler.installGlobalHandlers();\n\n fnord::log::LogOutputStream logger(fnord::io::OutputStream::getStderr());\n fnord::log::Logger::get()->setMinimumLogLevel(fnord::log::kInfo);\n fnord::log::Logger::get()->listen(&logger);\n\n auto dwn_ns = new cm::CustomerNamespace();\n dwn_ns->addVHost(\"dwnapps.net\");\n dwn_ns->loadTrackingJS(\"config\/c_dwn\/track.js\");\n\n std::unique_ptr tracker(new cm::Tracker());\n tracker->addCustomer(dwn_ns);\n\n fnord::thread::ThreadPool thread_pool;\n fnord::thread::EventLoop event_loop;\n\n fnord::http::HTTPRouter http_router;\n http_router.addRouteByPrefixMatch(\"\/\", tracker.get());\n\n fnord::http::HTTPServer http_server(&http_router, &thread_pool);\n http_server.listen(8080);\n\n for (;;) {\n usleep(10000);\n }\n\n return 0;\n}\n\nOMerge branch 'master' of \/home\/paul\/tmp\/..\/paulbox\/clickmatcher\/**\n * Copyright (c) 2015 - The CM Authors \n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \n#include \n#include \"fnord\/base\/random.h\"\n#include \"fnord\/net\/http\/httprouter.h\"\n#include \"fnord\/net\/http\/httpserver.h\"\n#include \"fnord\/thread\/eventloop.h\"\n#include \"fnord\/thread\/threadpool.h\"\n#include \"fnord\/system\/signalhandler.h\"\n#include \"fnord\/logging\/logoutputstream.h\"\n#include \"customernamespace.h\"\n#include \"tracker\/tracker.h\"\n\nint main() {\n fnord::system::SignalHandler::ignoreSIGHUP();\n fnord::system::SignalHandler::ignoreSIGPIPE();\n\n fnord::CatchAndAbortExceptionHandler ehandler;\n ehandler.installGlobalHandlers();\n\n fnord::log::LogOutputStream logger(fnord::io::OutputStream::getStderr());\n fnord::log::Logger::get()->setMinimumLogLevel(fnord::log::kInfo);\n fnord::log::Logger::get()->listen(&logger);\n\n auto dwn_ns = new cm::CustomerNamespace();\n dwn_ns->addVHost(\"dwnapps.net\");\n dwn_ns->loadTrackingJS(\"config\/c_dwn\/track.js\");\n\n std::unique_ptr tracker(new cm::Tracker());\n tracker->addCustomer(dwn_ns);\n\n fnord::thread::ThreadPool thread_pool;\n fnord::thread::EventLoop event_loop;\n\n fnord::http::HTTPRouter http_router;\n http_router.addRouteByPrefixMatch(\"\/\", tracker.get());\n\n fnord::http::HTTPServer http_server(&http_router, &event_loop);\n http_server.listen(8080);\n\n event_loop.run();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/* author: @gwzz\n * \n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"graph.h\"\n#include \"support.h\"\n#include \"sctfile.h\"\n\nusing namespace std;\n\n\/\/ Pre-define hierarchy array\n\/\/ CUI: array of top nodes concept id of each hierarchy\n\/\/ ConName: array of the name of each hierarchy\nconst long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};\nconst string ConName[19] = {\"Body_structure\", \"Clinical_finding\", \"Environment_or_geographical_location\", \"Event\", \"Observable_entity\", \"Organism\", \"Pharmaceutical_biologic_product\", \"Physical_force\", \"Physical_object\", \"Procedure\", \"Qualifier_value\", \"Record_artifact\", \"Situation_with_explicit_context\", \"SNOMED_CT_Model_Component\", \"Social_context\", \"Special_Concept\", \"Specimen\", \"Staging_and_scales\", \"Substance\"};\n\n\/\/ define global variables\n\/\/ node_map: store all the concepts [key,value]\n\/\/ reversed_node_map: store reversed node_map [value,key]\n\/\/ nodeFile, relationFile, out_put_file, as variable name\nstring nodeFile = \"2016nodes.txt\";\nstring relationFile = \"2016relation.txt\";\n\n\n \nint main(int argc, char* argv[])\n{ \n if (argc < 2)\n {\n std::cerr << \"Usage: \" << argv[0] << \" SNOMED_CT_FILE_PATH\" << std::endl;\n return 1;\n }\n string out_put_folder = \"\/Users\/zhuwei\/Desktop\/sct_nodes_within_hierarchy\/\";\n SctFile sf(argv[1]);\n long long top_node;\n std::map node_map;\n std::map reversed_node_map;\n std::vector output_vector;\n std::string sline;\n std::vector relation;\n std::vector nodes;\n\n \/\/ Read in node file\n fstream fin;\n fin.open(nodeFile,ios::in);\n while (getline(fin, sline)){\n nodes.push_back(sline);\n }\n fin.close();\n for (int i = 0; i < nodes.size(); ++i){\n node_map[std::stoll(nodes[i])] = i;\n }\n\n for (map::iterator i = node_map.begin(); i != node_map.end(); ++i)\n reversed_node_map[i->second] = i->first;\n\n int nodeSize = node_map.size();\n fin.open(relationFile,ios::in);\n while (getline(fin, sline)){\n relation.push_back(sline);\n }\n fin.close();\n \/\/ initialize graph g\n Graph g(nodeSize);\n std::vector is_a_relationship;\n for (auto i : relation){\n is_a_relationship.clear();\n is_a_relationship = Split(i, ',');\n g.addEdge(node_map[is_a_relationship[1]],node_map[is_a_relationship[0]]);\n }\n\n string out_put_file;\n for (int i = 0; i < 19; ++i){\n output_vector.clear();\n out_put_file.clear();\n out_put_file = out_put_folder + ConName[i];\n top_node = CUI[i];\n output_vector = g.DFS(node_map[top_node]);\n fstream fout;\n fout.open(out_put_file,ios::app);\n for (auto o : output_vector){\n fout << reversed_node_map[o] << endl;\n }\n fout.close();\n }\n \n return 0;\n}refactor\/* author: @gwzz\n * \n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"graph.h\"\n#include \"support.h\"\n#include \"sctfile.h\"\n\nusing namespace std;\n\n\/\/ Pre-define hierarchy array\n\/\/ CUI: array of top nodes concept id of each hierarchy\n\/\/ ConName: array of the name of each hierarchy\nconst long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};\nconst string ConName[19] = {\"Body_structure\", \"Clinical_finding\", \"Environment_or_geographical_location\", \"Event\", \"Observable_entity\", \"Organism\", \"Pharmaceutical_biologic_product\", \"Physical_force\", \"Physical_object\", \"Procedure\", \"Qualifier_value\", \"Record_artifact\", \"Situation_with_explicit_context\", \"SNOMED_CT_Model_Component\", \"Social_context\", \"Special_Concept\", \"Specimen\", \"Staging_and_scales\", \"Substance\"};\n\n\/\/ define global variables\n\/\/ node_map: store all the concepts [key,value]\n\/\/ reversed_node_map: store reversed node_map [value,key]\n\/\/ nodeFile, relationFile, out_put_file, as variable name\nstring nodeFile = \"2016nodes.txt\";\nstring relationFile = \"2016relation.txt\";\n\n\n \nint main(int argc, char* argv[])\n{ \n if (argc < 2)\n {\n std::cerr << \"Usage: \" << argv[0] << \" SNOMED_CT_FILE_PATH\" << std::endl;\n return 1;\n }\n string out_put_folder = \"\/Users\/zhuwei\/Desktop\/sct_nodes_within_hierarchy\/\";\n SctFile sf(argv[1]);\n long long top_node;\n std::map node_map;\n std::map reversed_node_map;\n std::vector output_vector;\n std::string sline;\n std::vector relation = sf.relations();\n std::vector nodes = sf.nodes();\n\n \/\/ Read in node file\n fstream fin;\n \/\/ fin.open(nodeFile,ios::in);\n \/\/ while (getline(fin, sline)){\n \/\/ nodes.push_back(sline);\n \/\/ }\n \/\/ fin.close();\n for (int i = 0; i < nodes.size(); ++i){\n node_map[std::stoll(nodes[i])] = i;\n }\n\n for (map::iterator i = node_map.begin(); i != node_map.end(); ++i)\n reversed_node_map[i->second] = i->first;\n\n int nodeSize = node_map.size();\n \/\/ fin.open(relationFile,ios::in);\n \/\/ while (getline(fin, sline)){\n \/\/ relation.push_back(sline);\n \/\/ }\n \/\/ fin.close();\n \/\/ initialize graph g\n Graph g(nodeSize);\n std::vector is_a_relationship;\n for (auto i : relation){\n is_a_relationship.clear();\n is_a_relationship = Split(i, ',');\n g.addEdge(node_map[is_a_relationship[1]],node_map[is_a_relationship[0]]);\n }\n\n string out_put_file;\n for (int i = 0; i < 19; ++i){\n output_vector.clear();\n out_put_file.clear();\n out_put_file = out_put_folder + ConName[i];\n top_node = CUI[i];\n output_vector = g.DFS(node_map[top_node]);\n fstream fout;\n fout.open(out_put_file,ios::app);\n for (auto o : output_vector){\n fout << reversed_node_map[o] << endl;\n }\n fout.close();\n }\n \n return 0;\n}<|endoftext|>"} {"text":"#include \"zs.hh\"\n\n#define REPL_PROMPT \">> \"\n\nint main(){\n install_builtin();\n\n vm.code.push_back(make_cons_list({intern(vm.symtable(), \"read-eval-print-loop\")}));\n eval();\n\n return 0;\n}\ncleanup#include \"zs.hh\"\n\nint main(){\n install_builtin();\n\n vm.code.push_back(make_cons_list({intern(vm.symtable(), \"read-eval-print-loop\")}));\n eval();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"cpu.h\"\n\nint main() {\n using namespace std;\n \n ifstream rom(\"..\/image\/rom\");\n ifstream flash(\"..\/image\/disk0\");\n\n CPU cpu(rom, flash);\n\n cpu.run();\n\n}\n\nbuffer rom and flash into memory#include \n#include \n\n#include \"cpu.h\"\n\nint main() {\n using namespace std;\n \n ifstream rom(\"..\/image\/rom\");\n ifstream flash(\"..\/image\/disk0\");\n\n \/\/ copy files to memory to speed up access\n stringstream rom_buffer;\n stringstream flash_buffer;\n copy(istreambuf_iterator(rom), istreambuf_iterator(), \n ostreambuf_iterator(rom_buffer));\n copy(istreambuf_iterator(flash), istreambuf_iterator(), \n ostreambuf_iterator(flash_buffer));\n\n CPU cpu(rom_buffer, flash_buffer);\n\n cpu.run();\n\n}\n\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include \"pcl\/impl\/instantiate.hpp\"\n#include \"pcl\/point_types.h\"\n#include \"pcl\/surface\/poisson.h\"\n#include \"pcl\/surface\/impl\/poisson.hpp\"\n\n\/\/ Instantiations of specific point types\nPCL_INSTANTIATE(Poisson, (pcl::PointNormal)(pcl::PointXYZRGBNormal)(pcl::PointXYZINormal));\n\ndisabling optimizations for Poisson on Windows - should fix the unit tests\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifdef WIN32\n#pragma optimize(\"g\", off)\n#endif WIN32\n\n#include \"pcl\/impl\/instantiate.hpp\"\n#include \"pcl\/point_types.h\"\n#include \"pcl\/surface\/poisson.h\"\n#include \"pcl\/surface\/impl\/poisson.hpp\"\n\n\/\/ Instantiations of specific point types\nPCL_INSTANTIATE(Poisson, (pcl::PointNormal)(pcl::PointXYZRGBNormal)(pcl::PointXYZINormal));\n\n<|endoftext|>"} {"text":"\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2008, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Willow Garage nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\/*\n Author: Melonee Wise\n Contributors: Dave Coleman, Jonathan Bohren, Bob Holmberg, Wim Meeussen\n Desc: Implements a standard proportional-integral-derivative controller\n*\/\n\n#include \n#include \n\nnamespace control_toolbox {\n\nstatic const std::string DEFAULT_NAMESPACE = \"pid\"; \/\/ \\todo better default prefix?\n\nPid::Pid(double p, double i, double d, double i_max, double i_min)\n : dynamic_reconfig_initialized_(false)\n{\n setGains(p,i,d,i_max,i_min);\n\n reset();\n}\n\nPid::Pid(const Pid &source)\n : dynamic_reconfig_initialized_(false)\n{\n \/\/ Copy the realtime buffer to then new PID class\n gains_buffer_ = source.gains_buffer_;\n\n \/\/ Reset the state of this PID controller\n reset();\n}\n\nPid::~Pid()\n{\n}\n\nvoid Pid::initPid(double p, double i, double d, double i_max, double i_min, \n const ros::NodeHandle &node)\n{\n initPid(p, i, d, i_max, i_min);\n\n \/\/ Create node handle for dynamic reconfigure\n ros::NodeHandle nh(DEFAULT_NAMESPACE);\n initDynamicReconfig(nh);\n}\n\nvoid Pid::initPid(double p, double i, double d, double i_max, double i_min)\n{\n setGains(p,i,d,i_max,i_min);\n\n reset();\n}\n\nbool Pid::initParam(const std::string& prefix, const bool quiet)\n{\n ros::NodeHandle nh(prefix);\n return init(nh, quiet);\n}\n\nbool Pid::init(const ros::NodeHandle &node, const bool quiet)\n{\n ros::NodeHandle nh(node);\n\n Gains gains;\n\n \/\/ Load PID gains from parameter server\n if (!nh.getParam(\"p\", gains.p_gain_)) \n {\n if (!quiet) {\n ROS_ERROR(\"No p gain specified for pid. Namespace: %s\", nh.getNamespace().c_str());\n }\n return false;\n }\n \/\/ Only the P gain is required, the I and D gains are optional and default to 0:\n nh.param(\"i\", gains.i_gain_, 0.0);\n nh.param(\"d\", gains.d_gain_, 0.0);\n\n \/\/ Load integral clamp from param server or default to 0\n double i_clamp;\n nh.param(\"i_clamp\", i_clamp, 0.0);\n gains.i_max_ = std::abs(i_clamp);\n gains.i_min_ = -std::abs(i_clamp);\n if(nh.hasParam(\"i_clamp_min\"))\n {\n nh.param(\"i_clamp_min\", gains.i_min_, gains.i_min_); \/\/ use i_clamp_min parameter, otherwise keep -i_clamp\n gains.i_min_ = -std::abs(gains.i_min_); \/\/ make sure the value is <= 0\n }\n if(nh.hasParam(\"i_clamp_max\"))\n {\n nh.param(\"i_clamp_max\", gains.i_max_, gains.i_max_); \/\/ use i_clamp_max parameter, otherwise keep i_clamp\n gains.i_max_ = std::abs(gains.i_max_); \/\/ make sure the value is >= 0\n }\n \n setGains(gains);\n\n reset();\n initDynamicReconfig(nh);\n\n return true;\n}\n\nbool Pid::initXml(TiXmlElement *config)\n{\n \/\/ Create node handle for dynamic reconfigure\n ros::NodeHandle nh(DEFAULT_NAMESPACE);\n\n double i_clamp;\n i_clamp = config->Attribute(\"iClamp\") ? atof(config->Attribute(\"iClamp\")) : 0.0;\n\n setGains( \n config->Attribute(\"p\") ? atof(config->Attribute(\"p\")) : 0.0,\n config->Attribute(\"i\") ? atof(config->Attribute(\"i\")) : 0.0,\n config->Attribute(\"d\") ? atof(config->Attribute(\"d\")) : 0.0,\n std::abs(i_clamp),\n -std::abs(i_clamp)\n );\n\n reset();\n initDynamicReconfig(nh);\n\n return true;\n}\n\nvoid Pid::initDynamicReconfig(ros::NodeHandle &node)\n{\n ROS_DEBUG_STREAM_NAMED(\"pid\",\"Initializing dynamic reconfigure in namespace \" \n << node.getNamespace());\n\n \/\/ Start dynamic reconfigure server\n param_reconfig_server_.reset(new DynamicReconfigServer(param_reconfig_mutex_, node));\n dynamic_reconfig_initialized_ = true;\n \n \/\/ Set Dynamic Reconfigure's gains to Pid's values\n updateDynamicReconfig();\n\n \/\/ Set callback\n param_reconfig_callback_ = boost::bind(&Pid::dynamicReconfigCallback, this, _1, _2);\n param_reconfig_server_->setCallback(param_reconfig_callback_); \n}\n\nvoid Pid::reset()\n{\n p_error_last_ = 0.0;\n p_error_ = 0.0;\n i_error_ = 0.0;\n d_error_ = 0.0;\n cmd_ = 0.0;\n}\n\nvoid Pid::getGains(double &p, double &i, double &d, double &i_max, double &i_min)\n{\n Gains gains = *gains_buffer_.readFromRT();\n\n p = gains.p_gain_;\n i = gains.i_gain_;\n d = gains.d_gain_;\n i_max = gains.i_max_;\n i_min = gains.i_min_;\n}\n\nPid::Gains Pid::getGains() \n{\n return *gains_buffer_.readFromRT();\n}\n\nvoid Pid::setGains(double p, double i, double d, double i_max, double i_min)\n{\n Gains gains(p,i,d,i_max,i_min);\n \n setGains(gains);\n}\n\nvoid Pid::setGains(const Gains &gains)\n{\n gains_buffer_.writeFromNonRT(gains);\n\n \/\/ Update dynamic reconfigure with the new gains\n updateDynamicReconfig(gains);\n}\n\nvoid Pid::updateDynamicReconfig()\n{\n \/\/ Make sure dynamic reconfigure is initialized\n if(!dynamic_reconfig_initialized_)\n return;\n\n \/\/ Get starting values \n control_toolbox::ParametersConfig config;\n\n \/\/ Get starting values \n getGains(config.p, config.i, config.d, config.i_clamp_max, config.i_clamp_min);\n\n updateDynamicReconfig(config);\n}\n\nvoid Pid::updateDynamicReconfig(Gains gains_config)\n{\n \/\/ Make sure dynamic reconfigure is initialized\n if(!dynamic_reconfig_initialized_)\n return;\n\n control_toolbox::ParametersConfig config;\n\n \/\/ Convert to dynamic reconfigure format\n config.p = gains_config.p_gain_;\n config.i = gains_config.i_gain_;\n config.d = gains_config.d_gain_;\n config.i_clamp_max = gains_config.i_max_;\n config.i_clamp_min = gains_config.i_min_;\n\n updateDynamicReconfig(config);\n}\n\nvoid Pid::updateDynamicReconfig(control_toolbox::ParametersConfig config)\n{\n \/\/ Make sure dynamic reconfigure is initialized\n if(!dynamic_reconfig_initialized_)\n return;\n\n \/\/ Set starting values, using a shared mutex with dynamic reconfig\n param_reconfig_mutex_.lock(); \n param_reconfig_server_->updateConfig(config);\n param_reconfig_mutex_.unlock(); \n}\n\nvoid Pid::dynamicReconfigCallback(control_toolbox::ParametersConfig &config, uint32_t level)\n{\n ROS_DEBUG_STREAM_NAMED(\"pid\",\"Dynamics reconfigure callback recieved.\");\n\n \/\/ Set the gains\n setGains(config.p, config.i, config.d, config.i_clamp_max, config.i_clamp_min);\n}\n\ndouble Pid::computeCommand(double error, ros::Duration dt)\n{\n \/\/ Get the gain parameters from the realtime buffer\n Gains gains = *gains_buffer_.readFromRT();\n\n double p_term, d_term, i_term;\n p_error_ = error; \/\/ this is error = target - state\n\n if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))\n return 0.0;\n\n \/\/ Calculate proportional contribution to command\n p_term = gains.p_gain_ * p_error_;\n\n \/\/ Calculate the integral of the position error\n i_error_ += dt.toSec() * p_error_;\n \n \/\/ Calculate integral contribution to command\n i_term = gains.i_gain_ * i_error_;\n\n \/\/ Limit i_term so that the limit is meaningful in the output\n i_term = std::max( gains.i_min_, std::min( i_term, gains.i_max_) );\n\n \/\/ Calculate the derivative error\n if (dt.toSec() > 0.0)\n {\n d_error_ = (p_error_ - p_error_last_) \/ dt.toSec();\n p_error_last_ = p_error_;\n }\n \/\/ Calculate derivative contribution to command\n d_term = gains.d_gain_ * d_error_;\n\n \/\/ Compute the command\n cmd_ = p_term + i_term + d_term;\n\n return cmd_;\n}\n\ndouble Pid::updatePid(double error, ros::Duration dt)\n{\n \/\/ Get the gain parameters from the realtime buffer\n Gains gains = *gains_buffer_.readFromRT();\n\n double p_term, d_term, i_term;\n p_error_ = error; \/\/this is pError = pState-pTarget\n\n if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))\n return 0.0;\n\n \/\/ Calculate proportional contribution to command\n p_term = gains.p_gain_ * p_error_;\n\n \/\/ Calculate the integral of the position error\n i_error_ += dt.toSec() * p_error_;\n \n \/\/ Calculate integral contribution to command\n i_term = gains.i_gain_ * i_error_;\n\n \/\/ Limit i_term so that the limit is meaningful in the output\n i_term = std::max( gains.i_min_, std::min( i_term, gains.i_max_) );\n\n \/\/ Calculate the derivative error\n if (dt.toSec() > 0.0)\n {\n d_error_ = (p_error_ - p_error_last_) \/ dt.toSec();\n p_error_last_ = p_error_;\n }\n \/\/ Calculate derivative contribution to command\n d_term = gains.d_gain_ * d_error_;\n\n \/\/ Compute the command\n cmd_ = - p_term - i_term - d_term;\n\n return cmd_;\n}\n\ndouble Pid::computeCommand(double error, double error_dot, ros::Duration dt)\n{\n \/\/ Get the gain parameters from the realtime buffer\n Gains gains = *gains_buffer_.readFromRT();\n\n double p_term, d_term, i_term;\n p_error_ = error; \/\/ this is error = target - state\n d_error_ = error_dot;\n\n if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))\n return 0.0;\n\n\n \/\/ Calculate proportional contribution to command\n p_term = gains.p_gain_ * p_error_;\n\n \/\/ Calculate the integral of the position error\n i_error_ += dt.toSec() * p_error_;\n \n \/\/ Calculate integral contribution to command\n i_term = gains.i_gain_ * i_error_;\n\n \/\/ Limit i_term so that the limit is meaningful in the output\n i_term = std::max( gains.i_min_, std::min( i_term, gains.i_max_) );\n\n \/\/ Calculate derivative contribution to command\n d_term = gains.d_gain_ * d_error_;\n\n \/\/ Compute the command\n cmd_ = p_term + i_term + d_term;\n\n return cmd_;\n}\n\ndouble Pid::updatePid(double error, double error_dot, ros::Duration dt)\n{\n \/\/ Get the gain parameters from the realtime buffer\n Gains gains = *gains_buffer_.readFromRT();\n\n double p_term, d_term, i_term;\n p_error_ = error; \/\/this is pError = pState-pTarget\n d_error_ = error_dot;\n\n if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))\n return 0.0;\n\n\n \/\/ Calculate proportional contribution to command\n p_term = gains.p_gain_ * p_error_;\n\n \/\/ Calculate the integral of the position error\n i_error_ += dt.toSec() * p_error_;\n \n \/\/ Calculate integral contribution to command\n i_term = gains.i_gain_ * i_error_;\n\n \/\/ Limit i_term so that the limit is meaningful in the output\n i_term = std::max( gains.i_min_, std::min( i_term, gains.i_max_) );\n\n \/\/ Calculate derivative contribution to command\n d_term = gains.d_gain_ * d_error_;\n\n \/\/ Compute the command\n cmd_ = - p_term - i_term - d_term;\n\n return cmd_;\n}\n\nvoid Pid::setCurrentCmd(double cmd)\n{\n cmd_ = cmd;\n}\n\ndouble Pid::getCurrentCmd()\n{\n return cmd_;\n}\n\nvoid Pid::getCurrentPIDErrors(double *pe, double *ie, double *de)\n{\n \/\/ Get the gain parameters from the realtime buffer\n Gains gains = *gains_buffer_.readFromRT();\n\n *pe = p_error_;\n *ie = i_error_;\n *de = d_error_;\n}\n\nvoid Pid::printValues()\n{\n Gains gains = getGains();\n\n ROS_INFO_STREAM_NAMED(\"pid\",\"Current Values of PID Class:\\n\"\n << \" P Gain: \" << gains.p_gain_ << \"\\n\"\n << \" I Gain: \" << gains.i_gain_ << \"\\n\"\n << \" D Gain: \" << gains.d_gain_ << \"\\n\"\n << \" I_Max: \" << gains.i_max_ << \"\\n\"\n << \" I_Min: \" << gains.i_min_ << \"\\n\"\n << \" P_Error_Last: \" << p_error_last_ << \"\\n\"\n << \" P_Error: \" << p_error_ << \"\\n\"\n << \" I_Error: \" << i_error_ << \"\\n\"\n << \" D_Error: \" << d_error_ << \"\\n\"\n << \" Command: \" << cmd_\n );\n\n}\n\n} \/\/ namespace\nChain calls of computeCommand and updatePid for code reuse\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2008, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Willow Garage nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\/*\n Author: Melonee Wise\n Contributors: Dave Coleman, Jonathan Bohren, Bob Holmberg, Wim Meeussen\n Desc: Implements a standard proportional-integral-derivative controller\n*\/\n\n#include \n#include \n\nnamespace control_toolbox {\n\nstatic const std::string DEFAULT_NAMESPACE = \"pid\"; \/\/ \\todo better default prefix?\n\nPid::Pid(double p, double i, double d, double i_max, double i_min)\n : dynamic_reconfig_initialized_(false)\n{\n setGains(p,i,d,i_max,i_min);\n\n reset();\n}\n\nPid::Pid(const Pid &source)\n : dynamic_reconfig_initialized_(false)\n{\n \/\/ Copy the realtime buffer to then new PID class\n gains_buffer_ = source.gains_buffer_;\n\n \/\/ Reset the state of this PID controller\n reset();\n}\n\nPid::~Pid()\n{\n}\n\nvoid Pid::initPid(double p, double i, double d, double i_max, double i_min, \n const ros::NodeHandle &node)\n{\n initPid(p, i, d, i_max, i_min);\n\n \/\/ Create node handle for dynamic reconfigure\n ros::NodeHandle nh(DEFAULT_NAMESPACE);\n initDynamicReconfig(nh);\n}\n\nvoid Pid::initPid(double p, double i, double d, double i_max, double i_min)\n{\n setGains(p,i,d,i_max,i_min);\n\n reset();\n}\n\nbool Pid::initParam(const std::string& prefix, const bool quiet)\n{\n ros::NodeHandle nh(prefix);\n return init(nh, quiet);\n}\n\nbool Pid::init(const ros::NodeHandle &node, const bool quiet)\n{\n ros::NodeHandle nh(node);\n\n Gains gains;\n\n \/\/ Load PID gains from parameter server\n if (!nh.getParam(\"p\", gains.p_gain_)) \n {\n if (!quiet) {\n ROS_ERROR(\"No p gain specified for pid. Namespace: %s\", nh.getNamespace().c_str());\n }\n return false;\n }\n \/\/ Only the P gain is required, the I and D gains are optional and default to 0:\n nh.param(\"i\", gains.i_gain_, 0.0);\n nh.param(\"d\", gains.d_gain_, 0.0);\n\n \/\/ Load integral clamp from param server or default to 0\n double i_clamp;\n nh.param(\"i_clamp\", i_clamp, 0.0);\n gains.i_max_ = std::abs(i_clamp);\n gains.i_min_ = -std::abs(i_clamp);\n if(nh.hasParam(\"i_clamp_min\"))\n {\n nh.param(\"i_clamp_min\", gains.i_min_, gains.i_min_); \/\/ use i_clamp_min parameter, otherwise keep -i_clamp\n gains.i_min_ = -std::abs(gains.i_min_); \/\/ make sure the value is <= 0\n }\n if(nh.hasParam(\"i_clamp_max\"))\n {\n nh.param(\"i_clamp_max\", gains.i_max_, gains.i_max_); \/\/ use i_clamp_max parameter, otherwise keep i_clamp\n gains.i_max_ = std::abs(gains.i_max_); \/\/ make sure the value is >= 0\n }\n \n setGains(gains);\n\n reset();\n initDynamicReconfig(nh);\n\n return true;\n}\n\nbool Pid::initXml(TiXmlElement *config)\n{\n \/\/ Create node handle for dynamic reconfigure\n ros::NodeHandle nh(DEFAULT_NAMESPACE);\n\n double i_clamp;\n i_clamp = config->Attribute(\"iClamp\") ? atof(config->Attribute(\"iClamp\")) : 0.0;\n\n setGains( \n config->Attribute(\"p\") ? atof(config->Attribute(\"p\")) : 0.0,\n config->Attribute(\"i\") ? atof(config->Attribute(\"i\")) : 0.0,\n config->Attribute(\"d\") ? atof(config->Attribute(\"d\")) : 0.0,\n std::abs(i_clamp),\n -std::abs(i_clamp)\n );\n\n reset();\n initDynamicReconfig(nh);\n\n return true;\n}\n\nvoid Pid::initDynamicReconfig(ros::NodeHandle &node)\n{\n ROS_DEBUG_STREAM_NAMED(\"pid\",\"Initializing dynamic reconfigure in namespace \" \n << node.getNamespace());\n\n \/\/ Start dynamic reconfigure server\n param_reconfig_server_.reset(new DynamicReconfigServer(param_reconfig_mutex_, node));\n dynamic_reconfig_initialized_ = true;\n \n \/\/ Set Dynamic Reconfigure's gains to Pid's values\n updateDynamicReconfig();\n\n \/\/ Set callback\n param_reconfig_callback_ = boost::bind(&Pid::dynamicReconfigCallback, this, _1, _2);\n param_reconfig_server_->setCallback(param_reconfig_callback_); \n}\n\nvoid Pid::reset()\n{\n p_error_last_ = 0.0;\n p_error_ = 0.0;\n i_error_ = 0.0;\n d_error_ = 0.0;\n cmd_ = 0.0;\n}\n\nvoid Pid::getGains(double &p, double &i, double &d, double &i_max, double &i_min)\n{\n Gains gains = *gains_buffer_.readFromRT();\n\n p = gains.p_gain_;\n i = gains.i_gain_;\n d = gains.d_gain_;\n i_max = gains.i_max_;\n i_min = gains.i_min_;\n}\n\nPid::Gains Pid::getGains() \n{\n return *gains_buffer_.readFromRT();\n}\n\nvoid Pid::setGains(double p, double i, double d, double i_max, double i_min)\n{\n Gains gains(p,i,d,i_max,i_min);\n \n setGains(gains);\n}\n\nvoid Pid::setGains(const Gains &gains)\n{\n gains_buffer_.writeFromNonRT(gains);\n\n \/\/ Update dynamic reconfigure with the new gains\n updateDynamicReconfig(gains);\n}\n\nvoid Pid::updateDynamicReconfig()\n{\n \/\/ Make sure dynamic reconfigure is initialized\n if(!dynamic_reconfig_initialized_)\n return;\n\n \/\/ Get starting values \n control_toolbox::ParametersConfig config;\n\n \/\/ Get starting values \n getGains(config.p, config.i, config.d, config.i_clamp_max, config.i_clamp_min);\n\n updateDynamicReconfig(config);\n}\n\nvoid Pid::updateDynamicReconfig(Gains gains_config)\n{\n \/\/ Make sure dynamic reconfigure is initialized\n if(!dynamic_reconfig_initialized_)\n return;\n\n control_toolbox::ParametersConfig config;\n\n \/\/ Convert to dynamic reconfigure format\n config.p = gains_config.p_gain_;\n config.i = gains_config.i_gain_;\n config.d = gains_config.d_gain_;\n config.i_clamp_max = gains_config.i_max_;\n config.i_clamp_min = gains_config.i_min_;\n\n updateDynamicReconfig(config);\n}\n\nvoid Pid::updateDynamicReconfig(control_toolbox::ParametersConfig config)\n{\n \/\/ Make sure dynamic reconfigure is initialized\n if(!dynamic_reconfig_initialized_)\n return;\n\n \/\/ Set starting values, using a shared mutex with dynamic reconfig\n param_reconfig_mutex_.lock(); \n param_reconfig_server_->updateConfig(config);\n param_reconfig_mutex_.unlock(); \n}\n\nvoid Pid::dynamicReconfigCallback(control_toolbox::ParametersConfig &config, uint32_t level)\n{\n ROS_DEBUG_STREAM_NAMED(\"pid\",\"Dynamics reconfigure callback recieved.\");\n\n \/\/ Set the gains\n setGains(config.p, config.i, config.d, config.i_clamp_max, config.i_clamp_min);\n}\n\ndouble Pid::computeCommand(double error, ros::Duration dt)\n{\n\n if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))\n return 0.0;\n\n double error_dot = d_error_;\n\n \/\/ Calculate the derivative error\n if (dt.toSec() > 0.0)\n {\n error_dot = (error - p_error_last_) \/ dt.toSec();\n p_error_last_ = error;\n }\n\n return computeCommand(error, error_dot, dt);\n}\n\ndouble Pid::updatePid(double error, ros::Duration dt)\n{\n if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error))\n return 0.0;\n\n double error_dot = d_error_;\n\n \/\/ Calculate the derivative error\n if (dt.toSec() > 0.0)\n {\n error_dot = (error - p_error_last_) \/ dt.toSec();\n p_error_last_ = error;\n }\n\n return updatePid(error, error_dot, dt);\n}\n\ndouble Pid::computeCommand(double error, double error_dot, ros::Duration dt)\n{\n \/\/ Get the gain parameters from the realtime buffer\n Gains gains = *gains_buffer_.readFromRT();\n\n double p_term, d_term, i_term;\n p_error_ = error; \/\/ this is error = target - state\n d_error_ = error_dot;\n\n if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))\n return 0.0;\n\n\n \/\/ Calculate proportional contribution to command\n p_term = gains.p_gain_ * p_error_;\n\n \/\/ Calculate the integral of the position error\n i_error_ += dt.toSec() * p_error_;\n \n \/\/ Calculate integral contribution to command\n i_term = gains.i_gain_ * i_error_;\n\n \/\/ Limit i_term so that the limit is meaningful in the output\n i_term = std::max( gains.i_min_, std::min( i_term, gains.i_max_) );\n\n \/\/ Calculate derivative contribution to command\n d_term = gains.d_gain_ * d_error_;\n\n \/\/ Compute the command\n cmd_ = p_term + i_term + d_term;\n\n return cmd_;\n}\n\ndouble Pid::updatePid(double error, double error_dot, ros::Duration dt)\n{\n \/\/ Get the gain parameters from the realtime buffer\n Gains gains = *gains_buffer_.readFromRT();\n\n double p_term, d_term, i_term;\n p_error_ = error; \/\/this is pError = pState-pTarget\n d_error_ = error_dot;\n\n if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot))\n return 0.0;\n\n\n \/\/ Calculate proportional contribution to command\n p_term = gains.p_gain_ * p_error_;\n\n \/\/ Calculate the integral of the position error\n i_error_ += dt.toSec() * p_error_;\n \n \/\/ Calculate integral contribution to command\n i_term = gains.i_gain_ * i_error_;\n\n \/\/ Limit i_term so that the limit is meaningful in the output\n i_term = std::max( gains.i_min_, std::min( i_term, gains.i_max_) );\n\n \/\/ Calculate derivative contribution to command\n d_term = gains.d_gain_ * d_error_;\n\n \/\/ Compute the command\n cmd_ = - p_term - i_term - d_term;\n\n return cmd_;\n}\n\nvoid Pid::setCurrentCmd(double cmd)\n{\n cmd_ = cmd;\n}\n\ndouble Pid::getCurrentCmd()\n{\n return cmd_;\n}\n\nvoid Pid::getCurrentPIDErrors(double *pe, double *ie, double *de)\n{\n \/\/ Get the gain parameters from the realtime buffer\n Gains gains = *gains_buffer_.readFromRT();\n\n *pe = p_error_;\n *ie = i_error_;\n *de = d_error_;\n}\n\nvoid Pid::printValues()\n{\n Gains gains = getGains();\n\n ROS_INFO_STREAM_NAMED(\"pid\",\"Current Values of PID Class:\\n\"\n << \" P Gain: \" << gains.p_gain_ << \"\\n\"\n << \" I Gain: \" << gains.i_gain_ << \"\\n\"\n << \" D Gain: \" << gains.d_gain_ << \"\\n\"\n << \" I_Max: \" << gains.i_max_ << \"\\n\"\n << \" I_Min: \" << gains.i_min_ << \"\\n\"\n << \" P_Error_Last: \" << p_error_last_ << \"\\n\"\n << \" P_Error: \" << p_error_ << \"\\n\"\n << \" I_Error: \" << i_error_ << \"\\n\"\n << \" D_Error: \" << d_error_ << \"\\n\"\n << \" Command: \" << cmd_\n );\n\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"libbpf.h\"\n#include \"utils.h\"\n\n#include \"map.h\"\n\nnamespace bpftrace {\n\nint Map::create_map(enum bpf_map_type map_type, const char *name, int key_size, int value_size, int max_entries, int flags) {\n#ifdef HAVE_BCC_CREATE_MAP\n return bcc_create_map(map_type, name, key_size, value_size, max_entries, flags);\n#else\n return bpf_create_map(map_type, name, key_size, value_size, max_entries, flags);\n#endif\n}\n\nMap::Map(const std::string &name, const SizedType &type, const MapKey &key, int min, int max, int step)\n{\n name_ = name;\n type_ = type;\n key_ = key;\n \/\/ for lhist maps:\n lqmin = min;\n lqmax = max;\n lqstep = step;\n\n int key_size = key.size();\n if (type.type == Type::hist || type.type == Type::lhist ||\n type.type == Type::avg || type.type == Type::stats)\n key_size += 8;\n if (key_size == 0)\n key_size = 8;\n\n int max_entries = 128;\n enum bpf_map_type map_type;\n if ((type.type == Type::hist || type.type == Type::lhist || type.type == Type::count ||\n type.type == Type::sum || type.type == Type::min || type.type == Type::max ||\n type.type == Type::avg || type.type == Type::stats) &&\n (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 6, 0)))\n {\n map_type = BPF_MAP_TYPE_PERCPU_HASH;\n }\n else if (type.type == Type::join)\n {\n map_type = BPF_MAP_TYPE_PERCPU_ARRAY;\n max_entries = 1;\n key_size = 4;\n }\n else\n map_type = BPF_MAP_TYPE_HASH;\n\n int value_size = type.size;\n int flags = 0;\n mapfd_ = create_map(map_type, name.c_str(), key_size, value_size, max_entries, flags);\n if (mapfd_ < 0)\n {\n std::cerr << \"Error creating map: '\" << name_ << \"'\" << std::endl;\n }\n}\n\nMap::Map(const SizedType &type) {\n#ifdef DEBUG\n \/\/ TODO (mmarchini): replace with DCHECK\n if (!type.IsStack()) {\n std::cerr << \"Map::Map(SizedType) constructor should be called only with stack types\" << std::endl;\n abort()\n }\n#endif\n type_ = type;\n int key_size = 4;\n int value_size = sizeof(uintptr_t) * type.stack_type.limit;\n std::string name = \"stack\";\n int max_entries = 4096;\n int flags = 0;\n enum bpf_map_type map_type = BPF_MAP_TYPE_STACK_TRACE;\n\n mapfd_ = create_map(map_type, name.c_str(), key_size, value_size, max_entries, flags);\n if (mapfd_ < 0)\n {\n std::cerr << \"Error creating stack id map\" << std::endl;\n \/\/ TODO (mmarchini): Check perf_event_max_stack in the semantic_analyzer\n std::cerr << \"This might have happened because kernel.perf_event_max_stack\"\n << \"is smaller than \" << type.stack_type.limit\n << \". Try to tweak this value with\"\n << \"sysctl kernel.perf_event_max_stack=\" << std::endl;\n }\n}\n\nMap::Map(enum bpf_map_type map_type)\n{\n int key_size, value_size, max_entries, flags;\n\n std::string name;\n#ifdef DEBUG\n \/\/ TODO (mmarchini): replace with DCHECK\n if (map_type == BPF_MAP_TYPE_STACK_TRACE)\n {\n std::cerr << \"Use Map::Map(SizedType) constructor instead\" << std::endl;\n abort();\n }\n#endif\n if (map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY)\n {\n std::vector cpus = get_online_cpus();\n name = \"printf\";\n key_size = 4;\n value_size = 4;\n max_entries = cpus.size();\n flags = 0;\n }\n else\n {\n std::cerr << \"invalid map type\" << std::endl;\n abort();\n }\n\n mapfd_ = create_map(map_type, name.c_str(), key_size, value_size, max_entries, flags);\n if (mapfd_ < 0)\n {\n std::string name;\n switch (map_type)\n {\n case BPF_MAP_TYPE_PERF_EVENT_ARRAY:\n name = \"perf event\";\n break;\n default:\n std::cerr << \"invalid map type\" << std::endl;\n abort();\n }\n\n std::cerr << \"Error creating \" << name << \" map (\" << mapfd_ << \")\" << std::endl;\n }\n}\n\nMap::~Map()\n{\n if (mapfd_ >= 0)\n close(mapfd_);\n}\n\n} \/\/ namespace bpftrace\nAdd missing space to error message#include \n#include \n#include \n\n#include \"libbpf.h\"\n#include \"utils.h\"\n\n#include \"map.h\"\n\nnamespace bpftrace {\n\nint Map::create_map(enum bpf_map_type map_type, const char *name, int key_size, int value_size, int max_entries, int flags) {\n#ifdef HAVE_BCC_CREATE_MAP\n return bcc_create_map(map_type, name, key_size, value_size, max_entries, flags);\n#else\n return bpf_create_map(map_type, name, key_size, value_size, max_entries, flags);\n#endif\n}\n\nMap::Map(const std::string &name, const SizedType &type, const MapKey &key, int min, int max, int step)\n{\n name_ = name;\n type_ = type;\n key_ = key;\n \/\/ for lhist maps:\n lqmin = min;\n lqmax = max;\n lqstep = step;\n\n int key_size = key.size();\n if (type.type == Type::hist || type.type == Type::lhist ||\n type.type == Type::avg || type.type == Type::stats)\n key_size += 8;\n if (key_size == 0)\n key_size = 8;\n\n int max_entries = 128;\n enum bpf_map_type map_type;\n if ((type.type == Type::hist || type.type == Type::lhist || type.type == Type::count ||\n type.type == Type::sum || type.type == Type::min || type.type == Type::max ||\n type.type == Type::avg || type.type == Type::stats) &&\n (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 6, 0)))\n {\n map_type = BPF_MAP_TYPE_PERCPU_HASH;\n }\n else if (type.type == Type::join)\n {\n map_type = BPF_MAP_TYPE_PERCPU_ARRAY;\n max_entries = 1;\n key_size = 4;\n }\n else\n map_type = BPF_MAP_TYPE_HASH;\n\n int value_size = type.size;\n int flags = 0;\n mapfd_ = create_map(map_type, name.c_str(), key_size, value_size, max_entries, flags);\n if (mapfd_ < 0)\n {\n std::cerr << \"Error creating map: '\" << name_ << \"'\" << std::endl;\n }\n}\n\nMap::Map(const SizedType &type) {\n#ifdef DEBUG\n \/\/ TODO (mmarchini): replace with DCHECK\n if (!type.IsStack()) {\n std::cerr << \"Map::Map(SizedType) constructor should be called only with stack types\" << std::endl;\n abort()\n }\n#endif\n type_ = type;\n int key_size = 4;\n int value_size = sizeof(uintptr_t) * type.stack_type.limit;\n std::string name = \"stack\";\n int max_entries = 4096;\n int flags = 0;\n enum bpf_map_type map_type = BPF_MAP_TYPE_STACK_TRACE;\n\n mapfd_ = create_map(map_type, name.c_str(), key_size, value_size, max_entries, flags);\n if (mapfd_ < 0)\n {\n std::cerr << \"Error creating stack id map\" << std::endl;\n \/\/ TODO (mmarchini): Check perf_event_max_stack in the semantic_analyzer\n std::cerr << \"This might have happened because kernel.perf_event_max_stack\"\n << \"is smaller than \" << type.stack_type.limit\n << \". Try to tweak this value with \"\n << \"sysctl kernel.perf_event_max_stack=\" << std::endl;\n }\n}\n\nMap::Map(enum bpf_map_type map_type)\n{\n int key_size, value_size, max_entries, flags;\n\n std::string name;\n#ifdef DEBUG\n \/\/ TODO (mmarchini): replace with DCHECK\n if (map_type == BPF_MAP_TYPE_STACK_TRACE)\n {\n std::cerr << \"Use Map::Map(SizedType) constructor instead\" << std::endl;\n abort();\n }\n#endif\n if (map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY)\n {\n std::vector cpus = get_online_cpus();\n name = \"printf\";\n key_size = 4;\n value_size = 4;\n max_entries = cpus.size();\n flags = 0;\n }\n else\n {\n std::cerr << \"invalid map type\" << std::endl;\n abort();\n }\n\n mapfd_ = create_map(map_type, name.c_str(), key_size, value_size, max_entries, flags);\n if (mapfd_ < 0)\n {\n std::string name;\n switch (map_type)\n {\n case BPF_MAP_TYPE_PERF_EVENT_ARRAY:\n name = \"perf event\";\n break;\n default:\n std::cerr << \"invalid map type\" << std::endl;\n abort();\n }\n\n std::cerr << \"Error creating \" << name << \" map (\" << mapfd_ << \")\" << std::endl;\n }\n}\n\nMap::~Map()\n{\n if (mapfd_ >= 0)\n close(mapfd_);\n}\n\n} \/\/ namespace bpftrace\n<|endoftext|>"} {"text":"#include \n#include \"io.h\"\n#include \"matrix.impl.h\"\n#include \"worker.h\"\n#include \n\nint main(int argc, char** argv){\n int width, height;\n std::vector map;\n\n \/\/ Reads a file\n IO::readFile(width, height, map);\n\n std::shared_ptr > crossword = std::make_shared >(width, height);\n std::shared_ptr > visited = std::make_shared >(width, height);\n\n for (auto i = 0; i < width; ++i) {\n for (auto j = 0; j < height; ++j) {\n crossword->set(i, j, map.at(i).at(j));\n visited->set(i, j, false);\n }\n }\n\n\n auto start = std::chrono::high_resolution_clock::now();\n\n \/\/Worker work(\"threads\", crossword);\n Worker work1(\"threads\", crossword);\n Worker work2(\"arquivos\", crossword);\n Worker work3(\"sinais\", crossword);\n Worker work4(\"pipe\", crossword);\n Worker work5(\"processos\", crossword);\n Worker work6(\"mutex\", crossword);\n\n work1.join();\n work2.join();\n work3.join();\n work4.join();\n work5.join();\n work6.join();\n\n \n auto end = std::chrono::high_resolution_clock::now();\n auto elapsed = std::chrono::duration_cast(end - start);\n\n std::cout << \"took \" << elapsed.count() << \" microseconds.\" << std::endl;\n \n std::cout << *crossword << std::endl;\n return 0;\n}\nworking#include \n#include \"io.h\"\n#include \"matrix.impl.h\"\n#include \"worker.h\"\n#include \n\nint main(int argc, char** argv){\n int width, height;\n std::vector map;\n\n \/\/ Reads a file\n IO::readFile(width, height, map);\n\n std::shared_ptr > crossword = std::make_shared >(width, height);\n\n for (auto i = 0; i < width; ++i) {\n for (auto j = 0; j < height; ++j) {\n crossword->set(i, j, map.at(i).at(j));\n }\n }\n\n std::cout << *crossword << std::endl;\n \n unsigned int numThreads;\n\n std::vector words = {\"threads\", \"arquivos\", \"sinais\", \"pipe\", \"processos\", \"mutex\"};\n\n std::vector > workers;\n \n do {\n std::cout << \"Numero de threads (Cada thread procura uma palavra)\" << std::endl;\n std::cin >> numThreads;\n } while (!(numThreads < words.size() && numThreads > 0));\n\n auto start = std::chrono::high_resolution_clock::now();\n\n for (auto i = 0u; i <= words.size() - numThreads; i+=numThreads) {\n for (auto j = i; j < i + numThreads; ++j) {\n workers.push_back(std::make_shared(words.at(j), crossword));\n }\n\n \n for (auto& worker : workers) {\n worker->join();\n }\n\n workers.clear();\n }\n \n auto end = std::chrono::high_resolution_clock::now();\n auto elapsed = std::chrono::duration_cast(end - start);\n\n std::cout << \"took \" << elapsed.count() << \" microseconds.\" << std::endl;\n \n std::cout << *crossword << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"chip8core\/Emulator.h\"\n\n#include \"curses.h\"\n\nusing namespace std;\nusing namespace chip8curses;\n\nint constexpr KEY_ESCAPE{27};\n\nint main(int argc, char* argv[]) {\n if (argc != 2) {\n cerr << \"Usage: \" << argv[0] << \" FILENAME\\n\";\n return 1;\n }\n\n Emulator chip8core;\n if (!chip8core.loadFileToRam(argv[1])) {\n cerr << argv[0] << \": Error loading file: \" << chip8core.getError() << \"\\n\";\n return 1;\n }\n\n curses::start(Emulator::screen_rows, Emulator::screen_columns);\n curses::attach(&chip8core);\n vector keys(Emulator::num_keys);\n\n bool loop = true;\n while (loop) {\n chip8core.tick();\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n switch (curses::get_char()) {\n case KEY_ESCAPE:\n loop = false;\n break;\n\n case '1': chip8core.setKeyState(0x0, (keys.at(0x0) = !keys.at(0x0))); break;\n case '2': chip8core.setKeyState(0x1, (keys.at(0x1) = !keys.at(0x1))); break;\n case '3': chip8core.setKeyState(0x2, (keys.at(0x2) = !keys.at(0x2))); break;\n case '4': chip8core.setKeyState(0x3, (keys.at(0x3) = !keys.at(0x3))); break;\n case 'q': chip8core.setKeyState(0x4, (keys.at(0x4) = !keys.at(0x4))); break;\n case 'w': chip8core.setKeyState(0x5, (keys.at(0x5) = !keys.at(0x5))); break;\n case 'e': chip8core.setKeyState(0x6, (keys.at(0x6) = !keys.at(0x6))); break;\n case 'r': chip8core.setKeyState(0x7, (keys.at(0x7) = !keys.at(0x7))); break;\n case 'a': chip8core.setKeyState(0x8, (keys.at(0x8) = !keys.at(0x8))); break;\n case 's': chip8core.setKeyState(0x9, (keys.at(0x9) = !keys.at(0x9))); break;\n case 'd': chip8core.setKeyState(0xA, (keys.at(0xA) = !keys.at(0xA))); break;\n case 'f': chip8core.setKeyState(0xB, (keys.at(0xB) = !keys.at(0xB))); break;\n case 'z': chip8core.setKeyState(0xC, (keys.at(0xC) = !keys.at(0xC))); break;\n case 'x': chip8core.setKeyState(0xD, (keys.at(0xD) = !keys.at(0xD))); break;\n case 'c': chip8core.setKeyState(0xE, (keys.at(0xE) = !keys.at(0xE))); break;\n case 'v': chip8core.setKeyState(0xF, (keys.at(0xF) = !keys.at(0xF))); break;\n }\n\n }\n\n curses::stop();\n return 0;\n}\nFix keyboard layout#include \n#include \n#include \n#include \n\n#include \"chip8core\/Emulator.h\"\n\n#include \"curses.h\"\n\nusing namespace std;\nusing namespace chip8curses;\n\nint constexpr KEY_ESCAPE{27};\n\nint main(int argc, char* argv[]) {\n if (argc != 2) {\n cerr << \"Usage: \" << argv[0] << \" FILENAME\\n\";\n return 1;\n }\n\n Emulator chip8core;\n if (!chip8core.loadFileToRam(argv[1])) {\n cerr << argv[0] << \": Error loading file: \" << chip8core.getError() << \"\\n\";\n return 1;\n }\n\n curses::start(Emulator::screen_rows, Emulator::screen_columns);\n curses::attach(&chip8core);\n vector keys(Emulator::num_keys);\n\n bool loop = true;\n while (loop) {\n chip8core.tick();\n std::this_thread::sleep_for(std::chrono::milliseconds(10));\n\n switch (curses::get_char()) {\n case KEY_ESCAPE:\n loop = false;\n break;\n\n case 'x': chip8core.setKeyState(0x0, (keys.at(0x0) = !keys.at(0x0))); break;\n case '1': chip8core.setKeyState(0x1, (keys.at(0x1) = !keys.at(0x1))); break;\n case '2': chip8core.setKeyState(0x2, (keys.at(0x2) = !keys.at(0x2))); break;\n case '3': chip8core.setKeyState(0x3, (keys.at(0x3) = !keys.at(0x3))); break;\n case 'q': chip8core.setKeyState(0x4, (keys.at(0x4) = !keys.at(0x4))); break;\n case 'w': chip8core.setKeyState(0x5, (keys.at(0x5) = !keys.at(0x5))); break;\n case 'e': chip8core.setKeyState(0x6, (keys.at(0x6) = !keys.at(0x6))); break;\n case 'a': chip8core.setKeyState(0x7, (keys.at(0x7) = !keys.at(0x7))); break;\n case 's': chip8core.setKeyState(0x8, (keys.at(0x8) = !keys.at(0x8))); break;\n case 'd': chip8core.setKeyState(0x9, (keys.at(0x9) = !keys.at(0x9))); break;\n case 'z': chip8core.setKeyState(0xA, (keys.at(0xA) = !keys.at(0xA))); break;\n case 'c': chip8core.setKeyState(0xB, (keys.at(0xB) = !keys.at(0xB))); break;\n case '4': chip8core.setKeyState(0xC, (keys.at(0xC) = !keys.at(0xC))); break;\n case 'r': chip8core.setKeyState(0xD, (keys.at(0xD) = !keys.at(0xD))); break;\n case 'f': chip8core.setKeyState(0xE, (keys.at(0xE) = !keys.at(0xE))); break;\n case 'v': chip8core.setKeyState(0xF, (keys.at(0xF) = !keys.at(0xF))); break;\n }\n\n }\n\n curses::stop();\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Core developers\n\/\/ Copyright (c) 2017 PM-Tech\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n#include \n\nstatic const int64_t nDiffChangeTarget = 56000; \/\/ Patch effective @ block 56000\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n int nHeight = pindexLast->nHeight + 1;\n bool fNewDifficultyProtocol = (nHeight >= nDiffChangeTarget);\n\n if (fNewDifficultyProtocol || params.fPowAllowMinDifficultyBlocks) {\n return DigiShield(pindexLast, pblock, params);\n }\n else {\n\n static const int64_t\t \t BlocksTargetSpacing = 60; \/\/ 1 minute\n unsigned int TimeDaySeconds = 60 * 60 * 24;\n int64_t PastSecondsMin = TimeDaySeconds * 0.25;\n int64_t PastSecondsMax = TimeDaySeconds * 7;\n uint64_t PastBlocksMin = PastSecondsMin \/ BlocksTargetSpacing;\n uint64_t PastBlocksMax = PastSecondsMax \/ BlocksTargetSpacing;\n return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax, params);\n }\n}\n\nunsigned int DigiShield(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();\n\n \/\/ Genesis block\n if (pindexLast == NULL)\n return nProofOfWorkLimit;\n\n \/\/ Only change once per interval\n if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)\n {\n if (params.fPowAllowMinDifficultyBlocks)\n {\n \/\/ Special difficulty rule for testnet:\n \/\/ If the new block's timestamp is more than 2* 10 minutes\n \/\/ then allow mining of a min-difficulty block.\n if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n return nProofOfWorkLimit;\n else\n {\n \/\/ Return the last non-special-min-difficulty-rules-block\n const CBlockIndex* pindex = pindexLast;\n while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)\n pindex = pindex->pprev;\n return pindex->nBits;\n }\n }\n return pindexLast->nBits;\n }\n\n \/\/ Litecoin: This fixes an issue where a 51% attack can change difficulty at will.\n \/\/ Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz\n int blockstogoback = params.DifficultyAdjustmentInterval()-1;\n if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())\n blockstogoback = params.DifficultyAdjustmentInterval();\n\n \/\/ Go back by what we want to be 14 days worth of blocks\n const CBlockIndex* pindexFirst = pindexLast;\n for (int i = 0; pindexFirst && i < blockstogoback; i++)\n pindexFirst = pindexFirst->pprev;\n assert(pindexFirst);\n\n return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);\n}\n\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n if (params.fPowNoRetargeting)\n return pindexLast->nBits;\n\n \/\/ Limit adjustment step\n int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;\n\n arith_uint256 bnNew;\n bnNew.SetCompact(pindexLast->nBits);\n\n\/\/DigiShield implementation - thanks to RealSolid & WDC for this code\n\/\/amplitude filter - thanks to daft27 for this code\n nActualTimespan = params.nPowTargetTimespan + (nActualTimespan - params.nPowTargetTimespan)\/8;\n if (nActualTimespan < (params.nPowTargetTimespan - (params.nPowTargetTimespan\/4)) ) nActualTimespan = (params.nPowTargetTimespan - (params.nPowTargetTimespan\/4));\n if (nActualTimespan > (params.nPowTargetTimespan + (params.nPowTargetTimespan\/2)) ) nActualTimespan = (params.nPowTargetTimespan + (params.nPowTargetTimespan\/2));\n \/\/ Retarget\n\n bnNew *= nActualTimespan;\n bnNew \/= params.nPowTargetTimespan;\n\n const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n if (bnNew > bnPowLimit)\n bnNew = bnPowLimit;\n\n \/\/\/ debug print\n \/\/ LogPrintf(\"GetNextWorkRequired: DIGISHIELD RETARGET\\n\");\n return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n bool fNegative;\n bool fOverflow;\n arith_uint256 bnTarget;\n\n bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n \/\/ Check range\n if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n return false;\n\n \/\/ Check proof of work matches claimed amount\n if (UintToArith256(hash) > bnTarget)\n return false;\n\n return true;\n}\n\nunsigned int KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax, const Consensus::Params& params)\n{\n \/* current difficulty formula - kimoto gravity well *\/\n const CBlockIndex *BlockLastSolved = pindexLast;\n const CBlockIndex *BlockReading = pindexLast;\n\n uint64_t PastBlocksMass = 0;\n int64_t PastRateActualSeconds = 0;\n int64_t PastRateTargetSeconds = 0;\n double PastRateAdjustmentRatio = double(1);\n arith_uint256 PastDifficultyAverage;\n arith_uint256 PastDifficultyAveragePrev;\n double EventHorizonDeviation;\n double EventHorizonDeviationFast;\n double EventHorizonDeviationSlow;\n const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n\n if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnPowLimit.GetCompact(); }\n\n for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n PastBlocksMass++;\n\n if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }\n else \/\/Einsteinium: workaround were to overcome the overflow issue when changing from CBigNum to arith_uint256\n if (arith_uint256().SetCompact(BlockReading->nBits) >= PastDifficultyAveragePrev)\n PastDifficultyAverage = ((arith_uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) \/ i) + PastDifficultyAveragePrev;\n else\n PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - arith_uint256().SetCompact(BlockReading->nBits)) \/ i);\n\n PastDifficultyAveragePrev = PastDifficultyAverage;\n\n PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();\n PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;\n PastRateAdjustmentRatio = double(1);\n if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }\n if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n PastRateAdjustmentRatio = double(PastRateTargetSeconds) \/ double(PastRateActualSeconds);\n }\n EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)\/double(144)), -1.228));\n EventHorizonDeviationFast = EventHorizonDeviation;\n EventHorizonDeviationSlow = 1 \/ EventHorizonDeviation;\n\n if (PastBlocksMass >= PastBlocksMin) {\n if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }\n }\n if (BlockReading->pprev == NULL) { assert(BlockReading); break; }\n BlockReading = BlockReading->pprev;\n }\n\n arith_uint256 bnNew(PastDifficultyAverage);\n\n if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n \/\/ LogPrintf(\"Difficulty Retarget - Kimoto Gravity Well\\n\");\n bnNew *= PastRateActualSeconds;\n bnNew \/= PastRateTargetSeconds;\n }\n if (bnNew > bnPowLimit)\n bnNew = bnPowLimit;\n\n\/* debug print (commented out due to spamming logs when the loop above breaks)\n printf(\"Difficulty Retarget - Kimoto Gravity Well\\n\");\n printf(\"PastRateAdjustmentRatio = %g\\n\", PastRateAdjustmentRatio);\n printf(\"Before: %08x %s\\n\", BlockLastSolved->nBits, arith_uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());\n printf(\"After: %08x %s\\n\", bnNew.GetCompact(), bnNew.ToString().c_str());\n*\/\n\n return bnNew.GetCompact();\n}\n\nAdd intermediate overflow prevention\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Core developers\n\/\/ Copyright (c) 2017 PM-Tech\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n#include \n\nstatic const int64_t nDiffChangeTarget = 56000; \/\/ Patch effective @ block 56000\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n int nHeight = pindexLast->nHeight + 1;\n bool fNewDifficultyProtocol = (nHeight >= nDiffChangeTarget);\n\n if (fNewDifficultyProtocol || params.fPowAllowMinDifficultyBlocks) {\n return DigiShield(pindexLast, pblock, params);\n }\n else {\n\n static const int64_t\t \t BlocksTargetSpacing = 60; \/\/ 1 minute\n unsigned int TimeDaySeconds = 60 * 60 * 24;\n int64_t PastSecondsMin = TimeDaySeconds * 0.25;\n int64_t PastSecondsMax = TimeDaySeconds * 7;\n uint64_t PastBlocksMin = PastSecondsMin \/ BlocksTargetSpacing;\n uint64_t PastBlocksMax = PastSecondsMax \/ BlocksTargetSpacing;\n return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax, params);\n }\n}\n\nunsigned int DigiShield(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();\n\n \/\/ Genesis block\n if (pindexLast == NULL)\n return nProofOfWorkLimit;\n\n \/\/ Only change once per interval\n if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)\n {\n if (params.fPowAllowMinDifficultyBlocks)\n {\n \/\/ Special difficulty rule for testnet:\n \/\/ If the new block's timestamp is more than 2* 10 minutes\n \/\/ then allow mining of a min-difficulty block.\n if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n return nProofOfWorkLimit;\n else\n {\n \/\/ Return the last non-special-min-difficulty-rules-block\n const CBlockIndex* pindex = pindexLast;\n while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)\n pindex = pindex->pprev;\n return pindex->nBits;\n }\n }\n return pindexLast->nBits;\n }\n\n \/\/ Litecoin: This fixes an issue where a 51% attack can change difficulty at will.\n \/\/ Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz\n int blockstogoback = params.DifficultyAdjustmentInterval()-1;\n if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())\n blockstogoback = params.DifficultyAdjustmentInterval();\n\n \/\/ Go back by what we want to be 14 days worth of blocks\n const CBlockIndex* pindexFirst = pindexLast;\n for (int i = 0; pindexFirst && i < blockstogoback; i++)\n pindexFirst = pindexFirst->pprev;\n assert(pindexFirst);\n\n return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);\n}\n\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n if (params.fPowNoRetargeting)\n return pindexLast->nBits;\n\n \/\/ Limit adjustment step\n int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;\n\n arith_uint256 bnNew;\n bnNew.SetCompact(pindexLast->nBits);\n\n\/\/DigiShield implementation - thanks to RealSolid & WDC for this code\n\/\/amplitude filter - thanks to daft27 for this code\n nActualTimespan = params.nPowTargetTimespan + (nActualTimespan - params.nPowTargetTimespan)\/8;\n if (nActualTimespan < (params.nPowTargetTimespan - (params.nPowTargetTimespan\/4)) ) nActualTimespan = (params.nPowTargetTimespan - (params.nPowTargetTimespan\/4));\n if (nActualTimespan > (params.nPowTargetTimespan + (params.nPowTargetTimespan\/2)) ) nActualTimespan = (params.nPowTargetTimespan + (params.nPowTargetTimespan\/2));\n \/\/ Retarget\n\n \/\/ Litecoin: intermediate uint256 can overflow by 1 bit\n const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n bool fShift = bnNew.bits() > bnPowLimit.bits() - 1;\n if (fShift)\n bnNew >>= 1;\n bnNew *= nActualTimespan;\n bnNew \/= params.nPowTargetTimespan;\n if (fShift)\n bnNew <<= 1;\n\n if (bnNew > bnPowLimit)\n bnNew = bnPowLimit;\n\n \/\/\/ debug print\n \/\/ LogPrintf(\"GetNextWorkRequired: DIGISHIELD RETARGET\\n\");\n return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n bool fNegative;\n bool fOverflow;\n arith_uint256 bnTarget;\n\n bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n \/\/ Check range\n if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n return false;\n\n \/\/ Check proof of work matches claimed amount\n if (UintToArith256(hash) > bnTarget)\n return false;\n\n return true;\n}\n\nunsigned int KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax, const Consensus::Params& params)\n{\n \/* current difficulty formula - kimoto gravity well *\/\n const CBlockIndex *BlockLastSolved = pindexLast;\n const CBlockIndex *BlockReading = pindexLast;\n\n uint64_t PastBlocksMass = 0;\n int64_t PastRateActualSeconds = 0;\n int64_t PastRateTargetSeconds = 0;\n double PastRateAdjustmentRatio = double(1);\n arith_uint256 PastDifficultyAverage;\n arith_uint256 PastDifficultyAveragePrev;\n double EventHorizonDeviation;\n double EventHorizonDeviationFast;\n double EventHorizonDeviationSlow;\n const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n\n if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnPowLimit.GetCompact(); }\n\n for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n PastBlocksMass++;\n\n if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }\n else \/\/Einsteinium: workaround were to overcome the overflow issue when changing from CBigNum to arith_uint256\n if (arith_uint256().SetCompact(BlockReading->nBits) >= PastDifficultyAveragePrev)\n PastDifficultyAverage = ((arith_uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) \/ i) + PastDifficultyAveragePrev;\n else\n PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - arith_uint256().SetCompact(BlockReading->nBits)) \/ i);\n\n PastDifficultyAveragePrev = PastDifficultyAverage;\n\n PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();\n PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;\n PastRateAdjustmentRatio = double(1);\n if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }\n if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n PastRateAdjustmentRatio = double(PastRateTargetSeconds) \/ double(PastRateActualSeconds);\n }\n EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)\/double(144)), -1.228));\n EventHorizonDeviationFast = EventHorizonDeviation;\n EventHorizonDeviationSlow = 1 \/ EventHorizonDeviation;\n\n if (PastBlocksMass >= PastBlocksMin) {\n if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }\n }\n if (BlockReading->pprev == NULL) { assert(BlockReading); break; }\n BlockReading = BlockReading->pprev;\n }\n\n arith_uint256 bnNew(PastDifficultyAverage);\n\n if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n \/\/ LogPrintf(\"Difficulty Retarget - Kimoto Gravity Well\\n\");\n bnNew *= PastRateActualSeconds;\n bnNew \/= PastRateTargetSeconds;\n }\n if (bnNew > bnPowLimit)\n bnNew = bnPowLimit;\n\n\/* debug print (commented out due to spamming logs when the loop above breaks)\n printf(\"Difficulty Retarget - Kimoto Gravity Well\\n\");\n printf(\"PastRateAdjustmentRatio = %g\\n\", PastRateAdjustmentRatio);\n printf(\"Before: %08x %s\\n\", BlockLastSolved->nBits, arith_uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());\n printf(\"After: %08x %s\\n\", bnNew.GetCompact(), bnNew.ToString().c_str());\n*\/\n\n return bnNew.GetCompact();\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"tbb\/parallel_sort.h\"\n#include \"tbb\/mutex.h\"\n#include \"tbb\/pipeline.h\"\n\n#define VALUE(x) std::cout << #x \"=\" << x << std::endl\n\nnamespace psh\n{\n\tusing uint = long unsigned int;\n\n\ttemplate\n\tclass map\n\t{\n\t\tstatic_assert(d > 0, \"d must be larger than 0.\");\n\tpublic:\n\t\tusing point = Eigen::Matrix;\n\t\tusing opt_T = std::experimental::optional;\n\n\t\tstruct data_t\n\t\t{\n\t\t\tpoint location;\n\t\t\tT contents;\n\t\t};\n\n\t\tstruct bucket : public std::vector\n\t\t{\n\t\t\tuint phi_index;\n\n\t\t\tbucket(uint phi_index) : phi_index(phi_index) { }\n\t\t\tfriend bool operator<(const bucket& lhs, const bucket& rhs) {\n\t\t\t\treturn lhs.size() > rhs.size();\n\t\t\t}\n\t\t};\n\n\t\tuint M0;\n\t\tuint M1;\n\t\tuint n;\n\t\tuint m_bar;\n\t\tuint m;\n\t\tuint r_bar;\n\t\tuint r;\n\t\tstd::vector phi;\n\t\tstd::vector H;\n\t\tstd::default_random_engine generator;\n\n\t\tmap(const std::vector& data)\n\t\t\t: n(data.size()), m_bar(std::ceil(std::pow(n, 1.0f \/ d))), m(std::pow(m_bar, d)),\n\t\t\t r_bar(std::ceil(std::pow(n \/ d, 1.0f \/ d)) - 1), generator(time(0))\n\t\t{\n\t\t\tM0 = prime();\n\t\t\twhile ((M1 = prime()) == M0);\n\n\t\t\tVALUE(m);\n\t\t\tVALUE(m_bar);\n\n\t\t\tbool create_succeeded = false;\n\n\t\t\tstd::uniform_int_distribution m_dist(0, m - 1);\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tr_bar += d;\n\t\t\t\tr = std::pow(r_bar, d);\n\t\t\t\tVALUE(r);\n\t\t\t\tVALUE(r_bar);\n\n\t\t\t\tcreate_succeeded = create(data, m_dist);\n\n\t\t\t} while (!create_succeeded);\n\t\t}\n\n\t\tuint prime()\n\t\t{\n\t\t\tstatic const std::vector primes{ 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289,\n\t\t\t\t24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469 };\n\t\t\tstatic std::uniform_int_distribution prime_dist(0, primes.size() - 1);\n\n\t\t\treturn primes[prime_dist(generator)];\n\t\t}\n\n\t\tbool bad_m_r()\n\t\t{\n\t\t\tauto m_mod_r = m_bar % r_bar;\n\t\t\treturn m_mod_r == 1 || m_mod_r == r - 1;\n\t\t}\n\n\t\tvoid insert(const bucket& b, decltype(H)& H_hat, const decltype(phi)& phi_hat)\n\t\t{\n\t\t\tfor (auto& element : b)\n\t\t\t{\n\t\t\t\tauto hashed = h(element.location, phi_hat);\n\t\t\t\tH_hat[point_to_index(hashed, m_bar, m)] = element.contents;\n\t\t\t}\n\t\t}\n\n\t\tbool jiggle_offsets(decltype(H)& H_hat, decltype(phi)& phi_hat,\n\t\t\tconst bucket& b, std::uniform_int_distribution& m_dist)\n\t\t{\n\t\t\tuint start_offset = m_dist(generator);\n\n\t\t\tbool found = false;\n\t\t\tpoint found_offset;\n\t\t\ttbb::mutex mutex;\n\n\t\t\tuint chunk_index = 0;\n\t\t\tconst uint num_cores = 8;\n\t\t\tconst uint group_size = r \/ num_cores + 1;\n\n\t\t\ttbb::parallel_pipeline(num_cores,\n\t\t\t\ttbb::make_filter(tbb::filter::serial,\n\t\t\t\t\t[=, &chunk_index, &found, &group_size](tbb::flow_control& fc) {\n\t\t\t\t\t\tif (found || chunk_index >= r)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfc.stop();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchunk_index += group_size;\n\t\t\t\t\t\treturn chunk_index;\n\t\t\t\t\t}) &\n\t\t\t\ttbb::make_filter(tbb::filter::parallel,\n\t\t\t\t\t[=, &mutex, &found, &found_offset, &b, &phi_hat, &H_hat](uint i0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (uint i = i0; i < i0 + group_size && !found; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto phi_offset = index_to_point((start_offset + i) % m, m_bar, m);\n\n\t\t\t\t\t\t\tbool collision = false;\n\t\t\t\t\t\t\tfor (auto& element : b)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto h0 = M0 * element.location;\n\t\t\t\t\t\t\t\tauto h1 = M1 * element.location;\n\t\t\t\t\t\t\t\tauto index = point_to_index(h1, r_bar, r);\n\t\t\t\t\t\t\t\tauto offset = index == b.phi_index ? phi_offset : phi_hat[index];\n\t\t\t\t\t\t\t\tauto hash = h0 + offset;\n\n\t\t\t\t\t\t\t\tcollision = bool(H_hat[point_to_index(hash, m_bar, m)]);\n\t\t\t\t\t\t\t\tif (collision)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (!collision)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttbb::mutex::scoped_lock lock(mutex);\n\t\t\t\t\t\t\t\tif (!found)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\tfound_offset = phi_offset;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\tif (found)\n\t\t\t{\n\t\t\t\tphi_hat[b.phi_index] = found_offset;\n\t\t\t\tinsert(b, H_hat, phi_hat);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector create_buckets(const std::vector& data)\n\t\t{\n\t\t\tstd::vector buckets;\n\t\t\tbuckets.reserve(r);\n\t\t\t{\n\t\t\t\tuint i = 0;\n\t\t\t\tstd::generate_n(std::back_inserter(buckets), r, [&] {\n\t\t\t\t\t\treturn bucket(i++);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\tfor (auto& element : data)\n\t\t\t{\n\t\t\t\tauto h1 = M1 * element.location;\n\t\t\t\tbuckets[point_to_index(h1, r_bar, r)].push_back(element);\n\t\t\t}\n\n\t\t\tstd::cout << \"buckets created\" << std::endl;\n\n\t\t\ttbb::parallel_sort(buckets.begin(), buckets.end());\n\t\t\tstd::cout << \"buckets sorted\" << std::endl;\n\n\t\t\treturn buckets;\n\t\t}\n\n\t\tbool create(const std::vector& data, std::uniform_int_distribution& m_dist)\n\t\t{\n\t\t\tdecltype(phi) phi_hat;\n\t\t\tphi_hat.reserve(r);\n\t\t\tdecltype(H) H_hat(m);\n\t\t\tstd::cout << \"creating \" << r << \" buckets\" << std::endl;\n\n\t\t\tif (bad_m_r())\n\t\t\t\treturn false;\n\n\t\t\tauto buckets = create_buckets(data);\n\t\t\tstd::cout << \"jiggling offsets\" << std::endl;\n\n\t\t\tfor (uint i = 0; i < buckets.size(); i++)\n\t\t\t{\n\t\t\t\tif (buckets[i].size() == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tif (i % (buckets.size() \/ 10) == 0)\n\t\t\t\t\tstd::cout << (100 * i) \/ buckets.size() << \"% done\" << std::endl;\n\n\t\t\t\tif (!jiggle_offsets(H_hat, phi_hat, buckets[i], m_dist))\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"done!\" << std::endl;\n\t\t\tphi = std::move(phi_hat);\n\t\t\tH = std::move(H_hat);\n\t\t\treturn true;\n\t\t}\n\n\t\tconstexpr uint point_to_index(const point& p, uint width, uint max) const\n\t\t{\n\t\t\tuint index = p[0];\n\t\t\tfor (uint i = 1; i < d; i++)\n\t\t\t{\n\t\t\t\tindex += uint(std::pow(width, i)) * p[i];\n\t\t\t}\n\t\t\treturn index % max;\n\t\t}\n\n\t\tconstexpr point index_to_point(uint index, uint width, uint max) const\n\t\t{\n\t\t\tpoint output;\n\t\t\tmax \/= width;\n\t\t\tfor (uint i = 0; i < d; i++)\n\t\t\t{\n\t\t\t\toutput[i] = index \/ max;\n\t\t\t\tindex = index % max;\n\n\t\t\t\tif (i + 1 < d)\n\t\t\t\t{\n\t\t\t\t\tmax \/= width;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn output;\n\t\t}\n\n\t\tpoint h(const point& p, const decltype(phi)& phi_hat) const\n\t\t{\n\t\t\tauto h0 = M0 * p;\n\t\t\tauto h1 = M1 * p;\n\t\t\tauto offset = phi_hat[point_to_index(h1, r_bar, r)];\n\t\t\treturn h0 + offset;\n\t\t}\n\n\t\tpoint h(const point& p) const\n\t\t{\n\t\t\treturn h(p, phi);\n\t\t}\n\n\t\tT get(const point& p) const\n\t\t{\n\t\t\tauto maybe_element = H[point_to_index(h(p), m_bar, m)];\n\t\t\tif (maybe_element)\n\t\t\t\treturn maybe_element.value();\n\t\t\telse\n\t\t\t\tthrow std::out_of_range(\"Element not found in map\");\n\t\t}\n\n\t\tbool contains(const data_t& data, const decltype(H)& H_hat, const decltype(phi)& phi_hat) const\n\t\t{\n\t\t\tauto found = H_hat[point_to_index(h(data.location, phi_hat), m_bar, m)];\n\t\t\treturn bool(found) && found == data.contents;\n\t\t}\n\n\t\tbool contains(const data_t& data) const\n\t\t{\n\t\t\treturn contains(data, H, phi);\n\t\t}\n\n\t\tbool contains(const point& p, const decltype(H)& H_hat, const decltype(phi)& phi_hat) const\n\t\t{\n\t\t\treturn bool(H_hat[point_to_index(h(p, phi_hat), m_bar, m)]);\n\t\t}\n\n\t\tbool contains(const point& p) const\n\t\t{\n\t\t\treturn contains(p, H, phi);\n\t\t}\n\n\t\tbool contains(uint index, const data_t& data, const decltype(H)& H_hat) const\n\t\t{\n\t\t\tauto found = H_hat[index];\n\t\t\treturn bool(found) && found == data.contents;\n\t\t}\n\n\t\tbool contains(uint index, const data_t& data) const\n\t\t{\n\t\t\treturn contains(index, data, H);\n\t\t}\n\n\t\tbool contains(uint index, const decltype(H)& H_hat) const\n\t\t{\n\t\t\treturn bool(H_hat[index]);\n\t\t}\n\n\t\tbool contains(uint index) const\n\t\t{\n\t\t\treturn contains(index, H);\n\t\t}\n\n\t\tuint memory_size()\n\t\t{\n\t\t\treturn sizeof(*this) + sizeof(typename decltype(phi)::value_type) * phi.size()\n\t\t\t\t+ sizeof(typename decltype(H)::value_type) * H.size();\n\t\t}\n\t};\n}specialized index and point conversions for 2 and 3 dimensions#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"tbb\/parallel_sort.h\"\n#include \"tbb\/mutex.h\"\n#include \"tbb\/pipeline.h\"\n\n#define VALUE(x) std::cout << #x \"=\" << x << std::endl\n\nnamespace psh\n{\n\tusing uint = long unsigned int;\n\n\ttemplate\n\tclass map\n\t{\n\t\tstatic_assert(d > 0, \"d must be larger than 0.\");\n\tpublic:\n\t\tusing point = Eigen::Matrix;\n\t\tusing opt_T = std::experimental::optional;\n\n\t\tstruct data_t\n\t\t{\n\t\t\tpoint location;\n\t\t\tT contents;\n\t\t};\n\n\t\tstruct bucket : public std::vector\n\t\t{\n\t\t\tuint phi_index;\n\n\t\t\tbucket(uint phi_index) : phi_index(phi_index) { }\n\t\t\tfriend bool operator<(const bucket& lhs, const bucket& rhs) {\n\t\t\t\treturn lhs.size() > rhs.size();\n\t\t\t}\n\t\t};\n\n\t\tuint M0;\n\t\tuint M1;\n\t\tuint n;\n\t\tuint m_bar;\n\t\tuint m;\n\t\tuint r_bar;\n\t\tuint r;\n\t\tstd::vector phi;\n\t\tstd::vector H;\n\t\tstd::default_random_engine generator;\n\n\t\tmap(const std::vector& data)\n\t\t\t: n(data.size()), m_bar(std::ceil(std::pow(n, 1.0f \/ d))), m(std::pow(m_bar, d)),\n\t\t\t r_bar(std::ceil(std::pow(n \/ d, 1.0f \/ d)) - 1), generator(time(0))\n\t\t{\n\t\t\tM0 = prime();\n\t\t\twhile ((M1 = prime()) == M0);\n\n\t\t\tVALUE(m);\n\t\t\tVALUE(m_bar);\n\n\t\t\tbool create_succeeded = false;\n\n\t\t\tstd::uniform_int_distribution m_dist(0, m - 1);\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tr_bar += d;\n\t\t\t\tr = std::pow(r_bar, d);\n\t\t\t\tVALUE(r);\n\t\t\t\tVALUE(r_bar);\n\n\t\t\t\tcreate_succeeded = create(data, m_dist);\n\n\t\t\t} while (!create_succeeded);\n\t\t}\n\n\t\tuint prime()\n\t\t{\n\t\t\tstatic const std::vector primes{ 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289,\n\t\t\t\t24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469 };\n\t\t\tstatic std::uniform_int_distribution prime_dist(0, primes.size() - 1);\n\n\t\t\treturn primes[prime_dist(generator)];\n\t\t}\n\n\t\tbool bad_m_r()\n\t\t{\n\t\t\tauto m_mod_r = m_bar % r_bar;\n\t\t\treturn m_mod_r == 1 || m_mod_r == r - 1;\n\t\t}\n\n\t\tvoid insert(const bucket& b, decltype(H)& H_hat, const decltype(phi)& phi_hat)\n\t\t{\n\t\t\tfor (auto& element : b)\n\t\t\t{\n\t\t\t\tauto hashed = h(element.location, phi_hat);\n\t\t\t\tH_hat[point_to_index(hashed, m_bar, m)] = element.contents;\n\t\t\t}\n\t\t}\n\n\t\tbool jiggle_offsets(decltype(H)& H_hat, decltype(phi)& phi_hat,\n\t\t\tconst bucket& b, std::uniform_int_distribution& m_dist)\n\t\t{\n\t\t\tuint start_offset = m_dist(generator);\n\n\t\t\tbool found = false;\n\t\t\tpoint found_offset;\n\t\t\ttbb::mutex mutex;\n\n\t\t\tuint chunk_index = 0;\n\t\t\tconst uint num_cores = 8;\n\t\t\tconst uint group_size = r \/ num_cores + 1;\n\n\t\t\ttbb::parallel_pipeline(num_cores,\n\t\t\t\ttbb::make_filter(tbb::filter::serial,\n\t\t\t\t\t[=, &chunk_index, &found, &group_size](tbb::flow_control& fc) {\n\t\t\t\t\t\tif (found || chunk_index >= r)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfc.stop();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchunk_index += group_size;\n\t\t\t\t\t\treturn chunk_index;\n\t\t\t\t\t}) &\n\t\t\t\ttbb::make_filter(tbb::filter::parallel,\n\t\t\t\t\t[=, &mutex, &found, &found_offset, &b, &phi_hat, &H_hat](uint i0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (uint i = i0; i < i0 + group_size && !found; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto phi_offset = index_to_point((start_offset + i) % m, m_bar, m);\n\n\t\t\t\t\t\t\tbool collision = false;\n\t\t\t\t\t\t\tfor (auto& element : b)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto h0 = M0 * element.location;\n\t\t\t\t\t\t\t\tauto h1 = M1 * element.location;\n\t\t\t\t\t\t\t\tauto index = point_to_index(h1, r_bar, r);\n\t\t\t\t\t\t\t\tauto offset = index == b.phi_index ? phi_offset : phi_hat[index];\n\t\t\t\t\t\t\t\tauto hash = h0 + offset;\n\n\t\t\t\t\t\t\t\tcollision = bool(H_hat[point_to_index(hash, m_bar, m)]);\n\t\t\t\t\t\t\t\tif (collision)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (!collision)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttbb::mutex::scoped_lock lock(mutex);\n\t\t\t\t\t\t\t\tif (!found)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\tfound_offset = phi_offset;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\tif (found)\n\t\t\t{\n\t\t\t\tphi_hat[b.phi_index] = found_offset;\n\t\t\t\tinsert(b, H_hat, phi_hat);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector create_buckets(const std::vector& data)\n\t\t{\n\t\t\tstd::vector buckets;\n\t\t\tbuckets.reserve(r);\n\t\t\t{\n\t\t\t\tuint i = 0;\n\t\t\t\tstd::generate_n(std::back_inserter(buckets), r, [&] {\n\t\t\t\t\t\treturn bucket(i++);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\tfor (auto& element : data)\n\t\t\t{\n\t\t\t\tauto h1 = M1 * element.location;\n\t\t\t\tbuckets[point_to_index(h1, r_bar, r)].push_back(element);\n\t\t\t}\n\n\t\t\tstd::cout << \"buckets created\" << std::endl;\n\n\t\t\ttbb::parallel_sort(buckets.begin(), buckets.end());\n\t\t\tstd::cout << \"buckets sorted\" << std::endl;\n\n\t\t\treturn buckets;\n\t\t}\n\n\t\tbool create(const std::vector& data, std::uniform_int_distribution& m_dist)\n\t\t{\n\t\t\tdecltype(phi) phi_hat;\n\t\t\tphi_hat.reserve(r);\n\t\t\tdecltype(H) H_hat(m);\n\t\t\tstd::cout << \"creating \" << r << \" buckets\" << std::endl;\n\n\t\t\tif (bad_m_r())\n\t\t\t\treturn false;\n\n\t\t\tauto buckets = create_buckets(data);\n\t\t\tstd::cout << \"jiggling offsets\" << std::endl;\n\n\t\t\tfor (uint i = 0; i < buckets.size(); i++)\n\t\t\t{\n\t\t\t\tif (buckets[i].size() == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tif (i % (buckets.size() \/ 10) == 0)\n\t\t\t\t\tstd::cout << (100 * i) \/ buckets.size() << \"% done\" << std::endl;\n\n\t\t\t\tif (!jiggle_offsets(H_hat, phi_hat, buckets[i], m_dist))\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"done!\" << std::endl;\n\t\t\tphi = std::move(phi_hat);\n\t\t\tH = std::move(H_hat);\n\t\t\treturn true;\n\t\t}\n\n\t\tconstexpr uint point_to_index(const point& p, uint width, uint max) const\n\t\t{\n\t\t\tif (d == 2)\n\t\t\t{\n\t\t\t\treturn (p[0] + width * p[1]) % max;\n\t\t\t}\n\t\t\telse if (d == 3)\n\t\t\t{\n\t\t\t\treturn (p[0] + width * p[1] + width * width * p[2]) % max;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint index = p[0];\n\t\t\t\tfor (uint i = 1; i < d; i++)\n\t\t\t\t{\n\t\t\t\t\tindex += uint(std::pow(width, i)) * p[i];\n\t\t\t\t}\n\t\t\t\treturn index % max;\n\t\t\t}\n\t\t}\n\n\t\tconstexpr point index_to_point(uint index, uint width, uint max) const\n\t\t{\n\t\t\tpoint output;\n\t\t\tif (d == 2)\n\t\t\t{\n\t\t\t\toutput << index \/ width, index % width;\n\t\t\t}\n\t\t\telse if (d == 3)\n\t\t\t{\n\t\t\t\toutput <<\n\t\t\t\t\tindex \/ (width * width),\n\t\t\t\t\t(index % (width * width)) \/ width,\n\t\t\t\t\t(index % (width * width)) % width;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmax \/= width;\n\t\t\t\tfor (uint i = 0; i < d; i++)\n\t\t\t\t{\n\t\t\t\t\toutput[i] = index \/ max;\n\t\t\t\t\tindex = index % max;\n\n\t\t\t\t\tif (i + 1 < d)\n\t\t\t\t\t{\n\t\t\t\t\t\tmax \/= width;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn output;\n\t\t}\n\n\t\tpoint h(const point& p, const decltype(phi)& phi_hat) const\n\t\t{\n\t\t\tauto h0 = M0 * p;\n\t\t\tauto h1 = M1 * p;\n\t\t\tauto offset = phi_hat[point_to_index(h1, r_bar, r)];\n\t\t\treturn h0 + offset;\n\t\t}\n\n\t\tpoint h(const point& p) const\n\t\t{\n\t\t\treturn h(p, phi);\n\t\t}\n\n\t\tT get(const point& p) const\n\t\t{\n\t\t\tauto maybe_element = H[point_to_index(h(p), m_bar, m)];\n\t\t\tif (maybe_element)\n\t\t\t\treturn maybe_element.value();\n\t\t\telse\n\t\t\t\tthrow std::out_of_range(\"Element not found in map\");\n\t\t}\n\n\t\tbool contains(const data_t& data, const decltype(H)& H_hat, const decltype(phi)& phi_hat) const\n\t\t{\n\t\t\tauto found = H_hat[point_to_index(h(data.location, phi_hat), m_bar, m)];\n\t\t\treturn bool(found) && found == data.contents;\n\t\t}\n\n\t\tbool contains(const data_t& data) const\n\t\t{\n\t\t\treturn contains(data, H, phi);\n\t\t}\n\n\t\tbool contains(const point& p, const decltype(H)& H_hat, const decltype(phi)& phi_hat) const\n\t\t{\n\t\t\treturn bool(H_hat[point_to_index(h(p, phi_hat), m_bar, m)]);\n\t\t}\n\n\t\tbool contains(const point& p) const\n\t\t{\n\t\t\treturn contains(p, H, phi);\n\t\t}\n\n\t\tbool contains(uint index, const data_t& data, const decltype(H)& H_hat) const\n\t\t{\n\t\t\tauto found = H_hat[index];\n\t\t\treturn bool(found) && found == data.contents;\n\t\t}\n\n\t\tbool contains(uint index, const data_t& data) const\n\t\t{\n\t\t\treturn contains(index, data, H);\n\t\t}\n\n\t\tbool contains(uint index, const decltype(H)& H_hat) const\n\t\t{\n\t\t\treturn bool(H_hat[index]);\n\t\t}\n\n\t\tbool contains(uint index) const\n\t\t{\n\t\t\treturn contains(index, H);\n\t\t}\n\n\t\tuint memory_size()\n\t\t{\n\t\t\treturn sizeof(*this) + sizeof(typename decltype(phi)::value_type) * phi.size()\n\t\t\t\t+ sizeof(typename decltype(H)::value_type) * H.size();\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"#include \"Prefetch.h\"\n\n\n#define CHECK_CASS(msg) if(rc != CASS_OK){ \\\nstd::cerr<> *token_ranges, uint32_t buff_size,\n TupleRowFactory *tuple_factory, CassSession *session, std::string query) {\n this->session = session;\n this->t_factory = tuple_factory;\n this->tokens = token_ranges;\n CassFuture *future = cass_session_prepare(session, query.c_str());\n CassError rc = cass_future_error_code(future);\n CHECK_CASS(\"prefetch cannot prepare\");\n this->prepared_query = cass_future_get_prepared(future);\n cass_future_free(future);\n this->data.set_capacity(buff_size);\n this->worker = new std::thread{&Prefetch::consume_tokens, this};\n\n}\n\nPyObject* Prefetch::get_next(){\n if(completed){\n PyErr_SetNone(PyExc_StopIteration);\n return NULL;\n }\n TupleRow *response = NULL;\n data.pop(response);\n if (!response) {\n completed = true;\n PyErr_SetNone(PyExc_StopIteration);\n return NULL;\n }\n PyObject* toberet= t_factory->tuple_as_py(response);\n delete(response);\n return toberet;\n}\n\nvoid Prefetch::consume_tokens() {\n for (std::pair range : *tokens) {\n CassStatement *statement = cass_prepared_bind(this->prepared_query);\n cass_statement_bind_int64(statement, 0, range.first);\n cass_statement_bind_int64(statement, 1, range.second);\n\n CassFuture *future = cass_session_execute(session, statement);\n cass_statement_free(statement);\n const CassResult *result = NULL;\n int tries = 0;\n while (result == NULL && tries < 10) {\n result = cass_future_get_result(future);\n cass_future_free(future);\n if (result == NULL) {\n CassError rc = cass_future_error_code(future);\n std::cout << cass_error_desc(rc) << std::endl;\n tries++;\n\n } else {\n CassIterator *iterator = cass_iterator_from_result(result);\n\n while (cass_iterator_next(iterator)) {\n const CassRow *row = cass_iterator_get_row(iterator);\n TupleRow *t = t_factory->make_tuple(row);\n try {\n data.push(t); \/\/blocking operation\n }\n catch (tbb::user_abort &e) {\n delete(t);\n cass_iterator_free(iterator);\n cass_result_free(result);\n return;\n\n }\n }\n cass_iterator_free(iterator);\n cass_result_free(result);\n }\n }\n }\n try {\n data.push(NULL);\n }\n catch (tbb::user_abort &e) {\n\n return;\n }\n}No longer returns empty list when tuple row has 0 elements#include \"Prefetch.h\"\n\n\n#define CHECK_CASS(msg) if(rc != CASS_OK){ \\\nstd::cerr<> *token_ranges, uint32_t buff_size,\n TupleRowFactory *tuple_factory, CassSession *session, std::string query) {\n this->session = session;\n this->t_factory = tuple_factory;\n this->tokens = token_ranges;\n CassFuture *future = cass_session_prepare(session, query.c_str());\n CassError rc = cass_future_error_code(future);\n CHECK_CASS(\"prefetch cannot prepare\");\n this->prepared_query = cass_future_get_prepared(future);\n cass_future_free(future);\n this->data.set_capacity(buff_size);\n this->worker = new std::thread{&Prefetch::consume_tokens, this};\n\n}\n\nPyObject* Prefetch::get_next(){\n if(completed){\n PyErr_SetNone(PyExc_StopIteration);\n return NULL;\n }\n TupleRow *response = NULL;\n data.pop(response);\n if (!response||response->n_elem()==0) {\n completed = true;\n PyErr_SetNone(PyExc_StopIteration);\n return NULL;\n }\n PyObject* toberet= t_factory->tuple_as_py(response);\n delete(response);\n return toberet;\n}\n\nvoid Prefetch::consume_tokens() {\n for (std::pair range : *tokens) {\n CassStatement *statement = cass_prepared_bind(this->prepared_query);\n cass_statement_bind_int64(statement, 0, range.first);\n cass_statement_bind_int64(statement, 1, range.second);\n\n CassFuture *future = cass_session_execute(session, statement);\n cass_statement_free(statement);\n const CassResult *result = NULL;\n int tries = 0;\n while (result == NULL && tries < 10) {\n result = cass_future_get_result(future);\n cass_future_free(future);\n if (result == NULL) {\n CassError rc = cass_future_error_code(future);\n std::cout << cass_error_desc(rc) << std::endl;\n tries++;\n\n } else {\n CassIterator *iterator = cass_iterator_from_result(result);\n\n while (cass_iterator_next(iterator)) {\n const CassRow *row = cass_iterator_get_row(iterator);\n TupleRow *t = t_factory->make_tuple(row);\n try {\n data.push(t); \/\/blocking operation\n }\n catch (tbb::user_abort &e) {\n delete(t);\n cass_iterator_free(iterator);\n cass_result_free(result);\n return;\n\n }\n }\n cass_iterator_free(iterator);\n cass_result_free(result);\n }\n }\n }\n try {\n data.push(NULL);\n }\n catch (tbb::user_abort &e) {\n\n return;\n }\n}<|endoftext|>"} {"text":"#include \"ram.h\"\n\n\/*USE EXAMPLE\nRam ram;\nchar *i;\ni = (char*)ram.allocate(4);\nstrcpy(i, \"siis\");\nstd::cout << i << '\\n';\nram.free(i);\n*\/\n\nRam::Ram(unsigned long blockNum, unsigned long blockSize) :memBlock(NULL), allocatedMemBlockLL(NULL), freeMemBlockLL(NULL), memPoolSize(blockNum*(blockSize + sizeof(LinkedList))), memBlockSize(blockSize){\n\tmemBlock = malloc(memPoolSize);\n\tif (memBlock != NULL){\n\t\tfor (unsigned long i = 0; iprev = NULL;\n\t\t\tcurrentBlock->next = freeMemBlockLL;\n\t\t\tif (freeMemBlockLL != NULL){\n\t\t\t\tfreeMemBlockLL->prev = currentBlock;\n\t\t\t}\n\t\t\tfreeMemBlockLL = currentBlock;\n\t\t}\n\t}\n\taddresses = new WORD[1024];\n\tprocesses = new PCB[30];\n}\nRam::~Ram(){\n\t::free(memBlock);\n}\n\nvoid *Ram::allocate(unsigned long size, bool useMemPool){\n\tif (size > memBlockSize || false == useMemPool || NULL == memBlock || NULL == freeMemBlockLL){\n\t\treturn malloc(size);\n\t}\n\n\tLinkedList *pCurUnit = freeMemBlockLL;\n\tfreeMemBlockLL = pCurUnit->next;\n\tif (NULL != freeMemBlockLL)\n\t{\n\t\tfreeMemBlockLL->prev = NULL;\n\t}\n\n\tpCurUnit->next = allocatedMemBlockLL;\n\n\tif (NULL != allocatedMemBlockLL)\n\t{\n\t\tallocatedMemBlockLL->prev = pCurUnit;\n\t}\n\tallocatedMemBlockLL = pCurUnit;\n\treturn (void *)((char *)pCurUnit + sizeof(LinkedList));\n}\n\nvoid *Ram::allocate(unsigned long size, int location, PCB process, bool useMemPool)\t\t\/\/modified allocate method that adds the jam to the LinkedList and also in the addresses array\n{\n\tif (size > memBlockSize || false == useMemPool || NULL == memBlock || NULL == freeMemBlockLL){\n\t\treturn malloc(size);\n\t}\n\n\tLinkedList *pCurUnit = freeMemBlockLL;\n\tfreeMemBlockLL = pCurUnit->next;\n\tif (NULL != freeMemBlockLL)\n\t{\n\t\tfreeMemBlockLL->prev = NULL;\n\t}\n\n\tpCurUnit->next = allocatedMemBlockLL;\n\n\tif (NULL != allocatedMemBlockLL)\n\t{\n\t\tallocatedMemBlockLL->prev = pCurUnit;\n\t}\n\tallocatedMemBlockLL = pCurUnit;\n\treturn (void *)((char *)pCurUnit + sizeof(LinkedList));\n\n\tprocesses[location] = process;\t\t\/\/saves temporary PCB information\n}\n\nvoid Ram::free(void *p){\n\tif (memBlock

next;\n\t\tif (NULL != allocatedMemBlockLL)\n\t\t{\n\t\t\tallocatedMemBlockLL->prev = NULL;\n\t\t}\n\n\t\tpCurUnit->next = freeMemBlockLL;\n\t\tif (NULL != freeMemBlockLL)\n\t\t{\n\t\t\tfreeMemBlockLL->prev = pCurUnit;\n\t\t}\n\n\t\tfreeMemBlockLL = pCurUnit;\n\t}\n\telse\n\t{\n\t\tfree(p);\n\t}\n}\n\n\n\n\n\n\/\/\/******************************************************\n\/\/ * ram.cpp - RAM module implementation\n\/\/ * created 150204 jonathan howard (j@hovverd.com)\n\/\/ ******************************************************\/\n\/\/\n\/\/#include \n\/\/#include \n\/\/#include \n\/\/#include \n\/\/#include \n\/\/\n\/\/#include \n\/\/\n\/\/#include \"ram.h\"\n\/\/\n\/\/#define BUFFER_SIZE (1024 * sizeof(WORD))\n\/\/#define blockSize(i) (1 << i)\n\/\/\n\/\/RAM::RAM()\n\/\/{\n\/\/ buffer = new WORD[1024]();\n\/\/ \/* 2^9 (512) word base allocation *\/\n\/\/ ((BlockTag *)buffer)->order = 9;\n\/\/ ((BlockTag *)(buffer + blockSize(9)))->order = 9;\n\/\/\n\/\/ ((BlockTag *)buffer)->isFree = true;\n\/\/ ((BlockTag *)(buffer + blockSize(9)))->isFree = true;\n\/\/}\n\/\/\n\/\/RAM::~RAM()\n\/\/{\n\/\/ delete[] buffer;\n\/\/}\n\/\/\n\/\/WORD * RAM::allocate(std::size_t size)\n\/\/{\n\/\/\tBlockTag * bestBlock = nullptr;\n\/\/\n\/\/ \/* calculate order for best fit, this is ceil(log2(size)) *\/\n\/\/ unsigned int order = 1;\n\/\/ for (order = 0; blockSize( order ) - sizeof(BlockTag) < size; order++);\n\/\/\n\/\/ \/* find best fit block to allocate in *\/\n\/\/\tfor (BlockTag * p = (BlockTag *)buffer; p != (BlockTag *)(buffer + 1024); p += blockSize(p->order))\n\/\/\t{\n\/\/\t\tif (p->isFree)\n\/\/\t\t{\n\/\/\t\t\tif ( order <= p->order )\n\/\/\t\t\t{\n\/\/ \/* select block if we don't have one otherwise best fit *\/\n\/\/ if ( bestBlock == nullptr || p->order < bestBlock->order )\n\/\/ {\n\/\/\t\t\t\t bestBlock = p;\n\/\/ }\n\/\/\t\t\t}\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/\tif (!bestBlock)\n\/\/\t{\n\/\/\t\tthrow std::bad_alloc();\n\/\/\t}\n\/\/\telse\n\/\/\t{\n\/\/ \/* subdividing block *\/\n\/\/ while(bestBlock->order != order)\n\/\/ { \n\/\/ bestBlock->order--;\n\/\/ BlockTag * friendBlock = (BlockTag *)((char *)bestBlock + blockSize( bestBlock->order ) * sizeof(WORD));\n\/\/ \n\/\/ friendBlock->order = bestBlock->order;\n\/\/ friendBlock->isFree = true;\n\/\/\n\/\/ DLOG(\"[RAM] splitting block of order %i at relative address %p\", bestBlock->order, (void*)((WORD *)((char *)bestBlock + sizeof(BlockTag)) - (WORD *)buffer));\n\/\/\n\/\/ \/* push smaller allocations to end *\/\n\/\/ bestBlock = friendBlock;\n\/\/ }\n\/\/\n\/\/ bestBlock->isFree = false;\n\/\/ DLOG(\"[RAM] allocating %lu words at relative address %p\", size, (void*)((WORD *)((char *)bestBlock + sizeof(BlockTag)) - (WORD *)buffer));\n\/\/ return (WORD *)((char *)bestBlock + sizeof(BlockTag));\n\/\/ }\n\/\/\n\/\/\treturn nullptr;\n\/\/}\n\/\/\n\/\/void RAM::deallocate(void * memory)\n\/\/{\n\/\/ if ( memory == nullptr )\n\/\/ {\n\/\/ return;\n\/\/ }\n\/\/\n\/\/ BlockTag * block = (BlockTag *)((char *)memory - sizeof(BlockTag));\n\/\/ BlockTag * buddy = (BlockTag *)((intptr_t)block ^ blockSize( ((BlockTag *)block)->order) );\n\/\/\n\/\/ uint8_t freeingOrder = block->order;\n\/\/\n\/\/ \/* combining blocks *\/\n\/\/ if ( buddy->isFree ) \n\/\/ {\n\/\/ freeingOrder++;\n\/\/\n\/\/ BlockTag * firstBlock;\n\/\/\n\/\/ std::less lss;\n\/\/\n\/\/ if ( lss(buddy, block) ) \/\/ | buddy | block |\n\/\/ {\n\/\/ firstBlock = (BlockTag *)buddy;\n\/\/ }\n\/\/ else \/\/ | block | buddy |\n\/\/ {\n\/\/ firstBlock = (BlockTag *)block;\n\/\/ }\n\/\/ \/* Zero both blocks simultaneously *\/\n\/\/ memset(firstBlock, 0, blockSize( freeingOrder ) * sizeof(WORD));\n\/\/\n\/\/ firstBlock->isFree = true;\n\/\/ firstBlock->order = freeingOrder;\n\/\/\n\/\/ DLOG(\"[RAM] deallocating %i words by combining blocks at relative addresses %p and %p\", blockSize(freeingOrder), block, buddy);\n\/\/ }\n\/\/ else \/* freeing a single block *\/\n\/\/ {\n\/\/ memset(block, 0, blockSize( freeingOrder ) * sizeof(WORD));\n\/\/ block->isFree = true;\n\/\/ block->order = freeingOrder;\n\/\/\n\/\/ DLOG(\"[RAM] deallocating %i words in single block at %p\", blockSize( freeingOrder ), block);\n\/\/ }\n\/\/\n\/\/ std::cout << buffer << std::endl << block << std::endl << buddy << std::endl << block - buddy << std::endl;\n\/\/} \n\/\/\n\/\/#undef BUFFER_SIZE\nSyntax correction#include \"ram.h\"\n\n\/*USE EXAMPLE\nRam ram;\nchar *i;\ni = (char*)ram.allocate(4);\nstrcpy(i, \"siis\");\nstd::cout << i << '\\n';\nram.free(i);\n*\/\n\nRam::Ram(unsigned long blockNum, unsigned long blockSize) :memBlock(NULL), allocatedMemBlockLL(NULL), freeMemBlockLL(NULL), memPoolSize(blockNum*(blockSize + sizeof(LinkedList))), memBlockSize(blockSize){\n\tmemBlock = malloc(memPoolSize);\n\tif (memBlock != NULL){\n\t\tfor (unsigned long i = 0; iprev = NULL;\n\t\t\tcurrentBlock->next = freeMemBlockLL;\n\t\t\tif (freeMemBlockLL != NULL){\n\t\t\t\tfreeMemBlockLL->prev = currentBlock;\n\t\t\t}\n\t\t\tfreeMemBlockLL = currentBlock;\n\t\t}\n\t}\n\taddresses = new WORD[1024];\n\tprocesses = new PCB[30];\n}\nRam::~Ram(){\n\t::free(memBlock);\n}\n\nvoid *Ram::allocate(unsigned long size, bool useMemPool){\n\tif (size > memBlockSize || false == useMemPool || NULL == memBlock || NULL == freeMemBlockLL){\n\t\treturn malloc(size);\n\t}\n\n\tLinkedList *pCurUnit = freeMemBlockLL;\n\tfreeMemBlockLL = pCurUnit->next;\n\tif (freeMemBlockLL != NULL)\n\t{\n\t\tfreeMemBlockLL->prev = NULL;\n\t}\n\n\tpCurUnit->next = allocatedMemBlockLL;\n\n\tif (allocatedMemBlockLL != NULL)\n\t{\n\t\tallocatedMemBlockLL->prev = pCurUnit;\n\t}\n\tallocatedMemBlockLL = pCurUnit;\n\treturn (void *)((char *)pCurUnit + sizeof(LinkedList));\n}\n\nvoid *Ram::allocate(unsigned long size, int location, PCB process, bool useMemPool)\t\t\/\/modified allocate method that adds the jam to the LinkedList and also in the addresses array\n{\n\tif (size > memBlockSize || false == useMemPool || NULL == memBlock || NULL == freeMemBlockLL){\n\t\treturn malloc(size);\n\t}\n\n\tLinkedList *pCurUnit = freeMemBlockLL;\n\tfreeMemBlockLL = pCurUnit->next;\n\tif (freeMemBlockLL != NULL)\n\t{\n\t\tfreeMemBlockLL->prev = NULL;\n\t}\n\n\tpCurUnit->next = allocatedMemBlockLL;\n\n\tif (allocatedMemBlockLL != NULL)\n\t{\n\t\tallocatedMemBlockLL->prev = pCurUnit;\n\t}\n\tallocatedMemBlockLL = pCurUnit;\n\treturn (void *)((char *)pCurUnit + sizeof(LinkedList));\n\n\tprocesses[location] = process;\t\t\/\/saves temporary PCB information\n}\n\nvoid Ram::free(void *p){\n\tif (memBlock

next;\n\t\tif (allocatedMemBlockLL != NULL)\n\t\t{\n\t\t\tallocatedMemBlockLL->prev = NULL;\n\t\t}\n\n\t\tpCurUnit->next = freeMemBlockLL;\n\t\tif (freeMemBlockLL != NULL)\n\t\t{\n\t\t\tfreeMemBlockLL->prev = pCurUnit;\n\t\t}\n\n\t\tfreeMemBlockLL = pCurUnit;\n\t}\n\telse\n\t{\n\t\tfree(p);\n\t}\n}\n\n\n\n\n\n\/\/\/******************************************************\n\/\/ * ram.cpp - RAM module implementation\n\/\/ * created 150204 jonathan howard (j@hovverd.com)\n\/\/ ******************************************************\/\n\/\/\n\/\/#include \n\/\/#include \n\/\/#include \n\/\/#include \n\/\/#include \n\/\/\n\/\/#include \n\/\/\n\/\/#include \"ram.h\"\n\/\/\n\/\/#define BUFFER_SIZE (1024 * sizeof(WORD))\n\/\/#define blockSize(i) (1 << i)\n\/\/\n\/\/RAM::RAM()\n\/\/{\n\/\/ buffer = new WORD[1024]();\n\/\/ \/* 2^9 (512) word base allocation *\/\n\/\/ ((BlockTag *)buffer)->order = 9;\n\/\/ ((BlockTag *)(buffer + blockSize(9)))->order = 9;\n\/\/\n\/\/ ((BlockTag *)buffer)->isFree = true;\n\/\/ ((BlockTag *)(buffer + blockSize(9)))->isFree = true;\n\/\/}\n\/\/\n\/\/RAM::~RAM()\n\/\/{\n\/\/ delete[] buffer;\n\/\/}\n\/\/\n\/\/WORD * RAM::allocate(std::size_t size)\n\/\/{\n\/\/\tBlockTag * bestBlock = nullptr;\n\/\/\n\/\/ \/* calculate order for best fit, this is ceil(log2(size)) *\/\n\/\/ unsigned int order = 1;\n\/\/ for (order = 0; blockSize( order ) - sizeof(BlockTag) < size; order++);\n\/\/\n\/\/ \/* find best fit block to allocate in *\/\n\/\/\tfor (BlockTag * p = (BlockTag *)buffer; p != (BlockTag *)(buffer + 1024); p += blockSize(p->order))\n\/\/\t{\n\/\/\t\tif (p->isFree)\n\/\/\t\t{\n\/\/\t\t\tif ( order <= p->order )\n\/\/\t\t\t{\n\/\/ \/* select block if we don't have one otherwise best fit *\/\n\/\/ if ( bestBlock == nullptr || p->order < bestBlock->order )\n\/\/ {\n\/\/\t\t\t\t bestBlock = p;\n\/\/ }\n\/\/\t\t\t}\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/\tif (!bestBlock)\n\/\/\t{\n\/\/\t\tthrow std::bad_alloc();\n\/\/\t}\n\/\/\telse\n\/\/\t{\n\/\/ \/* subdividing block *\/\n\/\/ while(bestBlock->order != order)\n\/\/ { \n\/\/ bestBlock->order--;\n\/\/ BlockTag * friendBlock = (BlockTag *)((char *)bestBlock + blockSize( bestBlock->order ) * sizeof(WORD));\n\/\/ \n\/\/ friendBlock->order = bestBlock->order;\n\/\/ friendBlock->isFree = true;\n\/\/\n\/\/ DLOG(\"[RAM] splitting block of order %i at relative address %p\", bestBlock->order, (void*)((WORD *)((char *)bestBlock + sizeof(BlockTag)) - (WORD *)buffer));\n\/\/\n\/\/ \/* push smaller allocations to end *\/\n\/\/ bestBlock = friendBlock;\n\/\/ }\n\/\/\n\/\/ bestBlock->isFree = false;\n\/\/ DLOG(\"[RAM] allocating %lu words at relative address %p\", size, (void*)((WORD *)((char *)bestBlock + sizeof(BlockTag)) - (WORD *)buffer));\n\/\/ return (WORD *)((char *)bestBlock + sizeof(BlockTag));\n\/\/ }\n\/\/\n\/\/\treturn nullptr;\n\/\/}\n\/\/\n\/\/void RAM::deallocate(void * memory)\n\/\/{\n\/\/ if ( memory == nullptr )\n\/\/ {\n\/\/ return;\n\/\/ }\n\/\/\n\/\/ BlockTag * block = (BlockTag *)((char *)memory - sizeof(BlockTag));\n\/\/ BlockTag * buddy = (BlockTag *)((intptr_t)block ^ blockSize( ((BlockTag *)block)->order) );\n\/\/\n\/\/ uint8_t freeingOrder = block->order;\n\/\/\n\/\/ \/* combining blocks *\/\n\/\/ if ( buddy->isFree ) \n\/\/ {\n\/\/ freeingOrder++;\n\/\/\n\/\/ BlockTag * firstBlock;\n\/\/\n\/\/ std::less lss;\n\/\/\n\/\/ if ( lss(buddy, block) ) \/\/ | buddy | block |\n\/\/ {\n\/\/ firstBlock = (BlockTag *)buddy;\n\/\/ }\n\/\/ else \/\/ | block | buddy |\n\/\/ {\n\/\/ firstBlock = (BlockTag *)block;\n\/\/ }\n\/\/ \/* Zero both blocks simultaneously *\/\n\/\/ memset(firstBlock, 0, blockSize( freeingOrder ) * sizeof(WORD));\n\/\/\n\/\/ firstBlock->isFree = true;\n\/\/ firstBlock->order = freeingOrder;\n\/\/\n\/\/ DLOG(\"[RAM] deallocating %i words by combining blocks at relative addresses %p and %p\", blockSize(freeingOrder), block, buddy);\n\/\/ }\n\/\/ else \/* freeing a single block *\/\n\/\/ {\n\/\/ memset(block, 0, blockSize( freeingOrder ) * sizeof(WORD));\n\/\/ block->isFree = true;\n\/\/ block->order = freeingOrder;\n\/\/\n\/\/ DLOG(\"[RAM] deallocating %i words in single block at %p\", blockSize( freeingOrder ), block);\n\/\/ }\n\/\/\n\/\/ std::cout << buffer << std::endl << block << std::endl << buddy << std::endl << block - buddy << std::endl;\n\/\/} \n\/\/\n\/\/#undef BUFFER_SIZE\n<|endoftext|>"} {"text":"\/\/ Module: Log4CPLUS\n\/\/ File: ndc.cxx\n\/\/ Created: 6\/2001\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2001-2015 Tad E. Smith\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n\n#if defined (LOG4CPLUS_WITH_UNIT_TESTS)\n#include \n#endif\n\n\nnamespace log4cplus\n{\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::DiagnosticContext ctors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace\n{\n\n\nstatic\nvoid\ninit_full_message (log4cplus::tstring & fullMessage,\n log4cplus::tstring const & message, DiagnosticContext const * parent)\n{\n if (parent)\n {\n fullMessage.reserve (parent->fullMessage.size () + 1\n + message.size ());\n fullMessage = parent->fullMessage;\n fullMessage += LOG4CPLUS_TEXT(\" \");\n fullMessage += message;\n }\n else\n fullMessage = message;\n}\n\n\n} \/\/ namespace\n\n\nDiagnosticContext::DiagnosticContext(const log4cplus::tstring& message_,\n DiagnosticContext const * parent)\n : message(message_)\n , fullMessage()\n{\n init_full_message (fullMessage, message, parent);\n}\n\n\nDiagnosticContext::DiagnosticContext(tchar const * message_,\n DiagnosticContext const * parent)\n : message(message_)\n , fullMessage()\n{\n init_full_message (fullMessage, message, parent);\n}\n\n\nDiagnosticContext::DiagnosticContext(const log4cplus::tstring& message_)\n : message(message_)\n , fullMessage(message)\n{\n}\n\n\nDiagnosticContext::DiagnosticContext(tchar const * message_)\n : message(message_)\n , fullMessage(message)\n{\n}\n\n\nDiagnosticContext::DiagnosticContext (DiagnosticContext const & other)\n : message (other.message)\n , fullMessage (other.fullMessage)\n{ }\n\n\nDiagnosticContext & DiagnosticContext::operator = (\n DiagnosticContext const & other)\n{\n DiagnosticContext (other).swap (*this);\n return *this;\n}\n\n\nDiagnosticContext::DiagnosticContext (DiagnosticContext && other)\n : message (std::move (other.message))\n , fullMessage (std::move (other.fullMessage))\n{ }\n\n\nDiagnosticContext &\nDiagnosticContext::operator = (DiagnosticContext && other)\n{\n DiagnosticContext (std::move (other)).swap (*this);\n return *this;\n}\n\n\nvoid\nDiagnosticContext::swap (DiagnosticContext & other)\n{\n using std::swap;\n swap (message, other.message);\n swap (fullMessage, other.fullMessage);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::NDC ctor and dtor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNDC::NDC()\n{ }\n\n\nNDC::~NDC()\n{ }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::NDC public methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nNDC::clear()\n{\n DiagnosticContextStack* ptr = getPtr();\n DiagnosticContextStack ().swap (*ptr);\n}\n\n\nvoid\nNDC::remove()\n{\n clear();\n}\n\n\nDiagnosticContextStack\nNDC::cloneStack() const\n{\n DiagnosticContextStack* ptr = getPtr();\n return DiagnosticContextStack(*ptr);\n}\n\n\nvoid\nNDC::inherit(const DiagnosticContextStack& stack)\n{\n DiagnosticContextStack* ptr = getPtr();\n DiagnosticContextStack (stack).swap (*ptr);\n}\n\n\nlog4cplus::tstring const &\nNDC::get() const\n{\n DiagnosticContextStack* ptr = getPtr();\n if(!ptr->empty())\n return ptr->back().fullMessage;\n else\n return internal::empty_str;\n}\n\n\nstd::size_t\nNDC::getDepth() const\n{\n DiagnosticContextStack* ptr = getPtr();\n return ptr->size();\n}\n\n\nlog4cplus::tstring\nNDC::pop()\n{\n DiagnosticContextStack* ptr = getPtr();\n if(!ptr->empty())\n {\n tstring message;\n message.swap (ptr->back ().message);\n ptr->pop_back();\n return message;\n }\n else\n return log4cplus::tstring ();\n}\n\n\nvoid\nNDC::pop_void ()\n{\n DiagnosticContextStack* ptr = getPtr ();\n if (! ptr->empty ())\n ptr->pop_back ();\n}\n\n\nlog4cplus::tstring const &\nNDC::peek() const\n{\n DiagnosticContextStack* ptr = getPtr();\n if(!ptr->empty())\n return ptr->back().message;\n else\n return internal::empty_str;\n}\n\n\nvoid\nNDC::push(const log4cplus::tstring& message)\n{\n push_worker (message);\n}\n\n\nvoid\nNDC::push(tchar const * message)\n{\n push_worker (message);\n}\n\n\ntemplate \nvoid\nNDC::push_worker (StringType const & message)\n{\n DiagnosticContextStack* ptr = getPtr();\n if (ptr->empty())\n ptr->push_back( DiagnosticContext(message, nullptr) );\n else\n {\n DiagnosticContext const & dc = ptr->back();\n ptr->push_back( DiagnosticContext(message, &dc) );\n }\n}\n\n\nvoid\nNDC::setMaxDepth(std::size_t maxDepth)\n{\n DiagnosticContextStack* ptr = getPtr();\n while(maxDepth < ptr->size())\n ptr->pop_back();\n}\n\n\nDiagnosticContextStack* NDC::getPtr()\n{\n internal::per_thread_data * ptd = internal::get_ptd ();\n return &ptd->ndc_dcs;\n}\n\n\n\/\/\n\/\/\n\/\/\n\nNDCContextCreator::NDCContextCreator(const log4cplus::tstring& msg)\n{\n getNDC().push(msg);\n}\n\n\nNDCContextCreator::NDCContextCreator(tchar const * msg)\n{\n getNDC().push(msg);\n}\n\n\nNDCContextCreator::~NDCContextCreator()\n{\n getNDC().pop_void();\n}\n\n\n#if defined (LOG4CPLUS_WITH_UNIT_TESTS)\nCATCH_TEST_CASE (\"NDC\", \"[NDC]\")\n{\n NDC & ndc = getNDC ();\n static tchar const CONTEXT1[] = LOG4CPLUS_TEXT (\"c1\");\n static tchar const CONTEXT2[] = LOG4CPLUS_TEXT (\"c2\");\n static tchar const CONTEXT3[] = LOG4CPLUS_TEXT (\"c3\");\n static tstring const C1C2 = tstring (CONTEXT1)\n + LOG4CPLUS_TEXT (' ')\n + CONTEXT2;\n static tstring const C1C2C3 = C1C2\n + LOG4CPLUS_TEXT (' ')\n + CONTEXT3;\n\n CATCH_SECTION (\"basic\")\n {\n CATCH_REQUIRE (ndc.get ().empty ());\n CATCH_REQUIRE (ndc.peek ().empty ());\n CATCH_REQUIRE (ndc.getDepth () == 0);\n NDCContextCreator c1 (CONTEXT1);\n CATCH_REQUIRE (ndc.peek () == CONTEXT1);\n CATCH_REQUIRE (ndc.get () == CONTEXT1);\n CATCH_REQUIRE (ndc.getDepth () == 1);\n {\n NDCContextCreator c2 (LOG4CPLUS_C_STR_TO_TSTRING (CONTEXT2));\n CATCH_REQUIRE (ndc.get () == C1C2);\n CATCH_REQUIRE (ndc.getDepth () == 2);\n CATCH_REQUIRE (ndc.peek () == CONTEXT2);\n\n ndc.push (CONTEXT3);\n CATCH_REQUIRE (ndc.get () == C1C2C3);\n CATCH_REQUIRE (ndc.peek () == CONTEXT3);\n CATCH_REQUIRE (ndc.pop () == CONTEXT3);\n }\n CATCH_REQUIRE (ndc.peek () == CONTEXT1);\n CATCH_REQUIRE (ndc.get () == CONTEXT1);\n CATCH_REQUIRE (ndc.getDepth () == 1);\n }\n\n CATCH_SECTION (\"remove\")\n {\n ndc.push (CONTEXT1);\n CATCH_REQUIRE (ndc.peek () == CONTEXT1);\n CATCH_REQUIRE (ndc.get () == CONTEXT1);\n CATCH_REQUIRE (ndc.getDepth () == 1);\n\n ndc.remove ();\n CATCH_REQUIRE (ndc.get ().empty ());\n CATCH_REQUIRE (ndc.peek ().empty ());\n CATCH_REQUIRE (ndc.getDepth () == 0);\n }\n}\n\n#endif\n\n} \/\/ namespace log4cplus\nClear NDC before each test.\/\/ Module: Log4CPLUS\n\/\/ File: ndc.cxx\n\/\/ Created: 6\/2001\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2001-2015 Tad E. Smith\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n\n#if defined (LOG4CPLUS_WITH_UNIT_TESTS)\n#include \n#endif\n\n\nnamespace log4cplus\n{\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::DiagnosticContext ctors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace\n{\n\n\nstatic\nvoid\ninit_full_message (log4cplus::tstring & fullMessage,\n log4cplus::tstring const & message, DiagnosticContext const * parent)\n{\n if (parent)\n {\n fullMessage.reserve (parent->fullMessage.size () + 1\n + message.size ());\n fullMessage = parent->fullMessage;\n fullMessage += LOG4CPLUS_TEXT(\" \");\n fullMessage += message;\n }\n else\n fullMessage = message;\n}\n\n\n} \/\/ namespace\n\n\nDiagnosticContext::DiagnosticContext(const log4cplus::tstring& message_,\n DiagnosticContext const * parent)\n : message(message_)\n , fullMessage()\n{\n init_full_message (fullMessage, message, parent);\n}\n\n\nDiagnosticContext::DiagnosticContext(tchar const * message_,\n DiagnosticContext const * parent)\n : message(message_)\n , fullMessage()\n{\n init_full_message (fullMessage, message, parent);\n}\n\n\nDiagnosticContext::DiagnosticContext(const log4cplus::tstring& message_)\n : message(message_)\n , fullMessage(message)\n{\n}\n\n\nDiagnosticContext::DiagnosticContext(tchar const * message_)\n : message(message_)\n , fullMessage(message)\n{\n}\n\n\nDiagnosticContext::DiagnosticContext (DiagnosticContext const & other)\n : message (other.message)\n , fullMessage (other.fullMessage)\n{ }\n\n\nDiagnosticContext & DiagnosticContext::operator = (\n DiagnosticContext const & other)\n{\n DiagnosticContext (other).swap (*this);\n return *this;\n}\n\n\nDiagnosticContext::DiagnosticContext (DiagnosticContext && other)\n : message (std::move (other.message))\n , fullMessage (std::move (other.fullMessage))\n{ }\n\n\nDiagnosticContext &\nDiagnosticContext::operator = (DiagnosticContext && other)\n{\n DiagnosticContext (std::move (other)).swap (*this);\n return *this;\n}\n\n\nvoid\nDiagnosticContext::swap (DiagnosticContext & other)\n{\n using std::swap;\n swap (message, other.message);\n swap (fullMessage, other.fullMessage);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::NDC ctor and dtor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNDC::NDC()\n{ }\n\n\nNDC::~NDC()\n{ }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::NDC public methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nNDC::clear()\n{\n DiagnosticContextStack* ptr = getPtr();\n DiagnosticContextStack ().swap (*ptr);\n}\n\n\nvoid\nNDC::remove()\n{\n clear();\n}\n\n\nDiagnosticContextStack\nNDC::cloneStack() const\n{\n DiagnosticContextStack* ptr = getPtr();\n return DiagnosticContextStack(*ptr);\n}\n\n\nvoid\nNDC::inherit(const DiagnosticContextStack& stack)\n{\n DiagnosticContextStack* ptr = getPtr();\n DiagnosticContextStack (stack).swap (*ptr);\n}\n\n\nlog4cplus::tstring const &\nNDC::get() const\n{\n DiagnosticContextStack* ptr = getPtr();\n if(!ptr->empty())\n return ptr->back().fullMessage;\n else\n return internal::empty_str;\n}\n\n\nstd::size_t\nNDC::getDepth() const\n{\n DiagnosticContextStack* ptr = getPtr();\n return ptr->size();\n}\n\n\nlog4cplus::tstring\nNDC::pop()\n{\n DiagnosticContextStack* ptr = getPtr();\n if(!ptr->empty())\n {\n tstring message;\n message.swap (ptr->back ().message);\n ptr->pop_back();\n return message;\n }\n else\n return log4cplus::tstring ();\n}\n\n\nvoid\nNDC::pop_void ()\n{\n DiagnosticContextStack* ptr = getPtr ();\n if (! ptr->empty ())\n ptr->pop_back ();\n}\n\n\nlog4cplus::tstring const &\nNDC::peek() const\n{\n DiagnosticContextStack* ptr = getPtr();\n if(!ptr->empty())\n return ptr->back().message;\n else\n return internal::empty_str;\n}\n\n\nvoid\nNDC::push(const log4cplus::tstring& message)\n{\n push_worker (message);\n}\n\n\nvoid\nNDC::push(tchar const * message)\n{\n push_worker (message);\n}\n\n\ntemplate \nvoid\nNDC::push_worker (StringType const & message)\n{\n DiagnosticContextStack* ptr = getPtr();\n if (ptr->empty())\n ptr->push_back( DiagnosticContext(message, nullptr) );\n else\n {\n DiagnosticContext const & dc = ptr->back();\n ptr->push_back( DiagnosticContext(message, &dc) );\n }\n}\n\n\nvoid\nNDC::setMaxDepth(std::size_t maxDepth)\n{\n DiagnosticContextStack* ptr = getPtr();\n while(maxDepth < ptr->size())\n ptr->pop_back();\n}\n\n\nDiagnosticContextStack* NDC::getPtr()\n{\n internal::per_thread_data * ptd = internal::get_ptd ();\n return &ptd->ndc_dcs;\n}\n\n\n\/\/\n\/\/\n\/\/\n\nNDCContextCreator::NDCContextCreator(const log4cplus::tstring& msg)\n{\n getNDC().push(msg);\n}\n\n\nNDCContextCreator::NDCContextCreator(tchar const * msg)\n{\n getNDC().push(msg);\n}\n\n\nNDCContextCreator::~NDCContextCreator()\n{\n getNDC().pop_void();\n}\n\n\n#if defined (LOG4CPLUS_WITH_UNIT_TESTS)\nCATCH_TEST_CASE (\"NDC\", \"[NDC]\")\n{\n NDC & ndc = getNDC ();\n ndc.clear ();\n static tchar const CONTEXT1[] = LOG4CPLUS_TEXT (\"c1\");\n static tchar const CONTEXT2[] = LOG4CPLUS_TEXT (\"c2\");\n static tchar const CONTEXT3[] = LOG4CPLUS_TEXT (\"c3\");\n static tstring const C1C2 = tstring (CONTEXT1)\n + LOG4CPLUS_TEXT (' ')\n + CONTEXT2;\n static tstring const C1C2C3 = C1C2\n + LOG4CPLUS_TEXT (' ')\n + CONTEXT3;\n\n CATCH_SECTION (\"basic\")\n {\n CATCH_REQUIRE (ndc.get ().empty ());\n CATCH_REQUIRE (ndc.peek ().empty ());\n CATCH_REQUIRE (ndc.getDepth () == 0);\n NDCContextCreator c1 (CONTEXT1);\n CATCH_REQUIRE (ndc.peek () == CONTEXT1);\n CATCH_REQUIRE (ndc.get () == CONTEXT1);\n CATCH_REQUIRE (ndc.getDepth () == 1);\n {\n NDCContextCreator c2 (LOG4CPLUS_C_STR_TO_TSTRING (CONTEXT2));\n CATCH_REQUIRE (ndc.get () == C1C2);\n CATCH_REQUIRE (ndc.getDepth () == 2);\n CATCH_REQUIRE (ndc.peek () == CONTEXT2);\n\n ndc.push (CONTEXT3);\n CATCH_REQUIRE (ndc.get () == C1C2C3);\n CATCH_REQUIRE (ndc.peek () == CONTEXT3);\n CATCH_REQUIRE (ndc.pop () == CONTEXT3);\n }\n CATCH_REQUIRE (ndc.peek () == CONTEXT1);\n CATCH_REQUIRE (ndc.get () == CONTEXT1);\n CATCH_REQUIRE (ndc.getDepth () == 1);\n }\n\n CATCH_SECTION (\"remove\")\n {\n ndc.push (CONTEXT1);\n CATCH_REQUIRE (ndc.peek () == CONTEXT1);\n CATCH_REQUIRE (ndc.get () == CONTEXT1);\n CATCH_REQUIRE (ndc.getDepth () == 1);\n\n ndc.remove ();\n CATCH_REQUIRE (ndc.get ().empty ());\n CATCH_REQUIRE (ndc.peek ().empty ());\n CATCH_REQUIRE (ndc.getDepth () == 0);\n }\n}\n\n#endif\n\n} \/\/ namespace log4cplus\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010, 2011 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"Box.h\"\n\n#include \n#include \n\n#include \n\n#include \"CSSStyleDeclarationImp.h\"\n#include \"ViewCSSImp.h\"\n\n#include \"font\/FontManager.h\"\n#include \"font\/FontManagerBackEndGL.h\"\n\nnamespace org { namespace w3c { namespace dom { namespace bootstrap {\n\nnamespace {\n\nenum\n{\n TOP,\n RIGHT,\n BOTTOM,\n LEFT\n};\n\nstd::map texnames;\n\nGLuint addImage(uint8_t* image, unsigned width, unsigned heigth, unsigned repeat, GLenum format)\n{\n GLuint texname;\n\n glGenTextures(1, &texname);\n glBindTexture(GL_TEXTURE_2D, texname);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (repeat & BoxImage::RepeatS) ? GL_REPEAT : (repeat & BoxImage::Clamp) ? GL_CLAMP_TO_EDGE : GL_CLAMP_TO_BORDER);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (repeat & BoxImage::RepeatT) ? GL_REPEAT : (repeat & BoxImage::Clamp) ? GL_CLAMP_TO_EDGE : GL_CLAMP_TO_BORDER);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, heigth, 0, format, GL_UNSIGNED_BYTE, image);\n texnames.insert(std::pair(image, texname));\n return texname;\n}\n\nGLuint getTexname(uint8_t* image, unsigned width, unsigned height, unsigned repeat, GLenum format)\n{\n std::map::iterator it = texnames.find(image);\n if (it == texnames.end())\n return addImage(image, width, height, repeat, format);\n return it->second;\n}\n\nvoid deleteImage(uint8_t* image)\n{\n std::map::iterator it = texnames.find(image);\n if (it != texnames.end()) {\n glDeleteTextures(1, &it->second);\n texnames.erase(it);\n }\n}\n\nvoid getOriginScreenPosition(float& x, float& y)\n{\n GLfloat m[16];\n glGetFloatv(GL_MODELVIEW_MATRIX, m);\n x = m[12];\n y = glutGet(GLUT_WINDOW_HEIGHT) - m[13];\n}\n\n} \/\/ namespace\n\nBoxImage::~BoxImage()\n{\n if (state == CompletelyAvailable)\n deleteImage(pixels);\n delete pixels;\n}\n\nvoid BoxImage::render(ViewCSSImp* view, float x, float y, float width, float height, float left, float top)\n{\n if (state != CompletelyAvailable)\n return;\n\n glMatrixMode(GL_TEXTURE);\n glLoadIdentity();\n if (repeat & BoxImage::Clamp)\n glScalef(1.0f \/ width, 1.0f \/ height, 0.0f);\n else\n glScalef(1.0f \/ naturalWidth, 1.0f \/ naturalHeight, 0.0f);\n glMatrixMode(GL_MODELVIEW);\n\n GLuint texname = getTexname(pixels, naturalWidth, naturalHeight, repeat, format);\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, texname);\n glColor3ub(255, 255, 255);\n glBegin(GL_QUADS);\n glTexCoord2f(x - left, y - top);\n glVertex2f(x, y);\n glTexCoord2f(x - left + width, y - top);\n glVertex2f(x + width, y);\n glTexCoord2f(x - left + width, y - top + height);\n glVertex2f(x + width, y + height);\n glTexCoord2f(x - left, y - top + height);\n glVertex2f(x, y + height);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n}\n\nvoid Box::renderBorderEdge(ViewCSSImp* view, int edge, unsigned borderStyle, unsigned color,\n float a, float b, float c, float d,\n float e, float f, float g, float h)\n{\n if (borderStyle == CSSBorderStyleValueImp::None ||\n borderStyle == CSSBorderStyleValueImp::Hidden)\n return;\n\n GLubyte red = color >> 16;\n GLubyte green = color >> 8;\n GLubyte blue = color;\n GLubyte alpha = color >> 24;\n\n if (borderStyle == CSSBorderStyleValueImp::Double) {\n float offset;\n offset = (g - a) \/ 3;\n float i = a + offset;\n float m = g - offset;\n offset = (h - b) \/ 3;\n float j = b + offset;\n float n = h - offset;\n offset = (c - e) \/ 3;\n float k = c - offset;\n float o = e + offset;\n offset = (f - d) \/ 3;\n float l = d + offset;\n float p = f - offset;\n glColor4ub(red, green, blue, alpha);\n glBegin(GL_QUADS);\n glVertex2f(a, b);\n glVertex2f(c, d);\n glVertex2f(k, l);\n glVertex2f(i, j);\n glEnd();\n glBegin(GL_QUADS);\n glVertex2f(m, n);\n glVertex2f(o, p);\n glVertex2f(e, f);\n glVertex2f(g, h);\n glEnd();\n return;\n }\n\n if (borderStyle == CSSBorderStyleValueImp::Dotted ||\n borderStyle == CSSBorderStyleValueImp::Dashed) {\n glEnable(GL_LINE_STIPPLE);\n glLineWidth(fabsf(g - a));\n glLineStipple(fabsf(g - a), (borderStyle == CSSBorderStyleValueImp::Dotted) ? 0xaaaa : 0xcccc);\n glBegin(GL_LINES);\n glColor4ub(red, green, blue, alpha);\n glVertex2f((a + g) \/ 2, (b + h) \/ 2);\n glVertex2f((c + e) \/ 2, (d + f) \/ 2);\n glEnd();\n glDisable(GL_LINE_STIPPLE);\n return;\n }\n\n if (borderStyle == CSSBorderStyleValueImp::Groove ||\n borderStyle == CSSBorderStyleValueImp::Ridge) {\n GLubyte redDark = std::max(red - 128, 0);\n GLubyte greenDark = std::max(green - 128, 0);\n GLubyte blueDark = std::max(blue - 128, 0);\n GLubyte redBright = std::min(red + 128, 255);\n GLubyte greenBright = std::min(green + 128, 255);\n GLubyte blueBright = std::min(blue + 128, 255);\n float offset;\n offset = (g - a) \/ 2;\n float i = a + offset;\n offset = (h - b) \/ 2;\n float j = b + offset;\n offset = (c - e) \/ 2;\n float k = c - offset;\n offset = (f - d) \/ 2;\n float l = d + offset;\n if (borderStyle == CSSBorderStyleValueImp::Groove)\n glColor4ub(redDark, greenDark, blueDark, alpha);\n else\n glColor4ub(redBright, greenBright, blueBright, alpha);\n glBegin(GL_QUADS);\n glVertex2f(a, b);\n glVertex2f(c, d);\n glVertex2f(k, l);\n glVertex2f(i, j);\n glEnd();\n if (borderStyle == CSSBorderStyleValueImp::Groove)\n glColor4ub(redBright, greenBright, blueBright, alpha);\n else\n glColor4ub(redDark, greenDark, blueDark, alpha);\n glBegin(GL_QUADS);\n glVertex2f(i, j);\n glVertex2f(k, l);\n glVertex2f(e, f);\n glVertex2f(g, h);\n glEnd();\n return;\n }\n\n if (borderStyle == CSSBorderStyleValueImp::Inset ||\n borderStyle == CSSBorderStyleValueImp::Outset) {\n bool dark = false;\n bool bright = false;\n if (borderStyle == CSSBorderStyleValueImp::Inset) {\n switch (edge) {\n case TOP:\n case LEFT:\n dark = true;\n break;;\n case RIGHT:\n case BOTTOM:\n bright = true;\n break;;\n }\n }\n if (borderStyle == CSSBorderStyleValueImp::Outset) {\n switch (edge) {\n case TOP:\n case LEFT:\n bright = true;\n break;;\n case RIGHT:\n case BOTTOM:\n dark = true;\n break;;\n }\n }\n if (dark) {\n red = std::max(red - 128, 0);\n green = std::max(green - 128, 0);\n blue = std::max(blue - 128, 0);\n } else if (bright) {\n red = std::min(red + 128, 255);\n green = std::min(green + 128, 255);\n blue = std::min(blue + 128, 255);\n }\n }\n\n glColor4ub(red, green, blue, alpha);\n glBegin(GL_QUADS);\n glVertex2f(a, b);\n glVertex2f(c, d);\n glVertex2f(e, f);\n glVertex2f(g, h);\n glEnd();\n}\n\nvoid Box::renderBorder(ViewCSSImp* view)\n{\n glDisable(GL_TEXTURE_2D);\n\n float ll = marginLeft;\n float lr = ll + borderLeft;\n float rl = lr + paddingLeft + width + paddingRight;\n float rr = rl + borderRight;\n float tt = marginTop;\n float tb = tt + borderTop;\n float bt = tb + paddingTop + height + paddingBottom;\n float bb = bt + borderBottom;\n\n if (backgroundColor != 0x00000000) {\n glColor4ub(backgroundColor >> 16, backgroundColor >> 8, backgroundColor, backgroundColor >> 24);\n glBegin(GL_QUADS);\n glVertex2f(lr, tb);\n glVertex2f(rl, tb);\n glVertex2f(rl, bt);\n glVertex2f(lr, bt);\n glEnd();\n }\n\n if (backgroundImage) {\n GLfloat border[] = { ((backgroundColor >> 16) & 0xff) \/ 255.0f,\n ((backgroundColor >> 8) & 0xff) \/ 255.0f,\n ((backgroundColor) & 0xff) \/ 255.0f,\n ((backgroundColor >> 24) & 0xff) \/ 255.0f };\n glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);\n glPushMatrix();\n if (getParentBox()) {\n \/\/ TODO: check padding\n glTranslatef(lr, tb, 0.0f);\n backgroundImage->render(view, 0, 0, rl - lr, bt - tb, backgroundLeft, backgroundTop);\n } else {\n const ContainingBlock* containingBlock = getContainingBlock(view);\n glTranslatef(ll, tt, 0.0f);\n backgroundImage->render(view, -ll, -tt, containingBlock->width, containingBlock->height, backgroundLeft, backgroundTop);\n }\n glPopMatrix();\n }\n\n if (borderTop)\n renderBorderEdge(view, TOP,\n style->borderTopStyle.getValue(),\n style->borderTopColor.getARGB(),\n ll, tt, rr, tt, rl, tb, lr, tb);\n if (borderRight)\n renderBorderEdge(view, RIGHT,\n style->borderRightStyle.getValue(),\n style->borderRightColor.getARGB(),\n rl, bt, rl, tb, rr, tt, rr, bb);\n if (borderBottom)\n renderBorderEdge(view, BOTTOM,\n style->borderBottomStyle.getValue(),\n style->borderBottomColor.getARGB(),\n lr, bt, rl, bt, rr, bb, ll, bb);\n if (borderLeft)\n renderBorderEdge(view, LEFT,\n style->borderLeftStyle.getValue(),\n style->borderLeftColor.getARGB(),\n ll, bb, ll, tt, lr, tb, lr, bt);\n glEnable(GL_TEXTURE_2D);\n}\n\nvoid BlockLevelBox::render(ViewCSSImp* view)\n{\n glPushMatrix();\n glTranslatef(offsetH, offsetV, 0.0f);\n getOriginScreenPosition(x, y);\n renderBorder(view);\n glTranslatef(getBlankLeft(), getBlankTop(), 0.0f);\n if (shadow)\n shadow->render();\n else {\n for (auto child = getFirstChild(); child; child = child->getNextSibling()) {\n child->render(view);\n glTranslatef(0.0f, child->getTotalHeight(), 0.0f);\n }\n }\n glPopMatrix();\n}\n\nvoid LineBox::render(ViewCSSImp* view)\n{\n glPushMatrix();\n glTranslatef(offsetH, offsetV, 0.0f);\n getOriginScreenPosition(x, y);\n for (auto child = getFirstChild(); child; child = child->getNextSibling()) {\n child->render(view);\n if (!child->isAbsolutelyPositioned()) {\n glTranslatef(child->getTotalWidth(), 0.0f, 0.0f);\n }\n }\n glPopMatrix();\n}\n\nvoid InlineLevelBox::render(ViewCSSImp* view)\n{\n glPushMatrix();\n glTranslatef(offsetH, offsetV, 0.0f);\n renderBorder(view);\n glTranslatef(getBlankLeft(), getBlankTop(), 0.0f);\n getOriginScreenPosition(x, y);\n if (shadow)\n shadow->render();\n else if (getFirstChild()) \/\/ for inline-block\n getFirstChild()->render(view);\n else if (0 < data.length()) {\n glTranslatef(0.0f, baseline, 0.0f);\n glScalef(point \/ font->getPoint(), point \/ font->getPoint(), 1.0);\n unsigned color = getStyle()->color.getARGB();\n glColor4ub(color >> 16, color >> 8, color, color >> 24);\n font->renderText(data.c_str(), data.length());\n }\n glPopMatrix();\n}\n\n}}}} \/\/ org::w3c::dom::bootstrap\n(Box::renderBorder) : Paint the background of the render tree root box correctly.\/*\n * Copyright 2010, 2011 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"Box.h\"\n\n#include \n#include \n\n#include \n\n#include \"CSSStyleDeclarationImp.h\"\n#include \"ViewCSSImp.h\"\n\n#include \"font\/FontManager.h\"\n#include \"font\/FontManagerBackEndGL.h\"\n\nnamespace org { namespace w3c { namespace dom { namespace bootstrap {\n\nnamespace {\n\nenum\n{\n TOP,\n RIGHT,\n BOTTOM,\n LEFT\n};\n\nstd::map texnames;\n\nGLuint addImage(uint8_t* image, unsigned width, unsigned heigth, unsigned repeat, GLenum format)\n{\n GLuint texname;\n\n glGenTextures(1, &texname);\n glBindTexture(GL_TEXTURE_2D, texname);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (repeat & BoxImage::RepeatS) ? GL_REPEAT : (repeat & BoxImage::Clamp) ? GL_CLAMP_TO_EDGE : GL_CLAMP_TO_BORDER);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (repeat & BoxImage::RepeatT) ? GL_REPEAT : (repeat & BoxImage::Clamp) ? GL_CLAMP_TO_EDGE : GL_CLAMP_TO_BORDER);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, heigth, 0, format, GL_UNSIGNED_BYTE, image);\n texnames.insert(std::pair(image, texname));\n return texname;\n}\n\nGLuint getTexname(uint8_t* image, unsigned width, unsigned height, unsigned repeat, GLenum format)\n{\n std::map::iterator it = texnames.find(image);\n if (it == texnames.end())\n return addImage(image, width, height, repeat, format);\n return it->second;\n}\n\nvoid deleteImage(uint8_t* image)\n{\n std::map::iterator it = texnames.find(image);\n if (it != texnames.end()) {\n glDeleteTextures(1, &it->second);\n texnames.erase(it);\n }\n}\n\nvoid getOriginScreenPosition(float& x, float& y)\n{\n GLfloat m[16];\n glGetFloatv(GL_MODELVIEW_MATRIX, m);\n x = m[12];\n y = glutGet(GLUT_WINDOW_HEIGHT) - m[13];\n}\n\n} \/\/ namespace\n\nBoxImage::~BoxImage()\n{\n if (state == CompletelyAvailable)\n deleteImage(pixels);\n delete pixels;\n}\n\nvoid BoxImage::render(ViewCSSImp* view, float x, float y, float width, float height, float left, float top)\n{\n if (state != CompletelyAvailable)\n return;\n\n glMatrixMode(GL_TEXTURE);\n glLoadIdentity();\n if (repeat & BoxImage::Clamp)\n glScalef(1.0f \/ width, 1.0f \/ height, 0.0f);\n else\n glScalef(1.0f \/ naturalWidth, 1.0f \/ naturalHeight, 0.0f);\n glMatrixMode(GL_MODELVIEW);\n\n GLuint texname = getTexname(pixels, naturalWidth, naturalHeight, repeat, format);\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, texname);\n glColor3ub(255, 255, 255);\n glBegin(GL_QUADS);\n glTexCoord2f(x - left, y - top);\n glVertex2f(x, y);\n glTexCoord2f(x - left + width, y - top);\n glVertex2f(x + width, y);\n glTexCoord2f(x - left + width, y - top + height);\n glVertex2f(x + width, y + height);\n glTexCoord2f(x - left, y - top + height);\n glVertex2f(x, y + height);\n glEnd();\n glDisable(GL_TEXTURE_2D);\n}\n\nvoid Box::renderBorderEdge(ViewCSSImp* view, int edge, unsigned borderStyle, unsigned color,\n float a, float b, float c, float d,\n float e, float f, float g, float h)\n{\n if (borderStyle == CSSBorderStyleValueImp::None ||\n borderStyle == CSSBorderStyleValueImp::Hidden)\n return;\n\n GLubyte red = color >> 16;\n GLubyte green = color >> 8;\n GLubyte blue = color;\n GLubyte alpha = color >> 24;\n\n if (borderStyle == CSSBorderStyleValueImp::Double) {\n float offset;\n offset = (g - a) \/ 3;\n float i = a + offset;\n float m = g - offset;\n offset = (h - b) \/ 3;\n float j = b + offset;\n float n = h - offset;\n offset = (c - e) \/ 3;\n float k = c - offset;\n float o = e + offset;\n offset = (f - d) \/ 3;\n float l = d + offset;\n float p = f - offset;\n glColor4ub(red, green, blue, alpha);\n glBegin(GL_QUADS);\n glVertex2f(a, b);\n glVertex2f(c, d);\n glVertex2f(k, l);\n glVertex2f(i, j);\n glEnd();\n glBegin(GL_QUADS);\n glVertex2f(m, n);\n glVertex2f(o, p);\n glVertex2f(e, f);\n glVertex2f(g, h);\n glEnd();\n return;\n }\n\n if (borderStyle == CSSBorderStyleValueImp::Dotted ||\n borderStyle == CSSBorderStyleValueImp::Dashed) {\n glEnable(GL_LINE_STIPPLE);\n glLineWidth(fabsf(g - a));\n glLineStipple(fabsf(g - a), (borderStyle == CSSBorderStyleValueImp::Dotted) ? 0xaaaa : 0xcccc);\n glBegin(GL_LINES);\n glColor4ub(red, green, blue, alpha);\n glVertex2f((a + g) \/ 2, (b + h) \/ 2);\n glVertex2f((c + e) \/ 2, (d + f) \/ 2);\n glEnd();\n glDisable(GL_LINE_STIPPLE);\n return;\n }\n\n if (borderStyle == CSSBorderStyleValueImp::Groove ||\n borderStyle == CSSBorderStyleValueImp::Ridge) {\n GLubyte redDark = std::max(red - 128, 0);\n GLubyte greenDark = std::max(green - 128, 0);\n GLubyte blueDark = std::max(blue - 128, 0);\n GLubyte redBright = std::min(red + 128, 255);\n GLubyte greenBright = std::min(green + 128, 255);\n GLubyte blueBright = std::min(blue + 128, 255);\n float offset;\n offset = (g - a) \/ 2;\n float i = a + offset;\n offset = (h - b) \/ 2;\n float j = b + offset;\n offset = (c - e) \/ 2;\n float k = c - offset;\n offset = (f - d) \/ 2;\n float l = d + offset;\n if (borderStyle == CSSBorderStyleValueImp::Groove)\n glColor4ub(redDark, greenDark, blueDark, alpha);\n else\n glColor4ub(redBright, greenBright, blueBright, alpha);\n glBegin(GL_QUADS);\n glVertex2f(a, b);\n glVertex2f(c, d);\n glVertex2f(k, l);\n glVertex2f(i, j);\n glEnd();\n if (borderStyle == CSSBorderStyleValueImp::Groove)\n glColor4ub(redBright, greenBright, blueBright, alpha);\n else\n glColor4ub(redDark, greenDark, blueDark, alpha);\n glBegin(GL_QUADS);\n glVertex2f(i, j);\n glVertex2f(k, l);\n glVertex2f(e, f);\n glVertex2f(g, h);\n glEnd();\n return;\n }\n\n if (borderStyle == CSSBorderStyleValueImp::Inset ||\n borderStyle == CSSBorderStyleValueImp::Outset) {\n bool dark = false;\n bool bright = false;\n if (borderStyle == CSSBorderStyleValueImp::Inset) {\n switch (edge) {\n case TOP:\n case LEFT:\n dark = true;\n break;;\n case RIGHT:\n case BOTTOM:\n bright = true;\n break;;\n }\n }\n if (borderStyle == CSSBorderStyleValueImp::Outset) {\n switch (edge) {\n case TOP:\n case LEFT:\n bright = true;\n break;;\n case RIGHT:\n case BOTTOM:\n dark = true;\n break;;\n }\n }\n if (dark) {\n red = std::max(red - 128, 0);\n green = std::max(green - 128, 0);\n blue = std::max(blue - 128, 0);\n } else if (bright) {\n red = std::min(red + 128, 255);\n green = std::min(green + 128, 255);\n blue = std::min(blue + 128, 255);\n }\n }\n\n glColor4ub(red, green, blue, alpha);\n glBegin(GL_QUADS);\n glVertex2f(a, b);\n glVertex2f(c, d);\n glVertex2f(e, f);\n glVertex2f(g, h);\n glEnd();\n}\n\nvoid Box::renderBorder(ViewCSSImp* view)\n{\n glDisable(GL_TEXTURE_2D);\n\n float ll = marginLeft;\n float lr = ll + borderLeft;\n float rl = lr + paddingLeft + width + paddingRight;\n float rr = rl + borderRight;\n float tt = marginTop;\n float tb = tt + borderTop;\n float bt = tb + paddingTop + height + paddingBottom;\n float bb = bt + borderBottom;\n\n if (backgroundColor != 0x00000000) {\n glColor4ub(backgroundColor >> 16, backgroundColor >> 8, backgroundColor, backgroundColor >> 24);\n glBegin(GL_QUADS);\n if (getParentBox()) {\n glVertex2f(lr, tb);\n glVertex2f(rl, tb);\n glVertex2f(rl, bt);\n glVertex2f(lr, bt);\n } else {\n const ContainingBlock* containingBlock = getContainingBlock(view);\n glVertex2f(0, 0);\n glVertex2f(containingBlock->width, 0);\n glVertex2f(containingBlock->width, containingBlock->height);\n glVertex2f(0, containingBlock->height);\n }\n glEnd();\n }\n\n if (backgroundImage) {\n GLfloat border[] = { ((backgroundColor >> 16) & 0xff) \/ 255.0f,\n ((backgroundColor >> 8) & 0xff) \/ 255.0f,\n ((backgroundColor) & 0xff) \/ 255.0f,\n ((backgroundColor >> 24) & 0xff) \/ 255.0f };\n glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);\n glPushMatrix();\n if (getParentBox()) {\n \/\/ TODO: check padding\n glTranslatef(lr, tb, 0.0f);\n backgroundImage->render(view, 0, 0, rl - lr, bt - tb, backgroundLeft, backgroundTop);\n } else {\n const ContainingBlock* containingBlock = getContainingBlock(view);\n glTranslatef(ll, tt, 0.0f);\n backgroundImage->render(view, -ll, -tt, containingBlock->width, containingBlock->height, backgroundLeft, backgroundTop);\n }\n glPopMatrix();\n }\n\n if (borderTop)\n renderBorderEdge(view, TOP,\n style->borderTopStyle.getValue(),\n style->borderTopColor.getARGB(),\n ll, tt, rr, tt, rl, tb, lr, tb);\n if (borderRight)\n renderBorderEdge(view, RIGHT,\n style->borderRightStyle.getValue(),\n style->borderRightColor.getARGB(),\n rl, bt, rl, tb, rr, tt, rr, bb);\n if (borderBottom)\n renderBorderEdge(view, BOTTOM,\n style->borderBottomStyle.getValue(),\n style->borderBottomColor.getARGB(),\n lr, bt, rl, bt, rr, bb, ll, bb);\n if (borderLeft)\n renderBorderEdge(view, LEFT,\n style->borderLeftStyle.getValue(),\n style->borderLeftColor.getARGB(),\n ll, bb, ll, tt, lr, tb, lr, bt);\n glEnable(GL_TEXTURE_2D);\n}\n\nvoid BlockLevelBox::render(ViewCSSImp* view)\n{\n glPushMatrix();\n glTranslatef(offsetH, offsetV, 0.0f);\n getOriginScreenPosition(x, y);\n renderBorder(view);\n glTranslatef(getBlankLeft(), getBlankTop(), 0.0f);\n if (shadow)\n shadow->render();\n else {\n for (auto child = getFirstChild(); child; child = child->getNextSibling()) {\n child->render(view);\n glTranslatef(0.0f, child->getTotalHeight(), 0.0f);\n }\n }\n glPopMatrix();\n}\n\nvoid LineBox::render(ViewCSSImp* view)\n{\n glPushMatrix();\n glTranslatef(offsetH, offsetV, 0.0f);\n getOriginScreenPosition(x, y);\n for (auto child = getFirstChild(); child; child = child->getNextSibling()) {\n child->render(view);\n if (!child->isAbsolutelyPositioned()) {\n glTranslatef(child->getTotalWidth(), 0.0f, 0.0f);\n }\n }\n glPopMatrix();\n}\n\nvoid InlineLevelBox::render(ViewCSSImp* view)\n{\n glPushMatrix();\n glTranslatef(offsetH, offsetV, 0.0f);\n renderBorder(view);\n glTranslatef(getBlankLeft(), getBlankTop(), 0.0f);\n getOriginScreenPosition(x, y);\n if (shadow)\n shadow->render();\n else if (getFirstChild()) \/\/ for inline-block\n getFirstChild()->render(view);\n else if (0 < data.length()) {\n glTranslatef(0.0f, baseline, 0.0f);\n glScalef(point \/ font->getPoint(), point \/ font->getPoint(), 1.0);\n unsigned color = getStyle()->color.getARGB();\n glColor4ub(color >> 16, color >> 8, color, color >> 24);\n font->renderText(data.c_str(), data.length());\n }\n glPopMatrix();\n}\n\n}}}} \/\/ org::w3c::dom::bootstrap\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ For information about interceptions as a whole see\n\/\/ http:\/\/wiki\/Main\/ChromeSandboxInterceptionDesign\n\n#include \"sandbox\/src\/interception_agent.h\"\n\n#include \"sandbox\/src\/interception_internal.h\"\n#include \"sandbox\/src\/eat_resolver.h\"\n#include \"sandbox\/src\/sidestep_resolver.h\"\n#include \"sandbox\/src\/sandbox_nt_util.h\"\n\nnamespace {\n\n\/\/ Returns true if target lies between base and base + range.\nbool IsWithinRange(const void* base, size_t range, const void* target) {\n const char* end = reinterpret_cast(base) + range;\n return reinterpret_cast(target) < end;\n}\n\n} \/\/ namespace\n\nnamespace sandbox {\n\n\/\/ This is the list of all imported symbols from ntdll.dll.\nSANDBOX_INTERCEPT NtExports g_nt;\n\n\/\/ Memory buffer mapped from the parent, with the list of interceptions.\nSANDBOX_INTERCEPT SharedMemory* g_interceptions = NULL;\n\nInterceptionAgent* InterceptionAgent::GetInterceptionAgent() {\n static InterceptionAgent* s_singleton_pointer = NULL;\n if (!s_singleton_pointer) {\n if (!g_interceptions)\n return NULL;\n\n size_t object_bytes = g_interceptions->num_intercepted_dlls * sizeof(void*);\n s_singleton_pointer = reinterpret_cast(\n new(NT_ALLOC) char[object_bytes]);\n\n bool success = s_singleton_pointer->Init(g_interceptions);\n if (!success) {\n operator delete(s_singleton_pointer, NT_ALLOC);\n s_singleton_pointer = NULL;\n }\n }\n return s_singleton_pointer;\n}\n\nbool InterceptionAgent::Init(SharedMemory* shared_memory) {\n interceptions_ = shared_memory;\n for (int i = 0 ; i < shared_memory->num_intercepted_dlls; i++)\n dlls_[i] = NULL;\n return true;\n}\n\nbool InterceptionAgent::DllMatch(const UNICODE_STRING* full_path,\n const UNICODE_STRING* name,\n const DllPatchInfo* dll_info) {\n UNICODE_STRING current_name;\n current_name.Length = static_cast(g_nt.wcslen(dll_info->dll_name) *\n sizeof(wchar_t));\n current_name.MaximumLength = current_name.Length;\n current_name.Buffer = const_cast(dll_info->dll_name);\n\n BOOLEAN case_insensitive = TRUE;\n if (full_path &&\n !g_nt.RtlCompareUnicodeString(¤t_name, full_path, case_insensitive))\n return true;\n\n if (!g_nt.RtlCompareUnicodeString(¤t_name, name, case_insensitive))\n return true;\n\n return false;\n}\n\nvoid InterceptionAgent::OnDllLoad(const UNICODE_STRING* full_path,\n const UNICODE_STRING* name,\n void* base_address) {\n DllPatchInfo* dll_info = interceptions_->dll_list;\n int i = 0;\n for (; i < interceptions_->num_intercepted_dlls; i++) {\n if (DllMatch(full_path, name, dll_info))\n break;\n\n dll_info = reinterpret_cast(\n reinterpret_cast(dll_info) + dll_info->record_bytes);\n }\n if (i == interceptions_->num_intercepted_dlls)\n return;\n\n \/\/ Purify causes this condition to trigger.\n if (dlls_[i])\n return;\n\n size_t buffer_bytes = offsetof(DllInterceptionData, thunks) +\n dll_info->num_functions * sizeof(ThunkData);\n dlls_[i] = reinterpret_cast(\n new(NT_PAGE) char[buffer_bytes]);\n\n DCHECK_NT(dlls_[i]);\n if (!dlls_[i])\n return;\n\n dlls_[i]->data_bytes = buffer_bytes;\n dlls_[i]->num_thunks = 0;\n dlls_[i]->base = base_address;\n dlls_[i]->used_bytes = offsetof(DllInterceptionData, thunks);\n\n VERIFY(PatchDll(dll_info, dlls_[i]));\n\n ULONG old_protect;\n SIZE_T real_size = buffer_bytes;\n void* to_protect = dlls_[i];\n VERIFY_SUCCESS(g_nt.ProtectVirtualMemory(NtCurrentProcess, &to_protect,\n &real_size, PAGE_EXECUTE_READ,\n &old_protect));\n}\n\nvoid InterceptionAgent::OnDllUnload(void* base_address) {\n for (int i = 0; i < interceptions_->num_intercepted_dlls; i++) {\n if (dlls_[i] && dlls_[i]->base == base_address) {\n operator delete(dlls_[i], NT_PAGE);\n dlls_[i] = NULL;\n break;\n }\n }\n}\n\n\/\/ TODO(rvargas): We have to deal with prebinded dlls. I see two options: change\n\/\/ the timestamp of the patched dll, or modify the info on the prebinded dll.\n\/\/ the first approach messes matching of debug symbols, the second one is more\n\/\/ complicated.\nbool InterceptionAgent::PatchDll(const DllPatchInfo* dll_info,\n DllInterceptionData* thunks) {\n DCHECK_NT(NULL != thunks);\n DCHECK_NT(NULL != dll_info);\n\n const FunctionInfo* function = reinterpret_cast(\n reinterpret_cast(dll_info) + dll_info->offset_to_functions);\n\n for (int i = 0; i < dll_info->num_functions; i++) {\n if (!IsWithinRange(dll_info, dll_info->record_bytes, function->function)) {\n NOTREACHED_NT();\n return false;\n }\n\n ResolverThunk* resolver = GetResolver(function->type);\n if (!resolver)\n return false;\n\n const char* interceptor = function->function +\n g_nt.strlen(function->function) + 1;\n\n if (!IsWithinRange(function, function->record_bytes, interceptor) ||\n !IsWithinRange(dll_info, dll_info->record_bytes, interceptor)) {\n NOTREACHED_NT();\n return false;\n }\n\n NTSTATUS ret = resolver->Setup(thunks->base,\n interceptions_->interceptor_base,\n function->function,\n interceptor,\n function->interceptor_address,\n &thunks->thunks[i],\n sizeof(ThunkData),\n NULL);\n if (!NT_SUCCESS(ret)) {\n NOTREACHED_NT();\n return false;\n }\n\n thunks->num_thunks++;\n thunks->used_bytes += sizeof(ThunkData);\n\n function = reinterpret_cast(\n reinterpret_cast(function) + function->record_bytes);\n }\n\n return true;\n}\n\n\/\/ This method is called from within the loader lock\nResolverThunk* InterceptionAgent::GetResolver(InterceptionType type) {\n static EatResolverThunk* eat_resolver = NULL;\n static SidestepResolverThunk* sidestep_resolver = NULL;\n static SmartSidestepResolverThunk* smart_sidestep_resolver = NULL;\n\n if (!eat_resolver)\n eat_resolver = new(NT_ALLOC) EatResolverThunk;\n\n if (!sidestep_resolver)\n sidestep_resolver = new(NT_ALLOC) SidestepResolverThunk;\n\n if (!smart_sidestep_resolver)\n smart_sidestep_resolver = new(NT_ALLOC) SmartSidestepResolverThunk;\n\n switch (type) {\n case INTERCEPTION_EAT:\n return eat_resolver;\n case INTERCEPTION_SIDESTEP:\n return sidestep_resolver;\n case INTERCEPTION_SMART_SIDESTEP:\n return smart_sidestep_resolver;\n default:\n NOTREACHED_NT();\n }\n\n return NULL;\n}\n\n} \/\/ namespace sandbox\n\nFix memory corruption when EAT patching in sandbox\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ For information about interceptions as a whole see\n\/\/ http:\/\/wiki\/Main\/ChromeSandboxInterceptionDesign\n\n#include \"sandbox\/src\/interception_agent.h\"\n\n#include \"sandbox\/src\/interception_internal.h\"\n#include \"sandbox\/src\/eat_resolver.h\"\n#include \"sandbox\/src\/sidestep_resolver.h\"\n#include \"sandbox\/src\/sandbox_nt_util.h\"\n\nnamespace {\n\n\/\/ Returns true if target lies between base and base + range.\nbool IsWithinRange(const void* base, size_t range, const void* target) {\n const char* end = reinterpret_cast(base) + range;\n return reinterpret_cast(target) < end;\n}\n\n} \/\/ namespace\n\nnamespace sandbox {\n\n\/\/ This is the list of all imported symbols from ntdll.dll.\nSANDBOX_INTERCEPT NtExports g_nt;\n\n\/\/ Memory buffer mapped from the parent, with the list of interceptions.\nSANDBOX_INTERCEPT SharedMemory* g_interceptions = NULL;\n\nInterceptionAgent* InterceptionAgent::GetInterceptionAgent() {\n static InterceptionAgent* s_singleton = NULL;\n if (!s_singleton) {\n if (!g_interceptions)\n return NULL;\n\n size_t array_bytes = g_interceptions->num_intercepted_dlls * sizeof(void*);\n s_singleton = reinterpret_cast(\n new(NT_ALLOC) char[array_bytes + sizeof(InterceptionAgent)]);\n\n bool success = s_singleton->Init(g_interceptions);\n if (!success) {\n operator delete(s_singleton, NT_ALLOC);\n s_singleton = NULL;\n }\n }\n return s_singleton;\n}\n\nbool InterceptionAgent::Init(SharedMemory* shared_memory) {\n interceptions_ = shared_memory;\n for (int i = 0 ; i < shared_memory->num_intercepted_dlls; i++)\n dlls_[i] = NULL;\n return true;\n}\n\nbool InterceptionAgent::DllMatch(const UNICODE_STRING* full_path,\n const UNICODE_STRING* name,\n const DllPatchInfo* dll_info) {\n UNICODE_STRING current_name;\n current_name.Length = static_cast(g_nt.wcslen(dll_info->dll_name) *\n sizeof(wchar_t));\n current_name.MaximumLength = current_name.Length;\n current_name.Buffer = const_cast(dll_info->dll_name);\n\n BOOLEAN case_insensitive = TRUE;\n if (full_path &&\n !g_nt.RtlCompareUnicodeString(¤t_name, full_path, case_insensitive))\n return true;\n\n if (!g_nt.RtlCompareUnicodeString(¤t_name, name, case_insensitive))\n return true;\n\n return false;\n}\n\nvoid InterceptionAgent::OnDllLoad(const UNICODE_STRING* full_path,\n const UNICODE_STRING* name,\n void* base_address) {\n DllPatchInfo* dll_info = interceptions_->dll_list;\n int i = 0;\n for (; i < interceptions_->num_intercepted_dlls; i++) {\n if (DllMatch(full_path, name, dll_info))\n break;\n\n dll_info = reinterpret_cast(\n reinterpret_cast(dll_info) + dll_info->record_bytes);\n }\n if (i == interceptions_->num_intercepted_dlls)\n return;\n\n \/\/ Purify causes this condition to trigger.\n if (dlls_[i])\n return;\n\n size_t buffer_bytes = offsetof(DllInterceptionData, thunks) +\n dll_info->num_functions * sizeof(ThunkData);\n dlls_[i] = reinterpret_cast(\n new(NT_PAGE) char[buffer_bytes]);\n\n DCHECK_NT(dlls_[i]);\n if (!dlls_[i])\n return;\n\n dlls_[i]->data_bytes = buffer_bytes;\n dlls_[i]->num_thunks = 0;\n dlls_[i]->base = base_address;\n dlls_[i]->used_bytes = offsetof(DllInterceptionData, thunks);\n\n VERIFY(PatchDll(dll_info, dlls_[i]));\n\n ULONG old_protect;\n SIZE_T real_size = buffer_bytes;\n void* to_protect = dlls_[i];\n VERIFY_SUCCESS(g_nt.ProtectVirtualMemory(NtCurrentProcess, &to_protect,\n &real_size, PAGE_EXECUTE_READ,\n &old_protect));\n}\n\nvoid InterceptionAgent::OnDllUnload(void* base_address) {\n for (int i = 0; i < interceptions_->num_intercepted_dlls; i++) {\n if (dlls_[i] && dlls_[i]->base == base_address) {\n operator delete(dlls_[i], NT_PAGE);\n dlls_[i] = NULL;\n break;\n }\n }\n}\n\n\/\/ TODO(rvargas): We have to deal with prebinded dlls. I see two options: change\n\/\/ the timestamp of the patched dll, or modify the info on the prebinded dll.\n\/\/ the first approach messes matching of debug symbols, the second one is more\n\/\/ complicated.\nbool InterceptionAgent::PatchDll(const DllPatchInfo* dll_info,\n DllInterceptionData* thunks) {\n DCHECK_NT(NULL != thunks);\n DCHECK_NT(NULL != dll_info);\n\n const FunctionInfo* function = reinterpret_cast(\n reinterpret_cast(dll_info) + dll_info->offset_to_functions);\n\n for (int i = 0; i < dll_info->num_functions; i++) {\n if (!IsWithinRange(dll_info, dll_info->record_bytes, function->function)) {\n NOTREACHED_NT();\n return false;\n }\n\n ResolverThunk* resolver = GetResolver(function->type);\n if (!resolver)\n return false;\n\n const char* interceptor = function->function +\n g_nt.strlen(function->function) + 1;\n\n if (!IsWithinRange(function, function->record_bytes, interceptor) ||\n !IsWithinRange(dll_info, dll_info->record_bytes, interceptor)) {\n NOTREACHED_NT();\n return false;\n }\n\n NTSTATUS ret = resolver->Setup(thunks->base,\n interceptions_->interceptor_base,\n function->function,\n interceptor,\n function->interceptor_address,\n &thunks->thunks[i],\n sizeof(ThunkData),\n NULL);\n if (!NT_SUCCESS(ret)) {\n NOTREACHED_NT();\n return false;\n }\n\n thunks->num_thunks++;\n thunks->used_bytes += sizeof(ThunkData);\n\n function = reinterpret_cast(\n reinterpret_cast(function) + function->record_bytes);\n }\n\n return true;\n}\n\n\/\/ This method is called from within the loader lock\nResolverThunk* InterceptionAgent::GetResolver(InterceptionType type) {\n static EatResolverThunk* eat_resolver = NULL;\n static SidestepResolverThunk* sidestep_resolver = NULL;\n static SmartSidestepResolverThunk* smart_sidestep_resolver = NULL;\n\n if (!eat_resolver)\n eat_resolver = new(NT_ALLOC) EatResolverThunk;\n\n if (!sidestep_resolver)\n sidestep_resolver = new(NT_ALLOC) SidestepResolverThunk;\n\n if (!smart_sidestep_resolver)\n smart_sidestep_resolver = new(NT_ALLOC) SmartSidestepResolverThunk;\n\n switch (type) {\n case INTERCEPTION_EAT:\n return eat_resolver;\n case INTERCEPTION_SIDESTEP:\n return sidestep_resolver;\n case INTERCEPTION_SMART_SIDESTEP:\n return smart_sidestep_resolver;\n default:\n NOTREACHED_NT();\n }\n\n return NULL;\n}\n\n} \/\/ namespace sandbox\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace newsbeuter;\n\nrss_parser::rss_parser(const char * uri, cache * c, configcontainer * cfg) : my_uri(uri), ch(c), cfgcont(cfg), mrss(0) { }\n\nrss_parser::~rss_parser() { }\n\nrss_feed rss_parser::parse() {\n\trss_feed feed(ch);\n\n\tfeed.set_rssurl(my_uri);\n\n\tchar * proxy = NULL;\n\tchar * proxy_auth = NULL;\n\n\tif (cfgcont->get_configvalue_as_bool(\"use-proxy\") == true) {\n\t\tproxy = const_cast(cfgcont->get_configvalue(\"proxy\").c_str());\n\t\tproxy_auth = const_cast(cfgcont->get_configvalue(\"proxy-auth\").c_str());\n\t}\n\n\tmrss_options_t * options = mrss_options_new(30, proxy, proxy_auth, NULL, NULL, NULL, 0, NULL, USER_AGENT);\n\tmrss_error_t err = mrss_parse_url_with_options(const_cast(my_uri.c_str()), &mrss, options);\n\tmrss_options_free(options);\n\n\tif (err != MRSS_OK) {\n\t\tGetLogger().log(LOG_ERROR,\"rss_parser::parse: mrss_parse_url_with_options failed: err = %s (%d)\",mrss_strerror(err), err);\n\t\tif (mrss) {\n\t\t\tmrss_free(mrss);\n\t\t}\n\t\tthrow std::string(mrss_strerror(err));\n\t}\n\n\tconst char * encoding = mrss->encoding ? mrss->encoding : \"utf-8\";\n\n\tif (mrss->title) {\n\t\tchar * str = stringprep_convert(mrss->title, stringprep_locale_charset(), encoding);\n\t\tif (str) {\n\t\t\tfeed.set_title(str);\n\t\t\tfree(str);\n\t\t}\n\t}\n\t\n\tif (mrss->description) {\n\t\tchar * str = stringprep_convert(mrss->description, stringprep_locale_charset(), encoding);\n\t\tif (str) {\n\t\t\tfeed.set_description(str);\n\t\t\tfree(str);\n\t\t}\n\t}\n\n\tif (mrss->link) feed.set_link(mrss->link);\n\tif (mrss->pubDate) \n\t\tfeed.set_pubDate(parse_date(mrss->pubDate));\n\telse\n\t\tfeed.set_pubDate(::time(NULL));\n\n\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: feed title = `%s' link = `%s'\", feed.title().c_str(), feed.link().c_str());\n\n\tfor (mrss_item_t * item = mrss->item; item != NULL; item = item->next ) {\n\t\trss_item x(ch);\n\t\tif (item->title) {\n\t\t\tchar * str = stringprep_convert(item->title,stringprep_locale_charset(), encoding);\n\t\t\tif (str) {\n\t\t\t\tx.set_title(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t}\n\t\tif (item->link) x.set_link(item->link);\n\t\tif (item->author) x.set_author(item->author);\n\n\t\tmrss_tag_t * content;\n\n\t\tif (mrss->version == MRSS_VERSION_2_0 && mrss_search_tag(item, \"encoded\", \"http:\/\/purl.org\/rss\/1.0\/modules\/content\/\", &content) == MRSS_OK && content) {\n\t\t\t\/* RSS 2.0 content:encoded *\/\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found rss 2.0 content:encoded: %s\\n\", content->value);\n\t\t\tif (content->value) {\n\t\t\t\tchar * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);\n\t\t\t\tif (str) {\n\t\t\t\t\tx.set_description(str);\n\t\t\t\t\tfree(str);\n\t\t\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: conversion was successful: %s\\n\", x.description().c_str());\n\t\t\t\t} else {\n\t\t\t\t\tGetLogger().log(LOG_WARN, \"rss_parser::parse: stringprep_convert() failed for %s, but trying anyway...\", x.link().c_str());\n\t\t\t\t\tx.set_description(content->value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found no rss 2.0 content:encoded\");\n\t\t}\n\n\t\tif ((mrss->version == MRSS_VERSION_ATOM_0_3 || mrss->version == MRSS_VERSION_ATOM_1_0)) {\n\t\t\tint rc;\n\t\t\tif (((rc = mrss_search_tag(item, \"content\", \"http:\/\/www.w3.org\/2005\/Atom\", &content)) == MRSS_OK && content) ||\n\t\t\t ((rc = mrss_search_tag(item, \"content\", \"http:\/\/purl.org\/atom\/ns#\", &content)) == MRSS_OK && content)) {\n\t\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found atom content: %s\\n\", content ? content->value : \"(content = null)\");\n\t\t\t\tif (content && content->value) {\n\t\t\t\t\tchar * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);\n\t\t\t\t\tif (str) {\n\t\t\t\t\t\tx.set_description(str);\n\t\t\t\t\t\tfree(str);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tx.set_description(content->value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: mrss_search_tag(content) failed with rc = %d content = %p\", rc, content);\n\t\t\t}\n\t\t} else {\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: not an atom feed\");\n\t\t}\n\n\t\tif (x.description().length() == 0 && item->description) {\n\t\t\tchar * str = stringprep_convert(item->description,stringprep_locale_charset(), encoding);\n\t\t\tif (str) {\n\t\t\t\tx.set_description(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t}\n\n\t\tif (item->pubDate) \n\t\t\tx.set_pubDate(parse_date(item->pubDate));\n\t\telse\n\t\t\tx.set_pubDate(::time(NULL));\n\t\t\t\n\t\tif (item->guid)\n\t\t\tx.set_guid(item->guid);\n\t\telse\n\t\t\tx.set_guid(item->link); \/\/ XXX hash something to get a better alternative GUID\n\n\t\tif (item->enclosure_url) {\n\t\t\tx.set_enclosure_url(item->enclosure_url);\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found enclosure_url: %s\", item->enclosure_url);\n\t\t}\n\t\tif (item->enclosure_type) {\n\t\t\tx.set_enclosure_type(item->enclosure_type);\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found enclosure_type: %s\", item->enclosure_type);\n\t\t}\n\n\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: item title = `%s' link = `%s' pubDate = `%s' (%d) description = `%s'\", \n\t\t\tx.title().c_str(), x.link().c_str(), x.pubDate().c_str(), x.pubDate_timestamp(), x.description().c_str());\n\t\tfeed.items().push_back(x);\n\t}\n\n\tmrss_free(mrss);\n\n\treturn feed;\n}\n\n\/\/ rss_item setters\n\nvoid rss_item::set_title(const std::string& t) { \n\ttitle_ = t; \n}\n\n\nvoid rss_item::set_link(const std::string& l) { \n\tlink_ = l; \n}\n\nvoid rss_item::set_author(const std::string& a) { \n\tauthor_ = a; \n}\n\nvoid rss_item::set_description(const std::string& d) { \n\tdescription_ = d; \n}\n\nvoid rss_item::set_pubDate(time_t t) { \n\tpubDate_ = t; \n}\n\nvoid rss_item::set_guid(const std::string& g) { \n\tguid_ = g; \n}\n\nvoid rss_item::set_unread(bool u) { \n\tif (unread_ != u) {\n\t\tunread_ = u;\n\t\tif (ch) ch->update_rssitem_unread_and_enqueued(*this, feedurl_); \n\t}\n}\n\nstd::string rss_item::pubDate() const {\n\tchar text[1024];\n\tstrftime(text,sizeof(text),\"%a, %d %b %Y %T\", gmtime(&pubDate_)); \n\treturn std::string(text);\n}\n\nunsigned int rss_feed::unread_item_count() const {\n\tunsigned int count = 0;\n\tfor (std::vector::const_iterator it=items_.begin();it!=items_.end();++it) {\n\t\tif (it->unread())\n\t\t\t++count;\n\t}\n\treturn count;\n}\n\ntime_t rss_parser::parse_date(const std::string& datestr) {\n\t\/\/ TODO: refactor\t\n\tstd::istringstream is(datestr);\n\tstd::string monthstr, time, tmp;\n\tstruct tm stm;\n\t\n\tmemset(&stm,0,sizeof(stm));\n\t\n\tis >> tmp;\n\tif (tmp[tmp.length()-1] == ',')\n\t\tis >> tmp;\n\t\n\tstd::istringstream dayis(tmp);\n\tdayis >> stm.tm_mday;\n\t\n\tis >> monthstr;\n\t\n\tif (monthstr == \"Jan\")\n\t\tstm.tm_mon = 0;\n\telse if (monthstr == \"Feb\")\n\t\tstm.tm_mon = 1;\n\telse if (monthstr == \"Mar\")\n\t\tstm.tm_mon = 2;\n\telse if (monthstr == \"Apr\")\n\t\tstm.tm_mon = 3;\n\telse if (monthstr == \"May\")\n\t\tstm.tm_mon = 4;\n\telse if (monthstr == \"Jun\")\n\t\tstm.tm_mon = 5;\n\telse if (monthstr == \"Jul\")\n\t\tstm.tm_mon = 6;\n\telse if (monthstr == \"Aug\")\n\t\tstm.tm_mon = 7;\n\telse if (monthstr == \"Sep\")\n\t\tstm.tm_mon = 8;\n\telse if (monthstr == \"Oct\")\n\t\tstm.tm_mon = 9;\n\telse if (monthstr == \"Nov\")\n\t\tstm.tm_mon = 10;\n\telse if (monthstr == \"Dec\")\n\t\tstm.tm_mon = 11;\n\t\n\tint year;\n\tis >> year;\n\tstm.tm_year = year - 1900;\n\t\n\tis >> time;\n\n stm.tm_hour = stm.tm_min = stm.tm_sec = 0;\n\t\n\tstd::vector tkns = utils::tokenize(time,\":\");\n\tif (tkns.size() > 0) {\n std::istringstream hs(tkns[0]);\n hs >> stm.tm_hour;\n if (tkns.size() > 1) {\n std::istringstream ms(tkns[1]);\n ms >> stm.tm_min;\n if (tkns.size() > 2) {\n std::istringstream ss(tkns[2]);\n ss >> stm.tm_sec;\n }\n }\n }\n\t\n\ttime_t value = mktime(&stm);\n\treturn value;\n}\n\nbool rss_feed::matches_tag(const std::string& tag) {\n\tfor (std::vector::iterator it=tags_.begin();it!=tags_.end();++it) {\n\t\tif (tag == *it)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nstd::string rss_feed::get_tags() {\n\tstd::string tags;\n\tfor (std::vector::iterator it=tags_.begin();it!=tags_.end();++it) {\n\t\ttags.append(*it);\n\t\ttags.append(\" \");\n\t}\n\treturn tags;\n}\n\nvoid rss_feed::set_tags(const std::vector& tags) {\n\tif (tags_.size() > 0)\n\t\ttags_.erase(tags_.begin(), tags_.end());\n\tfor (std::vector::const_iterator it=tags.begin();it!=tags.end();++it) {\n\t\ttags_.push_back(*it);\n\t}\n}\n\nvoid rss_item::set_enclosure_url(const std::string& url) {\n\tenclosure_url_ = url;\n}\n\nvoid rss_item::set_enclosure_type(const std::string& type) {\n\tenclosure_type_ = type;\n}\nAndreas Krennmair: \timproved support for podcast () summaries.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace newsbeuter;\n\nrss_parser::rss_parser(const char * uri, cache * c, configcontainer * cfg) : my_uri(uri), ch(c), cfgcont(cfg), mrss(0) { }\n\nrss_parser::~rss_parser() { }\n\nrss_feed rss_parser::parse() {\n\trss_feed feed(ch);\n\n\tfeed.set_rssurl(my_uri);\n\n\tchar * proxy = NULL;\n\tchar * proxy_auth = NULL;\n\n\tif (cfgcont->get_configvalue_as_bool(\"use-proxy\") == true) {\n\t\tproxy = const_cast(cfgcont->get_configvalue(\"proxy\").c_str());\n\t\tproxy_auth = const_cast(cfgcont->get_configvalue(\"proxy-auth\").c_str());\n\t}\n\n\tmrss_options_t * options = mrss_options_new(30, proxy, proxy_auth, NULL, NULL, NULL, 0, NULL, USER_AGENT);\n\tmrss_error_t err = mrss_parse_url_with_options(const_cast(my_uri.c_str()), &mrss, options);\n\tmrss_options_free(options);\n\n\tif (err != MRSS_OK) {\n\t\tGetLogger().log(LOG_ERROR,\"rss_parser::parse: mrss_parse_url_with_options failed: err = %s (%d)\",mrss_strerror(err), err);\n\t\tif (mrss) {\n\t\t\tmrss_free(mrss);\n\t\t}\n\t\tthrow std::string(mrss_strerror(err));\n\t}\n\n\tconst char * encoding = mrss->encoding ? mrss->encoding : \"utf-8\";\n\n\tif (mrss->title) {\n\t\tchar * str = stringprep_convert(mrss->title, stringprep_locale_charset(), encoding);\n\t\tif (str) {\n\t\t\tfeed.set_title(str);\n\t\t\tfree(str);\n\t\t}\n\t}\n\t\n\tif (mrss->description) {\n\t\tchar * str = stringprep_convert(mrss->description, stringprep_locale_charset(), encoding);\n\t\tif (str) {\n\t\t\tfeed.set_description(str);\n\t\t\tfree(str);\n\t\t}\n\t}\n\n\tif (mrss->link) feed.set_link(mrss->link);\n\tif (mrss->pubDate) \n\t\tfeed.set_pubDate(parse_date(mrss->pubDate));\n\telse\n\t\tfeed.set_pubDate(::time(NULL));\n\n\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: feed title = `%s' link = `%s'\", feed.title().c_str(), feed.link().c_str());\n\n\tfor (mrss_item_t * item = mrss->item; item != NULL; item = item->next ) {\n\t\trss_item x(ch);\n\t\tif (item->title) {\n\t\t\tchar * str = stringprep_convert(item->title,stringprep_locale_charset(), encoding);\n\t\t\tif (str) {\n\t\t\t\tx.set_title(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t}\n\t\tif (item->link) x.set_link(item->link);\n\t\tif (item->author) x.set_author(item->author);\n\n\t\tmrss_tag_t * content;\n\n\t\tif (mrss->version == MRSS_VERSION_2_0 && mrss_search_tag(item, \"encoded\", \"http:\/\/purl.org\/rss\/1.0\/modules\/content\/\", &content) == MRSS_OK && content) {\n\t\t\t\/* RSS 2.0 content:encoded *\/\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found rss 2.0 content:encoded: %s\\n\", content->value);\n\t\t\tif (content->value) {\n\t\t\t\tchar * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);\n\t\t\t\tif (str) {\n\t\t\t\t\tx.set_description(str);\n\t\t\t\t\tfree(str);\n\t\t\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: conversion was successful: %s\\n\", x.description().c_str());\n\t\t\t\t} else {\n\t\t\t\t\tGetLogger().log(LOG_WARN, \"rss_parser::parse: stringprep_convert() failed for %s, but trying anyway...\", x.link().c_str());\n\t\t\t\t\tx.set_description(content->value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found no rss 2.0 content:encoded\");\n\t\t}\n\n\t\tif ((mrss->version == MRSS_VERSION_ATOM_0_3 || mrss->version == MRSS_VERSION_ATOM_1_0)) {\n\t\t\tint rc;\n\t\t\tif (((rc = mrss_search_tag(item, \"content\", \"http:\/\/www.w3.org\/2005\/Atom\", &content)) == MRSS_OK && content) ||\n\t\t\t ((rc = mrss_search_tag(item, \"content\", \"http:\/\/purl.org\/atom\/ns#\", &content)) == MRSS_OK && content)) {\n\t\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found atom content: %s\\n\", content ? content->value : \"(content = null)\");\n\t\t\t\tif (content && content->value) {\n\t\t\t\t\tchar * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);\n\t\t\t\t\tif (str) {\n\t\t\t\t\t\tx.set_description(str);\n\t\t\t\t\t\tfree(str);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tx.set_description(content->value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: mrss_search_tag(content) failed with rc = %d content = %p\", rc, content);\n\t\t\t}\n\t\t} else {\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: not an atom feed\");\n\t\t}\n\n\t\t\/* last resort: search for itunes:summary tag (may be a podcast) *\/\n\t\tif (x.description().length() == 0 && mrss_search_tag(item, \"summary\", \"http:\/\/www.itunes.com\/dtds\/podcast-1.0.dtd\", &content) == MRSS_OK && content) {\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found itunes:summary: %s\\n\", content->value);\n\t\t\tif (content->value) {\n\t\t\t\tchar * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);\n\t\t\t\tif (str) {\n\t\t\t\t\tstd::string desc = \"

\";\n\t\t\t\t\tdesc.append(str);\n\t\t\t\t\tdesc.append(\"<\/pre>\");\n\t\t\t\t\tx.set_description(desc);\n\t\t\t\t\tfree(str);\n\t\t\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: conversion was successful: %s\\n\", x.description().c_str());\n\t\t\t\t} else {\n\t\t\t\t\tGetLogger().log(LOG_WARN, \"rss_parser::parse: stringprep_convert() failed for %s, but trying anyway...\", x.link().c_str());\n\t\t\t\t\tx.set_description(content->value);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: no luck with itunes:summary\");\n\t\t}\n\n\t\tif (x.description().length() == 0 && item->description) {\n\t\t\tchar * str = stringprep_convert(item->description,stringprep_locale_charset(), encoding);\n\t\t\tif (str) {\n\t\t\t\tx.set_description(str);\n\t\t\t\tfree(str);\n\t\t\t}\n\t\t}\n\n\t\tif (item->pubDate) \n\t\t\tx.set_pubDate(parse_date(item->pubDate));\n\t\telse\n\t\t\tx.set_pubDate(::time(NULL));\n\t\t\t\n\t\tif (item->guid)\n\t\t\tx.set_guid(item->guid);\n\t\telse\n\t\t\tx.set_guid(item->link); \/\/ XXX hash something to get a better alternative GUID\n\n\t\tif (item->enclosure_url) {\n\t\t\tx.set_enclosure_url(item->enclosure_url);\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found enclosure_url: %s\", item->enclosure_url);\n\t\t}\n\t\tif (item->enclosure_type) {\n\t\t\tx.set_enclosure_type(item->enclosure_type);\n\t\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: found enclosure_type: %s\", item->enclosure_type);\n\t\t}\n\n\t\tGetLogger().log(LOG_DEBUG, \"rss_parser::parse: item title = `%s' link = `%s' pubDate = `%s' (%d) description = `%s'\", \n\t\t\tx.title().c_str(), x.link().c_str(), x.pubDate().c_str(), x.pubDate_timestamp(), x.description().c_str());\n\t\tfeed.items().push_back(x);\n\t}\n\n\tmrss_free(mrss);\n\n\treturn feed;\n}\n\n\/\/ rss_item setters\n\nvoid rss_item::set_title(const std::string& t) { \n\ttitle_ = t; \n}\n\n\nvoid rss_item::set_link(const std::string& l) { \n\tlink_ = l; \n}\n\nvoid rss_item::set_author(const std::string& a) { \n\tauthor_ = a; \n}\n\nvoid rss_item::set_description(const std::string& d) { \n\tdescription_ = d; \n}\n\nvoid rss_item::set_pubDate(time_t t) { \n\tpubDate_ = t; \n}\n\nvoid rss_item::set_guid(const std::string& g) { \n\tguid_ = g; \n}\n\nvoid rss_item::set_unread(bool u) { \n\tif (unread_ != u) {\n\t\tunread_ = u;\n\t\tif (ch) ch->update_rssitem_unread_and_enqueued(*this, feedurl_); \n\t}\n}\n\nstd::string rss_item::pubDate() const {\n\tchar text[1024];\n\tstrftime(text,sizeof(text),\"%a, %d %b %Y %T\", gmtime(&pubDate_)); \n\treturn std::string(text);\n}\n\nunsigned int rss_feed::unread_item_count() const {\n\tunsigned int count = 0;\n\tfor (std::vector::const_iterator it=items_.begin();it!=items_.end();++it) {\n\t\tif (it->unread())\n\t\t\t++count;\n\t}\n\treturn count;\n}\n\ntime_t rss_parser::parse_date(const std::string& datestr) {\n\t\/\/ TODO: refactor\t\n\tstd::istringstream is(datestr);\n\tstd::string monthstr, time, tmp;\n\tstruct tm stm;\n\t\n\tmemset(&stm,0,sizeof(stm));\n\t\n\tis >> tmp;\n\tif (tmp[tmp.length()-1] == ',')\n\t\tis >> tmp;\n\t\n\tstd::istringstream dayis(tmp);\n\tdayis >> stm.tm_mday;\n\t\n\tis >> monthstr;\n\t\n\tif (monthstr == \"Jan\")\n\t\tstm.tm_mon = 0;\n\telse if (monthstr == \"Feb\")\n\t\tstm.tm_mon = 1;\n\telse if (monthstr == \"Mar\")\n\t\tstm.tm_mon = 2;\n\telse if (monthstr == \"Apr\")\n\t\tstm.tm_mon = 3;\n\telse if (monthstr == \"May\")\n\t\tstm.tm_mon = 4;\n\telse if (monthstr == \"Jun\")\n\t\tstm.tm_mon = 5;\n\telse if (monthstr == \"Jul\")\n\t\tstm.tm_mon = 6;\n\telse if (monthstr == \"Aug\")\n\t\tstm.tm_mon = 7;\n\telse if (monthstr == \"Sep\")\n\t\tstm.tm_mon = 8;\n\telse if (monthstr == \"Oct\")\n\t\tstm.tm_mon = 9;\n\telse if (monthstr == \"Nov\")\n\t\tstm.tm_mon = 10;\n\telse if (monthstr == \"Dec\")\n\t\tstm.tm_mon = 11;\n\t\n\tint year;\n\tis >> year;\n\tstm.tm_year = year - 1900;\n\t\n\tis >> time;\n\n    stm.tm_hour = stm.tm_min = stm.tm_sec = 0;\n\t\n\tstd::vector tkns = utils::tokenize(time,\":\");\n\tif (tkns.size() > 0) {\n        std::istringstream hs(tkns[0]);\n        hs >> stm.tm_hour;\n        if (tkns.size() > 1) {\n            std::istringstream ms(tkns[1]);\n            ms >> stm.tm_min;\n            if (tkns.size() > 2) {\n                std::istringstream ss(tkns[2]);\n                ss >> stm.tm_sec;\n            }\n        }\n    }\n\t\n\ttime_t value = mktime(&stm);\n\treturn value;\n}\n\nbool rss_feed::matches_tag(const std::string& tag) {\n\tfor (std::vector::iterator it=tags_.begin();it!=tags_.end();++it) {\n\t\tif (tag == *it)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nstd::string rss_feed::get_tags() {\n\tstd::string tags;\n\tfor (std::vector::iterator it=tags_.begin();it!=tags_.end();++it) {\n\t\ttags.append(*it);\n\t\ttags.append(\" \");\n\t}\n\treturn tags;\n}\n\nvoid rss_feed::set_tags(const std::vector& tags) {\n\tif (tags_.size() > 0)\n\t\ttags_.erase(tags_.begin(), tags_.end());\n\tfor (std::vector::const_iterator it=tags.begin();it!=tags.end();++it) {\n\t\ttags_.push_back(*it);\n\t}\n}\n\nvoid rss_item::set_enclosure_url(const std::string& url) {\n\tenclosure_url_ = url;\n}\n\nvoid rss_item::set_enclosure_type(const std::string& type) {\n\tenclosure_type_ = type;\n}\n<|endoftext|>"}
{"text":"\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkHierarchicalBoxDataSet.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkHierarchicalBoxDataSet.h\"\n\n#include \"vtkHierarchicalBoxDataSetInternal.h\"\n\n#include \"vtkMultiGroupDataInformation.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationIdTypeKey.h\"\n#include \"vtkInformationIntegerVectorKey.h\"\n#include \"vtkInformationKey.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkUniformGrid.h\"\n#include \"vtkUnsignedCharArray.h\"\n\nvtkCxxRevisionMacro(vtkHierarchicalBoxDataSet, \"1.16\");\nvtkStandardNewMacro(vtkHierarchicalBoxDataSet);\n\nvtkInformationKeyMacro(vtkHierarchicalBoxDataSet,BOX,IntegerVector);\nvtkInformationKeyMacro(vtkHierarchicalBoxDataSet,NUMBER_OF_BLANKED_POINTS,IdType);\n\ntypedef vtkstd::vector vtkAMRBoxList;\n\/\/----------------------------------------------------------------------------\nvtkHierarchicalBoxDataSet::vtkHierarchicalBoxDataSet()\n{\n  this->BoxInternal = new vtkHierarchicalBoxDataSetInternal;\n  this->ScalarRange[0]=VTK_DOUBLE_MAX;\n  this->ScalarRange[0]=VTK_DOUBLE_MIN;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkHierarchicalBoxDataSet::~vtkHierarchicalBoxDataSet()\n{\n  delete this->BoxInternal;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::SetDataSet(\n  unsigned int level, unsigned int id, vtkAMRBox& box, vtkUniformGrid* dataSet)\n{\n  this->Superclass::SetDataSet(level, id, dataSet);\n\n  vtkInformation* info =\n    this->MultiGroupDataInformation->GetInformation(level, id);\n  if (info)\n    {\n    info->Set(BOX(),\n              box.LoCorner[0], box.LoCorner[1], box.LoCorner[2],\n              box.HiCorner[0], box.HiCorner[1], box.HiCorner[2]);\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkUniformGrid* vtkHierarchicalBoxDataSet::GetDataSet(unsigned int level,\n                                                      unsigned int id,\n                                                      vtkAMRBox& box)\n{\n  if (this->Internal->DataSets.size() <= level)\n    {\n    return 0;\n    }\n\n  vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets =\n    this->Internal->DataSets[level];\n  if (ldataSets.size() <= id)\n    {\n    return 0;\n    }\n\n  if (!ldataSets[id])\n    {\n    return 0;\n    }\n\n  vtkInformation* info =\n    this->MultiGroupDataInformation->GetInformation(level, id);\n  if (info)\n    {\n    int* boxVec = info->Get(BOX());\n    if (boxVec)\n      {\n      vtkAMRBoxInitialize<3>(box.LoCorner, box.HiCorner,\n                             boxVec      , boxVec+3);\n      }\n    }\n  return static_cast(ldataSets[id].GetPointer());\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::SetRefinementRatio(unsigned int level,\n                                                   int ratio)\n{\n  if (level >= this->BoxInternal->RefinementRatios.size())\n    {\n    this->BoxInternal->RefinementRatios.resize(level+1);\n    }\n  this->BoxInternal->RefinementRatios[level] = ratio;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkHierarchicalBoxDataSet::GetRefinementRatio(unsigned int level)\n{\n  if (level >= this->BoxInternal->RefinementRatios.size())\n    {\n    return 0;\n    }\n  return this->BoxInternal->RefinementRatios[level];\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkHierarchicalBoxDataSetIsInBoxes(vtkAMRBoxList& boxes,\n                                       int i, int j, int k)\n{\n  vtkAMRBoxList::iterator it;\n  for(it = boxes.begin(); it != boxes.end(); it++)\n    {\n    if (it->DoesContainCell(i, j, k))\n      {\n      return 1;\n      }\n    }\n  return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::GenerateVisibilityArrays()\n{\n  if (!this->MultiGroupDataInformation)\n    {\n    vtkErrorMacro(\"No information about data layout is specified. \"\n                  \"Cannot generate visibility arrays\");\n    return;\n    }\n\n  unsigned int numLevels = this->GetNumberOfLevels();\n\n  for (unsigned int levelIdx=0; levelIdxGetNumberOfDataSets(levelIdx+1);\n    unsigned int dataSetIdx;\n    if (levelIdx < numLevels - 1)\n      {\n      for (dataSetIdx=0; dataSetIdxMultiGroupDataInformation->HasInformation(\n              levelIdx+1, dataSetIdx))\n          {\n          continue;\n          }\n        vtkInformation* info =\n          this->MultiGroupDataInformation->GetInformation(\n            levelIdx+1,dataSetIdx);\n        int* boxVec = info->Get(BOX());\n        vtkAMRBox coarsebox(3, boxVec, boxVec+3);\n        if (this->BoxInternal->RefinementRatios.size() <= levelIdx)\n          {\n          continue;\n          }\n        coarsebox.Coarsen(this->BoxInternal->RefinementRatios[levelIdx]);\n        boxes.push_back(coarsebox);\n        }\n      }\n\n    numDataSets = this->GetNumberOfDataSets(levelIdx);\n    for (dataSetIdx=0; dataSetIdxGetDataSet(levelIdx, dataSetIdx, box);\n\n      if (grid)\n        {\n        int i;\n        int cellDims[3];\n        for (i=0; i<3; i++)\n          {\n          cellDims[i] = box.HiCorner[i] - box.LoCorner[i] + 1;\n          }\n        vtkUnsignedCharArray* vis = vtkUnsignedCharArray::New();\n        vtkIdType numCells = box.GetNumberOfCells();\n        vis->SetNumberOfTuples(numCells);\n        for (i=0; iSetValue(i, 1);\n          }\n        vtkIdType numBlankedPts = 0;\n        for (int iz=box.LoCorner[2]; iz<=box.HiCorner[2]; iz++)\n          {\n          for (int iy=box.LoCorner[1]; iy<=box.HiCorner[1]; iy++)\n            {\n            for (int ix=box.LoCorner[0]; ix<=box.HiCorner[0]; ix++)\n              {\n              \/\/ Blank if cell is covered by a box of higher level\n              if (vtkHierarchicalBoxDataSetIsInBoxes(boxes, ix, iy, iz))\n                {\n                vtkIdType id =\n                  (iz-box.LoCorner[2])*cellDims[0]*cellDims[1] +\n                  (iy-box.LoCorner[1])*cellDims[0] +\n                  (ix-box.LoCorner[0]);\n                vis->SetValue(id, 0);\n                numBlankedPts++;\n                }\n              }\n            }\n          }\n        grid->SetCellVisibilityArray(vis);\n        vis->Delete();\n        if (this->MultiGroupDataInformation->HasInformation(\n              levelIdx, dataSetIdx))\n          {\n          vtkInformation* infotmp =\n            this->MultiGroupDataInformation->GetInformation(\n              levelIdx,dataSetIdx);\n          infotmp->Set(NUMBER_OF_BLANKED_POINTS(), numBlankedPts);\n          }\n        }\n      }\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkHierarchicalBoxDataSet::GetNumberOfPoints()\n{\n  vtkIdType numPts = 0;\n\n  unsigned int numLevels = this->GetNumberOfLevels();\n  for (unsigned int level=0; levelGetNumberOfDataSets(level);\n    for (unsigned int dataIdx=0; dataIdxMultiGroupDataInformation->GetInformation(level, dataIdx);\n      if (blockInfo)\n        {\n        if (blockInfo->Has(\n              vtkHierarchicalBoxDataSet::NUMBER_OF_BLANKED_POINTS()))\n          {\n          numBlankedPts = blockInfo->Get(NUMBER_OF_BLANKED_POINTS());\n          }\n        }\n      vtkDataSet* ds = vtkDataSet::SafeDownCast(\n        this->GetDataSet(level, dataIdx));\n      if (ds)\n        {\n        numPts += ds->GetNumberOfPoints() - numBlankedPts;\n        }\n      }\n    }\n\n  return numPts;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::ShallowCopy(vtkDataObject *src)\n{\n  if (src == this)\n    {\n    return;\n    }\n  this->InitializeDataSets();\n  this->Modified();\n\n  vtkHierarchicalBoxDataSet* from =\n    vtkHierarchicalBoxDataSet::SafeDownCast(src);\n  if (from)\n    {\n    \/\/ If the source is a vtkHierarchicalBoxDataSet, do not call\n    \/\/ superclass' ShallowCopy, instead skip to vtkCompositeDataSet's\n    \/\/ constructor\n    this->vtkCompositeDataSet::ShallowCopy(src);\n\n    unsigned int numLevels = from->GetNumberOfLevels();\n    this->SetNumberOfLevels(numLevels);\n    for (unsigned int i=0; iGetNumberOfDataSets(i);\n      this->SetNumberOfDataSets(i, numDataSets);\n      for (unsigned int j=0; jGetDataSet(i, j, box);\n        this->SetDataSet(i, j, box, grid);\n        }\n      }\n    }\n  else\n    {\n    this->Superclass::ShallowCopy(src);\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::DeepCopy(vtkDataObject *src)\n{\n  if (src == this)\n    {\n    return;\n    }\n  this->InitializeDataSets();\n  this->Modified();\n\n  vtkHierarchicalBoxDataSet* from =\n    vtkHierarchicalBoxDataSet::SafeDownCast(src);\n  if (from)\n    {\n    \/\/ If the source is a vtkHierarchicalBoxDataSet, do not call\n    \/\/ superclass' DeepCopy, instead skip to vtkCompositeDataSet's\n    \/\/ constructor\n    this->vtkCompositeDataSet::ShallowCopy(src);\n\n    unsigned int numLevels = from->GetNumberOfLevels();\n    this->SetNumberOfLevels(numLevels);\n    for (unsigned int i=0; iGetNumberOfDataSets(i);\n      this->SetNumberOfDataSets(i, numDataSets);\n      for (unsigned int j=0; jGetDataSet(i, j, box);\n        if (ds)\n          {\n          vtkUniformGrid* copy = ds->NewInstance();\n          copy->DeepCopy(ds);\n          this->SetDataSet(i, j, box, copy);\n          }\n        }\n      }\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n  unsigned int numLevels = this->GetNumberOfLevels();\n  os << indent << \"Number of levels: \" <<  numLevels << endl;\n  for (unsigned int i=0; iGetNumberOfDataSets(i);\n    os << indent << \"Level \" << i << \" number of datasets: \" << numDataSets\n       << endl;\n    for (unsigned j=0; jGetDataSet(i, j);\n      if (dobj)\n        {\n        os << endl;\n        dobj->PrintSelf(os, indent.GetNextIndent());\n        }\n      else\n        {\n        os << \"(none)\" << endl;\n        }\n      }\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkHierarchicalBoxDataSet* vtkHierarchicalBoxDataSet::GetData(\n  vtkInformation* info)\n{\n  return\n    info?vtkHierarchicalBoxDataSet::SafeDownCast(info->Get(DATA_OBJECT())) : 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkHierarchicalBoxDataSet* vtkHierarchicalBoxDataSet::GetData(\n  vtkInformationVector* v, int i)\n{\n  return vtkHierarchicalBoxDataSet::GetData(v->GetInformationObject(i));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Copy the cached scalar range into range.\nvoid vtkHierarchicalBoxDataSet::GetScalarRange(double range[2])\n{\n  this->ComputeScalarRange();\n  range[0]=this->ScalarRange[0];\n  range[1]=this->ScalarRange[1];\n}\n  \n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Return the cached range.\ndouble *vtkHierarchicalBoxDataSet::GetScalarRange()\n{\n  this->ComputeScalarRange();\n  return this->ScalarRange;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Compute the range of the scalars and cache it into ScalarRange\n\/\/ only if the cache became invalid (ScalarRangeComputeTime).\nvoid vtkHierarchicalBoxDataSet::ComputeScalarRange()\n{\n  if ( this->GetMTime() > this->ScalarRangeComputeTime )\n    {\n    double dataSetRange[2];\n    this->ScalarRange[0]=VTK_DOUBLE_MAX;\n    this->ScalarRange[1]=VTK_DOUBLE_MIN;\n    unsigned int level=0;\n    unsigned int levels=this->GetNumberOfLevels();\n    while(levelGetNumberOfDataSets(level);\n      while(dataset(this->GetDataSet(level,dataset));\n        ug->GetScalarRange(dataSetRange);\n        if(dataSetRange[0]ScalarRange[0])\n          {\n          this->ScalarRange[0]=dataSetRange[0];\n          }\n        if(dataSetRange[1]>this->ScalarRange[1])\n          {\n          this->ScalarRange[1]=dataSetRange[1];\n          }\n        ++dataset;\n        }\n      ++level;\n      }\n    this->ScalarRangeComputeTime.Modified();\n    }\n}\nBUG:Fixed bad index.\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkHierarchicalBoxDataSet.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkHierarchicalBoxDataSet.h\"\n\n#include \"vtkHierarchicalBoxDataSetInternal.h\"\n\n#include \"vtkMultiGroupDataInformation.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationIdTypeKey.h\"\n#include \"vtkInformationIntegerVectorKey.h\"\n#include \"vtkInformationKey.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkUniformGrid.h\"\n#include \"vtkUnsignedCharArray.h\"\n\nvtkCxxRevisionMacro(vtkHierarchicalBoxDataSet, \"1.17\");\nvtkStandardNewMacro(vtkHierarchicalBoxDataSet);\n\nvtkInformationKeyMacro(vtkHierarchicalBoxDataSet,BOX,IntegerVector);\nvtkInformationKeyMacro(vtkHierarchicalBoxDataSet,NUMBER_OF_BLANKED_POINTS,IdType);\n\ntypedef vtkstd::vector vtkAMRBoxList;\n\/\/----------------------------------------------------------------------------\nvtkHierarchicalBoxDataSet::vtkHierarchicalBoxDataSet()\n{\n  this->BoxInternal = new vtkHierarchicalBoxDataSetInternal;\n  this->ScalarRange[0]=VTK_DOUBLE_MAX;\n  this->ScalarRange[1]=VTK_DOUBLE_MIN;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkHierarchicalBoxDataSet::~vtkHierarchicalBoxDataSet()\n{\n  delete this->BoxInternal;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::SetDataSet(\n  unsigned int level, unsigned int id, vtkAMRBox& box, vtkUniformGrid* dataSet)\n{\n  this->Superclass::SetDataSet(level, id, dataSet);\n\n  vtkInformation* info =\n    this->MultiGroupDataInformation->GetInformation(level, id);\n  if (info)\n    {\n    info->Set(BOX(),\n              box.LoCorner[0], box.LoCorner[1], box.LoCorner[2],\n              box.HiCorner[0], box.HiCorner[1], box.HiCorner[2]);\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkUniformGrid* vtkHierarchicalBoxDataSet::GetDataSet(unsigned int level,\n                                                      unsigned int id,\n                                                      vtkAMRBox& box)\n{\n  if (this->Internal->DataSets.size() <= level)\n    {\n    return 0;\n    }\n\n  vtkMultiGroupDataSetInternal::GroupDataSetsType& ldataSets =\n    this->Internal->DataSets[level];\n  if (ldataSets.size() <= id)\n    {\n    return 0;\n    }\n\n  if (!ldataSets[id])\n    {\n    return 0;\n    }\n\n  vtkInformation* info =\n    this->MultiGroupDataInformation->GetInformation(level, id);\n  if (info)\n    {\n    int* boxVec = info->Get(BOX());\n    if (boxVec)\n      {\n      vtkAMRBoxInitialize<3>(box.LoCorner, box.HiCorner,\n                             boxVec      , boxVec+3);\n      }\n    }\n  return static_cast(ldataSets[id].GetPointer());\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::SetRefinementRatio(unsigned int level,\n                                                   int ratio)\n{\n  if (level >= this->BoxInternal->RefinementRatios.size())\n    {\n    this->BoxInternal->RefinementRatios.resize(level+1);\n    }\n  this->BoxInternal->RefinementRatios[level] = ratio;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkHierarchicalBoxDataSet::GetRefinementRatio(unsigned int level)\n{\n  if (level >= this->BoxInternal->RefinementRatios.size())\n    {\n    return 0;\n    }\n  return this->BoxInternal->RefinementRatios[level];\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkHierarchicalBoxDataSetIsInBoxes(vtkAMRBoxList& boxes,\n                                       int i, int j, int k)\n{\n  vtkAMRBoxList::iterator it;\n  for(it = boxes.begin(); it != boxes.end(); it++)\n    {\n    if (it->DoesContainCell(i, j, k))\n      {\n      return 1;\n      }\n    }\n  return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::GenerateVisibilityArrays()\n{\n  if (!this->MultiGroupDataInformation)\n    {\n    vtkErrorMacro(\"No information about data layout is specified. \"\n                  \"Cannot generate visibility arrays\");\n    return;\n    }\n\n  unsigned int numLevels = this->GetNumberOfLevels();\n\n  for (unsigned int levelIdx=0; levelIdxGetNumberOfDataSets(levelIdx+1);\n    unsigned int dataSetIdx;\n    if (levelIdx < numLevels - 1)\n      {\n      for (dataSetIdx=0; dataSetIdxMultiGroupDataInformation->HasInformation(\n              levelIdx+1, dataSetIdx))\n          {\n          continue;\n          }\n        vtkInformation* info =\n          this->MultiGroupDataInformation->GetInformation(\n            levelIdx+1,dataSetIdx);\n        int* boxVec = info->Get(BOX());\n        vtkAMRBox coarsebox(3, boxVec, boxVec+3);\n        if (this->BoxInternal->RefinementRatios.size() <= levelIdx)\n          {\n          continue;\n          }\n        coarsebox.Coarsen(this->BoxInternal->RefinementRatios[levelIdx]);\n        boxes.push_back(coarsebox);\n        }\n      }\n\n    numDataSets = this->GetNumberOfDataSets(levelIdx);\n    for (dataSetIdx=0; dataSetIdxGetDataSet(levelIdx, dataSetIdx, box);\n\n      if (grid)\n        {\n        int i;\n        int cellDims[3];\n        for (i=0; i<3; i++)\n          {\n          cellDims[i] = box.HiCorner[i] - box.LoCorner[i] + 1;\n          }\n        vtkUnsignedCharArray* vis = vtkUnsignedCharArray::New();\n        vtkIdType numCells = box.GetNumberOfCells();\n        vis->SetNumberOfTuples(numCells);\n        for (i=0; iSetValue(i, 1);\n          }\n        vtkIdType numBlankedPts = 0;\n        for (int iz=box.LoCorner[2]; iz<=box.HiCorner[2]; iz++)\n          {\n          for (int iy=box.LoCorner[1]; iy<=box.HiCorner[1]; iy++)\n            {\n            for (int ix=box.LoCorner[0]; ix<=box.HiCorner[0]; ix++)\n              {\n              \/\/ Blank if cell is covered by a box of higher level\n              if (vtkHierarchicalBoxDataSetIsInBoxes(boxes, ix, iy, iz))\n                {\n                vtkIdType id =\n                  (iz-box.LoCorner[2])*cellDims[0]*cellDims[1] +\n                  (iy-box.LoCorner[1])*cellDims[0] +\n                  (ix-box.LoCorner[0]);\n                vis->SetValue(id, 0);\n                numBlankedPts++;\n                }\n              }\n            }\n          }\n        grid->SetCellVisibilityArray(vis);\n        vis->Delete();\n        if (this->MultiGroupDataInformation->HasInformation(\n              levelIdx, dataSetIdx))\n          {\n          vtkInformation* infotmp =\n            this->MultiGroupDataInformation->GetInformation(\n              levelIdx,dataSetIdx);\n          infotmp->Set(NUMBER_OF_BLANKED_POINTS(), numBlankedPts);\n          }\n        }\n      }\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkHierarchicalBoxDataSet::GetNumberOfPoints()\n{\n  vtkIdType numPts = 0;\n\n  unsigned int numLevels = this->GetNumberOfLevels();\n  for (unsigned int level=0; levelGetNumberOfDataSets(level);\n    for (unsigned int dataIdx=0; dataIdxMultiGroupDataInformation->GetInformation(level, dataIdx);\n      if (blockInfo)\n        {\n        if (blockInfo->Has(\n              vtkHierarchicalBoxDataSet::NUMBER_OF_BLANKED_POINTS()))\n          {\n          numBlankedPts = blockInfo->Get(NUMBER_OF_BLANKED_POINTS());\n          }\n        }\n      vtkDataSet* ds = vtkDataSet::SafeDownCast(\n        this->GetDataSet(level, dataIdx));\n      if (ds)\n        {\n        numPts += ds->GetNumberOfPoints() - numBlankedPts;\n        }\n      }\n    }\n\n  return numPts;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::ShallowCopy(vtkDataObject *src)\n{\n  if (src == this)\n    {\n    return;\n    }\n  this->InitializeDataSets();\n  this->Modified();\n\n  vtkHierarchicalBoxDataSet* from =\n    vtkHierarchicalBoxDataSet::SafeDownCast(src);\n  if (from)\n    {\n    \/\/ If the source is a vtkHierarchicalBoxDataSet, do not call\n    \/\/ superclass' ShallowCopy, instead skip to vtkCompositeDataSet's\n    \/\/ constructor\n    this->vtkCompositeDataSet::ShallowCopy(src);\n\n    unsigned int numLevels = from->GetNumberOfLevels();\n    this->SetNumberOfLevels(numLevels);\n    for (unsigned int i=0; iGetNumberOfDataSets(i);\n      this->SetNumberOfDataSets(i, numDataSets);\n      for (unsigned int j=0; jGetDataSet(i, j, box);\n        this->SetDataSet(i, j, box, grid);\n        }\n      }\n    }\n  else\n    {\n    this->Superclass::ShallowCopy(src);\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::DeepCopy(vtkDataObject *src)\n{\n  if (src == this)\n    {\n    return;\n    }\n  this->InitializeDataSets();\n  this->Modified();\n\n  vtkHierarchicalBoxDataSet* from =\n    vtkHierarchicalBoxDataSet::SafeDownCast(src);\n  if (from)\n    {\n    \/\/ If the source is a vtkHierarchicalBoxDataSet, do not call\n    \/\/ superclass' DeepCopy, instead skip to vtkCompositeDataSet's\n    \/\/ constructor\n    this->vtkCompositeDataSet::ShallowCopy(src);\n\n    unsigned int numLevels = from->GetNumberOfLevels();\n    this->SetNumberOfLevels(numLevels);\n    for (unsigned int i=0; iGetNumberOfDataSets(i);\n      this->SetNumberOfDataSets(i, numDataSets);\n      for (unsigned int j=0; jGetDataSet(i, j, box);\n        if (ds)\n          {\n          vtkUniformGrid* copy = ds->NewInstance();\n          copy->DeepCopy(ds);\n          this->SetDataSet(i, j, box, copy);\n          }\n        }\n      }\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHierarchicalBoxDataSet::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n  unsigned int numLevels = this->GetNumberOfLevels();\n  os << indent << \"Number of levels: \" <<  numLevels << endl;\n  for (unsigned int i=0; iGetNumberOfDataSets(i);\n    os << indent << \"Level \" << i << \" number of datasets: \" << numDataSets\n       << endl;\n    for (unsigned j=0; jGetDataSet(i, j);\n      if (dobj)\n        {\n        os << endl;\n        dobj->PrintSelf(os, indent.GetNextIndent());\n        }\n      else\n        {\n        os << \"(none)\" << endl;\n        }\n      }\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkHierarchicalBoxDataSet* vtkHierarchicalBoxDataSet::GetData(\n  vtkInformation* info)\n{\n  return\n    info?vtkHierarchicalBoxDataSet::SafeDownCast(info->Get(DATA_OBJECT())) : 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkHierarchicalBoxDataSet* vtkHierarchicalBoxDataSet::GetData(\n  vtkInformationVector* v, int i)\n{\n  return vtkHierarchicalBoxDataSet::GetData(v->GetInformationObject(i));\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Copy the cached scalar range into range.\nvoid vtkHierarchicalBoxDataSet::GetScalarRange(double range[2])\n{\n  this->ComputeScalarRange();\n  range[0]=this->ScalarRange[0];\n  range[1]=this->ScalarRange[1];\n}\n  \n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Return the cached range.\ndouble *vtkHierarchicalBoxDataSet::GetScalarRange()\n{\n  this->ComputeScalarRange();\n  return this->ScalarRange;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Compute the range of the scalars and cache it into ScalarRange\n\/\/ only if the cache became invalid (ScalarRangeComputeTime).\nvoid vtkHierarchicalBoxDataSet::ComputeScalarRange()\n{\n  if ( this->GetMTime() > this->ScalarRangeComputeTime )\n    {\n    double dataSetRange[2];\n    this->ScalarRange[0]=VTK_DOUBLE_MAX;\n    this->ScalarRange[1]=VTK_DOUBLE_MIN;\n    unsigned int level=0;\n    unsigned int levels=this->GetNumberOfLevels();\n    while(levelGetNumberOfDataSets(level);\n      while(dataset(this->GetDataSet(level,dataset));\n        ug->GetScalarRange(dataSetRange);\n        if(dataSetRange[0]ScalarRange[0])\n          {\n          this->ScalarRange[0]=dataSetRange[0];\n          }\n        if(dataSetRange[1]>this->ScalarRange[1])\n          {\n          this->ScalarRange[1]=dataSetRange[1];\n          }\n        ++dataset;\n        }\n      ++level;\n      }\n    this->ScalarRangeComputeTime.Modified();\n    }\n}\n<|endoftext|>"}
{"text":"#include \"map.h\"\n#include \n#include \"iterator.h\"\n\nusing namespace v8;\n\nvoid NodeMap::init(Local target) {\n    Nan::HandleScope scope;\n\n    Local constructor = Nan::New(Constructor);\n\n    \/\/ got to do the Symbol.iterator function by hand, no Nan support\n    Local symbol_iterator = Symbol::GetIterator(Isolate::GetCurrent());\n    Local entries_templt = Nan::New(\n        Entries\n        , Local()\n        , Nan::New(constructor));\n    constructor->PrototypeTemplate()->Set(symbol_iterator, entries_templt);\n    entries_templt->SetClassName(Nan::New(\"Symbol(Symbol.iterator)\").ToLocalChecked());\n\n    constructor->SetClassName(Nan::New(\"NodeMap\").ToLocalChecked());\n    constructor->InstanceTemplate()->SetInternalFieldCount(1);\n\n    Nan::SetPrototypeMethod(constructor, \"set\", Set);\n    Nan::SetPrototypeMethod(constructor, \"get\", Get);\n    Nan::SetPrototypeMethod(constructor, \"has\", Has);\n    Nan::SetPrototypeMethod(constructor, \"entries\", Entries);\n    Nan::SetPrototypeMethod(constructor, \"keys\", Keys);\n    Nan::SetPrototypeMethod(constructor, \"values\", Values);\n    Nan::SetPrototypeMethod(constructor, \"delete\", Delete);\n    Nan::SetPrototypeMethod(constructor, \"clear\", Clear);\n    Nan::SetPrototypeMethod(constructor, \"forEach\", ForEach);\n    Nan::SetAccessor(constructor->InstanceTemplate(), Nan::New(\"size\").ToLocalChecked(), Size);\n\n    target->Set(Nan::New(\"NodeMap\").ToLocalChecked(), constructor->GetFunction());\n\n    PairNodeIterator::init(target);\n}\n\nNodeMap::NodeMap() {\n    this->_version = 0;\n    this->_iterator_count = 0;\n}\n\nNodeMap::~NodeMap() {\n    for(MapType::const_iterator itr = this->_set.begin(); itr != this->_set.end(); ) {\n        itr = this->_set.erase(itr);\n    }\n}\n\nuint32_t NodeMap::StartIterator() {\n    uint32_t version = this->_version;\n    this->_version++;\n    if (this->_iterator_count == 0) {\n        \/\/ if this is the first iterator, set the max load facto to infinity\n        \/\/ so that a rehash doesn't happen while iterating\n        this->_old_load_factor = this->_set.max_load_factor();\n        this->_set.max_load_factor(std::numeric_limits::infinity());\n    }\n    this->_iterator_count++;\n\n    \/\/ return the latest version that should be valid for this iterator\n    return version;\n}\n\nvoid NodeMap::StopIterator() {\n    this->_iterator_count--;\n    if (this->_iterator_count != 0) {\n        return;\n    }\n    \/\/ that was the last iterator running, so now go through the whole set\n    \/\/ and actually delete anything marked for deletion\n    for(MapType::const_iterator itr = this->_set.begin(); itr != this->_set.end(); ) {\n        if (itr->IsDeleted()) {\n            itr = this->_set.erase(itr);\n        } else {\n            itr++;\n        }\n    }\n    \/\/ since it was the last iterator, reset the max load factor back\n    \/\/ to what it was before the first iterator, this might cause a\n    \/\/ rehash to happen\n    this->_set.max_load_factor(this->_old_load_factor);\n}\n\nMapType::const_iterator NodeMap::GetBegin() {\n    return this->_set.begin();\n}\n\nMapType::const_iterator NodeMap::GetEnd() {\n    return this->_set.end();\n}\n\nNAN_METHOD(NodeMap::Constructor) {\n    Nan::HandleScope scope;\n    NodeMap *obj = new NodeMap();\n\n    Local set = Nan::New(\"set\").ToLocalChecked();\n    Local next = Nan::New(\"next\").ToLocalChecked();\n    Local done = Nan::New(\"done\").ToLocalChecked();\n    Local value = Nan::New(\"value\").ToLocalChecked();\n    Local symbol_iterator = Symbol::GetIterator(Isolate::GetCurrent());\n    Local info0;\n    Local iter;\n    Local iter_obj;\n    Local value_arr;\n    Local func_args[2];\n    Local setter;\n    Local next_func;\n\n    obj->Wrap(info.This());\n    info.GetReturnValue().Set(info.This());\n\n    if(info.Length() == 0) {\n        return;\n    }\n\n    if (!info.This()->Has(set) || !Nan::Get(info.This(), set).ToLocalChecked()->IsFunction()) {\n        Nan::ThrowTypeError(\"Invalid set method\");\n        return;\n\n    }\n    setter = Nan::Get(info.This(), set).ToLocalChecked().As();\n    if (!info[0]->IsObject()) {\n        Nan::ThrowTypeError(\"Invalid argument\");\n        return;\n    }\n    info0 = Nan::To(info[0]).ToLocalChecked();\n    if (!info0->Has(symbol_iterator)) {\n        Nan::ThrowTypeError(\"Argument not iterable\");\n        return;\n    }\n\n    iter = Nan::To(Nan::Call(Nan::Get(info0, symbol_iterator).ToLocalChecked().As(), info0, 0, 0).ToLocalChecked()).ToLocalChecked();\n    next_func = Nan::Get(iter, next).ToLocalChecked().As();\n    iter_obj = Nan::Call(next_func, iter, 0, 0).ToLocalChecked()->ToObject();\n    while(!Nan::Get(iter_obj, done).ToLocalChecked()->BooleanValue()) {\n        if (Nan::Get(iter_obj, value).ToLocalChecked()->IsArray()) {\n            value_arr = Nan::Get(iter_obj, value).ToLocalChecked().As();\n            if (value_arr->Length() >= 2) {\n                func_args[0] = Nan::Get(value_arr, 0).ToLocalChecked();\n                func_args[1] = Nan::Get(value_arr, 1).ToLocalChecked();\n                Nan::Call(setter, info.This(), 2, func_args);\n            }\n        }\n        iter_obj = Nan::Call(next_func, iter, 0, 0).ToLocalChecked()->ToObject();\n    }\n    return;\n}\n\nNAN_METHOD(NodeMap::Get) {\n    Nan::HandleScope scope;\n\n    if (info.Length() < 1 || info[0]->IsUndefined() || info[0]->IsNull()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    VersionedPersistentPair persistent(obj->_version, info[0]);\n\n    MapType::const_iterator itr = obj->_set.find(persistent);\n    MapType::const_iterator end = obj->_set.end();\n\n    while(itr != end && itr->IsDeleted()) {\n        itr++;\n    }\n\n    if(itr == end || !info[0]->StrictEquals(itr->GetLocalKey())) {\n        \/\/do nothing and return undefined\n        info.GetReturnValue().Set(Nan::Undefined());\n        return;\n    }\n\n    info.GetReturnValue().Set(itr->GetLocalValue());\n    return;\n}\n\nNAN_METHOD(NodeMap::Has) {\n    Nan::HandleScope scope;\n\n    if (info.Length() < 1 || info[0]->IsUndefined() || info[0]->IsNull()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    VersionedPersistentPair persistent(obj->_version, info[0]);\n\n    MapType::const_iterator itr = obj->_set.find(persistent);\n    MapType::const_iterator end = obj->_set.end();\n\n    while(itr != end && itr->IsDeleted()) {\n        itr++;\n    }\n\n    if(itr == end || !info[0]->StrictEquals(itr->GetLocalKey())) {\n        \/\/do nothing and return false\n        info.GetReturnValue().Set(Nan::False());\n        return;\n    }\n\n    info.GetReturnValue().Set(Nan::True());\n    return;\n}\n\nNAN_METHOD(NodeMap::Set) {\n    Nan::HandleScope scope;\n\n    if (info.Length() < 2 || info[0]->IsUndefined() || info[0]->IsNull()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    VersionedPersistentPair persistent(obj->_version, info[0], info[1]);\n\n    MapType::const_iterator itr = obj->_set.find(persistent);\n    MapType::const_iterator end = obj->_set.end();\n\n    while(itr != end && itr->IsDeleted()) {\n        itr++;\n    }\n\n    if(itr != end && info[0]->StrictEquals(itr->GetLocalKey())) {\n        itr->ReplaceValue(obj->_version, info[1]);\n    } else {\n        obj->_set.insert(persistent);\n    }\n\n    \/\/Return this\n    info.GetReturnValue().Set(info.This());\n    return;\n}\n\nNAN_METHOD(NodeMap::Entries) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n    Local iter = PairNodeIterator::New(PairNodeIterator::KEY_TYPE | PairNodeIterator::VALUE_TYPE, obj);\n\n    info.GetReturnValue().Set(iter);\n    return;\n}\n\nNAN_METHOD(NodeMap::Keys) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n    Local iter = PairNodeIterator::New(PairNodeIterator::KEY_TYPE, obj);\n\n    info.GetReturnValue().Set(iter);\n    return;\n}\n\nNAN_METHOD(NodeMap::Values) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n    Local iter = PairNodeIterator::New(PairNodeIterator::VALUE_TYPE, obj);\n\n    info.GetReturnValue().Set(iter);\n    return;\n}\n\n\nNAN_METHOD(NodeMap::Delete) {\n    Nan::HandleScope scope;\n\n    if (info.Length() < 1 || info[0]->IsUndefined() || info[0]->IsNull()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    VersionedPersistentPair persistent(obj->_version, info[0]);\n    bool using_iterator = (obj->_iterator_count != 0);\n    bool ret;\n\n    if (using_iterator) {\n        obj->StartIterator();\n    }\n\n    MapType::const_iterator itr = obj->_set.find(persistent);\n    MapType::const_iterator end = obj->_set.end();\n\n    while(itr != end && itr->IsDeleted()) {\n        itr++;\n    }\n\n    ret = (itr != end && info[0]->StrictEquals(itr->GetLocalKey()));\n\n    if (using_iterator) {\n        if (ret) {\n            itr->Delete();\n        }\n        obj->StopIterator();\n    } else {\n        if (ret) {\n            obj->_set.erase(itr);\n        }\n    }\n\n    if (ret) {\n        info.GetReturnValue().Set(Nan::True());\n    } else {\n        info.GetReturnValue().Set(Nan::False());\n    }\n    return;\n}\n\nNAN_METHOD(NodeMap::Clear) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    bool using_iterator = (obj->_iterator_count != 0);\n\n    if (using_iterator) {\n        obj->StartIterator();\n    }\n\n    for(MapType::const_iterator itr = obj->_set.begin(); itr != obj->_set.end(); ) {\n        if (using_iterator) {\n            itr->Delete();\n            itr++;\n        } else {\n            itr = obj->_set.erase(itr);\n        }\n    }\n\n    if (using_iterator) {\n        obj->StopIterator();\n    }\n\n    info.GetReturnValue().Set(Nan::Undefined());\n    return;\n}\n\nNAN_GETTER(NodeMap::Size) {\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    uint32_t size = 0;\n    if (obj->_iterator_count == 0) {\n        size = obj->_set.size();\n        info.GetReturnValue().Set(Nan::New(size));\n        return;\n    }\n\n    MapType::const_iterator itr = obj->_set.begin();\n    MapType::const_iterator end = obj->_set.end();\n    for (; itr != end; itr++) {\n        if (itr->IsValid(obj->_version)) {\n            size += 1;\n        }\n    }\n\n    info.GetReturnValue().Set(Nan::New(size));\n    return;\n}\n\nNAN_METHOD(NodeMap::ForEach) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n    if (info.Length() < 1 || !info[0]->IsFunction()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n    Local cb = info[0].As();\n\n    Local ctx;\n    if (info.Length() > 1 && info[1]->IsObject()) {\n        ctx = info[1]->ToObject();\n    } else {\n        ctx = Nan::GetCurrentContext()->Global();\n    }\n\n    const unsigned argc = 3;\n    Local argv[argc];\n    argv[2] = info.This();\n\n    uint32_t version = obj->StartIterator();\n    MapType::const_iterator itr = obj->_set.begin();\n    MapType::const_iterator end = obj->_set.end();\n\n    while (itr != end) {\n        if (itr->IsValid(version)) {\n            argv[0] = itr->GetLocalValue();\n            argv[1] = itr->GetLocalKey();\n            cb->Call(ctx, argc, argv);\n        }\n        itr++;\n    }\n    obj->StopIterator();\n\n    info.GetReturnValue().Set(Nan::Undefined());\n    return;\n}\n\n\nextern \"C\" void\ninit (Local target) {\n    Nan::HandleScope scope;\n\n    NodeMap::init(target);\n}\n\nNODE_MODULE(map, init);\nValidate that constructor argument is an array of key-value entries#include \"map.h\"\n#include \n#include \"iterator.h\"\n\nusing namespace v8;\n\nvoid NodeMap::init(Local target) {\n    Nan::HandleScope scope;\n\n    Local constructor = Nan::New(Constructor);\n\n    \/\/ got to do the Symbol.iterator function by hand, no Nan support\n    Local symbol_iterator = Symbol::GetIterator(Isolate::GetCurrent());\n    Local entries_templt = Nan::New(\n        Entries\n        , Local()\n        , Nan::New(constructor));\n    constructor->PrototypeTemplate()->Set(symbol_iterator, entries_templt);\n    entries_templt->SetClassName(Nan::New(\"Symbol(Symbol.iterator)\").ToLocalChecked());\n\n    constructor->SetClassName(Nan::New(\"NodeMap\").ToLocalChecked());\n    constructor->InstanceTemplate()->SetInternalFieldCount(1);\n\n    Nan::SetPrototypeMethod(constructor, \"set\", Set);\n    Nan::SetPrototypeMethod(constructor, \"get\", Get);\n    Nan::SetPrototypeMethod(constructor, \"has\", Has);\n    Nan::SetPrototypeMethod(constructor, \"entries\", Entries);\n    Nan::SetPrototypeMethod(constructor, \"keys\", Keys);\n    Nan::SetPrototypeMethod(constructor, \"values\", Values);\n    Nan::SetPrototypeMethod(constructor, \"delete\", Delete);\n    Nan::SetPrototypeMethod(constructor, \"clear\", Clear);\n    Nan::SetPrototypeMethod(constructor, \"forEach\", ForEach);\n    Nan::SetAccessor(constructor->InstanceTemplate(), Nan::New(\"size\").ToLocalChecked(), Size);\n\n    target->Set(Nan::New(\"NodeMap\").ToLocalChecked(), constructor->GetFunction());\n\n    PairNodeIterator::init(target);\n}\n\nNodeMap::NodeMap() {\n    this->_version = 0;\n    this->_iterator_count = 0;\n}\n\nNodeMap::~NodeMap() {\n    for(MapType::const_iterator itr = this->_set.begin(); itr != this->_set.end(); ) {\n        itr = this->_set.erase(itr);\n    }\n}\n\nuint32_t NodeMap::StartIterator() {\n    uint32_t version = this->_version;\n    this->_version++;\n    if (this->_iterator_count == 0) {\n        \/\/ if this is the first iterator, set the max load facto to infinity\n        \/\/ so that a rehash doesn't happen while iterating\n        this->_old_load_factor = this->_set.max_load_factor();\n        this->_set.max_load_factor(std::numeric_limits::infinity());\n    }\n    this->_iterator_count++;\n\n    \/\/ return the latest version that should be valid for this iterator\n    return version;\n}\n\nvoid NodeMap::StopIterator() {\n    this->_iterator_count--;\n    if (this->_iterator_count != 0) {\n        return;\n    }\n    \/\/ that was the last iterator running, so now go through the whole set\n    \/\/ and actually delete anything marked for deletion\n    for(MapType::const_iterator itr = this->_set.begin(); itr != this->_set.end(); ) {\n        if (itr->IsDeleted()) {\n            itr = this->_set.erase(itr);\n        } else {\n            itr++;\n        }\n    }\n    \/\/ since it was the last iterator, reset the max load factor back\n    \/\/ to what it was before the first iterator, this might cause a\n    \/\/ rehash to happen\n    this->_set.max_load_factor(this->_old_load_factor);\n}\n\nMapType::const_iterator NodeMap::GetBegin() {\n    return this->_set.begin();\n}\n\nMapType::const_iterator NodeMap::GetEnd() {\n    return this->_set.end();\n}\n\nNAN_METHOD(NodeMap::Constructor) {\n    Nan::HandleScope scope;\n    NodeMap *obj = new NodeMap();\n\n    Local set = Nan::New(\"set\").ToLocalChecked();\n    Local next = Nan::New(\"next\").ToLocalChecked();\n    Local done = Nan::New(\"done\").ToLocalChecked();\n    Local value = Nan::New(\"value\").ToLocalChecked();\n    Local symbol_iterator = Symbol::GetIterator(Isolate::GetCurrent());\n    Local info0;\n    Local iter;\n    Local iter_obj;\n    Local value_arr;\n    Local func_args[2];\n    Local setter;\n    Local next_func;\n\n    obj->Wrap(info.This());\n    info.GetReturnValue().Set(info.This());\n\n    if(info.Length() == 0) {\n        return;\n    }\n\n    if (!info.This()->Has(set) || !Nan::Get(info.This(), set).ToLocalChecked()->IsFunction()) {\n        Nan::ThrowTypeError(\"Invalid set method\");\n        return;\n\n    }\n    setter = Nan::Get(info.This(), set).ToLocalChecked().As();\n    if (!info[0]->IsObject()) {\n        Nan::ThrowTypeError(\"Invalid argument\");\n        return;\n    }\n    info0 = Nan::To(info[0]).ToLocalChecked();\n    if (!info0->Has(symbol_iterator)) {\n        Nan::ThrowTypeError(\"Argument not iterable\");\n        return;\n    }\n\n    iter = Nan::To(Nan::Call(Nan::Get(info0, symbol_iterator).ToLocalChecked().As(), info0, 0, 0).ToLocalChecked()).ToLocalChecked();\n    next_func = Nan::Get(iter, next).ToLocalChecked().As();\n    iter_obj = Nan::Call(next_func, iter, 0, 0).ToLocalChecked()->ToObject();\n    while(!Nan::Get(iter_obj, done).ToLocalChecked()->BooleanValue()) {\n        if (Nan::Get(iter_obj, value).ToLocalChecked()->IsArray()) {\n            value_arr = Nan::Get(iter_obj, value).ToLocalChecked().As();\n            if (value_arr->Length() >= 2) {\n                func_args[0] = Nan::Get(value_arr, 0).ToLocalChecked();\n                func_args[1] = Nan::Get(value_arr, 1).ToLocalChecked();\n                Nan::Call(setter, info.This(), 2, func_args);\n            } else {\n              Nan::ThrowTypeError(\"Iterator contains non-entry object\");\n              return;\n            }\n        } else {\n          Nan::ThrowTypeError(\"Iterator contains non-entry object\");\n          return;\n        }\n        iter_obj = Nan::Call(next_func, iter, 0, 0).ToLocalChecked()->ToObject();\n    }\n    return;\n}\n\nNAN_METHOD(NodeMap::Get) {\n    Nan::HandleScope scope;\n\n    if (info.Length() < 1 || info[0]->IsUndefined() || info[0]->IsNull()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    VersionedPersistentPair persistent(obj->_version, info[0]);\n\n    MapType::const_iterator itr = obj->_set.find(persistent);\n    MapType::const_iterator end = obj->_set.end();\n\n    while(itr != end && itr->IsDeleted()) {\n        itr++;\n    }\n\n    if(itr == end || !info[0]->StrictEquals(itr->GetLocalKey())) {\n        \/\/do nothing and return undefined\n        info.GetReturnValue().Set(Nan::Undefined());\n        return;\n    }\n\n    info.GetReturnValue().Set(itr->GetLocalValue());\n    return;\n}\n\nNAN_METHOD(NodeMap::Has) {\n    Nan::HandleScope scope;\n\n    if (info.Length() < 1 || info[0]->IsUndefined() || info[0]->IsNull()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    VersionedPersistentPair persistent(obj->_version, info[0]);\n\n    MapType::const_iterator itr = obj->_set.find(persistent);\n    MapType::const_iterator end = obj->_set.end();\n\n    while(itr != end && itr->IsDeleted()) {\n        itr++;\n    }\n\n    if(itr == end || !info[0]->StrictEquals(itr->GetLocalKey())) {\n        \/\/do nothing and return false\n        info.GetReturnValue().Set(Nan::False());\n        return;\n    }\n\n    info.GetReturnValue().Set(Nan::True());\n    return;\n}\n\nNAN_METHOD(NodeMap::Set) {\n    Nan::HandleScope scope;\n\n    if (info.Length() < 2 || info[0]->IsUndefined() || info[0]->IsNull()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    VersionedPersistentPair persistent(obj->_version, info[0], info[1]);\n\n    MapType::const_iterator itr = obj->_set.find(persistent);\n    MapType::const_iterator end = obj->_set.end();\n\n    while(itr != end && itr->IsDeleted()) {\n        itr++;\n    }\n\n    if(itr != end && info[0]->StrictEquals(itr->GetLocalKey())) {\n        itr->ReplaceValue(obj->_version, info[1]);\n    } else {\n        obj->_set.insert(persistent);\n    }\n\n    \/\/Return this\n    info.GetReturnValue().Set(info.This());\n    return;\n}\n\nNAN_METHOD(NodeMap::Entries) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n    Local iter = PairNodeIterator::New(PairNodeIterator::KEY_TYPE | PairNodeIterator::VALUE_TYPE, obj);\n\n    info.GetReturnValue().Set(iter);\n    return;\n}\n\nNAN_METHOD(NodeMap::Keys) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n    Local iter = PairNodeIterator::New(PairNodeIterator::KEY_TYPE, obj);\n\n    info.GetReturnValue().Set(iter);\n    return;\n}\n\nNAN_METHOD(NodeMap::Values) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n    Local iter = PairNodeIterator::New(PairNodeIterator::VALUE_TYPE, obj);\n\n    info.GetReturnValue().Set(iter);\n    return;\n}\n\n\nNAN_METHOD(NodeMap::Delete) {\n    Nan::HandleScope scope;\n\n    if (info.Length() < 1 || info[0]->IsUndefined() || info[0]->IsNull()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    VersionedPersistentPair persistent(obj->_version, info[0]);\n    bool using_iterator = (obj->_iterator_count != 0);\n    bool ret;\n\n    if (using_iterator) {\n        obj->StartIterator();\n    }\n\n    MapType::const_iterator itr = obj->_set.find(persistent);\n    MapType::const_iterator end = obj->_set.end();\n\n    while(itr != end && itr->IsDeleted()) {\n        itr++;\n    }\n\n    ret = (itr != end && info[0]->StrictEquals(itr->GetLocalKey()));\n\n    if (using_iterator) {\n        if (ret) {\n            itr->Delete();\n        }\n        obj->StopIterator();\n    } else {\n        if (ret) {\n            obj->_set.erase(itr);\n        }\n    }\n\n    if (ret) {\n        info.GetReturnValue().Set(Nan::True());\n    } else {\n        info.GetReturnValue().Set(Nan::False());\n    }\n    return;\n}\n\nNAN_METHOD(NodeMap::Clear) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    bool using_iterator = (obj->_iterator_count != 0);\n\n    if (using_iterator) {\n        obj->StartIterator();\n    }\n\n    for(MapType::const_iterator itr = obj->_set.begin(); itr != obj->_set.end(); ) {\n        if (using_iterator) {\n            itr->Delete();\n            itr++;\n        } else {\n            itr = obj->_set.erase(itr);\n        }\n    }\n\n    if (using_iterator) {\n        obj->StopIterator();\n    }\n\n    info.GetReturnValue().Set(Nan::Undefined());\n    return;\n}\n\nNAN_GETTER(NodeMap::Size) {\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n    uint32_t size = 0;\n    if (obj->_iterator_count == 0) {\n        size = obj->_set.size();\n        info.GetReturnValue().Set(Nan::New(size));\n        return;\n    }\n\n    MapType::const_iterator itr = obj->_set.begin();\n    MapType::const_iterator end = obj->_set.end();\n    for (; itr != end; itr++) {\n        if (itr->IsValid(obj->_version)) {\n            size += 1;\n        }\n    }\n\n    info.GetReturnValue().Set(Nan::New(size));\n    return;\n}\n\nNAN_METHOD(NodeMap::ForEach) {\n    Nan::HandleScope scope;\n\n    NodeMap *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n    if (info.Length() < 1 || !info[0]->IsFunction()) {\n        Nan::ThrowTypeError(\"Wrong arguments\");\n        return;\n    }\n    Local cb = info[0].As();\n\n    Local ctx;\n    if (info.Length() > 1 && info[1]->IsObject()) {\n        ctx = info[1]->ToObject();\n    } else {\n        ctx = Nan::GetCurrentContext()->Global();\n    }\n\n    const unsigned argc = 3;\n    Local argv[argc];\n    argv[2] = info.This();\n\n    uint32_t version = obj->StartIterator();\n    MapType::const_iterator itr = obj->_set.begin();\n    MapType::const_iterator end = obj->_set.end();\n\n    while (itr != end) {\n        if (itr->IsValid(version)) {\n            argv[0] = itr->GetLocalValue();\n            argv[1] = itr->GetLocalKey();\n            cb->Call(ctx, argc, argv);\n        }\n        itr++;\n    }\n    obj->StopIterator();\n\n    info.GetReturnValue().Set(Nan::Undefined());\n    return;\n}\n\n\nextern \"C\" void\ninit (Local target) {\n    Nan::HandleScope scope;\n\n    NodeMap::init(target);\n}\n\nNODE_MODULE(map, init);\n<|endoftext|>"}
{"text":"#include \n#include \"ClassWrappers.hpp\"\n\n\nnamespace Urho3D\n{\n\nclass ManagedObjectFactory : public ObjectFactory\n{\npublic:\n    ManagedObjectFactory(Context* context, const char* typeName, StringHash baseType)\n        : ObjectFactory(context)\n        , baseType_(baseType)\n        , managedType_(typeName)\n    {\n        typeInfo_ = new TypeInfo(typeName, context_->GetScripts()->GetRegisteredType(baseType));\n    }\n\n    ~ManagedObjectFactory() override\n    {\n        delete typeInfo_;\n    }\n\npublic:\n    SharedPtr CreateObject() override\n    {\n        return SharedPtr(context_->GetScripts()->CreateObject(context_, managedType_.Value()));\n    }\n\nprotected:\n    StringHash baseType_;\n    StringHash managedType_;\n};\n\nclass ManagedEventHandler : public EventHandler\n{\npublic:\n    ManagedEventHandler(Object* receiver, void* gcHandle, void(*function)(void*, StringHash, VariantMap*))\n        : EventHandler(receiver, nullptr)\n        , function_(function)\n        , gcHandle_(gcHandle)\n    {\n    }\n\n    ~ManagedEventHandler() override\n    {\n        receiver_->GetScripts()->FreeGCHandle(gcHandle_);\n        gcHandle_ = nullptr;\n    }\n\n    void Invoke(VariantMap& eventData) override\n    {\n        function_(gcHandle_, eventType_, &eventData);\n    }\n\n    EventHandler* Clone() const override\n    {\n        return new ManagedEventHandler(receiver_, receiver_->GetScripts()->CloneGCHandle(gcHandle_), function_);\n    }\n\npublic:\n\nprotected:\n    void* gcHandle_ = nullptr;\n    void(*function_)(void*, StringHash, VariantMap*) = nullptr;\n};\n\n}\n\nextern \"C\"\n{\n\nvoid Urho3D_Context_RegisterFactory(Context* context, MonoString* typeName, unsigned baseType,\n    const char* category)\n{\n    context->RegisterFactory(new Urho3D::ManagedObjectFactory(context, CSharpConverter::FromCSharp(typeName), StringHash(baseType)), category);\n}\n\nvoid Urho3D_Object_SubscribeToEvent(Object* receiver, void* gcHandle, unsigned eventType,\n    void(*function)(void*, StringHash, VariantMap*), Object* sender)\n{\n    \/\/ gcHandle is a handle to Action<> which references receiver object. We have to ensure object is alive as long as\n    \/\/ engine will be sending events to it. On the other hand pinning receiver object is not required as it's lifetime\n    \/\/ is managed by user or engine. If such object is deallocated it will simply stop sending events.\n    if (sender == nullptr)\n        receiver->SubscribeToEvent(StringHash(eventType), new ManagedEventHandler(receiver, gcHandle, function));\n    else\n        receiver->SubscribeToEvent(sender, StringHash(eventType), new ManagedEventHandler(receiver, gcHandle, function));\n}\n\nvoid RegisterObjectInternalCalls(Context* context)\n{\n    MONO_INTERNAL_CALL(Urho3D.Context, Urho3D_Context_RegisterFactory);\n    MONO_INTERNAL_CALL(Urho3D.Object, Urho3D_Object_SubscribeToEvent);\n}\n\n}\nCSharp: Fix category string conversion in factory registration.#include \n#include \"ClassWrappers.hpp\"\n\n\nnamespace Urho3D\n{\n\nclass ManagedObjectFactory : public ObjectFactory\n{\npublic:\n    ManagedObjectFactory(Context* context, const char* typeName, StringHash baseType)\n        : ObjectFactory(context)\n        , baseType_(baseType)\n        , managedType_(typeName)\n    {\n        typeInfo_ = new TypeInfo(typeName, context_->GetScripts()->GetRegisteredType(baseType));\n    }\n\n    ~ManagedObjectFactory() override\n    {\n        delete typeInfo_;\n    }\n\npublic:\n    SharedPtr CreateObject() override\n    {\n        return SharedPtr(context_->GetScripts()->CreateObject(context_, managedType_.Value()));\n    }\n\nprotected:\n    StringHash baseType_;\n    StringHash managedType_;\n};\n\nclass ManagedEventHandler : public EventHandler\n{\npublic:\n    ManagedEventHandler(Object* receiver, void* gcHandle, void(*function)(void*, StringHash, VariantMap*))\n        : EventHandler(receiver, nullptr)\n        , function_(function)\n        , gcHandle_(gcHandle)\n    {\n    }\n\n    ~ManagedEventHandler() override\n    {\n        receiver_->GetScripts()->FreeGCHandle(gcHandle_);\n        gcHandle_ = nullptr;\n    }\n\n    void Invoke(VariantMap& eventData) override\n    {\n        function_(gcHandle_, eventType_, &eventData);\n    }\n\n    EventHandler* Clone() const override\n    {\n        return new ManagedEventHandler(receiver_, receiver_->GetScripts()->CloneGCHandle(gcHandle_), function_);\n    }\n\npublic:\n\nprotected:\n    void* gcHandle_ = nullptr;\n    void(*function_)(void*, StringHash, VariantMap*) = nullptr;\n};\n\n}\n\nextern \"C\"\n{\n\nvoid Urho3D_Context_RegisterFactory(Context* context, MonoString* typeName, unsigned baseType,\n                                    MonoString* category)\n{\n    context->RegisterFactory(new Urho3D::ManagedObjectFactory(context,\n        CSharpConverter::FromCSharp(typeName), StringHash(baseType)),\n        CSharpConverter::FromCSharp(category));\n}\n\nvoid Urho3D_Object_SubscribeToEvent(Object* receiver, void* gcHandle, unsigned eventType,\n    void(*function)(void*, StringHash, VariantMap*), Object* sender)\n{\n    \/\/ gcHandle is a handle to Action<> which references receiver object. We have to ensure object is alive as long as\n    \/\/ engine will be sending events to it. On the other hand pinning receiver object is not required as it's lifetime\n    \/\/ is managed by user or engine. If such object is deallocated it will simply stop sending events.\n    if (sender == nullptr)\n        receiver->SubscribeToEvent(StringHash(eventType), new ManagedEventHandler(receiver, gcHandle, function));\n    else\n        receiver->SubscribeToEvent(sender, StringHash(eventType), new ManagedEventHandler(receiver, gcHandle, function));\n}\n\nvoid RegisterObjectInternalCalls(Context* context)\n{\n    MONO_INTERNAL_CALL(Urho3D.Context, Urho3D_Context_RegisterFactory);\n    MONO_INTERNAL_CALL(Urho3D.Object, Urho3D_Object_SubscribeToEvent);\n}\n\n}\n<|endoftext|>"}
{"text":"Remove Dead Code<|endoftext|>"}
{"text":"-Werror,-Wunused-member-function<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: privsplt.cxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: kz $ $Date: 2006-07-21 13:58:33 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n#include \"privsplt.hxx\"\n\n\/*************************************************************************\n#*  Member:     ScPrivatSplit                               Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     MD_Test\n#*\n#*  Funktion:   Konstruktor der Klasse ScPrivatSplit\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\n\nScPrivatSplit::ScPrivatSplit( Window* pParent, const ResId& rResId,\n                             SC_SPLIT_DIRECTION eSplit):\n                        Control( pParent, rResId )\n{\n    Point aPos=GetPosPixel();\n    nOldX=(short)aPos.X();\n    nOldY=(short)aPos.Y();\n    nNewX=(short)aPos.X();\n    nNewY=(short)aPos.Y();\n    eScSplit=eSplit;\n    aXMovingRange.Min()=nNewX;\n    aXMovingRange.Max()=nNewX;\n    aYMovingRange.Min()=nNewY;\n    aYMovingRange.Max()=nNewY;\n\n    aWinPointer=GetPointer();\n\n    aMovingFlag=FALSE;\n    if(eScSplit==SC_SPLIT_HORZ)\n    {\n        aWinPointer=Pointer(POINTER_HSPLIT);\n    }\n    else\n    {\n        aWinPointer=Pointer(POINTER_VSPLIT);\n    }\n    SetPointer(aWinPointer);\n}\n\n\n\/*************************************************************************\n#*  Member:     MouseButtonDown                         Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Reagiert auf einen einzelnen Mouse-Event. Nach Aufruf\n#*              werden alle Mauseingaben an dieses Control weitergeleitet.\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\n\nvoid ScPrivatSplit::MouseButtonDown( const MouseEvent& rMEvt )\n{\n    Point aPos=LogicToPixel(rMEvt.GetPosPixel());\n\n    nOldX=(short)aPos.X();\n    nOldY=(short)aPos.Y();\n\n    CaptureMouse();\n}\n\n\/*************************************************************************\n#*  Member:     MouseButtonUp                           Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Ende einer Benutzeraktion mit der Maus. Es werden\n#*              die aktuelle Maus- Koordinaten ermittelt und fuer\n#*              die Verschiebung des Fensters verwendet.\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\n\nvoid ScPrivatSplit::MouseButtonUp( const MouseEvent& rMEvt )\n{\n    ReleaseMouse();\n\n    Point aPos=LogicToPixel(rMEvt.GetPosPixel());\n    Point a2Pos=GetPosPixel();\n    Point a3Pos=a2Pos;\n\n    if(eScSplit==SC_SPLIT_HORZ)\n    {\n        nNewX=(short)aPos.X();\n        nDeltaX=nNewX-nOldX;\n        a2Pos.X()+=nDeltaX;\n        if(a2Pos.X()aXMovingRange.Max())\n        {\n            nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());\n            a2Pos.X()=aXMovingRange.Max();\n        }\n    }\n    else\n    {\n        nNewY=(short)aPos.Y();\n        nDeltaY=nNewY-nOldY;\n        a2Pos.Y()+=nDeltaY;\n        if(a2Pos.Y()aYMovingRange.Max())\n        {\n            nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());\n            a2Pos.Y()=aYMovingRange.Max();\n        }\n    }\n    SetPosPixel(a2Pos);\n    Invalidate();\n    Update();\n    CtrModified();\n}\n\n\/*************************************************************************\n#*  Member:     MouseMove                                   Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Reagiert kontinuierlich auf Mausbewegungen. Es werden\n#*              die aktuelle Maus- Koordinaten ermittelt und fuer\n#*              die Verschiebung des Fensters verwendet.\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\n\nvoid ScPrivatSplit::MouseMove( const MouseEvent& rMEvt )\n{\n    Point aPos=LogicToPixel(rMEvt.GetPosPixel());\n    Point a2Pos=GetPosPixel();\n    Point a3Pos=a2Pos;\n    if(rMEvt.IsLeft())\n    {\n        if(eScSplit==SC_SPLIT_HORZ)\n        {\n            nNewX=(short)aPos.X();\n            nDeltaX=nNewX-nOldX;\n            a2Pos.X()+=nDeltaX;\n\n            if(a2Pos.X()aXMovingRange.Max())\n            {\n                nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());\n                a2Pos.X()=aXMovingRange.Max();\n            }\n        }\n        else\n        {\n            nNewY=(short)aPos.Y();\n            nDeltaY=nNewY-nOldY;\n            a2Pos.Y()+=nDeltaY;\n            if(a2Pos.Y()aYMovingRange.Max())\n            {\n                nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());\n                a2Pos.Y()=aYMovingRange.Max();\n            }\n        }\n\n        SetPosPixel(a2Pos);\n\n        CtrModified();\n        Invalidate();\n        Update();\n    }\n}\n\n\/*************************************************************************\n#*  Member:     SetXRange                                   Datum:14.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Setzt den Range fuer die X- Verschiebung\n#*\n#*  Input:      neuer Bereich\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nvoid ScPrivatSplit::SetXRange(Range cRgeX)\n{\n    aXMovingRange=cRgeX;\n}\n\n\/*************************************************************************\n#*  Member:     SetYRange                                   Datum:14.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Setzt den Range fuer die Y- Verschiebung\n#*\n#*  Input:      neuer Bereich\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nvoid ScPrivatSplit::SetYRange(Range cRgeY)\n{\n    aYMovingRange=cRgeY;\n}\n\n\n\n\/*************************************************************************\n#*  Member:     GetDeltaY                                   Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Liefert die relative x-Verschiebung zurueck\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nshort ScPrivatSplit::GetDeltaX()\n{\n    return nDeltaX;\n}\n\n\/*************************************************************************\n#*  Member:     GetDeltaY                                   Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Liefert die relative y-Verschiebung zurueck\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nshort ScPrivatSplit::GetDeltaY()\n{\n    return nDeltaY;\n}\n\n\/*************************************************************************\n#*  Member:     CtrModified                                 Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Teilt einem installierten Handler mit, dass\n#*              eine Veraenderung eingetreten ist.\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nvoid ScPrivatSplit::CtrModified()\n{\n    aCtrModifiedLink.Call( this );\n}\n\nvoid ScPrivatSplit::MoveSplitTo(Point aPos)\n{\n    Point a2Pos=GetPosPixel();\n    nOldX=(short)a2Pos.X();\n    nOldY=(short)a2Pos.Y();\n    Point a3Pos=a2Pos;\n\n    if(eScSplit==SC_SPLIT_HORZ)\n    {\n        nNewX=(short)aPos.X();\n        nDeltaX=nNewX-nOldX;\n        a2Pos.X()+=nDeltaX;\n        if(a2Pos.X()aXMovingRange.Max())\n        {\n            nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());\n            a2Pos.X()=aXMovingRange.Max();\n        }\n    }\n    else\n    {\n        nNewY=(short)aPos.Y();\n        nDeltaY=nNewY-nOldY;\n        a2Pos.Y()+=nDeltaY;\n        if(a2Pos.Y()aYMovingRange.Max())\n        {\n            nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());\n            a2Pos.Y()=aYMovingRange.Max();\n        }\n    }\n    SetPosPixel(a2Pos);\n    Invalidate();\n    Update();\n    CtrModified();\n}\n\n\nvoid ScPrivatSplit::ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground )\n{\n    const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();\n\n    if ( bFont )\n    {\n        Font aFont = rStyleSettings.GetAppFont();\n        if ( IsControlFont() )\n            aFont.Merge( GetControlFont() );\n        SetFont( aFont );\n    }\n\n    if ( bFont || bForeground )\n    {\n        Color aTextColor = rStyleSettings.GetButtonTextColor();\n        if ( IsControlForeground() )\n            aTextColor = GetControlForeground();\n        SetTextColor( aTextColor );\n    }\n\n    if ( bBackground )\n    {\n        SetBackground( rStyleSettings.GetFaceColor());\n    }\n    if ( IsBackground() )\n    {\n        SetFillColor( GetBackground().GetColor() );\n        SetBackground();\n    }\n    Invalidate();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ScPrivatSplit::StateChanged( StateChangedType nType )\n{\n    if ( (nType == STATE_CHANGE_ZOOM) ||\n         (nType == STATE_CHANGE_CONTROLFONT) )\n    {\n        ImplInitSettings( TRUE, FALSE, FALSE );\n        Invalidate();\n    }\n    if ( nType == STATE_CHANGE_CONTROLFOREGROUND )\n    {\n        ImplInitSettings( FALSE, TRUE, FALSE );\n        Invalidate();\n    }\n    else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )\n    {\n        ImplInitSettings( FALSE, FALSE, TRUE );\n        Invalidate();\n    }\n\n    Control::StateChanged( nType );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ScPrivatSplit::DataChanged( const DataChangedEvent& rDCEvt )\n{\n    if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&\n         (rDCEvt.GetFlags() & SETTINGS_STYLE) )\n    {\n        ImplInitSettings( TRUE, TRUE, TRUE );\n        Invalidate();\n    }\n    else\n        Window::DataChanged( rDCEvt );\n}\n\n\nINTEGRATION: CWS changefileheader (1.3.492); FILE MERGED 2008\/03\/31 17:15:37 rt 1.3.492.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: privsplt.cxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n#include \"privsplt.hxx\"\n\n\/*************************************************************************\n#*  Member:     ScPrivatSplit                               Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     MD_Test\n#*\n#*  Funktion:   Konstruktor der Klasse ScPrivatSplit\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\n\nScPrivatSplit::ScPrivatSplit( Window* pParent, const ResId& rResId,\n                             SC_SPLIT_DIRECTION eSplit):\n                        Control( pParent, rResId )\n{\n    Point aPos=GetPosPixel();\n    nOldX=(short)aPos.X();\n    nOldY=(short)aPos.Y();\n    nNewX=(short)aPos.X();\n    nNewY=(short)aPos.Y();\n    eScSplit=eSplit;\n    aXMovingRange.Min()=nNewX;\n    aXMovingRange.Max()=nNewX;\n    aYMovingRange.Min()=nNewY;\n    aYMovingRange.Max()=nNewY;\n\n    aWinPointer=GetPointer();\n\n    aMovingFlag=FALSE;\n    if(eScSplit==SC_SPLIT_HORZ)\n    {\n        aWinPointer=Pointer(POINTER_HSPLIT);\n    }\n    else\n    {\n        aWinPointer=Pointer(POINTER_VSPLIT);\n    }\n    SetPointer(aWinPointer);\n}\n\n\n\/*************************************************************************\n#*  Member:     MouseButtonDown                         Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Reagiert auf einen einzelnen Mouse-Event. Nach Aufruf\n#*              werden alle Mauseingaben an dieses Control weitergeleitet.\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\n\nvoid ScPrivatSplit::MouseButtonDown( const MouseEvent& rMEvt )\n{\n    Point aPos=LogicToPixel(rMEvt.GetPosPixel());\n\n    nOldX=(short)aPos.X();\n    nOldY=(short)aPos.Y();\n\n    CaptureMouse();\n}\n\n\/*************************************************************************\n#*  Member:     MouseButtonUp                           Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Ende einer Benutzeraktion mit der Maus. Es werden\n#*              die aktuelle Maus- Koordinaten ermittelt und fuer\n#*              die Verschiebung des Fensters verwendet.\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\n\nvoid ScPrivatSplit::MouseButtonUp( const MouseEvent& rMEvt )\n{\n    ReleaseMouse();\n\n    Point aPos=LogicToPixel(rMEvt.GetPosPixel());\n    Point a2Pos=GetPosPixel();\n    Point a3Pos=a2Pos;\n\n    if(eScSplit==SC_SPLIT_HORZ)\n    {\n        nNewX=(short)aPos.X();\n        nDeltaX=nNewX-nOldX;\n        a2Pos.X()+=nDeltaX;\n        if(a2Pos.X()aXMovingRange.Max())\n        {\n            nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());\n            a2Pos.X()=aXMovingRange.Max();\n        }\n    }\n    else\n    {\n        nNewY=(short)aPos.Y();\n        nDeltaY=nNewY-nOldY;\n        a2Pos.Y()+=nDeltaY;\n        if(a2Pos.Y()aYMovingRange.Max())\n        {\n            nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());\n            a2Pos.Y()=aYMovingRange.Max();\n        }\n    }\n    SetPosPixel(a2Pos);\n    Invalidate();\n    Update();\n    CtrModified();\n}\n\n\/*************************************************************************\n#*  Member:     MouseMove                                   Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Reagiert kontinuierlich auf Mausbewegungen. Es werden\n#*              die aktuelle Maus- Koordinaten ermittelt und fuer\n#*              die Verschiebung des Fensters verwendet.\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\n\nvoid ScPrivatSplit::MouseMove( const MouseEvent& rMEvt )\n{\n    Point aPos=LogicToPixel(rMEvt.GetPosPixel());\n    Point a2Pos=GetPosPixel();\n    Point a3Pos=a2Pos;\n    if(rMEvt.IsLeft())\n    {\n        if(eScSplit==SC_SPLIT_HORZ)\n        {\n            nNewX=(short)aPos.X();\n            nDeltaX=nNewX-nOldX;\n            a2Pos.X()+=nDeltaX;\n\n            if(a2Pos.X()aXMovingRange.Max())\n            {\n                nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());\n                a2Pos.X()=aXMovingRange.Max();\n            }\n        }\n        else\n        {\n            nNewY=(short)aPos.Y();\n            nDeltaY=nNewY-nOldY;\n            a2Pos.Y()+=nDeltaY;\n            if(a2Pos.Y()aYMovingRange.Max())\n            {\n                nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());\n                a2Pos.Y()=aYMovingRange.Max();\n            }\n        }\n\n        SetPosPixel(a2Pos);\n\n        CtrModified();\n        Invalidate();\n        Update();\n    }\n}\n\n\/*************************************************************************\n#*  Member:     SetXRange                                   Datum:14.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Setzt den Range fuer die X- Verschiebung\n#*\n#*  Input:      neuer Bereich\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nvoid ScPrivatSplit::SetXRange(Range cRgeX)\n{\n    aXMovingRange=cRgeX;\n}\n\n\/*************************************************************************\n#*  Member:     SetYRange                                   Datum:14.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Setzt den Range fuer die Y- Verschiebung\n#*\n#*  Input:      neuer Bereich\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nvoid ScPrivatSplit::SetYRange(Range cRgeY)\n{\n    aYMovingRange=cRgeY;\n}\n\n\n\n\/*************************************************************************\n#*  Member:     GetDeltaY                                   Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Liefert die relative x-Verschiebung zurueck\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nshort ScPrivatSplit::GetDeltaX()\n{\n    return nDeltaX;\n}\n\n\/*************************************************************************\n#*  Member:     GetDeltaY                                   Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Liefert die relative y-Verschiebung zurueck\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nshort ScPrivatSplit::GetDeltaY()\n{\n    return nDeltaY;\n}\n\n\/*************************************************************************\n#*  Member:     CtrModified                                 Datum:13.10.97\n#*------------------------------------------------------------------------\n#*\n#*  Klasse:     ScPrivatSplit\n#*\n#*  Funktion:   Teilt einem installierten Handler mit, dass\n#*              eine Veraenderung eingetreten ist.\n#*\n#*  Input:      ---\n#*\n#*  Output:     ---\n#*\n#************************************************************************\/\nvoid ScPrivatSplit::CtrModified()\n{\n    aCtrModifiedLink.Call( this );\n}\n\nvoid ScPrivatSplit::MoveSplitTo(Point aPos)\n{\n    Point a2Pos=GetPosPixel();\n    nOldX=(short)a2Pos.X();\n    nOldY=(short)a2Pos.Y();\n    Point a3Pos=a2Pos;\n\n    if(eScSplit==SC_SPLIT_HORZ)\n    {\n        nNewX=(short)aPos.X();\n        nDeltaX=nNewX-nOldX;\n        a2Pos.X()+=nDeltaX;\n        if(a2Pos.X()aXMovingRange.Max())\n        {\n            nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());\n            a2Pos.X()=aXMovingRange.Max();\n        }\n    }\n    else\n    {\n        nNewY=(short)aPos.Y();\n        nDeltaY=nNewY-nOldY;\n        a2Pos.Y()+=nDeltaY;\n        if(a2Pos.Y()aYMovingRange.Max())\n        {\n            nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());\n            a2Pos.Y()=aYMovingRange.Max();\n        }\n    }\n    SetPosPixel(a2Pos);\n    Invalidate();\n    Update();\n    CtrModified();\n}\n\n\nvoid ScPrivatSplit::ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground )\n{\n    const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();\n\n    if ( bFont )\n    {\n        Font aFont = rStyleSettings.GetAppFont();\n        if ( IsControlFont() )\n            aFont.Merge( GetControlFont() );\n        SetFont( aFont );\n    }\n\n    if ( bFont || bForeground )\n    {\n        Color aTextColor = rStyleSettings.GetButtonTextColor();\n        if ( IsControlForeground() )\n            aTextColor = GetControlForeground();\n        SetTextColor( aTextColor );\n    }\n\n    if ( bBackground )\n    {\n        SetBackground( rStyleSettings.GetFaceColor());\n    }\n    if ( IsBackground() )\n    {\n        SetFillColor( GetBackground().GetColor() );\n        SetBackground();\n    }\n    Invalidate();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ScPrivatSplit::StateChanged( StateChangedType nType )\n{\n    if ( (nType == STATE_CHANGE_ZOOM) ||\n         (nType == STATE_CHANGE_CONTROLFONT) )\n    {\n        ImplInitSettings( TRUE, FALSE, FALSE );\n        Invalidate();\n    }\n    if ( nType == STATE_CHANGE_CONTROLFOREGROUND )\n    {\n        ImplInitSettings( FALSE, TRUE, FALSE );\n        Invalidate();\n    }\n    else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )\n    {\n        ImplInitSettings( FALSE, FALSE, TRUE );\n        Invalidate();\n    }\n\n    Control::StateChanged( nType );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ScPrivatSplit::DataChanged( const DataChangedEvent& rDCEvt )\n{\n    if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&\n         (rDCEvt.GetFlags() & SETTINGS_STYLE) )\n    {\n        ImplInitSettings( TRUE, TRUE, TRUE );\n        Invalidate();\n    }\n    else\n        Window::DataChanged( rDCEvt );\n}\n\n\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  $RCSfile: warnbox.cxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: dr $ $Date: 2002-10-23 14:52:40 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_WARNBOX_HXX\n#include \"warnbox.hxx\"\n#endif\n\n#include \"scmod.hxx\"\n#include \"inputopt.hxx\"\n#include \"scresid.hxx\"\n#include \"sc.hrc\"\n\n\n\/\/ ============================================================================\n\nScCbWarningBox::ScCbWarningBox( Window* pParent, const String& rMsgStr, bool bDefYes ) :\n    WarningBox( pParent, WB_YES_NO | (bDefYes ? WB_DEF_YES : WB_DEF_NO), rMsgStr )\n{\n    SetDefaultCheckBoxText();\n}\n\nsal_Int16 ScCbWarningBox::Execute()\n{\n    sal_Int16 nRet = (GetStyle() & WB_DEF_YES) ? RET_YES : RET_NO;\n    if( IsDialogEnabled() )\n    {\n        nRet = WarningBox::Execute();\n        if( GetCheckBoxState() )\n            DisableDialog();\n    }\n    return nRet;\n}\n\nbool ScCbWarningBox::IsDialogEnabled()\n{\n    return true;\n}\n\nvoid ScCbWarningBox::DisableDialog()\n{\n}\n\n\n\/\/ ----------------------------------------------------------------------------\n\nScReplaceWarnBox::ScReplaceWarnBox( Window* pParent ) :\n    ScCbWarningBox( pParent, String( ScResId( STR_REPLCELLSWARN ) ), true )\n{\n    SetHelpId( HID_SC_REPLCELLSWARN );\n}\n\nbool ScReplaceWarnBox::IsDialogEnabled()\n{\n    return SC_MOD()->GetInputOptions().GetReplaceCellsWarn() == TRUE;\n}\n\nvoid ScReplaceWarnBox::DisableDialog()\n{\n    ScModule* pScMod = SC_MOD();\n    ScInputOptions aInputOpt( pScMod->GetInputOptions() );\n    aInputOpt.SetReplaceCellsWarn( FALSE );\n    pScMod->SetInputOptions( aInputOpt );\n}\n\n\n\/\/ ============================================================================\n\nINTEGRATION: CWS ooo19126 (1.3.900); FILE MERGED 2005\/09\/05 15:06:39 rt 1.3.900.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: warnbox.cxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 22:15:31 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef SC_WARNBOX_HXX\n#include \"warnbox.hxx\"\n#endif\n\n#include \"scmod.hxx\"\n#include \"inputopt.hxx\"\n#include \"scresid.hxx\"\n#include \"sc.hrc\"\n\n\n\/\/ ============================================================================\n\nScCbWarningBox::ScCbWarningBox( Window* pParent, const String& rMsgStr, bool bDefYes ) :\n    WarningBox( pParent, WB_YES_NO | (bDefYes ? WB_DEF_YES : WB_DEF_NO), rMsgStr )\n{\n    SetDefaultCheckBoxText();\n}\n\nsal_Int16 ScCbWarningBox::Execute()\n{\n    sal_Int16 nRet = (GetStyle() & WB_DEF_YES) ? RET_YES : RET_NO;\n    if( IsDialogEnabled() )\n    {\n        nRet = WarningBox::Execute();\n        if( GetCheckBoxState() )\n            DisableDialog();\n    }\n    return nRet;\n}\n\nbool ScCbWarningBox::IsDialogEnabled()\n{\n    return true;\n}\n\nvoid ScCbWarningBox::DisableDialog()\n{\n}\n\n\n\/\/ ----------------------------------------------------------------------------\n\nScReplaceWarnBox::ScReplaceWarnBox( Window* pParent ) :\n    ScCbWarningBox( pParent, String( ScResId( STR_REPLCELLSWARN ) ), true )\n{\n    SetHelpId( HID_SC_REPLCELLSWARN );\n}\n\nbool ScReplaceWarnBox::IsDialogEnabled()\n{\n    return SC_MOD()->GetInputOptions().GetReplaceCellsWarn() == TRUE;\n}\n\nvoid ScReplaceWarnBox::DisableDialog()\n{\n    ScModule* pScMod = SC_MOD();\n    ScInputOptions aInputOpt( pScMod->GetInputOptions() );\n    aInputOpt.SetReplaceCellsWarn( FALSE );\n    pScMod->SetInputOptions( aInputOpt );\n}\n\n\n\/\/ ============================================================================\n\n<|endoftext|>"}
{"text":"Add awesome algorithm MO'.<|endoftext|>"}
{"text":"\/\/ netfortune session\n\/\/ Copyright © 2017 Christian Rapp\n\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/(at your option) any later version.\n\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/GNU General Public License for more details.\n\n\/\/ You should have received a copy of the GNU General Public License\n\/\/along with this program.  If not, see .\n\n#ifndef FSESSION_HPP\n#define FSESSION_HPP\n\n#include \n#include \n#include \n\n#include \n\n#include \"spdlog\/spdlog.h\"\n\n#include \"fproto.hpp\"\n\n\/**\n * @brief FSession class represents one TCP Connection from server to client\n * @detail\n * A session handels reading and writing from\/to the client.\n * 1. Reading the first 6 Bytes to get the actual message length. Then read\n *    the rest.\n * 2. Parse the message with a json encoder and see if this is valid json\n * 3. Get the information we need from the client and prepare the answer\n *    accordingly\n *\n *\/\nclass FSession : public std::enable_shared_from_this\n{\npublic:\n    explicit FSession(boost::asio::ip::tcp::socket socket);\n    virtual ~FSession() = default;\n\n    \/**\n     * @brief Start the reading on FSession::socket\n     *\/\n    void start();\n\nprivate:\n    std::vector\n        data_buf; \/**< buffer containing the request and later the answer *\/\n    const size_t max_buf_size = 2048;    \/**< maximum data buffer size *\/\n    boost::asio::ip::tcp::socket socket; \/**< Socket this session uses *\/\n\n    std::shared_ptr logger;\n    std::unique_ptr nfprot;\n\n    void do_read();\n    void do_write();\n};\n\n#endif \/* FSESSION_HPP *\/\nAdd fsession had also the wrong license\/\/ netfortune brings fortunes for everyone, everywhere\n\/\/ Copyright © 2017 Christian Rapp\n\/\/ All rights reserved.\n\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the organization nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\n\/\/ THIS SOFTWARE IS PROVIDED BY  ''AS IS'' AND ANY\n\/\/ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef FSESSION_HPP\n#define FSESSION_HPP\n\n#include \n#include \n#include \n\n#include \n\n#include \"spdlog\/spdlog.h\"\n\n#include \"fproto.hpp\"\n\n\/**\n * @brief FSession class represents one TCP Connection from server to client\n * @detail\n * A session handels reading and writing from\/to the client.\n * 1. Reading the first 6 Bytes to get the actual message length. Then read\n *    the rest.\n * 2. Parse the message with a json encoder and see if this is valid json\n * 3. Get the information we need from the client and prepare the answer\n *    accordingly\n *\n *\/\nclass FSession : public std::enable_shared_from_this\n{\npublic:\n    explicit FSession(boost::asio::ip::tcp::socket socket);\n    virtual ~FSession() = default;\n\n    \/**\n     * @brief Start the reading on FSession::socket\n     *\/\n    void start();\n\nprivate:\n    std::vector\n        data_buf; \/**< buffer containing the request and later the answer *\/\n    const size_t max_buf_size = 2048;    \/**< maximum data buffer size *\/\n    boost::asio::ip::tcp::socket socket; \/**< Socket this session uses *\/\n\n    std::shared_ptr logger;\n    std::unique_ptr nfprot;\n\n    void do_read();\n    void do_write();\n};\n\n#endif \/* FSESSION_HPP *\/\n<|endoftext|>"}
{"text":"\/\/\n\/\/ file : type_id.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/ntools\/type_id.hpp\n\/\/\n\/\/ created by : Timothée Feuillet\n\/\/ date: sam. avr. 28 18:58:38 2018 GMT-0400\n\/\/\n\/\/\n\/\/ Copyright (c) 2018 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#pragma once\n\n#include \n#include \"ct_string.hpp\"\n#include \"ct_array.hpp\"\n#include \"hash\/fnv1a.hpp\"\n\nnamespace neam::ct\n{\n  namespace details\n  {\n    template\n    constexpr std::array id_make_array(std::index_sequence&&) { return {{TID::str[Idxs]..., '\\0'}}; }\n\n    template\n    constexpr auto id_make_array() { return id_make_array(std::make_index_sequence{}); }\n\n    template\n    struct tid\n    {\n      static constexpr string type_name() noexcept\n      {\n        constexpr string s = { __PRETTY_FUNCTION__ };\n        constexpr string t = s.pad(s.find(\"= \") + 2, neam::ct::strlen(\"]\"));\n        return t;\n      }\n\n      static constexpr const char* str = type_name().str;\n      static constexpr size_t size = type_name().size;\n    };\n    template\n    struct vid\n    {\n      static constexpr string type_name() noexcept\n      {\n        constexpr string s = { __PRETTY_FUNCTION__ };\n        constexpr string t = s.pad(s.find(\"= \") + 2, neam::ct::strlen(\"]\"));\n        return t;\n      }\n\n      static constexpr const char* str = type_name().str;\n      static constexpr size_t size = type_name().size;\n    };\n\n    \/\/\/ This class has for effect to reduce the size of the executable:\n    \/\/\/ it holds the name for a given type T, and only that name (no other irrelevant data).\n    \/\/\/ It will generate some type-info (the name of the type will be stored in the binary), if rtti is enabled.\n    template\n    struct tholder { static constexpr auto name = details::id_make_array>(); };\n    template\n    struct vholder { static constexpr auto name = details::id_make_array>(); };\n  } \/\/ namespace details\n\n  \/\/\/ \\brief The name of the type, as a constexpr string.\n  template\n  static constexpr string type_name = { details::tholder::name.data(), details::tholder::name.size() - 1 };\n  \/\/\/ \\brief The name of the decayed type, as a constexpr string.\n  template\n  static constexpr string decayed_type_name = type_name>;\n\n  \/\/\/ \\brief A string for the corresponding value\n  template\n  static constexpr string value_name = { details::vholder::name.data(), details::vholder::name.size() - 1 };\n\n  \/\/\/ \\brief A hash for the type. No uniqueness guaranteed.\n  template\n  static constexpr auto type_hash = hash::fnv1a<64>(details::tholder::name.data(), details::tholder::name.size() - 1);\n  \/\/\/ \\brief A hash for the decayed type. No uniqueness guaranteed.\n  template\n  static constexpr auto decayed_type_hash = type_hash>;\n\n  \/\/\/ \\brief A (gratuitous) hash for the corresponding value. No uniqueness guaranteed.\n  template\n  static constexpr auto value_hash = hash::fnv1a<64>(details::vholder::name.data(), details::vholder::name.size() - 1);\n} \/\/ namespace neam::ct\n\n#ifdef NCT_TESTS\n    static_assert(neam::ct::type_name == neam::ct::string{\"int\"});\n    static_assert(neam::ct::type_name == neam::ct::string{\"double\"});\n    static_assert(neam::ct::type_name == neam::ct::string{\"double []\"});\n    static_assert(neam::ct::type_name == neam::ct::string{\"neam::ct::string\"});\n#endif\n\nFix compilation issue with newer gcc\/\/\n\/\/ file : type_id.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/ntools\/type_id.hpp\n\/\/\n\/\/ created by : Timothée Feuillet\n\/\/ date: sam. avr. 28 18:58:38 2018 GMT-0400\n\/\/\n\/\/\n\/\/ Copyright (c) 2018 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#pragma once\n\n#include \n#include \n#include \"ct_string.hpp\"\n#include \"ct_array.hpp\"\n#include \"hash\/fnv1a.hpp\"\n\nnamespace neam::ct\n{\n  namespace details\n  {\n    template\n    constexpr std::array id_make_array(std::index_sequence&&) { return {{TID::str[Idxs]..., '\\0'}}; }\n\n    template\n    constexpr auto id_make_array() { return id_make_array(std::make_index_sequence{}); }\n\n    template\n    struct tid\n    {\n      static constexpr string type_name() noexcept\n      {\n        constexpr string s = { __PRETTY_FUNCTION__ };\n        constexpr string t = s.pad(s.find(\"= \") + 2, neam::ct::strlen(\"]\"));\n        return t;\n      }\n\n      static constexpr const char* str = type_name().str;\n      static constexpr size_t size = type_name().size;\n    };\n    template\n    struct vid\n    {\n      static constexpr string type_name() noexcept\n      {\n        constexpr string s = { __PRETTY_FUNCTION__ };\n        constexpr string t = s.pad(s.find(\"= \") + 2, neam::ct::strlen(\"]\"));\n        return t;\n      }\n\n      static constexpr const char* str = type_name().str;\n      static constexpr size_t size = type_name().size;\n    };\n\n    \/\/\/ This class has for effect to reduce the size of the executable:\n    \/\/\/ it holds the name for a given type T, and only that name (no other irrelevant data).\n    \/\/\/ It will generate some type-info (the name of the type will be stored in the binary), if rtti is enabled.\n    template\n    struct tholder { static constexpr auto name = details::id_make_array>(); };\n    template\n    struct vholder { static constexpr auto name = details::id_make_array>(); };\n  } \/\/ namespace details\n\n  \/\/\/ \\brief The name of the type, as a constexpr string.\n  template\n  static constexpr string type_name = { details::tholder::name.data(), details::tholder::name.size() - 1 };\n  \/\/\/ \\brief The name of the decayed type, as a constexpr string.\n  template\n  static constexpr string decayed_type_name = type_name>;\n\n  \/\/\/ \\brief A string for the corresponding value\n  template\n  static constexpr string value_name = { details::vholder::name.data(), details::vholder::name.size() - 1 };\n\n  \/\/\/ \\brief A hash for the type. No uniqueness guaranteed.\n  template\n  static constexpr auto type_hash = hash::fnv1a<64>(details::tholder::name.data(), details::tholder::name.size() - 1);\n  \/\/\/ \\brief A hash for the decayed type. No uniqueness guaranteed.\n  template\n  static constexpr auto decayed_type_hash = type_hash>;\n\n  \/\/\/ \\brief A (gratuitous) hash for the corresponding value. No uniqueness guaranteed.\n  template\n  static constexpr auto value_hash = hash::fnv1a<64>(details::vholder::name.data(), details::vholder::name.size() - 1);\n} \/\/ namespace neam::ct\n\n#ifdef NCT_TESTS\n    static_assert(neam::ct::type_name == neam::ct::string{\"int\"});\n    static_assert(neam::ct::type_name == neam::ct::string{\"double\"});\n    static_assert(neam::ct::type_name == neam::ct::string{\"double []\"});\n    static_assert(neam::ct::type_name == neam::ct::string{\"neam::ct::string\"});\n#endif\n\n<|endoftext|>"}
{"text":"#include \"Debugger.Process.h\"\r\n\r\nnamespace GleeBug\r\n{\r\n    bool Process::SetBreakpoint(ptr address, bool singleshoot, SoftwareType type)\r\n    {\r\n        \/\/check the address\r\n        if(!MemIsValidPtr(address) ||\r\n                breakpoints.find({ BreakpointType::Software, address }) != breakpoints.end())\r\n            return false;\r\n\r\n        \/\/setup the breakpoint information struct\r\n        BreakpointInfo info = {};\r\n        info.address = address;\r\n        info.singleshoot = singleshoot;\r\n        info.type = BreakpointType::Software;\r\n\r\n        \/\/determine breakpoint byte and size from the type\r\n        switch(type)\r\n        {\r\n        case SoftwareType::ShortInt3:\r\n            info.internal.software.newbytes[0] = 0xCC;\r\n            info.internal.software.size = 1;\r\n            break;\r\n\r\n        default:\r\n            return false;\r\n        }\r\n\r\n        \/\/read\/write the breakpoint\r\n        if(!MemReadUnsafe(address, info.internal.software.oldbytes, info.internal.software.size))\r\n            return false;\r\n\r\n        if(!MemWriteUnsafe(address, info.internal.software.newbytes, info.internal.software.size))\r\n            return false;\r\n        FlushInstructionCache(hProcess, nullptr, 0);\r\n\r\n        \/\/insert in the breakpoint map\r\n        auto itr = breakpoints.insert({ { info.type, info.address }, info });\r\n        softwareBreakpointReferences[info.address] = itr.first;\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Process::SetBreakpoint(ptr address, const BreakpointCallback & cbBreakpoint, bool singleshoot, SoftwareType type)\r\n    {\r\n        \/\/check if a callback on this address was already found\r\n        if(breakpointCallbacks.find({ BreakpointType::Software, address }) != breakpointCallbacks.end())\r\n            return false;\r\n        \/\/set the breakpoint\r\n        if(!SetBreakpoint(address, singleshoot, type))\r\n            return false;\r\n        \/\/insert the callback\r\n        breakpointCallbacks.insert({ { BreakpointType::Software, address }, cbBreakpoint });\r\n        return true;\r\n    }\r\n\r\n    bool Process::DeleteBreakpoint(ptr address)\r\n    {\r\n        \/\/find the breakpoint\r\n        auto found = breakpoints.find({ BreakpointType::Software, address });\r\n        if(found == breakpoints.end())\r\n            return false;\r\n        const auto & info = found->second;\r\n\r\n        \/\/restore the breakpoint bytes\r\n        if(!MemWriteUnsafe(address, info.internal.software.oldbytes, info.internal.software.size))\r\n            return false;\r\n        FlushInstructionCache(hProcess, nullptr, 0);\r\n\r\n        \/\/remove the breakpoint from the maps\r\n        softwareBreakpointReferences.erase(info.address);\r\n        breakpoints.erase(found);\r\n        breakpointCallbacks.erase({ BreakpointType::Software, address });\r\n        return true;\r\n    }\r\n\r\n    bool Process::GetFreeHardwareBreakpointSlot(HardwareSlot & slot) const\r\n    {\r\n        \/\/find a free hardware breakpoint slot\r\n        for(int i = 0; i < HWBP_COUNT; i++)\r\n        {\r\n            if(!hardwareBreakpoints[i].internal.hardware.enabled)\r\n            {\r\n                slot = HardwareSlot(i);\r\n                return true;\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n    bool Process::SetHardwareBreakpoint(ptr address, HardwareSlot slot, HardwareType type, HardwareSize size, bool singleshoot)\r\n    {\r\n        \/\/check the address\r\n        if(!MemIsValidPtr(address) ||\r\n                breakpoints.find({ BreakpointType::Hardware, address }) != breakpoints.end())\r\n            return false;\r\n\r\n        \/\/attempt to set the hardware breakpoint in every thread\r\n        bool success = true;\r\n        for(auto & thread : threads)\r\n        {\r\n            if(!thread.second->SetHardwareBreakpoint(address, slot, type, size))\r\n            {\r\n                success = false;\r\n                break;\r\n            }\r\n        }\r\n\r\n        \/\/if setting failed, unset all\r\n        if(!success)\r\n        {\r\n            for(auto & thread : threads)\r\n                thread.second->DeleteHardwareBreakpoint(slot);\r\n            return false;\r\n        }\r\n\r\n        \/\/setup the breakpoint information struct\r\n        BreakpointInfo info = {};\r\n        info.address = address;\r\n        info.singleshoot = singleshoot;\r\n        info.type = BreakpointType::Hardware;\r\n        info.internal.hardware.slot = slot;\r\n        info.internal.hardware.type = type;\r\n        info.internal.hardware.size = size;\r\n        info.internal.hardware.enabled = true;\r\n\r\n        \/\/insert in the breakpoint map\r\n        breakpoints.insert({ { info.type, info.address }, info });\r\n\r\n        \/\/insert in the hardware breakpoint cache\r\n        hardwareBreakpoints[int(slot)] = info;\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Process::SetHardwareBreakpoint(ptr address, HardwareSlot slot, const BreakpointCallback & cbBreakpoint, HardwareType type, HardwareSize size, bool singleshoot)\r\n    {\r\n        \/\/check if a callback on this address was already found\r\n        if(breakpointCallbacks.find({ BreakpointType::Hardware, address }) != breakpointCallbacks.end())\r\n            return false;\r\n        \/\/set the hardware breakpoint\r\n        if(!SetHardwareBreakpoint(address, slot, type, size, singleshoot))\r\n            return false;\r\n        \/\/insert the callback\r\n        breakpointCallbacks.insert({ { BreakpointType::Hardware, address }, cbBreakpoint });\r\n        return true;\r\n    }\r\n\r\n    bool Process::DeleteHardwareBreakpoint(ptr address)\r\n    {\r\n        \/\/find the hardware breakpoint\r\n        auto found = breakpoints.find({ BreakpointType::Hardware, address });\r\n        if(found == breakpoints.end())\r\n            return false;\r\n        const auto & info = found->second;\r\n\r\n        \/\/delete the hardware breakpoint from the internal buffer\r\n        hardwareBreakpoints[int(info.internal.hardware.slot)].internal.hardware.enabled = false;\r\n\r\n        \/\/delete the hardware breakpoint from the registers\r\n        bool success = true;\r\n        for(auto & thread : threads)\r\n        {\r\n            if(!thread.second->DeleteHardwareBreakpoint(info.internal.hardware.slot))\r\n                success = false;\r\n        }\r\n\r\n        \/\/delete the breakpoint from the maps\r\n        breakpoints.erase(found);\r\n        breakpointCallbacks.erase({ BreakpointType::Hardware, address });\r\n        return success;\r\n    }\r\n\r\n#define PAGE_SHIFT              (12)\r\n#define PAGE_ALIGN(Va)          ((ULONG_PTR)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))\r\n#define BYTES_TO_PAGES(Size)    (((Size) >> PAGE_SHIFT) + (((Size) & (PAGE_SIZE - 1)) != 0))\r\n#define ROUND_TO_PAGES(Size)    (((ULONG_PTR)(Size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))\r\n\r\n    \/*\r\n    #define PAGE_NOACCESS          0x01\r\n    #define PAGE_READONLY          0x02\r\n    #define PAGE_READWRITE         0x04\r\n    #define PAGE_WRITECOPY         0x08 <- not supported\r\n\r\n    #define PAGE_EXECUTE           0x10\r\n    #define PAGE_EXECUTE_READ      0x20\r\n    #define PAGE_EXECUTE_READWRITE 0x40\r\n    #define PAGE_EXECUTE_WRITECOPY 0x80 <- not supported\r\n\r\n    #define PAGE_GUARD            0x100 <- not supported with PAGE_NOACCESS\r\n    #define PAGE_NOCACHE          0x200 <- not supported with PAGE_GUARD or PAGE_WRITECOMBINE\r\n    #define PAGE_WRITECOMBINE     0x400 <- not supported with PAGE_GUARD or PAGE_NOCACHE\r\n    *\/\r\n\r\n    static DWORD RemoveExecuteAccess(DWORD dwAccess)\r\n    {\r\n        \/\/These settings can trigger access violation.\r\n        DWORD dwBase = dwAccess & 0xFF;\r\n        DWORD dwHigh = dwAccess & 0xFFFFFF00;\r\n        switch(dwBase)\r\n        {\r\n        case PAGE_EXECUTE:\r\n            return dwHigh | PAGE_READONLY;\r\n        case PAGE_EXECUTE_READ:\r\n        case PAGE_EXECUTE_READWRITE:\r\n        case PAGE_EXECUTE_WRITECOPY:\r\n            return dwHigh | (dwBase >> 4); \/\/This removes execute in deed; https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa366786(v=vs.85).aspx - 0x1337 tricks\r\n        default:\r\n            return dwAccess;\r\n        }\r\n    }\r\n\r\n    static DWORD RemoveWriteAccess(DWORD dwAccess)\r\n    {\r\n        DWORD dwBase = dwAccess & 0xFF;\r\n        switch(dwBase)\r\n        {\r\n        case PAGE_READWRITE:\r\n        case PAGE_EXECUTE_READWRITE:\r\n            return (dwAccess & 0xFFFFFF00) | (dwBase >> 1);\r\n        default:\r\n            return dwAccess;\r\n        }\r\n    }\r\n\r\n    bool Process::SetNewPageProtection(ptr page, MemoryBreakpointData & data, MemoryType type)\r\n    {\r\n        DPRINTF();\r\n        \/\/TODO: handle PAGE_NOACCESS and such correctly (since it cannot be combined with PAGE_GUARD)\r\n\r\n        auto found = memoryBreakpointPages.find(page);\r\n        if(found == memoryBreakpointPages.end())\r\n        {\r\n            data.Refcount = 1;\r\n            switch(type)\r\n            {\r\n            case MemoryType::Access:\r\n            case MemoryType::Read:\r\n                data.NewProtect = data.OldProtect | PAGE_GUARD;\r\n                break;\r\n            case MemoryType::Write:\r\n                data.NewProtect = RemoveWriteAccess(data.OldProtect);\r\n                break;\r\n            case MemoryType::Execute:\r\n                data.NewProtect = permanentDep ? RemoveExecuteAccess(data.OldProtect) : data.OldProtect | PAGE_GUARD;\r\n                break;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            auto & oldData = found->second;\r\n            data.Type = oldData.Type | uint32(type); \/\/combines new protection\r\n            data.OldProtect = oldData.OldProtect; \/\/ old protection remains the same\r\n            data.Refcount = oldData.Refcount + 1; \/\/increment reference count\r\n            if(oldData.Type == uint32(type))  \/\/ Edge case for when you need to set a mem bpx on a same page with the same type, you just leave newProtect = OldProtect.\r\n            {\r\n                data.NewProtect = data.OldProtect;\r\n            }\r\n            else if(data.Type & uint32(MemoryType::Access) || data.Type & uint32(MemoryType::Read))  \/\/ Access\/Read always becomes PAGE_GUARD ; This page cannot access or Read?\r\n                data.NewProtect = data.OldProtect | PAGE_GUARD; \/\/as before\r\n            else if(data.Type & (uint32(MemoryType::Write) | uint32(MemoryType::Execute)))  \/\/ Write + Execute becomes either PAGE_GUARD or both write and execute flags removed\r\n                data.NewProtect = permanentDep ? RemoveExecuteAccess(RemoveWriteAccess(data.OldProtect)) : data.OldProtect | PAGE_GUARD;\r\n        }\r\n\r\n        dprintf(\"SetNewPageProtection(%p, %X)\\n\", page, data.NewProtect);\r\n        return MemProtect(page, PAGE_SIZE, data.NewProtect);\r\n    }\r\n\r\n    bool Process::SetMemoryBreakpoint(ptr address, ptr size, MemoryType type, bool singleshoot)\r\n    {\r\n        DPRINTF();\r\n        dprintf(\"SetMemoryBreakpoint(%p, %p, %d, %d)\\n\", address, size, type, singleshoot);\r\n        \/\/TODO: error reporting\r\n\r\n        \/\/basic checks\r\n        if(!MemIsValidPtr(address) || !size)\r\n            return false;\r\n\r\n        \/\/check if the range is unused for any previous memory breakpoints\r\n        auto range = Range(address, address + size - 1);\r\n        if(memoryBreakpointRanges.find(range) != memoryBreakpointRanges.end())\r\n            return false;\r\n\r\n        \/\/change page protections\r\n        bool success = true;\r\n        struct TempMemoryBreakpointData\r\n        {\r\n            ptr addr;\r\n            DWORD OldProtect;\r\n            MemoryBreakpointData data;\r\n        };\r\n        std::vector breakpointData;\r\n        {\r\n            breakpointData.reserve(size \/ PAGE_SIZE);\r\n            TempMemoryBreakpointData tempData;\r\n            MemoryBreakpointData data;\r\n            data.Type = uint32(type);\r\n            auto alignedAddress = PAGE_ALIGN(address);\r\n            for(auto page = alignedAddress; page < alignedAddress + ROUND_TO_PAGES(size); page += PAGE_SIZE)\r\n            {\r\n                MEMORY_BASIC_INFORMATION mbi;\r\n                if(!VirtualQueryEx(hProcess, LPCVOID(page), &mbi, sizeof(mbi)))\r\n                {\r\n                    success = false;\r\n                    dprintf(\"!VirtualQueryEx\\n\");\r\n                    break;\r\n                }\r\n                data.OldProtect = mbi.Protect;\r\n                if(!SetNewPageProtection(page, data, type))\r\n                {\r\n                    success = false;\r\n                    dprintf(\"!SetNewPageProtection\\n\");\r\n                    break;\r\n                }\r\n                tempData.addr = page;\r\n                tempData.OldProtect = mbi.Protect;\r\n                tempData.data = data;\r\n                breakpointData.push_back(tempData);\r\n            }\r\n        }\r\n\r\n        \/\/if changing the page protections failed, attempt to revert all protection changes\r\n        if(!success)\r\n        {\r\n            for(const auto & page : breakpointData)\r\n                MemProtect(page.addr, PAGE_SIZE, page.OldProtect);\r\n            return false;\r\n        }\r\n\r\n        \/\/set the page data\r\n        for(const auto & page : breakpointData)\r\n            memoryBreakpointPages[page.addr] = page.data;\r\n\r\n        \/\/setup the breakpoint information struct\r\n        BreakpointInfo info = {};\r\n        info.address = address;\r\n        info.singleshoot = singleshoot;\r\n        info.type = BreakpointType::Memory;\r\n        info.internal.memory.type = type;\r\n        info.internal.memory.size = size;\r\n\r\n        \/\/insert in the breakpoint map\r\n        breakpoints.insert({ { info.type, info.address }, info });\r\n        memoryBreakpointRanges.insert(range);\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Process::SetMemoryBreakpoint(ptr address, ptr size, const BreakpointCallback & cbBreakpoint, MemoryType type, bool singleshoot)\r\n    {\r\n        \/\/check if a callback on this address was already found\r\n        if(breakpointCallbacks.find({ BreakpointType::Memory, address }) != breakpointCallbacks.end())\r\n            return false;\r\n        \/\/set the memory breakpoint\r\n        if(!SetMemoryBreakpoint(address, size, type, singleshoot))\r\n            return false;\r\n        \/\/insert the callback\r\n        breakpointCallbacks.insert({ { BreakpointType::Memory, address }, cbBreakpoint });\r\n        return true;\r\n    }\r\n\r\n    bool Process::DeleteMemoryBreakpoint(ptr address)\r\n    {\r\n        \/\/find the memory breakpoint range\r\n        auto range = memoryBreakpointRanges.find(Range(address, address));\r\n        if(range == memoryBreakpointRanges.end())\r\n            return false;\r\n\r\n        \/\/find the memory breakpoint\r\n        auto found = breakpoints.find({ BreakpointType::Memory, range->first });\r\n        if(found == breakpoints.end())\r\n            return false;\r\n        const auto & info = found->second;\r\n\r\n        \/\/delete the memory breakpoint from the pages\r\n        bool success = true;\r\n        auto alignedAddress = PAGE_ALIGN(info.address);\r\n        for(auto page = alignedAddress; page < alignedAddress + ROUND_TO_PAGES(info.internal.memory.size); page += PAGE_SIZE)\r\n        {\r\n            auto foundData = memoryBreakpointPages.find(page);\r\n            if(foundData == memoryBreakpointPages.end())\r\n                continue; \/\/TODO: error reporting\r\n            auto & data = foundData->second;\r\n            DWORD Protect;\r\n            data.Refcount--;\r\n            if(data.Refcount)\r\n            {\r\n                \/\/TODO: properly determine the new protection flag\r\n                \/\/Are there any other protections left?\r\n                \/\/If so add the guard\r\n                if(data.Type & ~uint32(info.internal.memory.type))\r\n                    data.NewProtect = data.OldProtect | PAGE_GUARD;\r\n                Protect = data.NewProtect;\r\n            }\r\n            else\r\n                Protect = data.OldProtect;\r\n            if(!MemProtect(page, PAGE_SIZE, Protect))\r\n                success = false;\r\n            if(!data.Refcount)\r\n                memoryBreakpointPages.erase(foundData);\r\n        }\r\n\r\n        \/\/delete the breakpoint from the maps\r\n        breakpoints.erase(found);\r\n        breakpointCallbacks.erase({ BreakpointType::Hardware, address });\r\n        memoryBreakpointRanges.erase(Range(address, address));\r\n        return success;\r\n    }\r\n\r\n    bool Process::DeleteGenericBreakpoint(const BreakpointInfo & info)\r\n    {\r\n        switch(info.type)\r\n        {\r\n        case BreakpointType::Software:\r\n            return DeleteBreakpoint(info.address);\r\n        case BreakpointType::Hardware:\r\n            return DeleteHardwareBreakpoint(info.address);\r\n        case BreakpointType::Memory:\r\n            return DeleteMemoryBreakpoint(info.address);\r\n        default:\r\n            return false;\r\n        }\r\n    }\r\n};Fix incorrect type#include \"Debugger.Process.h\"\r\n\r\nnamespace GleeBug\r\n{\r\n    bool Process::SetBreakpoint(ptr address, bool singleshoot, SoftwareType type)\r\n    {\r\n        \/\/check the address\r\n        if(!MemIsValidPtr(address) ||\r\n                breakpoints.find({ BreakpointType::Software, address }) != breakpoints.end())\r\n            return false;\r\n\r\n        \/\/setup the breakpoint information struct\r\n        BreakpointInfo info = {};\r\n        info.address = address;\r\n        info.singleshoot = singleshoot;\r\n        info.type = BreakpointType::Software;\r\n\r\n        \/\/determine breakpoint byte and size from the type\r\n        switch(type)\r\n        {\r\n        case SoftwareType::ShortInt3:\r\n            info.internal.software.newbytes[0] = 0xCC;\r\n            info.internal.software.size = 1;\r\n            break;\r\n\r\n        default:\r\n            return false;\r\n        }\r\n\r\n        \/\/read\/write the breakpoint\r\n        if(!MemReadUnsafe(address, info.internal.software.oldbytes, info.internal.software.size))\r\n            return false;\r\n\r\n        if(!MemWriteUnsafe(address, info.internal.software.newbytes, info.internal.software.size))\r\n            return false;\r\n        FlushInstructionCache(hProcess, nullptr, 0);\r\n\r\n        \/\/insert in the breakpoint map\r\n        auto itr = breakpoints.insert({ { info.type, info.address }, info });\r\n        softwareBreakpointReferences[info.address] = itr.first;\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Process::SetBreakpoint(ptr address, const BreakpointCallback & cbBreakpoint, bool singleshoot, SoftwareType type)\r\n    {\r\n        \/\/check if a callback on this address was already found\r\n        if(breakpointCallbacks.find({ BreakpointType::Software, address }) != breakpointCallbacks.end())\r\n            return false;\r\n        \/\/set the breakpoint\r\n        if(!SetBreakpoint(address, singleshoot, type))\r\n            return false;\r\n        \/\/insert the callback\r\n        breakpointCallbacks.insert({ { BreakpointType::Software, address }, cbBreakpoint });\r\n        return true;\r\n    }\r\n\r\n    bool Process::DeleteBreakpoint(ptr address)\r\n    {\r\n        \/\/find the breakpoint\r\n        auto found = breakpoints.find({ BreakpointType::Software, address });\r\n        if(found == breakpoints.end())\r\n            return false;\r\n        const auto & info = found->second;\r\n\r\n        \/\/restore the breakpoint bytes\r\n        if(!MemWriteUnsafe(address, info.internal.software.oldbytes, info.internal.software.size))\r\n            return false;\r\n        FlushInstructionCache(hProcess, nullptr, 0);\r\n\r\n        \/\/remove the breakpoint from the maps\r\n        softwareBreakpointReferences.erase(info.address);\r\n        breakpoints.erase(found);\r\n        breakpointCallbacks.erase({ BreakpointType::Software, address });\r\n        return true;\r\n    }\r\n\r\n    bool Process::GetFreeHardwareBreakpointSlot(HardwareSlot & slot) const\r\n    {\r\n        \/\/find a free hardware breakpoint slot\r\n        for(int i = 0; i < HWBP_COUNT; i++)\r\n        {\r\n            if(!hardwareBreakpoints[i].internal.hardware.enabled)\r\n            {\r\n                slot = HardwareSlot(i);\r\n                return true;\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n    bool Process::SetHardwareBreakpoint(ptr address, HardwareSlot slot, HardwareType type, HardwareSize size, bool singleshoot)\r\n    {\r\n        \/\/check the address\r\n        if(!MemIsValidPtr(address) ||\r\n                breakpoints.find({ BreakpointType::Hardware, address }) != breakpoints.end())\r\n            return false;\r\n\r\n        \/\/attempt to set the hardware breakpoint in every thread\r\n        bool success = true;\r\n        for(auto & thread : threads)\r\n        {\r\n            if(!thread.second->SetHardwareBreakpoint(address, slot, type, size))\r\n            {\r\n                success = false;\r\n                break;\r\n            }\r\n        }\r\n\r\n        \/\/if setting failed, unset all\r\n        if(!success)\r\n        {\r\n            for(auto & thread : threads)\r\n                thread.second->DeleteHardwareBreakpoint(slot);\r\n            return false;\r\n        }\r\n\r\n        \/\/setup the breakpoint information struct\r\n        BreakpointInfo info = {};\r\n        info.address = address;\r\n        info.singleshoot = singleshoot;\r\n        info.type = BreakpointType::Hardware;\r\n        info.internal.hardware.slot = slot;\r\n        info.internal.hardware.type = type;\r\n        info.internal.hardware.size = size;\r\n        info.internal.hardware.enabled = true;\r\n\r\n        \/\/insert in the breakpoint map\r\n        breakpoints.insert({ { info.type, info.address }, info });\r\n\r\n        \/\/insert in the hardware breakpoint cache\r\n        hardwareBreakpoints[int(slot)] = info;\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Process::SetHardwareBreakpoint(ptr address, HardwareSlot slot, const BreakpointCallback & cbBreakpoint, HardwareType type, HardwareSize size, bool singleshoot)\r\n    {\r\n        \/\/check if a callback on this address was already found\r\n        if(breakpointCallbacks.find({ BreakpointType::Hardware, address }) != breakpointCallbacks.end())\r\n            return false;\r\n        \/\/set the hardware breakpoint\r\n        if(!SetHardwareBreakpoint(address, slot, type, size, singleshoot))\r\n            return false;\r\n        \/\/insert the callback\r\n        breakpointCallbacks.insert({ { BreakpointType::Hardware, address }, cbBreakpoint });\r\n        return true;\r\n    }\r\n\r\n    bool Process::DeleteHardwareBreakpoint(ptr address)\r\n    {\r\n        \/\/find the hardware breakpoint\r\n        auto found = breakpoints.find({ BreakpointType::Hardware, address });\r\n        if(found == breakpoints.end())\r\n            return false;\r\n        const auto & info = found->second;\r\n\r\n        \/\/delete the hardware breakpoint from the internal buffer\r\n        hardwareBreakpoints[int(info.internal.hardware.slot)].internal.hardware.enabled = false;\r\n\r\n        \/\/delete the hardware breakpoint from the registers\r\n        bool success = true;\r\n        for(auto & thread : threads)\r\n        {\r\n            if(!thread.second->DeleteHardwareBreakpoint(info.internal.hardware.slot))\r\n                success = false;\r\n        }\r\n\r\n        \/\/delete the breakpoint from the maps\r\n        breakpoints.erase(found);\r\n        breakpointCallbacks.erase({ BreakpointType::Hardware, address });\r\n        return success;\r\n    }\r\n\r\n#define PAGE_SHIFT              (12)\r\n#define PAGE_ALIGN(Va)          ((ULONG_PTR)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))\r\n#define BYTES_TO_PAGES(Size)    (((Size) >> PAGE_SHIFT) + (((Size) & (PAGE_SIZE - 1)) != 0))\r\n#define ROUND_TO_PAGES(Size)    (((ULONG_PTR)(Size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))\r\n\r\n    \/*\r\n    #define PAGE_NOACCESS          0x01\r\n    #define PAGE_READONLY          0x02\r\n    #define PAGE_READWRITE         0x04\r\n    #define PAGE_WRITECOPY         0x08 <- not supported\r\n\r\n    #define PAGE_EXECUTE           0x10\r\n    #define PAGE_EXECUTE_READ      0x20\r\n    #define PAGE_EXECUTE_READWRITE 0x40\r\n    #define PAGE_EXECUTE_WRITECOPY 0x80 <- not supported\r\n\r\n    #define PAGE_GUARD            0x100 <- not supported with PAGE_NOACCESS\r\n    #define PAGE_NOCACHE          0x200 <- not supported with PAGE_GUARD or PAGE_WRITECOMBINE\r\n    #define PAGE_WRITECOMBINE     0x400 <- not supported with PAGE_GUARD or PAGE_NOCACHE\r\n    *\/\r\n\r\n    static DWORD RemoveExecuteAccess(DWORD dwAccess)\r\n    {\r\n        \/\/These settings can trigger access violation.\r\n        DWORD dwBase = dwAccess & 0xFF;\r\n        DWORD dwHigh = dwAccess & 0xFFFFFF00;\r\n        switch(dwBase)\r\n        {\r\n        case PAGE_EXECUTE:\r\n            return dwHigh | PAGE_READONLY;\r\n        case PAGE_EXECUTE_READ:\r\n        case PAGE_EXECUTE_READWRITE:\r\n        case PAGE_EXECUTE_WRITECOPY:\r\n            return dwHigh | (dwBase >> 4); \/\/This removes execute in deed; https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa366786(v=vs.85).aspx - 0x1337 tricks\r\n        default:\r\n            return dwAccess;\r\n        }\r\n    }\r\n\r\n    static DWORD RemoveWriteAccess(DWORD dwAccess)\r\n    {\r\n        DWORD dwBase = dwAccess & 0xFF;\r\n        switch(dwBase)\r\n        {\r\n        case PAGE_READWRITE:\r\n        case PAGE_EXECUTE_READWRITE:\r\n            return (dwAccess & 0xFFFFFF00) | (dwBase >> 1);\r\n        default:\r\n            return dwAccess;\r\n        }\r\n    }\r\n\r\n    bool Process::SetNewPageProtection(ptr page, MemoryBreakpointData & data, MemoryType type)\r\n    {\r\n        DPRINTF();\r\n        \/\/TODO: handle PAGE_NOACCESS and such correctly (since it cannot be combined with PAGE_GUARD)\r\n\r\n        auto found = memoryBreakpointPages.find(page);\r\n        if(found == memoryBreakpointPages.end())\r\n        {\r\n            data.Refcount = 1;\r\n            switch(type)\r\n            {\r\n            case MemoryType::Access:\r\n            case MemoryType::Read:\r\n                data.NewProtect = data.OldProtect | PAGE_GUARD;\r\n                break;\r\n            case MemoryType::Write:\r\n                data.NewProtect = RemoveWriteAccess(data.OldProtect);\r\n                break;\r\n            case MemoryType::Execute:\r\n                data.NewProtect = permanentDep ? RemoveExecuteAccess(data.OldProtect) : data.OldProtect | PAGE_GUARD;\r\n                break;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            auto & oldData = found->second;\r\n            data.Type = oldData.Type | uint32(type); \/\/combines new protection\r\n            data.OldProtect = oldData.OldProtect; \/\/ old protection remains the same\r\n            data.Refcount = oldData.Refcount + 1; \/\/increment reference count\r\n            if(oldData.Type == uint32(type))  \/\/ Edge case for when you need to set a mem bpx on a same page with the same type, you just leave newProtect = OldProtect.\r\n            {\r\n                data.NewProtect = data.OldProtect;\r\n            }\r\n            else if(data.Type & uint32(MemoryType::Access) || data.Type & uint32(MemoryType::Read))  \/\/ Access\/Read always becomes PAGE_GUARD ; This page cannot access or Read?\r\n                data.NewProtect = data.OldProtect | PAGE_GUARD; \/\/as before\r\n            else if(data.Type & (uint32(MemoryType::Write) | uint32(MemoryType::Execute)))  \/\/ Write + Execute becomes either PAGE_GUARD or both write and execute flags removed\r\n                data.NewProtect = permanentDep ? RemoveExecuteAccess(RemoveWriteAccess(data.OldProtect)) : data.OldProtect | PAGE_GUARD;\r\n        }\r\n\r\n        dprintf(\"SetNewPageProtection(%p, %X)\\n\", page, data.NewProtect);\r\n        return MemProtect(page, PAGE_SIZE, data.NewProtect);\r\n    }\r\n\r\n    bool Process::SetMemoryBreakpoint(ptr address, ptr size, MemoryType type, bool singleshoot)\r\n    {\r\n        DPRINTF();\r\n        dprintf(\"SetMemoryBreakpoint(%p, %p, %d, %d)\\n\", address, size, type, singleshoot);\r\n        \/\/TODO: error reporting\r\n\r\n        \/\/basic checks\r\n        if(!MemIsValidPtr(address) || !size)\r\n            return false;\r\n\r\n        \/\/check if the range is unused for any previous memory breakpoints\r\n        auto range = Range(address, address + size - 1);\r\n        if(memoryBreakpointRanges.find(range) != memoryBreakpointRanges.end())\r\n            return false;\r\n\r\n        \/\/change page protections\r\n        bool success = true;\r\n        struct TempMemoryBreakpointData\r\n        {\r\n            ptr addr;\r\n            DWORD OldProtect;\r\n            MemoryBreakpointData data;\r\n        };\r\n        std::vector breakpointData;\r\n        {\r\n            breakpointData.reserve(size \/ PAGE_SIZE);\r\n            TempMemoryBreakpointData tempData;\r\n            MemoryBreakpointData data;\r\n            data.Type = uint32(type);\r\n            auto alignedAddress = PAGE_ALIGN(address);\r\n            for(auto page = alignedAddress; page < alignedAddress + ROUND_TO_PAGES(size); page += PAGE_SIZE)\r\n            {\r\n                MEMORY_BASIC_INFORMATION mbi;\r\n                if(!VirtualQueryEx(hProcess, LPCVOID(page), &mbi, sizeof(mbi)))\r\n                {\r\n                    success = false;\r\n                    dprintf(\"!VirtualQueryEx\\n\");\r\n                    break;\r\n                }\r\n                data.OldProtect = mbi.Protect;\r\n                if(!SetNewPageProtection(page, data, type))\r\n                {\r\n                    success = false;\r\n                    dprintf(\"!SetNewPageProtection\\n\");\r\n                    break;\r\n                }\r\n                tempData.addr = page;\r\n                tempData.OldProtect = mbi.Protect;\r\n                tempData.data = data;\r\n                breakpointData.push_back(tempData);\r\n            }\r\n        }\r\n\r\n        \/\/if changing the page protections failed, attempt to revert all protection changes\r\n        if(!success)\r\n        {\r\n            for(const auto & page : breakpointData)\r\n                MemProtect(page.addr, PAGE_SIZE, page.OldProtect);\r\n            return false;\r\n        }\r\n\r\n        \/\/set the page data\r\n        for(const auto & page : breakpointData)\r\n            memoryBreakpointPages[page.addr] = page.data;\r\n\r\n        \/\/setup the breakpoint information struct\r\n        BreakpointInfo info = {};\r\n        info.address = address;\r\n        info.singleshoot = singleshoot;\r\n        info.type = BreakpointType::Memory;\r\n        info.internal.memory.type = type;\r\n        info.internal.memory.size = size;\r\n\r\n        \/\/insert in the breakpoint map\r\n        breakpoints.insert({ { info.type, info.address }, info });\r\n        memoryBreakpointRanges.insert(range);\r\n\r\n        return true;\r\n    }\r\n\r\n    bool Process::SetMemoryBreakpoint(ptr address, ptr size, const BreakpointCallback & cbBreakpoint, MemoryType type, bool singleshoot)\r\n    {\r\n        \/\/check if a callback on this address was already found\r\n        if(breakpointCallbacks.find({ BreakpointType::Memory, address }) != breakpointCallbacks.end())\r\n            return false;\r\n        \/\/set the memory breakpoint\r\n        if(!SetMemoryBreakpoint(address, size, type, singleshoot))\r\n            return false;\r\n        \/\/insert the callback\r\n        breakpointCallbacks.insert({ { BreakpointType::Memory, address }, cbBreakpoint });\r\n        return true;\r\n    }\r\n\r\n    bool Process::DeleteMemoryBreakpoint(ptr address)\r\n    {\r\n        \/\/find the memory breakpoint range\r\n        auto range = memoryBreakpointRanges.find(Range(address, address));\r\n        if(range == memoryBreakpointRanges.end())\r\n            return false;\r\n\r\n        \/\/find the memory breakpoint\r\n        auto found = breakpoints.find({ BreakpointType::Memory, range->first });\r\n        if(found == breakpoints.end())\r\n            return false;\r\n        const auto & info = found->second;\r\n\r\n        \/\/delete the memory breakpoint from the pages\r\n        bool success = true;\r\n        auto alignedAddress = PAGE_ALIGN(info.address);\r\n        for(auto page = alignedAddress; page < alignedAddress + ROUND_TO_PAGES(info.internal.memory.size); page += PAGE_SIZE)\r\n        {\r\n            auto foundData = memoryBreakpointPages.find(page);\r\n            if(foundData == memoryBreakpointPages.end())\r\n                continue; \/\/TODO: error reporting\r\n            auto & data = foundData->second;\r\n            DWORD Protect;\r\n            data.Refcount--;\r\n            if(data.Refcount)\r\n            {\r\n                \/\/TODO: properly determine the new protection flag\r\n                \/\/Are there any other protections left?\r\n                \/\/If so add the guard\r\n                if(data.Type & ~uint32(info.internal.memory.type))\r\n                    data.NewProtect = data.OldProtect | PAGE_GUARD;\r\n                Protect = data.NewProtect;\r\n            }\r\n            else\r\n                Protect = data.OldProtect;\r\n            if(!MemProtect(page, PAGE_SIZE, Protect))\r\n                success = false;\r\n            if(!data.Refcount)\r\n                memoryBreakpointPages.erase(foundData);\r\n        }\r\n\r\n        \/\/delete the breakpoint from the maps\r\n        breakpoints.erase(found);\r\n        breakpointCallbacks.erase({ BreakpointType::Memory, address });\r\n        memoryBreakpointRanges.erase(Range(address, address));\r\n        return success;\r\n    }\r\n\r\n    bool Process::DeleteGenericBreakpoint(const BreakpointInfo & info)\r\n    {\r\n        switch(info.type)\r\n        {\r\n        case BreakpointType::Software:\r\n            return DeleteBreakpoint(info.address);\r\n        case BreakpointType::Hardware:\r\n            return DeleteHardwareBreakpoint(info.address);\r\n        case BreakpointType::Memory:\r\n            return DeleteMemoryBreakpoint(info.address);\r\n        default:\r\n            return false;\r\n        }\r\n    }\r\n};<|endoftext|>"}
{"text":"#include \"cute.h\"\n#include \"ide_listener.h\"\n#include \"xml_listener.h\"\n#include \"cute_runner.h\"\n\n#include \"MatVec.h\"\n\nvoid empty_double_initialisation() {\n\tMatVec vec;\n\tbool same{true};\n\n\tfor (auto& el : vec)\n\t\tsame &= el == 0;\n\tASSERTM(\"somewhere not the same\", same);\n}\n\nvoid test_norm2() {\n\tMatVec vec{-1,2,3};\n\tASSERTM(\"\", vec.norm2() == 14);\n}\n\nvoid test_norm() {\n\tMatVec vec{4,-3};\n\tASSERTM(\"\", vec.norm() == 5);\n}\n\nvoid scalar_product() {\n\tMatVec vec1{1,2,3};\n\tMatVec vec2{-1,-3,2};\n\n\tASSERTM(\"\",vec1*vec2 == -1);\n}\n\nvoid runAllTests(int argc, char const *argv[]){\n\tcute::suite s;\n\ts.push_back(CUTE(empty_double_initialisation));\n\ts.push_back(CUTE(scalar_product));\n\ts.push_back(CUTE(test_norm2));\n\ts.push_back(CUTE(test_norm));\n\t\/\/TODO add your test here\n\tcute::xml_file_opener xmlfile(argc,argv);\n\tcute::xml_listener >  lis(xmlfile.out);\n\tcute::makeRunner(lis,argc,argv)(s, \"AllTests\");\n}\n\nint main(int argc, char const *argv[]){\n    runAllTests(argc,argv);\n    return 0;\n}\n\n\n\nTests zu den Operationen#include \"cute.h\"\n#include \"ide_listener.h\"\n#include \"xml_listener.h\"\n#include \"cute_runner.h\"\n\n#include \"MatVec.h\"\n\nvoid empty_double_initialisation() {\n\tMatVec vec { };\n\tbool same{true};\n\n\tfor (auto& el : vec)\n\t\tsame &= el == 0;\n\tASSERTM(\"somewhere not the same\", same);\n}\n\nvoid vektor_addition() {\n\tMatVec vec1{1,2,3};\n\tMatVec vec2{-1,-3,2};\n\tMatVec res{0,-1,5};\n\n\tASSERTM(\"\", vec1 + vec2 == res);\n}\n\nvoid vektor_subtraktion() {\n\tMatVec vec1{1,2,3};\n\tMatVec vec2{-1,-3,2};\n\tMatVec res{2,5,1};\n\n\tASSERTM(\"\", vec1 - vec2 == res);\n}\n\nvoid vektorElemente_SkalarAddition() {\n\tMatVec vec{-1,-3,2};\n\tMatVec res{1,-1,4};\n\tdouble s = 2;\n\n\tASSERTM(\"\", vec + s == res);\n}\n\nvoid vektorElemente_SkalarSubtraktion() {\n\tMatVec vec{1,-3,2};\n\tMatVec res{-1,-5,0};\n\tdouble s = 2;\n\n\tASSERTM(\"\", vec - s == res);\n}\n\nvoid test_norm2() {\n\tMatVec vec{-1,2,3};\n\tASSERTM(\"\", vec.norm2() == 14);\n}\n\nvoid test_norm() {\n\tMatVec vec{4,-3};\n\tASSERTM(\"\", vec.norm() == 5);\n}\n\nvoid scalar_product() {\n\tMatVec vec1{1,2,3};\n\tMatVec vec2{-1,-3,2};\n\n\tASSERTM(\"\",vec1*vec2 == -1);\n}\n\nvoid multiplikation_skalar() {\n\tMatVec vec{1,-2,3};\n\tMatVec res{-2,4,-6};\n\tdouble skalar{-2};\n\n\tASSERTM(\"\", vec * skalar == res);\n}\n\nvoid division_skalar() {\n\tMatVec vec{-2,4,-6};\n\tMatVec res{1,-2,3};\n\tdouble skalar{-2};\n\n\tASSERTM(\"\", vec \/ skalar == res);\n}\n\nvoid make_negative() {\n\tMatVec vec{-2,4,-6};\n\tMatVec res{2,-4,6};\n\n\tASSERTM(\"\", -vec == res);\n}\n\n\nvoid runAllTests(int argc, char const *argv[]){\n\tcute::suite s;\n\ts.push_back(CUTE(empty_double_initialisation));\n\ts.push_back(CUTE(scalar_product));\n\ts.push_back(CUTE(test_norm2));\n\ts.push_back(CUTE(test_norm));\n\ts.push_back(CUTE(multiplikation_skalar));\n\ts.push_back(CUTE(division_skalar));\n\ts.push_back(CUTE(make_negative));\n\ts.push_back(CUTE(vektor_addition));\n\ts.push_back(CUTE(vektor_subtraktion));\n\ts.push_back(CUTE(vektorElemente_SkalarAddition));\n\ts.push_back(CUTE(vektorElemente_SkalarSubtraktion));\n\t\/\/TODO add your test here\n\tcute::xml_file_opener xmlfile(argc,argv);\n\tcute::xml_listener >  lis(xmlfile.out);\n\tcute::makeRunner(lis,argc,argv)(s, \"AllTests\");\n}\n\nint main(int argc, char const *argv[]){\n    runAllTests(argc,argv);\n    return 0;\n}\n\n\n\n<|endoftext|>"}
{"text":"\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2018 Intel Corporation. All Rights Reserved.\n\n#include \"software-device.h\"\n#include \"stream.h\"\n\nnamespace librealsense\n{\n    software_device::software_device()\n        : device(std::make_shared(backend_type::standard), {})\n    {\n        register_info(RS2_CAMERA_INFO_NAME, \"Software-Device\");\n    }\n\n    software_sensor& software_device::add_software_sensor(const std::string& name)\n    {\n        auto sensor = std::make_shared(name, this);\n        add_sensor(sensor);\n        _software_sensors.push_back(sensor);\n\n        return *sensor;\n    }\n\n    software_sensor& software_device::get_software_sensor(int index)\n    {\n        if (index >= _software_sensors.size())\n        {\n            throw rs2::error(\"Requested index is out of range!\");\n        }\n        return *_software_sensors[index];\n    }\n\n    void software_device::set_matcher_type(rs2_matchers matcher)\n    {\n        _matcher = matcher;\n    }\n\n    software_sensor::software_sensor(std::string name, software_device* owner)\n        : sensor_base(name, owner)\n    {\n\n    }\n\n    std::shared_ptr software_device::create_matcher(const frame_holder& frame) const\n    {\n        std::vector profiles;\n\n        for (auto&& s : _software_sensors)\n            for (auto&& p : s->get_stream_profiles())\n                profiles.push_back(p.get());\n\n        return matcher_factory::create(_matcher, profiles);\n    }\n\n    std::shared_ptr software_sensor::add_video_stream(rs2_video_stream video_stream)\n    {\n        auto exist = (std::find_if(_profiles.begin(), _profiles.end(), [&](std::shared_ptr profile)\n        {\n            if (profile->get_unique_id() == video_stream.uid)\n            {\n                return true;\n            }\n            return false;\n        } ) != _profiles.end());\n\n        if (exist)\n        {\n            LOG_WARNING(\"Stream unique ID already exist!\");\n            throw rs2::error(\"Stream unique ID already exist!\");\n        }\n\n        auto profile = std::make_shared(\n            platform::stream_profile{ (uint32_t)video_stream.width, (uint32_t)video_stream.height, (uint32_t)video_stream.fps, 0 });\n        profile->set_dims(video_stream.width, video_stream.height);\n        profile->set_format(video_stream.fmt);\n        profile->set_framerate(video_stream.fps);\n        profile->set_stream_index(video_stream.index);\n        profile->set_stream_type(video_stream.type);\n        profile->set_unique_id(video_stream.uid);\n        profile->set_intrinsics([=]() {return video_stream.intrinsics; });\n        _profiles.push_back(profile);\n\n        return profile;\n    }\n\n    stream_profiles software_sensor::init_stream_profiles()\n    {\n        return _profiles;\n    }\n\n    void software_sensor::open(const stream_profiles& requests)\n    {\n\n    }\n    void software_sensor::close()\n    {\n\n    }\n\n    void software_sensor::start(frame_callback_ptr callback)\n    {\n        _source.init(_metadata_parsers);\n        _source.set_sensor(this->shared_from_this());\n        _source.set_callback(callback);\n    }\n\n    void software_sensor::stop()\n    {\n        _source.flush();\n        _source.reset();\n    }\n\n    void software_sensor::on_video_frame(rs2_software_video_frame software_frame)\n    {\n        frame_additional_data data;\n        data.timestamp = software_frame.timestamp;\n        data.timestamp_domain = software_frame.domain;\n        data.frame_number = software_frame.frame_number;\n\n        rs2_extension extension = software_frame.profile->profile->get_stream_type() == RS2_STREAM_DEPTH ?\n            RS2_EXTENSION_DEPTH_FRAME : RS2_EXTENSION_VIDEO_FRAME;\n\n        auto frame = _source.alloc_frame(extension, 0, data, false);\n\n        auto vid_profile = dynamic_cast(software_frame.profile->profile);\n        auto vid_frame = dynamic_cast(frame);\n        vid_frame->assign(vid_profile->get_width(), vid_profile->get_height(), software_frame.stride, software_frame.bpp);\n\n        frame->set_stream(std::dynamic_pointer_cast(software_frame.profile->profile->shared_from_this()));\n        frame->attach_continuation(frame_continuation{ [=]() {\n            software_frame.deleter(software_frame.pixels);\n        }, software_frame.pixels });\n        _source.invoke_callback(frame);\n    }\n\n    void software_sensor::add_read_only_option(rs2_option option, float val)\n    {\n        register_option(RS2_OPTION_DEPTH_UNITS, std::make_shared(\"bypass sensor read only option\",\n            lazy([=]() { return val; })));\n    }\n\n    void software_sensor::update_read_only_option(rs2_option option, float val)\n    {\n        get_option(option).set(val);\n    }\n}\n\nFixes to the software device to enable recording into ROS-bag\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2018 Intel Corporation. All Rights Reserved.\n\n#include \"software-device.h\"\n#include \"stream.h\"\n\nnamespace librealsense\n{\n    software_device::software_device()\n        : device(std::make_shared(backend_type::standard), {})\n    {\n        register_info(RS2_CAMERA_INFO_NAME, \"Software-Device\");\n    }\n\n    software_sensor& software_device::add_software_sensor(const std::string& name)\n    {\n        auto sensor = std::make_shared(name, this);\n        add_sensor(sensor);\n        _software_sensors.push_back(sensor);\n\n        return *sensor;\n    }\n\n    software_sensor& software_device::get_software_sensor(int index)\n    {\n        if (index >= _software_sensors.size())\n        {\n            throw rs2::error(\"Requested index is out of range!\");\n        }\n        return *_software_sensors[index];\n    }\n\n    void software_device::set_matcher_type(rs2_matchers matcher)\n    {\n        _matcher = matcher;\n    }\n\n    software_sensor::software_sensor(std::string name, software_device* owner)\n        : sensor_base(name, owner)\n    {\n\n    }\n\n    std::shared_ptr software_device::create_matcher(const frame_holder& frame) const\n    {\n        std::vector profiles;\n\n        for (auto&& s : _software_sensors)\n            for (auto&& p : s->get_stream_profiles())\n                profiles.push_back(p.get());\n\n        return matcher_factory::create(_matcher, profiles);\n    }\n\n    std::shared_ptr software_sensor::add_video_stream(rs2_video_stream video_stream)\n    {\n        auto exist = (std::find_if(_profiles.begin(), _profiles.end(), [&](std::shared_ptr profile)\n        {\n            if (profile->get_unique_id() == video_stream.uid)\n            {\n                return true;\n            }\n            return false;\n        } ) != _profiles.end());\n\n        if (exist)\n        {\n            LOG_WARNING(\"Stream unique ID already exist!\");\n            throw rs2::error(\"Stream unique ID already exist!\");\n        }\n\n        auto profile = std::make_shared(\n            platform::stream_profile{ (uint32_t)video_stream.width, (uint32_t)video_stream.height, (uint32_t)video_stream.fps, 0 });\n        profile->set_dims(video_stream.width, video_stream.height);\n        profile->set_format(video_stream.fmt);\n        profile->set_framerate(video_stream.fps);\n        profile->set_stream_index(video_stream.index);\n        profile->set_stream_type(video_stream.type);\n        profile->set_unique_id(video_stream.uid);\n        profile->set_intrinsics([=]() {return video_stream.intrinsics; });\n        _profiles.push_back(profile);\n\n        return profile;\n    }\n\n    stream_profiles software_sensor::init_stream_profiles()\n    {\n        return _profiles;\n    }\n\n    void software_sensor::open(const stream_profiles& requests)\n    {\n        set_active_streams(requests);\n    }\n\n    void software_sensor::close(){}\n\n    void software_sensor::start(frame_callback_ptr callback)\n    {\n        _source.init(_metadata_parsers);\n        _source.set_sensor(this->shared_from_this());\n        _source.set_callback(callback);\n        raise_on_before_streaming_changes(true);\n    }\n\n    void software_sensor::stop()\n    {\n        raise_on_before_streaming_changes(false);\n        _source.flush();\n        _source.reset();\n    }\n\n    void software_sensor::on_video_frame(rs2_software_video_frame software_frame)\n    {\n        frame_additional_data data;\n        data.timestamp = software_frame.timestamp;\n        data.timestamp_domain = software_frame.domain;\n        data.frame_number = software_frame.frame_number;\n\n        rs2_extension extension = software_frame.profile->profile->get_stream_type() == RS2_STREAM_DEPTH ?\n            RS2_EXTENSION_DEPTH_FRAME : RS2_EXTENSION_VIDEO_FRAME;\n\n        auto frame = _source.alloc_frame(extension, 0, data, false);\n        if (!frame) return;\n\n        auto vid_profile = dynamic_cast(software_frame.profile->profile);\n        auto vid_frame = dynamic_cast(frame);\n        vid_frame->assign(vid_profile->get_width(), vid_profile->get_height(), software_frame.stride, software_frame.bpp);\n\n        frame->set_stream(std::dynamic_pointer_cast(software_frame.profile->profile->shared_from_this()));\n        frame->attach_continuation(frame_continuation{ [=]() {\n            software_frame.deleter(software_frame.pixels);\n        }, software_frame.pixels });\n        _source.invoke_callback(frame);\n    }\n\n    void software_sensor::add_read_only_option(rs2_option option, float val)\n    {\n        register_option(RS2_OPTION_DEPTH_UNITS, std::make_shared(\"bypass sensor read only option\",\n            lazy([=]() { return val; })));\n    }\n\n    void software_sensor::update_read_only_option(rs2_option option, float val)\n    {\n        get_option(option).set(val);\n    }\n}\n\n<|endoftext|>"}
{"text":"\/*\n  Copyright (c) DataStax, Inc.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*\/\n\n#ifndef DATASTAX_INTERNAL_SSL_NO_IMPL_HPP\n#define DATASTAX_INTERNAL_SSL_NO_IMPL_HPP\n\nnamespace datastax { namespace internal { namespace core {\n\nclass NoSslSession : public SslSession {\npublic:\n  NoSslSession(const Address& address, const String& hostname, const String& sni_server_name);\n\n  virtual bool is_handshake_done() const { return false; }\n  virtual void do_handshake() {}\n  virtual void verify() {}\n\n  virtual int encrypt(const char* buf, size_t size) { return -1; }\n  virtual int decrypt(char* buf, size_t size) { return -1; }\n};\n\nclass NoSslContext : public SslContext {\npublic:\n  virtual SslSession* create_session(const Address& address, const String& hostname);\n\n  virtual CassError add_trusted_cert(const char* cert, size_t cert_length);\n  virtual CassError set_cert(const char* cert, size_t cert_length);\n  virtual CassError set_private_key(const char* key, size_t key_length, const char* password,\n                                    size_t password_length);\n};\n\nclass NoSslContextFactory : public SslContextFactoryBase {\npublic:\n  static SslContext::Ptr create();\n  static void internal_init() {}\n  static void internal_thread_cleanup() {}\n  static void internal_cleanup() {}\n};\n\ntypedef SslContextFactoryBase SslContextFactory;\n\n}}} \/\/ namespace datastax::internal::core\n\n#endif\nFix silly error that made it to release\/*\n  Copyright (c) DataStax, Inc.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*\/\n\n#ifndef DATASTAX_INTERNAL_SSL_NO_IMPL_HPP\n#define DATASTAX_INTERNAL_SSL_NO_IMPL_HPP\n\nnamespace datastax { namespace internal { namespace core {\n\nclass NoSslSession : public SslSession {\npublic:\n  NoSslSession(const Address& address, const String& hostname, const String& sni_server_name);\n\n  virtual bool is_handshake_done() const { return false; }\n  virtual void do_handshake() {}\n  virtual void verify() {}\n\n  virtual int encrypt(const char* buf, size_t size) { return -1; }\n  virtual int decrypt(char* buf, size_t size) { return -1; }\n};\n\nclass NoSslContext : public SslContext {\npublic:\n  virtual SslSession* create_session(const Address& address, const String& hostname, const String& sni_server_name);\n\n  virtual CassError add_trusted_cert(const char* cert, size_t cert_length);\n  virtual CassError set_cert(const char* cert, size_t cert_length);\n  virtual CassError set_private_key(const char* key, size_t key_length, const char* password,\n                                    size_t password_length);\n};\n\nclass NoSslContextFactory : public SslContextFactoryBase {\npublic:\n  static SslContext::Ptr create();\n  static void internal_init() {}\n  static void internal_thread_cleanup() {}\n  static void internal_cleanup() {}\n};\n\ntypedef SslContextFactoryBase SslContextFactory;\n\n}}} \/\/ namespace datastax::internal::core\n\n#endif\n<|endoftext|>"}
{"text":"\/***************************************************************************\n *   Copyright (C) 2008 by Jason Ansel                                     *\n *   jansel@csail.mit.edu                                                  *\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 3 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************\/\n#include \"staticscheduler.h\"\n#include \"transform.h\"\n#include \"jasm.h\"\n#include \"codegenerator.h\"\n\nnamespace { \/\/file local\nvoid _remapSet(petabricks::ScheduleNodeSet& set, const petabricks::ScheduleNodeRemapping& map){\n  using namespace petabricks;\n  for(ScheduleNodeRemapping::const_iterator i=map.begin(); i!=map.end(); ++i){\n    ScheduleNodeSet::iterator rslt = set.find(i->first);\n    if(rslt!=set.end()){\n      set.erase(rslt);\n      set.insert(i->second);\n    }\n  }\n}\n}\n\n\npetabricks::ScheduleNode::ScheduleNode()\n  : _isInput(false)\n  , _isLast(false)\n{\n  static jalib::AtomicT i=0;\n  _id=jalib::atomicIncrementReturn(&i);\n}\n\n\npetabricks::StaticScheduler::StaticScheduler(const ChoiceGridMap& cg){\n  for(ChoiceGridMap::const_iterator m=cg.begin(); m!=cg.end(); ++m){\n    ScheduleNodeList& regions = _matrixToNodes[m->first];\n    for(ChoiceGridIndex::const_iterator i=m->second.begin(); i!=m->second.end(); ++i){\n      SimpleRegionPtr tmp = new SimpleRegion(i->first);\n      regions.push_back(new UnischeduledNode(m->first, tmp, i->second));\n      _allNodes.push_back(regions.back());\n    }\n  }\n}\n\npetabricks::ScheduleNodeSet petabricks::StaticScheduler::lookupNode(const MatrixDefPtr& matrix, const SimpleRegionPtr& region){\n  ScheduleNodeSet rv;\n  ScheduleNodeList& regions = _matrixToNodes[matrix];\n  if(matrix->numDimensions()==0){\n    JASSERT(regions.size()==1);\n    rv.insert(regions.begin()->asPtr());\n  }else{\n    for(ScheduleNodeList::iterator i=regions.begin(); i!=regions.end(); ++i){\n      if(region->toString() == (*i)->region()->toString()){\n        rv.insert(i->asPtr());\n        break; \/\/optimization\n      }\n      if((*i)->region()->hasIntersect(region)){\n        rv.insert(i->asPtr());\n      }\n    }\n  }\n  JASSERT(rv.size()>0)(matrix)(region).Text(\"failed to find rule for region\");\n  return rv;\n}\n\nvoid petabricks::StaticScheduler::generateSchedule(){\n  #ifdef DEBUG \n\/\/   writeGraphAsPDF(\"schedule_initial.pdf\");\n  #endif\n\n  computeIndirectDependencies();\n\n  mergeCoscheduledNodes();\n\n  #ifdef DEBUG \n  writeGraphAsPDF(\"schedule.pdf\");\n  #endif\n\n  for( std::set::const_iterator i=_goals.begin()\n      ; i!=_goals.end()\n      ; ++i )\n  {\n    depthFirstSchedule(*i);\n  }\n}\n\nvoid petabricks::StaticScheduler::computeIndirectDependencies(){\n  \/\/ this algorithm can be optimized, but since graphs are small it doesn't matter\n  for(int c=1; c>0;){ \/\/keep interating until no changes have been made\n    c=0;\n    for(ScheduleNodeList::iterator i=_allNodes.begin(); i!=_allNodes.end(); ++i)\n      c+=(*i)->updateIndirectDepends();\n  }\n}\n\nvoid petabricks::StaticScheduler::mergeCoscheduledNodes(){\n  ScheduleNodeSet done;\n  ScheduleNodeRemapping mapping;\n  ScheduleNodeList tmp = _allNodes;\n  for(ScheduleNodeList::iterator i=tmp.begin(); i!=tmp.end(); ++i){\n    if(done.find(i->asPtr()) == done.end()){\n      ScheduleNodeSet set=(*i)->getStronglyConnectedComponent();\n      done.insert(set.begin(),set.end());\n      if(set.size()>1){\n        JTRACE(\"coscheduling nodes\")((*i)->nodename())(set.size());\n        ScheduleNode* coscheduled = new CoscheduledNode(set);\n        _allNodes.push_back(coscheduled);\n        for(ScheduleNodeSet::iterator e=set.begin();e!=set.end(); ++e)\n          mapping[*e] = coscheduled;\n      }\n    }\n  }\n  applyRemapping(mapping);\n}\n\nvoid petabricks::StaticScheduler::applyRemapping(const ScheduleNodeRemapping& m){\n  for(ScheduleNodeList::iterator i=_allNodes.begin(); i!=_allNodes.end(); ++i){\n      (*i)->applyRemapping(m);\n  }\n  _remapSet(_goals, m);\n  _remapSet(_generated, m);\n  _remapSet(_pending, m);\n  ScheduleNodeList tmp;\n  _allNodes.swap(tmp);\n  _allNodes.reserve(tmp.size());\n  for(ScheduleNodeList::iterator i=tmp.begin(); i!=tmp.end(); ++i){\n    if(m.find(i->asPtr())==m.end())\n      _allNodes.push_back(*i);\n    else\n      _remappedNodes.push_back(*i);\n  }\n}\n\nvoid petabricks::StaticScheduler::depthFirstSchedule(ScheduleNode* n){\n  if(_generated.find(n)!=_generated.end())\n    return;\n\n  JASSERT(_pending.find(n)==_pending.end()).Text(\"dependency cycle\");\n  _pending.insert(n);\n\n  for( ScheduleDependencies::const_iterator i=n->directDepends().begin()\n      ; i!=n->directDepends().end()\n      ; ++i)\n  {\n    if(i->first != n)\n      depthFirstSchedule(i->first);\n  }\n\/\/   JTRACE(\"scheduling\")(n->matrix()); \n  _schedule.push_back(n);\n  _generated.insert(n);\n}\n\nvoid petabricks::StaticScheduler::generateCodeDynamic(Transform& trans, CodeGenerator& o){\n  JASSERT(_schedule.size()>0);\n  for(ScheduleNodeList::iterator i=_schedule.begin(); i!=_schedule.end(); ++i){\n    if(i!=_schedule.begin()) o.continuationPoint();\n    (*i)->generateCodeSimple(trans, o, false);\n  }\n  o.write(\"DynamicTaskPtr  _fini = new NullDynamicTask();\");\n  for(ScheduleNodeSet::iterator i=_goals.begin(); i!=_goals.end(); ++i)\n    o.write(\"_fini->dependsOn(\" + (*i)->nodename() + \".completionTask());\");\n  o.withEachMember(\"SpatialTaskList\", \".clear()\");\n  o.withEachMember(\"DynamicTaskPtr\", \"=0\");\n  o.write(\"return _fini;\");\n}\nvoid petabricks::StaticScheduler::generateCodeStatic(Transform& trans, CodeGenerator& o){\n  JASSERT(_schedule.size()>0);\n  for(ScheduleNodeList::iterator i=_schedule.begin(); i!=_schedule.end(); ++i){\n    (*i)->generateCodeSimple(trans, o, true);\n  }\n}\n\nvoid petabricks::UnischeduledNode::generateCodeSimple(Transform& trans, CodeGenerator& o, bool isStatic){\n  RuleChoicePtr rule = trans.learner().makeRuleChoice(_choices->rules(), _matrix, _region);\n  if(!isStatic){\n    o.addMember(\"SpatialTaskList\", nodename(), \"\");\n    rule->generateCodeSimple(false, nodename(), trans, *this, _region, o);\n  }else{\n    rule->generateCodeSimple(true, \"\", trans, *this, _region, o);\n  }\n}\n\nvoid petabricks::ScheduleNode::printDepsAndEnqueue(CodeGenerator& o, Transform& trans,  const RulePtr& rule, bool useDirections){\n\/\/bool printedBeforeDep = false;\n\n  ScheduleDependencies::const_iterator sd = _indirectDepends.find(this);\n  if(sd==_indirectDepends.end() && rule->isSingleElement()){\n    trans.markSplitSizeUse(o);\n    o.write(nodename()+\".spatialSplit(\"SPLIT_CHUNK_SIZE\");\");\n  }else{\n    \/\/TODO split selfdep tasks too\n  }\n\n  for(ScheduleDependencies::const_iterator i=_directDepends.begin();  i!=_directDepends.end(); ++i){\n    if(i->first!=this){\n      if(i->first->isInput()){\n\/\/      if(!printedBeforeDep){\n\/\/       printedBeforeDep=true;\n\/\/       if(useDirections)\n\/\/         o.write(nodename()+\".dependsOn(_before);\");\n\/\/       else\n\/\/         o.write(nodename()+\"->dependsOn(_before);\");\n\/\/      }\n      }else{\n        if(useDirections){\n          o.write(\"{\"); \n          o.incIndent();\n          o.write(\"DependencyDirection::DirectionT _dir[] = {\"+i->second.direction.toCodeStr()+\"};\");\n          o.write(nodename()+\".dependsOn<\"+jalib::XToString(i->second.direction.size())+\">\"\n                            \"(\"+i->first->nodename()+\", _dir);\");\n          o.decIndent();\n          o.write(\"}\"); \n        }else{\n          o.write(nodename()+\"->dependsOn(\"+i->first->nodename()+\");\");\n        }\n      }\n    }\n  }\n  if(!_isLast)\n    o.write(nodename()+\"->enqueue();\");\n}\n\nvoid petabricks::UnischeduledNode::generateCodeForSlice(Transform& trans, CodeGenerator& o, int d, const FormulaPtr& pos, bool isStatic){\n  RuleChoicePtr rule = trans.learner().makeRuleChoice(_choices->rules(), _matrix, _region);\n  \n  CoordinateFormula min = _region->minCoord();\n  CoordinateFormula max = _region->maxCoord();\n\n  min[d] = pos;\n  max[d] = pos->plusOne();\n\n  SimpleRegionPtr t = new SimpleRegion(min,max);\n\n  rule->generateCodeSimple(isStatic, \"\", trans, *this, t, o);\n  \/\/TODO deps for slice\n}\n\n\nvoid petabricks::StaticScheduler::writeGraphAsPDF(const char* filename) const{\n  std::string schedulerGraph = toString();\n  FILE* fd = popen((\"dot -Grankdir=LR -Tpdf -o \"+std::string(filename)).c_str(), \"w\");\n  fwrite(schedulerGraph.c_str(),1,schedulerGraph.length(),fd);\n  pclose(fd);\n}\n\nint petabricks::ScheduleNode::updateIndirectDepends(){\n  int c = 0;\n  if(_indirectDepends.empty()){  \/\/ seed first iteration\n    _indirectDepends = _directDepends;\n    c+=_indirectDepends.size();\n  }\n  ScheduleDependencies tmp = _indirectDepends;\n  for(ScheduleDependencies::iterator i=tmp.begin(); i!=tmp.end(); ++i){\n    const ScheduleDependencies& remote = i->first->indirectDepends();\n    for( ScheduleDependencies::const_iterator dep=remote.begin(); dep!=remote.end(); ++dep)\n    { \/\/for each dependency\n      if(_indirectDepends[dep->first].merge(dep->second))\n        ++c;\n    }\n  }\n  return c;\n}\n\npetabricks::ScheduleNodeSet petabricks::ScheduleNode::getStronglyConnectedComponent(){\n  \/\/\/ compute strongly connected component\n  ScheduleNodeSet s;\n  s.insert(this);\n  if(_indirectDepends.find(this)==_indirectDepends.end())\n    return s;\n\n  for(ScheduleDependencies::iterator i=_indirectDepends.begin(); i!=_indirectDepends.end(); ++i){\n    if(i->first->indirectDepends().find(this)!=i->first->indirectDepends().end()) \/\/if in a cycle with this\n      s.insert(i->first);\n  }\n  return s;\n}\n\npetabricks::CoscheduledNode::CoscheduledNode(const ScheduleNodeSet& set)\n  : _originalNodes(set)\n{\n  for(ScheduleNodeSet::const_iterator i=set.begin(); i!=set.end(); ++i){\n    _directDepends.merge((*i)->directDepends());\n    _indirectDepends.merge((*i)->indirectDepends());\n  }\n}\n\n\nvoid petabricks::CoscheduledNode::generateCodeSimple(Transform& trans, CodeGenerator& o, bool isStatic){\n  const DependencyInformation& selfDep = _indirectDepends[this];\n\n  if(selfDep.direction.isNone()){\n    if(!isStatic) o.addMember(\"SpatialTaskList\", nodename(), \"\");\n    o.comment(\"Dual outputs compacted \"+nodename());\n    std::string region;\n    ScheduleNode* first = NULL;\n    \/\/test matching region extents in d\n    for(ScheduleNodeSet::const_iterator i=_originalNodes.begin(); i!=_originalNodes.end(); ++i){\n      if(first==NULL){\n        region=(*i)->region()->toString();\n        first=*i;\n      }\n      else if(first->region()->dimensions()<(*i)->region()->dimensions())\n        first=*i;\n      JWARNING(region==(*i)->region()->toString())(region)((*i)->region()->toString())\n        .Text(\"to(...) regions of differing size not yet supported\");\n    }\n    RuleChoicePtr rule = trans.learner().makeRuleChoice(first->choices()->rules(), first->matrix(), first->region());\n    rule->generateCodeSimple(isStatic, nodename(), trans, *this, first->region(), o);\n  }else{\n    if(!isStatic) o.addMember(\"DynamicTaskPtr\", nodename(),\"\");\n    std::vector args;\n    args.push_back(\"const jalib::JRef<\"+trans.instClassName()+\"> transform\");\n    TaskCodeGenerator* task;\n    if(!isStatic) task=&o.createTask(\"coscheduled_\"+nodename(), args, \"DynamicTask\", \"_task\");\n    CodeGenerator& ot = isStatic ? o : *task;\n    std::string varname=\"coscheduled_\"+nodename();\n    if(!isStatic){\n      task->beginRunFunc();\n      for(FreeVars::const_iterator i=trans.constants().begin()\n         ;i!=trans.constants().end()\n         ;++i)\n      {\n        ot.define(*i, \"(transform->\"+*i+\")\");\n      }\n    }\n    \n    for(size_t d=selfDep.direction.size()-1; d>=0; --d){\n      bool passed=true;\n      FormulaPtr begin,end;\n    \n      \/\/test matching region extents in d\n      for(ScheduleNodeSet::const_iterator i=_originalNodes.begin(); i!=_originalNodes.end(); ++i){\n        if(!begin) begin = (*i)->region()->minCoord()[d];\n        if(!end)   end   = (*i)->region()->maxCoord()[d];\n        if(   begin->toString() != (*i)->region()->minCoord()[d]->toString()\n          ||  end->toString()   != (*i)->region()->maxCoord()[d]->toString())\n        {\n          JTRACE(\"Can't coschedule due to mismatched extents\")(d);\n          passed=false;\n          break;\n        }\n      }\n      if(!passed) continue;\n      \n      \/\/test direction\n      if((selfDep.direction[d]& ~DependencyDirection::D_LE) == 0){\n        JTRACE(\"Coscheduling forward\")(d)(*this);\n        ot.beginFor(varname, begin, end, FormulaInteger::one());\n      }else if((selfDep.direction[d]& ~DependencyDirection::D_GE) == 0){\n        JTRACE(\"Coscheduling backward\")(d)(*this);\n        ot.beginReverseFor(varname, begin, end, FormulaInteger::one());\n      }else{\n        JTRACE(\"Can't coschedule due to mismatched direction\")(d);\n        passed=false;\n        continue;\n      }\n\n      for(ScheduleNodeSet::iterator i=_originalNodes.begin(); i!=_originalNodes.end(); ++i){\n        (*i)->generateCodeForSlice(trans, ot, d, new FormulaVariable(varname), isStatic);\n      }\n      ot.endFor();\n      if(!isStatic){\n        ot.write(\"return NULL;\");\n        ot.undefineAll();\n        ot.endFunc();\n        std::vector args(1, \"this\");\n        o.setcall(nodename(),\"new \"+varname+\"_task\", args);\n        printDepsAndEnqueue(o, trans, NULL, false);\n      }\n      return;\n    }\n    JASSERT(false)(*this)(selfDep.direction).Text(\"Unresolved dependency cycle\");\n  }\n}\n- fixed input_count bug for coscheduled tasks (rootsolve bug)\/***************************************************************************\n *   Copyright (C) 2008 by Jason Ansel                                     *\n *   jansel@csail.mit.edu                                                  *\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 3 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************\/\n#include \"staticscheduler.h\"\n#include \"transform.h\"\n#include \"jasm.h\"\n#include \"codegenerator.h\"\n\nnamespace { \/\/file local\nvoid _remapSet(petabricks::ScheduleNodeSet& set, const petabricks::ScheduleNodeRemapping& map){\n  using namespace petabricks;\n  for(ScheduleNodeRemapping::const_iterator i=map.begin(); i!=map.end(); ++i){\n    ScheduleNodeSet::iterator rslt = set.find(i->first);\n    if(rslt!=set.end()){\n      set.erase(rslt);\n      set.insert(i->second);\n    }\n  }\n}\n}\n\n\npetabricks::ScheduleNode::ScheduleNode()\n  : _isInput(false)\n  , _isLast(false)\n{\n  static jalib::AtomicT i=0;\n  _id=jalib::atomicIncrementReturn(&i);\n}\n\n\npetabricks::StaticScheduler::StaticScheduler(const ChoiceGridMap& cg){\n  for(ChoiceGridMap::const_iterator m=cg.begin(); m!=cg.end(); ++m){\n    ScheduleNodeList& regions = _matrixToNodes[m->first];\n    for(ChoiceGridIndex::const_iterator i=m->second.begin(); i!=m->second.end(); ++i){\n      SimpleRegionPtr tmp = new SimpleRegion(i->first);\n      regions.push_back(new UnischeduledNode(m->first, tmp, i->second));\n      _allNodes.push_back(regions.back());\n    }\n  }\n}\n\npetabricks::ScheduleNodeSet petabricks::StaticScheduler::lookupNode(const MatrixDefPtr& matrix, const SimpleRegionPtr& region){\n  ScheduleNodeSet rv;\n  ScheduleNodeList& regions = _matrixToNodes[matrix];\n  if(matrix->numDimensions()==0){\n    JASSERT(regions.size()==1);\n    rv.insert(regions.begin()->asPtr());\n  }else{\n    for(ScheduleNodeList::iterator i=regions.begin(); i!=regions.end(); ++i){\n      if(region->toString() == (*i)->region()->toString()){\n        rv.insert(i->asPtr());\n        break; \/\/optimization\n      }\n      if((*i)->region()->hasIntersect(region)){\n        rv.insert(i->asPtr());\n      }\n    }\n  }\n  JASSERT(rv.size()>0)(matrix)(region).Text(\"failed to find rule for region\");\n  return rv;\n}\n\nvoid petabricks::StaticScheduler::generateSchedule(){\n  #ifdef DEBUG \n\/\/   writeGraphAsPDF(\"schedule_initial.pdf\");\n  #endif\n\n  computeIndirectDependencies();\n\n  mergeCoscheduledNodes();\n\n  #ifdef DEBUG \n  writeGraphAsPDF(\"schedule.pdf\");\n  #endif\n\n  for( std::set::const_iterator i=_goals.begin()\n      ; i!=_goals.end()\n      ; ++i )\n  {\n    depthFirstSchedule(*i);\n  }\n}\n\nvoid petabricks::StaticScheduler::computeIndirectDependencies(){\n  \/\/ this algorithm can be optimized, but since graphs are small it doesn't matter\n  for(int c=1; c>0;){ \/\/keep interating until no changes have been made\n    c=0;\n    for(ScheduleNodeList::iterator i=_allNodes.begin(); i!=_allNodes.end(); ++i)\n      c+=(*i)->updateIndirectDepends();\n  }\n}\n\nvoid petabricks::StaticScheduler::mergeCoscheduledNodes(){\n  ScheduleNodeSet done;\n  ScheduleNodeRemapping mapping;\n  ScheduleNodeList tmp = _allNodes;\n  for(ScheduleNodeList::iterator i=tmp.begin(); i!=tmp.end(); ++i){\n    if(done.find(i->asPtr()) == done.end()){\n      ScheduleNodeSet set=(*i)->getStronglyConnectedComponent();\n      done.insert(set.begin(),set.end());\n      if(set.size()>1){\n        JTRACE(\"coscheduling nodes\")((*i)->nodename())(set.size());\n        ScheduleNode* coscheduled = new CoscheduledNode(set);\n        _allNodes.push_back(coscheduled);\n        for(ScheduleNodeSet::iterator e=set.begin();e!=set.end(); ++e)\n          mapping[*e] = coscheduled;\n      }\n    }\n  }\n  applyRemapping(mapping);\n}\n\nvoid petabricks::StaticScheduler::applyRemapping(const ScheduleNodeRemapping& m){\n  for(ScheduleNodeList::iterator i=_allNodes.begin(); i!=_allNodes.end(); ++i){\n      (*i)->applyRemapping(m);\n  }\n  _remapSet(_goals, m);\n  _remapSet(_generated, m);\n  _remapSet(_pending, m);\n  ScheduleNodeList tmp;\n  _allNodes.swap(tmp);\n  _allNodes.reserve(tmp.size());\n  for(ScheduleNodeList::iterator i=tmp.begin(); i!=tmp.end(); ++i){\n    if(m.find(i->asPtr())==m.end())\n      _allNodes.push_back(*i);\n    else\n      _remappedNodes.push_back(*i);\n  }\n}\n\nvoid petabricks::StaticScheduler::depthFirstSchedule(ScheduleNode* n){\n  if(_generated.find(n)!=_generated.end())\n    return;\n\n  JASSERT(_pending.find(n)==_pending.end()).Text(\"dependency cycle\");\n  _pending.insert(n);\n\n  for( ScheduleDependencies::const_iterator i=n->directDepends().begin()\n      ; i!=n->directDepends().end()\n      ; ++i)\n  {\n    if(i->first != n)\n      depthFirstSchedule(i->first);\n  }\n\/\/   JTRACE(\"scheduling\")(n->matrix()); \n  _schedule.push_back(n);\n  _generated.insert(n);\n}\n\nvoid petabricks::StaticScheduler::generateCodeDynamic(Transform& trans, CodeGenerator& o){\n  JASSERT(_schedule.size()>0);\n  for(ScheduleNodeList::iterator i=_schedule.begin(); i!=_schedule.end(); ++i){\n    if(i!=_schedule.begin()) o.continuationPoint();\n    (*i)->generateCodeSimple(trans, o, false);\n  }\n  o.write(\"DynamicTaskPtr  _fini = new NullDynamicTask();\");\n  for(ScheduleNodeSet::iterator i=_goals.begin(); i!=_goals.end(); ++i)\n    o.write(\"_fini->dependsOn(\" + (*i)->nodename() + \".completionTask());\");\n  o.withEachMember(\"SpatialTaskList\", \".clear()\");\n  o.withEachMember(\"DynamicTaskPtr\", \"=0\");\n  o.write(\"return _fini;\");\n}\nvoid petabricks::StaticScheduler::generateCodeStatic(Transform& trans, CodeGenerator& o){\n  JASSERT(_schedule.size()>0);\n  for(ScheduleNodeList::iterator i=_schedule.begin(); i!=_schedule.end(); ++i){\n    (*i)->generateCodeSimple(trans, o, true);\n  }\n}\n\nvoid petabricks::UnischeduledNode::generateCodeSimple(Transform& trans, CodeGenerator& o, bool isStatic){\n  RuleChoicePtr rule = trans.learner().makeRuleChoice(_choices->rules(), _matrix, _region);\n  if(!isStatic){\n    o.addMember(\"SpatialTaskList\", nodename(), \"\");\n    rule->generateCodeSimple(false, nodename(), trans, *this, _region, o);\n  }else{\n    rule->generateCodeSimple(true, \"\", trans, *this, _region, o);\n  }\n}\n\nvoid petabricks::ScheduleNode::printDepsAndEnqueue(CodeGenerator& o, Transform& trans,  const RulePtr& rule, bool useDirections){\n\/\/bool printedBeforeDep = false;\n\n  ScheduleDependencies::const_iterator sd = _indirectDepends.find(this);\n  if(sd==_indirectDepends.end() && rule->isSingleElement()){\n    trans.markSplitSizeUse(o);\n    o.write(nodename()+\".spatialSplit(\"SPLIT_CHUNK_SIZE\");\");\n  }else{\n    \/\/TODO split selfdep tasks too\n  }\n\n  for(ScheduleDependencies::const_iterator i=_directDepends.begin();  i!=_directDepends.end(); ++i){\n    if(i->first!=this){\n      if(i->first->isInput()){\n\/\/      if(!printedBeforeDep){\n\/\/       printedBeforeDep=true;\n\/\/       if(useDirections)\n\/\/         o.write(nodename()+\".dependsOn(_before);\");\n\/\/       else\n\/\/         o.write(nodename()+\"->dependsOn(_before);\");\n\/\/      }\n      }else{\n        if(useDirections){\n          o.write(\"{\"); \n          o.incIndent();\n          o.write(\"DependencyDirection::DirectionT _dir[] = {\"+i->second.direction.toCodeStr()+\"};\");\n          o.write(nodename()+\".dependsOn<\"+jalib::XToString(i->second.direction.size())+\">\"\n                            \"(\"+i->first->nodename()+\", _dir);\");\n          o.decIndent();\n          o.write(\"}\"); \n        }else{\n          o.write(nodename()+\"->dependsOn(\"+i->first->nodename()+\");\");\n        }\n      }\n    }\n  }\n  if(!_isLast)\n    o.write(nodename()+\"->enqueue();\");\n}\n\nvoid petabricks::UnischeduledNode::generateCodeForSlice(Transform& trans, CodeGenerator& o, int d, const FormulaPtr& pos, bool isStatic){\n  RuleChoicePtr rule = trans.learner().makeRuleChoice(_choices->rules(), _matrix, _region);\n  \n  CoordinateFormula min = _region->minCoord();\n  CoordinateFormula max = _region->maxCoord();\n\n  min[d] = pos;\n  max[d] = pos->plusOne();\n\n  SimpleRegionPtr t = new SimpleRegion(min,max);\n\n  rule->generateCodeSimple(isStatic, \"\", trans, *this, t, o);\n  \/\/TODO deps for slice\n}\n\n\nvoid petabricks::StaticScheduler::writeGraphAsPDF(const char* filename) const{\n  std::string schedulerGraph = toString();\n  FILE* fd = popen((\"dot -Grankdir=LR -Tpdf -o \"+std::string(filename)).c_str(), \"w\");\n  fwrite(schedulerGraph.c_str(),1,schedulerGraph.length(),fd);\n  pclose(fd);\n}\n\nint petabricks::ScheduleNode::updateIndirectDepends(){\n  int c = 0;\n  if(_indirectDepends.empty()){  \/\/ seed first iteration\n    _indirectDepends = _directDepends;\n    c+=_indirectDepends.size();\n  }\n  ScheduleDependencies tmp = _indirectDepends;\n  for(ScheduleDependencies::iterator i=tmp.begin(); i!=tmp.end(); ++i){\n    const ScheduleDependencies& remote = i->first->indirectDepends();\n    for( ScheduleDependencies::const_iterator dep=remote.begin(); dep!=remote.end(); ++dep)\n    { \/\/for each dependency\n      if(_indirectDepends[dep->first].merge(dep->second))\n        ++c;\n    }\n  }\n  return c;\n}\n\npetabricks::ScheduleNodeSet petabricks::ScheduleNode::getStronglyConnectedComponent(){\n  \/\/\/ compute strongly connected component\n  ScheduleNodeSet s;\n  s.insert(this);\n  if(_indirectDepends.find(this)==_indirectDepends.end())\n    return s;\n\n  for(ScheduleDependencies::iterator i=_indirectDepends.begin(); i!=_indirectDepends.end(); ++i){\n    if(i->first->indirectDepends().find(this)!=i->first->indirectDepends().end()) \/\/if in a cycle with this\n      s.insert(i->first);\n  }\n  return s;\n}\n\npetabricks::CoscheduledNode::CoscheduledNode(const ScheduleNodeSet& set)\n  : _originalNodes(set)\n{\n  for(ScheduleNodeSet::const_iterator i=set.begin(); i!=set.end(); ++i){\n    _directDepends.merge((*i)->directDepends());\n    _indirectDepends.merge((*i)->indirectDepends());\n  }\n}\n\n\nvoid petabricks::CoscheduledNode::generateCodeSimple(Transform& trans, CodeGenerator& o, bool isStatic){\n  const DependencyInformation& selfDep = _indirectDepends[this];\n\n  if(selfDep.direction.isNone()){\n    if(!isStatic) o.addMember(\"SpatialTaskList\", nodename(), \"\");\n    o.comment(\"Dual outputs compacted \"+nodename());\n    std::string region;\n    ScheduleNode* first = NULL;\n    \/\/test matching region extents in d\n    for(ScheduleNodeSet::const_iterator i=_originalNodes.begin(); i!=_originalNodes.end(); ++i){\n      if(first==NULL){\n        region=(*i)->region()->toString();\n        first=*i;\n      }\n      else if(first->region()->dimensions()<(*i)->region()->dimensions())\n        first=*i;\n      JWARNING(region==(*i)->region()->toString())(region)((*i)->region()->toString())\n        .Text(\"to(...) regions of differing size not yet supported\");\n    }\n    RuleChoicePtr rule = trans.learner().makeRuleChoice(first->choices()->rules(), first->matrix(), first->region());\n    rule->generateCodeSimple(isStatic, nodename(), trans, *this, first->region(), o);\n  }else{\n    if(!isStatic) o.addMember(\"DynamicTaskPtr\", nodename(),\"\");\n    std::vector args;\n    args.push_back(\"const jalib::JRef<\"+trans.instClassName()+\"> transform\");\n    TaskCodeGenerator* task;\n    if(!isStatic) task=&o.createTask(\"coscheduled_\"+nodename(), args, \"DynamicTask\", \"_task\");\n    CodeGenerator& ot = isStatic ? o : *task;\n    std::string varname=\"coscheduled_\"+nodename();\n    if(!isStatic){\n      task->beginRunFunc();\n      for(FreeVars::const_iterator i=trans.constants().begin()\n         ;i!=trans.constants().end()\n         ;++i)\n      {\n        ot.define(*i, \"(transform->\"+*i+\")\");\n      }\n      ot.define(\"input_count\", \"(transform->input_count)\");\n    }\n    \n    for(size_t d=selfDep.direction.size()-1; d>=0; --d){\n      bool passed=true;\n      FormulaPtr begin,end;\n    \n      \/\/test matching region extents in d\n      for(ScheduleNodeSet::const_iterator i=_originalNodes.begin(); i!=_originalNodes.end(); ++i){\n        if(!begin) begin = (*i)->region()->minCoord()[d];\n        if(!end)   end   = (*i)->region()->maxCoord()[d];\n        if(   begin->toString() != (*i)->region()->minCoord()[d]->toString()\n          ||  end->toString()   != (*i)->region()->maxCoord()[d]->toString())\n        {\n          JTRACE(\"Can't coschedule due to mismatched extents\")(d);\n          passed=false;\n          break;\n        }\n      }\n      if(!passed) continue;\n      \n      \/\/test direction\n      if((selfDep.direction[d]& ~DependencyDirection::D_LE) == 0){\n        JTRACE(\"Coscheduling forward\")(d)(*this);\n        ot.beginFor(varname, begin, end, FormulaInteger::one());\n      }else if((selfDep.direction[d]& ~DependencyDirection::D_GE) == 0){\n        JTRACE(\"Coscheduling backward\")(d)(*this);\n        ot.beginReverseFor(varname, begin, end, FormulaInteger::one());\n      }else{\n        JTRACE(\"Can't coschedule due to mismatched direction\")(d);\n        passed=false;\n        continue;\n      }\n\n      for(ScheduleNodeSet::iterator i=_originalNodes.begin(); i!=_originalNodes.end(); ++i){\n        (*i)->generateCodeForSlice(trans, ot, d, new FormulaVariable(varname), isStatic);\n      }\n      ot.endFor();\n      if(!isStatic){\n        ot.write(\"return NULL;\");\n        ot.undefineAll();\n        ot.endFunc();\n        std::vector args(1, \"this\");\n        o.setcall(nodename(),\"new \"+varname+\"_task\", args);\n        printDepsAndEnqueue(o, trans, NULL, false);\n      }\n      return;\n    }\n    JASSERT(false)(*this)(selfDep.direction).Text(\"Unresolved dependency cycle\");\n  }\n}\n<|endoftext|>"}
{"text":"\/*\n    Copyright (C) 2011  Lasath Fernando \n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n*\/\n\n\n#include \"conversations-model.h\"\n#include \"conversation.h\"\n#include \"messages-model.h\"\n\n#include \"debug.h\"\n\n#include \n#include \n#include \n\nstatic inline Tp::ChannelClassSpecList channelClassList()\n{\n    return Tp::ChannelClassSpecList() << Tp::ChannelClassSpec::textChat();\n}\n\nclass ConversationsModel::ConversationsModelPrivate\n{\n  public:\n    QList conversations;\n    int activeChatIndex;\n};\n\nConversationsModel::ConversationsModel(QObject *parent) :\n        QAbstractListModel(parent),\n        Tp::AbstractClientHandler(channelClassList()),\n        d(new ConversationsModelPrivate)\n{\n    d->activeChatIndex = -1;\n    connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), SIGNAL(totalUnreadCountChanged()));\n    connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), SIGNAL(totalUnreadCountChanged()));\n}\n\nConversationsModel::~ConversationsModel()\n{\n    qDeleteAll(d->conversations);\n    delete d;\n}\n\nQHash ConversationsModel::roleNames() const\n{\n    QHash roles = QAbstractListModel::roleNames();\n    roles[ConversationRole] = \"conversation\";\n    return roles;\n}\n\nQVariant ConversationsModel::data(const QModelIndex &index, int role) const\n{\n    QVariant result;\n    if (index.isValid()) {\n        if (role == ConversationRole) {\n            result = QVariant::fromValue(d->conversations[index.row()]);\n        }\n    }\n    return result;\n}\n\nint ConversationsModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return d->conversations.count();\n}\n\nvoid ConversationsModel::handleChannels(const Tp::MethodInvocationContextPtr<> &context,\n                                        const Tp::AccountPtr &account,\n                                        const Tp::ConnectionPtr &connection,\n                                        const QList &channels,\n                                        const QList &channelRequests,\n                                        const QDateTime &userActionTime,\n                                        const HandlerInfo &handlerInfo)\n{\n    Q_UNUSED(connection);\n    Q_UNUSED(handlerInfo);\n    Q_UNUSED(userActionTime);\n\n    bool handled = false;\n    bool shouldDelegate = false;\n\n    \/\/check that the channel is of type text\n    Tp::TextChannelPtr textChannel;\n    Q_FOREACH(const Tp::ChannelPtr &channel, channels) {\n        textChannel = Tp::TextChannelPtr::dynamicCast(channel);\n        if (textChannel) {\n            break;\n        }\n    }\n\n    Q_ASSERT(textChannel);\n\n    \/\/find the relevant channelRequest\n    Q_FOREACH(const Tp::ChannelRequestPtr channelRequest, channelRequests) {\n        qCDebug(KTP_DECLARATIVE) << channelRequest->hints().allHints();\n        shouldDelegate = channelRequest->hints().hint(QLatin1String(\"org.freedesktop.Telepathy.ChannelRequest\"), QLatin1String(\"DelegateToPreferredHandler\")).toBool();\n    }\n\n    \/\/loop through all conversations checking for matches\n\n    \/\/if we are handling and we're not told to delegate it, update the text channel\n    \/\/if we are handling but should delegate, call delegate channel\n    int i = 0;\n    Q_FOREACH(Conversation *convo, d->conversations) {\n        if (convo->textChannel()->targetId() == textChannel->targetId() &&\n                convo->textChannel()->targetHandleType() == textChannel->targetHandleType())\n        {\n            if (!shouldDelegate) {\n                convo->setTextChannel(textChannel);\n                \/\/Update the active chat index to this channel\n                d->activeChatIndex = i;\n                Q_EMIT activeChatIndexChanged();\n            } else {\n                if (convo->textChannel() == textChannel) {\n                    convo->delegateToProperClient();\n                }\n            }\n            handled = true;\n            break;\n        }\n        i++;\n    }\n\n    \/\/if we are not handling channel already and should not delegate, add the conversation\n    \/\/if we not handling the channel but should delegate it, do nothing.\n    if (!handled && !shouldDelegate) {\n        beginInsertRows(QModelIndex(), rowCount(), rowCount());\n        Conversation *newConvo = new Conversation(textChannel, account, this);\n        connect(newConvo, SIGNAL(conversationCloseRequested()), SLOT(onConversationCloseRequested()));\n        connect(newConvo->messages(), SIGNAL(unreadCountChanged(int)), SIGNAL(totalUnreadCountChanged()));\n        d->conversations.append(newConvo);\n        endInsertRows();\n\n        \/\/If this is a locally generated request or there is no active chat, the index of the newly inserted conversation is saved as the active chat\n        \/\/The model is reset to load the newly created chat channel\n        if(textChannel->isRequested() || d->activeChatIndex == -1) {\n            d->activeChatIndex = rowCount() - 1;\n            Q_EMIT activeChatIndexChanged();\n        }\n        context->setFinished();\n    }\n}\n\nbool ConversationsModel::bypassApproval() const\n{\n    return true;\n}\n\nvoid ConversationsModel::onConversationCloseRequested()\n{\n    removeConversation(qobject_cast(QObject::sender()));\n}\n\nvoid ConversationsModel::removeConversation(Conversation* conv)\n{\n    int index = d->conversations.indexOf(conv);\n    if (index != -1) {\n        beginRemoveRows(QModelIndex(), index, index);\n        d->conversations.removeAt(index);\n        conv->deleteLater();\n        endRemoveRows();\n    } else {\n        qWarning() << \"attempting to delete non-existent conversation\";\n    }\n}\n\nint ConversationsModel::nextActiveConversation(int fromRow)\n{\n    if(d->conversations.isEmpty()) {\n        return -1;\n    }\n    Q_ASSERT(qBound(0, fromRow, d->conversations.count()-1) == fromRow);\n\n    bool first = true; \/\/let first be checked on the first loop\n    for(int i = fromRow; i != fromRow || first; i = (i + 1) % d->conversations.count()) {\n        if(d->conversations[i]->messages()->unreadCount() > 0) {\n            return i;\n        }\n        first = false;\n    }\n    return -1;\n}\n\nint ConversationsModel::totalUnreadCount() const\n{\n    int ret = 0;\n    Q_FOREACH(Conversation *c, d->conversations) {\n        ret += c->messages()->unreadCount();\n    }\n    return ret;\n}\n\nint ConversationsModel::activeChatIndex() const\n{\n    return d->activeChatIndex;\n}\n\nvoid ConversationsModel::closeAllConversations()\n{\n    Q_FOREACH(Conversation *c, d->conversations) {\n        c->requestClose();\n    }\n}\nImprove how we close all conversations at once\/*\n    Copyright (C) 2011  Lasath Fernando \n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n*\/\n\n\n#include \"conversations-model.h\"\n#include \"conversation.h\"\n#include \"messages-model.h\"\n\n#include \"debug.h\"\n\n#include \n#include \n#include \n\nstatic inline Tp::ChannelClassSpecList channelClassList()\n{\n    return Tp::ChannelClassSpecList() << Tp::ChannelClassSpec::textChat();\n}\n\nclass ConversationsModel::ConversationsModelPrivate\n{\n  public:\n    QList conversations;\n    int activeChatIndex;\n};\n\nConversationsModel::ConversationsModel(QObject *parent) :\n        QAbstractListModel(parent),\n        Tp::AbstractClientHandler(channelClassList()),\n        d(new ConversationsModelPrivate)\n{\n    d->activeChatIndex = -1;\n    connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), SIGNAL(totalUnreadCountChanged()));\n    connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), SIGNAL(totalUnreadCountChanged()));\n}\n\nConversationsModel::~ConversationsModel()\n{\n    qDeleteAll(d->conversations);\n    delete d;\n}\n\nQHash ConversationsModel::roleNames() const\n{\n    QHash roles = QAbstractListModel::roleNames();\n    roles[ConversationRole] = \"conversation\";\n    return roles;\n}\n\nQVariant ConversationsModel::data(const QModelIndex &index, int role) const\n{\n    QVariant result;\n    if (index.isValid()) {\n        if (role == ConversationRole) {\n            result = QVariant::fromValue(d->conversations[index.row()]);\n        }\n    }\n    return result;\n}\n\nint ConversationsModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return d->conversations.count();\n}\n\nvoid ConversationsModel::handleChannels(const Tp::MethodInvocationContextPtr<> &context,\n                                        const Tp::AccountPtr &account,\n                                        const Tp::ConnectionPtr &connection,\n                                        const QList &channels,\n                                        const QList &channelRequests,\n                                        const QDateTime &userActionTime,\n                                        const HandlerInfo &handlerInfo)\n{\n    Q_UNUSED(connection);\n    Q_UNUSED(handlerInfo);\n    Q_UNUSED(userActionTime);\n\n    bool handled = false;\n    bool shouldDelegate = false;\n\n    \/\/check that the channel is of type text\n    Tp::TextChannelPtr textChannel;\n    Q_FOREACH(const Tp::ChannelPtr &channel, channels) {\n        textChannel = Tp::TextChannelPtr::dynamicCast(channel);\n        if (textChannel) {\n            break;\n        }\n    }\n\n    Q_ASSERT(textChannel);\n\n    \/\/find the relevant channelRequest\n    Q_FOREACH(const Tp::ChannelRequestPtr channelRequest, channelRequests) {\n        qCDebug(KTP_DECLARATIVE) << channelRequest->hints().allHints();\n        shouldDelegate = channelRequest->hints().hint(QLatin1String(\"org.freedesktop.Telepathy.ChannelRequest\"), QLatin1String(\"DelegateToPreferredHandler\")).toBool();\n    }\n\n    \/\/loop through all conversations checking for matches\n\n    \/\/if we are handling and we're not told to delegate it, update the text channel\n    \/\/if we are handling but should delegate, call delegate channel\n    int i = 0;\n    Q_FOREACH(Conversation *convo, d->conversations) {\n        if (convo->textChannel()->targetId() == textChannel->targetId() &&\n                convo->textChannel()->targetHandleType() == textChannel->targetHandleType())\n        {\n            if (!shouldDelegate) {\n                convo->setTextChannel(textChannel);\n                \/\/Update the active chat index to this channel\n                d->activeChatIndex = i;\n                Q_EMIT activeChatIndexChanged();\n            } else {\n                if (convo->textChannel() == textChannel) {\n                    convo->delegateToProperClient();\n                }\n            }\n            handled = true;\n            break;\n        }\n        i++;\n    }\n\n    \/\/if we are not handling channel already and should not delegate, add the conversation\n    \/\/if we not handling the channel but should delegate it, do nothing.\n    if (!handled && !shouldDelegate) {\n        beginInsertRows(QModelIndex(), rowCount(), rowCount());\n        Conversation *newConvo = new Conversation(textChannel, account, this);\n        connect(newConvo, SIGNAL(conversationCloseRequested()), SLOT(onConversationCloseRequested()));\n        connect(newConvo->messages(), SIGNAL(unreadCountChanged(int)), SIGNAL(totalUnreadCountChanged()));\n        d->conversations.append(newConvo);\n        endInsertRows();\n\n        \/\/If this is a locally generated request or there is no active chat, the index of the newly inserted conversation is saved as the active chat\n        \/\/The model is reset to load the newly created chat channel\n        if(textChannel->isRequested() || d->activeChatIndex == -1) {\n            d->activeChatIndex = rowCount() - 1;\n            Q_EMIT activeChatIndexChanged();\n        }\n        context->setFinished();\n    }\n}\n\nbool ConversationsModel::bypassApproval() const\n{\n    return true;\n}\n\nvoid ConversationsModel::onConversationCloseRequested()\n{\n    removeConversation(qobject_cast(QObject::sender()));\n}\n\nvoid ConversationsModel::removeConversation(Conversation* conv)\n{\n    int index = d->conversations.indexOf(conv);\n    if (index != -1) {\n        beginRemoveRows(QModelIndex(), index, index);\n        d->conversations.removeAt(index);\n        conv->deleteLater();\n        endRemoveRows();\n    } else {\n        qWarning() << \"attempting to delete non-existent conversation\";\n    }\n}\n\nint ConversationsModel::nextActiveConversation(int fromRow)\n{\n    if(d->conversations.isEmpty()) {\n        return -1;\n    }\n    Q_ASSERT(qBound(0, fromRow, d->conversations.count()-1) == fromRow);\n\n    bool first = true; \/\/let first be checked on the first loop\n    for(int i = fromRow; i != fromRow || first; i = (i + 1) % d->conversations.count()) {\n        if(d->conversations[i]->messages()->unreadCount() > 0) {\n            return i;\n        }\n        first = false;\n    }\n    return -1;\n}\n\nint ConversationsModel::totalUnreadCount() const\n{\n    int ret = 0;\n    Q_FOREACH(Conversation *c, d->conversations) {\n        ret += c->messages()->unreadCount();\n    }\n    return ret;\n}\n\nint ConversationsModel::activeChatIndex() const\n{\n    return d->activeChatIndex;\n}\n\nvoid ConversationsModel::closeAllConversations()\n{\n    if (!d->conversations.isEmpty()) {\n        beginRemoveRows(QModelIndex(), 0, rowCount() - 1);\n        d->conversations.clear();\n        endRemoveRows();\n        qDeleteAll(d->conversations);\n    }\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic std::vector\nacorr_r(const std::vector &signal)\n{\n\tint N = signal.size();\n\tint N2 = 2 * N - 1;\n\n\t\/* https:\/\/stackoverflow.com\/questions\/466204\/rounding-up-to-next-power-of-2\n\t *\/\n\tif (N2 & (N2 - 1)) {\n\t\tN2--;\n\t\tN2 |= N2 >> 1;\n\t\tN2 |= N2 >> 2;\n\t\tN2 |= N2 >> 4;\n\t\tN2 |= N2 >> 8;\n\t\tN2 |= N2 >> 16;\n\t\tN2++;\n\t}\n\n\tassert(!(N2 & (N2 - 1)));\n\n\tauto fft_forward = ffts_init_1d(N2, false);\n\tauto fft_backward = ffts_init_1d(N2, false);\n\t\n\tstd::vector> signala_ext(N2);\n\tstd::vector> signalb_ext(N2);\n\n\tfor (int i = 0; i < N; i++) {\n\t\tsignala_ext[(N2 - N) + i] = {signal[i], 0.0};\n\t\tsignalb_ext[i] = {signal[i], 0.0};\n\t}\n\n\tstd::vector> outa(N2);\n\tstd::vector> outb(N2);\n\tstd::vector> out(N2);\n\tstd::vector> result(N2);\n\n\tffts_execute(fft_forward, signala_ext.data(), outa.data());\n\tffts_execute(fft_forward, signalb_ext.data(), outb.data());\n\n\tstd::complex scale = {1.0 \/ (double)N2, 0.0};\n\tfor (int i = 0; i < N2; ++i)\n\t\tout[i] = outa[i] * std::conj(outb[i]) * scale;\n\n\tffts_execute(fft_backward, out.data(), result.data());\n\n\tffts_free(fft_forward);\n\tffts_free(fft_backward);\n\n\tstd::vector normalized_result(N, 0.0);\n\tfor (int i = 0; i < N; ++i)\n\t\tnormalized_result[i] = std::real(result[i + (N2 - N)]) \/ std::real(result[N2 - N]);\n\treturn normalized_result;\n}\n\nstatic std::vector\npeak_picking(const std::vector &nsdf)\n{\n\tstd::vector max_positions{};\n\tint pos = 0;\n\tint cur_max_pos = 0;\n\tssize_t size = nsdf.size();\n\n\twhile (pos < (size - 1) \/ 3 && nsdf[pos] > 0)\n\t\tpos++;\n\twhile (pos < size - 1 && nsdf[pos] <= 0.0)\n\t\tpos++;\n\n\tif (pos == 0)\n\t\tpos = 1;\n\n\twhile (pos < size - 1) {\n\t\tif (nsdf[pos] > nsdf[pos - 1] && nsdf[pos] >= nsdf[pos + 1]) {\n\t\t\tif (cur_max_pos == 0) {\n\t\t\t\tcur_max_pos = pos;\n\t\t\t} else if (nsdf[pos] > nsdf[cur_max_pos]) {\n\t\t\t\tcur_max_pos = pos;\n\t\t\t}\n\t\t}\n\t\tpos++;\n\t\tif (pos < size - 1 && nsdf[pos] <= 0) {\n\t\t\tif (cur_max_pos > 0) {\n\t\t\t\tmax_positions.push_back(cur_max_pos);\n\t\t\t\tcur_max_pos = 0;\n\t\t\t}\n\t\t\twhile (pos < size - 1 && nsdf[pos] <= 0.0) {\n\t\t\t\tpos++;\n\t\t\t}\n\t\t}\n\t}\n\tif (cur_max_pos > 0) {\n\t\tmax_positions.push_back(cur_max_pos);\n\t}\n\treturn max_positions;\n}\n\ndouble\nget_pitch_mpm(const std::vector &data, int sample_rate)\n{\n\tstd::vector nsdf = acorr_r(data);\n\tstd::vector max_positions = peak_picking(nsdf);\n\tstd::vector> estimates;\n\n\tdouble highest_amplitude = -DBL_MAX;\n\n\tfor (int i : max_positions) {\n\t\thighest_amplitude = std::max(highest_amplitude, nsdf[i]);\n\t\tif (nsdf[i] > MPM_SMALL_CUTOFF) {\n\t\t\tauto x = parabolic_interpolation(nsdf, i);\n\t\t\testimates.push_back(x);\n\t\t\thighest_amplitude = std::max(highest_amplitude, std::get<1>(x));\n\t\t}\n\t}\n\n\tif (estimates.empty())\n\t\treturn -1;\n\n\tdouble actual_cutoff = MPM_CUTOFF * highest_amplitude;\n\tdouble period = 0;\n\n\tfor (auto i : estimates) {\n\t\tif (std::get<1>(i) >= actual_cutoff) {\n\t\t\tperiod = std::get<0>(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tdouble pitch_estimate = (sample_rate \/ period);\n\treturn (pitch_estimate > MPM_LOWER_PITCH_CUTOFF) ? pitch_estimate : -1;\n}\nFix use of FFTS#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic std::vector\nacorr_r(const std::vector &signal)\n{\n\tint N = signal.size();\n\tint N2 = 2 * N;\/\/ - 1;\n\n\tauto fft_forward = ffts_init_1d(N2, false);\n\tauto fft_backward = ffts_init_1d(N2, false);\n\n\tstd::vector> signala_ext(N2);\n\tstd::vector> signalb_ext(N2);\n\n\tfor (int i = 0; i < N; i++) {\n\t\tsignala_ext[(N2 - N) + i] = {float(signal[i]), 0.0};\n\t\tsignalb_ext[i] = {float(signal[i]), 0.0};\n\t}\n\n\tstd::vector> outa(N2);\n\tstd::vector> outb(N2);\n\tstd::vector> out(N2);\n\tstd::vector> result(N2);\n\n\tffts_execute(fft_forward, signala_ext.data(), outa.data());\n\tffts_execute(fft_forward, signalb_ext.data(), outb.data());\n\n\tstd::complex scale = {1.0f \/ (float)N2, 0.0};\n\tfor (int i = 0; i < N2; ++i)\n\t\tout[i] = outa[i] * std::conj(outb[i]) * scale;\n\n\tffts_execute(fft_backward, out.data(), result.data());\n\n\tffts_free(fft_forward);\n\tffts_free(fft_backward);\n\n\tstd::vector normalized_result(N, 0.0);\n\tfor (int i = 0; i < N; ++i)\n\t\tnormalized_result[i] =\n\t\t    std::real(result[i + (N2 - N)]) \/ std::real(result[N2 - N]);\n\treturn normalized_result;\n}\n\nstatic std::vector\npeak_picking(const std::vector &nsdf)\n{\n\tstd::vector max_positions{};\n\tint pos = 0;\n\tint cur_max_pos = 0;\n\tssize_t size = nsdf.size();\n\n\twhile (pos < (size - 1) \/ 3 && nsdf[pos] > 0)\n\t\tpos++;\n\twhile (pos < size - 1 && nsdf[pos] <= 0.0)\n\t\tpos++;\n\n\tif (pos == 0)\n\t\tpos = 1;\n\n\twhile (pos < size - 1) {\n\t\tif (nsdf[pos] > nsdf[pos - 1] && nsdf[pos] >= nsdf[pos + 1]) {\n\t\t\tif (cur_max_pos == 0) {\n\t\t\t\tcur_max_pos = pos;\n\t\t\t} else if (nsdf[pos] > nsdf[cur_max_pos]) {\n\t\t\t\tcur_max_pos = pos;\n\t\t\t}\n\t\t}\n\t\tpos++;\n\t\tif (pos < size - 1 && nsdf[pos] <= 0) {\n\t\t\tif (cur_max_pos > 0) {\n\t\t\t\tmax_positions.push_back(cur_max_pos);\n\t\t\t\tcur_max_pos = 0;\n\t\t\t}\n\t\t\twhile (pos < size - 1 && nsdf[pos] <= 0.0) {\n\t\t\t\tpos++;\n\t\t\t}\n\t\t}\n\t}\n\tif (cur_max_pos > 0) {\n\t\tmax_positions.push_back(cur_max_pos);\n\t}\n\treturn max_positions;\n}\n\ndouble\nget_pitch_mpm(const std::vector &data, int sample_rate)\n{\n\tstd::vector nsdf = acorr_r(data);\n\tstd::vector max_positions = peak_picking(nsdf);\n\tstd::vector> estimates;\n\n\tdouble highest_amplitude = -DBL_MAX;\n\n\tfor (int i : max_positions) {\n\t\thighest_amplitude = std::max(highest_amplitude, nsdf[i]);\n\t\tif (nsdf[i] > MPM_SMALL_CUTOFF) {\n\t\t\tauto x = parabolic_interpolation(nsdf, i);\n\t\t\testimates.push_back(x);\n\t\t\thighest_amplitude = std::max(highest_amplitude, std::get<1>(x));\n\t\t}\n\t}\n\n\tif (estimates.empty())\n\t\treturn -1;\n\n\tdouble actual_cutoff = MPM_CUTOFF * highest_amplitude;\n\tdouble period = 0;\n\n\tfor (auto i : estimates) {\n\t\tif (std::get<1>(i) >= actual_cutoff) {\n\t\t\tperiod = std::get<0>(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tdouble pitch_estimate = (sample_rate \/ period);\n\treturn (pitch_estimate > MPM_LOWER_PITCH_CUTOFF) ? pitch_estimate : -1;\n}\n<|endoftext|>"}
{"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"plasmacore.h\"\n#include \"plasmacore_message.h\"\n#include \"plasmacore_view.h\"\n#include \"rogue_interface.h\"\n\n#ifdef __EMSCRIPTEN__\n#include \n#else\n#include \n#include \n#endif\n\n#define LOCAL_FS 1\n\/\/#define WINDOW_BASED 1\n\n\/\/ The \"code\" value for SDL_USEREVENT for our async call mechanism\n#define ASYNC_CALL_EVENT 1\n\nstatic int gargc;\nstatic char ** gargv;\n\n\nstatic int iterations;\n\n\n#ifdef __EMSCRIPTEN__\nstatic void do_async_call ( void (*cb)(void *), int millis )\n{\n  emscripten_async_call(cb, 0, millis);\n}\n\n#else\n\nstatic Uint32 sdl_async_cb_poster (Uint32 interval, void * arg)\n{\n  SDL_Event event;\n  event.user.type = SDL_USEREVENT;\n  event.user.code = ASYNC_CALL_EVENT;\n  event.user.data1 = arg; \/\/ The callback\n  \/\/userevent.data2 = ...\n  SDL_PushEvent(&event);\n  return 0;\n}\n\nstatic void do_async_call ( void (*cb)(void *), int millis )\n{\n  SDL_AddTimer(millis, sdl_async_cb_poster, (void *)cb);\n}\n\n#endif\n\n\nHID Plasmacore::addMessageHandler( std::string & type, HandlerCallback handler )\n{\n  auto info = PlasmacoreMessageHandler( nextHandlerID, type, handler );\n  nextHandlerID += 1;\n\n  handlers_by_id[ info.handlerID ] = info;\n  handlers[ type ].push_back( info );\n  return info.handlerID;\n}\n\n\nHID Plasmacore::addMessageHandler( const char * type, HandlerCallback handler )\n{\n  auto info = PlasmacoreMessageHandler( nextHandlerID, type, handler );\n  nextHandlerID += 1;\n\n  handlers_by_id[ info.handlerID ] = info;\n  handlers[ type ].push_back( info );\n  return info.handlerID;\n}\n\n\nPlasmacore & Plasmacore::configure()\n{\n  if (is_configured) return *this;\n  is_configured = true;\n\n  addMessageHandler( \"\", [] (PlasmacoreMessage m)\n    {\n        auto iter = singleton.reply_handlers.find( m.message_id );\n        if (iter != singleton.reply_handlers.end())\n        {\n          auto info = iter->second;\n          singleton.reply_handlers.erase(iter);\n          info.callback( m );\n        }\n    }\n  );\n\n  #ifdef WINDOW_BASED\n  addMessageHandler( \"Window.create\", [] (PlasmacoreMessage m)\n    {\n      auto name = m.getString( \"name\" );\n\n      auto view = plasmacore_new_view(name);\n      if (!view) throw \"No view created!\";\n\n      Plasmacore::singleton.resources[ m.getInt32(\"id\") ] = view;\n      std::cerr << \"Controller window: \" << view << std::endl;\n    }\n  );\n\n  addMessageHandler( \"Window.show\", [] (PlasmacoreMessage m)\n    {\n      auto window_id = m.getInt32( \"id\" );\n      auto view  = (PlasmacoreView*)Plasmacore::singleton.resources[ window_id ];\n      if (view) view->show();\n    }\n  );\n  #else\n  auto view = plasmacore_new_view(\"Main\");\n  if (!view) throw \"No view created!\";\n  std::cerr << \"Controller window: \" << view << std::endl;\n  #endif\n\n  RogueInterface_set_arg_count( gargc );\n  for (int i = 0; i < gargc; ++i)\n  {\n    RogueInterface_set_arg_value( i, gargv[i] );\n  }\n\n  RogueInterface_configure();\n  return *this;\n}\n\n\nRID Plasmacore::getResourceID( void * resource)\n{\n  if (! resource) return 0;\n\n  for (auto const & it : resources)\n  {\n    if (it.second == resource) { return it.first; }\n  }\n  return 0;\n}\n\n\nPlasmacore & Plasmacore::launch()\n{\n  if (is_launched) { return *this; }\n  is_launched = true;\n\n  RogueInterface_launch();\n  auto m = PlasmacoreMessage( \"Application.on_launch\" );\n#ifdef WINDOW_BASED\n  m.set( \"is_window_based\", true );\n#endif\n  m.send();\n  return *this;\n}\n\n\n\n\nPlasmacore & Plasmacore::relaunch()\n{\n  \/\/XXX: Always relaunch window based?\n  PlasmacoreMessage( \"Application.on_launch\" ).set( \"is_window_based\", true ).send();\n  return *this;\n}\n\n\nvoid Plasmacore::removeMessageHandler( HID handlerID )\n{\n  auto iter = handlers_by_id.find(handlerID);\n  if (iter != handlers_by_id.end())\n  {\n    auto handler = iter->second;\n    handlers_by_id.erase( handlerID );\n    auto & handler_list = handlers[ handler.type ]; \/\/ This should always work, right?\n    {\n      for (int i = 0; i < handler_list.size(); ++i)\n      {\n        if (handler_list[i].handlerID == handlerID)\n        {\n          handler_list.erase(handler_list.begin() + i);\n          return;\n        }\n      }\n    }\n  }\n}\n\n\nvoid Plasmacore::send( PlasmacoreMessage & m )\n{\n  auto size = m.data.size();\n  pending_message_data.push_back( uint8_t((size>>24)&255) );\n  pending_message_data.push_back( uint8_t((size>>16)&255) );\n  pending_message_data.push_back( uint8_t((size>>8)&255) );\n  pending_message_data.push_back( uint8_t(size&255) );\n  for (int i = 0; i < m.data.size(); ++i)\n  {\n    pending_message_data.push_back( m.data[i] );\n  }\n  real_update(false);\n}\n\n\nvoid Plasmacore::send_rsvp( PlasmacoreMessage & m, HandlerCallback callback )\n{\n  reply_handlers[ m.message_id ] = PlasmacoreMessageHandler( nextHandlerID, \"\", callback );\n  nextHandlerID += 1;\n  send( m );\n}\n\n\nPlasmacore & Plasmacore::setIdleUpdateFrequency( double f )\n{\n  idleUpdateFrequency = f;\n  if (update_timer)\n  {\n    stop();\n    start();\n  }\n  return *this;\n}\n\n\nvoid Plasmacore::start()\n{\n  if ( !is_launched ) { configure().launch(); }\n  printf(\"LOG: start()\\n\");\n\n  update_timer = true;\n  real_update(true);\n}\n\n\nvoid Plasmacore::stop()\n{\n  \/\/ Note that we don't actually stop any timer from running.  The major\n  \/\/ outcome here is that you may get an extra update if you stop, restart,\n  \/\/ or change the update frequency.\n  \/\/ We *could* probably make this work \"right\" by using a cancellable SDL\n  \/\/ timer, but I don't think it really matters, and I'm not sure that such\n  \/\/ timers are available in emscripten, so we'd have to do this for emscripten\n  \/\/ mode anyway.\n  update_timer = false;\n}\n\n\nvoid Plasmacore::update(void * dummy)\n{\n  \/\/printf(\"LOG: update(); iterations=%i\\n\", iterations);\n  Plasmacore::singleton.real_update(true);\n}\n\nvoid Plasmacore::fast_update(void * dummy)\n{\n  \/\/printf(\"LOG: update(); iterations=%i\\n\", iterations);\n  Plasmacore::singleton.real_update(false);\n}\n\nvoid Plasmacore::real_update (bool reschedule)\n{\n  if (!Plasmacore::singleton.update_timer) return; \/\/ Ignore, since timer shouldn't be running.\n\n  \/\/ Schedule the next idle update.\n  if (reschedule) do_async_call(update, int(1000*idleUpdateFrequency));\n\n  if (is_sending)\n  {\n    update_requested = true;\n    return;\n  }\n\n  is_sending = true;\n\n  \/\/ Execute a small burst of message dispatching and receiving.  Stop after\n  \/\/ 10 iterations or when there are no new messages.  Global state updates\n  \/\/ are frequency capped to 1\/60 second intervals and draws are synced to\n  \/\/ the display refresh so this isn't triggering large amounts of extra work.\n  for (int _ = 0; _ < 10; ++_)\n  {\n    update_requested = false;\n\n    \/\/ Swap pending data with io_buffer data\n    io_buffer.swap(pending_message_data);\n\n    RogueInterface_send_messages( &io_buffer[0], io_buffer.size(), pending_message_data );\n    auto count = pending_message_data.size();\n    \/\/if (count || io_buffer.size())\n    \/\/  printf(\"TX:%-8lu  RX:%-8lu  @iter:%i\\n\", io_buffer.size(), count, iterations);\n    uint8_t * bytes = &pending_message_data[0];\n\n    int read_pos = 0;\n    while (read_pos+4 <= count)\n    {\n      auto size = int( bytes[read_pos] ) << 24;\n      size |= int( bytes[read_pos+1] ) << 16;\n      size |= int( bytes[read_pos+2] ) << 8;\n      size |= int( bytes[read_pos+3] );\n      read_pos += 4;\n\n      if (read_pos + size <= count)\n      {\n        std::vector message_data;\n        message_data.reserve( size );\n        for (int i = 0; i < size; ++i)\n        {\n          message_data.push_back( bytes[read_pos+i] );\n        }\n\n        auto m = PlasmacoreMessage( message_data );\n        printf( \"Received message type %s\\n\", m.type.c_str() );\n        auto iter = handlers.find(m.type);\n        if (iter != handlers.end())\n        {\n          for (auto const & handler : iter->second)\n          {\n            handler.callback( m );\n          }\n        }\n      }\n      else\n      {\n        std::cerr << \"*** Skipping message due to invalid size.\\n\";\n      }\n      read_pos += size;\n    }\n\n    io_buffer.clear();\n\n    if ( !update_requested )\n    {\n      break;\n    }\n  }\n\n  is_sending = false;\n\n  if (update_requested)\n  {\n    \/\/ There are still some pending messages after 10 iterations.  Schedule another round\n    \/\/ in 1\/60 second instead of the usual 1.0 seconds.\n    \/\/ We'll now have another (slow) call to update, but it'll probably return\n    do_async_call(fast_update, 16);\n  }\n}\n\n\nstatic bool should_quit = false;\n\n\nstatic void do_iteration (void)\n{\n  ++iterations;\n  plasmacore_redraw_all_windows();\n  SDL_Event e;\n  while (SDL_PollEvent(&e))\n  {\n    switch (e.type)\n    {\n      case SDL_QUIT:\n        should_quit = true;\n        return;\n      case SDL_MOUSEBUTTONDOWN:\n      case SDL_MOUSEBUTTONUP:\n      {\n        auto w = plasmacore_get_window(e.button.windowID);\n        if (!w) break;\n        int which;\n        switch (e.button.button)\n        {\n          case SDL_BUTTON_LEFT:\n            which = 0;\n            break;\n          case SDL_BUTTON_RIGHT:\n            which = 1;\n            break;\n          default:\n            return;\n        }\n        if (e.type == SDL_MOUSEBUTTONDOWN)\n          w->on_mouse_down(e.button.x, e.button.y, which);\n        else\n          w->on_mouse_up(e.button.x, e.button.y, which);\n        break;\n      }\n      case SDL_MOUSEMOTION:\n      {\n        auto w = plasmacore_get_window(e.motion.windowID);\n        w->on_mouse_move(e.motion.x, e.motion.y);\n        break;\n      }\n      case SDL_WINDOWEVENT:\n      {\n        auto w = plasmacore_get_window(e.button.windowID);\n        if (!w) break;\n        switch (e.window.event)\n        {\n          case SDL_WINDOWEVENT_FOCUS_GAINED:\n            w->on_focus_gained();\n            break;\n        }\n        break;\n      }\n      case SDL_USEREVENT:\n      {\n        if (e.user.code == ASYNC_CALL_EVENT)\n        {\n          \/\/ The following cast is theoretically not allowed.  Let's hope\n          \/\/ it works anyway on platforms we care about.\n          void (*f) (void*) = (void (*)(void*))e.user.data1;\n          f(0);\n          break;\n        }\n      }\n    }\n  }\n}\n\n\nextern \"C\" void start_main_loop (void)\n{\n  emscripten_set_main_loop(do_iteration, 0, 1);\n}\n\n\nPlasmacore Plasmacore::singleton;\n\nint main (int argc, char * argv[])\n{\n  gargc = argc;\n  gargv = argv;\n\n  #ifdef __EMSCRIPTEN__\n    auto flags = 0;\n  #else\n    auto flags = SDL_INIT_TIMER;\n\n    \/\/ CD into what we think the executable's directory is.\n    char * exe = strdup(argv[0]);\n    char * dir = dirname(exe);\n    chdir(dir);\n    free(exe);\n  #endif\n\n  if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|flags) != 0) return 1;\n\n  \/\/ Might want to call this here... but it might also be easier to just\n  \/\/ call it from Rogue via \"native\".\n  \/\/SDL_ShowCursor(false);\n\n  Plasmacore::singleton.configure().launch();\n  PlasmacoreMessage( \"Application.on_start\" ).send();\n  Plasmacore::singleton.start();\n\n#ifdef __EMSCRIPTEN__\n  #ifdef LOCAL_FS\n    EM_ASM(\n       FS.mkdir(\"\/local_storage\");\n       FS.mount(IDBFS, {}, \"\/local_storage\");\n       FS.syncfs(true, function (err) {\n         Module.print(\"Persistent storage ready.\");\n         Module[\"_start_main_loop\"]();\n       });\n    );\n  #else\n    start_main_loop();\n  #endif\n#else\n  SDL_GL_SetSwapInterval(1);\n  while (!should_quit)\n  {\n    do_iteration();\n    \/\/SDL_Delay(20);\n  }\n#endif\n\n  return 0;\n}\n[Web] Attempt to sync FS on leaving page#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"plasmacore.h\"\n#include \"plasmacore_message.h\"\n#include \"plasmacore_view.h\"\n#include \"rogue_interface.h\"\n\n#ifdef __EMSCRIPTEN__\n#include \n#include \n#else\n#include \n#include \n#endif\n\n#define LOCAL_FS 1\n\/\/#define WINDOW_BASED 1\n\n\/\/ The \"code\" value for SDL_USEREVENT for our async call mechanism\n#define ASYNC_CALL_EVENT 1\n\nstatic int gargc;\nstatic char ** gargv;\n\n\nstatic int iterations;\n\n\n#ifdef __EMSCRIPTEN__\nstatic void do_async_call ( void (*cb)(void *), int millis )\n{\n  emscripten_async_call(cb, 0, millis);\n}\n\n#else\n\nstatic Uint32 sdl_async_cb_poster (Uint32 interval, void * arg)\n{\n  SDL_Event event;\n  event.user.type = SDL_USEREVENT;\n  event.user.code = ASYNC_CALL_EVENT;\n  event.user.data1 = arg; \/\/ The callback\n  \/\/userevent.data2 = ...\n  SDL_PushEvent(&event);\n  return 0;\n}\n\nstatic void do_async_call ( void (*cb)(void *), int millis )\n{\n  SDL_AddTimer(millis, sdl_async_cb_poster, (void *)cb);\n}\n\n#endif\n\n\nHID Plasmacore::addMessageHandler( std::string & type, HandlerCallback handler )\n{\n  auto info = PlasmacoreMessageHandler( nextHandlerID, type, handler );\n  nextHandlerID += 1;\n\n  handlers_by_id[ info.handlerID ] = info;\n  handlers[ type ].push_back( info );\n  return info.handlerID;\n}\n\n\nHID Plasmacore::addMessageHandler( const char * type, HandlerCallback handler )\n{\n  auto info = PlasmacoreMessageHandler( nextHandlerID, type, handler );\n  nextHandlerID += 1;\n\n  handlers_by_id[ info.handlerID ] = info;\n  handlers[ type ].push_back( info );\n  return info.handlerID;\n}\n\n\nPlasmacore & Plasmacore::configure()\n{\n  if (is_configured) return *this;\n  is_configured = true;\n\n  addMessageHandler( \"\", [] (PlasmacoreMessage m)\n    {\n        auto iter = singleton.reply_handlers.find( m.message_id );\n        if (iter != singleton.reply_handlers.end())\n        {\n          auto info = iter->second;\n          singleton.reply_handlers.erase(iter);\n          info.callback( m );\n        }\n    }\n  );\n\n  #ifdef WINDOW_BASED\n  addMessageHandler( \"Window.create\", [] (PlasmacoreMessage m)\n    {\n      auto name = m.getString( \"name\" );\n\n      auto view = plasmacore_new_view(name);\n      if (!view) throw \"No view created!\";\n\n      Plasmacore::singleton.resources[ m.getInt32(\"id\") ] = view;\n      std::cerr << \"Controller window: \" << view << std::endl;\n    }\n  );\n\n  addMessageHandler( \"Window.show\", [] (PlasmacoreMessage m)\n    {\n      auto window_id = m.getInt32( \"id\" );\n      auto view  = (PlasmacoreView*)Plasmacore::singleton.resources[ window_id ];\n      if (view) view->show();\n    }\n  );\n  #else\n  auto view = plasmacore_new_view(\"Main\");\n  if (!view) throw \"No view created!\";\n  std::cerr << \"Controller window: \" << view << std::endl;\n  #endif\n\n  RogueInterface_set_arg_count( gargc );\n  for (int i = 0; i < gargc; ++i)\n  {\n    RogueInterface_set_arg_value( i, gargv[i] );\n  }\n\n  RogueInterface_configure();\n  return *this;\n}\n\n\nRID Plasmacore::getResourceID( void * resource)\n{\n  if (! resource) return 0;\n\n  for (auto const & it : resources)\n  {\n    if (it.second == resource) { return it.first; }\n  }\n  return 0;\n}\n\n\nPlasmacore & Plasmacore::launch()\n{\n  if (is_launched) { return *this; }\n  is_launched = true;\n\n  RogueInterface_launch();\n  auto m = PlasmacoreMessage( \"Application.on_launch\" );\n#ifdef WINDOW_BASED\n  m.set( \"is_window_based\", true );\n#endif\n  m.send();\n  return *this;\n}\n\n\n\n\nPlasmacore & Plasmacore::relaunch()\n{\n  \/\/XXX: Always relaunch window based?\n  PlasmacoreMessage( \"Application.on_launch\" ).set( \"is_window_based\", true ).send();\n  return *this;\n}\n\n\nvoid Plasmacore::removeMessageHandler( HID handlerID )\n{\n  auto iter = handlers_by_id.find(handlerID);\n  if (iter != handlers_by_id.end())\n  {\n    auto handler = iter->second;\n    handlers_by_id.erase( handlerID );\n    auto & handler_list = handlers[ handler.type ]; \/\/ This should always work, right?\n    {\n      for (int i = 0; i < handler_list.size(); ++i)\n      {\n        if (handler_list[i].handlerID == handlerID)\n        {\n          handler_list.erase(handler_list.begin() + i);\n          return;\n        }\n      }\n    }\n  }\n}\n\n\nvoid Plasmacore::send( PlasmacoreMessage & m )\n{\n  auto size = m.data.size();\n  pending_message_data.push_back( uint8_t((size>>24)&255) );\n  pending_message_data.push_back( uint8_t((size>>16)&255) );\n  pending_message_data.push_back( uint8_t((size>>8)&255) );\n  pending_message_data.push_back( uint8_t(size&255) );\n  for (int i = 0; i < m.data.size(); ++i)\n  {\n    pending_message_data.push_back( m.data[i] );\n  }\n  real_update(false);\n}\n\n\nvoid Plasmacore::send_rsvp( PlasmacoreMessage & m, HandlerCallback callback )\n{\n  reply_handlers[ m.message_id ] = PlasmacoreMessageHandler( nextHandlerID, \"\", callback );\n  nextHandlerID += 1;\n  send( m );\n}\n\n\nPlasmacore & Plasmacore::setIdleUpdateFrequency( double f )\n{\n  idleUpdateFrequency = f;\n  if (update_timer)\n  {\n    stop();\n    start();\n  }\n  return *this;\n}\n\n\nvoid Plasmacore::start()\n{\n  if ( !is_launched ) { configure().launch(); }\n  printf(\"LOG: start()\\n\");\n\n  update_timer = true;\n  real_update(true);\n}\n\n\nvoid Plasmacore::stop()\n{\n  \/\/ Note that we don't actually stop any timer from running.  The major\n  \/\/ outcome here is that you may get an extra update if you stop, restart,\n  \/\/ or change the update frequency.\n  \/\/ We *could* probably make this work \"right\" by using a cancellable SDL\n  \/\/ timer, but I don't think it really matters, and I'm not sure that such\n  \/\/ timers are available in emscripten, so we'd have to do this for emscripten\n  \/\/ mode anyway.\n  update_timer = false;\n}\n\n\nvoid Plasmacore::update(void * dummy)\n{\n  \/\/printf(\"LOG: update(); iterations=%i\\n\", iterations);\n  Plasmacore::singleton.real_update(true);\n}\n\nvoid Plasmacore::fast_update(void * dummy)\n{\n  \/\/printf(\"LOG: update(); iterations=%i\\n\", iterations);\n  Plasmacore::singleton.real_update(false);\n}\n\nvoid Plasmacore::real_update (bool reschedule)\n{\n  if (!Plasmacore::singleton.update_timer) return; \/\/ Ignore, since timer shouldn't be running.\n\n  \/\/ Schedule the next idle update.\n  if (reschedule) do_async_call(update, int(1000*idleUpdateFrequency));\n\n  if (is_sending)\n  {\n    update_requested = true;\n    return;\n  }\n\n  is_sending = true;\n\n  \/\/ Execute a small burst of message dispatching and receiving.  Stop after\n  \/\/ 10 iterations or when there are no new messages.  Global state updates\n  \/\/ are frequency capped to 1\/60 second intervals and draws are synced to\n  \/\/ the display refresh so this isn't triggering large amounts of extra work.\n  for (int _ = 0; _ < 10; ++_)\n  {\n    update_requested = false;\n\n    \/\/ Swap pending data with io_buffer data\n    io_buffer.swap(pending_message_data);\n\n    RogueInterface_send_messages( &io_buffer[0], io_buffer.size(), pending_message_data );\n    auto count = pending_message_data.size();\n    \/\/if (count || io_buffer.size())\n    \/\/  printf(\"TX:%-8lu  RX:%-8lu  @iter:%i\\n\", io_buffer.size(), count, iterations);\n    uint8_t * bytes = &pending_message_data[0];\n\n    int read_pos = 0;\n    while (read_pos+4 <= count)\n    {\n      auto size = int( bytes[read_pos] ) << 24;\n      size |= int( bytes[read_pos+1] ) << 16;\n      size |= int( bytes[read_pos+2] ) << 8;\n      size |= int( bytes[read_pos+3] );\n      read_pos += 4;\n\n      if (read_pos + size <= count)\n      {\n        std::vector message_data;\n        message_data.reserve( size );\n        for (int i = 0; i < size; ++i)\n        {\n          message_data.push_back( bytes[read_pos+i] );\n        }\n\n        auto m = PlasmacoreMessage( message_data );\n        printf( \"Received message type %s\\n\", m.type.c_str() );\n        auto iter = handlers.find(m.type);\n        if (iter != handlers.end())\n        {\n          for (auto const & handler : iter->second)\n          {\n            handler.callback( m );\n          }\n        }\n      }\n      else\n      {\n        std::cerr << \"*** Skipping message due to invalid size.\\n\";\n      }\n      read_pos += size;\n    }\n\n    io_buffer.clear();\n\n    if ( !update_requested )\n    {\n      break;\n    }\n  }\n\n  is_sending = false;\n\n  if (update_requested)\n  {\n    \/\/ There are still some pending messages after 10 iterations.  Schedule another round\n    \/\/ in 1\/60 second instead of the usual 1.0 seconds.\n    \/\/ We'll now have another (slow) call to update, but it'll probably return\n    do_async_call(fast_update, 16);\n  }\n}\n\n\nstatic bool should_quit = false;\n\n\nstatic void do_iteration (void)\n{\n  ++iterations;\n  plasmacore_redraw_all_windows();\n  SDL_Event e;\n  while (SDL_PollEvent(&e))\n  {\n    switch (e.type)\n    {\n      case SDL_QUIT:\n        should_quit = true;\n        return;\n      case SDL_MOUSEBUTTONDOWN:\n      case SDL_MOUSEBUTTONUP:\n      {\n        auto w = plasmacore_get_window(e.button.windowID);\n        if (!w) break;\n        int which;\n        switch (e.button.button)\n        {\n          case SDL_BUTTON_LEFT:\n            which = 0;\n            break;\n          case SDL_BUTTON_RIGHT:\n            which = 1;\n            break;\n          default:\n            return;\n        }\n        if (e.type == SDL_MOUSEBUTTONDOWN)\n          w->on_mouse_down(e.button.x, e.button.y, which);\n        else\n          w->on_mouse_up(e.button.x, e.button.y, which);\n        break;\n      }\n      case SDL_MOUSEMOTION:\n      {\n        auto w = plasmacore_get_window(e.motion.windowID);\n        w->on_mouse_move(e.motion.x, e.motion.y);\n        break;\n      }\n      case SDL_WINDOWEVENT:\n      {\n        auto w = plasmacore_get_window(e.button.windowID);\n        if (!w) break;\n        switch (e.window.event)\n        {\n          case SDL_WINDOWEVENT_FOCUS_GAINED:\n            w->on_focus_gained();\n            break;\n        }\n        break;\n      }\n      case SDL_USEREVENT:\n      {\n        if (e.user.code == ASYNC_CALL_EVENT)\n        {\n          \/\/ The following cast is theoretically not allowed.  Let's hope\n          \/\/ it works anyway on platforms we care about.\n          void (*f) (void*) = (void (*)(void*))e.user.data1;\n          f(0);\n          break;\n        }\n      }\n    }\n  }\n}\n\n\nextern \"C\" void start_main_loop (void)\n{\n  emscripten_set_main_loop(do_iteration, 0, 1);\n}\n\n\nPlasmacore Plasmacore::singleton;\n\nint main (int argc, char * argv[])\n{\n  gargc = argc;\n  gargv = argv;\n\n  #ifdef __EMSCRIPTEN__\n    auto flags = 0;\n  #else\n    auto flags = SDL_INIT_TIMER;\n\n    \/\/ CD into what we think the executable's directory is.\n    char * exe = strdup(argv[0]);\n    char * dir = dirname(exe);\n    chdir(dir);\n    free(exe);\n  #endif\n\n  if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|flags) != 0) return 1;\n\n  \/\/ Might want to call this here... but it might also be easier to just\n  \/\/ call it from Rogue via \"native\".\n  \/\/SDL_ShowCursor(false);\n\n  Plasmacore::singleton.configure().launch();\n  PlasmacoreMessage( \"Application.on_start\" ).send();\n  Plasmacore::singleton.start();\n\n#ifdef __EMSCRIPTEN__\n  #ifdef LOCAL_FS\n    EM_ASM(\n       FS.mkdir(\"\/local_storage\");\n       FS.mount(IDBFS, {}, \"\/local_storage\");\n       FS.syncfs(true, function (err) {\n         Module.print(\"Persistent storage ready.\");\n         Module[\"_start_main_loop\"]();\n       });\n       window.addEventListener(\"beforeunload\", function (e) {\n         \/\/ Sync all filesystems\n         FS.syncfs(false, function(err) {});\n         return null;\n       });\n    );\n  #else\n    start_main_loop();\n  #endif\n#else\n  SDL_GL_SetSwapInterval(1);\n  while (!should_quit)\n  {\n    do_iteration();\n    \/\/SDL_Delay(20);\n  }\n#endif\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nnamespace {\n  CFStringRef applicationID = CFSTR(\"org.pqrs.KeyRemap4MacBook\");\n\n  \/\/ ============================================================\n  \/\/ SAVE & LOAD\n  CFMutableDictionaryRef dict_sysctl = NULL;\n  std::map map_reset;\n\n  void\n  save(const char *name)\n  {\n    if (! dict_sysctl) return;\n\n    char entry[512];\n    snprintf(entry, sizeof(entry), \"keyremap4macbook.%s\", name);\n\n    int value;\n    size_t len = sizeof(value);\n    if (sysctlbyname(entry, &value, &len, NULL, 0) == -1) return;\n\n    CFStringRef key = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);\n    CFNumberRef val = CFNumberCreate(NULL, kCFNumberIntType, &value);\n\n    typeof(map_reset.end()) it = map_reset.find(name);\n    if (it == map_reset.end()) return;\n    CFNumberRef defaultval = CFNumberCreate(NULL, kCFNumberIntType, &(it->second));\n\n    if (CFNumberCompare(val, defaultval, NULL) != 0) {\n      CFDictionarySetValue(dict_sysctl, key, val);\n    }\n  }\n\n  void\n  load(const char *name)\n  {\n    if (! dict_sysctl) return;\n    CFStringRef key = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);\n\n    CFNumberRef val = reinterpret_cast(CFDictionaryGetValue(dict_sysctl, key));\n    if (! val) return;\n\n    int value;\n    if (! CFNumberGetValue(val, kCFNumberIntType, &value)) return;\n\n    char cmd[512];\n    snprintf(cmd, sizeof(cmd), \"\/Library\/org.pqrs\/KeyRemap4MacBook\/bin\/KeyRemap4MacBook_sysctl_set %s %d\", name, value);\n    system(cmd);\n  }\n\n  void\n  scanLines(const char *filename, void (*func)(const char *))\n  {\n    std::ifstream ifs(filename);\n    if (! ifs) return;\n\n    while (! ifs.eof()) {\n      char line[512];\n\n      ifs.getline(line, sizeof(line));\n\n      const char *sysctl_begin = \"\";\n      const char *sysctl_end = \"<\/sysctl>\";\n\n      char *begin = strstr(line, \"\");\n      if (! begin) continue;\n      char *end = strstr(line, sysctl_end);\n      if (! end) continue;\n\n      begin += strlen(sysctl_begin);\n      *end = '\\0';\n\n      func(begin);\n    }\n  }\n\n  bool\n  makeMapReset(void)\n  {\n    std::ifstream ifs(\"\/Library\/org.pqrs\/KeyRemap4MacBook\/share\/reset\");\n    if (! ifs) return false;\n\n    while (! ifs.eof()) {\n      char line[512];\n\n      ifs.getline(line, sizeof(line));\n\n      char *p = strchr(line, ' ');\n      if (! p) continue;\n      *p = '\\0';\n\n      int value = atoi(p + 1);\n\n      map_reset[line] = value;\n    }\n\n    return true;\n  }\n\n  bool\n  saveToFile(const char **targetFiles, CFStringRef identify)\n  {\n    if (! makeMapReset()) return false;\n\n    dict_sysctl = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);\n    if (! dict_sysctl) return false;\n\n    for (int i = 0; ; ++i) {\n      const char *filename = targetFiles[i];\n      if (! filename) break;\n      scanLines(filename, save);\n    }\n    CFPreferencesSetAppValue(identify, dict_sysctl, applicationID);\n\n    CFRelease(dict_sysctl); dict_sysctl = NULL;\n    return true;\n  }\n\n  bool\n  loadFromFile(const char **targetFiles, CFStringRef identify)\n  {\n    dict_sysctl = reinterpret_cast(const_cast(CFPreferencesCopyAppValue(identify, applicationID)));\n    if (! dict_sysctl) return false;\n\n    for (int i = 0; ; ++i) {\n      const char *filename = targetFiles[i];\n      if (! filename) break;\n      scanLines(filename, load);\n    }\n\n    CFRelease(dict_sysctl); dict_sysctl = NULL;\n    return true;\n  }\n\n  \/\/ ============================================================\n  \/\/ ADD & DELETE & SELECT\n  void\n  setConfigList(CFArrayRef list)\n  {\n    CFPreferencesSetAppValue(CFSTR(\"configList\"), list, applicationID);\n  }\n\n  CFArrayRef\n  getConfigList(void)\n  {\n    CFArrayRef list = reinterpret_cast(CFPreferencesCopyAppValue(CFSTR(\"configList\"), applicationID));\n\n    if (! list || CFArrayGetCount(list) == 0) {\n      if (list) CFRelease(list);\n\n      CFMutableDictionaryRef dict[1];\n      dict[0] = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);\n      CFDictionarySetValue(dict[0], CFSTR(\"name\"), CFSTR(\"Default\"));\n      CFDictionarySetValue(dict[0], CFSTR(\"identify\"), CFSTR(\"config_default\"));\n\n      list = CFArrayCreate(NULL, const_cast(reinterpret_cast(dict)), 1, NULL);\n      setConfigList(list);\n    }\n\n    return list;\n  }\n\n  CFDictionaryRef\n  getConfigDictionary(int index)\n  {\n    CFArrayRef list = getConfigList();\n    if (! list) return NULL;\n\n    if (index < 0) return NULL;\n    if (index >= CFArrayGetCount(list)) return NULL;\n\n    return reinterpret_cast(CFArrayGetValueAtIndex(list, index));\n  }\n\n  CFStringRef\n  getIdentify(int index)\n  {\n    CFDictionaryRef dict = getConfigDictionary(index);\n    if (! dict) return NULL;\n\n    return reinterpret_cast(CFDictionaryGetValue(dict, CFSTR(\"identify\")));\n  }\n\n  bool\n  appendConfig(void)\n  {\n    CFArrayRef list = getConfigList();\n    if (! list) return false;\n\n    struct timeval tm;\n    gettimeofday(&tm, NULL);\n    CFStringRef identify = CFStringCreateWithFormat(NULL, NULL, CFSTR(\"config_%d_%d\"), tm.tv_sec, tm.tv_usec);\n\n    CFMutableDictionaryRef dict;\n    dict = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);\n    CFDictionarySetValue(dict, CFSTR(\"name\"), CFSTR(\"NewItem\"));\n    CFDictionarySetValue(dict, CFSTR(\"identify\"), identify);\n\n    CFMutableArrayRef newlist = CFArrayCreateMutableCopy(NULL, 0, list);\n    CFArrayAppendValue(newlist, dict);\n\n    setConfigList(newlist);\n    return true;\n  }\n\n  bool\n  removeConfig(int index)\n  {\n    CFStringRef identify = getIdentify(index);\n    if (! identify) return false;\n\n    CFPreferencesSetAppValue(identify, NULL, applicationID);\n\n    CFArrayRef list = getConfigList();\n    if (! list) return false;\n\n    CFMutableArrayRef newlist = CFArrayCreateMutableCopy(NULL, 0, list);\n    CFArrayRemoveValueAtIndex(newlist, index);\n\n    setConfigList(newlist);\n    return true;\n  }\n\n\n  bool\n  renameConfig(int index, const char *newname)\n  {\n    CFArrayRef list = getConfigList();\n    if (! list) return false;\n\n    CFDictionaryRef olddict = getConfigDictionary(index);\n    if (! olddict) return false;\n\n    CFMutableDictionaryRef newdict = CFDictionaryCreateMutableCopy(NULL, 0, olddict);\n    CFDictionarySetValue(newdict, CFSTR(\"name\"), CFStringCreateWithCString(NULL, newname, kCFStringEncodingUTF8));\n\n    CFMutableArrayRef newlist = CFArrayCreateMutableCopy(NULL, 0, list);\n    CFArraySetValueAtIndex(newlist, index, newdict);\n\n    setConfigList(newlist);\n    return true;\n  }\n\n  \/\/ ----------------------------------------\n  bool\n  setSelectedIndex(int index)\n  {\n    CFDictionaryRef dict = getConfigDictionary(index);\n    if (! dict) return false;\n\n    CFNumberRef val = CFNumberCreate(NULL, kCFNumberIntType, &index);\n    CFPreferencesSetAppValue(CFSTR(\"selectedIndex\"), val, applicationID);\n\n    return true;\n  }\n\n  int\n  getSelectedIndex(void)\n  {\n    Boolean isOK;\n    CFIndex value = CFPreferencesGetAppIntegerValue(CFSTR(\"selectedIndex\"), applicationID, &isOK);\n    if (! isOK || value < 0) {\n      value = 0;\n      setSelectedIndex(value);\n    }\n    return value;\n  }\n}\n\n\nint\nmain(int argc, char **argv)\n{\n  if (argc == 1) {\n    fprintf(stderr, \"Usage: %s (save|load|add|delete|name|select) [params]\\n\", argv[0]);\n    return 1;\n  }\n\n  bool isSuccess = false;\n\n  if (strcmp(argv[1], \"select\") == 0) {\n    if (argc < 3) {\n      fprintf(stderr, \"Usage: %s select index\\n\", argv[0]);\n      goto finish;\n    }\n    int index = atoi(argv[2]);\n    isSuccess = setSelectedIndex(index);\n\n  } else if (strcmp(argv[1], \"add\") == 0) {\n    isSuccess = appendConfig();\n\n  } else if (strcmp(argv[1], \"delete\") == 0) {\n    if (argc < 3) {\n      fprintf(stderr, \"Usage: %s delete index\\n\", argv[0]);\n      goto finish;\n    }\n    int index = atoi(argv[2]);\n    isSuccess = removeConfig(index);\n\n  } else if (strcmp(argv[1], \"name\") == 0) {\n    \/\/ sysctl_ctl name \"index\" \"newname\"\n    if (argc < 4) {\n      fprintf(stderr, \"Usage: %s name index newname\\n\", argv[0]);\n      goto finish;\n    }\n    int index = atoi(argv[2]);\n    isSuccess = renameConfig(index, argv[3]);\n\n  } else if ((strcmp(argv[1], \"save\") == 0) || (strcmp(argv[1], \"load\") == 0)) {\n    int value = getSelectedIndex();\n    CFStringRef identify = getIdentify(value);\n\n    const char *targetFiles[] = {\n      \"\/Library\/org.pqrs\/KeyRemap4MacBook\/prefpane\/checkbox.xml\",\n      \"\/Library\/org.pqrs\/KeyRemap4MacBook\/prefpane\/number.xml\",\n      NULL,\n    };\n    if (strcmp(argv[1], \"save\") == 0) {\n      isSuccess = saveToFile(targetFiles, identify);\n    }\n    if (strcmp(argv[1], \"load\") == 0) {\n      system(\"\/Library\/org.pqrs\/KeyRemap4MacBook\/bin\/KeyRemap4MacBook_sysctl_reset\");\n      system(\"\/Library\/org.pqrs\/KeyRemap4MacBook\/bin\/KeyRemap4MacBook_sysctl_set initialized 1\");\n      isSuccess = loadFromFile(targetFiles, identify);\n    }\n  }\n\n  CFPreferencesAppSynchronize(applicationID);\n\nfinish:\n  if (isSuccess) {\n    fprintf(stderr, \"[DONE]\\n\");\n  } else {\n    fprintf(stderr, \"[ERROR]\\n\");\n  }\n\n  return 0;\n}\nsupport rename, count, getname @ sysctl_ctl#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nnamespace {\n  CFStringRef applicationID = CFSTR(\"org.pqrs.KeyRemap4MacBook\");\n\n  \/\/ ============================================================\n  \/\/ SAVE & LOAD\n  CFMutableDictionaryRef dict_sysctl = NULL;\n  std::map map_reset;\n\n  void\n  save(const char *name)\n  {\n    if (! dict_sysctl) return;\n\n    char entry[512];\n    snprintf(entry, sizeof(entry), \"keyremap4macbook.%s\", name);\n\n    int value;\n    size_t len = sizeof(value);\n    if (sysctlbyname(entry, &value, &len, NULL, 0) == -1) return;\n\n    CFStringRef key = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);\n    CFNumberRef val = CFNumberCreate(NULL, kCFNumberIntType, &value);\n\n    typeof(map_reset.end()) it = map_reset.find(name);\n    if (it == map_reset.end()) return;\n    CFNumberRef defaultval = CFNumberCreate(NULL, kCFNumberIntType, &(it->second));\n\n    if (CFNumberCompare(val, defaultval, NULL) != 0) {\n      CFDictionarySetValue(dict_sysctl, key, val);\n    }\n  }\n\n  void\n  load(const char *name)\n  {\n    if (! dict_sysctl) return;\n    CFStringRef key = CFStringCreateWithCString(NULL, name, kCFStringEncodingUTF8);\n\n    CFNumberRef val = reinterpret_cast(CFDictionaryGetValue(dict_sysctl, key));\n    if (! val) return;\n\n    int value;\n    if (! CFNumberGetValue(val, kCFNumberIntType, &value)) return;\n\n    char cmd[512];\n    snprintf(cmd, sizeof(cmd), \"\/Library\/org.pqrs\/KeyRemap4MacBook\/bin\/KeyRemap4MacBook_sysctl_set %s %d\", name, value);\n    system(cmd);\n  }\n\n  void\n  scanLines(const char *filename, void (*func)(const char *))\n  {\n    std::ifstream ifs(filename);\n    if (! ifs) return;\n\n    while (! ifs.eof()) {\n      char line[512];\n\n      ifs.getline(line, sizeof(line));\n\n      const char *sysctl_begin = \"\";\n      const char *sysctl_end = \"<\/sysctl>\";\n\n      char *begin = strstr(line, \"\");\n      if (! begin) continue;\n      char *end = strstr(line, sysctl_end);\n      if (! end) continue;\n\n      begin += strlen(sysctl_begin);\n      *end = '\\0';\n\n      func(begin);\n    }\n  }\n\n  bool\n  makeMapReset(void)\n  {\n    std::ifstream ifs(\"\/Library\/org.pqrs\/KeyRemap4MacBook\/share\/reset\");\n    if (! ifs) return false;\n\n    while (! ifs.eof()) {\n      char line[512];\n\n      ifs.getline(line, sizeof(line));\n\n      char *p = strchr(line, ' ');\n      if (! p) continue;\n      *p = '\\0';\n\n      int value = atoi(p + 1);\n\n      map_reset[line] = value;\n    }\n\n    return true;\n  }\n\n  bool\n  saveToFile(const char **targetFiles, CFStringRef identify)\n  {\n    if (! makeMapReset()) return false;\n\n    dict_sysctl = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);\n    if (! dict_sysctl) return false;\n\n    for (int i = 0; ; ++i) {\n      const char *filename = targetFiles[i];\n      if (! filename) break;\n      scanLines(filename, save);\n    }\n    CFPreferencesSetAppValue(identify, dict_sysctl, applicationID);\n\n    CFRelease(dict_sysctl); dict_sysctl = NULL;\n    return true;\n  }\n\n  bool\n  loadFromFile(const char **targetFiles, CFStringRef identify)\n  {\n    dict_sysctl = reinterpret_cast(const_cast(CFPreferencesCopyAppValue(identify, applicationID)));\n    if (! dict_sysctl) return false;\n\n    for (int i = 0; ; ++i) {\n      const char *filename = targetFiles[i];\n      if (! filename) break;\n      scanLines(filename, load);\n    }\n\n    CFRelease(dict_sysctl); dict_sysctl = NULL;\n    return true;\n  }\n\n  \/\/ ============================================================\n  \/\/ ADD & DELETE & SELECT\n  void\n  setConfigList(CFArrayRef list)\n  {\n    CFPreferencesSetAppValue(CFSTR(\"configList\"), list, applicationID);\n  }\n\n  CFArrayRef\n  getConfigList(void)\n  {\n    CFArrayRef list = reinterpret_cast(CFPreferencesCopyAppValue(CFSTR(\"configList\"), applicationID));\n\n    if (! list || CFArrayGetCount(list) == 0) {\n      if (list) CFRelease(list);\n\n      CFMutableDictionaryRef dict[1];\n      dict[0] = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);\n      CFDictionarySetValue(dict[0], CFSTR(\"name\"), CFSTR(\"Default\"));\n      CFDictionarySetValue(dict[0], CFSTR(\"identify\"), CFSTR(\"config_default\"));\n\n      list = CFArrayCreate(NULL, const_cast(reinterpret_cast(dict)), 1, NULL);\n      setConfigList(list);\n    }\n\n    return list;\n  }\n\n  CFDictionaryRef\n  getConfigDictionary(int index)\n  {\n    CFArrayRef list = getConfigList();\n    if (! list) return NULL;\n\n    if (index < 0) return NULL;\n    if (index >= CFArrayGetCount(list)) return NULL;\n\n    return reinterpret_cast(CFArrayGetValueAtIndex(list, index));\n  }\n\n  CFStringRef\n  getIdentify(int index)\n  {\n    CFDictionaryRef dict = getConfigDictionary(index);\n    if (! dict) return NULL;\n\n    return reinterpret_cast(CFDictionaryGetValue(dict, CFSTR(\"identify\")));\n  }\n\n  CFStringRef\n  getConfigName(int index)\n  {\n    CFDictionaryRef dict = getConfigDictionary(index);\n    if (! dict) return NULL;\n\n    return reinterpret_cast(CFDictionaryGetValue(dict, CFSTR(\"name\")));\n  }\n\n  bool\n  appendConfig(void)\n  {\n    CFArrayRef list = getConfigList();\n    if (! list) return false;\n\n    struct timeval tm;\n    gettimeofday(&tm, NULL);\n    CFStringRef identify = CFStringCreateWithFormat(NULL, NULL, CFSTR(\"config_%d_%d\"), tm.tv_sec, tm.tv_usec);\n\n    CFMutableDictionaryRef dict;\n    dict = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);\n    CFDictionarySetValue(dict, CFSTR(\"name\"), CFSTR(\"NewItem\"));\n    CFDictionarySetValue(dict, CFSTR(\"identify\"), identify);\n\n    CFMutableArrayRef newlist = CFArrayCreateMutableCopy(NULL, 0, list);\n    CFArrayAppendValue(newlist, dict);\n\n    setConfigList(newlist);\n    return true;\n  }\n\n  bool\n  removeConfig(int index)\n  {\n    CFStringRef identify = getIdentify(index);\n    if (! identify) return false;\n\n    CFPreferencesSetAppValue(identify, NULL, applicationID);\n\n    CFArrayRef list = getConfigList();\n    if (! list) return false;\n\n    CFMutableArrayRef newlist = CFArrayCreateMutableCopy(NULL, 0, list);\n    CFArrayRemoveValueAtIndex(newlist, index);\n\n    setConfigList(newlist);\n    return true;\n  }\n\n  bool\n  renameConfig(int index, const char *newname)\n  {\n    CFArrayRef list = getConfigList();\n    if (! list) return false;\n\n    CFDictionaryRef olddict = getConfigDictionary(index);\n    if (! olddict) return false;\n\n    CFMutableDictionaryRef newdict = CFDictionaryCreateMutableCopy(NULL, 0, olddict);\n    CFDictionarySetValue(newdict, CFSTR(\"name\"), CFStringCreateWithCString(NULL, newname, kCFStringEncodingUTF8));\n\n    CFMutableArrayRef newlist = CFArrayCreateMutableCopy(NULL, 0, list);\n    CFArraySetValueAtIndex(newlist, index, newdict);\n\n    setConfigList(newlist);\n    return true;\n  }\n\n  int\n  getConfigCount(void)\n  {\n    CFArrayRef list = getConfigList();\n    if (! list) return 0;\n\n    return CFArrayGetCount(list);\n  }\n\n  \/\/ ----------------------------------------\n  bool\n  setSelectedIndex(int index)\n  {\n    CFDictionaryRef dict = getConfigDictionary(index);\n    if (! dict) return false;\n\n    CFNumberRef val = CFNumberCreate(NULL, kCFNumberIntType, &index);\n    CFPreferencesSetAppValue(CFSTR(\"selectedIndex\"), val, applicationID);\n\n    return true;\n  }\n\n  int\n  getSelectedIndex(void)\n  {\n    Boolean isOK;\n    CFIndex value = CFPreferencesGetAppIntegerValue(CFSTR(\"selectedIndex\"), applicationID, &isOK);\n    if (! isOK || value < 0) {\n      value = 0;\n      setSelectedIndex(value);\n    }\n    return value;\n  }\n}\n\n\nint\nmain(int argc, char **argv)\n{\n  if (argc == 1) {\n    fprintf(stderr, \"Usage: %s (save|load|add|delete|rename|getname|select|count) [params]\\n\", argv[0]);\n    return 1;\n  }\n\n  bool isSuccess = false;\n\n  if (strcmp(argv[1], \"select\") == 0) {\n    if (argc < 3) {\n      fprintf(stderr, \"Usage: %s select index\\n\", argv[0]);\n      goto finish;\n    }\n    int index = atoi(argv[2]);\n    isSuccess = setSelectedIndex(index);\n\n  } else if (strcmp(argv[1], \"add\") == 0) {\n    isSuccess = appendConfig();\n\n  } else if (strcmp(argv[1], \"delete\") == 0) {\n    if (argc < 3) {\n      fprintf(stderr, \"Usage: %s delete index\\n\", argv[0]);\n      goto finish;\n    }\n    int index = atoi(argv[2]);\n    isSuccess = removeConfig(index);\n\n  } else if (strcmp(argv[1], \"rename\") == 0) {\n    \/\/ sysctl_ctl rename \"index\" \"newname\"\n    if (argc < 4) {\n      fprintf(stderr, \"Usage: %s rename index newname\\n\", argv[0]);\n      goto finish;\n    }\n    int index = atoi(argv[2]);\n    isSuccess = renameConfig(index, argv[3]);\n\n  } else if (strcmp(argv[1], \"count\") == 0) {\n    printf(\"%d\\n\", getConfigCount());\n    return 0;\n\n  } else if (strcmp(argv[1], \"getname\") == 0) {\n    if (argc < 3) {\n      fprintf(stderr, \"Usage: %s getname index\\n\", argv[0]);\n      goto finish;\n    }\n    int index = atoi(argv[2]);\n    CFStringRef name = getConfigName(index);\n    if (name) {\n      printf(\"%s\\n\", CFStringGetCStringPtr(name, kCFStringEncodingUTF8));\n    }\n    return 0;\n\n  } else if ((strcmp(argv[1], \"save\") == 0) || (strcmp(argv[1], \"load\") == 0)) {\n    int value = getSelectedIndex();\n    CFStringRef identify = getIdentify(value);\n\n    const char *targetFiles[] = {\n      \"\/Library\/org.pqrs\/KeyRemap4MacBook\/prefpane\/checkbox.xml\",\n      \"\/Library\/org.pqrs\/KeyRemap4MacBook\/prefpane\/number.xml\",\n      NULL,\n    };\n    if (strcmp(argv[1], \"save\") == 0) {\n      isSuccess = saveToFile(targetFiles, identify);\n    }\n    if (strcmp(argv[1], \"load\") == 0) {\n      system(\"\/Library\/org.pqrs\/KeyRemap4MacBook\/bin\/KeyRemap4MacBook_sysctl_reset\");\n      system(\"\/Library\/org.pqrs\/KeyRemap4MacBook\/bin\/KeyRemap4MacBook_sysctl_set initialized 1\");\n      isSuccess = loadFromFile(targetFiles, identify);\n    }\n  }\n\n  CFPreferencesAppSynchronize(applicationID);\n\nfinish:\n  if (isSuccess) {\n    fprintf(stderr, \"[DONE]\\n\");\n  } else {\n    fprintf(stderr, \"[ERROR]\\n\");\n  }\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"\/\/ Module:  Log4CPLUS\n\/\/ File:    ndc.cxx\n\/\/ Created: 6\/2001\n\/\/ Author:  Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2001-2015 Tad E. Smith\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n\n\nnamespace log4cplus\n{\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::DiagnosticContext ctors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace\n{\n\n\nstatic\nvoid\ninit_full_message (log4cplus::tstring & fullMessage,\n    log4cplus::tstring const & message, DiagnosticContext const * parent)\n{\n    if (parent)\n    {\n        fullMessage.reserve (parent->fullMessage.size () + 1\n            + message.size ());\n        fullMessage = parent->fullMessage;\n        fullMessage += LOG4CPLUS_TEXT(\" \");\n        fullMessage += message;\n    }\n    else\n        fullMessage = message;\n}\n\n\n} \/\/ namespace\n\n\nDiagnosticContext::DiagnosticContext(const log4cplus::tstring& message_,\n                                     DiagnosticContext const * parent)\n    : message(message_)\n    , fullMessage()\n{\n    init_full_message (fullMessage, message, parent);\n}\n\n\nDiagnosticContext::DiagnosticContext(tchar const * message_,\n                                     DiagnosticContext const * parent)\n    : message(message_)\n    , fullMessage()\n{\n    init_full_message (fullMessage, message, parent);\n}\n\n\nDiagnosticContext::DiagnosticContext(const log4cplus::tstring& message_)\n    : message(message_)\n    , fullMessage(message)\n{\n}\n\n\nDiagnosticContext::DiagnosticContext(tchar const * message_)\n    : message(message_)\n    , fullMessage(message)\n{\n}\n\n\nDiagnosticContext::DiagnosticContext (DiagnosticContext const & other)\n    : message (other.message)\n    , fullMessage (other.fullMessage)\n{ }\n\n\nDiagnosticContext & DiagnosticContext::operator = (\n    DiagnosticContext const & other)\n{\n    DiagnosticContext (other).swap (*this);\n    return *this;\n}\n\n\n#if defined (LOG4CPLUS_HAVE_RVALUE_REFS)\nDiagnosticContext::DiagnosticContext (DiagnosticContext && other)\n    : message (std::move (other.message))\n    , fullMessage (std::move (other.fullMessage))\n{ }\n\n\nDiagnosticContext &\nDiagnosticContext::operator = (DiagnosticContext && other)\n{\n    DiagnosticContext (std::move (other)).swap (*this);\n    return *this;\n}\n\n#endif\n\n\nvoid\nDiagnosticContext::swap (DiagnosticContext & other)\n{\n    using std::swap;\n    swap (message, other.message);\n    swap (fullMessage, other.fullMessage);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::NDC ctor and dtor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNDC::NDC() \n{ }\n\n\nNDC::~NDC() \n{ }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::NDC public methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nNDC::clear()\n{\n    DiagnosticContextStack* ptr = getPtr();\n    DiagnosticContextStack ().swap (*ptr);\n}\n\n\nDiagnosticContextStack\nNDC::cloneStack() const\n{\n    DiagnosticContextStack* ptr = getPtr();\n    return DiagnosticContextStack(*ptr);\n}\n\n\nvoid \nNDC::inherit(const DiagnosticContextStack& stack)\n{\n    DiagnosticContextStack* ptr = getPtr();\n    DiagnosticContextStack (stack).swap (*ptr);\n}\n\n\nlog4cplus::tstring const &\nNDC::get() const\n{\n    DiagnosticContextStack* ptr = getPtr();\n    if(!ptr->empty())\n        return ptr->back().fullMessage;\n    else\n        return internal::empty_str;\n}\n\n\nstd::size_t \nNDC::getDepth() const\n{\n    DiagnosticContextStack* ptr = getPtr();\n    return ptr->size();\n}\n\n\nlog4cplus::tstring \nNDC::pop()\n{\n    DiagnosticContextStack* ptr = getPtr();\n    if(!ptr->empty())\n    {\n        tstring message;\n        message.swap (ptr->back ().message);\n        ptr->pop_back();\n        return message;\n    }\n    else\n        return log4cplus::tstring ();\n}\n\n\nvoid\nNDC::pop_void ()\n{\n    DiagnosticContextStack* ptr = getPtr ();\n    if (! ptr->empty ())\n        ptr->pop_back ();\n}\n\n\nlog4cplus::tstring const &\nNDC::peek() const\n{\n    DiagnosticContextStack* ptr = getPtr();\n    if(!ptr->empty())\n        return ptr->back().message;\n    else\n        return internal::empty_str;\n}\n\n\nvoid \nNDC::push(const log4cplus::tstring& message)\n{\n    push_worker (message);\n}\n\n\nvoid \nNDC::push(tchar const * message)\n{\n    push_worker (message);\n}\n\n\ntemplate \nvoid\nNDC::push_worker (StringType const & message)\n{\n    DiagnosticContextStack* ptr = getPtr();\n    if (ptr->empty())\n        ptr->push_back( DiagnosticContext(message, NULL) );\n    else\n    {\n        DiagnosticContext const & dc = ptr->back();\n        ptr->push_back( DiagnosticContext(message, &dc) );\n    }\n}\n\n\nvoid \nNDC::remove()\n{\n    DiagnosticContextStack* ptr = getPtr();\n    DiagnosticContextStack ().swap (*ptr);\n}\n\n\nvoid \nNDC::setMaxDepth(std::size_t maxDepth)\n{\n    DiagnosticContextStack* ptr = getPtr();\n    while(maxDepth < ptr->size())\n        ptr->pop_back();\n}\n\n\nDiagnosticContextStack* NDC::getPtr()\n{\n    internal::per_thread_data * ptd = internal::get_ptd ();\n    return &ptd->ndc_dcs;\n}\n\n\n\/\/\n\/\/\n\/\/\n\nNDCContextCreator::NDCContextCreator(const log4cplus::tstring& msg) \n{ \n    getNDC().push(msg); \n}\n\n\nNDCContextCreator::NDCContextCreator(tchar const * msg)\n{\n    getNDC().push(msg);\n}\n\n\nNDCContextCreator::~NDCContextCreator() \n{ \n    getNDC().pop_void(); \n}\n\n\n} \/\/ namespace log4cplus\nndc.cxx: Implement remove() in terms of clear().\/\/ Module:  Log4CPLUS\n\/\/ File:    ndc.cxx\n\/\/ Created: 6\/2001\n\/\/ Author:  Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2001-2015 Tad E. Smith\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n\n\nnamespace log4cplus\n{\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::DiagnosticContext ctors\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace\n{\n\n\nstatic\nvoid\ninit_full_message (log4cplus::tstring & fullMessage,\n    log4cplus::tstring const & message, DiagnosticContext const * parent)\n{\n    if (parent)\n    {\n        fullMessage.reserve (parent->fullMessage.size () + 1\n            + message.size ());\n        fullMessage = parent->fullMessage;\n        fullMessage += LOG4CPLUS_TEXT(\" \");\n        fullMessage += message;\n    }\n    else\n        fullMessage = message;\n}\n\n\n} \/\/ namespace\n\n\nDiagnosticContext::DiagnosticContext(const log4cplus::tstring& message_,\n                                     DiagnosticContext const * parent)\n    : message(message_)\n    , fullMessage()\n{\n    init_full_message (fullMessage, message, parent);\n}\n\n\nDiagnosticContext::DiagnosticContext(tchar const * message_,\n                                     DiagnosticContext const * parent)\n    : message(message_)\n    , fullMessage()\n{\n    init_full_message (fullMessage, message, parent);\n}\n\n\nDiagnosticContext::DiagnosticContext(const log4cplus::tstring& message_)\n    : message(message_)\n    , fullMessage(message)\n{\n}\n\n\nDiagnosticContext::DiagnosticContext(tchar const * message_)\n    : message(message_)\n    , fullMessage(message)\n{\n}\n\n\nDiagnosticContext::DiagnosticContext (DiagnosticContext const & other)\n    : message (other.message)\n    , fullMessage (other.fullMessage)\n{ }\n\n\nDiagnosticContext & DiagnosticContext::operator = (\n    DiagnosticContext const & other)\n{\n    DiagnosticContext (other).swap (*this);\n    return *this;\n}\n\n\n#if defined (LOG4CPLUS_HAVE_RVALUE_REFS)\nDiagnosticContext::DiagnosticContext (DiagnosticContext && other)\n    : message (std::move (other.message))\n    , fullMessage (std::move (other.fullMessage))\n{ }\n\n\nDiagnosticContext &\nDiagnosticContext::operator = (DiagnosticContext && other)\n{\n    DiagnosticContext (std::move (other)).swap (*this);\n    return *this;\n}\n\n#endif\n\n\nvoid\nDiagnosticContext::swap (DiagnosticContext & other)\n{\n    using std::swap;\n    swap (message, other.message);\n    swap (fullMessage, other.fullMessage);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::NDC ctor and dtor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNDC::NDC()\n{ }\n\n\nNDC::~NDC()\n{ }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ log4cplus::NDC public methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nNDC::clear()\n{\n    DiagnosticContextStack* ptr = getPtr();\n    DiagnosticContextStack ().swap (*ptr);\n}\n\n\nvoid\nNDC::remove()\n{\n    clear();\n}\n\n\nDiagnosticContextStack\nNDC::cloneStack() const\n{\n    DiagnosticContextStack* ptr = getPtr();\n    return DiagnosticContextStack(*ptr);\n}\n\n\nvoid\nNDC::inherit(const DiagnosticContextStack& stack)\n{\n    DiagnosticContextStack* ptr = getPtr();\n    DiagnosticContextStack (stack).swap (*ptr);\n}\n\n\nlog4cplus::tstring const &\nNDC::get() const\n{\n    DiagnosticContextStack* ptr = getPtr();\n    if(!ptr->empty())\n        return ptr->back().fullMessage;\n    else\n        return internal::empty_str;\n}\n\n\nstd::size_t\nNDC::getDepth() const\n{\n    DiagnosticContextStack* ptr = getPtr();\n    return ptr->size();\n}\n\n\nlog4cplus::tstring\nNDC::pop()\n{\n    DiagnosticContextStack* ptr = getPtr();\n    if(!ptr->empty())\n    {\n        tstring message;\n        message.swap (ptr->back ().message);\n        ptr->pop_back();\n        return message;\n    }\n    else\n        return log4cplus::tstring ();\n}\n\n\nvoid\nNDC::pop_void ()\n{\n    DiagnosticContextStack* ptr = getPtr ();\n    if (! ptr->empty ())\n        ptr->pop_back ();\n}\n\n\nlog4cplus::tstring const &\nNDC::peek() const\n{\n    DiagnosticContextStack* ptr = getPtr();\n    if(!ptr->empty())\n        return ptr->back().message;\n    else\n        return internal::empty_str;\n}\n\n\nvoid\nNDC::push(const log4cplus::tstring& message)\n{\n    push_worker (message);\n}\n\n\nvoid\nNDC::push(tchar const * message)\n{\n    push_worker (message);\n}\n\n\ntemplate \nvoid\nNDC::push_worker (StringType const & message)\n{\n    DiagnosticContextStack* ptr = getPtr();\n    if (ptr->empty())\n        ptr->push_back( DiagnosticContext(message, NULL) );\n    else\n    {\n        DiagnosticContext const & dc = ptr->back();\n        ptr->push_back( DiagnosticContext(message, &dc) );\n    }\n}\n\n\nvoid\nNDC::setMaxDepth(std::size_t maxDepth)\n{\n    DiagnosticContextStack* ptr = getPtr();\n    while(maxDepth < ptr->size())\n        ptr->pop_back();\n}\n\n\nDiagnosticContextStack* NDC::getPtr()\n{\n    internal::per_thread_data * ptd = internal::get_ptd ();\n    return &ptd->ndc_dcs;\n}\n\n\n\/\/\n\/\/\n\/\/\n\nNDCContextCreator::NDCContextCreator(const log4cplus::tstring& msg)\n{\n    getNDC().push(msg);\n}\n\n\nNDCContextCreator::NDCContextCreator(tchar const * msg)\n{\n    getNDC().push(msg);\n}\n\n\nNDCContextCreator::~NDCContextCreator()\n{\n    getNDC().pop_void();\n}\n\n\n} \/\/ namespace log4cplus\n<|endoftext|>"}
{"text":"\n\/\/ LightSample.cpp :  α׷  Ŭ  մϴ.\n\/\/\n\n#include \"stdafx.h\"\n#include \"resource.h\"\t\t\/\/  ȣԴϴ.\n#include \"D3DView.h\"\n#include \"TopPanel.h\"\n#include \"Controller.h\"\n#include \n\n\nclass CLightSampleApp : public CWinApp\n{\npublic:\n\tCLightSampleApp();\n\tvirtual BOOL InitInstance();\n\tDECLARE_MESSAGE_MAP()\n};\n\nextern CLightSampleApp theApp;\n\n\n\/\/ CLightSampleDlg ȭ \nclass CLightSampleDlg : public CDialogEx\n{\npublic:\n\tCLightSampleDlg(CWnd* pParent = NULL);\t\/\/ ǥ Դϴ.\n\n\tenum { IDD = IDD_LIGHTSAMPLE_DIALOG };\n\n\tvoid MainLoop();\n\n\nprotected:\n\tHICON m_hIcon;\n\tCD3DView *m_view;\n\tbool m_loop;\n\n\tvirtual void DoDataExchange(CDataExchange* pDX);\t\/\/ DDX\/DDV Դϴ.\n\n\t\/\/  ޽  Լ\n\tvirtual BOOL OnInitDialog();\n\tafx_msg void OnSysCommand(UINT nID, LPARAM lParam);\n\tafx_msg void OnPaint();\n\tafx_msg HCURSOR OnQueryDragIcon();\n\tDECLARE_MESSAGE_MAP()\npublic:\n\tafx_msg void OnBnClickedOk();\n\tafx_msg void OnBnClickedCancel();\n};\n\n\n\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n\/\/ CLightSampleApp\n\nBEGIN_MESSAGE_MAP(CLightSampleApp, CWinApp)\n\tON_COMMAND(ID_HELP, &CWinApp::OnHelp)\nEND_MESSAGE_MAP()\n\n\n\/\/ CLightSampleApp \n\nCLightSampleApp::CLightSampleApp()\n{\n\t\/\/ ٽ   \n\tm_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;\n}\n\nCLightSampleApp theApp;\n\n\n\/\/ CLightSampleApp ʱȭ\n\nBOOL CLightSampleApp::InitInstance()\n{\n\tINITCOMMONCONTROLSEX InitCtrls;\n\tInitCtrls.dwSize = sizeof(InitCtrls);\n\tInitCtrls.dwICC = ICC_WIN95_CLASSES;\n\tInitCommonControlsEx(&InitCtrls);\n\n\tCWinApp::InitInstance();\n\tAfxEnableControlContainer();\n\n\tCLightSampleDlg *dlg = new CLightSampleDlg();\n\tdlg->Create(CLightSampleDlg::IDD);\n\tm_pMainWnd = dlg;\n\n\tdlg->ShowWindow(SW_SHOW);\n\tdlg->MainLoop();\n\n\tdelete dlg;\n\treturn FALSE;\n}\n\n\n\n\n\/\/ CLightSampleDlg ȭ \n\nCLightSampleDlg::CLightSampleDlg(CWnd* pParent \/*=NULL*\/)\n\t: CDialogEx(CLightSampleDlg::IDD, pParent)\n,\tm_loop(true)\n,\tm_view(NULL)\n{\n\tm_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);\n}\n\nvoid CLightSampleDlg::DoDataExchange(CDataExchange* pDX)\n{\n\tCDialogEx::DoDataExchange(pDX);\n}\n\nBEGIN_MESSAGE_MAP(CLightSampleDlg, CDialogEx)\n\tON_WM_SYSCOMMAND()\n\tON_WM_PAINT()\n\tON_WM_QUERYDRAGICON()\n\tON_BN_CLICKED(IDOK, &CLightSampleDlg::OnBnClickedOk)\n\tON_BN_CLICKED(IDCANCEL, &CLightSampleDlg::OnBnClickedCancel)\nEND_MESSAGE_MAP()\n\n\n\/\/ CLightSampleDlg ޽ ó\n\nBOOL CLightSampleDlg::OnInitDialog()\n{\n\tCDialogEx::OnInitDialog();\n\n\t\/\/ ý ޴ \"...\" ޴ ׸ ߰մϴ.\n\n\t\/\/ IDM_ABOUTBOX ý   ־ մϴ.\n\tASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);\n\tASSERT(IDM_ABOUTBOX < 0xF000);\n\n\tCMenu* pSysMenu = GetSystemMenu(FALSE);\n\tif (pSysMenu != NULL)\n\t{\n\t\tBOOL bNameValid;\n\t\tCString strAboutMenu;\n\t\tbNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);\n\t\tASSERT(bNameValid);\n\t\tif (!strAboutMenu.IsEmpty())\n\t\t{\n\t\t\tpSysMenu->AppendMenu(MF_SEPARATOR);\n\t\t\tpSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);\n\t\t}\n\t}\n\n\tSetIcon(m_hIcon, TRUE);\t\t\t\/\/ ū  մϴ.\n\tSetIcon(m_hIcon, FALSE);\t\t\/\/   մϴ.\n\n\n\n\tMoveWindow(CRect(0,0,REAL_WINDOW_WIDTH,REAL_WINDOW_HEIGHT));\n\n\t\/\/ Create Main Model View\n\tm_view = new CD3DView();\n\tm_view->Create(NULL, _T(\"CView\"), WS_CHILDWINDOW, \n\t\tCRect(0,0, VIEW_WIDTH, VIEW_HEIGHT), this, 0);\n\n\t\/\/ Create Direct\n\tgraphic::cRenderer::Get()->CreateDirectX(\n\t\tm_view->GetSafeHwnd(), VIEW_WIDTH, VIEW_HEIGHT);\n\n\tm_view->Init();\n\tcController::Get()->Init();\n\tm_view->ShowWindow(SW_SHOW);\n\n\n\t\/\/ TopPanel .\n\t{\n\t\tconst int PANEL_WIDTH = 420;\n\t\tconst int PANEL_HEIGHT = 600;\n\n\t\tCTopPanel *dlg = new CTopPanel();\n\t\tconst CString StrClassName = AfxRegisterWndClass( CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS,\n\t\t\tLoadCursor(NULL, IDC_ARROW), (HBRUSH)GetStockObject(COLOR_BTNFACE+1), \n\t\t\tLoadIcon(NULL, IDI_APPLICATION) );\n\n\t\tdlg->CreateEx(0, StrClassName, L\"Top Panel\", \n\t\t\tWS_POPUP | WS_CAPTION | WS_SYSMENU | MFS_THICKFRAME, \n\t\t\tCRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT), this );\n\n\t\tdlg->Init();\n\n\t\t\/\/ TopPanel Positioning\n\t\t{\n\t\t\tCRect panelR;\n\t\t\tdlg->GetWindowRect(panelR);\n\n\t\t\tconst int screenCX = GetSystemMetrics(SM_CXSCREEN);\n\t\t\tconst int screenCY = GetSystemMetrics(SM_CYSCREEN);\n\t\t\tint x = screenCX\/2 - REAL_WINDOW_WIDTH\/2 + REAL_WINDOW_WIDTH - panelR.Width()\/2;\n\t\t\tconst int y = screenCY\/2 - REAL_WINDOW_HEIGHT\/2;\n\n\t\t\tif ((x+panelR.Width()) > screenCX)\n\t\t\t\tx = screenCX - panelR.Width();\n\n\t\t\tdlg->MoveWindow(x, y, panelR.Width(), panelR.Height());\n\n\n\t\t\t\/\/ Main Dialog RePositioning\n\t\t\tint px = screenCX\/2 - REAL_WINDOW_WIDTH\/2 - panelR.Width()\/2;\n\t\t\tpx = max(0, px);\n\t\t\tMoveWindow(px, y, REAL_WINDOW_WIDTH,REAL_WINDOW_HEIGHT);\n\t\t}\n\n\t\tdlg->ShowWindow(SW_SHOW);\n\t}\n\n\n\treturn TRUE;  \/\/ Ŀ Ʈѿ   TRUE ȯմϴ.\n}\n\nvoid CLightSampleDlg::OnSysCommand(UINT nID, LPARAM lParam)\n{\n\tif ((nID & 0xFFF0) == IDM_ABOUTBOX)\n\t{\n\t}\n\telse\n\t{\n\t\tCDialogEx::OnSysCommand(nID, lParam);\n\t}\n}\n\n\nvoid CLightSampleDlg::OnPaint()\n{\n\tif (IsIconic())\n\t{\n\t\tCPaintDC dc(this); \/\/ ׸⸦  ̽ ؽƮԴϴ.\n\n\t\tSendMessage(WM_ICONERASEBKGND, reinterpret_cast(dc.GetSafeHdc()), 0);\n\n\t\t\/\/ Ŭ̾Ʈ 簢   ϴ.\n\t\tint cxIcon = GetSystemMetrics(SM_CXICON);\n\t\tint cyIcon = GetSystemMetrics(SM_CYICON);\n\t\tCRect rect;\n\t\tGetClientRect(&rect);\n\t\tint x = (rect.Width() - cxIcon + 1) \/ 2;\n\t\tint y = (rect.Height() - cyIcon + 1) \/ 2;\n\n\t\t\/\/  ׸ϴ.\n\t\tdc.DrawIcon(x, y, m_hIcon);\n\t}\n\telse\n\t{\n\t\tCDialogEx::OnPaint();\n\t}\n}\n\n\/\/ ڰ ּȭ â  ȿ Ŀ ǥõǵ ýۿ\n\/\/   Լ ȣմϴ.\nHCURSOR CLightSampleDlg::OnQueryDragIcon()\n{\n\treturn static_cast(m_hIcon);\n}\n\n\n\nvoid CLightSampleDlg::OnBnClickedOk()\n{\n\tCDialogEx::OnOK();\n}\n\n\nvoid CLightSampleDlg::OnBnClickedCancel()\n{\n\tm_loop = false;\n\tCDialogEx::OnCancel();\n}\n\n\nvoid CLightSampleDlg::MainLoop()\n{\n\twhile (m_loop)\n\t{\n\t\tMSG msg;\n\t\tif (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))\n\t\t{\n\t\t\tif (!GetMessage(&msg, NULL, 0, 0)) \n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t::TranslateMessage(&msg);\n\t\t\t::DispatchMessage(&msg);\n\t\t}\n\n\t\tconst int curT = timeGetTime();\n\t\tstatic int oldT = curT;\n\t\tconst int elapseT = curT - oldT;\n\t\tconst float t = elapseT * 0.001f;\n\t\toldT = curT;\n\n\t\tif (m_view)\n\t\t{\n\t\t\tm_view->Update(t);\n\t\t\tm_view->Render();\n\t\t}\n\n\t\tSleep(0);\n\t}\n}\nupdate comment\/\/\n\/\/\n\/\/    Ʈ\n\/\/ http:\/\/www.directxtutorial.com\/Lesson.aspx?lessonid=9-4-9\n\/\/\n\n#include \"stdafx.h\"\n#include \"resource.h\"\t\t\/\/  ȣԴϴ.\n#include \"D3DView.h\"\n#include \"TopPanel.h\"\n#include \"Controller.h\"\n#include \n\n\nclass CLightSampleApp : public CWinApp\n{\npublic:\n\tCLightSampleApp();\n\tvirtual BOOL InitInstance();\n\tDECLARE_MESSAGE_MAP()\n};\n\nextern CLightSampleApp theApp;\n\n\n\/\/ CLightSampleDlg ȭ \nclass CLightSampleDlg : public CDialogEx\n{\npublic:\n\tCLightSampleDlg(CWnd* pParent = NULL);\t\/\/ ǥ Դϴ.\n\n\tenum { IDD = IDD_LIGHTSAMPLE_DIALOG };\n\n\tvoid MainLoop();\n\n\nprotected:\n\tHICON m_hIcon;\n\tCD3DView *m_view;\n\tbool m_loop;\n\n\tvirtual void DoDataExchange(CDataExchange* pDX);\t\/\/ DDX\/DDV Դϴ.\n\n\t\/\/  ޽  Լ\n\tvirtual BOOL OnInitDialog();\n\tafx_msg void OnSysCommand(UINT nID, LPARAM lParam);\n\tafx_msg void OnPaint();\n\tafx_msg HCURSOR OnQueryDragIcon();\n\tDECLARE_MESSAGE_MAP()\npublic:\n\tafx_msg void OnBnClickedOk();\n\tafx_msg void OnBnClickedCancel();\n};\n\n\n\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n\/\/ CLightSampleApp\n\nBEGIN_MESSAGE_MAP(CLightSampleApp, CWinApp)\n\tON_COMMAND(ID_HELP, &CWinApp::OnHelp)\nEND_MESSAGE_MAP()\n\n\n\/\/ CLightSampleApp \n\nCLightSampleApp::CLightSampleApp()\n{\n\t\/\/ ٽ   \n\tm_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;\n}\n\nCLightSampleApp theApp;\n\n\n\/\/ CLightSampleApp ʱȭ\n\nBOOL CLightSampleApp::InitInstance()\n{\n\tINITCOMMONCONTROLSEX InitCtrls;\n\tInitCtrls.dwSize = sizeof(InitCtrls);\n\tInitCtrls.dwICC = ICC_WIN95_CLASSES;\n\tInitCommonControlsEx(&InitCtrls);\n\n\tCWinApp::InitInstance();\n\tAfxEnableControlContainer();\n\n\tCLightSampleDlg *dlg = new CLightSampleDlg();\n\tdlg->Create(CLightSampleDlg::IDD);\n\tm_pMainWnd = dlg;\n\n\tdlg->ShowWindow(SW_SHOW);\n\tdlg->MainLoop();\n\n\tdelete dlg;\n\treturn FALSE;\n}\n\n\n\n\n\/\/ CLightSampleDlg ȭ \n\nCLightSampleDlg::CLightSampleDlg(CWnd* pParent \/*=NULL*\/)\n\t: CDialogEx(CLightSampleDlg::IDD, pParent)\n,\tm_loop(true)\n,\tm_view(NULL)\n{\n\tm_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);\n}\n\nvoid CLightSampleDlg::DoDataExchange(CDataExchange* pDX)\n{\n\tCDialogEx::DoDataExchange(pDX);\n}\n\nBEGIN_MESSAGE_MAP(CLightSampleDlg, CDialogEx)\n\tON_WM_SYSCOMMAND()\n\tON_WM_PAINT()\n\tON_WM_QUERYDRAGICON()\n\tON_BN_CLICKED(IDOK, &CLightSampleDlg::OnBnClickedOk)\n\tON_BN_CLICKED(IDCANCEL, &CLightSampleDlg::OnBnClickedCancel)\nEND_MESSAGE_MAP()\n\n\n\/\/ CLightSampleDlg ޽ ó\n\nBOOL CLightSampleDlg::OnInitDialog()\n{\n\tCDialogEx::OnInitDialog();\n\n\t\/\/ ý ޴ \"...\" ޴ ׸ ߰մϴ.\n\n\t\/\/ IDM_ABOUTBOX ý   ־ մϴ.\n\tASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);\n\tASSERT(IDM_ABOUTBOX < 0xF000);\n\n\tCMenu* pSysMenu = GetSystemMenu(FALSE);\n\tif (pSysMenu != NULL)\n\t{\n\t\tBOOL bNameValid;\n\t\tCString strAboutMenu;\n\t\tbNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);\n\t\tASSERT(bNameValid);\n\t\tif (!strAboutMenu.IsEmpty())\n\t\t{\n\t\t\tpSysMenu->AppendMenu(MF_SEPARATOR);\n\t\t\tpSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);\n\t\t}\n\t}\n\n\tSetIcon(m_hIcon, TRUE);\t\t\t\/\/ ū  մϴ.\n\tSetIcon(m_hIcon, FALSE);\t\t\/\/   մϴ.\n\n\n\n\tMoveWindow(CRect(0,0,REAL_WINDOW_WIDTH,REAL_WINDOW_HEIGHT));\n\n\t\/\/ Create Main Model View\n\tm_view = new CD3DView();\n\tm_view->Create(NULL, _T(\"CView\"), WS_CHILDWINDOW, \n\t\tCRect(0,0, VIEW_WIDTH, VIEW_HEIGHT), this, 0);\n\n\t\/\/ Create Direct\n\tgraphic::cRenderer::Get()->CreateDirectX(\n\t\tm_view->GetSafeHwnd(), VIEW_WIDTH, VIEW_HEIGHT);\n\n\tm_view->Init();\n\tcController::Get()->Init();\n\tm_view->ShowWindow(SW_SHOW);\n\n\n\t\/\/ TopPanel .\n\t{\n\t\tconst int PANEL_WIDTH = 420;\n\t\tconst int PANEL_HEIGHT = 600;\n\n\t\tCTopPanel *dlg = new CTopPanel();\n\t\tconst CString StrClassName = AfxRegisterWndClass( CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS,\n\t\t\tLoadCursor(NULL, IDC_ARROW), (HBRUSH)GetStockObject(COLOR_BTNFACE+1), \n\t\t\tLoadIcon(NULL, IDI_APPLICATION) );\n\n\t\tdlg->CreateEx(0, StrClassName, L\"Top Panel\", \n\t\t\tWS_POPUP | WS_CAPTION | WS_SYSMENU | MFS_THICKFRAME, \n\t\t\tCRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT), this );\n\n\t\tdlg->Init();\n\n\t\t\/\/ TopPanel Positioning\n\t\t{\n\t\t\tCRect panelR;\n\t\t\tdlg->GetWindowRect(panelR);\n\n\t\t\tconst int screenCX = GetSystemMetrics(SM_CXSCREEN);\n\t\t\tconst int screenCY = GetSystemMetrics(SM_CYSCREEN);\n\t\t\tint x = screenCX\/2 - REAL_WINDOW_WIDTH\/2 + REAL_WINDOW_WIDTH - panelR.Width()\/2;\n\t\t\tconst int y = screenCY\/2 - REAL_WINDOW_HEIGHT\/2;\n\n\t\t\tif ((x+panelR.Width()) > screenCX)\n\t\t\t\tx = screenCX - panelR.Width();\n\n\t\t\tdlg->MoveWindow(x, y, panelR.Width(), panelR.Height());\n\n\n\t\t\t\/\/ Main Dialog RePositioning\n\t\t\tint px = screenCX\/2 - REAL_WINDOW_WIDTH\/2 - panelR.Width()\/2;\n\t\t\tpx = max(0, px);\n\t\t\tMoveWindow(px, y, REAL_WINDOW_WIDTH,REAL_WINDOW_HEIGHT);\n\t\t}\n\n\t\tdlg->ShowWindow(SW_SHOW);\n\t}\n\n\n\treturn TRUE;  \/\/ Ŀ Ʈѿ   TRUE ȯմϴ.\n}\n\nvoid CLightSampleDlg::OnSysCommand(UINT nID, LPARAM lParam)\n{\n\tif ((nID & 0xFFF0) == IDM_ABOUTBOX)\n\t{\n\t}\n\telse\n\t{\n\t\tCDialogEx::OnSysCommand(nID, lParam);\n\t}\n}\n\n\nvoid CLightSampleDlg::OnPaint()\n{\n\tif (IsIconic())\n\t{\n\t\tCPaintDC dc(this); \/\/ ׸⸦  ̽ ؽƮԴϴ.\n\n\t\tSendMessage(WM_ICONERASEBKGND, reinterpret_cast(dc.GetSafeHdc()), 0);\n\n\t\t\/\/ Ŭ̾Ʈ 簢   ϴ.\n\t\tint cxIcon = GetSystemMetrics(SM_CXICON);\n\t\tint cyIcon = GetSystemMetrics(SM_CYICON);\n\t\tCRect rect;\n\t\tGetClientRect(&rect);\n\t\tint x = (rect.Width() - cxIcon + 1) \/ 2;\n\t\tint y = (rect.Height() - cyIcon + 1) \/ 2;\n\n\t\t\/\/  ׸ϴ.\n\t\tdc.DrawIcon(x, y, m_hIcon);\n\t}\n\telse\n\t{\n\t\tCDialogEx::OnPaint();\n\t}\n}\n\n\/\/ ڰ ּȭ â  ȿ Ŀ ǥõǵ ýۿ\n\/\/   Լ ȣմϴ.\nHCURSOR CLightSampleDlg::OnQueryDragIcon()\n{\n\treturn static_cast(m_hIcon);\n}\n\n\n\nvoid CLightSampleDlg::OnBnClickedOk()\n{\n\tCDialogEx::OnOK();\n}\n\n\nvoid CLightSampleDlg::OnBnClickedCancel()\n{\n\tm_loop = false;\n\tCDialogEx::OnCancel();\n}\n\n\nvoid CLightSampleDlg::MainLoop()\n{\n\twhile (m_loop)\n\t{\n\t\tMSG msg;\n\t\tif (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))\n\t\t{\n\t\t\tif (!GetMessage(&msg, NULL, 0, 0)) \n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t::TranslateMessage(&msg);\n\t\t\t::DispatchMessage(&msg);\n\t\t}\n\n\t\tconst int curT = timeGetTime();\n\t\tstatic int oldT = curT;\n\t\tconst int elapseT = curT - oldT;\n\t\tconst float t = elapseT * 0.001f;\n\t\toldT = curT;\n\n\t\tif (m_view)\n\t\t{\n\t\t\tm_view->Update(t);\n\t\t\tm_view->Render();\n\t\t}\n\n\t\tSleep(0);\n\t}\n}\n<|endoftext|>"}
{"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n\n#include \"VisitorUtils.hpp\"\n#include \"Variable.hpp\"\n#include \"SemanticalException.hpp\"\n\n#include \"tac\/TacCompiler.hpp\"\n#include \"tac\/Program.hpp\"\n\n#include \"ast\/Program.hpp\"\n\nusing namespace eddic;\n\nclass CompilerVisitor : public boost::static_visitor<> {\n    private:\n        StringPool& pool;\n        tac::Program& program;\n\n        std::shared_ptr function;\n    \n    public:\n        CompilerVisitor(StringPool& p, tac::Program& tacProgram) : pool(p), program(tacProgram) {}\n        \n        void operator()(ast::Program& p){\n            program.context = p.Content->context;\n\n            visit_each(*this, p.Content->blocks);\n        }\n\n        void operator()(ast::FunctionDeclaration& f){\n            function = std::make_shared(f.Content->context);\n\n            \/\/The entry basic block\n            function->newBasicBlock(); \n\n            visit_each(*this, f.Content->instructions);\n\n            program.functions.push_back(function);\n        }\n\n        void operator()(ast::GlobalVariableDeclaration&){\n            \/\/Nothing to compile, the global variable values are written using global contexts\n        }\n        \n        void operator()(ast::GlobalArrayDeclaration&){\n            \/\/Nothing to compile, the global arrays are written using global contexts\n        }\n\n        void operator()(ast::ArrayDeclaration&){\n            \/\/Nothing to compile there, everything is done by the function context\n        }\n\n        void operator()(ast::If& if_){\n\n        }\n\n        void operator()(ast::Assignment& assignment){\n\n        }\n        \n        void operator()(ast::ArrayAssignment& assignment){\n\n        }\n\n        void operator()(ast::VariableDeclaration& declaration){\n\n        }\n\n        void operator()(ast::Swap& swap){\n            auto lhs_var = swap.Content->lhs_var;\n            auto rhs_var = swap.Content->rhs_var;\n\n            \/\/We have the guarantee here that both variables are of the same type\n            switch (lhs_var->type().base()) {\n                case BaseType::INT:{\n                    auto temp = swap.Content->context->newTemporary();\n\n                    function->currentBasicBlock()->add(tac::Quadruple(temp, rhs_var));  \n                    function->currentBasicBlock()->add(tac::Quadruple(rhs_var, lhs_var));  \n                    function->currentBasicBlock()->add(tac::Quadruple(lhs_var, temp));  \n\n                    break;\n                }\n                case BaseType::STRING:{\n  \/*                  auto registerA = program.registers(EAX);\n                   \n                    auto left = lhs_var->toStringOperand();\n                    auto right = rhs_var->toStringOperand();\n                    \n                    program.addInstruction(program.factory().createMove(left.first, registerA));\n                    program.addInstruction(program.factory().createMove(right.first, left.first));\n                    program.addInstruction(program.factory().createMove(registerA, right.first));\n                    \n                    program.addInstruction(program.factory().createMove(left.second, registerA));\n                    program.addInstruction(program.factory().createMove(right.second, left.second));\n                    program.addInstruction(program.factory().createMove(registerA, right.second));\n    *\/                \n                    break;\n                }\n                default:\n                   throw SemanticalException(\"Variable of invalid type\");\n            }\n        }\n\n        void operator()(ast::While& while_){\n\n        }\n\n        void operator()(ast::For for_){\n\n        }\n\n        void operator()(ast::Foreach&){\n            assert(false); \/\/This node has been transformed into a for node\n        }\n       \n        void operator()(ast::ForeachIn& foreach){\n\n        }\n\n        void operator()(ast::FunctionCall& functionCall){\n\n        }\n\n        void operator()(ast::Return& return_){\n\n        }\n};\n\nvoid tac::TacCompiler::compile(ast::Program& program, StringPool& pool, tac::Program& tacProgram) const {\n    CompilerVisitor visitor(pool, tacProgram);\n    visitor(program);\n}\nCompile string variables swap\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n\n#include \"VisitorUtils.hpp\"\n#include \"Variable.hpp\"\n#include \"SemanticalException.hpp\"\n\n#include \"tac\/TacCompiler.hpp\"\n#include \"tac\/Program.hpp\"\n\n#include \"ast\/Program.hpp\"\n\nusing namespace eddic;\n\nclass CompilerVisitor : public boost::static_visitor<> {\n    private:\n        StringPool& pool;\n        tac::Program& program;\n\n        std::shared_ptr function;\n    \n    public:\n        CompilerVisitor(StringPool& p, tac::Program& tacProgram) : pool(p), program(tacProgram) {}\n        \n        void operator()(ast::Program& p){\n            program.context = p.Content->context;\n\n            visit_each(*this, p.Content->blocks);\n        }\n\n        void operator()(ast::FunctionDeclaration& f){\n            function = std::make_shared(f.Content->context);\n\n            \/\/The entry basic block\n            function->newBasicBlock(); \n\n            visit_each(*this, f.Content->instructions);\n\n            program.functions.push_back(function);\n        }\n\n        void operator()(ast::GlobalVariableDeclaration&){\n            \/\/Nothing to compile, the global variable values are written using global contexts\n        }\n        \n        void operator()(ast::GlobalArrayDeclaration&){\n            \/\/Nothing to compile, the global arrays are written using global contexts\n        }\n\n        void operator()(ast::ArrayDeclaration&){\n            \/\/Nothing to compile there, everything is done by the function context\n        }\n\n        void operator()(ast::If& if_){\n\n        }\n\n        void operator()(ast::Assignment& assignment){\n\n        }\n        \n        void operator()(ast::ArrayAssignment& assignment){\n\n        }\n\n        void operator()(ast::VariableDeclaration& declaration){\n\n        }\n\n        void operator()(ast::Swap& swap){\n            auto lhs_var = swap.Content->lhs_var;\n            auto rhs_var = swap.Content->rhs_var;\n\n            \/\/We have the guarantee here that both variables are of the same type\n            switch (lhs_var->type().base()) {\n                case BaseType::INT:{\n                    auto temp = swap.Content->context->newTemporary();\n\n                    function->currentBasicBlock()->add(tac::Quadruple(temp, rhs_var));  \n                    function->currentBasicBlock()->add(tac::Quadruple(rhs_var, lhs_var));  \n                    function->currentBasicBlock()->add(tac::Quadruple(lhs_var, temp));  \n\n                    break;\n                }\n                case BaseType::STRING:{\n                    auto temp = swap.Content->context->newTemporary();\n\n                    function->currentBasicBlock()->add(tac::Quadruple(temp, rhs_var));  \n                    function->currentBasicBlock()->add(tac::Quadruple(rhs_var, lhs_var));  \n                    function->currentBasicBlock()->add(tac::Quadruple(lhs_var, temp));  \n\n                    function->currentBasicBlock()->add(tac::Quadruple(temp, rhs_var, tac::Operator::DOT, 4));  \n                    function->currentBasicBlock()->add(tac::Quadruple(rhs_var, lhs_var, tac::Operator::DOT, 4));  \n                    function->currentBasicBlock()->add(tac::Quadruple(lhs_var, temp));  \n\n                    break;\n                }\n                default:\n                   throw SemanticalException(\"Variable of invalid type\");\n            }\n        }\n\n        void operator()(ast::While& while_){\n\n        }\n\n        void operator()(ast::For for_){\n\n        }\n\n        void operator()(ast::Foreach&){\n            assert(false); \/\/This node has been transformed into a for node\n        }\n       \n        void operator()(ast::ForeachIn& foreach){\n\n        }\n\n        void operator()(ast::FunctionCall& functionCall){\n\n        }\n\n        void operator()(ast::Return& return_){\n\n        }\n};\n\nvoid tac::TacCompiler::compile(ast::Program& program, StringPool& pool, tac::Program& tacProgram) const {\n    CompilerVisitor visitor(pool, tacProgram);\n    visitor(program);\n}\n<|endoftext|>"}
{"text":"\/*=========================================================================\n\n  Program:   Insight Segmentation & Registration Toolkit\n  Module:    MetaImageImporter.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n  Copyright (c) 2002 Insight Consortium. All rights reserved.\n  See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n  {\n  std::cout << \"Importing your data into the MetaImage format\"\n    << std::endl\n    << \"  is merely of matter of making a text file that\"\n    << std::endl\n    << \"  contains some info about your data and that also\"\n    << std::endl\n    << \"  lists the file(s) that contain your data.\"\n    << std::endl\n    << std::endl\n    << \"This program helps you create that text file - we\"\n    << std::endl\n    << \"  designate these text files with the suffix '.mhd'\"\n    << std::endl\n    << std::endl;\n  \n  std::string filename;\n  std::cout << \"What is the name of the '.mhd' file that you\"\n    << std::endl\n    << \"  want to create?   Please include '.mhd' at the end.\" \n    << std::endl\n    << \"  -=> \";\n  std::cin >> filename;\n  std::cout << std::endl;\n  \n  std::ofstream fp;\n  fp.open(filename.c_str());\n  \n  std::cout << \"What is the dimensionality of your data (1, 2, 3, ...)?\"\n    << std::endl\n    << \"  -=> \";\n  int nDims;\n  std::cin >> nDims;\n  if(nDims < 1)\n    {\n    std::cout << \"...have a nice day\" << std::endl;\n    return 1;\n    }\n  std::cout << std::endl;\n  fp << \"NDims = \" << nDims << std::endl;\n  \n  int i;\n  int * dimSize = new int [nDims];\n  std::cout << \"Assuming dimension 0 is the 'x' dimension...\" << std::endl;\n  for(i = 0; i < nDims; i++)\n    {\n    std::cout << \"  How large is dimension \" << i << \" -=> \";\n    std::cin >> dimSize[i];\n    if(dimSize[i]<1)\n      {\n      std::cout << \"    ...we'll assume you meant 1...\" << std::endl;\n      dimSize[i] = 1;\n      }\n    }\n  std::cout << std::endl;\n  fp << \"DimSize =\";\n  for(i = 0; i < nDims; i++)\n    {\n    fp << \" \" << dimSize[i];\n    }\n  fp << std::endl;\n  \n  \n  float * pointSpacing = new float [nDims];\n  std::cout << \"Points in an image represent a measure in physical space.\"\n    << std::endl\n    << \"   Measures in physical space are done using a particular\"\n    << std::endl\n    << \"   aperature spacing - that is, what is the spacing of the\"\n    << std::endl\n    << \"   points in your data...if you don't know\/care, answer 1.\"\n    << std::endl;\n  for(i = 0; i < nDims; i++)\n    {\n    std::cout << \"  What is the point spacing in dimension \" << i << \"? -=> \";\n    std::cin >> pointSpacing[i];\n    if(pointSpacing[i]<0.0000000000000001)\n      {\n      std::cout << \"...we'll assume you meant 1...\" << std::endl;\n      pointSpacing[i] = 1;\n      }\n    }\n  std::cout << std::endl;\n  fp << \"ElementSpacing =\";\n  for(i = 0; i < nDims; i++)\n    {\n    fp << \" \" << pointSpacing[i];\n    }\n  fp << std::endl;\n  \n  float * origin = new float [nDims];\n  std::cout << \"Images are taken of a particular location in space.\"\n    << std::endl\n    << \"   That is, they have an origin in space...if you don't\"\n    << std::endl\n    << \"   know\/care, answer 0 for each dimension.\"\n    << std::endl;\n  for(i = 0; i < nDims; i++)\n    {\n    std::cout << \"  What is the origin in dimension \" << i << \"? -=> \";\n    std::cin >> origin[i];\n    }\n  std::cout << std::endl;\n  fp << \"Position =\";\n  for(i = 0; i < nDims; i++)\n    {\n    fp << \" \" << origin[i];\n    }\n  fp << std::endl;\n  \n  bool byteOrderMSB = false;\n  std::cout << \"Is your data stored using MSB byte ordering?\"\n    << std::endl\n    << \"  Data written on a 'PC' is in 'Little-endian' byte order.\"\n    << std::endl\n    << \"  Data from almost every other machine is in 'Big-endian'\"\n    << std::endl\n    << \"  byte order.  If your data was written on a 'PC', enter 0.\"\n    << std::endl\n    << \"  Otherwise, if you data was written on a Mac\/Sun\/Other, enter 1.\"\n    << std::endl\n    << \"  -=> \";\n  std::cin >> byteOrderMSB;\n  std::cout << std::endl;\n  if(byteOrderMSB)\n    {\n    fp << \"ElementByteOrderMSB = True\" << std::endl;\n    }\n  else\n    {\n    fp << \"ElementByteOrderMSB = False\" << std::endl;\n    }\n  \n  int nComps = 1;\n  std::cout << \"How many channels are stored at each point in your image?\"\n    << std::endl\n    << \"  For example, RGB images have 3 channels, and most medical\"\n    << std::endl\n    << \"  images have a single channel.\"\n    << std::endl\n    << \"  -=> \";\n  std::cin >> nComps;\n  std::cout << std::endl;\n  if(nComps<1)\n    {\n    nComps = 1;\n    }\n  if(nComps != 1)\n    {\n    fp << \"ElementNumberOfChannels = \" << nComps << std::endl;\n    }\n  \n  int elementType;\n  std::cout << \"What is the 'type' of the elements in your data :\"\n    << std::endl\n    << \"  0 - signed char (one byte)\" << std::endl\n    << \"  1 - unsigned char\" << std::endl\n    << \"  2 - signed short (two byte)\" << std::endl\n    << \"  3 - unsigned short\" << std::endl\n    << \"  4 - signed int (four byte)\" << std::endl\n    << \"  5 - unsigned int\" << std::endl\n    << \"  6 - float (four byte)\" << std::endl\n    << \"  7 - double (eight byte)\" << std::endl\n    << \"  -=> \";\n  std::cin >> elementType;\n  std::cout << std::endl;\n  switch(elementType)\n    {\n    case 0 : fp << \"ElementType = MET_CHAR\" << std::endl;\n      break;\n    case 1 : fp << \"ElementType = MET_UCHAR\" << std::endl;\n      break;\n    case 2 : fp << \"ElementType = MET_SHORT\" << std::endl;\n      break;\n    case 3 : fp << \"ElementType = MET_USHORT\" << std::endl;\n      break;\n    case 4 : fp << \"ElementType = MET_INT\" << std::endl;\n      break;\n    case 5 : fp << \"ElementType = MET_UINT\" << std::endl;\n      break;\n    case 6 : fp << \"ElementType = MET_FLOAT\" << std::endl;\n      break;\n    case 7 : fp << \"ElementType = MET_DOUBLE\" << std::endl;\n      break;\n    default: fp.close();\n      std::cout << \"...have a nice day.\" << std::endl;\n    }\n  \n  int storage = 0;\n  std::cout << \"How is the data stored ?\" << std::endl\n    << \"  0 - in one file\" << std::endl\n    << \"  1 - in one file per slice (e.g., like dicom)\" << std::endl\n    << \"  -=> \";\n  std::cin >> storage;\n  std::cout << std::endl;\n\n  int headerSize = -1;\n  std::cout << \"Size of the header that must be skipped to\"\n    << std::endl\n    << \"  reach the data in the file(s)? Enter 0 to not skip\"\n    << std::endl\n    << \"  a header, -1 to have MetaImageReader automatically\"\n    << std::endl\n    << \"  calculate the headersize assuming the data is at\"\n    << std::endl\n    << \"  the end of the file, or enter the headersize\"\n    << std::endl\n    << \"  -=> \";\n  std::cin >> headerSize;\n  std::cout << std::endl;\n  if(headerSize > 0 || headerSize == -1)\n    {\n    fp << \"HeaderSize = \" << headerSize << std::endl;\n    }\n\n  int storageList = 0;\n  if(storage == 0)\n    {\n    std::string fname;\n    std::cout << \"Name of the file containing the data -=> \";\n    std::cin >> fname;\n    fp << \"ElementDataFile = \" << fname << std::endl;\n    fp.close();\n    std::cout << std::endl;\n    std::cout << std::endl;\n    std::cout << \"You're done!\" << std::endl;\n    std::cout << std::endl;\n    }\n  else\n    {\n    std::cout << \"You've got two options when doing one file per slice:\"\n      << std::endl\n      << \"  0 - Listing the name of each slice in the .mhd file\"\n      << std::endl\n      << \"  1 - Specifying a 'fprintf' style string and min, max,\"\n      << std::endl\n      << \"        and step values for integers to be substituted\"\n      << std::endl\n      << \"        into that string to specify the numbered files\"\n      << std::endl\n      << \"        that are the slices.  For example, use data.%03d to\"\n      << std::endl\n      << \"        match data.000, data.001, data.002,...If you don't\"\n      << std::endl\n      << \"        know what we are talking about, choose option 0.\"\n      << std::endl\n      << \"  -=> \";\n    std::cin >> storageList;\n    std::cout << std::endl;\n    \n    if(storageList == 0)\n      {\n      fp << \"ElementDataFile = LIST\" << std::endl;\n      std::string str;\n      for(i=0; i \";\n        std::cin >> str;\n        fp << str << std::endl;\n        str.erase();\n        }\n      fp.close();\n      std::cout << std::endl;\n      std::cout << std::endl;\n      std::cout << \"You're done!\" << std::endl;\n      std::cout << std::endl;\n      }\n    else\n      {\n      std::string storageListString;\n      float storageListStringMin;\n      float storageListStringMax;\n      float storageListStringStep;\n      std::cout << \"Filename string -=> \";\n      std::cin >> storageListString;\n      std::cout << \"  Min value to substitute into string -=> \";\n      std::cin >> storageListStringMin;\n      std::cout << \"  Max value to substitute into string -=> \";\n      std::cin >> storageListStringMax;\n      std::cout << \"  Step size to use to go from min to max -=> \";\n      std::cin >> storageListStringStep;\n      std::cout << std::endl;\n      fp << \"ElementDataFile = \" << storageListString << \" \" \n        << storageListStringMin << \" \" << storageListStringMax << \" \"\n        << storageListStringStep << std::endl;\n      fp.close();\n      std::cout << std::endl;\n      std::cout << std::endl;\n      std::cout << \"You're done!\" << std::endl;\n      std::cout << std::endl;\n      }\n    }\n\n  return 0;\n  }\nFIX:  must be the first header to be included.\/*=========================================================================\n\n  Program:   Insight Segmentation & Registration Toolkit\n  Module:    MetaImageImporter.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n  Copyright (c) 2002 Insight Consortium. All rights reserved.\n  See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n  {\n  std::cout << \"Importing your data into the MetaImage format\"\n    << std::endl\n    << \"  is merely of matter of making a text file that\"\n    << std::endl\n    << \"  contains some info about your data and that also\"\n    << std::endl\n    << \"  lists the file(s) that contain your data.\"\n    << std::endl\n    << std::endl\n    << \"This program helps you create that text file - we\"\n    << std::endl\n    << \"  designate these text files with the suffix '.mhd'\"\n    << std::endl\n    << std::endl;\n  \n  std::string filename;\n  std::cout << \"What is the name of the '.mhd' file that you\"\n    << std::endl\n    << \"  want to create?   Please include '.mhd' at the end.\" \n    << std::endl\n    << \"  -=> \";\n  std::cin >> filename;\n  std::cout << std::endl;\n  \n  std::ofstream fp;\n  fp.open(filename.c_str());\n  \n  std::cout << \"What is the dimensionality of your data (1, 2, 3, ...)?\"\n    << std::endl\n    << \"  -=> \";\n  int nDims;\n  std::cin >> nDims;\n  if(nDims < 1)\n    {\n    std::cout << \"...have a nice day\" << std::endl;\n    return 1;\n    }\n  std::cout << std::endl;\n  fp << \"NDims = \" << nDims << std::endl;\n  \n  int i;\n  int * dimSize = new int [nDims];\n  std::cout << \"Assuming dimension 0 is the 'x' dimension...\" << std::endl;\n  for(i = 0; i < nDims; i++)\n    {\n    std::cout << \"  How large is dimension \" << i << \" -=> \";\n    std::cin >> dimSize[i];\n    if(dimSize[i]<1)\n      {\n      std::cout << \"    ...we'll assume you meant 1...\" << std::endl;\n      dimSize[i] = 1;\n      }\n    }\n  std::cout << std::endl;\n  fp << \"DimSize =\";\n  for(i = 0; i < nDims; i++)\n    {\n    fp << \" \" << dimSize[i];\n    }\n  fp << std::endl;\n  \n  \n  float * pointSpacing = new float [nDims];\n  std::cout << \"Points in an image represent a measure in physical space.\"\n    << std::endl\n    << \"   Measures in physical space are done using a particular\"\n    << std::endl\n    << \"   aperature spacing - that is, what is the spacing of the\"\n    << std::endl\n    << \"   points in your data...if you don't know\/care, answer 1.\"\n    << std::endl;\n  for(i = 0; i < nDims; i++)\n    {\n    std::cout << \"  What is the point spacing in dimension \" << i << \"? -=> \";\n    std::cin >> pointSpacing[i];\n    if(pointSpacing[i]<0.0000000000000001)\n      {\n      std::cout << \"...we'll assume you meant 1...\" << std::endl;\n      pointSpacing[i] = 1;\n      }\n    }\n  std::cout << std::endl;\n  fp << \"ElementSpacing =\";\n  for(i = 0; i < nDims; i++)\n    {\n    fp << \" \" << pointSpacing[i];\n    }\n  fp << std::endl;\n  \n  float * origin = new float [nDims];\n  std::cout << \"Images are taken of a particular location in space.\"\n    << std::endl\n    << \"   That is, they have an origin in space...if you don't\"\n    << std::endl\n    << \"   know\/care, answer 0 for each dimension.\"\n    << std::endl;\n  for(i = 0; i < nDims; i++)\n    {\n    std::cout << \"  What is the origin in dimension \" << i << \"? -=> \";\n    std::cin >> origin[i];\n    }\n  std::cout << std::endl;\n  fp << \"Position =\";\n  for(i = 0; i < nDims; i++)\n    {\n    fp << \" \" << origin[i];\n    }\n  fp << std::endl;\n  \n  bool byteOrderMSB = false;\n  std::cout << \"Is your data stored using MSB byte ordering?\"\n    << std::endl\n    << \"  Data written on a 'PC' is in 'Little-endian' byte order.\"\n    << std::endl\n    << \"  Data from almost every other machine is in 'Big-endian'\"\n    << std::endl\n    << \"  byte order.  If your data was written on a 'PC', enter 0.\"\n    << std::endl\n    << \"  Otherwise, if you data was written on a Mac\/Sun\/Other, enter 1.\"\n    << std::endl\n    << \"  -=> \";\n  std::cin >> byteOrderMSB;\n  std::cout << std::endl;\n  if(byteOrderMSB)\n    {\n    fp << \"ElementByteOrderMSB = True\" << std::endl;\n    }\n  else\n    {\n    fp << \"ElementByteOrderMSB = False\" << std::endl;\n    }\n  \n  int nComps = 1;\n  std::cout << \"How many channels are stored at each point in your image?\"\n    << std::endl\n    << \"  For example, RGB images have 3 channels, and most medical\"\n    << std::endl\n    << \"  images have a single channel.\"\n    << std::endl\n    << \"  -=> \";\n  std::cin >> nComps;\n  std::cout << std::endl;\n  if(nComps<1)\n    {\n    nComps = 1;\n    }\n  if(nComps != 1)\n    {\n    fp << \"ElementNumberOfChannels = \" << nComps << std::endl;\n    }\n  \n  int elementType;\n  std::cout << \"What is the 'type' of the elements in your data :\"\n    << std::endl\n    << \"  0 - signed char (one byte)\" << std::endl\n    << \"  1 - unsigned char\" << std::endl\n    << \"  2 - signed short (two byte)\" << std::endl\n    << \"  3 - unsigned short\" << std::endl\n    << \"  4 - signed int (four byte)\" << std::endl\n    << \"  5 - unsigned int\" << std::endl\n    << \"  6 - float (four byte)\" << std::endl\n    << \"  7 - double (eight byte)\" << std::endl\n    << \"  -=> \";\n  std::cin >> elementType;\n  std::cout << std::endl;\n  switch(elementType)\n    {\n    case 0 : fp << \"ElementType = MET_CHAR\" << std::endl;\n      break;\n    case 1 : fp << \"ElementType = MET_UCHAR\" << std::endl;\n      break;\n    case 2 : fp << \"ElementType = MET_SHORT\" << std::endl;\n      break;\n    case 3 : fp << \"ElementType = MET_USHORT\" << std::endl;\n      break;\n    case 4 : fp << \"ElementType = MET_INT\" << std::endl;\n      break;\n    case 5 : fp << \"ElementType = MET_UINT\" << std::endl;\n      break;\n    case 6 : fp << \"ElementType = MET_FLOAT\" << std::endl;\n      break;\n    case 7 : fp << \"ElementType = MET_DOUBLE\" << std::endl;\n      break;\n    default: fp.close();\n      std::cout << \"...have a nice day.\" << std::endl;\n    }\n  \n  int storage = 0;\n  std::cout << \"How is the data stored ?\" << std::endl\n    << \"  0 - in one file\" << std::endl\n    << \"  1 - in one file per slice (e.g., like dicom)\" << std::endl\n    << \"  -=> \";\n  std::cin >> storage;\n  std::cout << std::endl;\n\n  int headerSize = -1;\n  std::cout << \"Size of the header that must be skipped to\"\n    << std::endl\n    << \"  reach the data in the file(s)? Enter 0 to not skip\"\n    << std::endl\n    << \"  a header, -1 to have MetaImageReader automatically\"\n    << std::endl\n    << \"  calculate the headersize assuming the data is at\"\n    << std::endl\n    << \"  the end of the file, or enter the headersize\"\n    << std::endl\n    << \"  -=> \";\n  std::cin >> headerSize;\n  std::cout << std::endl;\n  if(headerSize > 0 || headerSize == -1)\n    {\n    fp << \"HeaderSize = \" << headerSize << std::endl;\n    }\n\n  int storageList = 0;\n  if(storage == 0)\n    {\n    std::string fname;\n    std::cout << \"Name of the file containing the data -=> \";\n    std::cin >> fname;\n    fp << \"ElementDataFile = \" << fname << std::endl;\n    fp.close();\n    std::cout << std::endl;\n    std::cout << std::endl;\n    std::cout << \"You're done!\" << std::endl;\n    std::cout << std::endl;\n    }\n  else\n    {\n    std::cout << \"You've got two options when doing one file per slice:\"\n      << std::endl\n      << \"  0 - Listing the name of each slice in the .mhd file\"\n      << std::endl\n      << \"  1 - Specifying a 'fprintf' style string and min, max,\"\n      << std::endl\n      << \"        and step values for integers to be substituted\"\n      << std::endl\n      << \"        into that string to specify the numbered files\"\n      << std::endl\n      << \"        that are the slices.  For example, use data.%03d to\"\n      << std::endl\n      << \"        match data.000, data.001, data.002,...If you don't\"\n      << std::endl\n      << \"        know what we are talking about, choose option 0.\"\n      << std::endl\n      << \"  -=> \";\n    std::cin >> storageList;\n    std::cout << std::endl;\n    \n    if(storageList == 0)\n      {\n      fp << \"ElementDataFile = LIST\" << std::endl;\n      std::string str;\n      for(i=0; i \";\n        std::cin >> str;\n        fp << str << std::endl;\n        str.erase();\n        }\n      fp.close();\n      std::cout << std::endl;\n      std::cout << std::endl;\n      std::cout << \"You're done!\" << std::endl;\n      std::cout << std::endl;\n      }\n    else\n      {\n      std::string storageListString;\n      float storageListStringMin;\n      float storageListStringMax;\n      float storageListStringStep;\n      std::cout << \"Filename string -=> \";\n      std::cin >> storageListString;\n      std::cout << \"  Min value to substitute into string -=> \";\n      std::cin >> storageListStringMin;\n      std::cout << \"  Max value to substitute into string -=> \";\n      std::cin >> storageListStringMax;\n      std::cout << \"  Step size to use to go from min to max -=> \";\n      std::cin >> storageListStringStep;\n      std::cout << std::endl;\n      fp << \"ElementDataFile = \" << storageListString << \" \" \n        << storageListStringMin << \" \" << storageListStringMax << \" \"\n        << storageListStringStep << std::endl;\n      fp.close();\n      std::cout << std::endl;\n      std::cout << std::endl;\n      std::cout << \"You're done!\" << std::endl;\n      std::cout << std::endl;\n      }\n    }\n\n  return 0;\n  }\n<|endoftext|>"}
{"text":"\/*\n            This file is part of: \n                NoahFrame\n            https:\/\/github.com\/ketoo\/NoahGameFrame\n\n   Copyright 2009 - 2018 NoahFrame(NoahGameFrame)\n\n   File creator: lvsheng.huang\n   \n   NoahFrame is open-source software and you can redistribute it and\/or modify\n   it under the terms of the License; besides, anyone who use this file\/software must include this copyright announcement.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\n\n#include \"NFCActorModule.h\"\n\nNFCActorModule::NFCActorModule(NFIPluginManager* p)\n\t:mFramework(NF_ACTOR_THREAD_COUNT)\n{\n\tpPluginManager = p;\n\n    srand((unsigned)time(NULL));\n\n    m_pMainActor = NF_SHARE_PTR(NF_NEW NFCActor(mFramework, this));\n}\n\nNFCActorModule::~NFCActorModule()\n{\n\tm_pMainActor.reset();\n\tm_pMainActor = nullptr;\n}\n\nbool NFCActorModule::Init()\n{\n    return true;\n}\n\nbool NFCActorModule::AfterInit()\n{\n\n    return true;\n}\n\nbool NFCActorModule::BeforeShut()\n{\n\tmxActorMap.ClearAll();\n    return true;\n}\n\nbool NFCActorModule::Shut()\n{\n \n    return true;\n}\n\nbool NFCActorModule::Execute()\n{\n\tExecuteEvent();\n    return true;\n}\n\n\nint NFCActorModule::RequireActor()\n{\n\tNF_SHARE_PTR pActor = nullptr;\n\tif (mxActorPool.size() <= 0)\n\t{\n\t\tpActor = NF_SHARE_PTR(NF_NEW NFCActor(mFramework, this));\n\t\tmxActorMap.AddElement(pActor->GetAddress().AsInteger(), pActor);\n\n\t\treturn pActor->GetAddress().AsInteger();\n\t}\n\n\tstd::map::iterator it = mxActorPool.begin();\n\tint nActorID = it->first;\n\tmxActorPool.erase(it);\n\n    return nActorID;\n}\n\nNF_SHARE_PTR NFCActorModule::GetActor(const int nActorIndex)\n{\n\treturn mxActorMap.GetElement(nActorIndex);\n}\n\nbool NFCActorModule::HandlerEx(const NFIActorMessage & message, const int from)\n{\n\tif (message.msgType != NFIActorMessage::ACTOR_MSG_TYPE_COMPONENT)\n\t{\n\t\treturn mxQueue.Push(message);\n\t}\n\n\treturn false;\n}\n\nbool NFCActorModule::ExecuteEvent()\n{\n\tNFIActorMessage xMsg;\n\tbool bRet = false;\n\tbRet = mxQueue.TryPop(xMsg);\n\twhile (bRet)\n\t{\n\t\tif (xMsg.msgType != NFIActorMessage::ACTOR_MSG_TYPE_COMPONENT && xMsg.xEndFuncptr != nullptr)\n\t\t{\n\t\t\t\/\/Actor can be reused in ActorPool mode, so we don't release it.\n\t\t\t\/\/>ReleaseActor(xMsg.nFormActor);\n\t\t\tACTOR_PROCESS_FUNCTOR* pFun = xMsg.xEndFuncptr.get();\n\t\t\tpFun->operator()(xMsg.nFormActor, xMsg.nMsgID, xMsg.data);\n\n\n\t\t\tNF_SHARE_PTR xActor = mxActorMap.GetElement(xMsg.nFormActor);\n\t\t\tif (xActor)\n\t\t\t{\n\t\t\t\tint nActorID = xActor->GetAddress().AsInteger();\n\t\t\t\tif (mxActorPool.find(nActorID) == mxActorPool.end())\n\t\t\t\t{\n\t\t\t\t\tmxActorPool.insert(std::pair(nActorID, 0));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbRet = mxQueue.TryPop(xMsg);\n\t}\n\n\treturn true;\n}\n\nbool NFCActorModule::SendMsgToActor(const int nActorIndex, const int nEventID, const std::string& strArg)\n{\n    NF_SHARE_PTR pActor = GetActor(nActorIndex);\n    if (nullptr != pActor)\n    {\n        NFIActorMessage xMessage;\n\n\t\txMessage.msgType = NFIActorMessage::ACTOR_MSG_TYPE_COMPONENT;\n        xMessage.data = strArg;\n        xMessage.nMsgID = nEventID;\n        xMessage.nFormActor = m_pMainActor->GetAddress().AsInteger();\n\n        return mFramework.Send(xMessage, m_pMainActor->GetAddress(), pActor->GetAddress());\n    }\n\n    return false;\n}\n\nbool NFCActorModule::AddComponent(const int nActorIndex, NF_SHARE_PTR pComponent)\n{\n    NF_SHARE_PTR pActor = GetActor(nActorIndex);\n    if (nullptr != pActor)\n    {\n        pActor->AddComponent(pComponent);\n\n        return true;\n    }\n\n    return false;\n}\n\nbool NFCActorModule::ReleaseActor(const int nActorIndex)\n{\n\treturn mxActorMap.RemoveElement(nActorIndex);\n}\n\nbool NFCActorModule::AddEndFunc(const int nActorIndex, const int nSubMsgID, ACTOR_PROCESS_FUNCTOR_PTR functorPtr)\n{\n    NF_SHARE_PTR pActor = GetActor(nActorIndex);\n    if (nullptr != pActor)\n    {\n\t\treturn pActor->AddEndFunc(nSubMsgID, functorPtr);\n    }\n\n    return false;\n}Update NFCActorModule.cpp\/*\n            This file is part of: \n                NoahFrame\n            https:\/\/github.com\/ketoo\/NoahGameFrame\n\n   Copyright 2009 - 2018 NoahFrame(NoahGameFrame)\n\n   File creator: lvsheng.huang\n   \n   NoahFrame is open-source software and you can redistribute it and\/or modify\n   it under the terms of the License; besides, anyone who use this file\/software must include this copyright announcement.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\n\n#include \"NFCActorModule.h\"\n\nNFCActorModule::NFCActorModule(NFIPluginManager* p)\n\t:mFramework(NF_ACTOR_THREAD_COUNT)\n{\n\tpPluginManager = p;\n\n    srand((unsigned)time(NULL));\n\n    m_pMainActor = NF_SHARE_PTR(NF_NEW NFCActor(mFramework, this));\n}\n\nNFCActorModule::~NFCActorModule()\n{\n\tm_pMainActor.reset();\n\tm_pMainActor = nullptr;\n}\n\nbool NFCActorModule::Init()\n{\n    return true;\n}\n\nbool NFCActorModule::AfterInit()\n{\n\n    return true;\n}\n\nbool NFCActorModule::BeforeShut()\n{\n\tmxActorMap.ClearAll();\n    return true;\n}\n\nbool NFCActorModule::Shut()\n{\n \n    return true;\n}\n\nbool NFCActorModule::Execute()\n{\n\tExecuteEvent();\n    return true;\n}\n\n\nint NFCActorModule::RequireActor()\n{\n\tNF_SHARE_PTR pActor = nullptr;\n\tif (mxActorPool.size() <= 0)\n\t{\n\t\tpActor = NF_SHARE_PTR(NF_NEW NFCActor(mFramework, this));\n\t\tmxActorMap.AddElement(pActor->GetAddress().AsInteger(), pActor);\n\n\t\treturn pActor->GetAddress().AsInteger();\n\t}\n\n\tstd::map::iterator it = mxActorPool.begin();\n\tint nActorID = it->first;\n\tmxActorPool.erase(it);\n\n    return nActorID;\n}\n\nNF_SHARE_PTR NFCActorModule::GetActor(const int nActorIndex)\n{\n\treturn mxActorMap.GetElement(nActorIndex);\n}\n\nbool NFCActorModule::HandlerEx(const NFIActorMessage & message, const int from)\n{\n\tif (message.msgType != NFIActorMessage::ACTOR_MSG_TYPE_COMPONENT)\n\t{\n\t\treturn mxQueue.Push(message);\n\t}\n\n\treturn false;\n}\n\nbool NFCActorModule::ExecuteEvent()\n{\n\tNFIActorMessage xMsg;\n\tbool bRet = false;\n\tbRet = mxQueue.TryPop(xMsg);\n\twhile (bRet)\n\t{\n\t\tif (xMsg.msgType != NFIActorMessage::ACTOR_MSG_TYPE_COMPONENT && xMsg.xEndFuncptr != nullptr)\n\t\t{\n\t\t\t\/\/Actor can be reused in ActorPool mode, so we don't release it.\n\t\t\t\/\/>ReleaseActor(xMsg.nFormActor);\n\t\t\tACTOR_PROCESS_FUNCTOR* pFun = xMsg.xEndFuncptr.get();\n\t\t\tpFun->operator()(xMsg.nFormActor, xMsg.nMsgID, xMsg.data);\n\n\n\t\t\tNF_SHARE_PTR xActor = mxActorMap.GetElement(xMsg.nFormActor);\n\t\t\tif (xActor)\n\t\t\t{\n\t\t\t\tif (xActor->GetNumQueuedMessages() <= 0)\n\t\t\t\t{\n\t\t\t\t\tint nActorID = xActor->GetAddress().AsInteger();\n\t\t\t\t\tif (mxActorPool.find(nActorID) == mxActorPool.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tmxActorPool.insert(std::pair(nActorID, 0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbRet = mxQueue.TryPop(xMsg);\n\t}\n\n\treturn true;\n}\n\nbool NFCActorModule::SendMsgToActor(const int nActorIndex, const int nEventID, const std::string& strArg)\n{\n    NF_SHARE_PTR pActor = GetActor(nActorIndex);\n    if (nullptr != pActor)\n    {\n        NFIActorMessage xMessage;\n\n        xMessage.msgType = NFIActorMessage::ACTOR_MSG_TYPE_COMPONENT;\n        xMessage.data = strArg;\n        xMessage.nMsgID = nEventID;\n        xMessage.nFormActor = m_pMainActor->GetAddress().AsInteger();\n\n        return mFramework.Send(xMessage, m_pMainActor->GetAddress(), pActor->GetAddress());\n    }\n\n    return false;\n}\n\nbool NFCActorModule::AddComponent(const int nActorIndex, NF_SHARE_PTR pComponent)\n{\n    NF_SHARE_PTR pActor = GetActor(nActorIndex);\n    if (nullptr != pActor)\n    {\n        pActor->AddComponent(pComponent);\n\n        return true;\n    }\n\n    return false;\n}\n\nbool NFCActorModule::ReleaseActor(const int nActorIndex)\n{\n\treturn mxActorMap.RemoveElement(nActorIndex);\n}\n\nbool NFCActorModule::AddEndFunc(const int nActorIndex, const int nSubMsgID, ACTOR_PROCESS_FUNCTOR_PTR functorPtr)\n{\n    NF_SHARE_PTR pActor = GetActor(nActorIndex);\n    if (nullptr != pActor)\n    {\n\t\treturn pActor->AddEndFunc(nSubMsgID, functorPtr);\n    }\n\n    return false;\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"utils.cc\"\n\nusing namespace std;\nusing namespace zmqpp;\n\n#define PIECES_PATH  \".\/pieces\/list\"\n\n\nstring address, port, tracker_ip, tracker_port;\n\n\nvoid wake_up(socket &tracker) {\n  set pieces;\n  ifstream i_file(PIECES_PATH);\n  string line;\n  while (getline(i_file, line)) {\n    pieces.insert(line);\n  }\n\n  remove(PIECES_PATH);\n\n  ofstream o_file(PIECES_PATH);\n\n  message request;\n  request << ADD << address << port << pieces.size();\n  for (string piece : pieces) {\n    o_file << piece << endl;\n    request << piece;\n  }\n\n  tracker.send(request);\n\n  i_file.close();\n  o_file.close();\n}\n\nbool  share_file(socket &tracker, string &filename) {\n  filename = \".\/files\/\" + filename;\n  if (!file_exists(filename))\n    return false;\n\n  string command = \".\/totient_generator.sh \" + filename + \" \" + tracker_ip + \" \" + tracker_port;\n  cerr << string_color(command, BLUE) << endl;\n  system(command.c_str());\n\n\n  totient::entry totient_file(filename + \".totient\");\n\n  message request;\n\n  request << ADD << address << port << totient_file.pieces.size();\n\n  for (size_t i = 0; i < totient_file.pieces.size(); ++i)\n    request << totient_file.pieces[i];\n\n  tracker.send(request);\n\n  return true;\n}\n\nbool download_file(socket &tracker, unordered_map &downloads, string &filename,\n      socket &download_t) {\n  filename = \".\/totient\/\" + filename + \".totient\";\n  if (!file_exists(filename))\n    return false;\n\n  if (downloads.count(filename) == 0) {\n    totient::entry entry(filename);\n    downloads[filename] = entry;\n  }\n\n  message request;\n  request << \"push\";\n\n  download_t.send(request);\n\n  return true;\n}\n\nvoid play_song(const string &filename) {\n\n}\n\nvoid download_thread(void * _ctx) {\n  context *ctx= (context *)_ctx;\n  socket cli(*(ctx), socket_type::dealer);\n  cli.connect(\"inproc:\/\/download\");\n\n  while (true) {\n    message request;\n    cli.receive(request);\n    string command;\n    request >> command;\n    if (command == \"quit\")\n      break;\n\n    else {\n      cout << string_color(\"@@@ Received request in download thread\", GREEN) << endl;\n    }\n  }\n}\n\nvoid play_thread(void *_ctx){\n  sf::Music music;\n  vector playlist;\n  \n  context *ctx = (context*)_ctx;\n  socket main(*(ctx), socket_type::dealer);\n  main.connect(\"inproc:\/\/playlist\");\n  unsigned int pos = 0;\n  \n  poller pol;\n  pol.add(main);\n  \/\/it = playlist.begin();\n  while(true){\n    \/\/cout << \"here\" << endl;\n    if (playlist.size() > 0 and pos < playlist.size()){\n      string name = playlist[pos];\n      \/\/cout << name << endl << pos << endl << playlist.size() << endl;\n      if (music.getStatus() == 0 and music.openFromFile(\"files\/\" + name)){\n        music.play();\n        pos++;\n      }\n    }\n  \n    if(pol.poll(10)){\n      if(pol.has_input(main)){\n        message incmsg;\n        main.receive(incmsg);\n        string command;\n        incmsg >> command;\n        if (command == \"add\"){\n          string filename;\n          incmsg >> filename;\n          playlist.push_back(filename);\n        } else if (command == \"next\"){\n          music.stop();\n        }        \n      }\n    }\n  } \n}\n\nint main(int argc, char **argv) {\n\n  if (argc < 5) {\n    cout << \"Usage: \" << argv[0] << \"address port tracker_ip tracker_port\";\n    exit(1);\n  }\n\n  address = argv[1];\n  port    = argv[2];\n  tracker_ip = argv[3];\n  tracker_port = argv[4];\n  const string tracker_endpoint = string(\"tcp:\/\/\") + tracker_ip + \":\" + tracker_port;\n\n  context ctx;\n  socket tracker(ctx, socket_type::dealer);\n  tracker.connect(tracker_endpoint);\n\n  wake_up(tracker);\n\n\n  \/\/ Peer state\n  unordered_map downloads;\n  \/\/ End peer state\n\n  socket download_t(ctx, socket_type::dealer);\n  download_t.bind(\"inproc:\/\/download\");\n  socket playlist_t(ctx, socket_type::dealer);\n  playlist_t.bind(\"inproc:\/\/playlist\");\n\n  thread download_task(download_thread, (void *) &ctx);\n  thread playlist_task(play_thread, (void *) &ctx);\n\n  while (true) {\n    string command;\n\n    cout << \"Totient P2P file sharing.\" << endl;\n    cin >> command;\n\n    if ((command == \"q\") or (command == \"quit\"))\n      break;\n\n    string filename;\n    if (command == \"share\") {\n      cout << \"Enter the name of the file that you want to share (must be in the files dir)\" << endl;\n      cin >> filename;\n      if (share_file(tracker, filename))\n        cout << string_color(\"The file was successfully shared\", GREEN) << endl;\n      else\n        cout << string_color(\"The file does not exist\", RED) << endl;\n    } else if (command == \"download\") {\n      cout << \"Enter the name of the file that you want to download (must be in the totient dir)\" << endl;\n      cin >> filename;\n      if (download_file(tracker, downloads, filename, download_t))\n        cout << string_color(\"Download in process\", GREEN) << endl;\n      else\n        cout << string_color(\"The file does not exist\", RED) << endl;\n    } else if (command == \"add\") {\n      cout << \"Enter the name of the file that you want to hear (must be in the files dir)\" << endl;\n      cin >> filename;\n      message p_command;\n      p_command << command << filename;\n      playlist_t.send(p_command);\n    } else if (command == \"next\"){\n      message p_command;\n      p_command << command;\n      playlist_t.send(p_command);\n    }\n  }\n\n  getchar();\n  cout << \"Bye bye\" << endl;\n\n  return 0;\n}\nFull playback functionality#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"utils.cc\"\n\nusing namespace std;\nusing namespace zmqpp;\n\n#define PIECES_PATH  \".\/pieces\/list\"\n\n\nstring address, port, tracker_ip, tracker_port;\n\n\nvoid wake_up(socket &tracker) {\n  set pieces;\n  ifstream i_file(PIECES_PATH);\n  string line;\n  while (getline(i_file, line)) {\n    pieces.insert(line);\n  }\n\n  remove(PIECES_PATH);\n\n  ofstream o_file(PIECES_PATH);\n\n  message request;\n  request << ADD << address << port << pieces.size();\n  for (string piece : pieces) {\n    o_file << piece << endl;\n    request << piece;\n  }\n\n  tracker.send(request);\n\n  i_file.close();\n  o_file.close();\n}\n\nbool  share_file(socket &tracker, string &filename) {\n  filename = \".\/files\/\" + filename;\n  if (!file_exists(filename))\n    return false;\n\n  string command = \".\/totient_generator.sh \" + filename + \" \" + tracker_ip + \" \" + tracker_port;\n  cerr << string_color(command, BLUE) << endl;\n  system(command.c_str());\n\n\n  totient::entry totient_file(filename + \".totient\");\n\n  message request;\n\n  request << ADD << address << port << totient_file.pieces.size();\n\n  for (size_t i = 0; i < totient_file.pieces.size(); ++i)\n    request << totient_file.pieces[i];\n\n  tracker.send(request);\n\n  return true;\n}\n\nbool download_file(socket &tracker, unordered_map &downloads, string &filename,\n      socket &download_t) {\n  filename = \".\/totient\/\" + filename + \".totient\";\n  if (!file_exists(filename))\n    return false;\n\n  if (downloads.count(filename) == 0) {\n    totient::entry entry(filename);\n    downloads[filename] = entry;\n  }\n\n  message request;\n  request << \"push\";\n\n  download_t.send(request);\n\n  return true;\n}\n\nvoid play_song(const string &filename) {\n\n}\n\nvoid download_thread(void * _ctx) {\n  context *ctx= (context *)_ctx;\n  socket cli(*(ctx), socket_type::dealer);\n  cli.connect(\"inproc:\/\/download\");\n\n  while (true) {\n    message request;\n    cli.receive(request);\n    string command;\n    request >> command;\n    if (command == \"quit\")\n      break;\n\n    else {\n      cout << string_color(\"@@@ Received request in download thread\", GREEN) << endl;\n    }\n  }\n}\n\nvoid play_thread(void *_ctx){\n  sf::Music music;\n  vector playlist;\n  bool playflag = true;\n  \n  context *ctx = (context*)_ctx;\n  socket main(*(ctx), socket_type::dealer);\n  main.connect(\"inproc:\/\/playlist\");\n  int pos = 0;\n  \n  poller pol;\n  pol.add(main);\n  \/\/it = playlist.begin();\n  while(true){\n    \/\/cout << \"here\" << endl;\n    \/\/cout << pos << endl;\n    if (playlist.size() > 0 and pos < playlist.size()){\n      string name = playlist[pos];\n      \/\/cout << pos << endl;\n      \/\/cout << name << endl << pos << endl << playlist.size() << endl;\n      if (music.getStatus() == 0 and music.openFromFile(\"files\/\" + name) and playflag){\n        music.play();\n        pos++;\n      }\n    }\n  \n    if(pol.poll(100)){\n      if(pol.has_input(main)){\n        message incmsg;\n        main.receive(incmsg);\n        string command;\n        incmsg >> command;\n        if (command == \"add\"){\n          string filename;\n          incmsg >> filename;\n          playlist.push_back(filename);\n        } else if (command == \"next\"){\n          music.stop();\n        } else if (command == \"prev\"){\n          pos = pos - 2;\n          if (pos < 0)\n            pos = 0;\n          music.stop();\n          \/\/cout << pos << endl;\n        } else if (command == \"stop\" and playflag){\n          playflag = false;\n          pos--;\n          if (pos < 0)\n            pos = 0;\n          music.stop();         \n        } else if(command == \"play\" and not playflag){\n          playflag = \"true\";\n        } else if(command == \"del\" and playlist.size() > 0){\n          pos--;\n          if (pos < 0)\n            pos = 0;\n          playlist.erase(playlist.begin() + pos);\n          music.stop();\n        }\n      }\n    }\n  } \n}\n\nint main(int argc, char **argv) {\n\n  if (argc < 5) {\n    cout << \"Usage: \" << argv[0] << \"address port tracker_ip tracker_port\";\n    exit(1);\n  }\n\n  address = argv[1];\n  port    = argv[2];\n  tracker_ip = argv[3];\n  tracker_port = argv[4];\n  const string tracker_endpoint = string(\"tcp:\/\/\") + tracker_ip + \":\" + tracker_port;\n\n  context ctx;\n  socket tracker(ctx, socket_type::dealer);\n  tracker.connect(tracker_endpoint);\n\n  wake_up(tracker);\n\n\n  \/\/ Peer state\n  unordered_map downloads;\n  \/\/ End peer state\n\n  socket download_t(ctx, socket_type::dealer);\n  download_t.bind(\"inproc:\/\/download\");\n  socket playlist_t(ctx, socket_type::dealer);\n  playlist_t.bind(\"inproc:\/\/playlist\");\n\n  thread download_task(download_thread, (void *) &ctx);\n  thread playlist_task(play_thread, (void *) &ctx);\n\n  while (true) {\n    string command;\n\n    cout << \"Totient P2P file sharing.\" << endl;\n    cin >> command;\n\n    if ((command == \"q\") or (command == \"quit\"))\n      break;\n\n    string filename;\n    if (command == \"share\") {\n      cout << \"Enter the name of the file that you want to share (must be in the files dir)\" << endl;\n      cin >> filename;\n      if (share_file(tracker, filename))\n        cout << string_color(\"The file was successfully shared\", GREEN) << endl;\n      else\n        cout << string_color(\"The file does not exist\", RED) << endl;\n    } else if (command == \"download\") {\n      cout << \"Enter the name of the file that you want to download (must be in the totient dir)\" << endl;\n      cin >> filename;\n      if (download_file(tracker, downloads, filename, download_t))\n        cout << string_color(\"Download in process\", GREEN) << endl;\n      else\n        cout << string_color(\"The file does not exist\", RED) << endl;\n    } else if (command == \"add\") {\n      cout << \"Enter the name of the file that you want to hear (must be in the files dir)\" << endl;\n      cin >> filename;\n      message p_command;\n      p_command << command << filename;\n      playlist_t.send(p_command);\n    } else if (command == \"next\" or command == \"prev\" or command == \"stop\" or command == \"play\" or \"del\"){\n      message p_command;\n      p_command << command;\n      playlist_t.send(p_command);\n    }\n  }\n\n  download_task.detach();\n  playlist_task.detach();\n  download_task.~thread();\n  playlist_task.~thread();\n  cout << \"Bye bye\" << endl;\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"\/*\n    Copyright (C) 2014-2016 Leosac\n\n    This file is part of Leosac.\n\n    Leosac is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    Leosac is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program. If not, see .\n*\/\n\n#include \"SysFSGPIOPin.hpp\"\n#include \"tools\/unixfs.hpp\"\n#include \n#include \n#include \n\nusing namespace Leosac::Module::SysFsGpio;\nusing Leosac::Tools::UnixFs;\n\nSysFsGpioPin::SysFsGpioPin(zmqpp::context &ctx, const std::string &name, int gpio_no,\n                           Direction direction, InterruptMode interrupt_mode,\n                           bool initial_value, SysFsGpioModule &module)\n    : gpio_no_(gpio_no)\n    , sock_(ctx, zmqpp::socket_type::rep)\n    , name_(name)\n    , direction_(direction)\n    , initial_value_(initial_value)\n    , module_(module)\n    , path_cfg_(module.general_config())\n    , next_update_time_(std::chrono::system_clock::time_point::max())\n{\n    sock_.bind(\"inproc:\/\/\" + name);\n\n    set_direction(direction);\n    set_interrupt(interrupt_mode);\n    std::string full_path = path_cfg_.value_path(gpio_no);\n\n    if (direction == Direction::Out)\n    {\n        if (initial_value_)\n            turn_on();\n        else\n            turn_off();\n    }\n\n    file_fd_ = open(full_path.c_str(), O_RDONLY | O_NONBLOCK);\n    assert(file_fd_ != -1);\n}\n\nSysFsGpioPin::~SysFsGpioPin()\n{\n    if (direction_ == Direction::Out)\n    {\n        if (initial_value_)\n            turn_on();\n        else\n            turn_off();\n    }\n\n    if (file_fd_ != -1 && ::close(file_fd_) != 0)\n    {\n        ERROR(\"fail to close fd \" << file_fd_);\n    }\n    try\n    {\n        UnixFs::writeSysFsValue(module_.general_config().unexport_path(), gpio_no_);\n    }\n    catch (FsException &e)\n    {\n        ERROR(\"Error while unexporting GPIO: \" << e.what());\n    }\n}\n\nvoid SysFsGpioPin::set_direction(Direction dir)\n{\n    std::string direction = dir == Direction::In ? \"in\" : \"out\";\n    UnixFs::writeSysFsValue(path_cfg_.direction_path(gpio_no_), direction);\n}\n\nvoid SysFsGpioPin::set_interrupt(InterruptMode mode)\n{\n    std::string value;\n    if (mode == SysFsGpioPin::InterruptMode::None)\n        value = \"none\";\n    else if (mode == SysFsGpioPin::InterruptMode::Both)\n        value = \"both\";\n    else if (mode == SysFsGpioPin::InterruptMode::Falling)\n        value = \"falling\";\n    else if (mode == SysFsGpioPin::InterruptMode::Rising)\n        value = \"rising\";\n    else\n        assert(0);\n    UnixFs::writeSysFsValue(path_cfg_.edge_path(gpio_no_), value);\n}\n\nvoid SysFsGpioPin::handle_message()\n{\n    zmqpp::message_t msg;\n    std::string frame1;\n    sock_.receive(msg);\n\n    msg >> frame1;\n    bool ok = false;\n    if (frame1 == \"ON\")\n        ok = turn_on(&msg);\n    else if (frame1 == \"OFF\")\n        ok = turn_off();\n    else if (frame1 == \"TOGGLE\")\n        ok = toggle();\n    sock_.send(ok ? \"OK\" : \"KO\");\n\n    \/\/ publish new state.\n    module_.publish_on_bus(zmqpp::message() << (\"S_\" + name_)\n                                            << (read_value() ? \"ON\" : \"OFF\"));\n}\n\nbool SysFsGpioPin::turn_on(zmqpp::message *msg \/* = nullptr *\/)\n{\n    DEBUG(\"Remaining = \" << msg->remaining());\n    if (msg && msg->remaining() == 1)\n    {\n        \/\/ ASSERT_LOG(msg->parts() == 2 && msg->remaining() == 1, \"Invalid internal\n        \/\/ message.\");\n        \/\/ optional parameter is present\n        int64_t duration;\n        *msg >> duration;\n        next_update_time_ =\n            std::chrono::system_clock::now() + std::chrono::milliseconds(duration);\n    }\n    UnixFs::writeSysFsValue(path_cfg_.value_path(gpio_no_), 1);\n    return true;\n}\n\nbool SysFsGpioPin::turn_off()\n{\n    UnixFs::writeSysFsValue(path_cfg_.value_path(gpio_no_), 0);\n    return true;\n}\n\nbool SysFsGpioPin::toggle()\n{\n    int v = UnixFs::readSysFsValue(path_cfg_.value_path(gpio_no_));\n    UnixFs::writeSysFsValue(path_cfg_.value_path(gpio_no_), v == 1 ? 0 : 1);\n    return true;\n}\n\nbool SysFsGpioPin::read_value()\n{\n    return UnixFs::readSysFsValue(path_cfg_.value_path(gpio_no_));\n}\n\nvoid SysFsGpioPin::handle_interrupt()\n{\n    std::array buffer;\n    ssize_t ret;\n\n    \/\/ flush interrupt by reading.\n    \/\/ if we fail we cant recover, this means hardware failure.\n    ret = ::read(file_fd_, &buffer[0], buffer.size());\n    ASSERT_LOG(ret >= 0, \"Read failed on GPIO pin.\");\n    ret = ::lseek(file_fd_, 0, SEEK_SET);\n    ASSERT_LOG(ret >= 0, \"Lseek failed on GPIO pin.\");\n\n    module_.publish_on_bus(zmqpp::message() << \"S_INT:\" + name_);\n}\n\nvoid SysFsGpioPin::register_sockets(zmqpp::reactor *reactor)\n{\n    reactor->add(sock_, std::bind(&SysFsGpioPin::handle_message, this));\n    if (direction_ == Direction::In)\n        reactor->add(file_fd_, std::bind(&SysFsGpioPin::handle_interrupt, this),\n                     zmqpp::poller::poll_pri);\n}\n\nstd::chrono::system_clock::time_point SysFsGpioPin::next_update() const\n{\n    return next_update_time_;\n}\n\nvoid SysFsGpioPin::update()\n{\n    DEBUG(\"Turning off SysFsGPIO pin.\");\n    turn_off();\n    next_update_time_ = std::chrono::system_clock::time_point::max();\n}\n[SYSFSGPIO] Fix segfault.\/*\n    Copyright (C) 2014-2016 Leosac\n\n    This file is part of Leosac.\n\n    Leosac is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    Leosac is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program. If not, see .\n*\/\n\n#include \"SysFSGPIOPin.hpp\"\n#include \"tools\/unixfs.hpp\"\n#include \n#include \n#include \n\nusing namespace Leosac::Module::SysFsGpio;\nusing Leosac::Tools::UnixFs;\n\nSysFsGpioPin::SysFsGpioPin(zmqpp::context &ctx, const std::string &name, int gpio_no,\n                           Direction direction, InterruptMode interrupt_mode,\n                           bool initial_value, SysFsGpioModule &module)\n    : gpio_no_(gpio_no)\n    , sock_(ctx, zmqpp::socket_type::rep)\n    , name_(name)\n    , direction_(direction)\n    , initial_value_(initial_value)\n    , module_(module)\n    , path_cfg_(module.general_config())\n    , next_update_time_(std::chrono::system_clock::time_point::max())\n{\n    sock_.bind(\"inproc:\/\/\" + name);\n\n    set_direction(direction);\n    set_interrupt(interrupt_mode);\n    std::string full_path = path_cfg_.value_path(gpio_no);\n\n    if (direction == Direction::Out)\n    {\n        if (initial_value_)\n            turn_on();\n        else\n            turn_off();\n    }\n\n    file_fd_ = open(full_path.c_str(), O_RDONLY | O_NONBLOCK);\n    assert(file_fd_ != -1);\n}\n\nSysFsGpioPin::~SysFsGpioPin()\n{\n    if (direction_ == Direction::Out)\n    {\n        if (initial_value_)\n            turn_on();\n        else\n            turn_off();\n    }\n\n    if (file_fd_ != -1 && ::close(file_fd_) != 0)\n    {\n        ERROR(\"fail to close fd \" << file_fd_);\n    }\n    try\n    {\n        UnixFs::writeSysFsValue(module_.general_config().unexport_path(), gpio_no_);\n    }\n    catch (FsException &e)\n    {\n        ERROR(\"Error while unexporting GPIO: \" << e.what());\n    }\n}\n\nvoid SysFsGpioPin::set_direction(Direction dir)\n{\n    std::string direction = dir == Direction::In ? \"in\" : \"out\";\n    UnixFs::writeSysFsValue(path_cfg_.direction_path(gpio_no_), direction);\n}\n\nvoid SysFsGpioPin::set_interrupt(InterruptMode mode)\n{\n    std::string value;\n    if (mode == SysFsGpioPin::InterruptMode::None)\n        value = \"none\";\n    else if (mode == SysFsGpioPin::InterruptMode::Both)\n        value = \"both\";\n    else if (mode == SysFsGpioPin::InterruptMode::Falling)\n        value = \"falling\";\n    else if (mode == SysFsGpioPin::InterruptMode::Rising)\n        value = \"rising\";\n    else\n        assert(0);\n    UnixFs::writeSysFsValue(path_cfg_.edge_path(gpio_no_), value);\n}\n\nvoid SysFsGpioPin::handle_message()\n{\n    zmqpp::message_t msg;\n    std::string frame1;\n    sock_.receive(msg);\n\n    msg >> frame1;\n    bool ok = false;\n    if (frame1 == \"ON\")\n        ok = turn_on(&msg);\n    else if (frame1 == \"OFF\")\n        ok = turn_off();\n    else if (frame1 == \"TOGGLE\")\n        ok = toggle();\n    sock_.send(ok ? \"OK\" : \"KO\");\n\n    \/\/ publish new state.\n    module_.publish_on_bus(zmqpp::message() << (\"S_\" + name_)\n                                            << (read_value() ? \"ON\" : \"OFF\"));\n}\n\nbool SysFsGpioPin::turn_on(zmqpp::message *msg \/* = nullptr *\/)\n{\n    if (msg && msg->remaining() == 1)\n    {\n        \/\/ ASSERT_LOG(msg->parts() == 2 && msg->remaining() == 1, \"Invalid internal\n        \/\/ message.\");\n        \/\/ optional parameter is present\n        int64_t duration;\n        *msg >> duration;\n        next_update_time_ =\n            std::chrono::system_clock::now() + std::chrono::milliseconds(duration);\n    }\n    else if (msg)\n    {\n        WARN(\"Called with unexpected number of arguments: \" << msg->remaining());\n    }\n\n    UnixFs::writeSysFsValue(path_cfg_.value_path(gpio_no_), 1);\n    return true;\n}\n\nbool SysFsGpioPin::turn_off()\n{\n    UnixFs::writeSysFsValue(path_cfg_.value_path(gpio_no_), 0);\n    return true;\n}\n\nbool SysFsGpioPin::toggle()\n{\n    int v = UnixFs::readSysFsValue(path_cfg_.value_path(gpio_no_));\n    UnixFs::writeSysFsValue(path_cfg_.value_path(gpio_no_), v == 1 ? 0 : 1);\n    return true;\n}\n\nbool SysFsGpioPin::read_value()\n{\n    return UnixFs::readSysFsValue(path_cfg_.value_path(gpio_no_));\n}\n\nvoid SysFsGpioPin::handle_interrupt()\n{\n    std::array buffer;\n    ssize_t ret;\n\n    \/\/ flush interrupt by reading.\n    \/\/ if we fail we cant recover, this means hardware failure.\n    ret = ::read(file_fd_, &buffer[0], buffer.size());\n    ASSERT_LOG(ret >= 0, \"Read failed on GPIO pin.\");\n    ret = ::lseek(file_fd_, 0, SEEK_SET);\n    ASSERT_LOG(ret >= 0, \"Lseek failed on GPIO pin.\");\n\n    module_.publish_on_bus(zmqpp::message() << \"S_INT:\" + name_);\n}\n\nvoid SysFsGpioPin::register_sockets(zmqpp::reactor *reactor)\n{\n    reactor->add(sock_, std::bind(&SysFsGpioPin::handle_message, this));\n    if (direction_ == Direction::In)\n        reactor->add(file_fd_, std::bind(&SysFsGpioPin::handle_interrupt, this),\n                     zmqpp::poller::poll_pri);\n}\n\nstd::chrono::system_clock::time_point SysFsGpioPin::next_update() const\n{\n    return next_update_time_;\n}\n\nvoid SysFsGpioPin::update()\n{\n    DEBUG(\"Turning off SysFsGPIO pin.\");\n    turn_off();\n    next_update_time_ = std::chrono::system_clock::time_point::max();\n}\n<|endoftext|>"}
{"text":"\/\/\/\n\/\/\/ @file  phi.cpp\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \"pi_bsearch.h\"\n#include \"isqrt.h\"\n\n#include \n#include \n#include \n#include \n\n#ifdef _OPENMP\n  #include \n  #include \"to_omp_threads.h\"\n#endif\n\n\/\/\/ Results of phi(x, a) are cached for x < PHI_CACHE_LIMIT\n\/\/\/ @pre PHI_CACHE_LIMIT <= 32767\n\/\/\/\n#define PHI_CACHE_LIMIT 32767\n\n\/\/\/ Avoids slow 64-bit division if possible\n#define FAST_DIV(x, y) ((x <= std::numeric_limits::max()) \\\n    ? static_cast(x) \/ (y) : (x) \/ (y))\n\n\nnamespace primecount {\n\n\/\/\/ This class is used to calculate phi(x, a) using the recursive\n\/\/\/ formula: phi(x, a) = phi(x, a - 1) - phi(x \/ primes_[a], a - 1).\n\/\/\/ This implementation is based on an algorithm from Tomas Oliveira e\n\/\/\/ Silva [1]. I have added a cache to my implementation in which\n\/\/\/ results of phi(x, a) are stored if x is small. This cache speeds\n\/\/\/ up the calculations by at least 3 orders of magnitude near 10^15.\n\/\/\/ For PHI_CACHE_LIMIT = 32767 the memory usage of the cache is < 200\n\/\/\/ megabytes per thread.\n\/\/\/\n\/\/\/ [1] Tomas Oliveira e Silva, \"Computing pi(x): the combinatorial method\",\n\/\/\/     Revista do DETUA, vol. 4, no. 6, pp. 759-768, March 2006\n\/\/\/\nclass PhiCache {\npublic:\n  PhiCache(const std::vector& primes)\n    : primes_(primes)\n  {\n    PrimeSieve ps;\n    int size = ps.countPrimes(0, PHI_CACHE_LIMIT);\n    cache_.resize(size);\n  }\n\n  template int64_t phi(int64_t x, int64_t a)\n  {\n    int64_t sum = x * SIGN;\n    if (a > 0)\n    {\n      int64_t iters = pi_bsearch(primes_.begin(), primes_.begin() + a, isqrt(x));\n      sum += (a - iters) * -SIGN;\n\n      for (int64_t a2 = 0; a2 < iters; a2++)\n      {\n        \/\/ x2 = x \/ primes_[a2]\n        int64_t x2 = FAST_DIV(x, primes_[a2]);\n\n        if (x2 < PHI_CACHE_LIMIT && validIndexes(a2, x2) && \n            cache_[a2][x2] != 0)\n        {\n          \/\/ phi(x2, a2) is cached\n          sum += cache_[a2][x2] * -SIGN;\n        }\n        else\n        {\n          \/\/ phi(x2, a2) is not cached, calculate recursively\n          int64_t phiResult = phi<-SIGN>(x2, a2);\n          \/\/ cache phi(x2, a2)\n          if (x2 < PHI_CACHE_LIMIT)\n          {\n            if (!validIndexes(a2, x2))\n              cache_[a2].resize(x2 + 1, 0);\n            cache_[a2][x2] = static_cast(phiResult * -SIGN);\n          }\n          sum += phiResult;\n        }\n      }\n    }\n    return sum;\n  }\nprivate:\n  \/\/\/ First a primes needed to calculate phi(x, a)\n  const std::vector& primes_;\n  \/\/\/ Cache of phi(x, a) results with x < PHI_CACHE_LIMIT\n  std::vector > cache_;\n\n  bool validIndexes(int64_t a2, int64_t x2) const\n  {\n    return x2 < static_cast(cache_[a2].size());\n  }\n};\n\n\/\/\/ Partial sieve function (a.k.a. Legendre-sum).\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible\n\/\/\/ by any of the first a primes.\n\/\/\/\nint64_t phi(int64_t x, int64_t a, int threads)\n{\n  if (x < 1) return 0;\n  if (a < 1) return x;\n\n  std::vector primes;\n  PrimeSieve ps;\n  ps.generate_N_Primes(a, &primes);\n\n  int iters = pi_bsearch(primes.begin(), primes.begin() + a, isqrt(x));\n  PhiCache cache(primes);\n  int64_t sum = x - a + iters;\n\n#ifdef _OPENMP\n  threads = to_omp_threads(threads);\n  #pragma omp parallel for firstprivate(cache) reduction(+: sum) \\\n      num_threads(threads) schedule(dynamic, 16)\n#endif\n  for (int i = 0; i < iters; i++)\n    sum += cache.phi<-1>(x \/ primes[i], i);\n\n  return sum;\n}\n\n} \/\/ namespace primecount\nMinor speed up on Haswell CPUs\/\/\/\n\/\/\/ @file  phi.cpp\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \"pi_bsearch.h\"\n#include \"isqrt.h\"\n\n#include \n#include \n#include \n#include \n\n#ifdef _OPENMP\n  #include \n  #include \"to_omp_threads.h\"\n#endif\n\n\/\/\/ Results of phi(x, a) are cached for x < PHI_CACHE_LIMIT\n\/\/\/ @pre PHI_CACHE_LIMIT <= 32767\n\/\/\/\n#define PHI_CACHE_LIMIT 32767\n\n\/\/\/ Avoids slow 64-bit division if possible\n#define FAST_DIV(x, y) ((x <= std::numeric_limits::max()) \\\n    ? static_cast(x) \/ (y) : (x) \/ (y))\n\n\nnamespace primecount {\n\n\/\/\/ This class is used to calculate phi(x, a) using the recursive\n\/\/\/ formula: phi(x, a) = phi(x, a - 1) - phi(x \/ primes_[a], a - 1).\n\/\/\/ This implementation is based on an algorithm from Tomas Oliveira e\n\/\/\/ Silva [1]. I have added a cache to my implementation in which\n\/\/\/ results of phi(x, a) are stored if x is small. This cache speeds\n\/\/\/ up the calculations by at least 3 orders of magnitude near 10^15.\n\/\/\/ For PHI_CACHE_LIMIT = 32767 the memory usage of the cache is < 200\n\/\/\/ megabytes per thread.\n\/\/\/\n\/\/\/ [1] Tomas Oliveira e Silva, \"Computing pi(x): the combinatorial method\",\n\/\/\/     Revista do DETUA, vol. 4, no. 6, pp. 759-768, March 2006\n\/\/\/\nclass PhiCache {\npublic:\n  PhiCache(const std::vector& primes)\n    : primes_(primes)\n  {\n    PrimeSieve ps;\n    int size = ps.countPrimes(0, PHI_CACHE_LIMIT);\n    cache_.resize(size);\n  }\n\n  template int64_t phi(int64_t x, int64_t a)\n  {\n    int64_t sum = x * SIGN;\n    if (a > 0)\n    {\n      int64_t iters = pi_bsearch(primes_.begin(), primes_.begin() + a, isqrt(x));\n      sum += (a - iters) * -SIGN;\n\n      for (int64_t a2 = 0; a2 < iters; a2++)\n      {\n        \/\/ x2 = x \/ primes_[a2]\n        int64_t x2 = FAST_DIV(x, primes_[a2]);\n\n        if (x2 < PHI_CACHE_LIMIT && validIndexes(a2, x2) && \n            cache_[a2][x2] != 0)\n        {\n          \/\/ phi(x2, a2) is cached\n          sum += cache_[a2][x2] * -SIGN;\n        }\n        else\n        {\n          \/\/ phi(x2, a2) is not cached, calculate recursively\n          int64_t phiResult = phi<-SIGN>(x2, a2);\n          \/\/ cache phi(x2, a2)\n          if (x2 < PHI_CACHE_LIMIT)\n          {\n            if (!validIndexes(a2, x2))\n              cache_[a2].resize(x2 + 1, 0);\n            cache_[a2][x2] = static_cast(phiResult * -SIGN);\n          }\n          sum += phiResult;\n        }\n      }\n    }\n    return sum;\n  }\nprivate:\n  \/\/\/ First a primes needed to calculate phi(x, a)\n  const std::vector& primes_;\n  \/\/\/ Cache of phi(x, a) results with x < PHI_CACHE_LIMIT\n  std::vector > cache_;\n\n  bool validIndexes(int64_t a2, int64_t x2) const\n  {\n    return x2 < static_cast(cache_[a2].size());\n  }\n};\n\n\/\/\/ Partial sieve function (a.k.a. Legendre-sum).\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible\n\/\/\/ by any of the first a primes.\n\/\/\/\nint64_t phi(int64_t x, int64_t a, int threads)\n{\n  if (x < 1) return 0;\n  if (a < 1) return x;\n\n  std::vector primes;\n  PrimeSieve ps;\n  ps.generate_N_Primes(a, &primes);\n\n  int iters = pi_bsearch(primes.begin(), primes.begin() + a, isqrt(x));\n  PhiCache cache(primes);\n  int64_t sum = x - a + iters;\n\n#ifdef _OPENMP\n  threads = to_omp_threads(threads);\n  #pragma omp parallel for firstprivate(cache) reduction(+: sum) \\\n      num_threads(threads) schedule(dynamic)\n#endif\n  for (int i = 0; i < iters; i++)\n    sum += cache.phi<-1>(x \/ primes[i], i);\n\n  return sum;\n}\n\n} \/\/ namespace primecount\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Copyright (c) 2015 CNRS\n\/\/ Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n\/\/\n\/\/ This file is part of Pinocchio\n\/\/ Pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ Pinocchio If not, see\n\/\/ .\n\n#include \"pinocchio\/multibody\/parser\/sample-models.hpp\"\n\nnamespace se3\n{\n  namespace buildModels\n  {\n\n    void humanoid2d(Model& model)\n    {\n      model.addBody(model.getBodyId(\"universe\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\n                    \"ff1_joint\", \"ff1_body\");\n      model.addBody(model.getBodyId(\"ff1_body\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\n                    \"root_joint\", \"root_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"lleg1_joint\", \"lleg1_body\");\n      model.addBody(model.getBodyId(\"lleg1_body\"),JointModelRY(),SE3::Random(),Inertia::Random(),\n                    \"lleg2_joint\", \"lleg2_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"rleg1_joint\", \"rleg1_body\");\n      model.addBody(model.getBodyId(\"rleg1_body\"),JointModelRY(),SE3::Random(),Inertia::Random(),\n                    \"rleg2_joint\", \"rleg2_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRY(),SE3::Random(),Inertia::Random(),\n                    \"torso1_joint\", \"torso1_body\");\n      model.addBody(model.getBodyId(\"torso1_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"chest_joint\", \"chest_body\");\n\n      model.addBody(model.getBodyId(\"chest_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rarm1_joint\", \"rarm1_body\");\n      model.addBody(model.getBodyId(\"rarm1_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"rarm2_joint\", \"rarm2_body\");\n\n      model.addBody(model.getBodyId(\"chest_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"larm1_joint\", \"larm1_body\");\n      model.addBody(model.getBodyId(\"larm1_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"larm2_joint\", \"larm2_body\");\n    }\n\n    void humanoidSimple(Model& model, bool usingFF)\n    {\n      if(! usingFF )\n      {\n        model.addBody(model.getBodyId(\"universe\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\n                      \"ff1_joint\", \"ff1_body\");\n        model.addBody(model.getBodyId(\"ff1_body\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\n                      \"ff2_joint\", \"ff2_body\");\n        model.addBody(model.getBodyId(\"ff2_body\"),JointModelRZ(),SE3::Identity(),Inertia::Random(),\n                      \"ff3_joint\", \"ff3_body\");\n        model.addBody(model.getBodyId(\"ff3_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                      \"ff4_joint\", \"ff4_body\");\n        model.addBody(model.getBodyId(\"ff4_body\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\n                      \"ff5_joint\", \"ff5_body\");\n        model.addBody(model.getBodyId(\"ff5_body\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\n                      \"root_joint\", \"root_body\");\n      }\n      else\n      {\n        model.addBody(model.getBodyId(\"universe\"),JointModelFreeFlyer(),SE3::Identity(),\n                      Inertia::Random(),\"root_joint\", \"root_body\");\n      }\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"lleg1_joint\", \"lleg1_body\");\n      model.addBody(model.getBodyId(\"lleg1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"lleg2_joint\", \"lleg2_body\");\n      model.addBody(model.getBodyId(\"lleg2_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"lleg3_joint\", \"lleg3_body\");\n      model.addBody(model.getBodyId(\"lleg3_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"lleg4_joint\", \"lleg4_body\");\n      model.addBody(model.getBodyId(\"lleg4_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"lleg5_joint\", \"lleg5_body\");\n      model.addBody(model.getBodyId(\"lleg5_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"lleg6_joint\", \"lleg6_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rleg1_joint\", \"rleg1_body\");\n      model.addBody(model.getBodyId(\"rleg1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rleg2_joint\", \"rleg2_body\");\n      model.addBody(model.getBodyId(\"rleg2_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rleg3_joint\", \"rleg3_body\");\n      model.addBody(model.getBodyId(\"rleg3_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rleg4_joint\", \"rleg4_body\");\n      model.addBody(model.getBodyId(\"rleg4_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rleg5_joint\", \"rleg5_body\");\n      model.addBody(model.getBodyId(\"rleg5_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rleg6_joint\", \"rleg6_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"torso1_joint\", \"torso1_body\");\n      model.addBody(model.getBodyId(\"torso1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"chest_joint\", \"chest_body\");\n\n      model.addBody(model.getBodyId(\"chest_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rarm1_joint\", \"rarm1_body\");\n      model.addBody(model.getBodyId(\"rarm1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rarm2_joint\", \"rarm2_body\");\n      model.addBody(model.getBodyId(\"rarm2_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rarm3_joint\", \"rarm3_body\");\n      model.addBody(model.getBodyId(\"rarm3_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rarm4_joint\", \"rarm4_body\");\n      model.addBody(model.getBodyId(\"rarm4_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rarm5_joint\", \"rarm5_body\");\n      model.addBody(model.getBodyId(\"rarm5_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rarm6_joint\", \"rarm6_body\");\n\n      model.addBody(model.getBodyId(\"chest_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"larm1_joint\", \"larm1_body\");\n      model.addBody(model.getBodyId(\"larm1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"larm2_joint\", \"larm2_body\");\n      model.addBody(model.getBodyId(\"larm2_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"larm3_joint\", \"larm3_body\");\n      model.addBody(model.getBodyId(\"larm3_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"larm4_joint\", \"larm4_body\");\n      model.addBody(model.getBodyId(\"larm4_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"larm5_joint\", \"larm5_body\");\n      model.addBody(model.getBodyId(\"larm5_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"larm6_joint\", \"larm6_body\");\n    }\n\n  } \/\/ namespace buildModels\n} \/\/ namespace se3\nBuild sample humanoid model with joint limits.\/\/\n\/\/ Copyright (c) 2015 CNRS\n\/\/ Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n\/\/\n\/\/ This file is part of Pinocchio\n\/\/ Pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ Pinocchio If not, see\n\/\/ .\n\n#include \"pinocchio\/multibody\/parser\/sample-models.hpp\"\n\nnamespace se3\n{\n  namespace buildModels\n  {\n\n    void humanoid2d(Model& model)\n    {\n      model.addBody(model.getBodyId(\"universe\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\n                    \"ff1_joint\", \"ff1_body\");\n      model.addBody(model.getBodyId(\"ff1_body\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\n                    \"root_joint\", \"root_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"lleg1_joint\", \"lleg1_body\");\n      model.addBody(model.getBodyId(\"lleg1_body\"),JointModelRY(),SE3::Random(),Inertia::Random(),\n                    \"lleg2_joint\", \"lleg2_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"rleg1_joint\", \"rleg1_body\");\n      model.addBody(model.getBodyId(\"rleg1_body\"),JointModelRY(),SE3::Random(),Inertia::Random(),\n                    \"rleg2_joint\", \"rleg2_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRY(),SE3::Random(),Inertia::Random(),\n                    \"torso1_joint\", \"torso1_body\");\n      model.addBody(model.getBodyId(\"torso1_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"chest_joint\", \"chest_body\");\n\n      model.addBody(model.getBodyId(\"chest_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"rarm1_joint\", \"rarm1_body\");\n      model.addBody(model.getBodyId(\"rarm1_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"rarm2_joint\", \"rarm2_body\");\n\n      model.addBody(model.getBodyId(\"chest_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    \"larm1_joint\", \"larm1_body\");\n      model.addBody(model.getBodyId(\"larm1_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                    \"larm2_joint\", \"larm2_body\");\n    }\n\n    void humanoidSimple(Model& model, bool usingFF)\n    {\n      if(! usingFF )\n      {\n        model.addBody(model.getBodyId(\"universe\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\n                      \"ff1_joint\", \"ff1_body\");\n        model.addBody(model.getBodyId(\"ff1_body\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\n                      \"ff2_joint\", \"ff2_body\");\n        model.addBody(model.getBodyId(\"ff2_body\"),JointModelRZ(),SE3::Identity(),Inertia::Random(),\n                      \"ff3_joint\", \"ff3_body\");\n        model.addBody(model.getBodyId(\"ff3_body\"),JointModelRZ(),SE3::Random(),Inertia::Random(),\n                      \"ff4_joint\", \"ff4_body\");\n        model.addBody(model.getBodyId(\"ff4_body\"),JointModelRY(),SE3::Identity(),Inertia::Random(),\n                      \"ff5_joint\", \"ff5_body\");\n        model.addBody(model.getBodyId(\"ff5_body\"),JointModelRX(),SE3::Identity(),Inertia::Random(),\n                      \"root_joint\", \"root_body\");\n      }\n      else\n      {\n        model.addBody(model.getBodyId(\"universe\"),JointModelFreeFlyer(),\n                      SE3::Identity(),Inertia::Random(),\n                      Eigen::VectorXd::Zero(6), 1e3 * (Eigen::VectorXd::Random(6).array() + 1),\n                      1e3 * (Eigen::VectorXd::Random(7).array() - 1),\n                      1e3 * (Eigen::VectorXd::Random(7).array() + 1),\n                      \"root_joint\", \"root_body\");\n      }\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"lleg1_joint\", \"lleg1_body\");\n      model.addBody(model.getBodyId(\"lleg1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"lleg2_joint\", \"lleg2_body\");\n      model.addBody(model.getBodyId(\"lleg2_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"lleg3_joint\", \"lleg3_body\");\n      model.addBody(model.getBodyId(\"lleg3_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"lleg4_joint\", \"lleg4_body\");\n      model.addBody(model.getBodyId(\"lleg4_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"lleg5_joint\", \"lleg5_body\");\n      model.addBody(model.getBodyId(\"lleg5_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"lleg6_joint\", \"lleg6_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rleg1_joint\", \"rleg1_body\");\n      model.addBody(model.getBodyId(\"rleg1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rleg2_joint\", \"rleg2_body\");\n      model.addBody(model.getBodyId(\"rleg2_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rleg3_joint\", \"rleg3_body\");\n      model.addBody(model.getBodyId(\"rleg3_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rleg4_joint\", \"rleg4_body\");\n      model.addBody(model.getBodyId(\"rleg4_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rleg5_joint\", \"rleg5_body\");\n      model.addBody(model.getBodyId(\"rleg5_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rleg6_joint\", \"rleg6_body\");\n\n      model.addBody(model.getBodyId(\"root_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"torso1_joint\", \"torso1_body\");\n      model.addBody(model.getBodyId(\"torso1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"chest_joint\", \"chest_body\");\n\n      model.addBody(model.getBodyId(\"chest_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rarm1_joint\", \"rarm1_body\");\n      model.addBody(model.getBodyId(\"rarm1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rarm2_joint\", \"rarm2_body\");\n      model.addBody(model.getBodyId(\"rarm2_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rarm3_joint\", \"rarm3_body\");\n      model.addBody(model.getBodyId(\"rarm3_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rarm4_joint\", \"rarm4_body\");\n      model.addBody(model.getBodyId(\"rarm4_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rarm5_joint\", \"rarm5_body\");\n      model.addBody(model.getBodyId(\"rarm5_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"rarm6_joint\", \"rarm6_body\");\n\n      model.addBody(model.getBodyId(\"chest_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"larm1_joint\", \"larm1_body\");\n      model.addBody(model.getBodyId(\"larm1_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"larm2_joint\", \"larm2_body\");\n      model.addBody(model.getBodyId(\"larm2_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"larm3_joint\", \"larm3_body\");\n      model.addBody(model.getBodyId(\"larm3_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"larm4_joint\", \"larm4_body\");\n      model.addBody(model.getBodyId(\"larm4_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"larm5_joint\", \"larm5_body\");\n      model.addBody(model.getBodyId(\"larm5_body\"),JointModelRX(),SE3::Random(),Inertia::Random(),\n                    Eigen::VectorXd::Random(1).array() + 1, Eigen::VectorXd::Random(1).array() + 1,\n                    Eigen::VectorXd::Random(1).array() - 1, Eigen::VectorXd::Random(1).array() + 1,\n                    \"larm6_joint\", \"larm6_body\");\n    }\n\n  } \/\/ namespace buildModels\n} \/\/ namespace se3\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nvoid initialize()\n{\n    const static auto verify_handle = MakeUnique();\n    SelectParams(CBaseChainParams::REGTEST);\n}\n\nvoid test_one_input(const std::vector& buffer)\n{\n    CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);\n    CBlock block;\n    try {\n        int nVersion;\n        ds >> nVersion;\n        ds.SetVersion(nVersion);\n        ds >> block;\n    } catch (const std::ios_base::failure&) {\n        return;\n    }\n    const Consensus::Params& consensus_params = Params().GetConsensus();\n    BlockValidationState validation_state_pow_and_merkle;\n    const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, \/* fCheckPOW= *\/ true, \/* fCheckMerkleRoot= *\/ true);\n    BlockValidationState validation_state_pow;\n    const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, \/* fCheckPOW= *\/ true, \/* fCheckMerkleRoot= *\/ false);\n    BlockValidationState validation_state_merkle;\n    const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, \/* fCheckPOW= *\/ false, \/* fCheckMerkleRoot= *\/ true);\n    BlockValidationState validation_state_none;\n    const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, \/* fCheckPOW= *\/ false, \/* fCheckMerkleRoot= *\/ false);\n    if (valid_incl_pow_and_merkle) {\n        assert(valid_incl_pow && valid_incl_merkle && valid_incl_none);\n    } else if (valid_incl_merkle || valid_incl_pow) {\n        assert(valid_incl_none);\n    }\n    (void)block.GetHash();\n    (void)block.ToString();\n    (void)BlockMerkleRoot(block);\n    if (!block.vtx.empty()) {\n        \/\/ TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot\n        \/\/       when block.vtx.empty().\n        (void)BlockWitnessMerkleRoot(block);\n    }\n    (void)GetBlockWeight(block);\n    (void)GetWitnessCommitmentIndex(block);\n    (void)RecursiveDynamicUsage(block);\n}\ntests: Fuzz RecursiveDynamicUsage(const std::shared_ptr& p)\/\/ Copyright (c) 2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nvoid initialize()\n{\n    const static auto verify_handle = MakeUnique();\n    SelectParams(CBaseChainParams::REGTEST);\n}\n\nvoid test_one_input(const std::vector& buffer)\n{\n    CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);\n    CBlock block;\n    try {\n        int nVersion;\n        ds >> nVersion;\n        ds.SetVersion(nVersion);\n        ds >> block;\n    } catch (const std::ios_base::failure&) {\n        return;\n    }\n    const Consensus::Params& consensus_params = Params().GetConsensus();\n    BlockValidationState validation_state_pow_and_merkle;\n    const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, \/* fCheckPOW= *\/ true, \/* fCheckMerkleRoot= *\/ true);\n    BlockValidationState validation_state_pow;\n    const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, \/* fCheckPOW= *\/ true, \/* fCheckMerkleRoot= *\/ false);\n    BlockValidationState validation_state_merkle;\n    const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, \/* fCheckPOW= *\/ false, \/* fCheckMerkleRoot= *\/ true);\n    BlockValidationState validation_state_none;\n    const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, \/* fCheckPOW= *\/ false, \/* fCheckMerkleRoot= *\/ false);\n    if (valid_incl_pow_and_merkle) {\n        assert(valid_incl_pow && valid_incl_merkle && valid_incl_none);\n    } else if (valid_incl_merkle || valid_incl_pow) {\n        assert(valid_incl_none);\n    }\n    (void)block.GetHash();\n    (void)block.ToString();\n    (void)BlockMerkleRoot(block);\n    if (!block.vtx.empty()) {\n        \/\/ TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot\n        \/\/       when block.vtx.empty().\n        (void)BlockWitnessMerkleRoot(block);\n    }\n    (void)GetBlockWeight(block);\n    (void)GetWitnessCommitmentIndex(block);\n    const size_t raw_memory_size = RecursiveDynamicUsage(block);\n    const size_t raw_memory_size_as_shared_ptr = RecursiveDynamicUsage(std::make_shared(block));\n    assert(raw_memory_size_as_shared_ptr > raw_memory_size);\n}\n<|endoftext|>"}
{"text":"#include \"parser.hpp\"\n#include \n\nstd::string pre_rules(std::string def_out,std::string def_in)\n{\n\tstd::string pre;\n\tpre+=\"ufw --force disable\\n\";\n\tpre+=\"ufw --force reset\\n\";\n\tpre+=\"ufw logging on\\n\";\n\tpre+=\"ufw default \"+def_out+\" outgoing\\n\";\n\tpre+=\"ufw default \"+def_in+\" incoming\\n\";\n\treturn pre;\n}\n\nstd::string post_rules(std::string def_out,std::string def_in)\n{\n\treturn \"ufw --force enable\\n\";\n}\n\nstd::string gen_rule(wof_t wof)\n{\n\tstd::string rule;\n\trule+=\"ufw \";\n\tif(wof.action==\"deny\")\n\t\trule+=\"block\";\n\telse\n\t\trule+=\"allow\";\n\tstd::string dir_str=\" out\";\n\tif(wof.dir==\"<\")\n\t{\n\t\tdir_str=\" in \";\n\t\tstd::swap(wof.l_ip,wof.f_ip);\n\t\tstd::swap(wof.l_mask,wof.f_mask);\n\t\tstd::swap(wof.l_port,wof.f_port);\n\t}\n\trule+=dir_str;\n\trule+=\" proto \"+wof.proto;\n\trule+=\" from \"+wof.l_ip+\"\/\"+wof.l_mask;\n\tif(wof.l_port!=\"0\")\n\t\trule+=\" port \"+wof.l_port;\n\trule+=\" to \"+wof.f_ip+\"\/\"+wof.f_mask;\n\tif(wof.f_port!=\"0\")\n\t\trule+=\" port \"+wof.f_port;\n\n\treturn rule;\n}Deny\/block error ufw.#include \"parser.hpp\"\n#include \n\nstd::string pre_rules(std::string def_out,std::string def_in)\n{\n\tif(def_out==\"pass\")\n\t\tdef_out=\"allow\";\n\tif(def_in==\"pass\")\n\t\tdef_in=\"allow\";\n\tstd::string pre;\n\tpre+=\"ufw --force disable\\n\";\n\tpre+=\"ufw --force reset\\n\";\n\tpre+=\"ufw logging on\\n\";\n\tpre+=\"ufw default \"+def_out+\" outgoing\\n\";\n\tpre+=\"ufw default \"+def_in+\" incoming\\n\";\n\treturn pre;\n}\n\nstd::string post_rules(std::string def_out,std::string def_in)\n{\n\treturn \"ufw --force enable\\n\";\n}\n\nstd::string gen_rule(wof_t wof)\n{\n\tstd::string rule;\n\trule+=\"ufw \";\n\tif(wof.action==\"deny\")\n\t\trule+=\"deny\";\n\telse\n\t\trule+=\"allow\";\n\tstd::string dir_str=\" out\";\n\tif(wof.dir==\"<\")\n\t{\n\t\tdir_str=\" in \";\n\t\tstd::swap(wof.l_ip,wof.f_ip);\n\t\tstd::swap(wof.l_mask,wof.f_mask);\n\t\tstd::swap(wof.l_port,wof.f_port);\n\t}\n\trule+=dir_str;\n\trule+=\" proto \"+wof.proto;\n\trule+=\" from \"+wof.l_ip+\"\/\"+wof.l_mask;\n\tif(wof.l_port!=\"0\")\n\t\trule+=\" port \"+wof.l_port;\n\trule+=\" to \"+wof.f_ip+\"\/\"+wof.f_mask;\n\tif(wof.f_port!=\"0\")\n\t\trule+=\" port \"+wof.f_port;\n\n\treturn rule;\n}<|endoftext|>"}
{"text":"\/*  This file is part of the Tufão project\n    Copyright (C) 2011 Vinícius dos Santos Oliveira \n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 3 of the License, or (at your option) any\n    later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library.  If not, see .\n*\/\n\n#include \"url.h\"\n#include \"priv\/url.h\"\n\n#include \"httpserverrequest.h\"\n\n#include \n#include \n\n\/\/ Groups:\n\/\/ 1  = scheme\n\/\/ 2  = authority\n\/\/ 3  = userinfo\n\/\/ 4  = username\n\/\/ 5  = userpass\n\/\/ 6  = hostname\n\/\/ 7  = port\n\/\/ 8  = path\n\/\/ 9  = query\n\/\/ 10 = fragment\nstatic QRegExp regex(\"^(?:([^:\/?#]+):)?\"\n                     \"(?:\/\/((?:(([^\/?#@:]*)(?::([^\/?#@]*))?)@)?\"\n                     \"([^\/?#:]*)(?::([^\/?#]*))?))?\"\n                     \"([^?#]*)\"\n                     \"(?:\\\\?([^#]*))?\"\n                     \"(?:#(.*))?\");\n\nnamespace Tufao {\n\nUrl::Url(const QString &url) :\n    priv(new Priv::Url(regex))\n{\n    priv->regex.indexIn(url);\n}\n\nUrl::Url(const Url &url) :\n    priv(new Priv::Url(url.priv->regex))\n{\n}\n\nUrl::~Url()\n{\n    delete priv;\n}\n\nUrl &Url::operator =(const Url &url)\n{\n    if (this == &url)\n        return *this;\n\n    delete priv;\n    priv = new Priv::Url(url.priv->regex);\n    return *this;\n}\n\nQString Url::scheme() const\n{\n    return priv->regex.cap(1);\n}\n\nQString Url::authority() const\n{\n    return priv->regex.cap(2);\n}\n\nQString Url::path() const\n{\n    return priv->regex.cap(8);\n}\n\nQString Url::query() const\n{\n    return priv->regex.cap(9);\n}\n\nQString Url::fragment() const\n{\n    return priv->regex.cap(10);\n}\n\nQString Url::userinfo() const\n{\n    return priv->regex.cap(3);\n}\n\nQString Url::hostname() const\n{\n    return priv->regex.cap(6);\n}\n\nQString Url::port() const\n{\n    return priv->regex.cap(7);\n}\n\nQString Url::username() const\n{\n    return priv->regex.cap(4);\n}\n\nQString Url::password() const\n{\n    return priv->regex.cap(5);\n}\n\nQByteArray Url::url(HttpServerRequest *request)\n{\n    QByteArray host(request->headers().value(\"Host\"));\n    if (host.isEmpty())\n        host = request->socket()->localAddress().toString();\n\n    if (qobject_cast(request->socket()))\n        return \"https:\/\/\" + host + request->url();\n    else\n        return \"http:\/\/\" + host + request->url();\n}\n\n} \/\/ namespace Tufao\nfix: build issue in Url\/*  This file is part of the Tufão project\n    Copyright (C) 2011 Vinícius dos Santos Oliveira \n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 3 of the License, or (at your option) any\n    later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library.  If not, see .\n*\/\n\n#include \"url.h\"\n#include \"priv\/url.h\"\n\n#include \"httpserverrequest.h\"\n#include \"headers.h\"\n\n#include \n#include \n\n\/\/ Groups:\n\/\/ 1  = scheme\n\/\/ 2  = authority\n\/\/ 3  = userinfo\n\/\/ 4  = username\n\/\/ 5  = userpass\n\/\/ 6  = hostname\n\/\/ 7  = port\n\/\/ 8  = path\n\/\/ 9  = query\n\/\/ 10 = fragment\nstatic QRegExp regex(\"^(?:([^:\/?#]+):)?\"\n                     \"(?:\/\/((?:(([^\/?#@:]*)(?::([^\/?#@]*))?)@)?\"\n                     \"([^\/?#:]*)(?::([^\/?#]*))?))?\"\n                     \"([^?#]*)\"\n                     \"(?:\\\\?([^#]*))?\"\n                     \"(?:#(.*))?\");\n\nnamespace Tufao {\n\nUrl::Url(const QString &url) :\n    priv(new Priv::Url(regex))\n{\n    priv->regex.indexIn(url);\n}\n\nUrl::Url(const Url &url) :\n    priv(new Priv::Url(url.priv->regex))\n{\n}\n\nUrl::~Url()\n{\n    delete priv;\n}\n\nUrl &Url::operator =(const Url &url)\n{\n    if (this == &url)\n        return *this;\n\n    delete priv;\n    priv = new Priv::Url(url.priv->regex);\n    return *this;\n}\n\nQString Url::scheme() const\n{\n    return priv->regex.cap(1);\n}\n\nQString Url::authority() const\n{\n    return priv->regex.cap(2);\n}\n\nQString Url::path() const\n{\n    return priv->regex.cap(8);\n}\n\nQString Url::query() const\n{\n    return priv->regex.cap(9);\n}\n\nQString Url::fragment() const\n{\n    return priv->regex.cap(10);\n}\n\nQString Url::userinfo() const\n{\n    return priv->regex.cap(3);\n}\n\nQString Url::hostname() const\n{\n    return priv->regex.cap(6);\n}\n\nQString Url::port() const\n{\n    return priv->regex.cap(7);\n}\n\nQString Url::username() const\n{\n    return priv->regex.cap(4);\n}\n\nQString Url::password() const\n{\n    return priv->regex.cap(5);\n}\n\nQByteArray Url::url(HttpServerRequest *request)\n{\n    QByteArray host(request->headers().value(\"Host\"));\n    if (host.isEmpty())\n        host = request->socket()->localAddress().toString().toUtf8();\n\n    if (qobject_cast(request->socket()))\n        return \"https:\/\/\" + host + request->url();\n    else\n        return \"http:\/\/\" + host + request->url();\n}\n\n} \/\/ namespace Tufao\n<|endoftext|>"}
{"text":"#include \n#include \"..\/tlang.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nVector complex_mul(const Vector &a, const Vector &b) {\n  Vector ret(2);\n  ret(0) = a(0) * b(0) - a(1) * b(1);\n  ret(1) = a(0) * b(1) + a(1) * b(0);\n  return ret;\n}\n\nauto mset = [] {\n  CoreState::set_trigger_gdb_when_crash(true);\n  int n = 1024;\n  Program prog(Arch::x86_64);\n\n  Global(a, i32);\n\n  layout([&]() { root.fixed(0, n * n).place(a); });\n\n  auto func = kernel([&]() {\n    Declare(i);\n\n    Vectorize(8);\n    For(i, 0, n * n, [&] {\n      Local(j) = 0;\n      int limit = 20;\n      if (false) {\n        Local(c_re) = cast(i \/ n) \/ float(n \/ 2) - 1.5f;\n        Local(c_im) = cast(i % n) \/ float(n \/ 2) - 1.0f;\n        Local(z_re) = c_re;\n        Local(z_im) = c_im;\n\n        While(j < limit && (z_re * z_re + z_im * z_im) < 4.0f, [&] {\n          Local(new_re) = z_re * z_re - z_im * z_im;\n          Local(new_im) = 2.0f * z_re * z_im;\n          z_re = c_re + new_re;\n          z_im = c_im + new_im;\n          j += 1;\n        });\n      } else {\n        Vector c(2);\n\n        c(0) = cast(i \/ n) \/ float(n \/ 2) - 1.5f;\n        c(1) = cast(i % n) \/ float(n \/ 2) - 1.0f;\n\n        Vector z = c;\n\n        While(j < limit && z.norm2() < 4.0f, [&] {\n          z = complex_mul(z, z) + c;\n          j += 1;\n        });\n      }\n      a[i] = j;\n    });\n  });\n\n  TC_P(measure_cpe(func, 1));\n\n  GUI gui(\"Mandelbrot Set\", Vector2i(n));\n  for (int i = 0; i < n * n; i++) {\n    gui.buffer[i \/ n][i % n] = Vector4(a.val(i) % 11 * 0.1f);\n  }\n  while (1)\n    gui.update();\n};\nTC_REGISTER_TASK(mset);\n\nauto ray_march = [] {\n  CoreState::set_trigger_gdb_when_crash(true);\n  int n = 512;\n  Program prog(Arch::x86_64);\n  prog.config.print_ir = true;\n\n  Global(color_r, f32);\n  Global(color_g, f32);\n  Global(color_b, f32);\n\n  layout([&]() { root.fixed(0, n * n * 2).place(color_r, color_g, color_b); });\n\n  auto sdf = [&](Vector p_) {\n    float alpha = -0.7f;\n    Vector p(3);\n    p(0) = (cos(alpha) * p_(0) + sin(alpha) * p_(2) + 1.0_f) % 2.0_f - 1.0_f;\n    p(1) = p_(1);\n    p(2) = -sin(alpha) * p_(0) + cos(alpha) * p_(2);\n\n    auto dist_sphere = p.norm() - 0.5_f;\n    auto dist_walls = min(p(2) + 6.0f, p(1) + 1.0f);\n    Vector d(3);\n    d(0) = abs(p(0) - 1.0_f) - 0.3_f;\n    d(1) = abs(p(1) + 0.5_f) - 1.2_f;\n    d(2) = abs(p(2) - 1.0_f) - 0.2_f;\n    auto dist_cube = norm(d.map([](const Expr &v) { return max(v, 0.0f); })) +\n                     min(max(max(d(0), d(1)), d(2)), 0.0_f);\n    return min(dist_sphere, min(dist_walls, dist_cube));\n  };\n\n  float32 eps = 1e-5f;\n  float32 dist_limit = 1e2;\n  int limit = 200;\n\n  auto ray_march = [&](Vector p, Vector dir) {\n    Local(j) = 0;\n    Local(dist) = 0.0f;\n\n    While(j < limit && sdf(p + dist * dir) > eps && dist < dist_limit, [&] {\n      dist += sdf(p + dist * dir);\n      j += 1;\n    });\n    return dist;\n  };\n\n  auto normal = [&](Vector p) {\n    float d = 1e-3f;\n    Vector n(3);\n    for (int i = 0; i < 3; i++) {\n      Vector inc = p, dec = p;\n      inc(i) += d;\n      dec(i) -= d;\n      n(i) = (0.5f \/ d) * (sdf(inc) - sdf(dec));\n    }\n    return normalized(n);\n  };\n\n  auto out_dir = [&](Vector n) {\n    Vector u({1.0f, 0.0f, 0.0f}), v(3);\n    Mutable(u, DataType::f32);\n    If(abs(n(1)) < 1 - 1e-3f, [&] {\n      u = normalized(cross(n, Vector({0.0f, 1.0f, 0.0f})));\n    });\n    v = cross(n, u);\n    Local(phi) = 2 * pi * Rand();\n    Local(r) = Rand();\n    Local(alpha) = 0.5_f * pi * (r * r);\n    return sin(alpha) * (cos(phi) * u + sin(phi) * v) + cos(alpha) * n;\n  };\n\n  auto background = [](Vector dir) {\n    return 1.0f * max(dir(1) + dir(0), 0.0f);\n  };\n\n  float fov = 0.3;\n\n  auto main = kernel([&]() {\n    Declare(i);\n    Parallelize(8);\n    \/\/ Vectorize(8);\n    For(i, 0, n * n * 2, [&] {\n      Vector orig({0.0f, 0.0f, 12.0f}), c(3);\n      Mutable(orig, DataType::f32);\n\n      c(0) = fov * (cast(i \/ n) \/ float(n \/ 2) - 2.0f);\n      c(1) = fov * (cast(i % n) \/ float(n \/ 2) - 1.0f);\n      c(2) = -1.0f;\n      c = normalized(c);\n\n      Mutable(c, DataType::f32);\n\n      Vector color(3);\n      color = Vector({1.0f, 1.0f, 1.0f});\n      Mutable(color, DataType::f32);\n      int depth_limit = 4;\n      Local(depth) = 0;\n\n      While(depth < depth_limit, [&] {\n        depth += 1;\n        Local(_dist) = ray_march(orig, c);\n        If(_dist < dist_limit,\n           [&] {\n             orig += _dist * c;\n             Vector nor;\n             nor = normal(orig);\n             c = normalized(out_dir(nor));\n             orig += 0.01f * c;\n             color *= 0.7_f;\n           })\n            .Else([&] {\n              color = color * background(c);\n              depth = depth_limit;\n            });\n      });\n\n      color_r[i] += color(0);\n      color_g[i] += color(1);\n      color_b[i] += color(2);\n    });\n  });\n\n  \/\/\/ TC_P(measure_cpe(func, 1));\n\n  GUI gui(\"ray march\", Vector2i(n * 2, n));\n\n  auto tone_map = [](real x) { return x; };\n  constexpr int N = 1;\n  for (int frame = 0;; frame++) {\n    for (int i = 0; i < N; i++)\n      main();\n    real scale = 1.0_f \/ ((frame + 1) * N);\n    for (int i = 0; i < n * n * 2; i++) {\n      gui.buffer[i \/ n][i % n] =\n          Vector4(tone_map(scale * color_r.val(i)),\n                  tone_map(scale * color_g.val(i)),\n                  tone_map(scale * color_b.val(i)), 1);\n    }\n    gui.update();\n  }\n};\nTC_REGISTER_TASK(ray_march);\n\nTLANG_NAMESPACE_END\nVectorized ray_march on CPU#include \n#include \"..\/tlang.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nVector complex_mul(const Vector &a, const Vector &b) {\n  Vector ret(2);\n  ret(0) = a(0) * b(0) - a(1) * b(1);\n  ret(1) = a(0) * b(1) + a(1) * b(0);\n  return ret;\n}\n\nauto mset = [] {\n  CoreState::set_trigger_gdb_when_crash(true);\n  int n = 1024;\n  Program prog(Arch::x86_64);\n\n  Global(a, i32);\n\n  layout([&]() { root.fixed(0, n * n).place(a); });\n\n  auto func = kernel([&]() {\n    Declare(i);\n\n    Vectorize(8);\n    For(i, 0, n * n, [&] {\n      Local(j) = 0;\n      int limit = 20;\n      if (false) {\n        Local(c_re) = cast(i \/ n) \/ float(n \/ 2) - 1.5f;\n        Local(c_im) = cast(i % n) \/ float(n \/ 2) - 1.0f;\n        Local(z_re) = c_re;\n        Local(z_im) = c_im;\n\n        While(j < limit && (z_re * z_re + z_im * z_im) < 4.0f, [&] {\n          Local(new_re) = z_re * z_re - z_im * z_im;\n          Local(new_im) = 2.0f * z_re * z_im;\n          z_re = c_re + new_re;\n          z_im = c_im + new_im;\n          j += 1;\n        });\n      } else {\n        Vector c(2);\n\n        c(0) = cast(i \/ n) \/ float(n \/ 2) - 1.5f;\n        c(1) = cast(i % n) \/ float(n \/ 2) - 1.0f;\n\n        Vector z = c;\n\n        While(j < limit && z.norm2() < 4.0f, [&] {\n          z = complex_mul(z, z) + c;\n          j += 1;\n        });\n      }\n      a[i] = j;\n    });\n  });\n\n  TC_P(measure_cpe(func, 1));\n\n  GUI gui(\"Mandelbrot Set\", Vector2i(n));\n  for (int i = 0; i < n * n; i++) {\n    gui.buffer[i \/ n][i % n] = Vector4(a.val(i) % 11 * 0.1f);\n  }\n  while (1)\n    gui.update();\n};\nTC_REGISTER_TASK(mset);\n\nauto ray_march = [] {\n  CoreState::set_trigger_gdb_when_crash(true);\n  int n = 512;\n  Program prog(Arch::x86_64);\n  prog.config.print_ir = true;\n\n  Global(color_r, f32);\n  Global(color_g, f32);\n  Global(color_b, f32);\n\n  layout([&]() { root.fixed(0, n * n * 2).place(color_r, color_g, color_b); });\n\n  auto sdf = [&](Vector p_) {\n    float alpha = -0.7f;\n    Vector p(3);\n    p(0) = (cos(alpha) * p_(0) + sin(alpha) * p_(2) + 1.0_f) % 2.0_f - 1.0_f;\n    p(1) = p_(1);\n    p(2) = -sin(alpha) * p_(0) + cos(alpha) * p_(2);\n\n    auto dist_sphere = p.norm() - 0.5_f;\n    auto dist_walls = min(p(2) + 6.0f, p(1) + 1.0f);\n    Vector d(3);\n    d(0) = abs(p(0) - 1.0_f) - 0.3_f;\n    d(1) = abs(p(1) + 0.5_f) - 1.2_f;\n    d(2) = abs(p(2) - 1.0_f) - 0.2_f;\n    auto dist_cube = norm(d.map([](const Expr &v) { return max(v, 0.0f); })) +\n                     min(max(max(d(0), d(1)), d(2)), 0.0_f);\n    return min(dist_sphere, min(dist_walls, dist_cube));\n  };\n\n  float32 eps = 1e-5f;\n  float32 dist_limit = 1e2;\n  int limit = 200;\n\n  auto ray_march = [&](Vector p, Vector dir) {\n    Local(j) = 0;\n    Local(dist) = 0.0f;\n\n    While(j < limit && sdf(p + dist * dir) > eps && dist < dist_limit, [&] {\n      dist += sdf(p + dist * dir);\n      j += 1;\n    });\n    return dist;\n  };\n\n  auto normal = [&](Vector p) {\n    float d = 1e-3f;\n    Vector n(3);\n    for (int i = 0; i < 3; i++) {\n      Vector inc = p, dec = p;\n      inc(i) += d;\n      dec(i) -= d;\n      n(i) = (0.5f \/ d) * (sdf(inc) - sdf(dec));\n    }\n    return normalized(n);\n  };\n\n  auto out_dir = [&](Vector n) {\n    Vector u({1.0f, 0.0f, 0.0f}), v(3);\n    Mutable(u, DataType::f32);\n    If(abs(n(1)) < 1 - 1e-3f, [&] {\n      u = normalized(cross(n, Vector({0.0f, 1.0f, 0.0f})));\n    });\n    v = cross(n, u);\n    Local(phi) = 2 * pi * Rand();\n    Local(r) = Rand();\n    Local(alpha) = 0.5_f * pi * (r * r);\n    return sin(alpha) * (cos(phi) * u + sin(phi) * v) + cos(alpha) * n;\n  };\n\n  auto background = [](Vector dir) {\n    return 1.0f * max(dir(1) + dir(0), 0.0f);\n  };\n\n  float fov = 0.3;\n\n  auto main = kernel([&]() {\n    Declare(i);\n    Parallelize(8);\n    Vectorize(8);\n    For(i, 0, n * n * 2, [&] {\n      Vector orig({0.0f, 0.0f, 12.0f}), c(3);\n      Mutable(orig, DataType::f32);\n\n      c(0) = fov * (cast(i \/ n) \/ float(n \/ 2) - 2.0f);\n      c(1) = fov * (cast(i % n) \/ float(n \/ 2) - 1.0f);\n      c(2) = -1.0f;\n      c = normalized(c);\n\n      Mutable(c, DataType::f32);\n\n      Vector color(3);\n      color = Vector({1.0f, 1.0f, 1.0f});\n      Mutable(color, DataType::f32);\n      int depth_limit = 4;\n      Local(depth) = 0;\n\n      While(depth < depth_limit, [&] {\n        depth += 1;\n        Local(_dist) = ray_march(orig, c);\n        If(_dist < dist_limit,\n           [&] {\n             orig += _dist * c;\n             Vector nor;\n             nor = normal(orig);\n             c = normalized(out_dir(nor));\n             orig += 0.01f * c;\n             color *= 0.7_f;\n           })\n            .Else([&] {\n              color = color * background(c);\n              depth = depth_limit;\n            });\n      });\n\n      color_r[i] += color(0);\n      color_g[i] += color(1);\n      color_b[i] += color(2);\n    });\n  });\n\n  \/\/\/ TC_P(measure_cpe(func, 1));\n\n  GUI gui(\"ray march\", Vector2i(n * 2, n));\n\n  auto tone_map = [](real x) { return x; };\n  constexpr int N = 1;\n  for (int frame = 0;; frame++) {\n    for (int i = 0; i < N; i++)\n      main();\n    real scale = 1.0_f \/ ((frame + 1) * N);\n    for (int i = 0; i < n * n * 2; i++) {\n      gui.buffer[i \/ n][i % n] =\n          Vector4(tone_map(scale * color_r.val(i)),\n                  tone_map(scale * color_g.val(i)),\n                  tone_map(scale * color_b.val(i)), 1);\n    }\n    gui.update();\n  }\n};\nTC_REGISTER_TASK(ray_march);\n\nTLANG_NAMESPACE_END\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"chainparams.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n\n#include \n\nunsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const Consensus::Params& params) {\n    const CBlockIndex *BlockLastSolved = pindexLast;\n    const CBlockIndex *BlockReading = pindexLast;\n    uint64_t PastBlocksMass = 0;\n    int64_t PastRateActualSeconds = 0;\n    int64_t PastRateTargetSeconds = 0;\n    double PastRateAdjustmentRatio = double(1);\n    arith_uint256 PastDifficultyAverage;\n    arith_uint256 PastDifficultyAveragePrev;\n    double EventHorizonDeviation;\n    double EventHorizonDeviationFast;\n    double EventHorizonDeviationSlow;\n\n    uint64_t pastSecondsMin = params.nPowTargetTimespan * 0.025;\n    uint64_t pastSecondsMax = params.nPowTargetTimespan * 7;\n    uint64_t PastBlocksMin = pastSecondsMin \/ params.nPowTargetSpacing;\n    uint64_t PastBlocksMax = pastSecondsMax \/ params.nPowTargetSpacing;\n\n    if (BlockLastSolved == nullptr || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); }\n\n    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n        PastBlocksMass++;\n\n        PastDifficultyAverage.SetCompact(BlockReading->nBits);\n        if (i > 1) {\n            \/\/ handle negative arith_uint256\n            if(PastDifficultyAverage >= PastDifficultyAveragePrev)\n                PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) \/ i) + PastDifficultyAveragePrev;\n            else\n                PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) \/ i);\n        }\n        PastDifficultyAveragePrev = PastDifficultyAverage;\n\n        PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();\n        PastRateTargetSeconds = params.nPowTargetSpacing * PastBlocksMass;\n        PastRateAdjustmentRatio = double(1);\n        if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }\n        if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n            PastRateAdjustmentRatio = double(PastRateTargetSeconds) \/ double(PastRateActualSeconds);\n        }\n        EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)\/double(28.2)), -1.228));\n        EventHorizonDeviationFast = EventHorizonDeviation;\n        EventHorizonDeviationSlow = 1 \/ EventHorizonDeviation;\n\n        if (PastBlocksMass >= PastBlocksMin) {\n                if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast))\n                { assert(BlockReading); break; }\n        }\n        if (BlockReading->pprev == nullptr) { assert(BlockReading); break; }\n        BlockReading = BlockReading->pprev;\n    }\n\n    arith_uint256 bnNew(PastDifficultyAverage);\n    if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n        bnNew *= PastRateActualSeconds;\n        bnNew \/= PastRateTargetSeconds;\n    }\n\n    if (bnNew > UintToArith256(params.powLimit)) {\n        bnNew = UintToArith256(params.powLimit);\n    }\n\n    return bnNew.GetCompact();\n}\n\nunsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) {\n    \/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dash.org *\/\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n    int64_t nPastBlocks = 24;\n\n    \/\/ make sure we have at least (nPastBlocks + 1) blocks, otherwise just return powLimit\n    if (!pindexLast || pindexLast->nHeight < nPastBlocks) {\n        return bnPowLimit.GetCompact();\n    }\n\n    if (params.fPowAllowMinDifficultyBlocks) {\n        \/\/ recent block is more than 2 hours old\n        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + 2 * 60 * 60) {\n            return bnPowLimit.GetCompact();\n        }\n        \/\/ recent block is more than 10 minutes old\n        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing * 4) {\n            arith_uint256 bnNew = arith_uint256().SetCompact(pindexLast->nBits) * 10;\n            if (bnNew > bnPowLimit) {\n                bnNew = bnPowLimit;\n            }\n            return bnNew.GetCompact();\n        }\n    }\n\n    const CBlockIndex *pindex = pindexLast;\n    arith_uint256 bnPastTargetAvg;\n\n    for (unsigned int nCountBlocks = 1; nCountBlocks <= nPastBlocks; nCountBlocks++) {\n        arith_uint256 bnTarget = arith_uint256().SetCompact(pindex->nBits);\n        if (nCountBlocks == 1) {\n            bnPastTargetAvg = bnTarget;\n        } else {\n            \/\/ NOTE: that's not an average really...\n            bnPastTargetAvg = (bnPastTargetAvg * nCountBlocks + bnTarget) \/ (nCountBlocks + 1);\n        }\n\n        if(nCountBlocks != nPastBlocks) {\n            assert(pindex->pprev); \/\/ should never fail\n            pindex = pindex->pprev;\n        }\n    }\n\n    arith_uint256 bnNew(bnPastTargetAvg);\n\n    int64_t nActualTimespan = pindexLast->GetBlockTime() - pindex->GetBlockTime();\n    \/\/ NOTE: is this accurate? nActualTimespan counts it for (nPastBlocks - 1) blocks only...\n    int64_t nTargetTimespan = nPastBlocks * params.nPowTargetSpacing;\n\n    if (nActualTimespan < nTargetTimespan\/3)\n        nActualTimespan = nTargetTimespan\/3;\n    if (nActualTimespan > nTargetTimespan*3)\n        nActualTimespan = nTargetTimespan*3;\n\n    \/\/ Retarget\n    bnNew *= nActualTimespan;\n    bnNew \/= nTargetTimespan;\n\n    if (bnNew > bnPowLimit) {\n        bnNew = bnPowLimit;\n    }\n\n    return bnNew.GetCompact();\n}\n\nunsigned int GetNextWorkRequiredBTC(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n    assert(pindexLast != nullptr);\n    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();\n\n    \/\/ Only change once per interval\n    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)\n    {\n        if (params.fPowAllowMinDifficultyBlocks)\n        {\n            \/\/ Special difficulty rule for testnet:\n            \/\/ If the new block's timestamp is more than 2* 2.5 minutes\n            \/\/ then allow mining of a min-difficulty block.\n            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n                return nProofOfWorkLimit;\n            else\n            {\n                \/\/ Return the last non-special-min-difficulty-rules-block\n                const CBlockIndex* pindex = pindexLast;\n                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)\n                    pindex = pindex->pprev;\n                return pindex->nBits;\n            }\n        }\n        return pindexLast->nBits;\n    }\n\n    \/\/ Go back by what we want to be 1 day worth of blocks\n    int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1);\n    assert(nHeightFirst >= 0);\n    const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);\n    assert(pindexFirst);\n\n   return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);\n}\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n    \/\/ this is only active on devnets\n    if (pindexLast->nHeight < params.nMinimumDifficultyBlocks) {\n        unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();\n        return nProofOfWorkLimit;\n    }\n\n    \/\/ Most recent algo first\n    if (pindexLast->nHeight + 1 >= params.nPowDGWHeight) {\n        return DarkGravityWave(pindexLast, pblock, params);\n    }\n    else if (pindexLast->nHeight + 1 >= params.nPowKGWHeight) {\n        return KimotoGravityWell(pindexLast, params);\n    }\n    else {\n        return GetNextWorkRequiredBTC(pindexLast, pblock, params);\n    }\n}\n\n\/\/ for DIFF_BTC only!\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n    if (params.fPowNoRetargeting)\n        return pindexLast->nBits;\n\n    \/\/ Limit adjustment step\n    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;\n    if (nActualTimespan < params.nPowTargetTimespan\/4)\n        nActualTimespan = params.nPowTargetTimespan\/4;\n    if (nActualTimespan > params.nPowTargetTimespan*4)\n        nActualTimespan = params.nPowTargetTimespan*4;\n\n    \/\/ Retarget\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n    arith_uint256 bnNew;\n    bnNew.SetCompact(pindexLast->nBits);\n    bnNew *= nActualTimespan;\n    bnNew \/= params.nPowTargetTimespan;\n\n    if (bnNew > bnPowLimit)\n        bnNew = bnPowLimit;\n\n    return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n    bool fNegative;\n    bool fOverflow;\n    arith_uint256 bnTarget;\n\n    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n    \/\/ Check range\n    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n        return false;\n\n    \/\/ Check proof of work matches claimed amount\n    if (UintToArith256(hash) > bnTarget)\n        return false;\n\n    return true;\n}\nRefactor some pow functions (#3198)\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"chainparams.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n\n#include \n\nunsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const Consensus::Params& params) {\n    const CBlockIndex *BlockLastSolved = pindexLast;\n    const CBlockIndex *BlockReading = pindexLast;\n    uint64_t PastBlocksMass = 0;\n    int64_t PastRateActualSeconds = 0;\n    int64_t PastRateTargetSeconds = 0;\n    double PastRateAdjustmentRatio = double(1);\n    arith_uint256 PastDifficultyAverage;\n    arith_uint256 PastDifficultyAveragePrev;\n    double EventHorizonDeviation;\n    double EventHorizonDeviationFast;\n    double EventHorizonDeviationSlow;\n\n    uint64_t pastSecondsMin = params.nPowTargetTimespan * 0.025;\n    uint64_t pastSecondsMax = params.nPowTargetTimespan * 7;\n    uint64_t PastBlocksMin = pastSecondsMin \/ params.nPowTargetSpacing;\n    uint64_t PastBlocksMax = pastSecondsMax \/ params.nPowTargetSpacing;\n\n    if (BlockLastSolved == nullptr || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); }\n\n    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n        PastBlocksMass++;\n\n        PastDifficultyAverage.SetCompact(BlockReading->nBits);\n        if (i > 1) {\n            \/\/ handle negative arith_uint256\n            if(PastDifficultyAverage >= PastDifficultyAveragePrev)\n                PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) \/ i) + PastDifficultyAveragePrev;\n            else\n                PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) \/ i);\n        }\n        PastDifficultyAveragePrev = PastDifficultyAverage;\n\n        PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();\n        PastRateTargetSeconds = params.nPowTargetSpacing * PastBlocksMass;\n        PastRateAdjustmentRatio = double(1);\n        if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }\n        if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n            PastRateAdjustmentRatio = double(PastRateTargetSeconds) \/ double(PastRateActualSeconds);\n        }\n        EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)\/double(28.2)), -1.228));\n        EventHorizonDeviationFast = EventHorizonDeviation;\n        EventHorizonDeviationSlow = 1 \/ EventHorizonDeviation;\n\n        if (PastBlocksMass >= PastBlocksMin) {\n                if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast))\n                { assert(BlockReading); break; }\n        }\n        if (BlockReading->pprev == nullptr) { assert(BlockReading); break; }\n        BlockReading = BlockReading->pprev;\n    }\n\n    arith_uint256 bnNew(PastDifficultyAverage);\n    if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n        bnNew *= PastRateActualSeconds;\n        bnNew \/= PastRateTargetSeconds;\n    }\n\n    if (bnNew > UintToArith256(params.powLimit)) {\n        bnNew = UintToArith256(params.powLimit);\n    }\n\n    return bnNew.GetCompact();\n}\n\nunsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const Consensus::Params& params) {\n    \/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dash.org *\/\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n    int64_t nPastBlocks = 24;\n\n    \/\/ make sure we have at least (nPastBlocks + 1) blocks, otherwise just return powLimit\n    if (!pindexLast || pindexLast->nHeight < nPastBlocks) {\n        return bnPowLimit.GetCompact();\n    }\n\n    const CBlockIndex *pindex = pindexLast;\n    arith_uint256 bnPastTargetAvg;\n\n    for (unsigned int nCountBlocks = 1; nCountBlocks <= nPastBlocks; nCountBlocks++) {\n        arith_uint256 bnTarget = arith_uint256().SetCompact(pindex->nBits);\n        if (nCountBlocks == 1) {\n            bnPastTargetAvg = bnTarget;\n        } else {\n            \/\/ NOTE: that's not an average really...\n            bnPastTargetAvg = (bnPastTargetAvg * nCountBlocks + bnTarget) \/ (nCountBlocks + 1);\n        }\n\n        if(nCountBlocks != nPastBlocks) {\n            assert(pindex->pprev); \/\/ should never fail\n            pindex = pindex->pprev;\n        }\n    }\n\n    arith_uint256 bnNew(bnPastTargetAvg);\n\n    int64_t nActualTimespan = pindexLast->GetBlockTime() - pindex->GetBlockTime();\n    \/\/ NOTE: is this accurate? nActualTimespan counts it for (nPastBlocks - 1) blocks only...\n    int64_t nTargetTimespan = nPastBlocks * params.nPowTargetSpacing;\n\n    if (nActualTimespan < nTargetTimespan\/3)\n        nActualTimespan = nTargetTimespan\/3;\n    if (nActualTimespan > nTargetTimespan*3)\n        nActualTimespan = nTargetTimespan*3;\n\n    \/\/ Retarget\n    bnNew *= nActualTimespan;\n    bnNew \/= nTargetTimespan;\n\n    if (bnNew > bnPowLimit) {\n        bnNew = bnPowLimit;\n    }\n\n    return bnNew.GetCompact();\n}\n\nunsigned int GetNextWorkRequiredBTC(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n    assert(pindexLast != nullptr);\n    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();\n\n    \/\/ Only change once per interval\n    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)\n    {\n        if (params.fPowAllowMinDifficultyBlocks)\n        {\n            \/\/ Special difficulty rule for testnet:\n            \/\/ If the new block's timestamp is more than 2* 2.5 minutes\n            \/\/ then allow mining of a min-difficulty block.\n            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n                return nProofOfWorkLimit;\n            else\n            {\n                \/\/ Return the last non-special-min-difficulty-rules-block\n                const CBlockIndex* pindex = pindexLast;\n                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)\n                    pindex = pindex->pprev;\n                return pindex->nBits;\n            }\n        }\n        return pindexLast->nBits;\n    }\n\n    \/\/ Go back by what we want to be 1 day worth of blocks\n    int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1);\n    assert(nHeightFirst >= 0);\n    const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);\n    assert(pindexFirst);\n\n   return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);\n}\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n    assert(pindexLast != nullptr);\n    assert(pblock != nullptr);\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n\n    \/\/ this is only active on devnets\n    if (pindexLast->nHeight < params.nMinimumDifficultyBlocks) {\n        return bnPowLimit.GetCompact();\n    }\n\n    if (pindexLast->nHeight + 1 < params.nPowKGWHeight) {\n        return GetNextWorkRequiredBTC(pindexLast, pblock, params);\n    }\n\n    \/\/ Note: GetNextWorkRequiredBTC has it's own special difficulty rule,\n    \/\/ so we only apply this to post-BTC algos.\n    if (params.fPowAllowMinDifficultyBlocks) {\n        \/\/ recent block is more than 2 hours old\n        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + 2 * 60 * 60) {\n            return bnPowLimit.GetCompact();\n        }\n        \/\/ recent block is more than 10 minutes old\n        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing * 4) {\n            arith_uint256 bnNew = arith_uint256().SetCompact(pindexLast->nBits) * 10;\n            if (bnNew > bnPowLimit) {\n                return bnPowLimit.GetCompact();\n            }\n            return bnNew.GetCompact();\n        }\n    }\n\n    if (pindexLast->nHeight + 1 < params.nPowDGWHeight) {\n        return KimotoGravityWell(pindexLast, params);\n    }\n\n    return DarkGravityWave(pindexLast, params);\n}\n\n\/\/ for DIFF_BTC only!\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n    if (params.fPowNoRetargeting)\n        return pindexLast->nBits;\n\n    \/\/ Limit adjustment step\n    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;\n    if (nActualTimespan < params.nPowTargetTimespan\/4)\n        nActualTimespan = params.nPowTargetTimespan\/4;\n    if (nActualTimespan > params.nPowTargetTimespan*4)\n        nActualTimespan = params.nPowTargetTimespan*4;\n\n    \/\/ Retarget\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n    arith_uint256 bnNew;\n    bnNew.SetCompact(pindexLast->nBits);\n    bnNew *= nActualTimespan;\n    bnNew \/= params.nPowTargetTimespan;\n\n    if (bnNew > bnPowLimit)\n        bnNew = bnPowLimit;\n\n    return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n    bool fNegative;\n    bool fOverflow;\n    arith_uint256 bnTarget;\n\n    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n    \/\/ Check range\n    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n        return false;\n\n    \/\/ Check proof of work matches claimed amount\n    if (UintToArith256(hash) > bnTarget)\n        return false;\n\n    return true;\n}\n<|endoftext|>"}
{"text":"#ifndef VARIANT_HPP\n#define VARIANT_HPP\n\n#include \n#include \n#include \n#include \n\ntemplate class variant;\n\n\nnamespace impl {\n  template\n  struct select;\n\n  template\n  struct select : select {\n\n    using select::index;\n    static inline constexpr std::size_t index(const H* ) { return start; }\n\n    using select::cast;\n    static inline constexpr const H& cast(const H& value) { return value; }\n    static inline constexpr H&& cast(H&& value) { return std::move(value); }    \n    \n  };\n\n  \n  template struct select {\n    static inline constexpr void index();\n    static inline constexpr void cast();    \n  };\n\n\n  template\n  struct dispatch;\n\n  template\n  struct dispatch, Self, Ret (Visitor, Args...) > {\n  \n    template\n    static Ret call_thunk(Self& self, Visitor&& visitor, Args&& ... args) {\n      return std::forward(visitor)(self.template get(), std::forward(args)...);\n    }\n  \n    using thunk_type = Ret (*)(Self& self, Visitor&& visitor, Args&& ... args);\n    static constexpr thunk_type table[] = { call_thunk... };\n  };\n\n  template\n  constexpr typename dispatch, Self, Ret (Visitor, Args...) >::thunk_type\n  dispatch, Self, Ret (Visitor, Args...) >::table[];\n\n  \n}\n\n\n\n\ntemplate\nclass variant {\n\n  using storage_type = typename std::aligned_union<0, T...>::type;\n  storage_type storage;\n\nprotected:\n  using index_type = std::size_t;\n  index_type index;\n\nprivate:\n  \n  using select_type = impl::select<0, T...>;\n\n\n  template\n  void construct(U&& value) {\n    new (&storage) typename std::decay::type(std::forward(value));\n  }\n  \n  struct copy_construct {\n    template\n    void operator()(U& self, const variant& other) const {\n      new (&self) U(other.template get());\n    }\n  };\n\n\n  struct copy {\n    template\n    void operator()(U& self, const variant& other) const {\n      self = other.template get();\n    }\n  };\n\n\n  struct move {\n    template\n    void operator()(U& self, variant&& other) const {\n      self = std::move(other.template get());\n    }\n  };\n  \n  \n  struct move_construct {\n    template\n    void operator()(U& self, variant&& other) const {\n      new (&self) U(std::move(other.template get()));\n    }\n  };\n\n\n  \n  struct destruct {\n    template\n    void operator()(U& self) const {\n      self.~U();\n    }\n  };\n\n\n  struct compare {\n\n    template\n    bool operator()(const U& self, const variant& other) const {\n      return self == other.get();\n    }\n\n  };\n\n  struct less {\n\n    template\n    bool operator()(const U& self, const variant& other) const {\n      return self < other.get();\n    }\n     \n  };\n  \npublic:\n  std::size_t type() const { return index; }\n\n  struct bad_cast : std::runtime_error {\n    bad_cast() : std::runtime_error(\"bad_cast\") { }\n  };\n\n  template::type*)0) ) >\n  static constexpr index_type type_index() { return R; }\n  \n  template() >\n  U& cast() {\n    U& res = reinterpret_cast(storage);\n    if( R != index ) throw bad_cast();\n    return res;\n  }\n\n  \n  template() >\n  const U& cast() const {\n    const U& res = reinterpret_cast(storage);\n    if( R != index ) {\n      throw bad_cast();\n    }\n    return res;\n  }\n\n\n  template()>\n  U& get() {\n    U& res = reinterpret_cast(storage);\n    assert(R == index);\n    return res;\n  } \n\n\n  template() >\n  const U& get() const {\n    const U& res = reinterpret_cast(storage);\n    assert(R == index);\n    return res;\n  }\n  \n\n  template()>\n  U* get_if() {\n    if(!is()) return nullptr;\n    return &get();\n  } \n\n  template()>\n  const U* get_if() const {\n    if(!is()) return nullptr;\n    return &get();\n  } \n  \n  \n\n  \n  template() >\n  bool is() const noexcept {\n    return R == index;\n  }\n  \n  variant(const variant& other) noexcept \n    : index(other.index) {\n    static constexpr bool skip[] = {std::is_trivially_copy_constructible::value...};\n    \n    if(skip[index]) {\n      storage = other.storage;\n    } else {\n      apply( copy_construct(), other );\n    }\n  }\n\n  variant(variant&& other) noexcept\n    : index(other.index) {\n    static constexpr bool skip[] = {std::is_trivially_move_constructible::value...};\n    \n    if(skip[index]) {\n      storage = std::move(other.storage);\n    } else {\n      apply( move_construct(), std::move(other) );\n    }\n  }\n  \n  ~variant() noexcept {\n    static constexpr bool dont_skip[] = {!std::is_trivially_destructible::value...};\n    \n    if(dont_skip[index]) {\n      apply( destruct() );\n    }\n    \n  }\n\n\n  variant& operator=(const variant& other) noexcept {\n    if(index == other.index) {\n      apply(copy(), other);\n    } else {\n      this->~variant();\n      index = other.index;      \n      apply(copy_construct(), other);\n    }\n    \n    return *this;\n  }\n\n  bool operator==(const variant& other) const {\n    if(type() != other.type()) return false;\n    return map(compare(), other);\n  }\n\n  bool operator!=(const variant& other) const {\n    return !operator==(other);\n  }\n\n  \n  bool operator<(const variant& other) const {\n    return index < other.index || (index == other.index && map(less(), other));\n  }\n\n  \n  \n  variant& operator=(variant&& other)  noexcept{\n    \n    if(index == other.index) {\n      apply( move(), std::move(other) );\n    } else {\n      this->~variant();\n      index = other.index;\n      apply( move_construct(), std::move(other) );\n    }\n    \n    return *this;\n  }\n  \n  \n  template() >\n  variant(U&& value) noexcept\n    : index( R ) {\n    construct( select_type::cast( std::forward(value)) );\n  }\n\n\n  template\n  void apply(Visitor&& visitor, Args&& ... args) {\n\n    impl::dispatch::table[index]\n      (*this, std::forward(visitor), std::forward(args)...);\n    \n  }\n\n  template\n  void apply(Visitor&& visitor, Args&& ... args) const {\n\n    impl::dispatch::table[index]\n      (*this, std::forward(visitor), std::forward(args)...);\n\n    \n  }\n\n\n  template\n  Return map(Visitor&& visitor, Args&& ... args) const {\n\n    return impl::dispatch::table[index]\n      (*this, std::forward(visitor), std::forward(args)...);\n    \n  }\n\n\n};\n\n\n\n\n\n\n\n\n#endif\nvariant asserts yo#ifndef VARIANT_HPP\n#define VARIANT_HPP\n\n#include \n#include \n#include \n#include \n\ntemplate class variant;\n\n\nnamespace impl {\n  template\n  struct select;\n\n  template\n  struct select : select {\n\n    using select::index;\n    static inline constexpr std::size_t index(const H* ) { return start; }\n\n    using select::cast;\n    static inline constexpr const H& cast(const H& value) { return value; }\n    static inline constexpr H&& cast(H&& value) { return std::move(value); }    \n    \n  };\n\n  \n  template struct select {\n    static inline constexpr void index();\n    static inline constexpr void cast();    \n  };\n\n\n  template\n  struct dispatch;\n\n  template\n  struct dispatch, Self, Ret (Visitor, Args...) > {\n  \n    template\n    static Ret call_thunk(Self& self, Visitor&& visitor, Args&& ... args) {\n      return std::forward(visitor)(self.template get(), std::forward(args)...);\n    }\n  \n    using thunk_type = Ret (*)(Self& self, Visitor&& visitor, Args&& ... args);\n    static constexpr thunk_type table[] = { call_thunk... };\n  };\n\n  template\n  constexpr typename dispatch, Self, Ret (Visitor, Args...) >::thunk_type\n  dispatch, Self, Ret (Visitor, Args...) >::table[];\n\n\n  template\n  static bool check_type() {\n    assert((std::is_same::value) );\n    return std::is_same::value;\n  }\n\n  template\n  static bool check_type(std::size_t index) {\n    using type = bool (*)();\n    static const type expand[] = {\n      &check_type...\n    };\n\n    return expand[index]();\n  }\n}\n\n\n\n\ntemplate\nclass variant {\n\n  using storage_type = typename std::aligned_union<0, T...>::type;\n  storage_type storage;\n\nprotected:\n  using index_type = std::size_t;\n  index_type index;\n\nprivate:\n  \n  using select_type = impl::select<0, T...>;\n\n\n  template\n  void construct(U&& value) {\n    new (&storage) typename std::decay::type(std::forward(value));\n  }\n  \n  struct copy_construct {\n    template\n    void operator()(U& self, const variant& other) const {\n      new (&self) U(other.template get());\n    }\n  };\n\n\n  struct copy {\n    template\n    void operator()(U& self, const variant& other) const {\n      self = other.template get();\n    }\n  };\n\n\n  struct move {\n    template\n    void operator()(U& self, variant&& other) const {\n      self = std::move(other.template get());\n    }\n  };\n  \n  \n  struct move_construct {\n    template\n    void operator()(U& self, variant&& other) const {\n      new (&self) U(std::move(other.template get()));\n    }\n  };\n\n\n  \n  struct destruct {\n    template\n    void operator()(U& self) const {\n      self.~U();\n    }\n  };\n\n\n  struct compare {\n\n    template\n    bool operator()(const U& self, const variant& other) const {\n      return self == other.get();\n    }\n\n  };\n\n  struct less {\n\n    template\n    bool operator()(const U& self, const variant& other) const {\n      return self < other.get();\n    }\n     \n  };\n  \npublic:\n  std::size_t type() const { return index; }\n\n  struct bad_cast : std::runtime_error {\n    bad_cast() : std::runtime_error(\"bad_cast\") { }\n  };\n\n  template::type*)0) ) >\n  static constexpr index_type type_index() { return R; }\n  \n  template() >\n  U& cast() {\n    U& res = reinterpret_cast(storage);\n    if( R != index ) throw bad_cast();\n    return res;\n  }\n\n  \n  template() >\n  const U& cast() const {\n    const U& res = reinterpret_cast(storage);\n    if( R != index ) {\n      throw bad_cast();\n    }\n    return res;\n  }\n\n\n  template()>\n  U& get() {\n    U& res = reinterpret_cast(storage);\n    assert( (impl::check_type(index)) );\n    return res;\n  } \n\n\n  template() >\n  const U& get() const {\n    const U& res = reinterpret_cast(storage);\n    assert( (impl::check_type(index)) );    \n    return res;\n  }\n  \n\n  template()>\n  U* get_if() {\n    if(!is()) return nullptr;\n    return &get();\n  } \n\n  template()>\n  const U* get_if() const {\n    if(!is()) return nullptr;\n    return &get();\n  } \n  \n  \n\n  \n  template() >\n  bool is() const noexcept {\n    return R == index;\n  }\n  \n  variant(const variant& other) noexcept \n    : index(other.index) {\n    static constexpr bool skip[] = {std::is_trivially_copy_constructible::value...};\n    \n    if(skip[index]) {\n      storage = other.storage;\n    } else {\n      apply( copy_construct(), other );\n    }\n  }\n\n  variant(variant&& other) noexcept\n    : index(other.index) {\n    static constexpr bool skip[] = {std::is_trivially_move_constructible::value...};\n    \n    if(skip[index]) {\n      storage = std::move(other.storage);\n    } else {\n      apply( move_construct(), std::move(other) );\n    }\n  }\n  \n  ~variant() noexcept {\n    static constexpr bool dont_skip[] = {!std::is_trivially_destructible::value...};\n    \n    if(dont_skip[index]) {\n      apply( destruct() );\n    }\n    \n  }\n\n\n  variant& operator=(const variant& other) noexcept {\n    if(index == other.index) {\n      apply(copy(), other);\n    } else {\n      this->~variant();\n      index = other.index;      \n      apply(copy_construct(), other);\n    }\n    \n    return *this;\n  }\n\n  bool operator==(const variant& other) const {\n    if(type() != other.type()) return false;\n    return map(compare(), other);\n  }\n\n  bool operator!=(const variant& other) const {\n    return !operator==(other);\n  }\n\n  \n  bool operator<(const variant& other) const {\n    return index < other.index || (index == other.index && map(less(), other));\n  }\n\n  \n  \n  variant& operator=(variant&& other)  noexcept{\n    \n    if(index == other.index) {\n      apply( move(), std::move(other) );\n    } else {\n      this->~variant();\n      index = other.index;\n      apply( move_construct(), std::move(other) );\n    }\n    \n    return *this;\n  }\n  \n  \n  template() >\n  variant(U&& value) noexcept\n    : index( R ) {\n    construct( select_type::cast( std::forward(value)) );\n  }\n\n\n  template\n  void apply(Visitor&& visitor, Args&& ... args) {\n\n    impl::dispatch::table[index]\n      (*this, std::forward(visitor), std::forward(args)...);\n    \n  }\n\n  template\n  void apply(Visitor&& visitor, Args&& ... args) const {\n\n    impl::dispatch::table[index]\n      (*this, std::forward(visitor), std::forward(args)...);\n\n    \n  }\n\n\n  template\n  Return map(Visitor&& visitor, Args&& ... args) const {\n\n    return impl::dispatch::table[index]\n      (*this, std::forward(visitor), std::forward(args)...);\n    \n  }\n\n\n};\n\n\n\n\n\n\n\n\n#endif\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n#include \"map.h\"\n#include \"image.h\"\n#include \"world.h\"\n#include \n#include \n\n\/\/ returns chance of  over  roll\nbool roll(int die, int eye);\n\n\/\/ Constants\n#define CELL_LENGTH 16\n#define COL_TILE_DESIRED 7\n\nMap::Map()\n{\n}\n\nMap::~Map()\n{\n    delete platformImage;\n    delete potatoImage;\n    delete meatImage;\n    delete babyImage;\n    delete moneyImage;\n}\n\nvoid Map::loadImages() {\n    \/\/ TODO initialize into spritemaps\n    platformImage = new Image( World::getRenderer(), \"platform.png\");\n    potatoImage = new Image( World::getRenderer(), \"small_potatoes.png\");\n    meatImage = new Image( World::getRenderer(), \"Meatloaf.png\");\n    babyImage = new Image( World::getRenderer(), \"baby.png\");\n    moneyImage = new Image( World::getRenderer(), \"Money.png\");\n}\n\nvoid Map::init()\n{\n    \/\/ Load assets\n    loadImages();\n\n    cCol = std::ceil(World::getWidth() \/ CELL_LENGTH);\n    cRow = std::ceil(World::getHeight() \/ CELL_LENGTH);\n\n    \/\/ Initialize mapGrid, a representation of Grid\n    mapGrid = new MapItem*[cCol];\n\n    \/\/ Initialize into MAP_SKY\n    for (int i = 0; i < cCol; i++) {\n        mapGrid[i] = new MapItem[cRow];\n        for (int j = 0; j < cRow; j++) {\n            mapGrid[i][j] = MAP_SKY;\n        }\n    }\n\n    leftCol = 0;\n    CreateMap();\n    printMap();\n}\n\nvoid Map::CreateMap() {\n    for (int i = 1; i < cCol; i++) {\n        createColumn(i);\n    }\n}\n\nvoid Map::createColumn(int col) {\n    \/\/ Counting struct\n    ColCount scanInfo;\n    \/\/ Column to be examined.\n    int prevColumn = (col - 1) % cCol;\n    \/\/ Column to be written, in case we start a Barrier this time.\n    int nextColumn = (col + 1) % cCol;\n    \/\/ Current Column to be created.\n    int currColumn = col % cCol;\n\n    \/\/ Currently created Tile\n    int tileCount = 0;\n\n    \/\/ Clean up first.\n    cleanColumn(col);\n\n    scanColumn(prevColumn, scanInfo);\n\n    printCount(scanInfo);\n\n    for (int row = 0; row < cRow; row++) {\n        if (mapGrid[prevColumn][row] != MAP_SKY) {\n\n            \/\/ TODO set this Roll to be configurable\n            if (roll(7, 3)) {\n                if (mapGrid[prevColumn][row] == MAP_BARRIER_A) {\n                    mapGrid[currColumn][row] = MAP_BARRIER_B;\n                }\n                else if (mapGrid[prevColumn][row] == MAP_BARRIER_B) {\n                    mapGrid[currColumn][row] = MAP_BARRIER_A;\n                }\n\n                else {\n                    mapGrid[currColumn][row] = mapGrid[prevColumn][row];\n                }\n                tileCount++;\n            }\n        }\n    }\n\n    \/\/ If this column has not enough tiles, give it another shot.\n    for( ;tileCount < COL_TILE_DESIRED; tileCount++) {\n        MapItem *newTile;\n\n        \/\/ TODO set this Roll to be configurable\n        if (roll(7, 5)) {\n            newTile = &mapGrid[currColumn][rand() % cRow];\n            if (*newTile == MAP_SKY) {\n                *newTile = MapItem(rand() % ITEM_KIND);\n\n                \/\/ Not gonna bother with retroactive barriering.\n                if (*newTile == MAP_BARRIER_B) {\n                    *newTile = MAP_SKY;\n                }\n            }\n        }\n    }\n}\n\nvoid Map::scanColumn(int col, ColCount &result) {\n    for (int i = 0; i < ITEM_KIND; i++) {\n        result.count[i] = 0;\n    }\n    for (int row = 0; row < cRow; row++) {\n        result.count[mapGrid[col][row]]++;\n    }\n    result.non_sky = cCol - result.count[MAP_SKY];\n}\n\nvoid Map::cleanColumn(int col) {\n    \/\/ Column to be written, in case we start a Barrier this time.\n    int nextCol = (col + 1) % cCol;\n\n    for (int row = 0; row < cRow; row++) {\n        \/\/ If BARRIER_A, then clean the next part as well.\n        if (mapGrid[col][row] == MAP_BARRIER_A) {\n            mapGrid[nextCol][row] = MAP_SKY;\n        }\n        \/\/ If BARRIER_B, leave it alone; we don't want to be cleaning up first half.\n        if (mapGrid[col][row] != MAP_BARRIER_B) {\n            mapGrid[col][row] = MAP_SKY;\n        }\n    }\n}\n\nvoid Map::newGame()\n{\n    printf(\"Map: New Game Init\\n\");\n}\n\n\/\/ Compute where at what screen coordinate the Grid Cell must be drawn.\nvoid Map::gridToScreen(int gridX, int gridY, int &screenX, int &screenY) {\n    \/\/ Nominal - \"original\" location of the grid; i.e., without any offset.\n    float nominalX, nominalY;\n    \/\/ Adjusted - location of the draw after the alignment to current location.\n    float adjustedX, adjustedY;\n    nominalX = gridX * 16.0f;\n    nominalY = gridY * 16.0f;\n\n    \/\/ For now;\n    adjustedX = nominalX * 1.0f;\n    adjustedY = nominalY * 1.0f;\n\n    World::worldToScreen(adjustedX, adjustedY, screenX, screenY);\n}\n\nvoid Map::draw(SDL_Renderer *renderer)\n{\n    Image *toDraw;\n    int screenX, screenY;\n\n    for (int x = 0; x < cCol; x++) {\n        for (int y = 0; y < cRow; y++) {\n            switch (mapGrid[x][y]) {\n                \/\/ Collectible\n                case MAP_BARRIER_A:\n                    toDraw = platformImage;\n                    break;\n                case MAP_POTATO:\n                    toDraw = potatoImage;\n                    break;\n                case MAP_MONEY:\n                    toDraw = moneyImage;\n                    break;\n                case MAP_MEATLOAF:\n                    toDraw = meatImage;\n                    break;\n\n                    \/\/ Animation\n                case MAP_SIGN:\n                case MAP_WHITESTART:\n                case MAP_REDSTAR:\n                case MAP_BLUESTAR:\n                    break;\n\n                    \/\/ SKY\n                default:\n                    toDraw = NULL;\n                    break;\n            }\n\n            \/\/kgridToScreen(int gridX, int gridY, int &screenX, int &screenY);\n            gridToScreen(x, y, screenX, screenY);\n\n\n            \/\/printf(\"%d, %d\\n\", screenX, screenY);\n            if (toDraw != NULL) {\n                toDraw->draw(renderer, screenX, screenY);\n            }\n        }\n    }\n}\n\nvoid Map::update(int elapsed) { \n    \/\/ data structure - this is a case where a linked list(vector?) would work\n\n    \/\/ TODO 1. shift horizontally\n    \/\/ TODO 2. determine if still in display\n    \/\/ TODO 3. dispose\n}\n\nint Map::collide(int x,int y,int w,int h)\n{\n    return MAP_SKY;\n}\n\nint Map::collect(int x,int y,int w,int h)\n{\n\n    return 0;\n}\n\/\/ Console Print\nvoid Map::printMap() {\n    printf(\"cCol: %d, cRow: %d\\n\", cCol, cRow);\n    for (int i = 0; i < cRow; i++) {\n        printf(\"[\");\n        for (int j = 0; j < cCol; j++) {\n            printf(\" %d \", mapGrid[j][i]);\n        }\n        printf(\"]\\n\");\n    }\n}\n\n\/\/ Console Print\nvoid Map::printCount(ColCount &c) {\n    printf(\"[\");\n    for (int i = 0; i < ITEM_KIND; i++) {\n        printf(\" %d \", c.count[i]);\n    }\n    printf(\"]\\n\");\n}\n\n\/\/ Helper function: returns true for eye \/ die.\nbool roll(int die, int eye) {\n    return std::rand() % die < eye;\n}\n\n\nshifting map to left in constant speed(not yet waiting for elapsed time)#include \n#include \n#include \n#include \n#include \"map.h\"\n#include \"image.h\"\n#include \"world.h\"\n#include \n#include \n\n\/\/ returns chance of  over  roll\nbool roll(int die, int eye);\n\n#define CELL_LENGTH 16\n#define COL_TILE_DESIRED 7\n#define TRUMP_SPEED 0.7f\n\nMap::Map()\n{\n}\n\nMap::~Map()\n{\n    delete platformImage;\n    delete potatoImage;\n    delete meatImage;\n    delete babyImage;\n    delete moneyImage;\n}\n\nvoid Map::loadImages() {\n    \/\/ TODO initialize into spritemaps\n    platformImage = new Image( World::getRenderer(), \"platform.png\");\n    potatoImage = new Image( World::getRenderer(), \"small_potatoes.png\");\n    meatImage = new Image( World::getRenderer(), \"Meatloaf.png\");\n    babyImage = new Image( World::getRenderer(), \"baby.png\");\n    moneyImage = new Image( World::getRenderer(), \"Money.png\");\n}\n\nvoid Map::init()\n{\n    \/\/ Load assets\n    loadImages();\n\n    cCol = std::ceil(World::getWidth() \/ CELL_LENGTH);\n    cRow = std::ceil(World::getHeight() \/ CELL_LENGTH);\n\n    \/\/ Initialize mapGrid, a representation of Grid\n    mapGrid = new MapItem*[cCol];\n\n    \/\/ Initialize into MAP_SKY\n    for (int i = 0; i < cCol; i++) {\n        mapGrid[i] = new MapItem[cRow];\n        for (int j = 0; j < cRow; j++) {\n            mapGrid[i][j] = MAP_SKY;\n        }\n    }\n\n    leftCol = 0;\n    CreateMap();\n    printMap();\n}\n\nvoid Map::CreateMap() {\n    for (int i = 1; i < cCol; i++) {\n        createColumn(i);\n    }\n}\n\nvoid Map::createColumn(int col) {\n    \/\/ Counting struct\n    ColCount scanInfo;\n    \/\/ Column to be examined.\n    int prevColumn = (col - 1) % cCol;\n    \/\/ Column to be written, in case we start a Barrier this time.\n    int nextColumn = (col + 1) % cCol;\n    \/\/ Current Column to be created.\n    int currColumn = col % cCol;\n\n    \/\/ Currently created Tile\n    int tileCount = 0;\n\n    \/\/ Clean up first.\n    cleanColumn(col);\n\n    scanColumn(prevColumn, scanInfo);\n\n    printCount(scanInfo);\n\n    for (int row = 0; row < cRow; row++) {\n        if (mapGrid[prevColumn][row] != MAP_SKY) {\n\n            \/\/ TODO set this Roll to be configurable\n            if (roll(7, 3)) {\n                if (mapGrid[prevColumn][row] == MAP_BARRIER_A) {\n                    mapGrid[currColumn][row] = MAP_BARRIER_B;\n                }\n                else if (mapGrid[prevColumn][row] == MAP_BARRIER_B) {\n                    mapGrid[currColumn][row] = MAP_BARRIER_A;\n                }\n\n                else {\n                    mapGrid[currColumn][row] = mapGrid[prevColumn][row];\n                }\n                tileCount++;\n            }\n        }\n    }\n\n    \/\/ If this column has not enough tiles, give it another shot.\n    for( ;tileCount < COL_TILE_DESIRED; tileCount++) {\n        MapItem *newTile;\n\n        \/\/ TODO set this Roll to be configurable\n        if (roll(7, 5)) {\n            newTile = &mapGrid[currColumn][rand() % cRow];\n            if (*newTile == MAP_SKY) {\n                *newTile = MapItem(rand() % ITEM_KIND);\n\n                \/\/ Not gonna bother with retroactive barriering.\n                if (*newTile == MAP_BARRIER_B) {\n                    *newTile = MAP_SKY;\n                }\n            }\n        }\n    }\n}\n\nvoid Map::scanColumn(int col, ColCount &result) {\n    for (int i = 0; i < ITEM_KIND; i++) {\n        result.count[i] = 0;\n    }\n    for (int row = 0; row < cRow; row++) {\n        result.count[mapGrid[col][row]]++;\n    }\n    result.non_sky = cCol - result.count[MAP_SKY];\n}\n\nvoid Map::cleanColumn(int col) {\n    \/\/ Column to be written, in case we start a Barrier this time.\n    int nextCol = (col + 1) % cCol;\n\n    for (int row = 0; row < cRow; row++) {\n        \/\/ If BARRIER_A, then clean the next part as well.\n        if (mapGrid[col][row] == MAP_BARRIER_A) {\n            mapGrid[nextCol][row] = MAP_SKY;\n        }\n        \/\/ If BARRIER_B, leave it alone; we don't want to be cleaning up first half.\n        if (mapGrid[col][row] != MAP_BARRIER_B) {\n            mapGrid[col][row] = MAP_SKY;\n        }\n    }\n}\n\nvoid Map::newGame()\n{\n    printf(\"Map: New Game Init\\n\");\n}\n\n\/\/ Compute where at what screen coordinate the Grid Cell must be drawn.\nvoid Map::gridToScreen(int gridX, int gridY, int &screenX, int &screenY) {\n    \/\/ Nominal - \"original\" location of the grid; i.e., without any offset.\n    float nominalX, nominalY;\n    \/\/ Adjusted - location of the draw after the alignment to current location.\n    float adjustedX, adjustedY;\n    nominalX = gridX * 16.0f;\n    nominalY = gridY * 16.0f;\n\n    \/\/ For now;\n    adjustedX = (nominalX - left) * 1.0f;\n    adjustedY = nominalY * 1.0f;\n\n    if (gridX == 1 && gridY == 1) {\n        printf(\"%f, %f\\n\", adjustedX, adjustedY);\n    }\n\n    World::worldToScreen(adjustedX, adjustedY, screenX, screenY);\n}\n\nvoid Map::draw(SDL_Renderer *renderer)\n{\n    Image *toDraw;\n    int screenX, screenY;\n\n    for (int x = 0; x < cCol; x++) {\n        for (int y = 0; y < cRow; y++) {\n            switch (mapGrid[x][y]) {\n                \/\/ Collectible\n                case MAP_BARRIER_A:\n                    toDraw = platformImage;\n                    break;\n                case MAP_POTATO:\n                    toDraw = potatoImage;\n                    break;\n                case MAP_MONEY:\n                    toDraw = moneyImage;\n                    break;\n                case MAP_MEATLOAF:\n                    toDraw = meatImage;\n                    break;\n\n                    \/\/ Animation\n                case MAP_SIGN:\n                case MAP_WHITESTART:\n                case MAP_REDSTAR:\n                case MAP_BLUESTAR:\n                    break;\n\n                    \/\/ SKY\n                default:\n                    toDraw = NULL;\n                    break;\n            }\n\n            \/\/kgridToScreen(int gridX, int gridY, int &screenX, int &screenY);\n            gridToScreen(x, y, screenX, screenY);\n\n\n            \/\/printf(\"%d, %d\\n\", screenX, screenY);\n            if (toDraw != NULL) {\n                toDraw->draw(renderer, screenX, screenY);\n            }\n        }\n    }\n}\n\nvoid Map::update(int elapsed) { \n    \/\/ 1. Shift horizontally.\n    left += TRUMP_SPEED;\n\n\n    \/\/ data structure - this is a case where a linked list(vector?) would work\n\n    \/\/ TODO 1. shift horizontally\n    \/\/ TODO 2. determine if still in display\n    \/\/ TODO 3. dispose\n}\n\nint Map::collide(int x,int y,int w,int h)\n{\n    return MAP_SKY;\n}\n\nint Map::collect(int x,int y,int w,int h)\n{\n\n    return 0;\n}\n\/\/ Console Print\nvoid Map::printMap() {\n    printf(\"cCol: %d, cRow: %d\\n\", cCol, cRow);\n    for (int i = 0; i < cRow; i++) {\n        printf(\"[\");\n        for (int j = 0; j < cCol; j++) {\n            printf(\" %d \", mapGrid[j][i]);\n        }\n        printf(\"]\\n\");\n    }\n}\n\n\/\/ Console Print\nvoid Map::printCount(ColCount &c) {\n    printf(\"[\");\n    for (int i = 0; i < ITEM_KIND; i++) {\n        printf(\" %d \", c.count[i]);\n    }\n    printf(\"]\\n\");\n}\n\n\/\/ Helper function: returns true for eye \/ die.\nbool roll(int die, int eye) {\n    return std::rand() % die < eye;\n}\n\n\n<|endoftext|>"}
{"text":"\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#ifdef _WIN32\n#include \n#else\n#include \n#endif\n\n#include \n\n#include \"ngraph\/file_util.hpp\"\n#include \"ngraph\/runtime\/backend.hpp\"\n#include \"ngraph\/runtime\/backend_manager.hpp\"\n#include \"ngraph\/runtime\/interpreter\/static_initialize.hpp\"\n#include \"ngraph\/util.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\n#ifdef _WIN32\n#define CLOSE_LIBRARY(a) FreeLibrary(a)\n#define DLSYM(a, b) GetProcAddress(a, b)\n#else\n#define CLOSE_LIBRARY(a) dlclose(a)\n#define DLSYM(a, b) dlsym(a, b)\n#endif\n\nunordered_map& runtime::BackendManager::get_registry()\n{\n    static unordered_map s_registered_backend;\n    static bool s_static_initialization_called = false;\n    if (!s_static_initialization_called)\n    {\n        s_static_initialization_called = true;\n#ifdef INTERPRETER_BACKEND_STATIC\n        runtime::interpreter::static_initialize();\n#endif\n    }\n    return s_registered_backend;\n}\n\nvoid runtime::BackendManager::register_backend(const string& name, BackendConstructor* new_backend)\n{\n    get_registry()[name] = new_backend;\n}\n\nvector runtime::BackendManager::get_registered_backends()\n{\n    vector rc;\n    for (const auto& p : get_registry())\n    {\n        rc.push_back(p.first);\n    }\n    for (const auto& p : get_registered_device_map())\n    {\n        if (find(rc.begin(), rc.end(), p.first) == rc.end())\n        {\n            rc.push_back(p.first);\n        }\n    }\n    return rc;\n}\n\nshared_ptr runtime::BackendManager::create_backend(const std::string& config)\n{\n    shared_ptr backend;\n    string type = config;\n\n    \/\/ strip off attributes, IE:CPU becomes IE\n    auto colon = type.find(\":\");\n    if (colon != type.npos)\n    {\n        type = type.substr(0, colon);\n    }\n\n    auto registry = get_registry();\n    auto it = registry.find(type);\n    for (auto x : registry)\n    {\n        NGRAPH_INFO << x.first;\n    }\n    if (it != registry.end())\n    {\n        BackendConstructor* new_backend = it->second;\n        backend = new_backend->create(config);\n    }\n    else\n    {\n        DL_HANDLE handle = open_shared_library(type);\n        if (!handle)\n        {\n            stringstream ss;\n            ss << \"Backend '\" << type << \"' not registered. Error:\";\n#ifndef _WIN32\n            ss << dlerror();\n#endif\n            throw runtime_error(ss.str());\n        }\n\n#ifndef _WIN32\n        dlerror(); \/\/ Clear any pending errors\n#endif\n        function get_backend_constructor_pointer =\n            reinterpret_cast(\n                DLSYM(handle, \"get_backend_constructor_pointer\"));\n        if (get_backend_constructor_pointer)\n        {\n            backend = get_backend_constructor_pointer()->create(config);\n        }\n        else\n        {\n            string error;\n#ifndef _WIN32\n            const char* err = dlerror();\n            error = (err ? err : \"\");\n#endif\n            CLOSE_LIBRARY(handle);\n            throw runtime_error(\n                \"Failed to find symbol 'get_backend_constructor_pointer' in backend \"\n                \"library.\\nError='\" +\n                error + \"'\");\n        }\n    }\n    return backend;\n}\n\n\/\/ This doodad finds the full path of the containing shared library\nstatic string find_my_file()\n{\n#ifdef _WIN32\n    HMODULE hModule = GetModuleHandleW(L\"ngraph.dll\");\n    WCHAR wpath[MAX_PATH];\n    GetModuleFileNameW(hModule, wpath, MAX_PATH);\n    wstring ws(wpath);\n    string path(ws.begin(), ws.end());\n    replace(path.begin(), path.end(), '\\\\', '\/');\n    path = file_util::get_directory(path);\n    path += \"\/\";\n    return path;\n#else\n    Dl_info dl_info;\n    dladdr(reinterpret_cast(find_my_file), &dl_info);\n    return dl_info.dli_fname;\n#endif\n}\n\nDL_HANDLE runtime::BackendManager::open_shared_library(string type)\n{\n    string lib_prefix = SHARED_LIB_PREFIX;\n    string lib_suffix = SHARED_LIB_SUFFIX;\n\n    DL_HANDLE handle = nullptr;\n\n    \/\/ strip off attributes, IE:CPU becomes IE\n    auto colon = type.find(\":\");\n    if (colon != type.npos)\n    {\n        type = type.substr(0, colon);\n    }\n\n    string library_name = lib_prefix + to_lower(type) + \"_backend\" + lib_suffix;\n    string my_directory = file_util::get_directory(find_my_file());\n    string library_path = file_util::path_join(my_directory, library_name);\n    string error;\n#ifdef _WIN32\n    SetDllDirectory((LPCSTR)my_directory.c_str());\n    handle = LoadLibrary(library_path.c_str());\n#else\n    dlerror(); \/\/ Clear any pending errors\n    handle = dlopen(library_path.c_str(), RTLD_NOW | RTLD_GLOBAL);\n    const char* err = dlerror();\n    error = (err ? err : \"\");\n#endif\n    if (!handle)\n    {\n        stringstream ss;\n        ss << \"Unable to find backend '\" << type << \"' as file '\" << library_path << \"'\";\n        ss << \"\\nOpen error message '\" << error << \"'\";\n        throw runtime_error(ss.str());\n    }\n    return handle;\n}\n\nmap runtime::BackendManager::get_registered_device_map()\n{\n    map rc;\n    string my_directory = file_util::get_directory(find_my_file());\n    vector backend_list;\n\n    auto f = [&](const string& file, bool is_dir) {\n        if (!is_dir)\n        {\n            string name = file_util::get_file_name(file);\n            string backend_name;\n            if (is_backend_name(name, backend_name))\n            {\n                rc.insert({to_upper(backend_name), file});\n            }\n        }\n    };\n    file_util::iterate_files(my_directory, f, false, true);\n    return rc;\n}\n\nbool runtime::BackendManager::is_backend_name(const string& file, string& backend_name)\n{\n    bool rc = false;\n    string name = file_util::get_file_name(file);\n    string lib_prefix = SHARED_LIB_PREFIX;\n    string lib_suffix = SHARED_LIB_SUFFIX;\n    if ((name.size() > lib_prefix.size() + lib_suffix.size()) &\n        !name.compare(0, lib_prefix.size(), lib_prefix))\n    {\n        if (!name.compare(name.size() - lib_suffix.size(), lib_suffix.size(), lib_suffix))\n        {\n            auto pos = name.find(\"_backend\");\n            if (pos != name.npos)\n            {\n                backend_name = name.substr(lib_prefix.size(), pos - lib_prefix.size());\n                rc = true;\n            }\n        }\n    }\n    return rc;\n}\noptimization for creating backend\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#ifdef _WIN32\n#include \n#else\n#include \n#endif\n\n#include \n\n#include \"ngraph\/file_util.hpp\"\n#include \"ngraph\/runtime\/backend.hpp\"\n#include \"ngraph\/runtime\/backend_manager.hpp\"\n#include \"ngraph\/runtime\/interpreter\/static_initialize.hpp\"\n#include \"ngraph\/util.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\n#ifdef _WIN32\n#define CLOSE_LIBRARY(a) FreeLibrary(a)\n#define DLSYM(a, b) GetProcAddress(a, b)\n#else\n#define CLOSE_LIBRARY(a) dlclose(a)\n#define DLSYM(a, b) dlsym(a, b)\n#endif\n\nunordered_map& runtime::BackendManager::get_registry()\n{\n    static unordered_map s_registered_backend;\n    static bool s_static_initialization_called = false;\n    if (!s_static_initialization_called)\n    {\n        s_static_initialization_called = true;\n#ifdef INTERPRETER_BACKEND_STATIC\n        runtime::interpreter::static_initialize();\n#endif\n    }\n    return s_registered_backend;\n}\n\nvoid runtime::BackendManager::register_backend(const string& name, BackendConstructor* new_backend)\n{\n    get_registry()[name] = new_backend;\n}\n\nvector runtime::BackendManager::get_registered_backends()\n{\n    vector rc;\n    for (const auto& p : get_registry())\n    {\n        rc.push_back(p.first);\n    }\n    for (const auto& p : get_registered_device_map())\n    {\n        if (find(rc.begin(), rc.end(), p.first) == rc.end())\n        {\n            rc.push_back(p.first);\n        }\n    }\n    return rc;\n}\n\nshared_ptr runtime::BackendManager::create_backend(const std::string& config)\n{\n    shared_ptr backend;\n    string type = config;\n\n    \/\/ strip off attributes, IE:CPU becomes IE\n    auto colon = type.find(\":\");\n    if (colon != type.npos)\n    {\n        type = type.substr(0, colon);\n    }\n\n    auto registry = get_registry();\n    auto it = registry.find(type);\n    \/\/ for (auto x : registry)\n    \/\/ {\n    \/\/     NGRAPH_INFO << x.first;\n    \/\/ }\n    if (it != registry.end())\n    {\n        BackendConstructor* new_backend = it->second;\n        backend = new_backend->create(config);\n    }\n    else\n    {\n        \/\/ NGRAPH_INFO << \"open\";\n        DL_HANDLE handle = open_shared_library(type);\n        if (!handle)\n        {\n            stringstream ss;\n            ss << \"Backend '\" << type << \"' not registered. Error:\";\n#ifndef _WIN32\n            ss << dlerror();\n#endif\n            throw runtime_error(ss.str());\n        }\n\n#ifndef _WIN32\n        dlerror(); \/\/ Clear any pending errors\n#endif\n        function get_backend_constructor_pointer =\n            reinterpret_cast(\n                DLSYM(handle, \"get_backend_constructor_pointer\"));\n        if (get_backend_constructor_pointer)\n        {\n            backend = get_backend_constructor_pointer()->create(config);\n            register_backend(type, get_backend_constructor_pointer());\n        }\n        else\n        {\n            string error;\n#ifndef _WIN32\n            const char* err = dlerror();\n            error = (err ? err : \"\");\n#endif\n            CLOSE_LIBRARY(handle);\n            throw runtime_error(\n                \"Failed to find symbol 'get_backend_constructor_pointer' in backend \"\n                \"library.\\nError='\" +\n                error + \"'\");\n        }\n    }\n    return backend;\n}\n\n\/\/ This doodad finds the full path of the containing shared library\nstatic string find_my_file()\n{\n#ifdef _WIN32\n    HMODULE hModule = GetModuleHandleW(L\"ngraph.dll\");\n    WCHAR wpath[MAX_PATH];\n    GetModuleFileNameW(hModule, wpath, MAX_PATH);\n    wstring ws(wpath);\n    string path(ws.begin(), ws.end());\n    replace(path.begin(), path.end(), '\\\\', '\/');\n    path = file_util::get_directory(path);\n    path += \"\/\";\n    return path;\n#else\n    Dl_info dl_info;\n    dladdr(reinterpret_cast(find_my_file), &dl_info);\n    return dl_info.dli_fname;\n#endif\n}\n\nDL_HANDLE runtime::BackendManager::open_shared_library(string type)\n{\n    string lib_prefix = SHARED_LIB_PREFIX;\n    string lib_suffix = SHARED_LIB_SUFFIX;\n\n    DL_HANDLE handle = nullptr;\n\n    \/\/ strip off attributes, IE:CPU becomes IE\n    auto colon = type.find(\":\");\n    if (colon != type.npos)\n    {\n        type = type.substr(0, colon);\n    }\n\n    string library_name = lib_prefix + to_lower(type) + \"_backend\" + lib_suffix;\n    string my_directory = file_util::get_directory(find_my_file());\n    string library_path = file_util::path_join(my_directory, library_name);\n    string error;\n#ifdef _WIN32\n    SetDllDirectory((LPCSTR)my_directory.c_str());\n    handle = LoadLibrary(library_path.c_str());\n#else\n    dlerror(); \/\/ Clear any pending errors\n    handle = dlopen(library_path.c_str(), RTLD_NOW | RTLD_GLOBAL);\n    const char* err = dlerror();\n    error = (err ? err : \"\");\n#endif\n    if (!handle)\n    {\n        stringstream ss;\n        ss << \"Unable to find backend '\" << type << \"' as file '\" << library_path << \"'\";\n        ss << \"\\nOpen error message '\" << error << \"'\";\n        throw runtime_error(ss.str());\n    }\n    return handle;\n}\n\nmap runtime::BackendManager::get_registered_device_map()\n{\n    map rc;\n    string my_directory = file_util::get_directory(find_my_file());\n    vector backend_list;\n\n    auto f = [&](const string& file, bool is_dir) {\n        if (!is_dir)\n        {\n            string name = file_util::get_file_name(file);\n            string backend_name;\n            if (is_backend_name(name, backend_name))\n            {\n                rc.insert({to_upper(backend_name), file});\n            }\n        }\n    };\n    file_util::iterate_files(my_directory, f, false, true);\n    return rc;\n}\n\nbool runtime::BackendManager::is_backend_name(const string& file, string& backend_name)\n{\n    bool rc = false;\n    string name = file_util::get_file_name(file);\n    string lib_prefix = SHARED_LIB_PREFIX;\n    string lib_suffix = SHARED_LIB_SUFFIX;\n    if ((name.size() > lib_prefix.size() + lib_suffix.size()) &\n        !name.compare(0, lib_prefix.size(), lib_prefix))\n    {\n        if (!name.compare(name.size() - lib_suffix.size(), lib_suffix.size(), lib_suffix))\n        {\n            auto pos = name.find(\"_backend\");\n            if (pos != name.npos)\n            {\n                backend_name = name.substr(lib_prefix.size(), pos - lib_prefix.size());\n                rc = true;\n            }\n        }\n    }\n    return rc;\n}\n<|endoftext|>"}
{"text":"\/*******************************************************************************\n * This file is part of \"Patrick's Programming Library\", Version 7 (PPL7).\n * Web: http:\/\/www.pfp.de\/ppl\/\n *\n *******************************************************************************\n * Copyright (c) 2022, Patrick Fedick \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *    1. Redistributions of source code must retain the above copyright notice, this\n *       list of conditions and the following disclaimer.\n *    2. Redistributions in binary form must reproduce the above copyright notice,\n *       this list of conditions and the following disclaimer in the documentation\n *       and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n *******************************************************************************\/\n\n#include \"prolog_ppl7.h\"\n\n#ifdef HAVE_STDIO_H\n#include \n#endif\n#ifdef HAVE_STDLIB_H\n#include \n#endif\n#ifdef HAVE_STRING_H\n#include \n#endif\n#ifdef HAVE_STDARG_H\n#include \n#endif\n\n#include \"ppl7.h\"\n#include \"ppl7-grafix.h\"\n#include \"ppl7-tk.h\"\n\nnamespace ppl7::tk {\n\n\nAbstractSpinBox::AbstractSpinBox()\n{\n    up_button=NULL;\n    down_button=NULL;\n    text_input=NULL;\n    createUi();\n}\n\nAbstractSpinBox::~AbstractSpinBox()\n{\n    if (text_input) delete text_input;\n    if (up_button) delete up_button;\n    if (down_button) delete down_button;\n}\n\nAbstractSpinBox::AbstractSpinBox(int x, int y, int width, int height, const String& text)\n{\n    create(x, y, width, height);\n    up_button=NULL;\n    down_button=NULL;\n    text_input=NULL;\n    createUi();\n    resizeUi();\n    text_input->setText(text);\n}\n\nvoid AbstractSpinBox::createUi()\n{\n    Grafix* gfx=GetGrafix();\n    text_input=new LineInput();\n    text_input->setEventHandler(this);\n    addChild(text_input);\n    up_button=new Button();\n    up_button->setEventHandler(this);\n    addChild(up_button);\n    down_button=new Button();\n    down_button->setEventHandler(this);\n    addChild(down_button);\n    if (gfx) {\n        const WidgetStyle& style=GetWidgetStyle();\n        img_up=gfx->ButtonSymbolsSmall.getDrawable(3, style.buttonSymbolColor);\n        img_down=gfx->ButtonSymbolsSmall.getDrawable(4, style.buttonSymbolColor);\n        up_button->setIcon(img_up);\n        down_button->setIcon(img_down);\n    }\n}\n\nvoid AbstractSpinBox::resizeUi()\n{\n    Rect client=this->clientRect();\n    text_input->setSize(client.width() - 25, client.height());\n    text_input->setPos(client.left(), client.top());\n\n    up_button->setSize(25, client.height() \/ 2);\n    up_button->setPos(client.width() - 25, client.top());\n\n    down_button->setSize(25, client.height() \/ 2);\n    down_button->setPos(client.width() - 25, client.top() + client.height() \/ 2);\n}\n\nconst Color& AbstractSpinBox::color() const\n{\n    return text_input->color();\n}\n\nvoid AbstractSpinBox::setColor(const Color& c)\n{\n    text_input->setColor(c);\n}\n\nconst Font& AbstractSpinBox::font() const\n{\n    return text_input->font();\n}\n\nvoid AbstractSpinBox::setFont(const Font& font)\n{\n    text_input->setFont(font);\n}\n\nvoid AbstractSpinBox::setText(const String& value)\n{\n    text_input->setText(value);\n    Event new_event(Event::TextChanged);\n    new_event.setWidget(this);\n    EventHandler::textChangedEvent(&new_event, value);\n}\n\nString AbstractSpinBox::text() const\n{\n    return String(text_input->text());\n}\n\nString AbstractSpinBox::widgetType() const\n{\n    return \"AbstractSpinBox\";\n}\n\n\n\nvoid AbstractSpinBox::debugEvent(const ppl7::String& name, Event* event)\n{\n    return;\n    Widget* w=event->widget();\n    ppl7::String wname=\"unknown\";\n    if (w == this) wname=\"AbstractSpinBox\";\n    else if (w == up_button) wname=\"UpButton\";\n    else if (w == down_button) wname=\"DownButton\";\n    else if (w == text_input) wname=\"TextInput\";\n\n    printf(\"Event [%s]: %s\\n\", (const char*)wname, (const char*)name);\n\n}\n\nvoid AbstractSpinBox::setInputValidator(InputValidator* validator)\n{\n    text_input->setInputValidator(validator);\n}\n\nvoid AbstractSpinBox::paint(Drawable& draw)\n{\n\n}\n\nvoid AbstractSpinBox::mouseDownEvent(MouseEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::mouseDownEvent\", event);\n    Widget* w=event->widget();\n    if (w == up_button) stepUp();\n    else if (w == down_button) stepDown();\n    GetWindowManager()->setKeyboardFocus(text_input);\n\n}\n\nvoid AbstractSpinBox::gotFocusEvent(FocusEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::gotFocusEvent\", event);\n    GetWindowManager()->setKeyboardFocus(text_input);\n}\n\nvoid AbstractSpinBox::lostFocusEvent(FocusEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::lostFocusEvent\", event);\n}\n\nvoid AbstractSpinBox::textInputEvent(TextInputEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::textInputEvent\", event);\n}\n\nvoid AbstractSpinBox::keyDownEvent(KeyEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::keyDownEvent\", event);\n    KeyEvent new_event=*event;\n    new_event.setWidget(this);\n    EventHandler::keyDownEvent(&new_event);\n}\n\nvoid AbstractSpinBox::keyUpEvent(KeyEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::keyUpEvent\", event);\n}\n\nvoid AbstractSpinBox::textChangedEvent(Event* event, const String& text)\n{\n    debugEvent(\"AbstractSpinBox::textChangedEvent\", event);\n    Event new_event=*event;\n    new_event.setWidget(this);\n    EventHandler::textChangedEvent(&new_event, text);\n}\n\n\nSpinBox::SpinBox()\n{\n    my_value=0;\n    step_size=1;\n    min=0;\n    max=0;\n    setInputValidator(this);\n}\n\nSpinBox::SpinBox(int x, int y, int width, int height, int64_t value)\n    :AbstractSpinBox(x, y, width, height)\n{\n    my_value=0;\n    step_size=1;\n    min=0;\n    max=0;\n    setInputValidator(this);\n    if (value < min) min=value;\n    if (value > max) max=value;\n    setValue(value);\n}\n\nString SpinBox::widgetType() const\n{\n    return \"SpinBox\";\n}\n\nvoid SpinBox::setValue(int64_t value)\n{\n    if (valuemax) return;\n    my_value=value;\n    setText(ppl7::ToString(\"%ld\", value));\n}\n\nint64_t SpinBox::value() const\n{\n    return text().toInt64();\n}\n\nvoid SpinBox::setMinimum(int64_t value)\n{\n    min=value;\n    if (my_value < min) my_value=min;\n}\n\nvoid SpinBox::setMaximum(int64_t value)\n{\n    max=value;\n    if (my_value > max) my_value=max;\n}\n\nvoid SpinBox::setLimits(int64_t min, int64_t max)\n{\n    setMinimum(min);\n    setMaximum(max);\n}\n\nint64_t SpinBox::minimum() const\n{\n    return min;\n}\n\nint64_t SpinBox::maximum() const\n{\n    return max;\n}\n\nvoid SpinBox::setStepSize(int64_t value)\n{\n    step_size=value;\n}\n\nint64_t SpinBox::stepSize() const\n{\n    return step_size;\n}\n\n\nvoid SpinBox::stepUp()\n{\n    int64_t v=value() + step_size;\n    if (v > max) v=max;\n    setValue(v);\n}\n\nvoid SpinBox::stepDown()\n{\n    int64_t v=value() - step_size;\n    if (v < min) v=min;\n    setValue(v);\n}\n\nbool SpinBox::validateText(const ppl7::WideString& text)\n{\n    ppl7::String t=text;\n    if (t.isEmpty() || t.pregMatch(\"\/^-?[0-9]*$\/\")) {\n        int64_t v=text.toInt64();\n        if (v >= min && v <= max) return true;\n        return false;\n    }\n    return false;\n}\n\nDoubleSpinBox::DoubleSpinBox()\n{\n    my_value=0.0f;\n    my_decimals=2;\n    step_size=1;\n    min=0;\n    max=0;\n    setInputValidator(this);\n}\n\nDoubleSpinBox::DoubleSpinBox(int x, int y, int width, int height, double value, int decimals)\n    :AbstractSpinBox(x, y, width, height)\n{\n    my_decimals=decimals;\n    step_size=1;\n    min=0;\n    max=0;\n    setInputValidator(this);\n    if (value < min) min=value;\n    if (value > max) max=value;\n    setValue(value);\n}\n\nString DoubleSpinBox::widgetType() const\n{\n    return \"DoubleSpinBox\";\n}\n\nvoid DoubleSpinBox::setValue(double value)\n{\n    if (valuemax) return;\n    my_value=value;\n    ppl7::String format;\n    format.setf(\"%%0.%df\", my_decimals);\n    setText(ppl7::ToString((const char*)format, value));\n\n}\n\ndouble DoubleSpinBox::value() const\n{\n    return text().toDouble();\n}\n\nvoid DoubleSpinBox::setMinimum(double value)\n{\n    min=value;\n    if (my_value < min) my_value=min;\n}\n\nvoid DoubleSpinBox::setMaximum(double value)\n{\n    max=value;\n    if (my_value > max) my_value=max;\n}\n\nvoid DoubleSpinBox::setLimits(double min, double max)\n{\n    setMinimum(min);\n    setMaximum(max);\n}\n\ndouble DoubleSpinBox::minimum() const\n{\n    return min;\n}\n\ndouble DoubleSpinBox::maximum() const\n{\n    return max;\n}\n\nvoid DoubleSpinBox::setStepSize(double value)\n{\n    step_size=value;\n}\n\ndouble DoubleSpinBox::stepSize() const\n{\n    return step_size;\n}\n\nvoid DoubleSpinBox::stepUp()\n{\n    int64_t v=value() + step_size;\n    if (v > max) v=max;\n    setValue(v);\n}\n\nvoid DoubleSpinBox::stepDown()\n{\n    int64_t v=value() - step_size;\n    if (v < min) v=min;\n    setValue(v);\n}\n\nbool DoubleSpinBox::validateText(const ppl7::WideString& text)\n{\n    ppl7::String t=text;\n    if (t.isEmpty() || t.pregMatch(\"\/^-?[0-9\\\\.,]*$\/\")) {\n        double v=text.toDouble();\n        if (v >= min && v <= max) return true;\n    }\n    return false;\n}\n\n\n}   \/\/ EOF namespace\nadded methods to read and set background color on SpinBox\/*******************************************************************************\n * This file is part of \"Patrick's Programming Library\", Version 7 (PPL7).\n * Web: http:\/\/www.pfp.de\/ppl\/\n *\n *******************************************************************************\n * Copyright (c) 2022, Patrick Fedick \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *    1. Redistributions of source code must retain the above copyright notice, this\n *       list of conditions and the following disclaimer.\n *    2. Redistributions in binary form must reproduce the above copyright notice,\n *       this list of conditions and the following disclaimer in the documentation\n *       and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n *******************************************************************************\/\n\n#include \"prolog_ppl7.h\"\n\n#ifdef HAVE_STDIO_H\n#include \n#endif\n#ifdef HAVE_STDLIB_H\n#include \n#endif\n#ifdef HAVE_STRING_H\n#include \n#endif\n#ifdef HAVE_STDARG_H\n#include \n#endif\n\n#include \"ppl7.h\"\n#include \"ppl7-grafix.h\"\n#include \"ppl7-tk.h\"\n\nnamespace ppl7::tk {\n\n\nAbstractSpinBox::AbstractSpinBox()\n{\n    up_button=NULL;\n    down_button=NULL;\n    text_input=NULL;\n    createUi();\n}\n\nAbstractSpinBox::~AbstractSpinBox()\n{\n    if (text_input) delete text_input;\n    if (up_button) delete up_button;\n    if (down_button) delete down_button;\n}\n\nAbstractSpinBox::AbstractSpinBox(int x, int y, int width, int height, const String& text)\n{\n    create(x, y, width, height);\n    up_button=NULL;\n    down_button=NULL;\n    text_input=NULL;\n    createUi();\n    resizeUi();\n    text_input->setText(text);\n}\n\nvoid AbstractSpinBox::createUi()\n{\n    Grafix* gfx=GetGrafix();\n    text_input=new LineInput();\n    text_input->setEventHandler(this);\n    addChild(text_input);\n    up_button=new Button();\n    up_button->setEventHandler(this);\n    addChild(up_button);\n    down_button=new Button();\n    down_button->setEventHandler(this);\n    addChild(down_button);\n    if (gfx) {\n        const WidgetStyle& style=GetWidgetStyle();\n        img_up=gfx->ButtonSymbolsSmall.getDrawable(3, style.buttonSymbolColor);\n        img_down=gfx->ButtonSymbolsSmall.getDrawable(4, style.buttonSymbolColor);\n        up_button->setIcon(img_up);\n        down_button->setIcon(img_down);\n    }\n}\n\nvoid AbstractSpinBox::resizeUi()\n{\n    Rect client=this->clientRect();\n    text_input->setSize(client.width() - 25, client.height());\n    text_input->setPos(client.left(), client.top());\n\n    up_button->setSize(25, client.height() \/ 2);\n    up_button->setPos(client.width() - 25, client.top());\n\n    down_button->setSize(25, client.height() \/ 2);\n    down_button->setPos(client.width() - 25, client.top() + client.height() \/ 2);\n}\n\nconst Color& AbstractSpinBox::color() const\n{\n    return text_input->color();\n}\n\nvoid AbstractSpinBox::setColor(const Color& c)\n{\n    text_input->setColor(c);\n}\n\nvoid AbstractSpinBox::setBackgroundColor(const ppl7::grafix::Color& color)\n{\n    text_input->setBackgroundColor(color);\n}\n\nconst Color& AbstractSpinBox::backgroundColor() const\n{\n    return text_input->backgroundColor();\n}\n\n\nconst Font& AbstractSpinBox::font() const\n{\n    return text_input->font();\n}\n\nvoid AbstractSpinBox::setFont(const Font& font)\n{\n    text_input->setFont(font);\n}\n\nvoid AbstractSpinBox::setText(const String& value)\n{\n    text_input->setText(value);\n    Event new_event(Event::TextChanged);\n    new_event.setWidget(this);\n    EventHandler::textChangedEvent(&new_event, value);\n}\n\nString AbstractSpinBox::text() const\n{\n    return String(text_input->text());\n}\n\nString AbstractSpinBox::widgetType() const\n{\n    return \"AbstractSpinBox\";\n}\n\n\n\nvoid AbstractSpinBox::debugEvent(const ppl7::String& name, Event* event)\n{\n    return;\n    Widget* w=event->widget();\n    ppl7::String wname=\"unknown\";\n    if (w == this) wname=\"AbstractSpinBox\";\n    else if (w == up_button) wname=\"UpButton\";\n    else if (w == down_button) wname=\"DownButton\";\n    else if (w == text_input) wname=\"TextInput\";\n\n    printf(\"Event [%s]: %s\\n\", (const char*)wname, (const char*)name);\n\n}\n\nvoid AbstractSpinBox::setInputValidator(InputValidator* validator)\n{\n    text_input->setInputValidator(validator);\n}\n\nvoid AbstractSpinBox::paint(Drawable& draw)\n{\n\n}\n\nvoid AbstractSpinBox::mouseDownEvent(MouseEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::mouseDownEvent\", event);\n    Widget* w=event->widget();\n    if (w == up_button) stepUp();\n    else if (w == down_button) stepDown();\n    GetWindowManager()->setKeyboardFocus(text_input);\n\n}\n\nvoid AbstractSpinBox::gotFocusEvent(FocusEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::gotFocusEvent\", event);\n    GetWindowManager()->setKeyboardFocus(text_input);\n}\n\nvoid AbstractSpinBox::lostFocusEvent(FocusEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::lostFocusEvent\", event);\n}\n\nvoid AbstractSpinBox::textInputEvent(TextInputEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::textInputEvent\", event);\n}\n\nvoid AbstractSpinBox::keyDownEvent(KeyEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::keyDownEvent\", event);\n    KeyEvent new_event=*event;\n    new_event.setWidget(this);\n    EventHandler::keyDownEvent(&new_event);\n}\n\nvoid AbstractSpinBox::keyUpEvent(KeyEvent* event)\n{\n    debugEvent(\"AbstractSpinBox::keyUpEvent\", event);\n}\n\nvoid AbstractSpinBox::textChangedEvent(Event* event, const String& text)\n{\n    debugEvent(\"AbstractSpinBox::textChangedEvent\", event);\n    Event new_event=*event;\n    new_event.setWidget(this);\n    EventHandler::textChangedEvent(&new_event, text);\n}\n\n\nSpinBox::SpinBox()\n{\n    my_value=0;\n    step_size=1;\n    min=0;\n    max=0;\n    setInputValidator(this);\n}\n\nSpinBox::SpinBox(int x, int y, int width, int height, int64_t value)\n    :AbstractSpinBox(x, y, width, height)\n{\n    my_value=0;\n    step_size=1;\n    min=0;\n    max=0;\n    setInputValidator(this);\n    if (value < min) min=value;\n    if (value > max) max=value;\n    setValue(value);\n}\n\nString SpinBox::widgetType() const\n{\n    return \"SpinBox\";\n}\n\nvoid SpinBox::setValue(int64_t value)\n{\n    if (valuemax) return;\n    my_value=value;\n    setText(ppl7::ToString(\"%ld\", value));\n}\n\nint64_t SpinBox::value() const\n{\n    return text().toInt64();\n}\n\nvoid SpinBox::setMinimum(int64_t value)\n{\n    min=value;\n    if (my_value < min) my_value=min;\n}\n\nvoid SpinBox::setMaximum(int64_t value)\n{\n    max=value;\n    if (my_value > max) my_value=max;\n}\n\nvoid SpinBox::setLimits(int64_t min, int64_t max)\n{\n    setMinimum(min);\n    setMaximum(max);\n}\n\nint64_t SpinBox::minimum() const\n{\n    return min;\n}\n\nint64_t SpinBox::maximum() const\n{\n    return max;\n}\n\nvoid SpinBox::setStepSize(int64_t value)\n{\n    step_size=value;\n}\n\nint64_t SpinBox::stepSize() const\n{\n    return step_size;\n}\n\n\nvoid SpinBox::stepUp()\n{\n    int64_t v=value() + step_size;\n    if (v > max) v=max;\n    setValue(v);\n}\n\nvoid SpinBox::stepDown()\n{\n    int64_t v=value() - step_size;\n    if (v < min) v=min;\n    setValue(v);\n}\n\nbool SpinBox::validateText(const ppl7::WideString& text)\n{\n    ppl7::String t=text;\n    if (t.isEmpty() || t.pregMatch(\"\/^-?[0-9]*$\/\")) {\n        int64_t v=text.toInt64();\n        if (v >= min && v <= max) return true;\n        return false;\n    }\n    return false;\n}\n\nDoubleSpinBox::DoubleSpinBox()\n{\n    my_value=0.0f;\n    my_decimals=2;\n    step_size=1;\n    min=0;\n    max=0;\n    setInputValidator(this);\n}\n\nDoubleSpinBox::DoubleSpinBox(int x, int y, int width, int height, double value, int decimals)\n    :AbstractSpinBox(x, y, width, height)\n{\n    my_decimals=decimals;\n    step_size=1;\n    min=0;\n    max=0;\n    setInputValidator(this);\n    if (value < min) min=value;\n    if (value > max) max=value;\n    setValue(value);\n}\n\nString DoubleSpinBox::widgetType() const\n{\n    return \"DoubleSpinBox\";\n}\n\nvoid DoubleSpinBox::setValue(double value)\n{\n    if (valuemax) return;\n    my_value=value;\n    ppl7::String format;\n    format.setf(\"%%0.%df\", my_decimals);\n    setText(ppl7::ToString((const char*)format, value));\n\n}\n\ndouble DoubleSpinBox::value() const\n{\n    return text().toDouble();\n}\n\nvoid DoubleSpinBox::setMinimum(double value)\n{\n    min=value;\n    if (my_value < min) my_value=min;\n}\n\nvoid DoubleSpinBox::setMaximum(double value)\n{\n    max=value;\n    if (my_value > max) my_value=max;\n}\n\nvoid DoubleSpinBox::setLimits(double min, double max)\n{\n    setMinimum(min);\n    setMaximum(max);\n}\n\ndouble DoubleSpinBox::minimum() const\n{\n    return min;\n}\n\ndouble DoubleSpinBox::maximum() const\n{\n    return max;\n}\n\nvoid DoubleSpinBox::setStepSize(double value)\n{\n    step_size=value;\n}\n\ndouble DoubleSpinBox::stepSize() const\n{\n    return step_size;\n}\n\nvoid DoubleSpinBox::stepUp()\n{\n    int64_t v=value() + step_size;\n    if (v > max) v=max;\n    setValue(v);\n}\n\nvoid DoubleSpinBox::stepDown()\n{\n    int64_t v=value() - step_size;\n    if (v < min) v=min;\n    setValue(v);\n}\n\nbool DoubleSpinBox::validateText(const ppl7::WideString& text)\n{\n    ppl7::String t=text;\n    if (t.isEmpty() || t.pregMatch(\"\/^-?[0-9\\\\.,]*$\/\")) {\n        double v=text.toDouble();\n        if (v >= min && v <= max) return true;\n    }\n    return false;\n}\n\n\n}   \/\/ EOF namespace\n<|endoftext|>"}
{"text":"#include \"niven\/routing\/nodes\/GreedyNode.h\"\n#include \n\nusing namespace std;\nusing namespace emg;\nusing namespace ent;\n\n\nnamespace niven\n{\n\tGreedyNode::GreedyNode(string segment) : TrieNode(segment, 0)\n\t{\n\t\t\/\/ Retrieve the capture name from the route segment.\n\t\tthis->name = String::trim(String::trim(String::trim(segment, '{'), '}'), '*');\n\t}\n\n\n\tvoid GreedyNode::GetMatches(vector &results, const vector &segments, int index, const tree &captures)\n\t{\n\t\ttree all = captures;\n\n\t\t\/\/ Add all remaining segments (stuck back together) as a capture.\n\t\tall.set(this->name, accumulate(\n\t\t\tsegments.begin() + index, segments.end(), segments[index - 1],\n\t\t\t[](auto &a, auto &b) { return a + '\/' + b; }\n\t\t));\n\n\t\t\/\/ A greedy node may still have children, retrieve any matches\n\t\t\/\/ for them (since they may have a higher score).\n\t\tif (this->children.size())\n\t\t{\n\t\t\tfor (; index < segments.size(); index++)\n\t\t\t{\n\t\t\t\tfor (auto &c : this->children)\n\t\t\t\t{\n\t\t\t\t\tif (c.second->IsMatch(segments[index]))\n\t\t\t\t\t{\n\t\t\t\t\t\tc.second->GetMatches(results, segments, index + 1, c.second->GetCaptures(all, segments[index]));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tresults.push_back({ this->route, all });\n\t}\n\n\n\tbool GreedyNode::IsMatch(const std::string &segment)\n\t{\n\t\treturn true;\n\t}\n}\n\nMissing numeric header for accumulate function.#include \"niven\/routing\/nodes\/GreedyNode.h\"\n#include \n#include \n\nusing namespace std;\nusing namespace emg;\nusing namespace ent;\n\n\nnamespace niven\n{\n\tGreedyNode::GreedyNode(string segment) : TrieNode(segment, 0)\n\t{\n\t\t\/\/ Retrieve the capture name from the route segment.\n\t\tthis->name = String::trim(String::trim(String::trim(segment, '{'), '}'), '*');\n\t}\n\n\n\tvoid GreedyNode::GetMatches(vector &results, const vector &segments, int index, const tree &captures)\n\t{\n\t\ttree all = captures;\n\n\t\t\/\/ Add all remaining segments (stuck back together) as a capture.\n\t\tall.set(this->name, accumulate(\n\t\t\tsegments.begin() + index, segments.end(), segments[index - 1],\n\t\t\t[](auto &a, auto &b) { return a + '\/' + b; }\n\t\t));\n\n\t\t\/\/ A greedy node may still have children, retrieve any matches\n\t\t\/\/ for them (since they may have a higher score).\n\t\tif (this->children.size())\n\t\t{\n\t\t\tfor (; index < segments.size(); index++)\n\t\t\t{\n\t\t\t\tfor (auto &c : this->children)\n\t\t\t\t{\n\t\t\t\t\tif (c.second->IsMatch(segments[index]))\n\t\t\t\t\t{\n\t\t\t\t\t\tc.second->GetMatches(results, segments, index + 1, c.second->GetCaptures(all, segments[index]));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tresults.push_back({ this->route, all });\n\t}\n\n\n\tbool GreedyNode::IsMatch(const std::string &segment)\n\t{\n\t\treturn true;\n\t}\n}\n\n<|endoftext|>"}
{"text":"\/*\nCopyright (c) 2010-2019, Mathieu Labbe - IntRoLab - Universite de Sherbrooke\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name of the Universite de Sherbrooke nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace rtabmap_ros\n{\n\n\/**\n * This nodelet can assemble a number of clouds (max_clouds) coming\n * from the same sensor, taking into account the displacement of the robot based on\n * fixed_frame_id, then publish the resulting cloud.\n * If fixed_frame_id is set to \"\" (empty), the nodelet will subscribe to\n * an odom topic that should have the exact same stamp than to input cloud.\n * The output cloud has the same stamp and frame than the last assembled cloud.\n *\/\nclass PointCloudAssembler : public nodelet::Nodelet\n{\npublic:\n\tPointCloudAssembler() :\n\t\twarningThread_(0),\n\t\tcallbackCalled_(false),\n\t\texactSync_(0),\n\t\tmaxClouds_(0),\n\t\tassemblingTime_(0),\n\t\tskipClouds_(0),\n\t\tcloudsSkipped_(0),\n\t\twaitForTransformDuration_(0.1),\n\t\trangeMin_(0),\n\t\trangeMax_(0),\n\t\tvoxelSize_(0),\n\t\tfixedFrameId_(\"odom\")\n\t{}\n\n\tvirtual ~PointCloudAssembler()\n\t{\n\t\tdelete exactSync_;\n\n\t\tif(warningThread_)\n\t\t{\n\t\t\tcallbackCalled_=true;\n\t\t\twarningThread_->join();\n\t\t\tdelete warningThread_;\n\t\t}\n\t}\n\nprivate:\n\tvirtual void onInit()\n\t{\n\t\tros::NodeHandle & nh = getNodeHandle();\n\t\tros::NodeHandle & pnh = getPrivateNodeHandle();\n\n\t\tint queueSize = 5;\n\n\t\tpnh.param(\"queue_size\", queueSize, queueSize);\n\t\tpnh.param(\"fixed_frame_id\", fixedFrameId_, fixedFrameId_);\n\t\tpnh.param(\"max_clouds\", maxClouds_, maxClouds_);\n\t\tpnh.param(\"assembling_time\", assemblingTime_, assemblingTime_);\n\t\tpnh.param(\"skip_clouds\", skipClouds_, skipClouds_);\n\t\tpnh.param(\"wait_for_transform_duration\", waitForTransformDuration_, waitForTransformDuration_);\n\t\tpnh.param(\"range_min\", rangeMin_, rangeMin_);\n\t\tpnh.param(\"range_max\", rangeMax_, rangeMax_);\n\t\tpnh.param(\"voxel_size\", voxelSize_, voxelSize_);\n\t\tROS_ASSERT(maxClouds_>=0 && assemblingTime_ >=0);\n\n\t\tcloudsSkipped_ = skipClouds_;\n\n\t\tstd::string subscribedTopicsMsg;\n\t\tif(!fixedFrameId_.empty())\n\t\t{\n\t\t\tcloudSub_ = nh.subscribe(\"cloud\", 1, &PointCloudAssembler::callbackCloud, this);\n\t\t\tsubscribedTopicsMsg = uFormat(\"\\n%s subscribed to %s\",\n\t\t\t\t\t\t\t\tgetName().c_str(),\n\t\t\t\t\t\t\t\tcloudSub_.getTopic().c_str());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsyncCloudSub_.subscribe(nh, \"cloud\", 1);\n\t\t\tsyncOdomSub_.subscribe(nh, \"odom\", 1);\n\t\t\texactSync_ = new message_filters::Synchronizer(syncPolicy(queueSize), syncCloudSub_, syncOdomSub_);\n\t\t\texactSync_->registerCallback(boost::bind(&rtabmap_ros::PointCloudAssembler::callbackCloudOdom, this, _1, _2));\n\t\t\tsubscribedTopicsMsg = uFormat(\"\\n%s subscribed to (exact sync):\\n   %s,\\n   %s\",\n\t\t\t\t\t\t\t\tgetName().c_str(),\n\t\t\t\t\t\t\t\tsyncCloudSub_.getTopic().c_str(),\n\t\t\t\t\t\t\t\tsyncOdomSub_.getTopic().c_str());\n\n\t\t\twarningThread_ = new boost::thread(boost::bind(&PointCloudAssembler::warningLoop, this, subscribedTopicsMsg));\n\t\t}\n\n\t\tcloudPub_ = nh.advertise(\"assembled_cloud\", 1);\n\n\t\tNODELET_INFO(\"%s\", subscribedTopicsMsg.c_str());\n\t}\n\n\tvoid callbackCloudOdom(\n\t\t\tconst sensor_msgs::PointCloud2ConstPtr & cloudMsg,\n\t\t\tconst nav_msgs::OdometryConstPtr & odomMsg)\n\t{\n\t\tcallbackCalled_ = true;\n\t\trtabmap::Transform odom = rtabmap_ros::transformFromPoseMsg(odomMsg->pose.pose);\n\t\tif(!odom.isNull())\n\t\t{\n\t\t\tfixedFrameId_ = odomMsg->header.frame_id;\n\t\t\tcallbackCloud(cloudMsg);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tNODELET_WARN(\"Reseting point cloud assembler as null odometry has been received.\");\n\t\t\tclouds_.clear();\n\t\t}\n\t}\n\n\tvoid callbackCloud(const sensor_msgs::PointCloud2ConstPtr & cloudMsg)\n\t{\n\t\tif(cloudPub_.getNumSubscribers())\n\t\t{\n\t\t\tif(skipClouds_<=0 || cloudsSkipped_ >= skipClouds_)\n\t\t\t{\n\t\t\t\tcloudsSkipped_ = 0;\n\n\t\t\t\tsensor_msgs::PointCloud2Ptr cpy(new sensor_msgs::PointCloud2);\n\t\t\t\t*cpy = *cloudMsg;\n\t\t\t\tclouds_.push_back(cpy);\n\n\t\t\t\tif(  (int)clouds_.size() >= maxClouds_ && maxClouds_ != 0 \n\t\t\t\t\t|| \n\t\t\t\t\t (double)(*cpy).header.stamp.toSec() >= (double)clouds_[0]->header.stamp.toSec() + assemblingTime_ && assemblingTime_ != 0.0 )\n\t\t\t\t{\n\t\t\t\t\tpcl::PCLPointCloud2Ptr assembled(new pcl::PCLPointCloud2);\n\t\t\t\t\tpcl_conversions::toPCL(*clouds_.back(), *assembled);\n\n\t\t\t\t\tfor(size_t i=0; iheader.frame_id, \/\/sourceTargetFrame\n\t\t\t\t\t\t\t\tfixedFrameId_, \/\/fixedFrame\n\t\t\t\t\t\t\t\tclouds_[i]->header.stamp, \/\/stampSource\n\t\t\t\t\t\t\t\tclouds_.back()->header.stamp, \/\/stampTarget\n\t\t\t\t\t\t\t\ttfListener_,\n\t\t\t\t\t\t\t\twaitForTransformDuration_);\n\n\t\t\t\t\t\tif(t.isNull())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tROS_ERROR(\"Cloud not transform all clouds! Resetting...\");\n\t\t\t\t\t\t\tclouds_.clear();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpcl::PCLPointCloud2Ptr assembledTmp(new pcl::PCLPointCloud2);\n\t\t\t\t\t\tif(rangeMin_ > 0.0 || rangeMax_ > 0.0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpcl::PCLPointCloud2 output2;\n\t\t\t\t\t\t\tpcl_conversions::toPCL(*clouds_[i], output2);\n\t\t\t\t\t\t\trtabmap::LaserScan scan = rtabmap::util3d::laserScanFromPointCloud(output2);\n\t\t\t\t\t\t\tif(rangeMin_ > 0.0 || rangeMax_ > 0.0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tscan = rtabmap::util3d::rangeFiltering(scan, rangeMin_, rangeMax_);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpcl::concatenatePointCloud(*assembled, *rtabmap::util3d::laserScanToPointCloud2(scan, t), *assembledTmp);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\tsensor_msgs::PointCloud2 output;\n\t\t\t\t\t\t\tpcl_ros::transformPointCloud(t.toEigen4f(), *clouds_[i], output);\n\t\t\t\t\t\t\tpcl::PCLPointCloud2 output2;\n\t\t\t\t\t\t\tpcl_conversions::toPCL(output, output2);\n\t\t\t\t\t\t\tpcl::concatenatePointCloud(*assembled, output2, *assembledTmp);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tassembled = assembledTmp;\n\t\t\t\t\t}\n\n\t\t\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\t\t\tif(voxelSize_>0.0)\n\t\t\t\t\t{\n\t\t\t\t\t\tpcl::VoxelGrid filter;\n\t\t\t\t\t\tfilter.setLeafSize(voxelSize_, voxelSize_, voxelSize_);\n\t\t\t\t\t\tfilter.setInputCloud(assembled);\n\t\t\t\t\t\tpcl::PCLPointCloud2Ptr output(new pcl::PCLPointCloud2);\n\t\t\t\t\t\tfilter.filter(*output);\n\t\t\t\t\t\tpcl_conversions::moveFromPCL(*output, rosCloud);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpcl_conversions::moveFromPCL(*assembled, rosCloud);\n\t\t\t\t\t}\n\t\t\t\t\trosCloud.header = cloudMsg->header;\n\t\t\t\t\tcloudPub_.publish(rosCloud);\n\t\t\t\t\tclouds_.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++cloudsSkipped_;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid warningLoop(const std::string & subscribedTopicsMsg)\n\t{\n\t\tros::Duration r(5.0);\n\t\twhile(!callbackCalled_)\n\t\t{\n\t\t\tr.sleep();\n\t\t\tif(!callbackCalled_)\n\t\t\t{\n\t\t\t\tROS_WARN(\"%s: Did not receive data since 5 seconds! Make sure the input topics are \"\n\t\t\t\t\t\t\"published (\\\"$ rostopic hz my_topic\\\") and the timestamps in their \"\n\t\t\t\t\t\t\"header are set. %s\",\n\t\t\t\t\t\tgetName().c_str(),\n\t\t\t\t\t\tsubscribedTopicsMsg.c_str());\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\tboost::thread * warningThread_;\n\tbool callbackCalled_;\n\n\tros::Subscriber cloudSub_;\n\tros::Publisher cloudPub_;\n\n\ttypedef message_filters::sync_policies::ExactTime syncPolicy;\n\tmessage_filters::Synchronizer* exactSync_;\n\tmessage_filters::Subscriber syncCloudSub_;\n\tmessage_filters::Subscriber syncOdomSub_;\n\n\tint maxClouds_;\n\tint skipClouds_;\n\tint cloudsSkipped_;\n\tdouble assemblingTime_;\n\tdouble waitForTransformDuration_;\n\tdouble rangeMin_;\n\tdouble rangeMax_;\n\tdouble voxelSize_;\n\tstd::string fixedFrameId_;\n\ttf::TransformListener tfListener_;\n\n\tstd::vector clouds_;\n};\n\nPLUGINLIB_EXPORT_CLASS(rtabmap_ros::PointCloudAssembler, nodelet::Nodelet);\n}\n\n:lipstick:\/*\nCopyright (c) 2010-2019, Mathieu Labbe - IntRoLab - Universite de Sherbrooke\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name of the Universite de Sherbrooke nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace rtabmap_ros\n{\n\n\/**\n * This nodelet can assemble a number of clouds (max_clouds) coming\n * from the same sensor, taking into account the displacement of the robot based on\n * fixed_frame_id, then publish the resulting cloud.\n * If fixed_frame_id is set to \"\" (empty), the nodelet will subscribe to\n * an odom topic that should have the exact same stamp than to input cloud.\n * The output cloud has the same stamp and frame than the last assembled cloud.\n *\/\nclass PointCloudAssembler : public nodelet::Nodelet\n{\npublic:\n\tPointCloudAssembler() :\n\t\twarningThread_(0),\n\t\tcallbackCalled_(false),\n\t\texactSync_(0),\n\t\tmaxClouds_(0),\n\t\tassemblingTime_(0),\n\t\tskipClouds_(0),\n\t\tcloudsSkipped_(0),\n\t\twaitForTransformDuration_(0.1),\n\t\trangeMin_(0),\n\t\trangeMax_(0),\n\t\tvoxelSize_(0),\n\t\tfixedFrameId_(\"odom\")\n\t{}\n\n\tvirtual ~PointCloudAssembler()\n\t{\n\t\tdelete exactSync_;\n\n\t\tif(warningThread_)\n\t\t{\n\t\t\tcallbackCalled_=true;\n\t\t\twarningThread_->join();\n\t\t\tdelete warningThread_;\n\t\t}\n\t}\n\nprivate:\n\tvirtual void onInit()\n\t{\n\t\tros::NodeHandle & nh = getNodeHandle();\n\t\tros::NodeHandle & pnh = getPrivateNodeHandle();\n\n\t\tint queueSize = 5;\n\n\t\tpnh.param(\"queue_size\", queueSize, queueSize);\n\t\tpnh.param(\"fixed_frame_id\", fixedFrameId_, fixedFrameId_);\n\t\tpnh.param(\"max_clouds\", maxClouds_, maxClouds_);\n\t\tpnh.param(\"assembling_time\", assemblingTime_, assemblingTime_);\n\t\tpnh.param(\"skip_clouds\", skipClouds_, skipClouds_);\n\t\tpnh.param(\"wait_for_transform_duration\", waitForTransformDuration_, waitForTransformDuration_);\n\t\tpnh.param(\"range_min\", rangeMin_, rangeMin_);\n\t\tpnh.param(\"range_max\", rangeMax_, rangeMax_);\n\t\tpnh.param(\"voxel_size\", voxelSize_, voxelSize_);\n\t\tROS_ASSERT(maxClouds_>0 || assemblingTime_ >0.0);\n\n\t\tcloudsSkipped_ = skipClouds_;\n\n\t\tstd::string subscribedTopicsMsg;\n\t\tif(!fixedFrameId_.empty())\n\t\t{\n\t\t\tcloudSub_ = nh.subscribe(\"cloud\", 1, &PointCloudAssembler::callbackCloud, this);\n\t\t\tsubscribedTopicsMsg = uFormat(\"\\n%s subscribed to %s\",\n\t\t\t\t\t\t\t\tgetName().c_str(),\n\t\t\t\t\t\t\t\tcloudSub_.getTopic().c_str());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsyncCloudSub_.subscribe(nh, \"cloud\", 1);\n\t\t\tsyncOdomSub_.subscribe(nh, \"odom\", 1);\n\t\t\texactSync_ = new message_filters::Synchronizer(syncPolicy(queueSize), syncCloudSub_, syncOdomSub_);\n\t\t\texactSync_->registerCallback(boost::bind(&rtabmap_ros::PointCloudAssembler::callbackCloudOdom, this, _1, _2));\n\t\t\tsubscribedTopicsMsg = uFormat(\"\\n%s subscribed to (exact sync):\\n   %s,\\n   %s\",\n\t\t\t\t\t\t\t\tgetName().c_str(),\n\t\t\t\t\t\t\t\tsyncCloudSub_.getTopic().c_str(),\n\t\t\t\t\t\t\t\tsyncOdomSub_.getTopic().c_str());\n\n\t\t\twarningThread_ = new boost::thread(boost::bind(&PointCloudAssembler::warningLoop, this, subscribedTopicsMsg));\n\t\t}\n\n\t\tcloudPub_ = nh.advertise(\"assembled_cloud\", 1);\n\n\t\tNODELET_INFO(\"%s\", subscribedTopicsMsg.c_str());\n\t}\n\n\tvoid callbackCloudOdom(\n\t\t\tconst sensor_msgs::PointCloud2ConstPtr & cloudMsg,\n\t\t\tconst nav_msgs::OdometryConstPtr & odomMsg)\n\t{\n\t\tcallbackCalled_ = true;\n\t\trtabmap::Transform odom = rtabmap_ros::transformFromPoseMsg(odomMsg->pose.pose);\n\t\tif(!odom.isNull())\n\t\t{\n\t\t\tfixedFrameId_ = odomMsg->header.frame_id;\n\t\t\tcallbackCloud(cloudMsg);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tNODELET_WARN(\"Reseting point cloud assembler as null odometry has been received.\");\n\t\t\tclouds_.clear();\n\t\t}\n\t}\n\n\tvoid callbackCloud(const sensor_msgs::PointCloud2ConstPtr & cloudMsg)\n\t{\n\t\tif(cloudPub_.getNumSubscribers())\n\t\t{\n\t\t\tif(skipClouds_<=0 || cloudsSkipped_ >= skipClouds_)\n\t\t\t{\n\t\t\t\tcloudsSkipped_ = 0;\n\n\t\t\t\tsensor_msgs::PointCloud2Ptr cpy(new sensor_msgs::PointCloud2);\n\t\t\t\t*cpy = *cloudMsg;\n\t\t\t\tclouds_.push_back(cpy);\n\n\t\t\t\tif(  (int)clouds_.size() >= maxClouds_ && maxClouds_ > 0\n\t\t\t\t\t||\n\t\t\t\t\t (double)(*cpy).header.stamp.toSec() >= (double)clouds_[0]->header.stamp.toSec() + assemblingTime_ && assemblingTime_ > 0.0 )\n\t\t\t\t{\n\t\t\t\t\tpcl::PCLPointCloud2Ptr assembled(new pcl::PCLPointCloud2);\n\t\t\t\t\tpcl_conversions::toPCL(*clouds_.back(), *assembled);\n\n\t\t\t\t\tfor(size_t i=0; iheader.frame_id, \/\/sourceTargetFrame\n\t\t\t\t\t\t\t\tfixedFrameId_, \/\/fixedFrame\n\t\t\t\t\t\t\t\tclouds_[i]->header.stamp, \/\/stampSource\n\t\t\t\t\t\t\t\tclouds_.back()->header.stamp, \/\/stampTarget\n\t\t\t\t\t\t\t\ttfListener_,\n\t\t\t\t\t\t\t\twaitForTransformDuration_);\n\n\t\t\t\t\t\tif(t.isNull())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tROS_ERROR(\"Cloud not transform all clouds! Resetting...\");\n\t\t\t\t\t\t\tclouds_.clear();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpcl::PCLPointCloud2Ptr assembledTmp(new pcl::PCLPointCloud2);\n\t\t\t\t\t\tif(rangeMin_ > 0.0 || rangeMax_ > 0.0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpcl::PCLPointCloud2 output2;\n\t\t\t\t\t\t\tpcl_conversions::toPCL(*clouds_[i], output2);\n\t\t\t\t\t\t\trtabmap::LaserScan scan = rtabmap::util3d::laserScanFromPointCloud(output2);\n\t\t\t\t\t\t\tif(rangeMin_ > 0.0 || rangeMax_ > 0.0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tscan = rtabmap::util3d::rangeFiltering(scan, rangeMin_, rangeMax_);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpcl::concatenatePointCloud(*assembled, *rtabmap::util3d::laserScanToPointCloud2(scan, t), *assembledTmp);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsensor_msgs::PointCloud2 output;\n\t\t\t\t\t\t\tpcl_ros::transformPointCloud(t.toEigen4f(), *clouds_[i], output);\n\t\t\t\t\t\t\tpcl::PCLPointCloud2 output2;\n\t\t\t\t\t\t\tpcl_conversions::toPCL(output, output2);\n\t\t\t\t\t\t\tpcl::concatenatePointCloud(*assembled, output2, *assembledTmp);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tassembled = assembledTmp;\n\t\t\t\t\t}\n\n\t\t\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\t\t\tif(voxelSize_>0.0)\n\t\t\t\t\t{\n\t\t\t\t\t\tpcl::VoxelGrid filter;\n\t\t\t\t\t\tfilter.setLeafSize(voxelSize_, voxelSize_, voxelSize_);\n\t\t\t\t\t\tfilter.setInputCloud(assembled);\n\t\t\t\t\t\tpcl::PCLPointCloud2Ptr output(new pcl::PCLPointCloud2);\n\t\t\t\t\t\tfilter.filter(*output);\n\t\t\t\t\t\tpcl_conversions::moveFromPCL(*output, rosCloud);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tpcl_conversions::moveFromPCL(*assembled, rosCloud);\n\t\t\t\t\t}\n\t\t\t\t\trosCloud.header = cloudMsg->header;\n\t\t\t\t\tcloudPub_.publish(rosCloud);\n\t\t\t\t\tclouds_.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++cloudsSkipped_;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid warningLoop(const std::string & subscribedTopicsMsg)\n\t{\n\t\tros::Duration r(5.0);\n\t\twhile(!callbackCalled_)\n\t\t{\n\t\t\tr.sleep();\n\t\t\tif(!callbackCalled_)\n\t\t\t{\n\t\t\t\tROS_WARN(\"%s: Did not receive data since 5 seconds! Make sure the input topics are \"\n\t\t\t\t\t\t\"published (\\\"$ rostopic hz my_topic\\\") and the timestamps in their \"\n\t\t\t\t\t\t\"header are set. %s\",\n\t\t\t\t\t\tgetName().c_str(),\n\t\t\t\t\t\tsubscribedTopicsMsg.c_str());\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\tboost::thread * warningThread_;\n\tbool callbackCalled_;\n\n\tros::Subscriber cloudSub_;\n\tros::Publisher cloudPub_;\n\n\ttypedef message_filters::sync_policies::ExactTime syncPolicy;\n\tmessage_filters::Synchronizer* exactSync_;\n\tmessage_filters::Subscriber syncCloudSub_;\n\tmessage_filters::Subscriber syncOdomSub_;\n\n\tint maxClouds_;\n\tint skipClouds_;\n\tint cloudsSkipped_;\n\tdouble assemblingTime_;\n\tdouble waitForTransformDuration_;\n\tdouble rangeMin_;\n\tdouble rangeMax_;\n\tdouble voxelSize_;\n\tstd::string fixedFrameId_;\n\ttf::TransformListener tfListener_;\n\n\tstd::vector clouds_;\n};\n\nPLUGINLIB_EXPORT_CLASS(rtabmap_ros::PointCloudAssembler, nodelet::Nodelet);\n}\n\n<|endoftext|>"}
{"text":"\/*\n * Copyright (c) 2014 New Designs Unlimited, LLC\n * Opensource Automated License Plate Recognition [http:\/\/www.openalpr.com]\n *\n * This file is part of OpenAlpr.\n *\n * OpenAlpr is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License\n * version 3 as published by the Free Software Foundation\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#include \n\n#include \"licenseplatecandidate.h\"\n\nusing namespace std;\nusing namespace cv;\n\nLicensePlateCandidate::LicensePlateCandidate(PipelineData* pipeline_data)\n{\n  this->pipeline_data = pipeline_data;\n  this->config = pipeline_data->config;\n\n}\n\nLicensePlateCandidate::~LicensePlateCandidate()\n{\n  delete charSegmenter;\n}\n\n\/\/ Must delete this pointer in parent class\nvoid LicensePlateCandidate::recognize()\n{\n  charSegmenter = NULL;\n\n  pipeline_data->plate_area_confidence = 0;\n  pipeline_data->isMultiline = config->multiline;\n\n  int expandX = round(this->pipeline_data->regionOfInterest.width * 0.20);\n  int expandY = round(this->pipeline_data->regionOfInterest.height * 0.15);\n  \/\/ expand box by 15% in all directions\n  Rect expandedRegion = expandRect( this->pipeline_data->regionOfInterest, expandX, expandY, this->pipeline_data->grayImg.cols, this->pipeline_data->grayImg.rows) ;\n\n  pipeline_data->crop_gray = Mat(this->pipeline_data->grayImg, expandedRegion);\n  resize(pipeline_data->crop_gray, pipeline_data->crop_gray, Size(config->templateWidthPx, config->templateHeightPx));\n  \n  \n  CharacterRegion charRegion(pipeline_data);\n\n  if (charRegion.confidence > 10)\n  {\n    PlateLines plateLines(pipeline_data);\n\n    if (pipeline_data->hasPlateBorder)\n      plateLines.processImage(pipeline_data->plateBorderMask, 1.10);\n    \n    plateLines.processImage(pipeline_data->crop_gray, 0.9);\n\n    PlateCorners cornerFinder(pipeline_data->crop_gray, &plateLines, pipeline_data);\n    vector smallPlateCorners = cornerFinder.findPlateCorners();\n\n    if (cornerFinder.confidence > 0)\n    {\n\n      timespec startTime;\n      getTime(&startTime);\n\n\n      Mat originalCrop = pipeline_data->crop_gray;\n      \n      pipeline_data->plate_corners = transformPointsToOriginalImage(this->pipeline_data->grayImg, pipeline_data->crop_gray, expandedRegion, smallPlateCorners);\n\n      Size outputImageSize = getOutputImageSize(pipeline_data->plate_corners);\n      Mat transmtx = getTransformationMatrix(pipeline_data->plate_corners, outputImageSize);\n      pipeline_data->crop_gray = deSkewPlate(this->pipeline_data->grayImg, outputImageSize, transmtx);\n\n\n      \n      \/\/ Apply a perspective transformation to the TextLine objects\n      \/\/ to match the newly deskewed license plate crop\n      vector newLines;\n      for (uint i = 0; i < pipeline_data->textLines.size(); i++)\n      {        \n        vector textArea = transformPointsToOriginalImage(this->pipeline_data->grayImg, originalCrop, expandedRegion, \n                pipeline_data->textLines[i].textArea);\n        vector linePolygon = transformPointsToOriginalImage(this->pipeline_data->grayImg, originalCrop, expandedRegion, \n                pipeline_data->textLines[i].linePolygon);\n        \n        vector textAreaRemapped;\n        vector linePolygonRemapped;\n        \n        perspectiveTransform(textArea, textAreaRemapped, transmtx);\n        perspectiveTransform(linePolygon, linePolygonRemapped, transmtx);\n        \n        newLines.push_back(TextLine(textAreaRemapped, linePolygonRemapped));\n      }\n      \n      pipeline_data->textLines.clear();\n      for (uint i = 0; i < newLines.size(); i++)\n        pipeline_data->textLines.push_back(newLines[i]);\n      \n      \n      \n      if (config->debugTiming)\n      {\n        timespec endTime;\n        getTime(&endTime);\n        cout << \"deskew Time: \" << diffclock(startTime, endTime) << \"ms.\" << endl;\n      }\n      \n      charSegmenter = new CharacterSegmenter(pipeline_data);\n\n\n      pipeline_data->plate_area_confidence = 100;\n    }\n    charRegion.confidence = 0;\n  }\n}\n\n\/\/ Re-maps the coordinates from the smallImage to the coordinate space of the bigImage.\nvector LicensePlateCandidate::transformPointsToOriginalImage(Mat bigImage, Mat smallImage, Rect region, vector corners)\n{\n  vector cornerPoints;\n  for (uint i = 0; i < corners.size(); i++)\n  {\n    float bigX = (corners[i].x * ((float) region.width \/ smallImage.cols));\n    float bigY = (corners[i].y * ((float) region.height \/ smallImage.rows));\n\n    bigX = bigX + region.x;\n    bigY = bigY + region.y;\n\n    cornerPoints.push_back(Point2f(bigX, bigY));\n  }\n\n  return cornerPoints;\n}\n\nSize LicensePlateCandidate::getOutputImageSize(vector corners)\n{\n  \/\/ Figure out the approximate width\/height of the license plate region, so we can maintain the aspect ratio.\n  LineSegment leftEdge(round(corners[3].x), round(corners[3].y), round(corners[0].x), round(corners[0].y));\n  LineSegment rightEdge(round(corners[2].x), round(corners[2].y), round(corners[1].x), round(corners[1].y));\n  LineSegment topEdge(round(corners[0].x), round(corners[0].y), round(corners[1].x), round(corners[1].y));\n  LineSegment bottomEdge(round(corners[3].x), round(corners[3].y), round(corners[2].x), round(corners[2].y));\n\n  float w = distanceBetweenPoints(leftEdge.midpoint(), rightEdge.midpoint());\n  float h = distanceBetweenPoints(bottomEdge.midpoint(), topEdge.midpoint());\n  float aspect = w\/h;\n  int width = config->ocrImageWidthPx;\n  int height = round(((float) width) \/ aspect);\n  if (height > config->ocrImageHeightPx)\n  {\n    height = config->ocrImageHeightPx;\n    width = round(((float) height) * aspect);\n  }\n  \n  return Size(width, height);\n}\n\nMat LicensePlateCandidate::getTransformationMatrix(vector corners, Size outputImageSize)\n{\n  \/\/ Corners of the destination image\n  vector quad_pts;\n  quad_pts.push_back(Point2f(0, 0));\n  quad_pts.push_back(Point2f(outputImageSize.width, 0));\n  quad_pts.push_back(Point2f(outputImageSize.width, outputImageSize.height));\n  quad_pts.push_back(Point2f(0, outputImageSize.height));\n\n  \/\/ Get transformation matrix\n  Mat transmtx = getPerspectiveTransform(corners, quad_pts);\n\n  return transmtx;\n}\n\nMat LicensePlateCandidate::deSkewPlate(Mat inputImage, Size outputImageSize, Mat transformationMatrix)\n{\n  \n  \n  Mat deskewed(outputImageSize, this->pipeline_data->grayImg.type());\n  \n  \/\/ Apply perspective transformation to the image\n  warpPerspective(inputImage, deskewed, transformationMatrix, deskewed.size(), INTER_CUBIC);\n\n  \n  \n  if (this->config->debugGeneral)\n    displayImage(config, \"quadrilateral\", deskewed);\n\n  return deskewed;\n}\n\n\n\nGot rid of expanding the region before doing text analysis\/*\n * Copyright (c) 2014 New Designs Unlimited, LLC\n * Opensource Automated License Plate Recognition [http:\/\/www.openalpr.com]\n *\n * This file is part of OpenAlpr.\n *\n * OpenAlpr is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License\n * version 3 as published by the Free Software Foundation\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#include \n\n#include \"licenseplatecandidate.h\"\n\nusing namespace std;\nusing namespace cv;\n\nLicensePlateCandidate::LicensePlateCandidate(PipelineData* pipeline_data)\n{\n  this->pipeline_data = pipeline_data;\n  this->config = pipeline_data->config;\n\n}\n\nLicensePlateCandidate::~LicensePlateCandidate()\n{\n  delete charSegmenter;\n}\n\n\/\/ Must delete this pointer in parent class\nvoid LicensePlateCandidate::recognize()\n{\n  charSegmenter = NULL;\n\n  pipeline_data->plate_area_confidence = 0;\n  pipeline_data->isMultiline = config->multiline;\n\n\n  Rect expandedRegion = this->pipeline_data->regionOfInterest;\n  \n  pipeline_data->crop_gray = Mat(this->pipeline_data->grayImg, expandedRegion);\n  resize(pipeline_data->crop_gray, pipeline_data->crop_gray, Size(config->templateWidthPx, config->templateHeightPx));\n  \n  \n  CharacterRegion charRegion(pipeline_data);\n\n  if (charRegion.confidence > 10)\n  {\n    PlateLines plateLines(pipeline_data);\n\n    if (pipeline_data->hasPlateBorder)\n      plateLines.processImage(pipeline_data->plateBorderMask, 1.10);\n    \n    plateLines.processImage(pipeline_data->crop_gray, 0.9);\n\n    PlateCorners cornerFinder(pipeline_data->crop_gray, &plateLines, pipeline_data);\n    vector smallPlateCorners = cornerFinder.findPlateCorners();\n\n    if (cornerFinder.confidence > 0)\n    {\n\n      timespec startTime;\n      getTime(&startTime);\n\n\n      Mat originalCrop = pipeline_data->crop_gray;\n      \n      pipeline_data->plate_corners = transformPointsToOriginalImage(this->pipeline_data->grayImg, pipeline_data->crop_gray, expandedRegion, smallPlateCorners);\n\n      Size outputImageSize = getOutputImageSize(pipeline_data->plate_corners);\n      Mat transmtx = getTransformationMatrix(pipeline_data->plate_corners, outputImageSize);\n      pipeline_data->crop_gray = deSkewPlate(this->pipeline_data->grayImg, outputImageSize, transmtx);\n\n\n      \n      \/\/ Apply a perspective transformation to the TextLine objects\n      \/\/ to match the newly deskewed license plate crop\n      vector newLines;\n      for (uint i = 0; i < pipeline_data->textLines.size(); i++)\n      {        \n        vector textArea = transformPointsToOriginalImage(this->pipeline_data->grayImg, originalCrop, expandedRegion, \n                pipeline_data->textLines[i].textArea);\n        vector linePolygon = transformPointsToOriginalImage(this->pipeline_data->grayImg, originalCrop, expandedRegion, \n                pipeline_data->textLines[i].linePolygon);\n        \n        vector textAreaRemapped;\n        vector linePolygonRemapped;\n        \n        perspectiveTransform(textArea, textAreaRemapped, transmtx);\n        perspectiveTransform(linePolygon, linePolygonRemapped, transmtx);\n        \n        newLines.push_back(TextLine(textAreaRemapped, linePolygonRemapped));\n      }\n      \n      pipeline_data->textLines.clear();\n      for (uint i = 0; i < newLines.size(); i++)\n        pipeline_data->textLines.push_back(newLines[i]);\n      \n      \n      \n      if (config->debugTiming)\n      {\n        timespec endTime;\n        getTime(&endTime);\n        cout << \"deskew Time: \" << diffclock(startTime, endTime) << \"ms.\" << endl;\n      }\n      \n      charSegmenter = new CharacterSegmenter(pipeline_data);\n\n\n      pipeline_data->plate_area_confidence = 100;\n    }\n    charRegion.confidence = 0;\n  }\n}\n\n\/\/ Re-maps the coordinates from the smallImage to the coordinate space of the bigImage.\nvector LicensePlateCandidate::transformPointsToOriginalImage(Mat bigImage, Mat smallImage, Rect region, vector corners)\n{\n  vector cornerPoints;\n  for (uint i = 0; i < corners.size(); i++)\n  {\n    float bigX = (corners[i].x * ((float) region.width \/ smallImage.cols));\n    float bigY = (corners[i].y * ((float) region.height \/ smallImage.rows));\n\n    bigX = bigX + region.x;\n    bigY = bigY + region.y;\n\n    cornerPoints.push_back(Point2f(bigX, bigY));\n  }\n\n  return cornerPoints;\n}\n\nSize LicensePlateCandidate::getOutputImageSize(vector corners)\n{\n  \/\/ Figure out the approximate width\/height of the license plate region, so we can maintain the aspect ratio.\n  LineSegment leftEdge(round(corners[3].x), round(corners[3].y), round(corners[0].x), round(corners[0].y));\n  LineSegment rightEdge(round(corners[2].x), round(corners[2].y), round(corners[1].x), round(corners[1].y));\n  LineSegment topEdge(round(corners[0].x), round(corners[0].y), round(corners[1].x), round(corners[1].y));\n  LineSegment bottomEdge(round(corners[3].x), round(corners[3].y), round(corners[2].x), round(corners[2].y));\n\n  float w = distanceBetweenPoints(leftEdge.midpoint(), rightEdge.midpoint());\n  float h = distanceBetweenPoints(bottomEdge.midpoint(), topEdge.midpoint());\n  float aspect = w\/h;\n  int width = config->ocrImageWidthPx;\n  int height = round(((float) width) \/ aspect);\n  if (height > config->ocrImageHeightPx)\n  {\n    height = config->ocrImageHeightPx;\n    width = round(((float) height) * aspect);\n  }\n  \n  return Size(width, height);\n}\n\nMat LicensePlateCandidate::getTransformationMatrix(vector corners, Size outputImageSize)\n{\n  \/\/ Corners of the destination image\n  vector quad_pts;\n  quad_pts.push_back(Point2f(0, 0));\n  quad_pts.push_back(Point2f(outputImageSize.width, 0));\n  quad_pts.push_back(Point2f(outputImageSize.width, outputImageSize.height));\n  quad_pts.push_back(Point2f(0, outputImageSize.height));\n\n  \/\/ Get transformation matrix\n  Mat transmtx = getPerspectiveTransform(corners, quad_pts);\n\n  return transmtx;\n}\n\nMat LicensePlateCandidate::deSkewPlate(Mat inputImage, Size outputImageSize, Mat transformationMatrix)\n{\n  \n  \n  Mat deskewed(outputImageSize, this->pipeline_data->grayImg.type());\n  \n  \/\/ Apply perspective transformation to the image\n  warpPerspective(inputImage, deskewed, transformationMatrix, deskewed.size(), INTER_CUBIC);\n\n  \n  \n  if (this->config->debugGeneral)\n    displayImage(config, \"quadrilateral\", deskewed);\n\n  return deskewed;\n}\n\n\n\n<|endoftext|>"}
{"text":"#include \"openmc\/wmp.h\"\n\n#include \"openmc\/constants.h\"\n#include \"openmc\/cross_sections.h\"\n#include \"openmc\/hdf5_interface.h\"\n#include \"openmc\/math_functions.h\"\n#include \"openmc\/nuclide.h\"\n\n#include \n\n#include \n\nnamespace openmc {\n\n\/\/========================================================================\n\/\/ WindowedeMultipole implementation\n\/\/========================================================================\n\nWindowedMultipole::WindowedMultipole(hid_t group)\n{\n  \/\/ Get name of nuclide from group, removing leading '\/'\n  name_ = object_name(group).substr(1);\n\n  \/\/ Read scalar values.\n  read_dataset(group, \"spacing\", spacing_);\n  read_dataset(group, \"sqrtAWR\", sqrt_awr_);\n  read_dataset(group, \"E_min\", E_min_);\n  read_dataset(group, \"E_max\", E_max_);\n\n  \/\/ Read the \"data\" array.  Use its shape to figure out the number of poles\n  \/\/ and residue types in this data.\n  read_dataset(group, \"data\", data_);\n  int n_residues = data_.shape()[1] - 1;\n\n  \/\/ Check to see if this data includes fission residues.\n  fissionable_ = (n_residues == 3);\n\n  \/\/ Read the \"windows\" array and use its shape to figure out the number of\n  \/\/ windows.\n  read_dataset(group, \"windows\", windows_);\n  int n_windows = windows_.shape()[0];\n\n  \/\/ Read the \"broaden_poly\" arrays.\n  read_dataset(group, \"broaden_poly\", broaden_poly_);\n  if (n_windows != broaden_poly_.shape()[0]) {\n    fatal_error(\"broaden_poly array shape is not consistent with the windows \"\n      \"array shape in WMP library for \" + name_ + \".\");\n  }\n\n  \/\/ Read the \"curvefit\" array.\n  read_dataset(group, \"curvefit\", curvefit_);\n  if (n_windows != broaden_poly_.shape()[0]) {\n    fatal_error(\"curvefit array shape is not consistent with the windows \"\n      \"array shape in WMP library for \" + name_ + \".\");\n  }\n  fit_order_ = curvefit_.shape()[1] - 1;\n}\n\nstd::tuple\nWindowedMultipole::evaluate(double E, double sqrtkT)\n{\n  using namespace std::complex_literals;\n\n  \/\/ ==========================================================================\n  \/\/ Bookkeeping\n\n  \/\/ Define some frequently used variables.\n  double sqrtE = std::sqrt(E);\n  double invE = 1.0 \/ E;\n\n  \/\/ Locate window containing energy\n  int i_window = (sqrtE - std::sqrt(E_min_)) \/ spacing_;\n  int startw = windows_(i_window, 0) - 1;\n  int endw = windows_(i_window, 1) - 1;\n\n  \/\/ Initialize the ouptut cross sections\n  double sig_s = 0.0;\n  double sig_a = 0.0;\n  double sig_f = 0.0;\n\n  \/\/ ==========================================================================\n  \/\/ Add the contribution from the curvefit polynomial.\n\n  if (sqrtkT > 0.0 && broaden_poly_(i_window)) {\n    \/\/ Broaden the curvefit.\n    double dopp = sqrt_awr_ \/ sqrtkT;\n    std::vector broadened_polynomials(fit_order_ + 1);\n    broaden_wmp_polynomials(E, dopp, fit_order_ + 1, broadened_polynomials.data());\n    for (int i_poly = 0; i_poly < fit_order_ + 1; ++i_poly) {\n      sig_s += curvefit_(i_window, i_poly, FIT_S) * broadened_polynomials[i_poly];\n      sig_a += curvefit_(i_window, i_poly, FIT_A) * broadened_polynomials[i_poly];\n      if (fissionable_) {\n        sig_f += curvefit_(i_window, i_poly, FIT_F) * broadened_polynomials[i_poly];\n      }\n    }\n  } else {\n    \/\/ Evaluate as if it were a polynomial\n    double temp = invE;\n    for (int i_poly = 0; i_poly < fit_order_ + 1; ++i_poly) {\n      sig_s += curvefit_(i_window, i_poly, FIT_S) * temp;\n      sig_a += curvefit_(i_window, i_poly, FIT_A) * temp;\n      if (fissionable_) {\n        sig_f += curvefit_(i_window, i_poly, FIT_F) * temp;\n      }\n      temp *= sqrtE;\n    }\n  }\n\n  \/\/ ==========================================================================\n  \/\/ Add the contribution from the poles in this window.\n\n  if (sqrtkT == 0.0) {\n    \/\/ If at 0K, use asymptotic form.\n    for (int i_pole = startw; i_pole <= endw; ++i_pole) {\n      std::complex psi_chi = -1.0i \/ (data_(i_pole, MP_EA) - sqrtE);\n      std::complex c_temp = psi_chi \/ E;\n      sig_s += (data_(i_pole, MP_RS) * c_temp).real();\n      sig_a += (data_(i_pole, MP_RA) * c_temp).real();\n      if (fissionable_) {\n        sig_f += (data_(i_pole, MP_RF) * c_temp).real();\n      }\n    }\n  } else {\n    \/\/ At temperature, use Faddeeva function-based form.\n    double dopp = sqrt_awr_ \/ sqrtkT;\n    if (endw >= startw) {\n      for (int i_pole = startw; i_pole <= endw; ++i_pole) {\n        std::complex z = (sqrtE - data_(i_pole, MP_EA)) * dopp;\n        std::complex w_val = faddeeva(z) * dopp * invE * SQRT_PI;\n        sig_s += (data_(i_pole, MP_RS) * w_val).real();\n        sig_a += (data_(i_pole, MP_RA) * w_val).real();\n        if (fissionable_) {\n          sig_f += (data_(i_pole, MP_RF) * w_val).real();\n        }\n      }\n    }\n  }\n\n  return std::make_tuple(sig_s, sig_a, sig_f);\n}\n\nstd::tuple\nWindowedMultipole::evaluate_deriv(double E, double sqrtkT)\n{\n  \/\/ ==========================================================================\n  \/\/ Bookkeeping\n\n  \/\/ Define some frequently used variables.\n  double sqrtE = std::sqrt(E);\n  double invE = 1.0 \/ E;\n  double T = sqrtkT*sqrtkT \/ K_BOLTZMANN;\n\n  if (sqrtkT == 0.0) {\n    fatal_error(\"Windowed multipole temperature derivatives are not implemented\"\n      \" for 0 Kelvin cross sections.\");\n  }\n\n  \/\/ Locate us\n  int i_window = (sqrtE - std::sqrt(E_min_)) \/ spacing_;\n  int startw = windows_(i_window, 0) - 1;\n  int endw = windows_(i_window, 1) - 1;\n\n  \/\/ Initialize the ouptut cross sections.\n  double sig_s = 0.0;\n  double sig_a = 0.0;\n  double sig_f = 0.0;\n\n  \/\/ TODO Polynomials: Some of the curvefit polynomials Doppler broaden so\n  \/\/ rigorously we should be computing the derivative of those.  But in\n  \/\/ practice, those derivatives are only large at very low energy and they\n  \/\/ have no effect on reactor calculations.\n\n  \/\/ ==========================================================================\n  \/\/ Add the contribution from the poles in this window.\n\n  double dopp = sqrt_awr_ \/ sqrtkT;\n  if (endw >= startw) {\n    for (int i_pole = startw; i_pole <= endw; ++i_pole) {\n      std::complex z = (sqrtE - data_(i_pole, MP_EA)) * dopp;\n      std::complex w_val = -invE * SQRT_PI * 0.5 * w_derivative(z, 2);\n      sig_s += (data_(i_pole, MP_RS) * w_val).real();\n      sig_a += (data_(i_pole, MP_RA) * w_val).real();\n      if (fissionable_) {\n        sig_f += (data_(i_pole, MP_RF) * w_val).real();\n      }\n    }\n    sig_s *= -0.5*sqrt_awr_ \/ std::sqrt(K_BOLTZMANN) * std::pow(T, -1.5);\n    sig_a *= -0.5*sqrt_awr_ \/ std::sqrt(K_BOLTZMANN) * std::pow(T, -1.5);\n    sig_f *= -0.5*sqrt_awr_ \/ std::sqrt(K_BOLTZMANN) * std::pow(T, -1.5);\n  }\n\n  return std::make_tuple(sig_s, sig_a, sig_f);\n}\n\n\/\/========================================================================\n\/\/ Non-member functions\n\/\/========================================================================\n\nvoid check_wmp_version(hid_t file)\n{\n  if (attribute_exists(file, \"version\")) {\n    std::array version;\n    read_attribute(file, \"version\", version);\n    if (version[0] != WMP_VERSION[0]) {\n      fatal_error(fmt::format(\n        \"WMP data format uses version {}.{} whereas your installation of \"\n        \"OpenMC expects version {}.x data.\",\n        version[0], version[1], WMP_VERSION[0]));\n    }\n  } else {\n    fatal_error(fmt::format(\"WMP data does not indicate a version. Your \"\n      \"installation of OpenMC expects version {}x data.\", WMP_VERSION[0]));\n  }\n}\n\nvoid read_multipole_data(int i_nuclide)\n{\n  \/\/ Look for WMP data in cross_sections.xml\n  const auto& nuc {data::nuclides[i_nuclide]};\n  auto it = data::library_map.find({Library::Type::wmp, nuc->name_});\n\n  \/\/ If no WMP library for this nuclide, just return\n  if (it == data::library_map.end()) return;\n\n  \/\/ Check if WMP library exists\n  int idx = it->second;\n  std::string& filename = data::libraries[idx].path_;\n\n  \/\/ Display message\n  write_message(\"Reading \" + nuc->name_ + \" WMP data from \" + filename, 6);\n\n  \/\/ Open file and make sure version is sufficient\n  hid_t file = file_open(filename, 'r');\n  check_wmp_version(file);\n\n  \/\/ Read nuclide data from HDF5\n  hid_t group = open_group(file, nuc->name_.c_str());\n  nuc->multipole_ = std::make_unique(group);\n  close_group(group);\n  file_close(file);\n}\n\n} \/\/ namespace openmc\nApply templated write_message to wmp.cpp#include \"openmc\/wmp.h\"\n\n#include \"openmc\/constants.h\"\n#include \"openmc\/cross_sections.h\"\n#include \"openmc\/hdf5_interface.h\"\n#include \"openmc\/math_functions.h\"\n#include \"openmc\/nuclide.h\"\n#include \"openmc\/error.h\"  \/\/ for writing messages\n\n#include \n\n#include \n\nnamespace openmc {\n\n\/\/========================================================================\n\/\/ WindowedeMultipole implementation\n\/\/========================================================================\n\nWindowedMultipole::WindowedMultipole(hid_t group)\n{\n  \/\/ Get name of nuclide from group, removing leading '\/'\n  name_ = object_name(group).substr(1);\n\n  \/\/ Read scalar values.\n  read_dataset(group, \"spacing\", spacing_);\n  read_dataset(group, \"sqrtAWR\", sqrt_awr_);\n  read_dataset(group, \"E_min\", E_min_);\n  read_dataset(group, \"E_max\", E_max_);\n\n  \/\/ Read the \"data\" array.  Use its shape to figure out the number of poles\n  \/\/ and residue types in this data.\n  read_dataset(group, \"data\", data_);\n  int n_residues = data_.shape()[1] - 1;\n\n  \/\/ Check to see if this data includes fission residues.\n  fissionable_ = (n_residues == 3);\n\n  \/\/ Read the \"windows\" array and use its shape to figure out the number of\n  \/\/ windows.\n  read_dataset(group, \"windows\", windows_);\n  int n_windows = windows_.shape()[0];\n\n  \/\/ Read the \"broaden_poly\" arrays.\n  read_dataset(group, \"broaden_poly\", broaden_poly_);\n  if (n_windows != broaden_poly_.shape()[0]) {\n    fatal_error(\"broaden_poly array shape is not consistent with the windows \"\n      \"array shape in WMP library for \" + name_ + \".\");\n  }\n\n  \/\/ Read the \"curvefit\" array.\n  read_dataset(group, \"curvefit\", curvefit_);\n  if (n_windows != broaden_poly_.shape()[0]) {\n    fatal_error(\"curvefit array shape is not consistent with the windows \"\n      \"array shape in WMP library for \" + name_ + \".\");\n  }\n  fit_order_ = curvefit_.shape()[1] - 1;\n}\n\nstd::tuple\nWindowedMultipole::evaluate(double E, double sqrtkT)\n{\n  using namespace std::complex_literals;\n\n  \/\/ ==========================================================================\n  \/\/ Bookkeeping\n\n  \/\/ Define some frequently used variables.\n  double sqrtE = std::sqrt(E);\n  double invE = 1.0 \/ E;\n\n  \/\/ Locate window containing energy\n  int i_window = (sqrtE - std::sqrt(E_min_)) \/ spacing_;\n  int startw = windows_(i_window, 0) - 1;\n  int endw = windows_(i_window, 1) - 1;\n\n  \/\/ Initialize the ouptut cross sections\n  double sig_s = 0.0;\n  double sig_a = 0.0;\n  double sig_f = 0.0;\n\n  \/\/ ==========================================================================\n  \/\/ Add the contribution from the curvefit polynomial.\n\n  if (sqrtkT > 0.0 && broaden_poly_(i_window)) {\n    \/\/ Broaden the curvefit.\n    double dopp = sqrt_awr_ \/ sqrtkT;\n    std::vector broadened_polynomials(fit_order_ + 1);\n    broaden_wmp_polynomials(E, dopp, fit_order_ + 1, broadened_polynomials.data());\n    for (int i_poly = 0; i_poly < fit_order_ + 1; ++i_poly) {\n      sig_s += curvefit_(i_window, i_poly, FIT_S) * broadened_polynomials[i_poly];\n      sig_a += curvefit_(i_window, i_poly, FIT_A) * broadened_polynomials[i_poly];\n      if (fissionable_) {\n        sig_f += curvefit_(i_window, i_poly, FIT_F) * broadened_polynomials[i_poly];\n      }\n    }\n  } else {\n    \/\/ Evaluate as if it were a polynomial\n    double temp = invE;\n    for (int i_poly = 0; i_poly < fit_order_ + 1; ++i_poly) {\n      sig_s += curvefit_(i_window, i_poly, FIT_S) * temp;\n      sig_a += curvefit_(i_window, i_poly, FIT_A) * temp;\n      if (fissionable_) {\n        sig_f += curvefit_(i_window, i_poly, FIT_F) * temp;\n      }\n      temp *= sqrtE;\n    }\n  }\n\n  \/\/ ==========================================================================\n  \/\/ Add the contribution from the poles in this window.\n\n  if (sqrtkT == 0.0) {\n    \/\/ If at 0K, use asymptotic form.\n    for (int i_pole = startw; i_pole <= endw; ++i_pole) {\n      std::complex psi_chi = -1.0i \/ (data_(i_pole, MP_EA) - sqrtE);\n      std::complex c_temp = psi_chi \/ E;\n      sig_s += (data_(i_pole, MP_RS) * c_temp).real();\n      sig_a += (data_(i_pole, MP_RA) * c_temp).real();\n      if (fissionable_) {\n        sig_f += (data_(i_pole, MP_RF) * c_temp).real();\n      }\n    }\n  } else {\n    \/\/ At temperature, use Faddeeva function-based form.\n    double dopp = sqrt_awr_ \/ sqrtkT;\n    if (endw >= startw) {\n      for (int i_pole = startw; i_pole <= endw; ++i_pole) {\n        std::complex z = (sqrtE - data_(i_pole, MP_EA)) * dopp;\n        std::complex w_val = faddeeva(z) * dopp * invE * SQRT_PI;\n        sig_s += (data_(i_pole, MP_RS) * w_val).real();\n        sig_a += (data_(i_pole, MP_RA) * w_val).real();\n        if (fissionable_) {\n          sig_f += (data_(i_pole, MP_RF) * w_val).real();\n        }\n      }\n    }\n  }\n\n  return std::make_tuple(sig_s, sig_a, sig_f);\n}\n\nstd::tuple\nWindowedMultipole::evaluate_deriv(double E, double sqrtkT)\n{\n  \/\/ ==========================================================================\n  \/\/ Bookkeeping\n\n  \/\/ Define some frequently used variables.\n  double sqrtE = std::sqrt(E);\n  double invE = 1.0 \/ E;\n  double T = sqrtkT*sqrtkT \/ K_BOLTZMANN;\n\n  if (sqrtkT == 0.0) {\n    fatal_error(\"Windowed multipole temperature derivatives are not implemented\"\n      \" for 0 Kelvin cross sections.\");\n  }\n\n  \/\/ Locate us\n  int i_window = (sqrtE - std::sqrt(E_min_)) \/ spacing_;\n  int startw = windows_(i_window, 0) - 1;\n  int endw = windows_(i_window, 1) - 1;\n\n  \/\/ Initialize the ouptut cross sections.\n  double sig_s = 0.0;\n  double sig_a = 0.0;\n  double sig_f = 0.0;\n\n  \/\/ TODO Polynomials: Some of the curvefit polynomials Doppler broaden so\n  \/\/ rigorously we should be computing the derivative of those.  But in\n  \/\/ practice, those derivatives are only large at very low energy and they\n  \/\/ have no effect on reactor calculations.\n\n  \/\/ ==========================================================================\n  \/\/ Add the contribution from the poles in this window.\n\n  double dopp = sqrt_awr_ \/ sqrtkT;\n  if (endw >= startw) {\n    for (int i_pole = startw; i_pole <= endw; ++i_pole) {\n      std::complex z = (sqrtE - data_(i_pole, MP_EA)) * dopp;\n      std::complex w_val = -invE * SQRT_PI * 0.5 * w_derivative(z, 2);\n      sig_s += (data_(i_pole, MP_RS) * w_val).real();\n      sig_a += (data_(i_pole, MP_RA) * w_val).real();\n      if (fissionable_) {\n        sig_f += (data_(i_pole, MP_RF) * w_val).real();\n      }\n    }\n    sig_s *= -0.5*sqrt_awr_ \/ std::sqrt(K_BOLTZMANN) * std::pow(T, -1.5);\n    sig_a *= -0.5*sqrt_awr_ \/ std::sqrt(K_BOLTZMANN) * std::pow(T, -1.5);\n    sig_f *= -0.5*sqrt_awr_ \/ std::sqrt(K_BOLTZMANN) * std::pow(T, -1.5);\n  }\n\n  return std::make_tuple(sig_s, sig_a, sig_f);\n}\n\n\/\/========================================================================\n\/\/ Non-member functions\n\/\/========================================================================\n\nvoid check_wmp_version(hid_t file)\n{\n  if (attribute_exists(file, \"version\")) {\n    std::array version;\n    read_attribute(file, \"version\", version);\n    if (version[0] != WMP_VERSION[0]) {\n      fatal_error(fmt::format(\n        \"WMP data format uses version {}.{} whereas your installation of \"\n        \"OpenMC expects version {}.x data.\",\n        version[0], version[1], WMP_VERSION[0]));\n    }\n  } else {\n    fatal_error(fmt::format(\"WMP data does not indicate a version. Your \"\n      \"installation of OpenMC expects version {}x data.\", WMP_VERSION[0]));\n  }\n}\n\nvoid read_multipole_data(int i_nuclide)\n{\n  \/\/ Look for WMP data in cross_sections.xml\n  const auto& nuc {data::nuclides[i_nuclide]};\n  auto it = data::library_map.find({Library::Type::wmp, nuc->name_});\n\n  \/\/ If no WMP library for this nuclide, just return\n  if (it == data::library_map.end()) return;\n\n  \/\/ Check if WMP library exists\n  int idx = it->second;\n  std::string& filename = data::libraries[idx].path_;\n\n  \/\/ Display message\n  write_message(6, \"Reading {} WMP data from {}\", nuc->name_, filename);\n\n  \/\/ Open file and make sure version is sufficient\n  hid_t file = file_open(filename, 'r');\n  check_wmp_version(file);\n\n  \/\/ Read nuclide data from HDF5\n  hid_t group = open_group(file, nuc->name_.c_str());\n  nuc->multipole_ = std::make_unique(group);\n  close_group(group);\n  file_close(file);\n}\n\n} \/\/ namespace openmc\n<|endoftext|>"}
{"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1999-2008 Robert Osfield \n *\n * This software is open source and may be redistributed and\/or modified under  \n * the terms of the GNU General Public License (GPL) version 2.0.\n * The full license is in LICENSE.txt file included with this distribution,.\n * \n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * include LICENSE.txt for more details.\n*\/\n\n#include \n\n#include \n#include \n#include \n\n#include \n\nextern \"C\" {\n#include \n}\n\nclass LibVncImage : public osgWidget::VncImage\n{\n    public:\n    \n        LibVncImage();\n\n        bool connect(const std::string& hostname);\n\n        void close();\n        \n        virtual bool sendPointerEvent(int x, int y, int buttonMask);\n\n        double getTimeOfLastUpdate() const { return _timeOfLastUpdate; }\n        double getTimeOfLastRender() const { return _timeOfLastRender; }\n\n        double time() const { return osg::Timer::instance()->time_s(); }\n\n        virtual bool sendKeyEvent(int key, bool keyDown);\n\n        virtual void setFrameLastRendered(const osg::FrameStamp* frameStamp);\n\n        void updated();\n\n        static rfbBool resizeImage(rfbClient* client);\n        \n        static void updateImage(rfbClient* client,int x,int y,int w,int h);\n        \n        double                      _timeOfLastUpdate;\n        double                      _timeOfLastRender;\n\n        bool                        _active;\n        osg::ref_ptr _inactiveBlock;\n\n    protected:\n    \n        virtual ~LibVncImage();\n\n        class RfbThread : public osg::Referenced, public OpenThreads::Thread\n        {\n        public:\n\n            RfbThread(rfbClient* client, LibVncImage* image):\n                _client(client),\n                _image(image),\n                _done(false) {}\n\n            virtual ~RfbThread()\n            {\n                _done = true;\n                while(isRunning()) \n                {\n                    OpenThreads::Thread::YieldCurrentThread();\n                }\n            }\n\n            virtual void run()\n            {\n                do\n                {\n                    if (_image->_active)\n                    {               \n                        int i=WaitForMessage(_client,5000);\n                        if(i<0)\n                            return;\n\n                        if(i)\n                        {\n                            osg::notify(osg::NOTICE)<<\"Handling \"<updated();\n                        }\n                    }\n                    else\n                    {\n                        _image->_inactiveBlock->block();\n                    }\n                    \n                    \n                    double deltaTime = _image->getTimeOfLastRender() - _image->getTimeOfLastUpdate();\n                    if (deltaTime<-0.01)\n                    {\n                        \/\/osg::notify(osg::NOTICE)<<\"Inactive\"<_active = false;\n                    }\n                    else\n                    {\n                        _image->_active = true;\n                    }\n\n                } while (!_done && !testCancel());\n            }\n\n            rfbClient*                      _client;\n            osg::observer_ptr  _image;\n            bool                            _done;\n\n        };\n\n    public:\n\n        rfbClient* _client;\n\n        osg::ref_ptr     _rfbThread;\n      \n};\n\nLibVncImage::LibVncImage():\n    _client(0)\n{\n    \/\/ setPixelBufferObject(new osg::PixelBufferObject(this);\n\n    _inactiveBlock = new osg::RefBlock;\n\n}\n\nLibVncImage::~LibVncImage()\n{\n    close();\n}\n\nstatic rfbBool rfbInitConnection(rfbClient* client)\n{\n  \/* Unless we accepted an incoming connection, make a TCP connection to the\n     given VNC server *\/\n\n  if (!client->listenSpecified) {\n    if (!client->serverHost || !ConnectToRFBServer(client,client->serverHost,client->serverPort))\n      return FALSE;\n  }\n\n  \/* Initialise the VNC connection, including reading the password *\/\n\n  if (!InitialiseRFBConnection(client))\n    return FALSE;\n\n  if (!SetFormatAndEncodings(client))\n    return FALSE;\n\n  client->width=client->si.framebufferWidth;\n  client->height=client->si.framebufferHeight;\n  client->MallocFrameBuffer(client);\n\n  if (client->updateRect.x < 0) {\n    client->updateRect.x = client->updateRect.y = 0;\n    client->updateRect.w = client->width;\n    client->updateRect.h = client->height;\n  }\n\n  if (client->appData.scaleSetting>1)\n  {\n      if (!SendScaleSetting(client, client->appData.scaleSetting))\n          return FALSE;\n      if (!SendFramebufferUpdateRequest(client,\n                  client->updateRect.x \/ client->appData.scaleSetting,\n                  client->updateRect.y \/ client->appData.scaleSetting,\n                  client->updateRect.w \/ client->appData.scaleSetting,\n                  client->updateRect.h \/ client->appData.scaleSetting,\n                  FALSE))\n          return FALSE;\n  }\n  else\n  {\n      if (!SendFramebufferUpdateRequest(client,\n                  client->updateRect.x, client->updateRect.y,\n                  client->updateRect.w, client->updateRect.h,\n                  FALSE))\n      return FALSE;\n  }\n\n  return TRUE;\n}\n\n\nbool LibVncImage::connect(const std::string& hostname)\n{\n    if (hostname.empty()) return false;\n\n    if (_client) close();\n\n    _client = rfbGetClient(8,3,4);\n    _client->canHandleNewFBSize = TRUE;\n    _client->MallocFrameBuffer = resizeImage;\n    _client->GotFrameBufferUpdate = updateImage;\n    _client->HandleKeyboardLedState = 0;\n    _client->HandleTextChat = 0;\n\n    rfbClientSetClientData(_client, 0, this);\n    \n    _client->serverHost = strdup(hostname.c_str());\n\n    \/\/ _client->serverPort = ;\n    \/\/ _client->appData.qualityLevel = ;\n    \/\/ _client->appData.encodings = ;\n    \/\/ _client->appData.compressLevel = ;\n    \/\/ _client->appData.scaleSetting = ;\n\n    if(rfbInitConnection(_client))\n    {\n        _rfbThread = new RfbThread(_client, this);\n        _rfbThread->startThread();\n        \n        return true;\n    }\n    else\n    {\n        close();\n        \n        return false;\n    }\n}\n\n\nvoid LibVncImage::close()\n{\n    if (_rfbThread.valid())\n    {\n        _inactiveBlock->release();\n\n        \/\/ stop the client thread\n        _rfbThread = 0;\n    }\n\n    if (_client)\n    {\n        \/\/ close the client\n        rfbClientCleanup(_client);\n        _client = 0;\n    }\n}\n\n\nrfbBool LibVncImage::resizeImage(rfbClient* client) \n{\n    osg::Image* image = (osg::Image*)(rfbClientGetClientData(client, 0));\n    \n    int width=client->width;\n    int height=client->height;\n    int depth=client->format.bitsPerPixel;\n\n    osg::notify(osg::NOTICE)<<\"resize \"<allocateImage(width,height,1,GL_RGBA,GL_UNSIGNED_BYTE);\n    \n    client->frameBuffer= (uint8_t*)(image->data());\n    \n    return TRUE;\n}\n\nvoid LibVncImage::updateImage(rfbClient* client,int x,int y,int w,int h)\n{\n    osg::Image* image = (osg::Image*)(rfbClientGetClientData(client, 0));\n    image->dirty();\n}\n\nbool LibVncImage::sendPointerEvent(int x, int y, int buttonMask)\n{\n    if (_client)\n    {\n        SendPointerEvent(_client ,x, y, buttonMask);\n        return true;\n    }\n    return false;\n}\n\nbool LibVncImage::sendKeyEvent(int key, bool keyDown)\n{\n    if (_client)\n    {\n        SendKeyEvent(_client, key, keyDown ? TRUE : FALSE);\n        return true;\n    }\n    return false;\n}\n\n\nvoid LibVncImage::setFrameLastRendered(const osg::FrameStamp*)\n{\n    _timeOfLastRender = time();\n\n    if (!_active) _inactiveBlock->release();\n    _active = true;\n}\n\nvoid LibVncImage::updated()\n{\n    _timeOfLastUpdate = time();\n}\n\nclass ReaderWriterVNC : public osgDB::ReaderWriter\n{\n    public:\n    \n        ReaderWriterVNC()\n        {\n            supportsExtension(\"vnc\",\"VNC plugin\");\n        }\n        \n        virtual const char* className() const { return \"VNC plugin\"; }\n\n        virtual osgDB::ReaderWriter::ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options) const\n        {\n            return readImage(file,options);\n        }\n\n        virtual osgDB::ReaderWriter::ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n        {\n            if (!osgDB::equalCaseInsensitive(osgDB::getFileExtension(fileName),\"vnc\"))\n            {\n                return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;\n            }\n\n            std::string hostname = osgDB::getNameLessExtension(fileName);\n            \n            osg::notify(osg::NOTICE)<<\"Hostname = \"< image = new LibVncImage;\n            image->setDataVariance(osg::Object::DYNAMIC);\n            \n            image->setOrigin(osg::Image::TOP_LEFT);\n\n            if (!image->connect(hostname))\n            {\n                return \"Could not connect to \"+hostname;\n            }\n            \n            return image.get();\n        }\n        \n        virtual osgDB::ReaderWriter::ReadResult readNode(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n        {\n            osgDB::ReaderWriter::ReadResult result = readImage(fileName, options);\n            if (!result.validImage()) return result;\n            \n            osg::ref_ptr vncClient = new osgWidget::VncClient();\n            if (vncClient->assign(dynamic_cast(result.getImage())))\n            {\n                return vncClient.release();\n            }\n            else\n            {\n                return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;\n            }\n        }\n};\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(vnc, ReaderWriterVNC)\n\nConverted osg::notify to OSG_INFO etc.\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1999-2008 Robert Osfield \n *\n * This software is open source and may be redistributed and\/or modified under  \n * the terms of the GNU General Public License (GPL) version 2.0.\n * The full license is in LICENSE.txt file included with this distribution,.\n * \n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * include LICENSE.txt for more details.\n*\/\n\n#include \n\n#include \n#include \n#include \n\n#include \n\nextern \"C\" {\n#include \n}\n\nclass LibVncImage : public osgWidget::VncImage\n{\n    public:\n    \n        LibVncImage();\n\n        bool connect(const std::string& hostname);\n\n        void close();\n        \n        virtual bool sendPointerEvent(int x, int y, int buttonMask);\n\n        double getTimeOfLastUpdate() const { return _timeOfLastUpdate; }\n        double getTimeOfLastRender() const { return _timeOfLastRender; }\n\n        double time() const { return osg::Timer::instance()->time_s(); }\n\n        virtual bool sendKeyEvent(int key, bool keyDown);\n\n        virtual void setFrameLastRendered(const osg::FrameStamp* frameStamp);\n\n        void updated();\n\n        static rfbBool resizeImage(rfbClient* client);\n        \n        static void updateImage(rfbClient* client,int x,int y,int w,int h);\n        \n        double                      _timeOfLastUpdate;\n        double                      _timeOfLastRender;\n\n        bool                        _active;\n        osg::ref_ptr _inactiveBlock;\n\n    protected:\n    \n        virtual ~LibVncImage();\n\n        class RfbThread : public osg::Referenced, public OpenThreads::Thread\n        {\n        public:\n\n            RfbThread(rfbClient* client, LibVncImage* image):\n                _client(client),\n                _image(image),\n                _done(false) {}\n\n            virtual ~RfbThread()\n            {\n                _done = true;\n                while(isRunning()) \n                {\n                    OpenThreads::Thread::YieldCurrentThread();\n                }\n            }\n\n            virtual void run()\n            {\n                do\n                {\n                    if (_image->_active)\n                    {               \n                        int i=WaitForMessage(_client,5000);\n                        if(i<0)\n                            return;\n\n                        if(i)\n                        {\n                            OSG_NOTICE<<\"Handling \"<updated();\n                        }\n                    }\n                    else\n                    {\n                        _image->_inactiveBlock->block();\n                    }\n                    \n                    \n                    double deltaTime = _image->getTimeOfLastRender() - _image->getTimeOfLastUpdate();\n                    if (deltaTime<-0.01)\n                    {\n                        \/\/OSG_NOTICE<<\"Inactive\"<_active = false;\n                    }\n                    else\n                    {\n                        _image->_active = true;\n                    }\n\n                } while (!_done && !testCancel());\n            }\n\n            rfbClient*                      _client;\n            osg::observer_ptr  _image;\n            bool                            _done;\n\n        };\n\n    public:\n\n        rfbClient* _client;\n\n        osg::ref_ptr     _rfbThread;\n      \n};\n\nLibVncImage::LibVncImage():\n    _client(0)\n{\n    \/\/ setPixelBufferObject(new osg::PixelBufferObject(this);\n\n    _inactiveBlock = new osg::RefBlock;\n\n}\n\nLibVncImage::~LibVncImage()\n{\n    close();\n}\n\nstatic rfbBool rfbInitConnection(rfbClient* client)\n{\n  \/* Unless we accepted an incoming connection, make a TCP connection to the\n     given VNC server *\/\n\n  if (!client->listenSpecified) {\n    if (!client->serverHost || !ConnectToRFBServer(client,client->serverHost,client->serverPort))\n      return FALSE;\n  }\n\n  \/* Initialise the VNC connection, including reading the password *\/\n\n  if (!InitialiseRFBConnection(client))\n    return FALSE;\n\n  if (!SetFormatAndEncodings(client))\n    return FALSE;\n\n  client->width=client->si.framebufferWidth;\n  client->height=client->si.framebufferHeight;\n  client->MallocFrameBuffer(client);\n\n  if (client->updateRect.x < 0) {\n    client->updateRect.x = client->updateRect.y = 0;\n    client->updateRect.w = client->width;\n    client->updateRect.h = client->height;\n  }\n\n  if (client->appData.scaleSetting>1)\n  {\n      if (!SendScaleSetting(client, client->appData.scaleSetting))\n          return FALSE;\n      if (!SendFramebufferUpdateRequest(client,\n                  client->updateRect.x \/ client->appData.scaleSetting,\n                  client->updateRect.y \/ client->appData.scaleSetting,\n                  client->updateRect.w \/ client->appData.scaleSetting,\n                  client->updateRect.h \/ client->appData.scaleSetting,\n                  FALSE))\n          return FALSE;\n  }\n  else\n  {\n      if (!SendFramebufferUpdateRequest(client,\n                  client->updateRect.x, client->updateRect.y,\n                  client->updateRect.w, client->updateRect.h,\n                  FALSE))\n      return FALSE;\n  }\n\n  return TRUE;\n}\n\n\nbool LibVncImage::connect(const std::string& hostname)\n{\n    if (hostname.empty()) return false;\n\n    if (_client) close();\n\n    _client = rfbGetClient(8,3,4);\n    _client->canHandleNewFBSize = TRUE;\n    _client->MallocFrameBuffer = resizeImage;\n    _client->GotFrameBufferUpdate = updateImage;\n    _client->HandleKeyboardLedState = 0;\n    _client->HandleTextChat = 0;\n\n    rfbClientSetClientData(_client, 0, this);\n    \n    _client->serverHost = strdup(hostname.c_str());\n\n    \/\/ _client->serverPort = ;\n    \/\/ _client->appData.qualityLevel = ;\n    \/\/ _client->appData.encodings = ;\n    \/\/ _client->appData.compressLevel = ;\n    \/\/ _client->appData.scaleSetting = ;\n\n    if(rfbInitConnection(_client))\n    {\n        _rfbThread = new RfbThread(_client, this);\n        _rfbThread->startThread();\n        \n        return true;\n    }\n    else\n    {\n        close();\n        \n        return false;\n    }\n}\n\n\nvoid LibVncImage::close()\n{\n    if (_rfbThread.valid())\n    {\n        _inactiveBlock->release();\n\n        \/\/ stop the client thread\n        _rfbThread = 0;\n    }\n\n    if (_client)\n    {\n        \/\/ close the client\n        rfbClientCleanup(_client);\n        _client = 0;\n    }\n}\n\n\nrfbBool LibVncImage::resizeImage(rfbClient* client) \n{\n    osg::Image* image = (osg::Image*)(rfbClientGetClientData(client, 0));\n    \n    int width=client->width;\n    int height=client->height;\n    int depth=client->format.bitsPerPixel;\n\n    OSG_NOTICE<<\"resize \"<allocateImage(width,height,1,GL_RGBA,GL_UNSIGNED_BYTE);\n    \n    client->frameBuffer= (uint8_t*)(image->data());\n    \n    return TRUE;\n}\n\nvoid LibVncImage::updateImage(rfbClient* client,int x,int y,int w,int h)\n{\n    osg::Image* image = (osg::Image*)(rfbClientGetClientData(client, 0));\n    image->dirty();\n}\n\nbool LibVncImage::sendPointerEvent(int x, int y, int buttonMask)\n{\n    if (_client)\n    {\n        SendPointerEvent(_client ,x, y, buttonMask);\n        return true;\n    }\n    return false;\n}\n\nbool LibVncImage::sendKeyEvent(int key, bool keyDown)\n{\n    if (_client)\n    {\n        SendKeyEvent(_client, key, keyDown ? TRUE : FALSE);\n        return true;\n    }\n    return false;\n}\n\n\nvoid LibVncImage::setFrameLastRendered(const osg::FrameStamp*)\n{\n    _timeOfLastRender = time();\n\n    if (!_active) _inactiveBlock->release();\n    _active = true;\n}\n\nvoid LibVncImage::updated()\n{\n    _timeOfLastUpdate = time();\n}\n\nclass ReaderWriterVNC : public osgDB::ReaderWriter\n{\n    public:\n    \n        ReaderWriterVNC()\n        {\n            supportsExtension(\"vnc\",\"VNC plugin\");\n        }\n        \n        virtual const char* className() const { return \"VNC plugin\"; }\n\n        virtual osgDB::ReaderWriter::ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options) const\n        {\n            return readImage(file,options);\n        }\n\n        virtual osgDB::ReaderWriter::ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n        {\n            if (!osgDB::equalCaseInsensitive(osgDB::getFileExtension(fileName),\"vnc\"))\n            {\n                return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;\n            }\n\n            std::string hostname = osgDB::getNameLessExtension(fileName);\n            \n            OSG_NOTICE<<\"Hostname = \"< image = new LibVncImage;\n            image->setDataVariance(osg::Object::DYNAMIC);\n            \n            image->setOrigin(osg::Image::TOP_LEFT);\n\n            if (!image->connect(hostname))\n            {\n                return \"Could not connect to \"+hostname;\n            }\n            \n            return image.get();\n        }\n        \n        virtual osgDB::ReaderWriter::ReadResult readNode(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n        {\n            osgDB::ReaderWriter::ReadResult result = readImage(fileName, options);\n            if (!result.validImage()) return result;\n            \n            osg::ref_ptr vncClient = new osgWidget::VncClient();\n            if (vncClient->assign(dynamic_cast(result.getImage())))\n            {\n                return vncClient.release();\n            }\n            else\n            {\n                return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;\n            }\n        }\n};\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(vnc, ReaderWriterVNC)\n\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"unzip.h\"\n\nclass ReaderWriterZIP : public osgDB::ReaderWriter\n{\n    public:\n\n        ReaderWriterZIP()\n        {\n            supportsExtension(\"zip\",\"Zip archive format\");\n        }\n\n        virtual const char* className() const { return \"ZIP Database Reader\/Writer\"; }\n\n        virtual ReadResult readNode(const std::string& file, const osgDB::Options* options) const\n        {\n            ReadResult rresult = ReadResult::FILE_NOT_HANDLED;\n\n            \/\/Check to see if option is to load and extract to filesystem\n            bool bExtractToFileSystem = false;            \n            if (options)\n            {\n                std::string optExtractTo = options->getPluginStringData(\"zipextract\");\n                if (!(optExtractTo.empty()))\n                {\n                    if (osgDB::convertToLowerCase(optExtractTo)==\"filesystem\")\n                    {\n                        bExtractToFileSystem = true;\n                    }\n                }\n            }\n\n            if (bExtractToFileSystem)\n            {\n                rresult = original_readNode(file,options);\n            }\n            else\n            {\n                std::string ext = osgDB::getLowerCaseFileExtension(file);\n                if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n                std::string fileName = osgDB::findDataFile( file, options );\n                if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n                osg::notify(osg::INFO)<<\"ReaderWriterZIP::readNode( \"< local_opt = options ?\n                        static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) :\n                        new Options;\n\n                    \/\/ minor issue associated with database path list, as in context of zip file it\n                    \/\/ doesn't make sense. Need to set to empty path for other plugins to access\n                    local_opt->getDatabasePathList().push_front(osgDB::getFilePath(file));\n\n                    \/\/    Now pass through to memory zip handler\n                    rresult = readNode(tmpStrmBuffer,local_opt.get());\n\n                    \/\/ Clean up options\n                    local_opt->getDatabasePathList().pop_front();\n                }\n            }\n\n            return rresult;\n        }\n\n        virtual ReadResult readNode(std::istream& fin,const osgDB::Options* options) const\n        {\n            ReadResult result = ReadResult(ReadResult::FILE_NOT_HANDLED);\n\n    \n            if (!fin.fail())\n            {\n                unsigned int ulzipFileLength;\n                fin.seekg(0,std::ios_base::end);\n                ulzipFileLength = fin.tellg();\n                fin.seekg(0,std::ios_base::beg);\n\n                \/\/ Decompress stream to standard stream\n                HZIP hz;\n\n                \/\/ Need to decouple stream content as I can't see any other way to get access to a byte array\n                \/\/ containing the content in the stream. One saving grace here is that we know that the\n                \/\/ stream has already been fully read in, hence no need to concern ourselves with asynchronous\n                \/\/ reads.\n\n                \/\/void * pMemBuffer = malloc(ulzipFileLength);\n                char * pMemBuffer = new char [ulzipFileLength];\n                if (pMemBuffer)\n                {\n                    fin.read(pMemBuffer,ulzipFileLength);\n                    if ((unsigned int)fin.gcount()==ulzipFileLength)\n                    {\n                        hz = OpenZip(pMemBuffer, ulzipFileLength, \"\");  SetUnzipBaseDir(hz,_T(\"\\\\\"));\n    \n                        ZIPENTRY ze;\n                        GetZipItem(hz,-1,&ze);\n                        int numitems=ze.index;\n\n                        \/\/ Initialise top level group\n                        osg::ref_ptr grp = new osg::Group;\n                        if (grp.valid())\n                        {\n                            \/\/ Now loop through each file in zip\n                            for (int i=0; igetReaderWriterForExtension(file_ext);\n                                    if (rw)\n                                    {\n                                        \/\/ Setup appropriate options\n                                        osg::ref_ptr local_opt = options ?\n                                            static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) :\n                                            new Options;\n\n                                        local_opt->setPluginStringData(\"STREAM_FILENAME\",osgDB::getSimpleFileName(StreamName));\n\n                                        result = rw->readNode(buffer,local_opt.get());\n                                        if (result.validNode())\n                                        {\n                                            grp->addChild( result.takeNode() );\n                                        }\n                                    }\n                                }\n                            }\n                            if( grp->getNumChildren() == 0 )\n                                result = ReadResult(ReadResult::FILE_NOT_HANDLED);\n                            else\n                                result = grp.get();\n                        }\n                        else\n                            result = ReadResult(ReadResult::FILE_NOT_HANDLED);\n                    }\n                    else\n                        result = ReadResult(ReadResult::FILE_NOT_HANDLED);\n                    delete [] pMemBuffer;\n                }\n                else\n                    result = ReadResult(ReadResult::FILE_NOT_HANDLED);\n\n            }\n            return result;\n        }\n\n        virtual ReadResult original_readNode(const std::string& file, const osgDB::Options* options) const\n        {\n\n            std::string ext = osgDB::getLowerCaseFileExtension(file);\n            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n            std::string fileName = osgDB::findDataFile( file, options );\n            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n            osg::notify(osg::INFO)<<\"ReaderWriterZIP::readNode( \"< grp = new osg::Group;\n\n            osg::ref_ptr local_options = options ? static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) : new osgDB::ReaderWriter::Options;\n            local_options->getDatabasePathList().push_front(dirname);\n\n            \/\/ deactivate the automatic generation of images to geode's.\n            bool prevCreateNodeFromImage = osgDB::Registry::instance()->getCreateNodeFromImage();\n            osgDB::Registry::instance()->setCreateNodeFromImage(false);\n\n            osgDB::DirectoryContents contents = osgDB::getDirectoryContents(dirname);\n            for(osgDB::DirectoryContents::iterator itr = contents.begin();\n                itr != contents.end();\n                ++itr)\n            {\n                std::string file_ext = osgDB::getFileExtension(*itr);\n                if (!acceptsExtension(file_ext) &&\n                    *itr!=std::string(\".\") &&\n                    *itr!=std::string(\"..\"))\n                {\n                    osg::Node *node = osgDB::readNodeFile( *itr, local_options.get() );\n                    grp->addChild( node );\n                }\n            }\n\n            osgDB::Registry::instance()->setCreateNodeFromImage(prevCreateNodeFromImage);\n\n        #if defined(WIN32) && !defined(__CYGWIN__)\n            \/\/ note, is this the right command for windows?\n            \/\/ is there any way of overiding the Y\/N option? RO.\n            sprintf( command, \"erase \/S \/Q \\\"%s\\\"\", dirname );\n            int result = system( command );\n        #else\n\n            sprintf( command, \"rm -rf %s\", dirname );\n            int result = system( command );\n        #endif\n            if (result!=0) return ReadResult::ERROR_IN_READING_FILE;\n\n            if( grp->getNumChildren() == 0 )\n            {\n                return ReadResult::FILE_NOT_HANDLED;\n            }\n\n            return grp.get();\n        }\n\n};\n\n\/\/ now register with sgRegistry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(zip, ReaderWriterZIP)\nFrom Chris Denham, \"I discovered a memory leak in the ZIP plugin, which was caused by a missing call to CloseZip. I attach a modified ReaderWriterZIP.cpp  (based on version 2.9.5 revision 10374). This includes a little bit of code tidying, but the only functional change is a test of the return value of OpenZip and the addition of a call to CloseZip.\"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"unzip.h\"\n\nclass ReaderWriterZIP : public osgDB::ReaderWriter\n{\n    public:\n\n        ReaderWriterZIP()\n        {\n            supportsExtension(\"zip\",\"Zip archive format\");\n        }\n\n        virtual const char* className() const { return \"ZIP Database Reader\/Writer\"; }\n\n        virtual ReadResult readNode(const std::string& file, const osgDB::Options* options) const\n        {\n            ReadResult rresult = ReadResult::FILE_NOT_HANDLED;\n\n            \/\/Check to see if option is to load and extract to filesystem\n            bool bExtractToFileSystem = false;            \n            if (options)\n            {\n                std::string optExtractTo = options->getPluginStringData(\"zipextract\");\n                if (!(optExtractTo.empty()))\n                {\n                    if (osgDB::convertToLowerCase(optExtractTo)==\"filesystem\")\n                    {\n                        bExtractToFileSystem = true;\n                    }\n                }\n            }\n\n            if (bExtractToFileSystem)\n            {\n                rresult = original_readNode(file,options);\n            }\n            else\n            {\n                std::string ext = osgDB::getLowerCaseFileExtension(file);\n                if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n                std::string fileName = osgDB::findDataFile( file, options );\n                if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n                osg::notify(osg::INFO)<<\"ReaderWriterZIP::readNode( \"< local_opt = options ?\n                        static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) :\n                        new Options;\n\n                    \/\/ minor issue associated with database path list, as in context of zip file it\n                    \/\/ doesn't make sense. Need to set to empty path for other plugins to access\n                    local_opt->getDatabasePathList().push_front(osgDB::getFilePath(file));\n\n                    \/\/    Now pass through to memory zip handler\n                    rresult = readNode(tmpStrmBuffer,local_opt.get());\n\n                    \/\/ Clean up options\n                    local_opt->getDatabasePathList().pop_front();\n                }\n            }\n\n            return rresult;\n        }\n\n        virtual ReadResult readNode(std::istream& fin,const osgDB::Options* options) const\n        {\n            ReadResult result = ReadResult(ReadResult::FILE_NOT_HANDLED);\n\n            if (fin.fail()) return result;\n\n            fin.seekg(0,std::ios_base::end);\n            unsigned int ulzipFileLength = fin.tellg();\n            fin.seekg(0,std::ios_base::beg);\n\n            \/\/ Need to decouple stream content as I can't see any other way to get access to a byte array\n            \/\/ containing the content in the stream. One saving grace here is that we know that the\n            \/\/ stream has already been fully read in, hence no need to concern ourselves with asynchronous\n            \/\/ reads.\n            char * pMemBuffer = new char [ulzipFileLength];\n            if (!pMemBuffer) return result;\n\n            fin.read(pMemBuffer, ulzipFileLength);\n            if ((unsigned int)fin.gcount() == ulzipFileLength)\n            {\n                HZIP hz = OpenZip(pMemBuffer, ulzipFileLength, \"\");\n                if (hz)\n                {\n                    ZIPENTRY ze;\n                    GetZipItem(hz,-1,&ze);\n                    int numitems=ze.index;\n\n                    \/\/ Initialise top level group\n                    osg::ref_ptr grp = new osg::Group;\n                    if (grp.valid())\n                    {\n                        \/\/ Now loop through each file in zip\n                        for (int i = 0; i < numitems; i++)\n                        {\n                            GetZipItem(hz,i,&ze);\n                            std::string StreamName = ze.name;\n                            std::stringstream buffer;\n\n                            char *ibuf = new char[ze.unc_size];\n                            if (ibuf)\n                            {\n                                UnzipItem(hz,i, ibuf, ze.unc_size);\n                                buffer.write(ibuf,ze.unc_size);\n                                delete[] ibuf;\n                                \/\/ Now ready to read node \/\/\n\n                                std::string file_ext = osgDB::getFileExtension(StreamName);\n\n                                ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(file_ext);\n                                if (rw)\n                                {\n                                    \/\/ Setup appropriate options\n                                    osg::ref_ptr local_opt = options ?\n                                        static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) :\n                                        new Options;\n\n                                    local_opt->setPluginStringData(\"STREAM_FILENAME\",osgDB::getSimpleFileName(StreamName));\n\n                                    ReadResult readResult = rw->readNode(buffer,local_opt.get());\n                                    if (readResult.validNode())\n                                    {\n                                        grp->addChild(readResult.takeNode());\n                                    }\n                                }\n                            }\n                        }\n                        if (grp->getNumChildren() > 0)\n                        {\n                            result = grp.get();\n                        }\n                    }\n                    CloseZip(hz);\n                }\n            }\n            delete [] pMemBuffer;\n\n            return result;\n        }\n\n        virtual ReadResult original_readNode(const std::string& file, const osgDB::Options* options) const\n        {\n\n            std::string ext = osgDB::getLowerCaseFileExtension(file);\n            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n            std::string fileName = osgDB::findDataFile( file, options );\n            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n            osg::notify(osg::INFO)<<\"ReaderWriterZIP::readNode( \"< grp = new osg::Group;\n\n            osg::ref_ptr local_options = options ? static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) : new osgDB::ReaderWriter::Options;\n            local_options->getDatabasePathList().push_front(dirname);\n\n            \/\/ deactivate the automatic generation of images to geode's.\n            bool prevCreateNodeFromImage = osgDB::Registry::instance()->getCreateNodeFromImage();\n            osgDB::Registry::instance()->setCreateNodeFromImage(false);\n\n            osgDB::DirectoryContents contents = osgDB::getDirectoryContents(dirname);\n            for(osgDB::DirectoryContents::iterator itr = contents.begin();\n                itr != contents.end();\n                ++itr)\n            {\n                std::string file_ext = osgDB::getFileExtension(*itr);\n                if (!acceptsExtension(file_ext) &&\n                    *itr!=std::string(\".\") &&\n                    *itr!=std::string(\"..\"))\n                {\n                    osg::Node *node = osgDB::readNodeFile( *itr, local_options.get() );\n                    grp->addChild( node );\n                }\n            }\n\n            osgDB::Registry::instance()->setCreateNodeFromImage(prevCreateNodeFromImage);\n\n        #if defined(WIN32) && !defined(__CYGWIN__)\n            \/\/ note, is this the right command for windows?\n            \/\/ is there any way of overiding the Y\/N option? RO.\n            sprintf( command, \"erase \/S \/Q \\\"%s\\\"\", dirname );\n            int result = system( command );\n        #else\n\n            sprintf( command, \"rm -rf %s\", dirname );\n            int result = system( command );\n        #endif\n            if (result!=0) return ReadResult::ERROR_IN_READING_FILE;\n\n            if( grp->getNumChildren() == 0 )\n            {\n                return ReadResult::FILE_NOT_HANDLED;\n            }\n\n            return grp.get();\n        }\n\n};\n\n\/\/ now register with sgRegistry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(zip, ReaderWriterZIP)\n<|endoftext|>"}
{"text":"\/**\n * Path manipulation utilities\n *\/\n\n#include \"path.h\"\n#include \n#include \n#include \n#include \n#include \n\n#ifdef windows\n#\tinclude \n#\tdefine realpath(in, out) _fullpath(out, in, PATH_MAX)\n#endif\n\n\/**\n * Normalize path by removing \".\/\", \"..\/\" and resolving symlinks\n *\/\nstd::string path_normalize(std::string path) {\n\tchar * p = new char[PATH_MAX];\n\trealpath(path.c_str(), p);\n\tstd::string result(p);\n\tdelete[] p;\n\treturn result;\n\/*\n\tstd::string result = path;\n\n\tsize_t pos = 0;\n\tint state = 1; \/\/ 0 bad, 1 just after dirname, 2 dot\n\twhile (pos != result.length()) {\n\t\tchar ch = result.at(pos);\n\t\tswitch (ch) {\n\t\t\tcase '\/':\n\t\t\tcase '\\\\':\n\t\t\t\tif (state == 0) { state = 1; }\n\t\t\t\tif (state == 2) { \n\t\t\t\t\tpos -= 1;\n\t\t\t\t\tresult.erase(pos, 2);\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase '.': \n\t\t\t\tif (state == 1) { \n\t\t\t\t\tstate = 2; \n\t\t\t\t} else {\n\t\t\t\t\tstate = 0;\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault: state = 0; break;\n\t\t}\n\t\tpos++;\n\t}\n\t\n\treturn result;\n*\/\n}\n\n\/**\n * Return file name component of path\n *\/\nstd::string path_filename(std::string path) {\n\tsize_t pos = path_lastslash(path);\n\tif (pos != std::string::npos) { path.erase(0, pos+1); }\n\treturn path;\n}\n\n\/**\n * Return directory name component of path\n *\/\nstd::string path_dirname(std::string path) {\n\tsize_t pos = path_lastslash(path);\n\tif (pos != std::string::npos) { path.erase(pos, path.length()-pos); }\n\treturn path;\n}\n\n\/**\n * Return index of last slash (normal or backslash) in a path\n *\/\nsize_t path_lastslash(std::string path) {\n\tsize_t pos = path.find_last_of('\/');\n\tif (pos == std::string::npos) { pos = path.find_last_of('\\\\'); }\n\treturn pos;\n}\n\n\/**\n * Is this path absolute?\n *\/\nbool path_isabsolute(std::string path) {\n#ifdef windows\n\tsize_t pos = path.find(':');\n\treturn (pos != std::string::npos);\n#else\n\tif (path.length() == 0) { return false; }\n\treturn (path.at(0) == '\/');\n#endif\n}\n \n\/**\n * Does a file exist at this path?\n *\/\nbool path_file_exists(std::string path) {\n\tstruct stat st;\n\tif (stat(path.c_str(), &st) != 0) { return false; } \/* does not exist *\/\n\tif (st.st_mode & S_IFDIR) { return false; } \/* is directory *\/\n\treturn true;\n}\n\n\/**\n * Does a directory exist at this path?\n *\/\nbool path_dir_exists(std::string path) {\n\tstruct stat st;\n\tif (stat(path.c_str(), &st) != 0) { return false; } \/* does not exist *\/\n\tif (st.st_mode & S_IFDIR) { return true; } \/* is directory *\/\n\treturn false;\n}\n\n\/**\n * Get current working directory\n *\/\nstd::string path_getcwd() {\n\treturn getcwd(NULL, 0);\n}\n\n\/**\n * Change current directory\n *\/\nvoid path_chdir(std::string dir) {\n#ifdef VERBOSE\n\tprintf(\"[path_chdir] chdir to '%s'\\n\", dir.c_str()); \n#endif\t\n\tchdir(dir.c_str());\n}\nmemory leak fix\/**\n * Path manipulation utilities\n *\/\n\n#include \"path.h\"\n#include \n#include \n#include \n#include \n#include \n\n#ifdef windows\n#\tinclude \n#\tdefine realpath(in, out) _fullpath(out, in, PATH_MAX)\n#endif\n\n\/**\n * Normalize path by removing \".\/\", \"..\/\" and resolving symlinks\n *\/\nstd::string path_normalize(std::string path) {\n\tchar * p = new char[PATH_MAX];\n\trealpath(path.c_str(), p);\n\tstd::string result(p);\n\tdelete[] p;\n\treturn result;\n\/*\n\tstd::string result = path;\n\n\tsize_t pos = 0;\n\tint state = 1; \/\/ 0 bad, 1 just after dirname, 2 dot\n\twhile (pos != result.length()) {\n\t\tchar ch = result.at(pos);\n\t\tswitch (ch) {\n\t\t\tcase '\/':\n\t\t\tcase '\\\\':\n\t\t\t\tif (state == 0) { state = 1; }\n\t\t\t\tif (state == 2) { \n\t\t\t\t\tpos -= 1;\n\t\t\t\t\tresult.erase(pos, 2);\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase '.': \n\t\t\t\tif (state == 1) { \n\t\t\t\t\tstate = 2; \n\t\t\t\t} else {\n\t\t\t\t\tstate = 0;\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault: state = 0; break;\n\t\t}\n\t\tpos++;\n\t}\n\t\n\treturn result;\n*\/\n}\n\n\/**\n * Return file name component of path\n *\/\nstd::string path_filename(std::string path) {\n\tsize_t pos = path_lastslash(path);\n\tif (pos != std::string::npos) { path.erase(0, pos+1); }\n\treturn path;\n}\n\n\/**\n * Return directory name component of path\n *\/\nstd::string path_dirname(std::string path) {\n\tsize_t pos = path_lastslash(path);\n\tif (pos != std::string::npos) { path.erase(pos, path.length()-pos); }\n\treturn path;\n}\n\n\/**\n * Return index of last slash (normal or backslash) in a path\n *\/\nsize_t path_lastslash(std::string path) {\n\tsize_t pos = path.find_last_of('\/');\n\tif (pos == std::string::npos) { pos = path.find_last_of('\\\\'); }\n\treturn pos;\n}\n\n\/**\n * Is this path absolute?\n *\/\nbool path_isabsolute(std::string path) {\n#ifdef windows\n\tsize_t pos = path.find(':');\n\treturn (pos != std::string::npos);\n#else\n\tif (path.length() == 0) { return false; }\n\treturn (path.at(0) == '\/');\n#endif\n}\n \n\/**\n * Does a file exist at this path?\n *\/\nbool path_file_exists(std::string path) {\n\tstruct stat st;\n\tif (stat(path.c_str(), &st) != 0) { return false; } \/* does not exist *\/\n\tif (st.st_mode & S_IFDIR) { return false; } \/* is directory *\/\n\treturn true;\n}\n\n\/**\n * Does a directory exist at this path?\n *\/\nbool path_dir_exists(std::string path) {\n\tstruct stat st;\n\tif (stat(path.c_str(), &st) != 0) { return false; } \/* does not exist *\/\n\tif (st.st_mode & S_IFDIR) { return true; } \/* is directory *\/\n\treturn false;\n}\n\n\/**\n * Get current working directory\n *\/\nstd::string path_getcwd() {\n\tchar * buf = getcwd(NULL, 0);\n\tstd::string result(buf);\n\tfree(buf);\n\treturn result;\n}\n\n\/**\n * Change current directory\n *\/\nvoid path_chdir(std::string dir) {\n#ifdef VERBOSE\n\tprintf(\"[path_chdir] chdir to '%s'\\n\", dir.c_str()); \n#endif\t\n\tchdir(dir.c_str());\n}\n<|endoftext|>"}
{"text":"#ifndef HEADER_GUARD_MODE_H\n#define HEADER_GUARD_MODE_H\n\n#include \n#include \n#include \n\nextern std::map < char, std::function > global_normal_map;\nextern std::map < char, std::function > global_insert_map;\n\nstruct mode {\n    public:\n    mode(const std::string&, bool (*const handle)(char));\n\n    bool operator()(char);\n\n    mode(const mode&);\n    mode& operator=(const mode&);\n\n    std::string get_name();\n\n    static mode fundamental; \/\/ use global maps only\n\n\n    private:\n    std::string name;\n    \/\/ true = has binding\n    bool (*handle)(char);\n};\n#endif\nMove mode's properties to beginning#ifndef HEADER_GUARD_MODE_H\n#define HEADER_GUARD_MODE_H\n\n#include \n#include \n#include \n\nextern std::map < char, std::function > global_normal_map;\nextern std::map < char, std::function > global_insert_map;\n\nstruct mode {\n    private:\n    std::string name;\n    \/\/ true = has binding\n    bool (*handle)(char);\n\n\n    public:\n    mode(const std::string&, bool (*const handle)(char));\n\n    bool operator()(char);\n\n    mode(const mode&);\n    mode& operator=(const mode&);\n\n    std::string get_name();\n\n    static mode fundamental; \/\/ use global maps only\n};\n#endif\n<|endoftext|>"}
{"text":"\/*\n * qconnman - Connman Applet\n * Copyright (C) 2011 O.S. Systems\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n*\/\n\n#include \"wirelesspage.h\"\n#include \"connman.h\"\n#include \"authdialog.h\"\n#include \"hiddennetworkdialog.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nWirelessPage::WirelessPage(const QModelIndex &technology, Manager *manager, QWidget *parent):\n    QWidget(parent),\n    m_technology(technology),\n    m_service(NULL)\n{\n    ui.setupUi(this);\n\n    m_wireless = static_cast(technology.internalPointer())->object();\n\n    ui.enabled->setChecked(m_wireless->isPowered());\n    ui.ipv4Widget->hide();\n\n    ui.networkList->setModel(manager);\n    ui.networkList->setRootModelIndex(technology);\n    ui.networkList->setCurrentIndex(-1);\n\n    connect(manager, SIGNAL(servicesChanged()), SLOT(configureService()));\n    connect(m_wireless, SIGNAL(dataChanged()), SLOT(updateUi()));\n    connect(ui.enabled, SIGNAL(toggled(bool)), SLOT(toggleTechnology(bool)));\n    connect(ui.networkList, SIGNAL(currentIndexChanged(int)), SLOT(setService(int)));\n\n    configureService();\n    updateUi();\n}\n\nvoid WirelessPage::updateUi()\n{\n    ui.enabled->setChecked(m_wireless->isPowered());\n\n    if (m_service && m_wireless->isPowered() && (m_service->state() == Service::ReadyState || m_service->state() == Service::OnlineState))\n    {\n        ui.status->setText(\"Connected\");\n        ui.ipv4Widget->setService(m_service);\n        ui.ipv4Widget->unhide();\n        ui.advancedButton->setEnabled(true);\n    }\n    else if (!m_service || (m_service->state() == Service::IdleState || m_service->state() == Service::DisconnectState))\n    {\n        ui.status->setText(\"Disconnected\");\n        ui.ipv4Widget->hide();\n    }\n}\n\nvoid WirelessPage::configureService()\n{\n    for (int i = 0; i < m_technology.model()->rowCount(m_technology); i++)\n    {\n        Service *service = static_cast(m_technology.child(i, 0).internalPointer())->object();\n        if (service->type() != \"wifi\") continue;\n\n        if (service->state() == Service::ReadyState || service->state() == Service::OnlineState)\n        {\n            ui.networkList->setCurrentIndex(i);\n            m_service = service;\n            updateUi();\n            break;\n        }\n    }\n}\n\nvoid WirelessPage::unconfigureService()\n{\n    Service *service = (Service *)QObject::sender();\n    if (!service)\n        return;\n    m_service = NULL;\n}\n\nvoid WirelessPage::toggleTechnology(bool enable)\n{\n    m_wireless->setPowered(enable);\n    if (!enable)\n        ui.networkList->setCurrentIndex(-1);\n}\n\nvoid WirelessPage::setService(int index)\n{\n\tif (index == -1) return;\n\n    ManagerNode *node = static_cast(m_technology.child(index, 1).internalPointer());\n    m_service = node->object();\n\n    ui.ipv4Widget->setService(m_service);\n\n    connect(m_service, SIGNAL(dataChanged()), SLOT(updateUi()));\n    connect(m_service, SIGNAL(destroyed()), SLOT(unconfigureService()));\n\n    if (m_service->state() == Service::ReadyState || m_service->state() == Service::OnlineState)\n        ui.ipv4Widget->unhide();\n    else\n        ui.ipv4Widget->hide();\n}\nConnect to service\/*\n * qconnman - Connman Applet\n * Copyright (C) 2011 O.S. Systems\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n*\/\n\n#include \"wirelesspage.h\"\n#include \"connman.h\"\n#include \"authdialog.h\"\n#include \"hiddennetworkdialog.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nWirelessPage::WirelessPage(const QModelIndex &technology, Manager *manager, QWidget *parent):\n    QWidget(parent),\n    m_technology(technology),\n    m_service(NULL)\n{\n    ui.setupUi(this);\n\n    m_wireless = static_cast(technology.internalPointer())->object();\n\n    ui.enabled->setChecked(m_wireless->isPowered());\n    ui.ipv4Widget->hide();\n\n    ui.networkList->setModel(manager);\n    ui.networkList->setRootModelIndex(technology);\n    ui.networkList->setCurrentIndex(-1);\n\n    connect(manager, SIGNAL(servicesChanged()), SLOT(configureService()));\n    connect(m_wireless, SIGNAL(dataChanged()), SLOT(updateUi()));\n    connect(ui.enabled, SIGNAL(toggled(bool)), SLOT(toggleTechnology(bool)));\n    connect(ui.networkList, SIGNAL(currentIndexChanged(int)), SLOT(setService(int)));\n\n    configureService();\n    updateUi();\n}\n\nvoid WirelessPage::updateUi()\n{\n    ui.enabled->setChecked(m_wireless->isPowered());\n\n    if (m_service && m_wireless->isPowered() && (m_service->state() == Service::ReadyState || m_service->state() == Service::OnlineState))\n    {\n        ui.status->setText(\"Connected\");\n        ui.ipv4Widget->setService(m_service);\n        ui.ipv4Widget->unhide();\n        ui.advancedButton->setEnabled(true);\n    }\n    else if (!m_service || (m_service->state() == Service::IdleState || m_service->state() == Service::DisconnectState))\n    {\n        ui.status->setText(\"Disconnected\");\n        ui.ipv4Widget->hide();\n    }\n}\n\nvoid WirelessPage::configureService()\n{\n    for (int i = 0; i < m_technology.model()->rowCount(m_technology); i++)\n    {\n        Service *service = static_cast(m_technology.child(i, 0).internalPointer())->object();\n        if (service->type() != \"wifi\") continue;\n\n        if (service->state() == Service::ReadyState || service->state() == Service::OnlineState)\n        {\n            ui.networkList->setCurrentIndex(i);\n            m_service = service;\n            updateUi();\n            break;\n        }\n    }\n}\n\nvoid WirelessPage::unconfigureService()\n{\n    Service *service = (Service *)QObject::sender();\n    if (!service)\n        return;\n    m_service = NULL;\n}\n\nvoid WirelessPage::toggleTechnology(bool enable)\n{\n    m_wireless->setPowered(enable);\n    if (!enable)\n        ui.networkList->setCurrentIndex(-1);\n}\n\nvoid WirelessPage::setService(int index)\n{\n\tif (index == -1) return;\n\n    ManagerNode *node = static_cast(m_technology.child(index, 1).internalPointer());\n    m_service = node->object();\n\n    ui.ipv4Widget->setService(m_service);\n\n    connect(m_service, SIGNAL(dataChanged()), SLOT(updateUi()));\n    connect(m_service, SIGNAL(destroyed()), SLOT(unconfigureService()));\n\n    if (m_service->state() == Service::ReadyState || m_service->state() == Service::OnlineState)\n        ui.ipv4Widget->unhide();\n    else\n        ui.ipv4Widget->hide();\n\n    m_service->connect();\n}\n<|endoftext|>"}
{"text":"f11fba1e-2e4c-11e5-9284-b827eb9e62bef124c1ee-2e4c-11e5-9284-b827eb9e62bef124c1ee-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2014, Dmitry Senin (seninds@gmail.com)\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/   1. Redistributions of source code must retain the above copyright notice,\n\/\/      this list of conditions and the following disclaimer.\n\/\/   2. Redistributions in binary form must reproduce the above copyright\n\/\/      notice, this list of conditions and the following disclaimer in the\n\/\/      documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ yeti - C++ lightweight threadsafe logging\n\/\/ URL: https:\/\/github.com\/seninds\/yeti.git\n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace yeti {\n\nconst std::map SIGNAME = {\n    { SIGABRT, \"SIGABRT\" },\n    { SIGFPE, \"SIGFPE\" },\n    { SIGILL, \"SIGILL\" },\n    { SIGINT, \"SIGINT\" },\n    { SIGSEGV, \"SIGSEGV\" },\n    { SIGTERM, \"SIGTERM\" }\n};\n\nvoid ShutdownLog() {\n  yeti::Logger::instance().Shutdown();\n}\n\nvoid SignalHandler(int sig_num) {\n  std::fprintf(stderr, \"caught %s: start flushing log...\\n\",\n               SIGNAME.at(sig_num).c_str());\n  std::exit(sig_num);\n}\n\nvoid RegisterSignals() {\n  std::atexit(ShutdownLog);\n  for (const auto& entry : SIGNAME) {\n    signal(entry.first, SignalHandler);\n  }\n}\n\nstd::string _CreateLogStr(const yeti::LogData& log_data) {\n  std::map subs;\n  subs[\"%(LEVEL)\"] = log_data.level;\n  subs[\"%(FILENAME)\"] = log_data.filename;\n  subs[\"%(FUNCNAME)\"] = log_data.funcname;\n  subs[\"%(MSG)\"] = log_data.msg;\n\n  if (log_data.log_format.find(\"%(PID)\") != std::string::npos) {\n    subs[\"%(PID)\"] = std::to_string(log_data.pid);\n  }\n\n  if (log_data.log_format.find(\"%(TID)\") != std::string::npos) {\n    std::hash hash_fn;\n    std::ostringstream oss;\n    oss << std::hex << std::uppercase << hash_fn(log_data.tid);\n    subs[\"%(TID)\"] = oss.str();\n  }\n\n  if (log_data.log_format.find(\"%(DATE)\") != std::string::npos) {\n    using namespace std::chrono;\n    char date_buf[16] = { 0 };\n    auto sec = duration_cast(log_data.time.time_since_epoch());\n    std::time_t t = sec.count();\n    std::strftime(date_buf, sizeof(date_buf), \"%F\", std::localtime(&t));\n    subs[\"%(DATE)\"] = date_buf;\n  }\n\n  if (log_data.log_format.find(\"%(TIME)\") != std::string::npos) {\n    using namespace std::chrono;\n    char time_buf[32] = { 0 };\n    auto nanos = duration_cast(log_data.time.time_since_epoch());\n    auto sec = duration_cast(log_data.time.time_since_epoch());\n    std::time_t t = sec.count();\n    std::size_t frac = nanos.count() % 1000000000;\n    std::strftime(time_buf, sizeof(time_buf), \"%T\", std::localtime(&t));\n    std::string time_str = std::string(time_buf) + \".\" + std::to_string(frac);\n    subs[\"%(TIME)\"] = time_str;\n  }\n\n  if (log_data.log_format.find(\"%(LINE)\") != std::string::npos) {\n    subs[\"%(LINE)\"] = std::to_string(log_data.line);\n  }\n\n  if (log_data.log_format.find(\"%(MSG_ID)\") != std::string::npos) {\n    subs[\"%(MSG_ID)\"] = std::to_string(log_data.msg_id);\n  }\n\n  std::string result = log_data.log_format;\n  size_t pos = 0;\n  for (const auto& entry : subs) {\n    while ((pos = result.find(entry.first)) != std::string::npos) {\n      result.replace(pos, entry.first.length(), entry.second);\n    }\n  }\n  return result;\n}\n\nvoid _EnqueueLogTask(LogData* log_data) {\n  log_data->log_format = yeti::Logger::instance().GetFormatStr();\n  log_data->time = std::chrono::high_resolution_clock::now();\n  log_data->pid = getpid();\n  log_data->tid = std::this_thread::get_id();\n  log_data->fd = yeti::Logger::instance().GetFileDesc();\n  bool is_colored = yeti::Logger::instance().IsColored();\n\n  LogData printed_data = *log_data;\n  auto print_func = [printed_data, is_colored] {\n    std::string log_str = _CreateLogStr(printed_data) + \"\\n\";\n    if (isatty(fileno(printed_data.fd)) != 0 && is_colored) {\n      log_str = printed_data.color + log_str + std::string(YETI_RESET);\n    }\n    std::fprintf(printed_data.fd, log_str.c_str());\n  };\n\n  yeti::Logger::instance().EnqueueTask(print_func);\n}\n\n}  \/\/ namespace yeti\nFixed ANSI escape code bug at WIN32\/\/ Copyright (c) 2014, Dmitry Senin (seninds@gmail.com)\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/   1. Redistributions of source code must retain the above copyright notice,\n\/\/      this list of conditions and the following disclaimer.\n\/\/   2. Redistributions in binary form must reproduce the above copyright\n\/\/      notice, this list of conditions and the following disclaimer in the\n\/\/      documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ yeti - C++ lightweight threadsafe logging\n\/\/ URL: https:\/\/github.com\/seninds\/yeti.git\n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace yeti {\n\nconst std::map SIGNAME = {\n    { SIGABRT, \"SIGABRT\" },\n    { SIGFPE, \"SIGFPE\" },\n    { SIGILL, \"SIGILL\" },\n    { SIGINT, \"SIGINT\" },\n    { SIGSEGV, \"SIGSEGV\" },\n    { SIGTERM, \"SIGTERM\" }\n};\n\nvoid ShutdownLog() {\n  yeti::Logger::instance().Shutdown();\n}\n\nvoid SignalHandler(int sig_num) {\n  std::fprintf(stderr, \"caught %s: start flushing log...\\n\",\n               SIGNAME.at(sig_num).c_str());\n  std::exit(sig_num);\n}\n\nvoid RegisterSignals() {\n  std::atexit(ShutdownLog);\n  for (const auto& entry : SIGNAME) {\n    signal(entry.first, SignalHandler);\n  }\n}\n\nstd::string _CreateLogStr(const yeti::LogData& log_data) {\n  std::map subs;\n  subs[\"%(LEVEL)\"] = log_data.level;\n  subs[\"%(FILENAME)\"] = log_data.filename;\n  subs[\"%(FUNCNAME)\"] = log_data.funcname;\n  subs[\"%(MSG)\"] = log_data.msg;\n\n  if (log_data.log_format.find(\"%(PID)\") != std::string::npos) {\n    subs[\"%(PID)\"] = std::to_string(log_data.pid);\n  }\n\n  if (log_data.log_format.find(\"%(TID)\") != std::string::npos) {\n    std::hash hash_fn;\n    std::ostringstream oss;\n    oss << std::hex << std::uppercase << hash_fn(log_data.tid);\n    subs[\"%(TID)\"] = oss.str();\n  }\n\n  if (log_data.log_format.find(\"%(DATE)\") != std::string::npos) {\n    using namespace std::chrono;\n    char date_buf[16] = { 0 };\n    auto sec = duration_cast(log_data.time.time_since_epoch());\n    std::time_t t = sec.count();\n    std::strftime(date_buf, sizeof(date_buf), \"%F\", std::localtime(&t));\n    subs[\"%(DATE)\"] = date_buf;\n  }\n\n  if (log_data.log_format.find(\"%(TIME)\") != std::string::npos) {\n    using namespace std::chrono;\n    char time_buf[32] = { 0 };\n    auto nanos = duration_cast(log_data.time.time_since_epoch());\n    auto sec = duration_cast(log_data.time.time_since_epoch());\n    std::time_t t = sec.count();\n    std::size_t frac = nanos.count() % 1000000000;\n    std::strftime(time_buf, sizeof(time_buf), \"%T\", std::localtime(&t));\n    std::string time_str = std::string(time_buf) + \".\" + std::to_string(frac);\n    subs[\"%(TIME)\"] = time_str;\n  }\n\n  if (log_data.log_format.find(\"%(LINE)\") != std::string::npos) {\n    subs[\"%(LINE)\"] = std::to_string(log_data.line);\n  }\n\n  if (log_data.log_format.find(\"%(MSG_ID)\") != std::string::npos) {\n    subs[\"%(MSG_ID)\"] = std::to_string(log_data.msg_id);\n  }\n\n  std::string result = log_data.log_format;\n  size_t pos = 0;\n  for (const auto& entry : subs) {\n    while ((pos = result.find(entry.first)) != std::string::npos) {\n      result.replace(pos, entry.first.length(), entry.second);\n    }\n  }\n  return result;\n}\n\nvoid _EnqueueLogTask(LogData* log_data) {\n  log_data->log_format = yeti::Logger::instance().GetFormatStr();\n  log_data->time = std::chrono::high_resolution_clock::now();\n  log_data->pid = getpid();\n  log_data->tid = std::this_thread::get_id();\n  log_data->fd = yeti::Logger::instance().GetFileDesc();\n  bool is_colored = yeti::Logger::instance().IsColored();\n\n  LogData printed_data = *log_data;\n  auto print_func = [printed_data, is_colored] {\n    std::string log_str = _CreateLogStr(printed_data) + \"\\n\";\n\n\/\/ To colorize stdout and stderr in Windows cmd.exe it is necessary\n\/\/ to include windows.h and use SetConsoleTextAttribute().\n\/\/ It is terrible, so I decided to disable coloring at WIN32 platform.\n#ifndef _WIN32\n    if (isatty(fileno(printed_data.fd)) != 0 && is_colored) {\n      log_str = printed_data.color + log_str + std::string(YETI_RESET);\n    }\n#endif  \/\/ _WIN32\n\n    std::fprintf(printed_data.fd, log_str.c_str());\n  };\n\n  yeti::Logger::instance().EnqueueTask(print_func);\n}\n\n}  \/\/ namespace yeti\n<|endoftext|>"}
{"text":"#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\"modules\/htmTree.h\"\n#include\t\"modules\/kdTree.h\"\n#include        \"misc.h\"\n#include        \"feat.h\"\n#include        \"structs.h\"\n#include        \"collision.h\"\n#include        \"global.h\"\n\/\/reduce redistributes, updates  07\/02\/15 rnc\nint main(int argc, char **argv) {\n\t\/\/\/\/ Initializations ---------------------------------------------\n\tsrand48(1234); \/\/ Make sure we have reproducability\n\tcheck_args(argc);\n\tTime t, time; \/\/ t for global, time for local\n\tinit_time(t);\n\tFeat F;\n\n\t\/\/ Read parameters file \/\/\n\tF.readInputFile(argv[1]);\n\tprintFile(argv[1]);\n    std::cout.flush();\n\t\/\/ Read galaxies\n\tGals G, Secret;\n    MTL Targ, SStars, SkyF;\n    if(F.Ascii){\n        printf(\"to read galaxies\\n\");\n        std::cout.flush();\n        G=read_galaxies_ascii(F);}\n    else{\n        G = read_galaxies(F);\n    }\n\tF.Ngal = G.size();\n    \n\tprintf(\"# Read %s galaxies from %s \\n\",f(F.Ngal).c_str(),F.galFile.c_str());\n        std::cout.flush();\n    std::vector count;\n    count=count_galaxies(G);\n    printf(\" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\\n\");\n    for(int i=0;i<2;i++){printf (\" type %d number  %d  \\n\",i, count[i]);}\n    \/\/ make MTL\n    \/\/read_MTL(G,F,Secret,Targ);\n    \/\/write_MTLfile(Secret,Targ,F);\n    make_MTL_SS_SF(G,Targ,SStars,SkyF,Secret,F);\n    write_MTL_SS_SFfile(Targ,SStars,SkyF,Secret,F);\n\treturn(0);\n  \n}\nprint only part of count#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\n#include\t\"modules\/htmTree.h\"\n#include\t\"modules\/kdTree.h\"\n#include        \"misc.h\"\n#include        \"feat.h\"\n#include        \"structs.h\"\n#include        \"collision.h\"\n#include        \"global.h\"\n\/\/reduce redistributes, updates  07\/02\/15 rnc\nint main(int argc, char **argv) {\n\t\/\/\/\/ Initializations ---------------------------------------------\n\tsrand48(1234); \/\/ Make sure we have reproducability\n\tcheck_args(argc);\n\tTime t, time; \/\/ t for global, time for local\n\tinit_time(t);\n\tFeat F;\n\n\t\/\/ Read parameters file \/\/\n\tF.readInputFile(argv[1]);\n\tprintFile(argv[1]);\n    std::cout.flush();\n\t\/\/ Read galaxies\n\tGals G, Secret;\n    MTL Targ, SStars, SkyF;\n    if(F.Ascii){\n        printf(\"to read galaxies\\n\");\n        std::cout.flush();\n        G=read_galaxies_ascii(F);}\n    else{\n        G = read_galaxies(F);\n    }\n\tF.Ngal = G.size();\n    \n\tprintf(\"# Read %s galaxies from %s \\n\",f(F.Ngal).c_str(),F.galFile.c_str());\n        std::cout.flush();\n    std::vector count;\n    count=count_galaxies(G);\n    printf(\" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\\n\");\n    std::cout.flush();\n    for(int i=0;i<2;i++){printf (\" type %d number  %d  \\n\",i, count[i]);}\n    \/\/ make MTL\n    \/\/read_MTL(G,F,Secret,Targ);\n    \/\/write_MTLfile(Secret,Targ,F);\n    make_MTL_SS_SF(G,Targ,SStars,SkyF,Secret,F);\n    write_MTL_SS_SFfile(Targ,SStars,SkyF,Secret,F);\n\treturn(0);\n  \n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \"thermostat.h\"\n#include \"rtc.h\"\n\ntmElements_t _rtcNow;\n\ntmElementsPtr_t rtcNow() {\n  if (!RTC.read(_rtcNow)) {\n    Serial.println(F(\"Read RTC failed!\"));\n    Serial.println();\n  }\n\n  return &_rtcNow;\n}\n\nvoid setRtc(tmElements_t &now) {\n  if (!RTC.write(now)) {\n    Serial.println(F(\"Set DS1307 time failed\"));\n    Serial.println();\n  }\n}\n\nvoid setupRTC() {\n  _rtcNow.Year = 2016 - 1970;\n  _rtcNow.Month = 11;\n  _rtcNow.Day = 22;\n  _rtcNow.Hour = 15;\n  _rtcNow.Minute = 50;\n  _rtcNow.Second = 0;\n  _rtcNow.Wday = 3;\n\n  if (!RTC.read(_rtcNow)) {\n    if (RTC.chipPresent()) {\n      \/\/ RTC maybe not inited\n      Serial.println(F(\"DS1307 not inited, set time to 2016-11-25 15:50:00\"));\n      setRtc(_rtcNow);\n\n      return;\n    }\n\n    Serial.println(F(\"DS1307 read error!  Please check the circuitry.\"));\n    Serial.println();\n  }\n}\n\nstruct Node {\n  alarmFunc fn;\n  tmElements_t when;\n  Node *next;\n\n  Node(tmElements_t aWhen, alarmFunc aFn) : fn(aFn), when(aWhen), next(NULL) {}\n};\n\nstruct Queue {\n  Node *head;\n\n  void add(Node *);\n  void remove(Node *);\n\n  Queue() : head(NULL) {}\n};\n\nvoid Queue::add(Node *node) {\n  if (head == NULL) {\n    head = node;\n    return;\n  }\n\n  for (Node *p = head; ; p = p->next) {\n    if (p->next == NULL) {\n      p->next = node;\n      break;\n    }\n  }\n}\n\nvoid Queue::remove(Node *node) {\n  for (Node *p = head, *prev = NULL; p != NULL; prev = p, p = p->next) {\n    if (p == node) {\n      if (prev == NULL) {\n        head = p->next;\n      } else {\n        prev->next = p->next;\n      }\n      delete node;\n      break;\n    }\n  }\n}\n\nQueue alarms;\n\nvoid checkAlarm() {\n  tmElementsPtr_t now = rtcNow();\n  for (Node *p = alarms.head; p != NULL; p = p->next) {\n    if (p->when.Month != 255 && p->when.Month != now->Month) {\n      continue;\n    }\n\n    if (p->when.Day != 255 && p->when.Day != now->Day) {\n      continue;\n    }\n\n    if (p->when.Wday != 255 && p->when.Wday != now->Wday) {\n      continue;\n    }\n\n    if (p->when.Hour != 255 && p->when.Hour != now->Hour) {\n      continue;\n    }\n\n    if (p->when.Minute != 255 && p->when.Minute != now->Minute) {\n      continue;\n    }\n\n    p->fn(now);\n  }\n}\n\nvoid *defineRtcAlarm(tmElements_t when, alarmFunc fn) {\n  static bool rtcHosted = false;\n  if (!rtcHosted) {\n    rtcHosted = true;\n    core::clock::interval(30 * 1000, &checkAlarm); \/\/ check alarm every 30 seconds.\n  }\n\n  Node *node = new Node(when, fn);\n  alarms.add(node);\n  return node;\n}\n\nvoid removeRtcAlarm(void *handle) {\n  alarms.remove((Node*)handle);\n}\nAlign rtc alarm to second 00#include \n#include \n#include \n#include \"thermostat.h\"\n#include \"rtc.h\"\n\ntmElements_t _rtcNow;\n\ntmElementsPtr_t rtcNow() {\n  if (!RTC.read(_rtcNow)) {\n    Serial.println(F(\"Read RTC failed!\"));\n    Serial.println();\n  }\n\n  return &_rtcNow;\n}\n\nvoid setRtc(tmElements_t &now) {\n  if (!RTC.write(now)) {\n    Serial.println(F(\"Set DS1307 time failed\"));\n    Serial.println();\n  }\n}\n\nvoid setupRTC() {\n  _rtcNow.Year = 2016 - 1970;\n  _rtcNow.Month = 11;\n  _rtcNow.Day = 22;\n  _rtcNow.Hour = 15;\n  _rtcNow.Minute = 50;\n  _rtcNow.Second = 0;\n  _rtcNow.Wday = 3;\n\n  if (!RTC.read(_rtcNow)) {\n    if (RTC.chipPresent()) {\n      \/\/ RTC maybe not inited\n      Serial.println(F(\"DS1307 not inited, set time to 2016-11-25 15:50:00\"));\n      setRtc(_rtcNow);\n\n      return;\n    }\n\n    Serial.println(F(\"DS1307 read error!  Please check the circuitry.\"));\n    Serial.println();\n  }\n}\n\nstruct Node {\n  alarmFunc fn;\n  tmElements_t when;\n  Node *next;\n\n  Node(tmElements_t aWhen, alarmFunc aFn) : fn(aFn), when(aWhen), next(NULL) {}\n};\n\nstruct Queue {\n  Node *head;\n\n  void add(Node *);\n  void remove(Node *);\n\n  Queue() : head(NULL) {}\n};\n\nvoid Queue::add(Node *node) {\n  if (head == NULL) {\n    head = node;\n    return;\n  }\n\n  for (Node *p = head; ; p = p->next) {\n    if (p->next == NULL) {\n      p->next = node;\n      break;\n    }\n  }\n}\n\nvoid Queue::remove(Node *node) {\n  for (Node *p = head, *prev = NULL; p != NULL; prev = p, p = p->next) {\n    if (p == node) {\n      if (prev == NULL) {\n        head = p->next;\n      } else {\n        prev->next = p->next;\n      }\n      delete node;\n      break;\n    }\n  }\n}\n\nQueue alarms;\n\nvoid checkAlarm() {\n  tmElementsPtr_t now = rtcNow();\n  for (Node *p = alarms.head; p != NULL; p = p->next) {\n    if (p->when.Month != 255 && p->when.Month != now->Month) {\n      continue;\n    }\n\n    if (p->when.Day != 255 && p->when.Day != now->Day) {\n      continue;\n    }\n\n    if (p->when.Wday != 255 && p->when.Wday != now->Wday) {\n      continue;\n    }\n\n    if (p->when.Hour != 255 && p->when.Hour != now->Hour) {\n      continue;\n    }\n\n    if (p->when.Minute != 255 && p->when.Minute != now->Minute) {\n      continue;\n    }\n\n    p->fn(now);\n  }\n}\n\nvoid startRtcAlarm() {\n  \/\/ Start Rtc alarm interval at second zero align to rtc alarm resolution of 1\n  \/\/ minute.\n  \/\/ TODO: if user adjust RTC time, then this align is not effect.\n  core::clock::interval((int32_t)(60) * 1000, &checkAlarm); \/\/ check alarm every 60 seconds.\n}\n\nvoid *defineRtcAlarm(tmElements_t when, alarmFunc fn) {\n  static bool rtcHosted = false;\n  if (!rtcHosted) {\n    rtcHosted = true;\n\n    int32_t delay = 60 - rtcNow()->Second;\n    delay %= 60;\n    core::clock::delay(delay * 1000, startRtcAlarm);\n  }\n\n  Node *node = new Node(when, fn);\n  alarms.add(node);\n  return node;\n}\n\nvoid removeRtcAlarm(void *handle) {\n  alarms.remove((Node*)handle);\n}\n<|endoftext|>"}
{"text":"\/**\\file twist_publisher.cpp\n * \\brief Description...\n *\n * @version 1.0\n * @author Carlos Miguel Correia da Costa\n *\/\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n#include \n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <\/includes>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\nnamespace robot_localization_tools {\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <\/imports>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\/\/ =============================================================================    ============================================================================\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <\/constructors-destructor>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nvoid TwistPublisher::setupConfigurationFromParameterServer(ros::NodeHandlePtr& node_handle, ros::NodeHandlePtr& private_node_handle) {\n\tstd::string twist_publisher_topic;\n\tprivate_node_handle->param(\"TwistPublisher\/twist_publisher_topic\", twist_publisher_topic, std::string(\"cmd_vel\"));\n\ttwist_publisher_ = node_handle->advertise(twist_publisher_topic, 10, true);\n}\n\nvoid TwistPublisher::publishTwistFromParameterServer(ros::NodeHandlePtr& private_node_handle) {\n\tXmlRpc::XmlRpcValue twist_msgs_yaml;\n\tprivate_node_handle->getParam(\"TwistPublisher\/Messages\", twist_msgs_yaml);\n\tgeometry_msgs::Twist twist_msg;\n\n\tfor (int twist_msg_config = 0; twist_msg_config < twist_msgs_yaml.size(); ++twist_msg_config) {\n\t\ttwist_msg.linear.x = twist_msgs_yaml[twist_msg_config][\"linear.x\"];\n\t\ttwist_msg.angular.z = twist_msgs_yaml[twist_msg_config][\"angular.z\"];\n\t\ttwist_publisher_.publish(twist_msg);\n\n\t\tros::Duration twist_duration(twist_msgs_yaml[twist_msg_config][\"duration\"]);\n\t\ttwist_duration.sleep();\n\t}\n}\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <\/TwistPublisher-functions>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\/\/ =============================================================================  <\/public-section>  ===========================================================================\n\n\/\/ =============================================================================      =======================================================================\n\/\/ =============================================================================   <\/protected-section>  =======================================================================\n\n\/\/ =============================================================================      =========================================================================\n\/\/ =============================================================================   <\/private-section>  =========================================================================\n\n\/\/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>