hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6f591527b2be7029eee4abfee918a2c3df84cc94 | 11,940 | cc | C++ | dcmpstat/libsrc/dvpsspl.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 10 | 2016-07-03T12:16:58.000Z | 2021-12-18T06:15:50.000Z | dcmpstat/libsrc/dvpsspl.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 1 | 2020-04-30T07:55:55.000Z | 2020-04-30T07:55:55.000Z | dcmpstat/libsrc/dvpsspl.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 9 | 2017-02-09T02:16:39.000Z | 2021-01-06T02:49:24.000Z | /*
*
* Copyright (C) 1998-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmpstat
*
* Author: Marco Eichelberg
*
* Purpose:
* classes: DVPSStoredPrint_PList
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmpstat/dvpsspl.h"
#include "dcmtk/dcmpstat/dvpssp.h" /* for DVPSStoredPrint */
#include "dcmtk/dcmpstat/dvpsib.h" /* for DVPSImageBoxContent */
#include "dcmtk/dcmpstat/dviface.h"
#include "dcmtk/dcmpstat/dvpsdef.h"
#include "dcmtk/dcmpstat/dvpsov.h" /* for DVPSOverlay, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsgl.h" /* for DVPSGraphicLayer, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsrs.h" /* for DVPSReferencedSeries, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsal.h" /* for DVPSOverlayCurveActivationLayer, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsga.h" /* for DVPSGraphicAnnotation, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpscu.h" /* for DVPSCurve, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsvl.h" /* for DVPSVOILUT, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsvw.h" /* for DVPSVOIWindow, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsda.h" /* for DVPSDisplayedArea, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpssv.h" /* for DVPSSoftcopyVOI, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsab.h" /* for DVPSAnnotationContent, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpstx.h" /* for DVPSTextObject, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsgr.h" /* for DVPSGraphicObject, needed by MSVC5 with STL */
#include "dcmtk/dcmpstat/dvpsri.h" /* for DVPSReferencedImage, needed by MSVC5 with STL */
DVPSStoredPrint_PList::DVPSStoredPrint_PList()
: list_()
{
}
DVPSStoredPrint_PList::DVPSStoredPrint_PList(const DVPSStoredPrint_PList &arg)
: list_()
{
OFListConstIterator(DVPSStoredPrint *) first = arg.list_.begin();
OFListConstIterator(DVPSStoredPrint *) last = arg.list_.end();
while (first != last)
{
list_.push_back((*first)->clone());
++first;
}
}
DVPSStoredPrint_PList::~DVPSStoredPrint_PList()
{
clear();
}
void DVPSStoredPrint_PList::clear()
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
delete (*first);
first = list_.erase(first);
}
}
void DVPSStoredPrint_PList::printSCPBasicFilmBoxSet(
DVConfiguration& cfg,
const char *cfgname,
T_DIMSE_Message& rq,
DcmDataset *rqDataset,
T_DIMSE_Message& rsp,
DcmDataset *& rspDataset,
OFBool presentationLUTnegotiated,
DVPSPresentationLUT_PList& globalPresentationLUTList)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
OFBool found = OFFalse;
while ((first != last) && (!found))
{
if ((*first)->isFilmBoxInstance(rq.msg.NSetRQ.RequestedSOPInstanceUID)) found = OFTrue;
else ++first;
}
if (found)
{
DVPSStoredPrint *newSP = new DVPSStoredPrint(*(*first));
if (newSP)
{
if (newSP->printSCPSet(cfg, cfgname, rqDataset, rsp, rspDataset, presentationLUTnegotiated, globalPresentationLUTList))
{
// N-SET successful, replace entry in list
delete (*first);
list_.erase(first);
list_.push_back(newSP);
} else delete newSP;
} else {
DCMPSTAT_WARN("cannot update film box, out of memory.");
rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
} else {
// film box does not exist or wrong instance UID
DCMPSTAT_WARN("cannot update film box, object not found.");
rsp.msg.NSetRSP.DimseStatus = STATUS_N_NoSuchObjectInstance;
}
}
void DVPSStoredPrint_PList::printSCPBasicGrayscaleImageBoxSet(
DVInterface& cfg,
const char *cfgname,
T_DIMSE_Message& rq,
DcmDataset *rqDataset,
T_DIMSE_Message& rsp,
DcmDataset *& rspDataset,
OFBool presentationLUTnegotiated)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
DVPSStoredPrint *sp = NULL;
DVPSImageBoxContent *newib = NULL;
while ((first != last) && (sp == NULL))
{
newib = (*first)->duplicateImageBox(rq.msg.NSetRQ.RequestedSOPInstanceUID);
if (newib) sp = *first; else ++first;
}
if (newib && sp)
{
DcmFileFormat imageFile;
DcmDataset *imageDataset = imageFile.getDataset();
if (newib->printSCPSet(cfg, cfgname, rqDataset, rsp, rspDataset, *imageDataset,
sp->getReferencedPresentationLUTAlignment(), presentationLUTnegotiated))
{
if (EC_Normal == sp->writeHardcopyImageAttributes(*imageDataset))
{
// check for image position clash
if (sp->haveImagePositionClash(rq.msg.NSetRQ.RequestedSOPInstanceUID, newib->getImageBoxPosition()))
{
delete rspDataset;
rspDataset = NULL;
DCMPSTAT_WARN("cannot update basic grayscale image box, image position collision.");
rsp.msg.NSetRSP.DimseStatus = STATUS_N_InvalidAttributeValue;
} else {
if (EC_Normal == cfg.saveFileFormatToDB(imageFile))
{
sp->replaceImageBox(newib);
} else {
delete rspDataset;
rspDataset = NULL;
rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
}
} else {
delete rspDataset;
rspDataset = NULL;
DCMPSTAT_WARN("cannot update basic grayscale image box, out of memory.");
rsp.msg.NSetRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
}
} else {
// image box does not exist or wrong instance UID
DCMPSTAT_WARN("cannot update basic grayscale image box, object not found.");
rsp.msg.NSetRSP.DimseStatus = STATUS_N_NoSuchObjectInstance;
}
}
void DVPSStoredPrint_PList::printSCPBasicFilmBoxAction(
DVInterface& cfg,
const char *cfgname,
T_DIMSE_Message& rq,
T_DIMSE_Message& rsp,
DVPSPresentationLUT_PList& globalPresentationLUTList)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
OFBool found = OFFalse;
while ((first != last) && (!found))
{
if ((*first)->isFilmBoxInstance(rq.msg.NActionRQ.RequestedSOPInstanceUID)) found = OFTrue;
else ++first;
}
if (found)
{
DcmFileFormat spFile;
DcmDataset *spDataset = spFile.getDataset();
DVPSStoredPrint *sp = *first;
OFBool writeRequestedImageSize = cfg.getTargetPrinterSupportsRequestedImageSize(cfgname);
sp->updatePresentationLUTList(globalPresentationLUTList);
sp->clearInstanceUID();
if ((*first)->emptyPageWarning())
{
DCMPSTAT_INFO("empty page, will not be stored in database");
if (STATUS_Success == rsp.msg.NActionRSP.DimseStatus) rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFB_Warn_EmptyPage;
} else {
if (EC_Normal == sp->write(*spDataset, writeRequestedImageSize, OFFalse, OFFalse, OFTrue))
{
if (EC_Normal == cfg.saveFileFormatToDB(spFile))
{
// N-ACTION successful.
} else {
rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
} else {
DCMPSTAT_WARN("cannot print basic film box, out of memory.");
rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
}
} else {
// film box does not exist or wrong instance UID
DCMPSTAT_WARN("cannot print film box, object not found.");
rsp.msg.NActionRSP.DimseStatus = STATUS_N_NoSuchObjectInstance;
}
}
void DVPSStoredPrint_PList::printSCPBasicFilmSessionAction(
DVInterface& cfg,
const char *cfgname,
T_DIMSE_Message& rsp,
DVPSPresentationLUT_PList& globalPresentationLUTList)
{
if (size() > 0)
{
OFBool writeRequestedImageSize = cfg.getTargetPrinterSupportsRequestedImageSize(cfgname);
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
DcmFileFormat spFile;
DcmDataset *spDataset = spFile.getDataset();
(*first)->updatePresentationLUTList(globalPresentationLUTList);
(*first)->clearInstanceUID();
if ((*first)->emptyPageWarning())
{
DCMPSTAT_INFO("empty page, will not be stored in database");
if (STATUS_Success == rsp.msg.NActionRSP.DimseStatus) rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFS_Warn_EmptyPage;
} else {
if (EC_Normal == (*first)->write(*spDataset, writeRequestedImageSize, OFFalse, OFFalse, OFTrue))
{
if (EC_Normal == cfg.saveFileFormatToDB(spFile))
{
// success for this film box
} else {
rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
} else {
DCMPSTAT_WARN("cannot print basic film session, out of memory.");
rsp.msg.NActionRSP.DimseStatus = STATUS_N_ProcessingFailure;
}
}
++first;
}
} else {
// no film boxes to print
DCMPSTAT_WARN("cannot print film session, no film box.");
rsp.msg.NActionRSP.DimseStatus = STATUS_N_PRINT_BFS_Fail_NoFilmBox;
}
}
void DVPSStoredPrint_PList::printSCPBasicFilmBoxDelete(T_DIMSE_Message& rq, T_DIMSE_Message& rsp)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
OFBool found = OFFalse;
while ((first != last) && (!found))
{
if ((*first)->isFilmBoxInstance(rq.msg.NDeleteRQ.RequestedSOPInstanceUID)) found = OFTrue;
else ++first;
}
if (found)
{
delete (*first);
list_.erase(first);
} else {
// film box does not exist or wrong instance UID
DCMPSTAT_WARN("cannot delete film box with instance UID '" << rq.msg.NDeleteRQ.RequestedSOPInstanceUID << "': object does not exist.");
rsp.msg.NDeleteRSP.DimseStatus = STATUS_N_NoSuchObjectInstance;
}
}
OFBool DVPSStoredPrint_PList::haveFilmBoxInstance(const char *uid)
{
if (uid==NULL) return OFFalse;
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
if ((*first)->isFilmBoxInstance(uid)) return OFTrue;
else ++first;
}
return OFFalse;
}
OFBool DVPSStoredPrint_PList::usesPresentationLUT(const char *uid)
{
if (uid==NULL) return OFFalse;
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
if ((*first)->usesPresentationLUT(uid)) return OFTrue;
else ++first;
}
return OFFalse;
}
OFBool DVPSStoredPrint_PList::matchesPresentationLUT(DVPSPrintPresentationLUTAlignment align) const
{
OFBool result = OFTrue;
OFListConstIterator(DVPSStoredPrint *) first = list_.begin();
OFListConstIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
result = result && (*first)->matchesPresentationLUT(align);
++first;
}
return result;
}
void DVPSStoredPrint_PList::overridePresentationLUTSettings(
DcmUnsignedShort& newIllumination,
DcmUnsignedShort& newReflectedAmbientLight,
DcmUniqueIdentifier& newReferencedPLUT,
DVPSPrintPresentationLUTAlignment newAlignment)
{
OFListIterator(DVPSStoredPrint *) first = list_.begin();
OFListIterator(DVPSStoredPrint *) last = list_.end();
while (first != last)
{
(*first)->overridePresentationLUTSettings(newIllumination, newReflectedAmbientLight, newReferencedPLUT, newAlignment);
++first;
}
}
| 33.633803 | 139 | 0.687102 | trice-imaging |
6f5b5c581e62b3d363fc5bd1a32840b839d2bf77 | 1,736 | cpp | C++ | src/helpers/Utils.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 11 | 2020-10-13T11:50:29.000Z | 2022-02-27T11:47:34.000Z | src/helpers/Utils.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 15 | 2020-10-07T18:01:27.000Z | 2021-07-08T09:09:13.000Z | src/helpers/Utils.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | 2 | 2020-10-07T21:29:06.000Z | 2020-10-14T18:02:17.000Z | //MIT License
//Copyright (c) 2020 bexoft GmbH (mail@bexoft.de)
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
#include "finalmq/helpers/Utils.h"
#include <assert.h>
namespace finalmq {
void Utils::split(const std::string& src, ssize_t indexBegin, ssize_t indexEnd, char delimiter, std::vector<std::string>& dest)
{
while (indexBegin < indexEnd)
{
size_t pos = src.find_first_of(delimiter, indexBegin);
if (pos == std::string::npos || static_cast<ssize_t>(pos) > indexEnd)
{
pos = indexEnd;
}
ssize_t len = pos - indexBegin;
assert(len >= 0);
dest.emplace_back(&src[indexBegin], len);
indexBegin += len + 1;
}
}
} // namespace finalmq
| 37.73913 | 127 | 0.718318 | mnaveedb |
6f5bca818e2a3c464f8effe2a8604306e66e4ab7 | 327 | cpp | C++ | Semestr_1/HomeWork_11/Number_1/Number_1/test.cpp | SaveliyLipaev/HomeWork | 06994ce6ab6f12dd69507fffb6f2d3ba361f0069 | [
"MIT"
] | null | null | null | Semestr_1/HomeWork_11/Number_1/Number_1/test.cpp | SaveliyLipaev/HomeWork | 06994ce6ab6f12dd69507fffb6f2d3ba361f0069 | [
"MIT"
] | 1 | 2018-11-06T05:30:37.000Z | 2018-11-06T05:30:37.000Z | Semestr_1/HomeWork_11/Number_1/Number_1/test.cpp | SaveliyLipaev/HomeWork | 06994ce6ab6f12dd69507fffb6f2d3ba361f0069 | [
"MIT"
] | null | null | null | #include "KMP.h"
using namespace std;
int readAndTest(string str)
{
ifstream file("Text.txt");
int temp = find(file, str);
file.close();
return temp;
}
bool test()
{
string str1 = "dda";
string str2 = "fff";
string str3 = "egj";
return readAndTest(str1) == -1 && readAndTest(str2) == 40 && readAndTest(str3) == 17;
} | 17.210526 | 86 | 0.642202 | SaveliyLipaev |
6f5d00c5fc96374548bde085971e7a8b45fecae6 | 14,791 | cpp | C++ | tests/LineTests.cpp | lindale-dev/MathGeoLib | bdd01c86b2d1450dfa323366e3b6646e2796e873 | [
"Apache-2.0"
] | null | null | null | tests/LineTests.cpp | lindale-dev/MathGeoLib | bdd01c86b2d1450dfa323366e3b6646e2796e873 | [
"Apache-2.0"
] | null | null | null | tests/LineTests.cpp | lindale-dev/MathGeoLib | bdd01c86b2d1450dfa323366e3b6646e2796e873 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include "../src/MathGeoLib.h"
#include "../src/Math/myassert.h"
#include "TestRunner.h"
MATH_IGNORE_UNUSED_VARS_WARNING
Line RandomLineContainingPoint(const vec &pt);
Ray RandomRayContainingPoint(const vec &pt);
LineSegment RandomLineSegmentContainingPoint(const vec &pt);
RANDOMIZED_TEST(ParallelLineLineClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Line a = RandomLineContainingPoint(pt);
Line b = a;
vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
b.pos += displacement;
if (rng.Int()%2) b.dir = -b.dir;
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
vec closestPointB = b.GetPoint(d2);
vec perpDistance = displacement - displacement.ProjectTo(a.dir);
mgl_assert2(EqualAbs(closestPointA.Distance(closestPointB), perpDistance.Length()), closestPointA.Distance(closestPointB), perpDistance.Length());
}
RANDOMIZED_TEST(ParallelLineRayClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Line a = RandomLineContainingPoint(pt);
Ray b;
vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
b.pos = a.pos + displacement;
b.dir = a.dir;
if (rng.Int()%2) b.dir = -b.dir;
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
vec closestPointB = b.GetPoint(d2);
vec perpDistance = displacement - displacement.ProjectTo(a.dir);
mgl_assert2(EqualAbs(closestPointA.Distance(closestPointB), perpDistance.Length()), closestPointA.Distance(closestPointB), perpDistance.Length());
}
RANDOMIZED_TEST(ParallelLineLineSegmentClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Line a = RandomLineContainingPoint(pt);
LineSegment b;
vec displacement = vec::RandomBox(rng, DIR_VEC_SCALAR(-SCALE), DIR_VEC_SCALAR(SCALE));
b.a = a.pos + displacement;
float len = rng.Float(1e-3f, SCALE) * (rng.Int(0,1) ? 1.f : -1.f);
b.b = b.a + len * a.dir;
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
vec closestPointB = b.GetPoint(d2);
vec perpDistance = displacement - displacement.ProjectTo(a.dir);
mgl_assert2(EqualAbs(closestPointA.Distance(closestPointB), perpDistance.Length()), closestPointA.Distance(closestPointB), perpDistance.Length());
}
RANDOMIZED_TEST(ParallelRayRayClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Ray a = RandomRayContainingPoint(pt);
Ray b = a;
vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
b.pos += displacement;
if (rng.Int()%2) b.dir = -b.dir;
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
vec closestPointB = b.GetPoint(d2);
float cpd = closestPointA.Distance(closestPointB);
mgl_assert(cpd <= displacement.Length()+1e-4f);
MARK_UNUSED(cpd);
float t = a.pos.Distance(b.pos);
mgl_assert(cpd <= t+1e-4f);
MARK_UNUSED(t);
}
RANDOMIZED_TEST(ParallelRayLineSegmentClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Ray a = RandomRayContainingPoint(pt);
LineSegment b;
vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
b.a = a.pos + displacement;
vec dir = rng.Float(1e-3f, SCALE) * a.dir;
if (rng.Int()%2) dir = -dir;
b.b = b.a + dir;
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
vec closestPointB = b.GetPoint(d2);
float cpd = closestPointA.Distance(closestPointB);
mgl_assert(cpd <= displacement.Length()+1e-4f);
MARK_UNUSED(cpd);
float t1 = a.pos.Distance(b.a);
float t2 = a.pos.Distance(b.b);
mgl_assert(cpd <= t1+1e-4f);
mgl_assert(cpd <= t2+1e-4f);
MARK_UNUSED(t1);
MARK_UNUSED(t2);
}
RANDOMIZED_TEST(ParallelLineSegmentLineSegmentClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
LineSegment a = RandomLineSegmentContainingPoint(pt);
LineSegment b;
vec displacement = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
b.a = a.a + displacement;
if (rng.Int()%2)
{
vec dir = (b.a - a.a).ScaledToLength(rng.Float(1e-3f, SCALE));
if (rng.Int()%2) dir = -dir;
b.b = b.a + dir;
}
else
{
b.b = a.b + displacement;
}
if (rng.Int()%2)
std::swap(b.a, b.b);
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
vec closestPointB = b.GetPoint(d2);
float cpd = closestPointA.Distance(closestPointB);
mgl_assert(cpd <= displacement.Length()+1e-4f);
MARK_UNUSED(cpd);
float t1 = a.a.Distance(b.a);
float t2 = a.a.Distance(b.b);
float t3 = a.b.Distance(b.a);
float t4 = a.b.Distance(b.b);
mgl_assert(cpd <= t1+1e-4f);
mgl_assert(cpd <= t2+1e-4f);
mgl_assert(cpd <= t3+1e-4f);
mgl_assert(cpd <= t4+1e-4f);
MARK_UNUSED(t1);
MARK_UNUSED(t2);
MARK_UNUSED(t3);
MARK_UNUSED(t4);
}
RANDOMIZED_TEST(LineLineClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Line a = RandomLineContainingPoint(pt);
Line b = RandomLineContainingPoint(pt2);
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
mgl_assert3(closestPointA.Equals(a.GetPoint(d), 1e-2f), closestPointA, a.GetPoint(d), closestPointA.Distance(a.GetPoint(d)));
vec closestPointB = b.GetPoint(d2);
float D, D2;
vec closestPointB2 = b.ClosestPoint(a, D, D2);
mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2);
mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2);
mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString());
vec closestPointA2 = a.GetPoint(D2);
mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString());
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f);
mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f));
}
RANDOMIZED_TEST(LineRayClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Line a = RandomLineContainingPoint(pt);
Ray b = RandomRayContainingPoint(pt2);
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
vec closestPointAd = a.GetPoint(d);
mgl_assert3(closestPointA.Equals(closestPointAd, 1e-1f), closestPointA, closestPointAd, closestPointA.Distance(closestPointAd));
vec closestPointB = b.GetPoint(d2);
float D, D2;
vec closestPointB2 = b.ClosestPoint(a, D, D2);
// mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2);
// mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2);
mgl_assert(closestPointB.Equals(closestPointB2, 1e-1f));
vec closestPointA2 = a.GetPoint(D2);
mgl_assert(closestPointA.Equals(closestPointA2, 1e-1f));
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-2f);
mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-1f));
mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-1f));
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.pos) + 1e-2f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.pos) + 1e-2f);
}
RANDOMIZED_TEST(LineLineSegmentClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Line a = RandomLineContainingPoint(pt);
LineSegment b = RandomLineSegmentContainingPoint(pt2);
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
mgl_assert3(closestPointA.Equals(a.GetPoint(d), 1e-2f), closestPointA, a.GetPoint(d), closestPointA.Distance(a.GetPoint(d)));
vec closestPointB = b.GetPoint(d2);
float D, D2;
vec closestPointB2 = b.ClosestPoint(a, D, D2);
// mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2);
// mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2);
mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString());
vec closestPointA2 = a.GetPoint(D2);
mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString());
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f);
mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.a) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.b) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.a) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.b) + 1e-3f);
}
RANDOMIZED_TEST(RayRayClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Ray a = RandomRayContainingPoint(pt);
Ray b = RandomRayContainingPoint(pt2);
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
vec closestPointA2 = a.GetPoint(d);
mgl_assert3(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA, closestPointA2, closestPointA.Distance(closestPointA2));
vec closestPointB = b.GetPoint(d2);
float D, D2;
vec closestPointB2 = b.ClosestPoint(a, D, D2);
// mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2);
// mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2);
mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString());
closestPointA2 = a.GetPoint(D2);
mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString());
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f);
mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.pos) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.pos) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointB.Distance(a.pos) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, b.Distance(a.pos) + 1e-3f);
}
RANDOMIZED_TEST(RayLineSegmentClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
Ray a = RandomRayContainingPoint(pt);
LineSegment b = RandomLineSegmentContainingPoint(pt2);
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
mgl_assert3(closestPointA.Equals(a.GetPoint(d), 1e-2f), closestPointA, a.GetPoint(d), closestPointA.Distance(a.GetPoint(d)));
vec closestPointB = b.GetPoint(d2);
float D, D2;
vec closestPointB2 = b.ClosestPoint(a, D, D2);
// mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2);
// mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2);
mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString());
vec closestPointA2 = a.GetPoint(D2);
mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString());
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f);
mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.a) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.b) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.a) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.b) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointB.Distance(a.pos) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, b.Distance(a.pos) + 1e-3f);
}
RANDOMIZED_TEST(LineSegmentLineSegmentClosestPoint)
{
vec pt = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
vec pt2 = vec::RandomBox(rng, POINT_VEC_SCALAR(-SCALE), POINT_VEC_SCALAR(SCALE));
LineSegment a = RandomLineSegmentContainingPoint(pt);
LineSegment b = RandomLineSegmentContainingPoint(pt2);
float d, d2;
vec closestPointA = a.ClosestPoint(b, d, d2);
mgl_assert3(closestPointA.Equals(a.GetPoint(d), 1e-2f), closestPointA, a.GetPoint(d), closestPointA.Distance(a.GetPoint(d)));
vec closestPointB = b.GetPoint(d2);
float D, D2;
vec closestPointB2 = b.ClosestPoint(a, D, D2);
// mgl_assert2(EqualAbs(d, D2, 1e-2f) || EqualRel(d, D2, 1e-2f), d, D2);
// mgl_assert2(EqualAbs(D, d2, 1e-2f) || EqualRel(D, d2, 1e-2f), D, d2);
mgl_assert2(closestPointB.Equals(closestPointB2, 1e-2f), closestPointB.SerializeToCodeString(), closestPointB2.SerializeToCodeString());
vec closestPointA2 = a.GetPoint(D2);
mgl_assert2(closestPointA.Equals(closestPointA2, 1e-2f), closestPointA.SerializeToCodeString(), closestPointA2.SerializeToCodeString());
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, pt.Distance(pt2) + 1e-3f);
mgl_assert(EqualAbs(a.Distance(b), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assert(EqualAbs(b.Distance(a), closestPointA.Distance(closestPointB), 1e-2f));
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.a) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointA.Distance(b.b) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.a) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, a.Distance(b.b) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointB.Distance(a.a) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, closestPointB.Distance(a.b) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, b.Distance(a.a) + 1e-3f);
mgl_assertcmp(closestPointA.Distance(closestPointB), <=, b.Distance(a.b) + 1e-3f);
}
| 45.371166 | 147 | 0.747279 | lindale-dev |
6f5d4f14fed83eb31f03d6488066852d15840ad1 | 28,327 | cc | C++ | src/protos/Docflow/DocumentWithDocflowV3.pb.cc | Edw-K/diadocsdk-cpp | c50c5ceb5e0c897c9322bd7b66c028cdbc82047e | [
"MIT"
] | 7 | 2016-05-31T17:37:54.000Z | 2022-01-17T14:28:18.000Z | src/protos/Docflow/DocumentWithDocflowV3.pb.cc | Edw-K/diadocsdk-cpp | c50c5ceb5e0c897c9322bd7b66c028cdbc82047e | [
"MIT"
] | 22 | 2017-02-07T09:34:02.000Z | 2021-09-06T08:08:34.000Z | src/protos/Docflow/DocumentWithDocflowV3.pb.cc | Edw-K/diadocsdk-cpp | c50c5ceb5e0c897c9322bd7b66c028cdbc82047e | [
"MIT"
] | 23 | 2016-06-07T06:11:47.000Z | 2020-10-06T13:00:21.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Docflow/DocumentWithDocflowV3.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "Docflow/DocumentWithDocflowV3.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace Diadoc {
namespace Api {
namespace Proto {
namespace Docflow {
namespace {
const ::google::protobuf::Descriptor* DocumentWithDocflowV3_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
DocumentWithDocflowV3_reflection_ = NULL;
const ::google::protobuf::Descriptor* LastEvent_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
LastEvent_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_Docflow_2fDocumentWithDocflowV3_2eproto() {
protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"Docflow/DocumentWithDocflowV3.proto");
GOOGLE_CHECK(file != NULL);
DocumentWithDocflowV3_descriptor_ = file->message_type(0);
static const int DocumentWithDocflowV3_offsets_[4] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, documentid_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, lastevent_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, documentinfo_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, docflow_),
};
DocumentWithDocflowV3_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
DocumentWithDocflowV3_descriptor_,
DocumentWithDocflowV3::default_instance_,
DocumentWithDocflowV3_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DocumentWithDocflowV3, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(DocumentWithDocflowV3));
LastEvent_descriptor_ = file->message_type(1);
static const int LastEvent_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LastEvent, eventid_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LastEvent, timestamp_),
};
LastEvent_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
LastEvent_descriptor_,
LastEvent::default_instance_,
LastEvent_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LastEvent, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LastEvent, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(LastEvent));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_Docflow_2fDocumentWithDocflowV3_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
DocumentWithDocflowV3_descriptor_, &DocumentWithDocflowV3::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
LastEvent_descriptor_, &LastEvent::default_instance());
}
} // namespace
void protobuf_ShutdownFile_Docflow_2fDocumentWithDocflowV3_2eproto() {
delete DocumentWithDocflowV3::default_instance_;
delete DocumentWithDocflowV3_reflection_;
delete LastEvent::default_instance_;
delete LastEvent_reflection_;
}
void protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::Diadoc::Api::Proto::protobuf_AddDesc_DocumentId_2eproto();
::Diadoc::Api::Proto::protobuf_AddDesc_Timestamp_2eproto();
::Diadoc::Api::Proto::Docflow::protobuf_AddDesc_Docflow_2fDocumentInfoV3_2eproto();
::Diadoc::Api::Proto::Docflow::protobuf_AddDesc_Docflow_2fDocflowV3_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n#Docflow/DocumentWithDocflowV3.proto\022\030D"
"iadoc.Api.Proto.Docflow\032\020DocumentId.prot"
"o\032\017Timestamp.proto\032\034Docflow/DocumentInfo"
"V3.proto\032\027Docflow/DocflowV3.proto\"\367\001\n\025Do"
"cumentWithDocflowV3\0220\n\nDocumentId\030\001 \002(\0132"
"\034.Diadoc.Api.Proto.DocumentId\0226\n\tLastEve"
"nt\030\002 \002(\0132#.Diadoc.Api.Proto.Docflow.Last"
"Event\022>\n\014DocumentInfo\030\003 \002(\0132(.Diadoc.Api"
".Proto.Docflow.DocumentInfoV3\0224\n\007Docflow"
"\030\004 \002(\0132#.Diadoc.Api.Proto.Docflow.Docflo"
"wV3\"L\n\tLastEvent\022\017\n\007EventId\030\001 \002(\t\022.\n\tTim"
"estamp\030\002 \002(\0132\033.Diadoc.Api.Proto.Timestam"
"p", 481);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"Docflow/DocumentWithDocflowV3.proto", &protobuf_RegisterTypes);
DocumentWithDocflowV3::default_instance_ = new DocumentWithDocflowV3();
LastEvent::default_instance_ = new LastEvent();
DocumentWithDocflowV3::default_instance_->InitAsDefaultInstance();
LastEvent::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_Docflow_2fDocumentWithDocflowV3_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_Docflow_2fDocumentWithDocflowV3_2eproto {
StaticDescriptorInitializer_Docflow_2fDocumentWithDocflowV3_2eproto() {
protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto();
}
} static_descriptor_initializer_Docflow_2fDocumentWithDocflowV3_2eproto_;
// ===================================================================
#ifndef _MSC_VER
const int DocumentWithDocflowV3::kDocumentIdFieldNumber;
const int DocumentWithDocflowV3::kLastEventFieldNumber;
const int DocumentWithDocflowV3::kDocumentInfoFieldNumber;
const int DocumentWithDocflowV3::kDocflowFieldNumber;
#endif // !_MSC_VER
DocumentWithDocflowV3::DocumentWithDocflowV3()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
}
void DocumentWithDocflowV3::InitAsDefaultInstance() {
documentid_ = const_cast< ::Diadoc::Api::Proto::DocumentId*>(&::Diadoc::Api::Proto::DocumentId::default_instance());
lastevent_ = const_cast< ::Diadoc::Api::Proto::Docflow::LastEvent*>(&::Diadoc::Api::Proto::Docflow::LastEvent::default_instance());
documentinfo_ = const_cast< ::Diadoc::Api::Proto::Docflow::DocumentInfoV3*>(&::Diadoc::Api::Proto::Docflow::DocumentInfoV3::default_instance());
docflow_ = const_cast< ::Diadoc::Api::Proto::Docflow::DocflowV3*>(&::Diadoc::Api::Proto::Docflow::DocflowV3::default_instance());
}
DocumentWithDocflowV3::DocumentWithDocflowV3(const DocumentWithDocflowV3& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
}
void DocumentWithDocflowV3::SharedCtor() {
_cached_size_ = 0;
documentid_ = NULL;
lastevent_ = NULL;
documentinfo_ = NULL;
docflow_ = NULL;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
DocumentWithDocflowV3::~DocumentWithDocflowV3() {
// @@protoc_insertion_point(destructor:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
SharedDtor();
}
void DocumentWithDocflowV3::SharedDtor() {
if (this != default_instance_) {
delete documentid_;
delete lastevent_;
delete documentinfo_;
delete docflow_;
}
}
void DocumentWithDocflowV3::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* DocumentWithDocflowV3::descriptor() {
protobuf_AssignDescriptorsOnce();
return DocumentWithDocflowV3_descriptor_;
}
const DocumentWithDocflowV3& DocumentWithDocflowV3::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto();
return *default_instance_;
}
DocumentWithDocflowV3* DocumentWithDocflowV3::default_instance_ = NULL;
DocumentWithDocflowV3* DocumentWithDocflowV3::New() const {
return new DocumentWithDocflowV3;
}
void DocumentWithDocflowV3::Clear() {
if (_has_bits_[0 / 32] & 15) {
if (has_documentid()) {
if (documentid_ != NULL) documentid_->::Diadoc::Api::Proto::DocumentId::Clear();
}
if (has_lastevent()) {
if (lastevent_ != NULL) lastevent_->::Diadoc::Api::Proto::Docflow::LastEvent::Clear();
}
if (has_documentinfo()) {
if (documentinfo_ != NULL) documentinfo_->::Diadoc::Api::Proto::Docflow::DocumentInfoV3::Clear();
}
if (has_docflow()) {
if (docflow_ != NULL) docflow_->::Diadoc::Api::Proto::Docflow::DocflowV3::Clear();
}
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool DocumentWithDocflowV3::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required .Diadoc.Api.Proto.DocumentId DocumentId = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_documentid()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_LastEvent;
break;
}
// required .Diadoc.Api.Proto.Docflow.LastEvent LastEvent = 2;
case 2: {
if (tag == 18) {
parse_LastEvent:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_lastevent()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_DocumentInfo;
break;
}
// required .Diadoc.Api.Proto.Docflow.DocumentInfoV3 DocumentInfo = 3;
case 3: {
if (tag == 26) {
parse_DocumentInfo:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_documentinfo()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_Docflow;
break;
}
// required .Diadoc.Api.Proto.Docflow.DocflowV3 Docflow = 4;
case 4: {
if (tag == 34) {
parse_Docflow:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_docflow()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
return false;
#undef DO_
}
void DocumentWithDocflowV3::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
// required .Diadoc.Api.Proto.DocumentId DocumentId = 1;
if (has_documentid()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->documentid(), output);
}
// required .Diadoc.Api.Proto.Docflow.LastEvent LastEvent = 2;
if (has_lastevent()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->lastevent(), output);
}
// required .Diadoc.Api.Proto.Docflow.DocumentInfoV3 DocumentInfo = 3;
if (has_documentinfo()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, this->documentinfo(), output);
}
// required .Diadoc.Api.Proto.Docflow.DocflowV3 Docflow = 4;
if (has_docflow()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, this->docflow(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
}
::google::protobuf::uint8* DocumentWithDocflowV3::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
// required .Diadoc.Api.Proto.DocumentId DocumentId = 1;
if (has_documentid()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, this->documentid(), target);
}
// required .Diadoc.Api.Proto.Docflow.LastEvent LastEvent = 2;
if (has_lastevent()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
2, this->lastevent(), target);
}
// required .Diadoc.Api.Proto.Docflow.DocumentInfoV3 DocumentInfo = 3;
if (has_documentinfo()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
3, this->documentinfo(), target);
}
// required .Diadoc.Api.Proto.Docflow.DocflowV3 Docflow = 4;
if (has_docflow()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
4, this->docflow(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Diadoc.Api.Proto.Docflow.DocumentWithDocflowV3)
return target;
}
int DocumentWithDocflowV3::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// required .Diadoc.Api.Proto.DocumentId DocumentId = 1;
if (has_documentid()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->documentid());
}
// required .Diadoc.Api.Proto.Docflow.LastEvent LastEvent = 2;
if (has_lastevent()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->lastevent());
}
// required .Diadoc.Api.Proto.Docflow.DocumentInfoV3 DocumentInfo = 3;
if (has_documentinfo()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->documentinfo());
}
// required .Diadoc.Api.Proto.Docflow.DocflowV3 Docflow = 4;
if (has_docflow()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->docflow());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void DocumentWithDocflowV3::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const DocumentWithDocflowV3* source =
::google::protobuf::internal::dynamic_cast_if_available<const DocumentWithDocflowV3*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void DocumentWithDocflowV3::MergeFrom(const DocumentWithDocflowV3& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_documentid()) {
mutable_documentid()->::Diadoc::Api::Proto::DocumentId::MergeFrom(from.documentid());
}
if (from.has_lastevent()) {
mutable_lastevent()->::Diadoc::Api::Proto::Docflow::LastEvent::MergeFrom(from.lastevent());
}
if (from.has_documentinfo()) {
mutable_documentinfo()->::Diadoc::Api::Proto::Docflow::DocumentInfoV3::MergeFrom(from.documentinfo());
}
if (from.has_docflow()) {
mutable_docflow()->::Diadoc::Api::Proto::Docflow::DocflowV3::MergeFrom(from.docflow());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void DocumentWithDocflowV3::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void DocumentWithDocflowV3::CopyFrom(const DocumentWithDocflowV3& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool DocumentWithDocflowV3::IsInitialized() const {
if ((_has_bits_[0] & 0x0000000f) != 0x0000000f) return false;
if (has_documentid()) {
if (!this->documentid().IsInitialized()) return false;
}
if (has_lastevent()) {
if (!this->lastevent().IsInitialized()) return false;
}
if (has_documentinfo()) {
if (!this->documentinfo().IsInitialized()) return false;
}
if (has_docflow()) {
if (!this->docflow().IsInitialized()) return false;
}
return true;
}
void DocumentWithDocflowV3::Swap(DocumentWithDocflowV3* other) {
if (other != this) {
std::swap(documentid_, other->documentid_);
std::swap(lastevent_, other->lastevent_);
std::swap(documentinfo_, other->documentinfo_);
std::swap(docflow_, other->docflow_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata DocumentWithDocflowV3::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = DocumentWithDocflowV3_descriptor_;
metadata.reflection = DocumentWithDocflowV3_reflection_;
return metadata;
}
// ===================================================================
#ifndef _MSC_VER
const int LastEvent::kEventIdFieldNumber;
const int LastEvent::kTimestampFieldNumber;
#endif // !_MSC_VER
LastEvent::LastEvent()
: ::google::protobuf::Message() {
SharedCtor();
// @@protoc_insertion_point(constructor:Diadoc.Api.Proto.Docflow.LastEvent)
}
void LastEvent::InitAsDefaultInstance() {
timestamp_ = const_cast< ::Diadoc::Api::Proto::Timestamp*>(&::Diadoc::Api::Proto::Timestamp::default_instance());
}
LastEvent::LastEvent(const LastEvent& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:Diadoc.Api.Proto.Docflow.LastEvent)
}
void LastEvent::SharedCtor() {
::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
eventid_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
timestamp_ = NULL;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
LastEvent::~LastEvent() {
// @@protoc_insertion_point(destructor:Diadoc.Api.Proto.Docflow.LastEvent)
SharedDtor();
}
void LastEvent::SharedDtor() {
if (eventid_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
delete eventid_;
}
if (this != default_instance_) {
delete timestamp_;
}
}
void LastEvent::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* LastEvent::descriptor() {
protobuf_AssignDescriptorsOnce();
return LastEvent_descriptor_;
}
const LastEvent& LastEvent::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_Docflow_2fDocumentWithDocflowV3_2eproto();
return *default_instance_;
}
LastEvent* LastEvent::default_instance_ = NULL;
LastEvent* LastEvent::New() const {
return new LastEvent;
}
void LastEvent::Clear() {
if (_has_bits_[0 / 32] & 3) {
if (has_eventid()) {
if (eventid_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
eventid_->clear();
}
}
if (has_timestamp()) {
if (timestamp_ != NULL) timestamp_->::Diadoc::Api::Proto::Timestamp::Clear();
}
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool LastEvent::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Diadoc.Api.Proto.Docflow.LastEvent)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required string EventId = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_eventid()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->eventid().data(), this->eventid().length(),
::google::protobuf::internal::WireFormat::PARSE,
"eventid");
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_Timestamp;
break;
}
// required .Diadoc.Api.Proto.Timestamp Timestamp = 2;
case 2: {
if (tag == 18) {
parse_Timestamp:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_timestamp()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Diadoc.Api.Proto.Docflow.LastEvent)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Diadoc.Api.Proto.Docflow.LastEvent)
return false;
#undef DO_
}
void LastEvent::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Diadoc.Api.Proto.Docflow.LastEvent)
// required string EventId = 1;
if (has_eventid()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->eventid().data(), this->eventid().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"eventid");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->eventid(), output);
}
// required .Diadoc.Api.Proto.Timestamp Timestamp = 2;
if (has_timestamp()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->timestamp(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Diadoc.Api.Proto.Docflow.LastEvent)
}
::google::protobuf::uint8* LastEvent::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:Diadoc.Api.Proto.Docflow.LastEvent)
// required string EventId = 1;
if (has_eventid()) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->eventid().data(), this->eventid().length(),
::google::protobuf::internal::WireFormat::SERIALIZE,
"eventid");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->eventid(), target);
}
// required .Diadoc.Api.Proto.Timestamp Timestamp = 2;
if (has_timestamp()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
2, this->timestamp(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Diadoc.Api.Proto.Docflow.LastEvent)
return target;
}
int LastEvent::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// required string EventId = 1;
if (has_eventid()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->eventid());
}
// required .Diadoc.Api.Proto.Timestamp Timestamp = 2;
if (has_timestamp()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->timestamp());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void LastEvent::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const LastEvent* source =
::google::protobuf::internal::dynamic_cast_if_available<const LastEvent*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void LastEvent::MergeFrom(const LastEvent& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_eventid()) {
set_eventid(from.eventid());
}
if (from.has_timestamp()) {
mutable_timestamp()->::Diadoc::Api::Proto::Timestamp::MergeFrom(from.timestamp());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void LastEvent::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void LastEvent::CopyFrom(const LastEvent& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool LastEvent::IsInitialized() const {
if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;
if (has_timestamp()) {
if (!this->timestamp().IsInitialized()) return false;
}
return true;
}
void LastEvent::Swap(LastEvent* other) {
if (other != this) {
std::swap(eventid_, other->eventid_);
std::swap(timestamp_, other->timestamp_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata LastEvent::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = LastEvent_descriptor_;
metadata.reflection = LastEvent_reflection_;
return metadata;
}
// @@protoc_insertion_point(namespace_scope)
} // namespace Docflow
} // namespace Proto
} // namespace Api
} // namespace Diadoc
// @@protoc_insertion_point(global_scope)
| 34.629584 | 146 | 0.70198 | Edw-K |
6f5e699fbaa40182d6c01ef357c42a9a1d9eaa44 | 1,422 | cpp | C++ | psx/_dump_/10/_dump_c_src_/diabpsx/psxsrc/psxmsg.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 15 | 2018-06-28T01:11:25.000Z | 2021-09-27T15:57:18.000Z | psx/_dump_/10/_dump_c_src_/diabpsx/psxsrc/psxmsg.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 7 | 2018-06-29T04:08:23.000Z | 2019-10-17T13:57:22.000Z | psx/_dump_/10/_dump_c_src_/diabpsx/psxsrc/psxmsg.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 7 | 2018-06-28T01:11:34.000Z | 2020-05-23T09:21:48.000Z | // C:\diabpsx\PSXSRC\PSXMSG.CPP
#include "types.h"
// address: 0x8008AC10
// line start: 178
// line end: 212
void PSX_WndProc__FUilUl(unsigned int Msg, long wParam, unsigned long lParam) {
}
// address: 0x8008ACC0
// line start: 223
// line end: 256
void PSX_PostWndProc__FUilUl(unsigned int Msg, long wParam, unsigned long lParam) {
}
// address: 0x8008AD60
// line start: 264
// line end: 271
void GoBackLevel__Fv() {
}
// address: 0x8008ADD8
// line start: 275
// line end: 279
void GoWarpLevel__Fv() {
}
// address: 0x8008AE10
// line start: 285
// line end: 291
void PostLoadGame__Fv() {
// register: 16
register int palnum;
}
// address: 0x8008AEAC
// line start: 295
// line end: 310
void GoLoadGame__Fv() {
}
// address: 0x8008AF34
// line start: 316
// line end: 320
void PostGoBackLevel__Fv() {
// register: 16
register int palnum;
}
// address: 0x8008AFCC
// line start: 327
// line end: 330
void GoForwardLevel__Fv() {
}
// address: 0x8008B024
// line start: 334
// line end: 338
void PostGoForwardLevel__Fv() {
// register: 16
register int palnum;
}
// address: 0x8008B0BC
// line start: 346
// line end: 351
void GoNewGame__Fv() {
{
// register: 3
register int i;
}
}
// address: 0x8008B10C
// line start: 355
// line end: 359
void PostNewGame__Fv() {
}
// address: 0x8008B144
// line start: 368
// line end: 379
void LevelToLevelInit__Fv() {
}
| 14.363636 | 83 | 0.665963 | maoa3 |
6f640aab4b430e2a29e45c5ec9aeaac9dee7d887 | 36,232 | cpp | C++ | src/CTimeUnits.cpp | MenaceSan/GrayCore | 244e394adaefa17399232896fbd04b7aaeebac21 | [
"MIT"
] | 1 | 2020-12-18T04:55:27.000Z | 2020-12-18T04:55:27.000Z | src/CTimeUnits.cpp | MenaceSan/GrayCore | 244e394adaefa17399232896fbd04b7aaeebac21 | [
"MIT"
] | null | null | null | src/CTimeUnits.cpp | MenaceSan/GrayCore | 244e394adaefa17399232896fbd04b7aaeebac21 | [
"MIT"
] | null | null | null | //
//! @file cTimeUnits.cpp
//! @copyright 1992 - 2020 Dennis Robinson (http://www.menasoft.com)
//
#include "pch.h"
#include "cTimeUnits.h"
#include "cTimeInt.h"
#include "cTimeZone.h"
#include "StrChar.h"
#include "StrT.h"
#include "cBits.h"
#ifdef __linux__
#include "cTimeVal.h"
#endif
namespace Gray
{
// Stock date time string formats.
const GChar_t cTimeUnits::k_SepsAll[8] = _GT("/ :T.,-"); // All/Any separator that might occur in k_StrFormats.
const GChar_t* cTimeUnits::k_StrFormats[TIME_FORMAT_QTY + 1] =
{
//! strftime() type string formats.
//! @todo USE k_TimeSeparator
_GT("%Y/%m/%d %H:%M:%S"), // TIME_FORMAT_DEFAULT = default Sortable/linear format. "2008/07/09 13:47:10"
_GT("%Y-%m-%d %H:%M:%S"), // TIME_FORMAT_DB = Sorted time = "2008-04-10 13:30:00"
_GT("%Y-%m-%d %H:%M:%S %Z"), // TIME_FORMAT_TZ = Sorted Universal/GMT time = "2008-04-10 13:30:00Z"
_GT("%m/%d/%Y %H:%M:%S"), // TIME_FORMAT_AMERICAN = "07/19/2008 13:47:10"
_GT("%a, %d %b %Y %H:%M:%S %z"), // TIME_FORMAT_HTTP = RFC1123 format "Tue, 03 Oct 2000 22:44:56 GMT"
_GT("%d %b %Y %H:%M:%S %z"), // TIME_FORMAT_SMTP = SMTP wants this format. "7 Aug 2001 10:12:12 GMT"
_GT("%Y/%m/%dT%H:%M:%S"), // TIME_FORMAT_ISO
_GT("%Y/%m/%dT%H:%M:%S%z"), // TIME_FORMAT_ISO_TZ
_GT("%Y%m%d%H%M%S%z"), // TIME_FORMAT_ASN
// 01/06/2016, 11:45 AM (-03:00)
nullptr,
};
const CTimeUnit cTimeUnits::k_Units[TIMEUNIT_QTY] =
{ // m_uSubRatio
{ _GT("year"), _GT("Y"), 1, 3000, 12, 365 * 24 * 60 * 60, 365.25 }, // approximate, depends on leap year.
{ _GT("month"), _GT("M"), 1, 12, 30, 30 * 24 * 60 * 60, 30.43 }, // approximate, depends on month
{ _GT("day"), _GT("d"), 1, 31, 24, 24 * 60 * 60, 1.0 },
{ _GT("hour"), _GT("h"), 0, 23, 60, 60 * 60, 1.0 / (24.0) },
{ _GT("minute"), _GT("m"), 0, 59, 60, 60, 1.0 / (24.0*60.0) },
{ _GT("second"), _GT("s"), 0, 59, 1000, 1, 1.0 / (24.0*60.0*60.0) },
{ _GT("millisec"), _GT("ms"), 0, 999, 1000, 0, 1.0 / (24.0*60.0*60.0*1000.0) },
{ _GT("microsec"), _GT("us"), 0, 999, 0, 0, 1.0 / (24.0*60.0*60.0*1000.0*1000.0) },
{ _GT("TZ"), _GT("TZ"), -24 * 60, 24 * 60, 0, 0, 1.0 }, // TIMEUNIT_TZ
};
const BYTE cTimeUnits::k_MonthDays[2][TIMEMONTH_QTY] = // Jan=0
{
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // normal year
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } // leap year
};
const WORD cTimeUnits::k_MonthDaySums[2][TIMEMONTH_QTY + 1] = // Jan=0
{
{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, // normal year
{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } // leap year
};
const GChar_t* const cTimeUnits::k_MonthName[TIMEMONTH_QTY + 1] = // Jan=0
{
_GT("January"), _GT("February"), _GT("March"), _GT("April"), _GT("May"), _GT("June"),
_GT("July"), _GT("August"), _GT("September"), _GT("October"), _GT("November"), _GT("December"),
nullptr
};
const GChar_t* const cTimeUnits::k_MonthAbbrev[TIMEMONTH_QTY + 1] = // Jan=0
{
_GT("Jan"), _GT("Feb"), _GT("Mar"), _GT("Apr"), _GT("May"), _GT("Jun"),
_GT("Jul"), _GT("Aug"), _GT("Sep"), _GT("Oct"), _GT("Nov"), _GT("Dec"),
nullptr,
};
const GChar_t* const cTimeUnits::k_DayName[TIMEDOW_QTY + 1] = // Sun=0
{
_GT("Sunday"), _GT("Monday"), _GT("Tuesday"), _GT("Wednesday"),
_GT("Thursday"), _GT("Friday"), _GT("Saturday"),
nullptr
};
const GChar_t* const cTimeUnits::k_DayAbbrev[TIMEDOW_QTY + 1] = // Sun=0
{
_GT("Sun"), _GT("Mon"), _GT("Tue"), _GT("Wed"), _GT("Thu"), _GT("Fri"), _GT("Sat"),
nullptr
};
const GChar_t cTimeUnits::k_Seps[3] = _GT("/:"); // Normal date string separators. "/:"
GChar_t cTimeUnits::sm_DateSeparator = '/'; //!< might be . for Germans,
bool cTimeUnits::sm_time24Mode = false;
//******************************************************************************************
#ifdef _WIN32
cTimeUnits::cTimeUnits(const SYSTEMTIME& sysTime)
: m_wYear(sysTime.wYear)
, m_wMonth(sysTime.wMonth) // 1 based.
, m_wDay(sysTime.wDay)
, m_wHour(sysTime.wHour)
, m_wMinute(sysTime.wMinute)
, m_wSecond(sysTime.wSecond)
, m_wMillisecond(sysTime.wMilliseconds)
, m_wMicrosecond(0)
, m_nTZ(0)
{
ASSERT(isValidTimeUnits());
}
bool cTimeUnits::GetSys(SYSTEMTIME& sysTime) const noexcept
{
sysTime.wYear = m_wYear;
sysTime.wMonth = m_wMonth; // 1 based.
sysTime.wDayOfWeek = (WORD)get_DOW(); // Sunday - [0,6] TIMEDOW_TYPE
sysTime.wDay = m_wDay;
sysTime.wHour = m_wHour;
sysTime.wMinute = m_wMinute;
sysTime.wSecond = m_wSecond;
sysTime.wMilliseconds = m_wMillisecond;
return true;
}
void cTimeUnits::SetSys(const SYSTEMTIME& sysTime)
{
m_wYear = sysTime.wYear;
m_wMonth = sysTime.wMonth; // 1 based.
m_wDay = sysTime.wDay;
m_wHour = sysTime.wHour;
m_wMinute = sysTime.wMinute;
m_wSecond = sysTime.wSecond;
m_wMillisecond = sysTime.wMilliseconds;
m_wMicrosecond = 0;
ASSERT(isValidTimeUnits());
}
#endif
void cTimeUnits::SetZeros()
{
cMem::Zero(&m_wYear, TIMEUNIT_QTY * sizeof(m_wYear));
m_wYear = 1; // m_uMin
m_wMonth = 1;
m_wDay = 1;
}
bool cTimeUnits::InitTimeNow(TZ_TYPE nTimeZoneOffset)
{
//! Get the current time, and adjust units for timezone. nDST ??
//! like _WIN32 GetLocalTime(st), GetSystemTime(st)
cTimeInt t;
t.InitTimeNow();
return t.GetTimeUnits(*this, nTimeZoneOffset);
}
COMPARE_TYPE cTimeUnits::Compare(cTimeUnits& b) const
{
//! Compare relevant parts of 2 times.
if (b.m_nTZ != this->m_nTZ)
{
//! @note TODO DOES NOT FACTOR TIMEUNIT_TZ
}
for (int i = TIMEUNIT_Year; i <= TIMEUNIT_Microsecond; i++) // TIMEUNIT_TYPE
{
TIMEUNIT_t nThis = GetUnit((TIMEUNIT_TYPE)i);
TIMEUNIT_t nB = b.GetUnit((TIMEUNIT_TYPE)i);
if (nThis != nB)
{
return (nThis > nB) ? COMPARE_Greater : COMPARE_Less;
}
}
return COMPARE_Equal;
}
bool cTimeUnits::isTimeFuture() const
{
cTimeUnits tNow;
tNow.InitTimeNow((TZ_TYPE)m_nTZ);
return Compare(tNow) >= COMPARE_Greater;
}
bool cTimeUnits::IsValidUnit(TIMEUNIT_TYPE i) const
{
TIMEUNIT_t iUnit = GetUnit(i);
if (iUnit < k_Units[i].m_uMin)
return false;
if (iUnit > k_Units[i].m_uMax)
return false;
return true;
}
bool cTimeUnits::isValidTimeUnits() const
{
//! Are the values in valid range ?
//! @note If we are just using this for time math values may go out of range ?
if (!isValidMonth())
return false;
if (m_wDay < 1 || m_wDay > get_DaysInMonth())
return false;
if (((UINT)m_wHour) > 23)
return false;
if (((UINT)m_wMinute) > 59)
return false;
if (((UINT)m_wSecond) > 59)
return false;
return true;
}
bool cTimeUnits::isReasonableTimeUnits() const
{
//! Is this data reasonable for most purposes?
if (m_wYear < 1900)
return false;
if (m_wYear > 2500)
return false;
return isValidTimeUnits();
}
int GRAYCALL cTimeUnits::IsLeapYear(TIMEUNIT_t wYear) // static
{
//! 0 or 1 NOT Boolean - for array access.
//! Every year divisible by 4 is a leap year.
//! But every year divisible by 100 is NOT a leap year
//! Unless the year is also divisible by 400, then it is still a leap year.
if ((wYear & 3) != 0) // not multiple of 4 = not leap year.
return 0;
if ((wYear % 100) == 0) // multiple of 100. i.e. 1900 is not a leap year.
{
if ((wYear % 400) == 0) // multiple of 400. i.e. 2000 is a leap year.
return 1;
return 0;
}
return 1;
}
int GRAYCALL cTimeUnits::GetLeapYearsSince2K(TIMEUNIT_t wYear) // static
{
//! calculate the number of leap days/years since Jan 1 of a year to Jan 1 2000.
//! (Jan 1 2000 = TIMEDOW_Sat) to Jan 1 wYear
//! can be negative if wYear < 2000
int iYear = wYear - 2000;
int iDays = (iYear > 0) ? 1 : 0;
iYear -= iDays;
iDays += iYear / 4; // add multiple 4 year days
iDays += iYear / 400; // add multiple 400 years days.
iDays -= iYear / 100; // remove multiple 100 years days
return iDays;
}
TIMEDOW_TYPE GRAYCALL cTimeUnits::GetDOW(TIMEUNIT_t wYear, TIMEUNIT_t wMonth, TIMEUNIT_t wDay) // static
{
//! @return day of week for a particular date. TIMEDOW_TYPE
//! wMonth = 1 based
//! wDay = 1 based.
ASSERT(wMonth > 0 && wMonth <= 12);
ASSERT(wDay > 0);
int iDays = (wYear - 2000); // should be *365 but since (364%7)==0 we can omit that.
iDays += GetLeapYearsSince2K(wYear); // can be negative if wYear < 2000
iDays += k_MonthDaySums[IsLeapYear(wYear)][wMonth - 1];
iDays += (wDay - 1) + TIMEDOW_Sat; // (Jan 1 2000 = Sat)
iDays %= TIMEDOW_QTY; // mod 7
if (iDays < 0)
{
iDays += TIMEDOW_QTY;
}
return (TIMEDOW_TYPE)iDays;
}
int GRAYCALL cTimeUnits::GetDOY(TIMEUNIT_t wYear, TIMEUNIT_t wMonth, TIMEUNIT_t wDay) // static
{
//! Day of the year. 0 to 365
//! wMonth = 1 based
//! wDay = 1 based.
ASSERT(wMonth > 0 && wMonth <= 12);
return k_MonthDaySums[IsLeapYear(wYear)][wMonth - 1] + wDay - 1;
}
bool cTimeUnits::isInDST() const
{
//! Is this Date DST? Assuming local time zone honors DST.
//! http://www.worldtimezone.com/daylight.html
//! like the C internal function _isindst(const struct tm *tb)
//! @note
//! rule for years < 1987:
//! begin after 2 AM on the last Sunday in April
//! end 1 AM on the last Sunday in October.
//!
//! rule for years >= 1987:
//! begin after 2 AM on the first Sunday in April
//! end 1 AM on the last Sunday in October.
//!
//! rule for years >= 2007:
//! begin Second Sunday in March 2AM
//! end First Sunday in November 2AM
TIMEUNIT_t wMonthLo;
TIMEUNIT_t wMonthHi;
if (m_wYear >= 2007)
{
// New US idiot rules.
wMonthLo = 3;
wMonthHi = 11;
}
else
{
wMonthLo = 4;
wMonthHi = 10;
}
// If the month is before April or after October, then we know immediately it can't be DST.
if (m_wMonth < wMonthLo || m_wMonth > wMonthHi)
return false;
// If the month is after April and before October then we know immediately it must be DST.
if (m_wMonth > wMonthLo && m_wMonth < wMonthHi)
return true;
// Month is April or October see if date falls between appropriate Sundays.
bool bLow = (m_wMonth < 6);
// What day (of the month) is the Sunday of interest?
TIMEUNIT_t wHour;
int iSunday;
if (m_wYear < 1987)
{
iSunday = 3; // always last Sunday
wHour = (bLow) ? 2 : 1;
}
else if (m_wYear < 2007)
{
iSunday = (bLow) ? 1 : 3; // first or last.
wHour = (bLow) ? 2 : 1;
}
else // >= 2007
{
iSunday = (bLow) ? 2 : 1; // second or first.
wHour = 2;
}
int iDayMin;
switch (iSunday)
{
case 1: // First Sunday of the month
iDayMin = 1;
break;
case 2: // Second Sunday of the month
iDayMin = 8;
break;
default: // Last Sunday in month
iDayMin = k_MonthDays[IsLeapYear(m_wYear)][m_wMonth - 1] - 6;
break;
}
TIMEDOW_TYPE eDOW = GetDOW(m_wYear, m_wMonth, (TIMEUNIT_t)iDayMin); // sun = 0
iSunday = iDayMin + ((7 - eDOW) % 7); // the next Sunday.
if (bLow)
{
return (m_wDay > iSunday || (m_wDay == iSunday && m_wHour >= wHour));
}
else
{
return (m_wDay < iSunday || (m_wDay == iSunday && m_wHour < wHour));
}
}
//******************************************************************
void cTimeUnits::put_DosDate(UINT32 ulDosDate)
{
//! unpack 32 bit DosDate format. for ZIP files and old FAT file system.
//! we could use DosDateTimeToFileTime and LocalFileTimeToFileTime for _WIN32
//! 0-4 =Day of the month (1-31)
//! 5-8 =Month (1 = January, 2 = February, and so on)
//! 9-15 =Year offset from 1980 (add 1980 to get actual year) . 6 bits = 63 years = 2043 failure.
WORD wFatDate = HIWORD(ulDosDate);
// 0-4 =Second divided by 2
// 5-10 =Minute (0-59)
// 11-15 =Hour (0-23 on a 24-hour clock)
WORD wFatTime = LOWORD(ulDosDate);
this->m_wSecond = (TIMEUNIT_t)(2 * (wFatTime & 0x1f)); // 2 second accurate.
this->m_wMinute = (TIMEUNIT_t)((wFatTime >> 5) & 0x3f);
this->m_wHour = (TIMEUNIT_t)((wFatTime >> 11));
this->m_wDay = (TIMEUNIT_t)(wFatDate & 0x1f);
this->m_wMonth = (TIMEUNIT_t)((wFatDate >> 5) & 0x0f);
this->m_wYear = (TIMEUNIT_t)(1980 + (wFatDate >> 9)); // up to 2043
}
UINT32 cTimeUnits::get_DosDate() const
{
//! get/pack a 32 bit DOS date format. for ZIP files. and old FAT file system.
//! ASSUME isValidTimeUnits().
UINT32 year = (UINT32)this->m_wYear; // 1980 to 2043
if (year > 1980)
year -= 1980;
else if (year > 80)
year -= 80;
return (UINT32)(((this->m_wDay) + (32 * (this->m_wMonth)) + (512 * year)) << 16) |
((this->m_wSecond / 2) + (32 * this->m_wMinute) + (2048 * (UINT32)this->m_wHour));
}
void cTimeUnits::AddMonths(int iMonths)
{
//! Add months to this structure. months are not exact time measures, but there are always 12 per year.
//! @arg iMonths = 0 based. Can be <0
iMonths += m_wMonth - 1;
m_wMonth = (TIMEUNIT_t)(1 + (iMonths % 12));
m_wYear = (TIMEUNIT_t)(m_wYear + (iMonths / 12)); // adjust years.
}
void cTimeUnits::AddDays(int iDays)
{
//! Add Days. Adjust for the fact that months and years are not all the same number of days.
//! @arg iDays can be negative.
//! Do we cross years ?
for (;;)
{
// Use GetLeapYearsSince2K to optimize this? don't bother, its never that big.
int iDayOfYear = get_DayOfYear();
int iDaysInYear = get_DaysInYear();
int iDays2 = iDayOfYear + iDays;
if (iDays2 >= iDaysInYear) // advance to next year.
{
ASSERT(iDays > 0);
iDays -= iDaysInYear - iDayOfYear;
m_wYear++;
m_wMonth = 1;
m_wDay = 1;
}
else if (iDays2 < 0) // previous year.
{
ASSERT(iDays < 0);
iDays += iDaysInYear;
m_wYear--;
m_wMonth = 12;
m_wDay = 31;
}
else
break;
}
// Do we cross months?
for (;;)
{
int iDayOfMonth = (m_wDay - 1);
int iDaysInMonth = get_DaysInMonth();
int iDays2 = iDayOfMonth + iDays;
if (iDays2 >= iDaysInMonth) // next month.
{
ASSERT(iDays > 0);
iDays -= iDaysInMonth - iDayOfMonth;
m_wMonth++;
m_wDay = 1;
}
else if (iDays2 < 0) // previous month
{
ASSERT(iDays < 0);
iDays += iDayOfMonth;
m_wMonth--;
m_wDay = get_DaysInMonth();
}
else
{
m_wDay += (TIMEUNIT_t)iDays;
break;
}
}
}
void cTimeUnits::AddSeconds(TIMESECD_t nSeconds)
{
//! Add TimeUnits with seconds. handles very large values of seconds.
//! Used to adjust for TZ and DST.
//! nSeconds can be negative.
int nSecondOfDay = get_SecondOfDay();
int nSeconds2 = nSeconds + nSecondOfDay;
int iDays = 0;
if (nSeconds2 >= k_nSecondsPerDay) // Test days as special case since months are not uniform.
{
// Cross into next day(s). TIMEUNIT_Day
ASSERT(nSeconds > 0);
iDays = nSeconds2 / k_nSecondsPerDay;
do_days:
AddDays(iDays);
nSeconds2 -= iDays * k_nSecondsPerDay;
}
else if (nSeconds2 < 0)
{
// Back to previous day(s). TIMEUNIT_Day
ASSERT(nSeconds < 0);
iDays = (nSeconds2 / k_nSecondsPerDay) - 1;
goto do_days;
}
int iTicksA = ABS(nSeconds2);
ASSERT(iTicksA < k_nSecondsPerDay);
int iUnitDiv = 60 * 60;
for (UINT i = TIMEUNIT_Hour; i <= TIMEUNIT_Second; i++)
{
TIMEUNIT_t iUnits = (TIMEUNIT_t)(nSeconds2 / iUnitDiv);
SetUnit((TIMEUNIT_TYPE)i, iUnits);
ASSERT(IsValidUnit((TIMEUNIT_TYPE)i));
nSeconds2 -= iUnits * iUnitDiv;
iUnitDiv /= 60;
}
}
void cTimeUnits::AddTZ(TZ_TYPE nTimeZoneOffset)
{
//! add TZ Offset in minutes.
if (nTimeZoneOffset == TZ_LOCAL)
{
nTimeZoneOffset = cTimeZoneMgr::GetLocalTimeZoneOffset();
}
m_nTZ = (TIMEUNIT_t)nTimeZoneOffset;
if (nTimeZoneOffset == TZ_UTC) // adjust for timezone and DST, TZ_GMT = 0
return;
TIMESECD_t nAdjustMinutes = -(nTimeZoneOffset);
if (isInDST())
{
nAdjustMinutes += 60; // add hour.
}
// adjust for TZ/DST offsets. may be new day or year ?
AddSeconds(nAdjustMinutes * 60);
}
//******************************************************************
StrLen_t cTimeUnits::GetTimeSpanStr(GChar_t* pszOut, StrLen_t iOutSizeMax, TIMEUNIT_TYPE eUnitHigh, int iUnitsDesired, bool bShortText) const
{
//! A delta/span time string. from years to milliseconds.
//! Get a text description of amount of time span (delta)
//! @arg
//! eUnitHigh = the highest unit, TIMEUNIT_Day, TIMEUNIT_Minute
//! iUnitsDesired = the number of units up the cTimeUnits::k_Units ladder to go. default=2
//! @return
//! length of string in chars
if (iUnitsDesired < 1)
{
iUnitsDesired = 1; // must have at least 1.
}
if (IS_INDEX_BAD_ARRAY(eUnitHigh, cTimeUnits::k_Units))
{
eUnitHigh = TIMEUNIT_Day; // days is highest unit by default. months is not accurate!
}
int iUnitsPrinted = 0;
StrLen_t iOutLen = 0;
UINT64 nUnits = 0;
int i = TIMEUNIT_Year; // 0
for (; i < eUnitHigh; i++)
{
nUnits = (nUnits + GetUnit0((TIMEUNIT_TYPE)i)) * k_Units[i].m_uSubRatio;
}
for (; i < TIMEUNIT_Microsecond; i++) // highest to lowest.
{
nUnits += GetUnit0((TIMEUNIT_TYPE)i);
if (!nUnits) // just skip empty units.
{
continue;
}
if (iOutLen)
{
iOutLen += StrT::CopyLen(pszOut + iOutLen, _GT(" "), iOutSizeMax - iOutLen); // " and ";
}
if (bShortText)
{
iOutLen += StrT::sprintfN(pszOut + iOutLen, iOutSizeMax - iOutLen,
_GT("%u%s"),
(int)nUnits,
StrArg<GChar_t>(cTimeUnits::k_Units[i].m_pszUnitNameS));
}
else if (nUnits == 1)
{
iOutLen += StrT::CopyLen(pszOut + iOutLen, _GT("1 "), iOutSizeMax - iOutLen);
iOutLen += StrT::CopyLen(pszOut + iOutLen, cTimeUnits::k_Units[i].m_pszUnitNameL, iOutSizeMax - iOutLen);
}
else
{
iOutLen += StrT::sprintfN(pszOut + iOutLen, iOutSizeMax - iOutLen,
_GT("%u %ss"),
(int)nUnits,
cTimeUnits::k_Units[i].m_pszUnitNameL);
}
if (++iUnitsPrinted >= iUnitsDesired) // only print iUnitsDesired most significant units of time
break;
nUnits = 0;
}
if (iUnitsPrinted == 0)
{
// just 0
iOutLen = StrT::CopyLen(pszOut, bShortText ? _GT("0s") : _GT("0 seconds"), iOutSizeMax);
}
return iOutLen;
}
StrLen_t cTimeUnits::GetFormStr(GChar_t* pszOut, StrLen_t iOutSizeMax, const GChar_t* pszFormat) const
{
//! Get the time as a formatted string using "C" strftime()
//! build formatted string from cTimeUnits.
//! similar to C stdlib strftime() http://linux.die.net/man/3/strftime
//! add TZ as postfix if desired??
//! used by cTimeDouble::GetTimeFormStr and cTimeInt::GetTimeFormStr
//! @return
//! length of string in chars. <= 0 = failed.
if (((UINT_PTR)pszFormat) < TIME_FORMAT_QTY) // IS_INTRESOURCE()
{
pszFormat = k_StrFormats[((UINT_PTR)pszFormat)];
}
GChar_t szTmp[2];
StrLen_t iOut = 0;
for (StrLen_t i = 0; iOut < iOutSizeMax; i++)
{
GChar_t ch = pszFormat[i];
if (ch == '\0')
break;
if (ch != '%')
{
pszOut[iOut++] = ch;
continue;
}
ch = pszFormat[++i];
if (ch == '\0')
break;
if (ch == '#') // As in the printf function, the # flag may prefix/modify any formatting code
{
ch = pszFormat[++i];
if (ch == '\0')
break;
}
const GChar_t* pszVal = nullptr;
int iValPad = 0;
short wVal = 0;
switch (ch)
{
case '/':
szTmp[0] = sm_DateSeparator;
szTmp[1] = '\0';
pszVal = szTmp;
break;
case '%':
pszVal = _GT("%");
break;
case 'y': // Year without century, as decimal number (00 to 99)
wVal = m_wYear % 100;
iValPad = 2;
break;
case 'Y': // Year with century, as decimal number
wVal = m_wYear;
iValPad = 0;
break;
case 'b': // Abbreviated month name
case 'h':
if (m_wMonth == 0)
break;
pszVal = k_MonthAbbrev[m_wMonth - 1];
break;
case 'B': // Full month name
if (m_wMonth == 0)
break;
pszVal = k_MonthName[m_wMonth - 1];
break;
case 'm': // Month as decimal number (01 to 12)
wVal = m_wMonth;
iValPad = 2;
break;
case 'd': // Day of month as decimal number (01 to 31)
wVal = m_wDay;
iValPad = 2;
break;
case 'a':
pszVal = k_DayAbbrev[get_DOW()];
break;
case 'A':
pszVal = k_DayName[get_DOW()];
break;
case 'w': // Weekday as decimal number (0 to 6; Sunday is 0)
wVal = (WORD)get_DOW();
iValPad = 0;
break;
case 'j': // Day of year as decimal number (001 to 366)
wVal = (WORD)get_DOY();
iValPad = 3;
break;
case 'H': // Hour in 24-hour format (00 to 23)
wVal = m_wHour;
iValPad = 2;
break;
case 'k':
wVal = m_wHour;
iValPad = 0;
break;
case 'I': // Hour in 12-hour format (01 to 12)
wVal = (m_wHour % 12);
iValPad = 2;
if (!wVal)
wVal = 12;
break;
case 'p': // Current locale's A.M./P.M. indicator for 12-hour clock
pszVal = (m_wHour < 12) ? _GT("AM") : _GT("PM");
break;
case 'M': // Minute as decimal number (00 to 59)
wVal = m_wMinute;
iValPad = 2;
break;
case 'S': // Second as decimal number (00 to 59)
wVal = m_wSecond;
iValPad = 2;
break;
case 'Z': // Either the time-zone name or time zone abbreviation, depending on registry settings; no characters if time zone is unknown
{
const cTimeZone* pTZ = cTimeZoneMgr::FindTimeZone((TZ_TYPE)m_nTZ);
if (pTZ != nullptr)
{
pszVal = pTZ->m_pszTimeZoneName;
}
else
{
pszVal = _GT(""); // +00 for timezone.
}
break;
}
case 'z':
{
const cTimeZone* pTZ = cTimeZoneMgr::FindTimeZone((TZ_TYPE)m_nTZ);
if (pTZ != nullptr)
{
pszVal = pTZ->m_pszTimeZoneName;
}
else
{
pszVal = _GT("");
}
break;
}
// TIMEUNIT_Millisecond
// TIMEUNIT_Microsecond
case 'F': // equiv to "%Y-%m-%d" for ISO
case 'c': // Date and time representation appropriate for locale. NOT SUPPORTED.
case 'U': // Week of year as decimal number, with Sunday as first day of week (00 to 53)
case 'W': // Week of year as decimal number, with Monday as first day of week (00 to 53)
case 'x': // Date representation for current locale
case 'X': // Time representation for current locale
default:
ASSERT(0);
break;
}
GChar_t* pszOutCur = pszOut + iOut;
StrLen_t iOutSizeLeft = iOutSizeMax - iOut;
if (pszVal != nullptr)
{
iOut += StrT::CopyLen(pszOutCur, pszVal, iOutSizeLeft);
}
else if (iValPad > 0 && iValPad < iOutSizeLeft)
{
// right padded number.
GChar_t* pszMSD = StrT::ULtoA2(wVal, pszOutCur, iValPad + 1, 10, 'A');
while (pszMSD > pszOutCur)
{
*(--pszMSD) = '0';
}
iOut += iValPad;
}
else
{
iOut += StrT::UtoA(wVal, pszOutCur, iOutSizeLeft);
}
}
pszOut[iOut] = '\0';
return iOut;
}
//******************************************************************
HRESULT cTimeUnits::SetTimeStr(const GChar_t* pszDateTime, TZ_TYPE nTimeZoneOffset)
{
//! set cTimeUnits from a string.
//! @arg
//! pszDateTime = "2008/10/23 12:0:0 PM GMT"
//! rnTimeZoneOffset = if found a time zone indicator in the string. do not set if nothing found.
//! @note
//! Must support all regular TIME_FORMAT_QTY types.
//! @return
//! > 0 length = OK, <=0 = doesn't seem like a valid datetime.
//! e.g. "Sat, 07 Aug 2004 01:20:20", ""
//! toJSON method: "2012-04-23T18:25:43.511Z" is sortable.
SetZeros();
cTimeParser parser;
HRESULT hRes = parser.ParseString(pszDateTime, nullptr);
if (FAILED(hRes))
return hRes;
if (!parser.TestMatches()) // try all formats i know.
return MK_E_SYNTAX;
m_nTZ = (TIMEUNIT_t)nTimeZoneOffset; // allowed to be overridden by cTimeParser.GetTimeUnits
hRes = parser.GetTimeUnits(*this);
if (m_nTZ == TZ_LOCAL)
{
m_nTZ = (TIMEUNIT_t)cTimeZoneMgr::GetLocalTimeZoneOffset();
}
return hRes;
}
//******************************************************************************************
StrLen_t cTimeParser::ParseNamedUnit(const GChar_t* pszName)
{
// Get values for named units. TIMEUNIT_Month, TIMEUNIT_TZ or TIMEUNIT_QTY (for DOW)
ITERATE_t iStart = STR_TABLEFIND_NH(pszName, cTimeUnits::k_MonthName);
if (iStart >= 0)
{
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Month;
m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)(iStart + 1);
return StrT::Len(cTimeUnits::k_MonthName[iStart]);
}
iStart = STR_TABLEFIND_NH(pszName, cTimeUnits::k_MonthAbbrev);
if (iStart >= 0)
{
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Month;
m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)(iStart + 1);
return StrT::Len(cTimeUnits::k_MonthAbbrev[iStart]);
}
iStart = STR_TABLEFIND_NH(pszName, cTimeUnits::k_DayName);
if (iStart >= 0)
{
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_DOW; // Temporary for DOW
m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)iStart;
return StrT::Len(cTimeUnits::k_DayName[iStart]);
}
iStart = STR_TABLEFIND_NH(pszName, cTimeUnits::k_DayAbbrev);
if (iStart >= 0)
{
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_DOW; // Temporary for DOW
m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)iStart;
return StrT::Len(cTimeUnits::k_DayAbbrev[iStart]);
}
const cTimeZone* pTZ = cTimeZoneMgr::FindTimeZoneHead(pszName);
if (pTZ != nullptr)
{
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_TZ;
m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)(pTZ->m_nTimeZoneOffset);
return StrT::Len(pTZ->m_pszTimeZoneName);
}
// AM / PM
if (!StrT::CmpHeadI(_GT("PM"), pszName))
{
// Add 12 hours.
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Hour;
m_Unit[m_iUnitsParsed].m_nValue = 12;
return 2;
}
if (!StrT::CmpHeadI(_GT("AM"), pszName))
{
// Add 0 hours.
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Hour;
m_Unit[m_iUnitsParsed].m_nValue = 0;
return 2;
}
return 0;
}
HRESULT cTimeParser::ParseString(const GChar_t* pszTimeString, const GChar_t* pszSeparators)
{
//! parse the pszTimeString to look for things that look like a date time.
//! parse 3 types of things: Separators, numbers and unit names (e.g. Sunday).
//! @return: m_iUnitsParsed
//! @todo parse odd time zone storage . (-03:00)
if (pszTimeString == nullptr)
return E_POINTER;
const GChar_t* pszSepFind = nullptr;
bool bNeedSep = false;
m_iUnitsParsed = 0;
if (pszSeparators == nullptr)
pszSeparators = cTimeUnits::k_SepsAll;
int i = 0;
for (;;)
{
int iStart = i;
i += StrT::GetNonWhitespaceI(pszTimeString + i);
GChar_t ch = pszTimeString[i];
if ((pszSepFind = StrT::FindChar(pszSeparators, ch)) != nullptr) // its a legal separator char?
{
do_sep:
m_Unit[m_iUnitsParsed].m_iOffsetSep = i;
m_Unit[m_iUnitsParsed].m_Separator = ch;
if (!bNeedSep)
{
// Was just empty!? NOT ALLOWED.
break;
}
bNeedSep = false;
m_iUnitsParsed++;
if (m_iUnitsParsed >= (int)_countof(m_Unit))
break;
if (ch == '\0') // done.
break;
i++;
continue;
}
if (bNeedSep) // must complete the previous first.
{
if (iStart == i) // needed a space separator but didn't get one.
{
if (ch == 'T' && StrChar::IsDigit(pszTimeString[i + 1])) // ISO can use this as a separator.
{
goto do_sep;
}
//! @todo parse odd time zone storage . (-03:00)
// Check for terminating TZ with no separator.
const cTimeZone* pTZ = cTimeZoneMgr::FindTimeZoneHead(pszTimeString + i);
if (pTZ != nullptr)
{
// Insert fake separator.
ch = ' ';
i--;
goto do_sep;
}
break; // quit.
}
// Was whitespace separator.
m_Unit[m_iUnitsParsed].m_iOffsetSep = iStart;
m_Unit[m_iUnitsParsed].m_Separator = ' ';
bNeedSep = false;
m_iUnitsParsed++;
if (m_iUnitsParsed >= (int)_countof(m_Unit))
break;
}
if (ch == '\0') // done.
break;
m_Unit[m_iUnitsParsed].Init();
const GChar_t* pszStart = pszTimeString + i;
if (StrChar::IsDigit(ch))
{
// We found a number. good. use it.
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_Numeric; // this just means its a number. don't care what kind yet. resolve later.
const GChar_t* pszEnd = nullptr;
m_Unit[m_iUnitsParsed].m_nValue = (TIMEUNIT_t)StrT::toI(pszStart, &pszEnd, 10);
if (pszStart >= pszEnd || pszEnd == nullptr)
break;
i += StrT::Diff(pszEnd, pszStart);
bNeedSep = true;
continue;
}
else if (StrChar::IsAlpha(ch)) // specific named units . DOW, TZ, Month.
{
int iLen = ParseNamedUnit(pszStart);
if (iLen <= 0)
break;
i += iLen;
bNeedSep = true;
continue;
}
// nothing more so stop.
break;
}
// The End. post process.
// Identify stuff near : as Time. Always in hour:min:sec format.
int iHourFound = -1;
int iYearFound = -1;
int iMonthFound = -1;
for (i = 0; i < m_iUnitsParsed; i++)
{
if (iMonthFound < 0 && m_Unit[i].m_Type == TIMEUNIT_Month)
{
iMonthFound = i;
}
if (iYearFound < 0 && m_Unit[i].m_Type == TIMEUNIT_Numeric && m_Unit[i].m_nValue > 366)
{
// This must be the year.
iYearFound = i;
m_Unit[i].m_Type = TIMEUNIT_Year;
}
if (iHourFound < 0 && m_Unit[i].m_Type == TIMEUNIT_Numeric && m_Unit[i].m_Separator == ':')
{
iHourFound = i;
m_Unit[i].m_Type = TIMEUNIT_Hour;
i++;
m_Unit[i].m_Type = TIMEUNIT_Minute;
if (i + 1 < m_iUnitsParsed && m_Unit[i + 1].m_Type == TIMEUNIT_Numeric && m_Unit[i].m_Separator == ':')
{
i++;
m_Unit[i].m_Type = TIMEUNIT_Second;
if (i + 1 < m_iUnitsParsed && m_Unit[i + 1].m_Type == TIMEUNIT_Numeric && m_Unit[i].m_Separator == '.')
{
i++;
m_Unit[i].m_Type = TIMEUNIT_Millisecond;
}
}
}
if (iHourFound >= 0 && m_Unit[i].m_Type == TIMEUNIT_Hour) // PM ?
{
m_Unit[i].m_Type = TIMEUNIT_Ignore; // Ignore this from now on.
if (m_Unit[iHourFound].m_nValue < 12)
{
m_Unit[iHourFound].m_nValue += m_Unit[i].m_nValue; // Add 'PM'
}
}
}
// Fail is there are type dupes.
// Find day if month is found ?
// We are not reading a valid time/date anymore. done. stop.
m_Unit[m_iUnitsParsed].m_Type = TIMEUNIT_UNUSED; // end
return m_iUnitsParsed;
}
TIMEUNIT_TYPE GRAYCALL cTimeParser::GetTypeFromFormatCode(GChar_t ch) // static
{
switch (ch)
{
case 'y': // Year without century, as decimal number (00 to 99)
case 'Y': // Year with century, as decimal number
return TIMEUNIT_Year;
case 'b': // Abbreviated month name
case 'h':
case 'B': // Full month name
case 'm': // Month as decimal number (01 to 12)
return TIMEUNIT_Month;
case 'd': // Day of month as decimal number (01 to 31)
return TIMEUNIT_Day;
case 'H': // Hour in 24-hour format (00 to 23)
case 'I': // Hour in 12-hour format (01 to 12)
return TIMEUNIT_Hour;
case 'M': // Minute as decimal number (00 to 59)
return TIMEUNIT_Minute;
case 'S': // Second as decimal number (00 to 59)
return TIMEUNIT_Second;
case 'Z': // Either the time-zone name or time zone abbreviation, depending on registry settings; no characters if time zone is unknown
case 'z':
return TIMEUNIT_TZ;
case 'a':
case 'A': // Day of week.
case 'w': // Weekday as decimal number (0 to 6; Sunday is 0)
return TIMEUNIT_DOW; // No equiv. ignore.
case 'j': // Day of year as decimal number (001 to 366)
case 'p': // Current locale's A.M./P.M. indicator for 12-hour clock
return TIMEUNIT_Ignore; // No equiv. ignore.
}
ASSERT(0);
return TIMEUNIT_UNUSED; // bad
}
int cTimeParser::FindType(TIMEUNIT_TYPE t) const
{
// is this TIMEUNIT_TYPE already used ?
for (int i = 0; i < m_iUnitsParsed; i++)
{
if (m_Unit[i].m_Type == t)
return i;
}
return -1; // TIMEUNIT_TYPE not used.
}
void cTimeParser::SetUnitFormats(const GChar_t* pszFormat)
{
//! Similar to ParseString but assumes we just want to set units from a format string.
m_iUnitsParsed = 0;
int i = 0;
for (;;) // TIMEUNIT_QTY2
{
GChar_t ch = pszFormat[i];
if (ch == '\0')
break;
if (ch != '%')
break;
TIMEUNIT_TYPE eType = GetTypeFromFormatCode(pszFormat[i + 1]);
m_Unit[m_iUnitsParsed].m_Type = eType;
if (IS_INDEX_BAD(eType, TIMEUNIT_Numeric)) // this should not happen ?! bad format string!
break;
m_Unit[m_iUnitsParsed].m_nValue = -1; // set later.
m_Unit[m_iUnitsParsed].m_iOffsetSep = i + 2;
ch = pszFormat[i + 2];
m_Unit[m_iUnitsParsed].m_Separator = ch;
m_iUnitsParsed++;
if (ch == '\0')
break;
i += 3;
i += StrT::GetNonWhitespaceI(pszFormat + i);
}
}
bool GRAYCALL cTimeParser::TestMatchUnit(const cTimeParserUnit& u, TIMEUNIT_TYPE t) // static
{
// is the value and type in cTimeParserUnit compatible with type t;
ASSERT(IS_INDEX_GOOD(u.m_Type, TIMEUNIT_QTY2));
ASSERT(IS_INDEX_GOOD(t, TIMEUNIT_Numeric));
if (IS_INDEX_GOOD_ARRAY(t, cTimeUnits::k_Units))
{
if (u.m_nValue < cTimeUnits::k_Units[t].m_uMin)
return false;
if (u.m_nValue > cTimeUnits::k_Units[t].m_uMax)
return false;
}
if (t == u.m_Type) // exact match is good.
return true;
// TIMEUNIT_Numeric is parsed wildcard (i don't know yet) type.
if (u.m_Type == TIMEUNIT_Numeric) // known types must match. TIMEUNIT_Month or TIMEUNIT_DOW
return true; // It looks like a match ? I guess.
return false; // not a match.
}
bool cTimeParser::TestMatchFormat(const cTimeParser& parserFormat, bool bTrimJunk)
{
//! Does parserFormat fit with data in m_Units ?
//! Does this contain compatible units with parserFormat? if so fix m_Unit types!
//! @arg bTrimJunk = any unrecognized stuff beyond parserFormat can just be trimmed.
ASSERT(m_iUnitsParsed <= (int)_countof(m_Unit));
if (m_iUnitsParsed <= 1)
return false;
int iUnitsMatched = 0;
for (; iUnitsMatched < m_iUnitsParsed && iUnitsMatched < parserFormat.m_iUnitsParsed; iUnitsMatched++) // TIMEUNIT_QTY2
{
if (!TestMatchUnit(m_Unit[iUnitsMatched], parserFormat.m_Unit[iUnitsMatched].m_Type)) // not all parserFormat matched.
return false;
}
// All m_iUnitsParsed matches parserFormat, but is there more ?
if (m_iUnitsParsed > parserFormat.m_iUnitsParsed)
{
// More arguments than the template supplies . is this OK?
// As long as the extra units are assigned and not duplicated we are good.
for (; iUnitsMatched < m_iUnitsParsed; iUnitsMatched++)
{
TIMEUNIT_TYPE t = m_Unit[iUnitsMatched].m_Type;
if (t == TIMEUNIT_Numeric) // cant determine type.
{
if (bTrimJunk)
break;
return false;
}
if (parserFormat.FindType(t) >= 0) // duped.
return false;
if (FindType(t) < iUnitsMatched) // duped.
return false;
}
}
if (iUnitsMatched < parserFormat.m_iUnitsParsed)
{
if (parserFormat.m_iUnitsParsed <= 3) // must have at least 3 parsed units to be valid.
return false;
if (iUnitsMatched < 3)
return false;
// int iLeft = parserFormat.m_iUnitsParsed - m_iUnitsParsed;
}
// Its a match, so fix the ambiguous types.
for (int i = 0; i < iUnitsMatched && i < parserFormat.m_iUnitsParsed; i++)
{
if (m_Unit[i].m_Type == TIMEUNIT_Numeric)
m_Unit[i].m_Type = parserFormat.m_Unit[i].m_Type;
}
m_iUnitsMatched = iUnitsMatched;
return true; // its compatible!
}
bool cTimeParser::TestMatch(const GChar_t* pszFormat)
{
//! Does pszFormat fit with data in m_Units ?
if (pszFormat == nullptr)
return false;
if (m_iUnitsParsed <= 1)
return false;
cTimeParser t1;
t1.SetUnitFormats(pszFormat);
return TestMatchFormat(t1);
}
bool cTimeParser::TestMatches(const GChar_t** ppStrFormats)
{
//! Try standard k_StrFormats to match.
if (m_iUnitsParsed <= 1)
return false;
if (ppStrFormats == nullptr)
{
ppStrFormats = cTimeUnits::k_StrFormats;
}
for (int i = 0; ppStrFormats[i] != nullptr; i++)
{
if (TestMatch(ppStrFormats[i]))
return true;
}
// If all units have assignments then no match is needed ??
return false;
}
HRESULT cTimeParser::GetTimeUnits(OUT cTimeUnits& tu) const
{
//! Make a valid cTimeUnits class from what we already parsed. If i can.
if (!isMatched())
return MK_E_SYNTAX;
for (int i = 0; i < m_iUnitsMatched; i++) // <TIMEUNIT_QTY2
{
if (m_Unit[i].m_Type >= TIMEUNIT_QTY)
{
continue; // TIMEUNIT_DOW, TIMEUNIT_Ignore ignored.
}
tu.SetUnit(m_Unit[i].m_Type, m_Unit[i].m_nValue);
}
return GetMatchedLength();
}
}
| 28.664557 | 142 | 0.627953 | MenaceSan |
6f65e943f84922e051aab70aef8f82b5238e41a5 | 1,055 | hpp | C++ | Fw/Prm/PrmString.hpp | lahiruroot/fprime | 8245dbd0c454e379af3504b70462e98d7f4353c2 | [
"Apache-2.0"
] | 4 | 2021-02-20T13:38:25.000Z | 2021-05-04T17:20:34.000Z | Fw/Prm/PrmString.hpp | lahiruroot/fprime | 8245dbd0c454e379af3504b70462e98d7f4353c2 | [
"Apache-2.0"
] | 4 | 2020-10-12T18:52:14.000Z | 2021-09-02T22:38:58.000Z | Fw/Prm/PrmString.hpp | lahiruroot/fprime | 8245dbd0c454e379af3504b70462e98d7f4353c2 | [
"Apache-2.0"
] | 5 | 2019-09-06T23:25:26.000Z | 2021-06-22T03:01:07.000Z | #ifndef FW_PRM_STRING_TYPE_HPP
#define FW_PRM_STRING_TYPE_HPP
#include <Fw/Types/BasicTypes.hpp>
#include <Fw/Types/StringType.hpp>
#include <FpConfig.hpp>
#include <Fw/Cfg/SerIds.hpp>
namespace Fw {
class ParamString : public Fw::StringBase {
public:
enum {
SERIALIZED_TYPE_ID = FW_TYPEID_PRM_STR,
SERIALIZED_SIZE = FW_PARAM_STRING_MAX_SIZE + sizeof(FwBuffSizeType) // size of buffer + storage of two size words
};
ParamString(const char* src);
ParamString(const StringBase& src);
ParamString(const ParamString& src);
ParamString(void);
ParamString& operator=(const ParamString& other);
ParamString& operator=(const StringBase& other);
ParamString& operator=(const char* other);
~ParamString(void);
const char* toChar(void) const;
NATIVE_UINT_TYPE getCapacity(void) const;
private:
char m_buf[FW_PARAM_STRING_MAX_SIZE];
};
}
#endif
| 27.051282 | 129 | 0.625592 | lahiruroot |
6f674fa14c2da8331dd7575ef3a92eaf379da8b7 | 53,572 | cpp | C++ | src/libraries/dynamicMesh/dynamicMesh/polyMeshAdder/polyMeshAdder.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/dynamicMesh/dynamicMesh/polyMeshAdder/polyMeshAdder.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/dynamicMesh/dynamicMesh/polyMeshAdder/polyMeshAdder.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011-2012 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
\*----------------------------------------------------------------------------*/
#include "polyMeshAdder.hpp"
#include "mapAddedPolyMesh.hpp"
#include "IOobject.hpp"
#include "faceCoupleInfo.hpp"
#include "processorPolyPatch.hpp"
#include "SortableList.hpp"
#include "Time.hpp"
#include "globalMeshData.hpp"
#include "mergePoints.hpp"
#include "polyModifyFace.hpp"
#include "polyRemovePoint.hpp"
#include "polyTopoChange.hpp"
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
// Append all mapped elements of a list to a DynamicList
void CML::polyMeshAdder::append
(
const labelList& map,
const labelList& lst,
DynamicList<label>& dynLst
)
{
dynLst.setCapacity(dynLst.size() + lst.size());
forAll(lst, i)
{
const label newElem = map[lst[i]];
if (newElem != -1)
{
dynLst.append(newElem);
}
}
}
// Append all mapped elements of a list to a DynamicList
void CML::polyMeshAdder::append
(
const labelList& map,
const labelList& lst,
const SortableList<label>& sortedLst,
DynamicList<label>& dynLst
)
{
dynLst.setCapacity(dynLst.size() + lst.size());
forAll(lst, i)
{
const label newElem = map[lst[i]];
if (newElem != -1 && findSortedIndex(sortedLst, newElem) == -1)
{
dynLst.append(newElem);
}
}
}
// Get index of patch in new set of patchnames/types
CML::label CML::polyMeshAdder::patchIndex
(
const polyPatch& p,
DynamicList<word>& allPatchNames,
DynamicList<word>& allPatchTypes
)
{
// Find the patch name on the list. If the patch is already there
// and patch types match, return index
const word& pType = p.type();
const word& pName = p.name();
label patchI = findIndex(allPatchNames, pName);
if (patchI == -1)
{
// Patch not found. Append to the list
allPatchNames.append(pName);
allPatchTypes.append(pType);
return allPatchNames.size() - 1;
}
else if (allPatchTypes[patchI] == pType)
{
// Found name and types match
return patchI;
}
else
{
// Found the name, but type is different
// Duplicate name is not allowed. Create a composite name from the
// patch name and case name
const word& caseName = p.boundaryMesh().mesh().time().caseName();
allPatchNames.append(pName + "_" + caseName);
allPatchTypes.append(pType);
Pout<< "label patchIndex(const polyPatch& p) : "
<< "Patch " << p.index() << " named "
<< pName << " in mesh " << caseName
<< " already exists, but patch types"
<< " do not match.\nCreating a composite name as "
<< allPatchNames.last() << endl;
return allPatchNames.size() - 1;
}
}
// Get index of zone in new set of zone names
CML::label CML::polyMeshAdder::zoneIndex
(
const word& curName,
DynamicList<word>& names
)
{
label zoneI = findIndex(names, curName);
if (zoneI != -1)
{
return zoneI;
}
else
{
// Not found. Add new name to the list
names.append(curName);
return names.size() - 1;
}
}
void CML::polyMeshAdder::mergePatchNames
(
const polyBoundaryMesh& patches0,
const polyBoundaryMesh& patches1,
DynamicList<word>& allPatchNames,
DynamicList<word>& allPatchTypes,
labelList& from1ToAllPatches,
labelList& fromAllTo1Patches
)
{
// Insert the mesh0 patches and zones
allPatchNames.append(patches0.names());
allPatchTypes.append(patches0.types());
// Patches
// ~~~~~~~
// Patches from 0 are taken over as is; those from 1 get either merged
// (if they share name and type) or appended.
// Empty patches are filtered out much much later on.
// Add mesh1 patches and build map both ways.
from1ToAllPatches.setSize(patches1.size());
forAll(patches1, patchI)
{
from1ToAllPatches[patchI] = patchIndex
(
patches1[patchI],
allPatchNames,
allPatchTypes
);
}
allPatchTypes.shrink();
allPatchNames.shrink();
// Invert 1 to all patch map
fromAllTo1Patches.setSize(allPatchNames.size());
fromAllTo1Patches = -1;
forAll(from1ToAllPatches, i)
{
fromAllTo1Patches[from1ToAllPatches[i]] = i;
}
}
CML::labelList CML::polyMeshAdder::getPatchStarts
(
const polyBoundaryMesh& patches
)
{
labelList patchStarts(patches.size());
forAll(patches, patchI)
{
patchStarts[patchI] = patches[patchI].start();
}
return patchStarts;
}
CML::labelList CML::polyMeshAdder::getPatchSizes
(
const polyBoundaryMesh& patches
)
{
labelList patchSizes(patches.size());
forAll(patches, patchI)
{
patchSizes[patchI] = patches[patchI].size();
}
return patchSizes;
}
CML::List<CML::polyPatch*> CML::polyMeshAdder::combinePatches
(
const polyMesh& mesh0,
const polyMesh& mesh1,
const polyBoundaryMesh& allBoundaryMesh,
const label nAllPatches,
const labelList& fromAllTo1Patches,
const label nInternalFaces,
const labelList& nFaces,
labelList& from0ToAllPatches,
labelList& from1ToAllPatches
)
{
const polyBoundaryMesh& patches0 = mesh0.boundaryMesh();
const polyBoundaryMesh& patches1 = mesh1.boundaryMesh();
// Compacted new patch list.
DynamicList<polyPatch*> allPatches(nAllPatches);
// Map from 0 to all patches (since gets compacted)
from0ToAllPatches.setSize(patches0.size());
from0ToAllPatches = -1;
label startFaceI = nInternalFaces;
// Copy patches0 with new sizes. First patches always come from
// mesh0 and will always be present.
forAll(patches0, patchI)
{
// Originates from mesh0. Clone with new size & filter out empty
// patch.
label filteredPatchI;
if (nFaces[patchI] == 0 && isA<processorPolyPatch>(patches0[patchI]))
{
//Pout<< "Removing zero sized mesh0 patch "
// << patches0[patchI].name() << endl;
filteredPatchI = -1;
}
else
{
filteredPatchI = allPatches.size();
allPatches.append
(
patches0[patchI].clone
(
allBoundaryMesh,
filteredPatchI,
nFaces[patchI],
startFaceI
).ptr()
);
startFaceI += nFaces[patchI];
}
// Record new index in allPatches
from0ToAllPatches[patchI] = filteredPatchI;
// Check if patch was also in mesh1 and update its addressing if so.
if (fromAllTo1Patches[patchI] != -1)
{
from1ToAllPatches[fromAllTo1Patches[patchI]] = filteredPatchI;
}
}
// Copy unique patches of mesh1.
forAll(from1ToAllPatches, patchI)
{
label allPatchI = from1ToAllPatches[patchI];
if (allPatchI >= patches0.size())
{
// Patch has not been merged with any mesh0 patch.
label filteredPatchI;
if
(
nFaces[allPatchI] == 0
&& isA<processorPolyPatch>(patches1[patchI])
)
{
//Pout<< "Removing zero sized mesh1 patch "
// << patches1[patchI].name() << endl;
filteredPatchI = -1;
}
else
{
filteredPatchI = allPatches.size();
allPatches.append
(
patches1[patchI].clone
(
allBoundaryMesh,
filteredPatchI,
nFaces[allPatchI],
startFaceI
).ptr()
);
startFaceI += nFaces[allPatchI];
}
from1ToAllPatches[patchI] = filteredPatchI;
}
}
allPatches.shrink();
return allPatches;
}
CML::labelList CML::polyMeshAdder::getFaceOrder
(
const cellList& cells,
const label nInternalFaces,
const labelList& owner,
const labelList& neighbour
)
{
labelList oldToNew(owner.size(), -1);
// Leave boundary faces in order
for (label faceI = nInternalFaces; faceI < owner.size(); ++faceI)
{
oldToNew[faceI] = faceI;
}
// First unassigned face
label newFaceI = 0;
forAll(cells, cellI)
{
const labelList& cFaces = cells[cellI];
SortableList<label> nbr(cFaces.size());
forAll(cFaces, i)
{
label faceI = cFaces[i];
label nbrCellI = neighbour[faceI];
if (nbrCellI != -1)
{
// Internal face. Get cell on other side.
if (nbrCellI == cellI)
{
nbrCellI = owner[faceI];
}
if (cellI < nbrCellI)
{
// CellI is master
nbr[i] = nbrCellI;
}
else
{
// nbrCell is master. Let it handle this face.
nbr[i] = -1;
}
}
else
{
// External face. Do later.
nbr[i] = -1;
}
}
nbr.sort();
forAll(nbr, i)
{
if (nbr[i] != -1)
{
oldToNew[cFaces[nbr.indices()[i]]] = newFaceI++;
}
}
}
// Check done all faces.
forAll(oldToNew, faceI)
{
if (oldToNew[faceI] == -1)
{
FatalErrorInFunction
<< "Did not determine new position"
<< " for face " << faceI
<< abort(FatalError);
}
}
return oldToNew;
}
// Extends face f with split points. cutEdgeToPoints gives for every
// edge the points introduced inbetween the endpoints.
void CML::polyMeshAdder::insertVertices
(
const edgeLookup& cutEdgeToPoints,
const Map<label>& meshToMaster,
const labelList& masterToCutPoints,
const face& masterF,
DynamicList<label>& workFace,
face& allF
)
{
workFace.clear();
// Check any edge for being cut (check on the cut so takes account
// for any point merging on the cut)
forAll(masterF, fp)
{
label v0 = masterF[fp];
label v1 = masterF.nextLabel(fp);
// Copy existing face point
workFace.append(allF[fp]);
// See if any edge between v0,v1
Map<label>::const_iterator v0Fnd = meshToMaster.find(v0);
if (v0Fnd != meshToMaster.end())
{
Map<label>::const_iterator v1Fnd = meshToMaster.find(v1);
if (v1Fnd != meshToMaster.end())
{
// Get edge in cutPoint numbering
edge cutEdge
(
masterToCutPoints[v0Fnd()],
masterToCutPoints[v1Fnd()]
);
edgeLookup::const_iterator iter = cutEdgeToPoints.find(cutEdge);
if (iter != cutEdgeToPoints.end())
{
const edge& e = iter.key();
const labelList& addedPoints = iter();
// cutPoints first in allPoints so no need for renumbering
if (e[0] == cutEdge[0])
{
forAll(addedPoints, i)
{
workFace.append(addedPoints[i]);
}
}
else
{
forAllReverse(addedPoints, i)
{
workFace.append(addedPoints[i]);
}
}
}
}
}
}
if (workFace.size() != allF.size())
{
allF.transfer(workFace);
}
}
// Adds primitives (cells, faces, points)
// Cells:
// - all of mesh0
// - all of mesh1
// Faces:
// - all uncoupled of mesh0
// - all coupled faces
// - all uncoupled of mesh1
// Points:
// - all coupled
// - all uncoupled of mesh0
// - all uncoupled of mesh1
void CML::polyMeshAdder::mergePrimitives
(
const polyMesh& mesh0,
const polyMesh& mesh1,
const faceCoupleInfo& coupleInfo,
const label nAllPatches, // number of patches in the new mesh
const labelList& fromAllTo1Patches,
const labelList& from1ToAllPatches,
pointField& allPoints,
labelList& from0ToAllPoints,
labelList& from1ToAllPoints,
faceList& allFaces,
labelList& allOwner,
labelList& allNeighbour,
label& nInternalFaces,
labelList& nFacesPerPatch,
label& nCells,
labelList& from0ToAllFaces,
labelList& from1ToAllFaces,
labelList& from1ToAllCells
)
{
const polyBoundaryMesh& patches0 = mesh0.boundaryMesh();
const polyBoundaryMesh& patches1 = mesh1.boundaryMesh();
const primitiveFacePatch& cutFaces = coupleInfo.cutFaces();
const indirectPrimitivePatch& masterPatch = coupleInfo.masterPatch();
const indirectPrimitivePatch& slavePatch = coupleInfo.slavePatch();
// Points
// ~~~~~~
// Storage for new points
allPoints.setSize(mesh0.nPoints() + mesh1.nPoints());
label allPointI = 0;
from0ToAllPoints.setSize(mesh0.nPoints());
from0ToAllPoints = -1;
from1ToAllPoints.setSize(mesh1.nPoints());
from1ToAllPoints = -1;
// Copy coupled points (on cut)
{
const pointField& cutPoints = coupleInfo.cutPoints();
//const labelListList& cutToMasterPoints =
// coupleInfo.cutToMasterPoints();
labelListList cutToMasterPoints
(
invertOneToMany
(
cutPoints.size(),
coupleInfo.masterToCutPoints()
)
);
//const labelListList& cutToSlavePoints =
// coupleInfo.cutToSlavePoints();
labelListList cutToSlavePoints
(
invertOneToMany
(
cutPoints.size(),
coupleInfo.slaveToCutPoints()
)
);
forAll(cutPoints, i)
{
allPoints[allPointI] = cutPoints[i];
// Mark all master and slave points referring to this point.
const labelList& masterPoints = cutToMasterPoints[i];
forAll(masterPoints, j)
{
label mesh0PointI = masterPatch.meshPoints()[masterPoints[j]];
from0ToAllPoints[mesh0PointI] = allPointI;
}
const labelList& slavePoints = cutToSlavePoints[i];
forAll(slavePoints, j)
{
label mesh1PointI = slavePatch.meshPoints()[slavePoints[j]];
from1ToAllPoints[mesh1PointI] = allPointI;
}
allPointI++;
}
}
// Add uncoupled mesh0 points
forAll(mesh0.points(), pointI)
{
if (from0ToAllPoints[pointI] == -1)
{
allPoints[allPointI] = mesh0.points()[pointI];
from0ToAllPoints[pointI] = allPointI;
allPointI++;
}
}
// Add uncoupled mesh1 points
forAll(mesh1.points(), pointI)
{
if (from1ToAllPoints[pointI] == -1)
{
allPoints[allPointI] = mesh1.points()[pointI];
from1ToAllPoints[pointI] = allPointI;
allPointI++;
}
}
allPoints.setSize(allPointI);
// Faces
// ~~~~~
// Sizes per patch
nFacesPerPatch.setSize(nAllPatches);
nFacesPerPatch = 0;
// Storage for faces and owner/neighbour
allFaces.setSize(mesh0.nFaces() + mesh1.nFaces());
allOwner.setSize(allFaces.size());
allOwner = -1;
allNeighbour.setSize(allFaces.size());
allNeighbour = -1;
label allFaceI = 0;
from0ToAllFaces.setSize(mesh0.nFaces());
from0ToAllFaces = -1;
from1ToAllFaces.setSize(mesh1.nFaces());
from1ToAllFaces = -1;
// Copy mesh0 internal faces (always uncoupled)
for (label faceI = 0; faceI < mesh0.nInternalFaces(); faceI++)
{
allFaces[allFaceI] = renumber(from0ToAllPoints, mesh0.faces()[faceI]);
allOwner[allFaceI] = mesh0.faceOwner()[faceI];
allNeighbour[allFaceI] = mesh0.faceNeighbour()[faceI];
from0ToAllFaces[faceI] = allFaceI++;
}
// Copy coupled faces. Every coupled face has an equivalent master and
// slave. Also uncount as boundary faces all the newly coupled faces.
const labelList& cutToMasterFaces = coupleInfo.cutToMasterFaces();
const labelList& cutToSlaveFaces = coupleInfo.cutToSlaveFaces();
forAll(cutFaces, i)
{
label masterFaceI = cutToMasterFaces[i];
label mesh0FaceI = masterPatch.addressing()[masterFaceI];
if (from0ToAllFaces[mesh0FaceI] == -1)
{
// First occurrence of face
from0ToAllFaces[mesh0FaceI] = allFaceI;
// External face becomes internal so uncount
label patch0 = patches0.whichPatch(mesh0FaceI);
nFacesPerPatch[patch0]--;
}
label slaveFaceI = cutToSlaveFaces[i];
label mesh1FaceI = slavePatch.addressing()[slaveFaceI];
if (from1ToAllFaces[mesh1FaceI] == -1)
{
from1ToAllFaces[mesh1FaceI] = allFaceI;
label patch1 = patches1.whichPatch(mesh1FaceI);
nFacesPerPatch[from1ToAllPatches[patch1]]--;
}
// Copy cut face (since cutPoints are copied first no renumbering
// necessary)
allFaces[allFaceI] = cutFaces[i];
allOwner[allFaceI] = mesh0.faceOwner()[mesh0FaceI];
allNeighbour[allFaceI] = mesh1.faceOwner()[mesh1FaceI] + mesh0.nCells();
allFaceI++;
}
// Copy mesh1 internal faces (always uncoupled)
for (label faceI = 0; faceI < mesh1.nInternalFaces(); faceI++)
{
allFaces[allFaceI] = renumber(from1ToAllPoints, mesh1.faces()[faceI]);
allOwner[allFaceI] = mesh1.faceOwner()[faceI] + mesh0.nCells();
allNeighbour[allFaceI] = mesh1.faceNeighbour()[faceI] + mesh0.nCells();
from1ToAllFaces[faceI] = allFaceI++;
}
nInternalFaces = allFaceI;
// Copy (unmarked/uncoupled) external faces in new order.
for (label allPatchI = 0; allPatchI < nAllPatches; allPatchI++)
{
if (allPatchI < patches0.size())
{
// Patch is present in mesh0
const polyPatch& pp = patches0[allPatchI];
nFacesPerPatch[allPatchI] += pp.size();
label faceI = pp.start();
forAll(pp, i)
{
if (from0ToAllFaces[faceI] == -1)
{
// Is uncoupled face since has not yet been dealt with
allFaces[allFaceI] = renumber
(
from0ToAllPoints,
mesh0.faces()[faceI]
);
allOwner[allFaceI] = mesh0.faceOwner()[faceI];
allNeighbour[allFaceI] = -1;
from0ToAllFaces[faceI] = allFaceI++;
}
faceI++;
}
}
if (fromAllTo1Patches[allPatchI] != -1)
{
// Patch is present in mesh1
const polyPatch& pp = patches1[fromAllTo1Patches[allPatchI]];
nFacesPerPatch[allPatchI] += pp.size();
label faceI = pp.start();
forAll(pp, i)
{
if (from1ToAllFaces[faceI] == -1)
{
// Is uncoupled face
allFaces[allFaceI] = renumber
(
from1ToAllPoints,
mesh1.faces()[faceI]
);
allOwner[allFaceI] =
mesh1.faceOwner()[faceI]
+ mesh0.nCells();
allNeighbour[allFaceI] = -1;
from1ToAllFaces[faceI] = allFaceI++;
}
faceI++;
}
}
}
allFaces.setSize(allFaceI);
allOwner.setSize(allFaceI);
allNeighbour.setSize(allFaceI);
// So now we have all ok for one-to-one mapping.
// For split slace faces:
// - mesh consistent with slave side
// - mesh not consistent with owner side. It is not zipped up, the
// original faces need edges split.
// Use brute force to prevent having to calculate addressing:
// - get map from master edge to split edges.
// - check all faces to find any edge that is split.
{
// From two cut-points to labels of cut-points inbetween.
// (in order: from e[0] to e[1]
const edgeLookup& cutEdgeToPoints = coupleInfo.cutEdgeToPoints();
// Get map of master face (in mesh labels) that are in cut. These faces
// do not need to be renumbered.
labelHashSet masterCutFaces(cutToMasterFaces.size());
forAll(cutToMasterFaces, i)
{
label meshFaceI = masterPatch.addressing()[cutToMasterFaces[i]];
masterCutFaces.insert(meshFaceI);
}
DynamicList<label> workFace(100);
forAll(from0ToAllFaces, face0)
{
if (!masterCutFaces.found(face0))
{
label allFaceI = from0ToAllFaces[face0];
insertVertices
(
cutEdgeToPoints,
masterPatch.meshPointMap(),
coupleInfo.masterToCutPoints(),
mesh0.faces()[face0],
workFace,
allFaces[allFaceI]
);
}
}
// Same for slave face
labelHashSet slaveCutFaces(cutToSlaveFaces.size());
forAll(cutToSlaveFaces, i)
{
label meshFaceI = slavePatch.addressing()[cutToSlaveFaces[i]];
slaveCutFaces.insert(meshFaceI);
}
forAll(from1ToAllFaces, face1)
{
if (!slaveCutFaces.found(face1))
{
label allFaceI = from1ToAllFaces[face1];
insertVertices
(
cutEdgeToPoints,
slavePatch.meshPointMap(),
coupleInfo.slaveToCutPoints(),
mesh1.faces()[face1],
workFace,
allFaces[allFaceI]
);
}
}
}
// Now we have a full facelist and owner/neighbour addressing.
// Cells
// ~~~~~
from1ToAllCells.setSize(mesh1.nCells());
from1ToAllCells = -1;
forAll(mesh1.cells(), i)
{
from1ToAllCells[i] = i + mesh0.nCells();
}
// Make cells (= cell-face addressing)
nCells = mesh0.nCells() + mesh1.nCells();
cellList allCells(nCells);
primitiveMesh::calcCells(allCells, allOwner, allNeighbour, nCells);
// Reorder faces for upper-triangular order.
labelList oldToNew
(
getFaceOrder
(
allCells,
nInternalFaces,
allOwner,
allNeighbour
)
);
inplaceReorder(oldToNew, allFaces);
inplaceReorder(oldToNew, allOwner);
inplaceReorder(oldToNew, allNeighbour);
inplaceRenumber(oldToNew, from0ToAllFaces);
inplaceRenumber(oldToNew, from1ToAllFaces);
}
void CML::polyMeshAdder::mergePointZones
(
const pointZoneMesh& pz0,
const pointZoneMesh& pz1,
const labelList& from0ToAllPoints,
const labelList& from1ToAllPoints,
DynamicList<word>& zoneNames,
labelList& from1ToAll,
List<DynamicList<label> >& pzPoints
)
{
zoneNames.setCapacity(pz0.size() + pz1.size());
zoneNames.append(pz0.names());
from1ToAll.setSize(pz1.size());
forAll(pz1, zoneI)
{
from1ToAll[zoneI] = zoneIndex(pz1[zoneI].name(), zoneNames);
}
zoneNames.shrink();
// Point labels per merged zone
pzPoints.setSize(zoneNames.size());
forAll(pz0, zoneI)
{
append(from0ToAllPoints, pz0[zoneI], pzPoints[zoneI]);
}
// Get sorted zone contents for duplicate element recognition
PtrList<SortableList<label> > pzPointsSorted(pzPoints.size());
forAll(pzPoints, zoneI)
{
pzPointsSorted.set
(
zoneI,
new SortableList<label>(pzPoints[zoneI])
);
}
// Now we have full addressing for points so do the pointZones of mesh1.
forAll(pz1, zoneI)
{
// Relabel all points of zone and add to correct pzPoints.
const label allZoneI = from1ToAll[zoneI];
append
(
from1ToAllPoints,
pz1[zoneI],
pzPointsSorted[allZoneI],
pzPoints[allZoneI]
);
}
forAll(pzPoints, i)
{
pzPoints[i].shrink();
}
}
void CML::polyMeshAdder::mergeFaceZones
(
const faceZoneMesh& fz0,
const faceZoneMesh& fz1,
const labelList& from0ToAllFaces,
const labelList& from1ToAllFaces,
DynamicList<word>& zoneNames,
labelList& from1ToAll,
List<DynamicList<label> >& fzFaces,
List<DynamicList<bool> >& fzFlips
)
{
zoneNames.setCapacity(fz0.size() + fz1.size());
zoneNames.append(fz0.names());
from1ToAll.setSize(fz1.size());
forAll(fz1, zoneI)
{
from1ToAll[zoneI] = zoneIndex(fz1[zoneI].name(), zoneNames);
}
zoneNames.shrink();
// Create temporary lists for faceZones.
fzFaces.setSize(zoneNames.size());
fzFlips.setSize(zoneNames.size());
forAll(fz0, zoneI)
{
DynamicList<label>& newZone = fzFaces[zoneI];
DynamicList<bool>& newFlip = fzFlips[zoneI];
newZone.setCapacity(fz0[zoneI].size());
newFlip.setCapacity(newZone.size());
const labelList& addressing = fz0[zoneI];
const boolList& flipMap = fz0[zoneI].flipMap();
forAll(addressing, i)
{
label faceI = addressing[i];
if (from0ToAllFaces[faceI] != -1)
{
newZone.append(from0ToAllFaces[faceI]);
newFlip.append(flipMap[i]);
}
}
}
// Get sorted zone contents for duplicate element recognition
PtrList<SortableList<label> > fzFacesSorted(fzFaces.size());
forAll(fzFaces, zoneI)
{
fzFacesSorted.set
(
zoneI,
new SortableList<label>(fzFaces[zoneI])
);
}
// Now we have full addressing for faces so do the faceZones of mesh1.
forAll(fz1, zoneI)
{
label allZoneI = from1ToAll[zoneI];
DynamicList<label>& newZone = fzFaces[allZoneI];
const SortableList<label>& newZoneSorted = fzFacesSorted[allZoneI];
DynamicList<bool>& newFlip = fzFlips[allZoneI];
newZone.setCapacity(newZone.size() + fz1[zoneI].size());
newFlip.setCapacity(newZone.size());
const labelList& addressing = fz1[zoneI];
const boolList& flipMap = fz1[zoneI].flipMap();
forAll(addressing, i)
{
label faceI = addressing[i];
label allFaceI = from1ToAllFaces[faceI];
if
(
allFaceI != -1
&& findSortedIndex(newZoneSorted, allFaceI) == -1
)
{
newZone.append(allFaceI);
newFlip.append(flipMap[i]);
}
}
}
forAll(fzFaces, i)
{
fzFaces[i].shrink();
fzFlips[i].shrink();
}
}
void CML::polyMeshAdder::mergeCellZones
(
const cellZoneMesh& cz0,
const cellZoneMesh& cz1,
const labelList& from1ToAllCells,
DynamicList<word>& zoneNames,
labelList& from1ToAll,
List<DynamicList<label> >& czCells
)
{
zoneNames.setCapacity(cz0.size() + cz1.size());
zoneNames.append(cz0.names());
from1ToAll.setSize(cz1.size());
forAll(cz1, zoneI)
{
from1ToAll[zoneI] = zoneIndex(cz1[zoneI].name(), zoneNames);
}
zoneNames.shrink();
// Create temporary lists for cellZones.
czCells.setSize(zoneNames.size());
forAll(cz0, zoneI)
{
// Insert mesh0 cells
czCells[zoneI].append(cz0[zoneI]);
}
// Cell mapping is trivial.
forAll(cz1, zoneI)
{
const label allZoneI = from1ToAll[zoneI];
append(from1ToAllCells, cz1[zoneI], czCells[allZoneI]);
}
forAll(czCells, i)
{
czCells[i].shrink();
}
}
void CML::polyMeshAdder::mergeZones
(
const polyMesh& mesh0,
const polyMesh& mesh1,
const labelList& from0ToAllPoints,
const labelList& from0ToAllFaces,
const labelList& from1ToAllPoints,
const labelList& from1ToAllFaces,
const labelList& from1ToAllCells,
DynamicList<word>& pointZoneNames,
List<DynamicList<label> >& pzPoints,
DynamicList<word>& faceZoneNames,
List<DynamicList<label> >& fzFaces,
List<DynamicList<bool> >& fzFlips,
DynamicList<word>& cellZoneNames,
List<DynamicList<label> >& czCells
)
{
labelList from1ToAllPZones;
mergePointZones
(
mesh0.pointZones(),
mesh1.pointZones(),
from0ToAllPoints,
from1ToAllPoints,
pointZoneNames,
from1ToAllPZones,
pzPoints
);
labelList from1ToAllFZones;
mergeFaceZones
(
mesh0.faceZones(),
mesh1.faceZones(),
from0ToAllFaces,
from1ToAllFaces,
faceZoneNames,
from1ToAllFZones,
fzFaces,
fzFlips
);
labelList from1ToAllCZones;
mergeCellZones
(
mesh0.cellZones(),
mesh1.cellZones(),
from1ToAllCells,
cellZoneNames,
from1ToAllCZones,
czCells
);
}
void CML::polyMeshAdder::addZones
(
const DynamicList<word>& pointZoneNames,
const List<DynamicList<label> >& pzPoints,
const DynamicList<word>& faceZoneNames,
const List<DynamicList<label> >& fzFaces,
const List<DynamicList<bool> >& fzFlips,
const DynamicList<word>& cellZoneNames,
const List<DynamicList<label> >& czCells,
polyMesh& mesh
)
{
List<pointZone*> pZones(pzPoints.size());
forAll(pZones, i)
{
pZones[i] = new pointZone
(
pointZoneNames[i],
pzPoints[i],
i,
mesh.pointZones()
);
}
List<faceZone*> fZones(fzFaces.size());
forAll(fZones, i)
{
fZones[i] = new faceZone
(
faceZoneNames[i],
fzFaces[i],
fzFlips[i],
i,
mesh.faceZones()
);
}
List<cellZone*> cZones(czCells.size());
forAll(cZones, i)
{
cZones[i] = new cellZone
(
cellZoneNames[i],
czCells[i],
i,
mesh.cellZones()
);
}
mesh.addZones
(
pZones,
fZones,
cZones
);
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
// Returns new mesh and sets
// - map from new cell/face/point/patch to either mesh0 or mesh1
//
// mesh0Faces/mesh1Faces: corresponding faces on both meshes.
CML::autoPtr<CML::polyMesh> CML::polyMeshAdder::add
(
const IOobject& io,
const polyMesh& mesh0,
const polyMesh& mesh1,
const faceCoupleInfo& coupleInfo,
autoPtr<mapAddedPolyMesh>& mapPtr
)
{
const polyBoundaryMesh& patches0 = mesh0.boundaryMesh();
const polyBoundaryMesh& patches1 = mesh1.boundaryMesh();
DynamicList<word> allPatchNames(patches0.size() + patches1.size());
DynamicList<word> allPatchTypes(allPatchNames.size());
// Patch maps
labelList from1ToAllPatches(patches1.size());
labelList fromAllTo1Patches(allPatchNames.size(), -1);
mergePatchNames
(
patches0,
patches1,
allPatchNames,
allPatchTypes,
from1ToAllPatches,
fromAllTo1Patches
);
// New points
pointField allPoints;
// Map from mesh0/1 points to allPoints.
labelList from0ToAllPoints(mesh0.nPoints(), -1);
labelList from1ToAllPoints(mesh1.nPoints(), -1);
// New faces
faceList allFaces;
label nInternalFaces;
// New cells
labelList allOwner;
labelList allNeighbour;
label nCells;
// Sizes per patch
labelList nFaces(allPatchNames.size(), 0);
// Maps
labelList from0ToAllFaces(mesh0.nFaces(), -1);
labelList from1ToAllFaces(mesh1.nFaces(), -1);
// Map
labelList from1ToAllCells(mesh1.nCells(), -1);
mergePrimitives
(
mesh0,
mesh1,
coupleInfo,
allPatchNames.size(),
fromAllTo1Patches,
from1ToAllPatches,
allPoints,
from0ToAllPoints,
from1ToAllPoints,
allFaces,
allOwner,
allNeighbour,
nInternalFaces,
nFaces,
nCells,
from0ToAllFaces,
from1ToAllFaces,
from1ToAllCells
);
// Zones
// ~~~~~
DynamicList<word> pointZoneNames;
List<DynamicList<label> > pzPoints;
DynamicList<word> faceZoneNames;
List<DynamicList<label> > fzFaces;
List<DynamicList<bool> > fzFlips;
DynamicList<word> cellZoneNames;
List<DynamicList<label> > czCells;
mergeZones
(
mesh0,
mesh1,
from0ToAllPoints,
from0ToAllFaces,
from1ToAllPoints,
from1ToAllFaces,
from1ToAllCells,
pointZoneNames,
pzPoints,
faceZoneNames,
fzFaces,
fzFlips,
cellZoneNames,
czCells
);
// Patches
// ~~~~~~~
// Map from 0 to all patches (since gets compacted)
labelList from0ToAllPatches(patches0.size(), -1);
List<polyPatch*> allPatches
(
combinePatches
(
mesh0,
mesh1,
patches0, // Should be boundaryMesh() on new mesh.
allPatchNames.size(),
fromAllTo1Patches,
mesh0.nInternalFaces()
+ mesh1.nInternalFaces()
+ coupleInfo.cutFaces().size(),
nFaces,
from0ToAllPatches,
from1ToAllPatches
)
);
// Map information
// ~~~~~~~~~~~~~~~
mapPtr.reset
(
new mapAddedPolyMesh
(
mesh0.nPoints(),
mesh0.nFaces(),
mesh0.nCells(),
mesh1.nPoints(),
mesh1.nFaces(),
mesh1.nCells(),
from0ToAllPoints,
from0ToAllFaces,
identity(mesh0.nCells()),
from1ToAllPoints,
from1ToAllFaces,
from1ToAllCells,
from0ToAllPatches,
from1ToAllPatches,
getPatchSizes(patches0),
getPatchStarts(patches0)
)
);
// Now we have extracted all information from all meshes.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Construct mesh
autoPtr<polyMesh> tmesh
(
new polyMesh
(
io,
xferMove(allPoints),
xferMove(allFaces),
xferMove(allOwner),
xferMove(allNeighbour)
)
);
polyMesh& mesh = tmesh();
// Add zones to new mesh.
addZones
(
pointZoneNames,
pzPoints,
faceZoneNames,
fzFaces,
fzFlips,
cellZoneNames,
czCells,
mesh
);
// Add patches to new mesh
mesh.addPatches(allPatches);
return tmesh;
}
// Inplace add mesh1 to mesh0
CML::autoPtr<CML::mapAddedPolyMesh> CML::polyMeshAdder::add
(
polyMesh& mesh0,
const polyMesh& mesh1,
const faceCoupleInfo& coupleInfo,
const bool validBoundary
)
{
const polyBoundaryMesh& patches0 = mesh0.boundaryMesh();
const polyBoundaryMesh& patches1 = mesh1.boundaryMesh();
DynamicList<word> allPatchNames(patches0.size() + patches1.size());
DynamicList<word> allPatchTypes(allPatchNames.size());
// Patch maps
labelList from1ToAllPatches(patches1.size());
labelList fromAllTo1Patches(allPatchNames.size(), -1);
mergePatchNames
(
patches0,
patches1,
allPatchNames,
allPatchTypes,
from1ToAllPatches,
fromAllTo1Patches
);
// New points
pointField allPoints;
// Map from mesh0/1 points to allPoints.
labelList from0ToAllPoints(mesh0.nPoints(), -1);
labelList from1ToAllPoints(mesh1.nPoints(), -1);
// New faces
faceList allFaces;
labelList allOwner;
labelList allNeighbour;
label nInternalFaces;
// Sizes per patch
labelList nFaces(allPatchNames.size(), 0);
label nCells;
// Maps
labelList from0ToAllFaces(mesh0.nFaces(), -1);
labelList from1ToAllFaces(mesh1.nFaces(), -1);
// Map
labelList from1ToAllCells(mesh1.nCells(), -1);
mergePrimitives
(
mesh0,
mesh1,
coupleInfo,
allPatchNames.size(),
fromAllTo1Patches,
from1ToAllPatches,
allPoints,
from0ToAllPoints,
from1ToAllPoints,
allFaces,
allOwner,
allNeighbour,
nInternalFaces,
nFaces,
nCells,
from0ToAllFaces,
from1ToAllFaces,
from1ToAllCells
);
// Zones
// ~~~~~
DynamicList<word> pointZoneNames;
List<DynamicList<label> > pzPoints;
DynamicList<word> faceZoneNames;
List<DynamicList<label> > fzFaces;
List<DynamicList<bool> > fzFlips;
DynamicList<word> cellZoneNames;
List<DynamicList<label> > czCells;
mergeZones
(
mesh0,
mesh1,
from0ToAllPoints,
from0ToAllFaces,
from1ToAllPoints,
from1ToAllFaces,
from1ToAllCells,
pointZoneNames,
pzPoints,
faceZoneNames,
fzFaces,
fzFlips,
cellZoneNames,
czCells
);
// Patches
// ~~~~~~~
// Store mesh0 patch info before modifying patches0.
labelList mesh0PatchSizes(getPatchSizes(patches0));
labelList mesh0PatchStarts(getPatchStarts(patches0));
// Map from 0 to all patches (since gets compacted)
labelList from0ToAllPatches(patches0.size(), -1);
// Inplace extend mesh0 patches (note that patches0.size() now also
// has changed)
polyBoundaryMesh& allPatches =
const_cast<polyBoundaryMesh&>(mesh0.boundaryMesh());
allPatches.setSize(allPatchNames.size());
labelList patchSizes(allPatches.size());
labelList patchStarts(allPatches.size());
label startFaceI = nInternalFaces;
// Copy patches0 with new sizes. First patches always come from
// mesh0 and will always be present.
label allPatchI = 0;
forAll(from0ToAllPatches, patch0)
{
// Originates from mesh0. Clone with new size & filter out empty
// patch.
if (nFaces[patch0] == 0 && isA<processorPolyPatch>(allPatches[patch0]))
{
//Pout<< "Removing zero sized mesh0 patch " << allPatchNames[patch0]
// << endl;
from0ToAllPatches[patch0] = -1;
// Check if patch was also in mesh1 and update its addressing if so.
if (fromAllTo1Patches[patch0] != -1)
{
from1ToAllPatches[fromAllTo1Patches[patch0]] = -1;
}
}
else
{
// Clone. Note dummy size and start. Gets overwritten later in
// resetPrimitives. This avoids getting temporarily illegal
// SubList construction in polyPatch.
allPatches.set
(
allPatchI,
allPatches[patch0].clone
(
allPatches,
allPatchI,
0, // dummy size
0 // dummy start
)
);
patchSizes[allPatchI] = nFaces[patch0];
patchStarts[allPatchI] = startFaceI;
// Record new index in allPatches
from0ToAllPatches[patch0] = allPatchI;
// Check if patch was also in mesh1 and update its addressing if so.
if (fromAllTo1Patches[patch0] != -1)
{
from1ToAllPatches[fromAllTo1Patches[patch0]] = allPatchI;
}
startFaceI += nFaces[patch0];
allPatchI++;
}
}
// Copy unique patches of mesh1.
forAll(from1ToAllPatches, patch1)
{
label uncompactAllPatchI = from1ToAllPatches[patch1];
if (uncompactAllPatchI >= from0ToAllPatches.size())
{
// Patch has not been merged with any mesh0 patch.
if
(
nFaces[uncompactAllPatchI] == 0
&& isA<processorPolyPatch>(patches1[patch1])
)
{
//Pout<< "Removing zero sized mesh1 patch "
// << allPatchNames[uncompactAllPatchI] << endl;
from1ToAllPatches[patch1] = -1;
}
else
{
// Clone.
allPatches.set
(
allPatchI,
patches1[patch1].clone
(
allPatches,
allPatchI,
0, // dummy size
0 // dummy start
)
);
patchSizes[allPatchI] = nFaces[uncompactAllPatchI];
patchStarts[allPatchI] = startFaceI;
// Record new index in allPatches
from1ToAllPatches[patch1] = allPatchI;
startFaceI += nFaces[uncompactAllPatchI];
allPatchI++;
}
}
}
allPatches.setSize(allPatchI);
patchSizes.setSize(allPatchI);
patchStarts.setSize(allPatchI);
// Construct map information before changing mesh0 primitives
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
autoPtr<mapAddedPolyMesh> mapPtr
(
new mapAddedPolyMesh
(
mesh0.nPoints(),
mesh0.nFaces(),
mesh0.nCells(),
mesh1.nPoints(),
mesh1.nFaces(),
mesh1.nCells(),
from0ToAllPoints,
from0ToAllFaces,
identity(mesh0.nCells()),
from1ToAllPoints,
from1ToAllFaces,
from1ToAllCells,
from0ToAllPatches,
from1ToAllPatches,
mesh0PatchSizes,
mesh0PatchStarts
)
);
// Now we have extracted all information from all meshes.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mesh0.resetMotion(); // delete any oldPoints.
mesh0.resetPrimitives
(
xferMove(allPoints),
xferMove(allFaces),
xferMove(allOwner),
xferMove(allNeighbour),
patchSizes, // size
patchStarts, // patchstarts
validBoundary // boundary valid?
);
// Add zones to new mesh.
mesh0.pointZones().clear();
mesh0.faceZones().clear();
mesh0.cellZones().clear();
addZones
(
pointZoneNames,
pzPoints,
faceZoneNames,
fzFaces,
fzFlips,
cellZoneNames,
czCells,
mesh0
);
return mapPtr;
}
CML::Map<CML::label> CML::polyMeshAdder::findSharedPoints
(
const polyMesh& mesh,
const scalar mergeDist
)
{
const labelList& sharedPointLabels = mesh.globalData().sharedPointLabels();
const labelList& sharedPointAddr = mesh.globalData().sharedPointAddr();
// Because of adding the missing pieces e.g. when redistributing a mesh
// it can be that there are multiple points on the same processor that
// refer to the same shared point.
// Invert point-to-shared addressing
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Map<labelList> sharedToMesh(sharedPointLabels.size());
label nMultiple = 0;
forAll(sharedPointLabels, i)
{
label pointI = sharedPointLabels[i];
label sharedI = sharedPointAddr[i];
Map<labelList>::iterator iter = sharedToMesh.find(sharedI);
if (iter != sharedToMesh.end())
{
// sharedI already used by other point. Add this one.
nMultiple++;
labelList& connectedPointLabels = iter();
label sz = connectedPointLabels.size();
// Check just to make sure.
if (findIndex(connectedPointLabels, pointI) != -1)
{
FatalErrorInFunction
<< "Duplicate point in sharedPoint addressing." << endl
<< "When trying to add point " << pointI << " on shared "
<< sharedI << " with connected points "
<< connectedPointLabels
<< abort(FatalError);
}
connectedPointLabels.setSize(sz+1);
connectedPointLabels[sz] = pointI;
}
else
{
sharedToMesh.insert(sharedI, labelList(1, pointI));
}
}
// Assign single master for every shared with multiple geometric points
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Map<label> pointToMaster(nMultiple);
forAllConstIter(Map<labelList>, sharedToMesh, iter)
{
const labelList& connectedPointLabels = iter();
//Pout<< "For shared:" << iter.key()
// << " found points:" << connectedPointLabels
// << " at coords:"
// << pointField(mesh.points(), connectedPointLabels) << endl;
if (connectedPointLabels.size() > 1)
{
const pointField connectedPoints
(
mesh.points(),
connectedPointLabels
);
labelList toMergedPoints;
pointField mergedPoints;
bool hasMerged = CML::mergePoints
(
connectedPoints,
mergeDist,
false,
toMergedPoints,
mergedPoints
);
if (hasMerged)
{
// Invert toMergedPoints
const labelListList mergeSets
(
invertOneToMany
(
mergedPoints.size(),
toMergedPoints
)
);
// Find master for valid merges
forAll(mergeSets, setI)
{
const labelList& mergeSet = mergeSets[setI];
if (mergeSet.size() > 1)
{
// Pick lowest numbered point
label masterPointI = labelMax;
forAll(mergeSet, i)
{
label pointI = connectedPointLabels[mergeSet[i]];
masterPointI = min(masterPointI, pointI);
}
forAll(mergeSet, i)
{
label pointI = connectedPointLabels[mergeSet[i]];
//Pout<< "Merging point " << pointI
// << " at " << mesh.points()[pointI]
// << " into master point "
// << masterPointI
// << " at " << mesh.points()[masterPointI]
// << endl;
pointToMaster.insert(pointI, masterPointI);
}
}
}
}
}
}
//- Old: geometric merging. Causes problems for two close shared points.
//labelList sharedToMerged;
//pointField mergedPoints;
//bool hasMerged = CML::mergePoints
//(
// pointField
// (
// mesh.points(),
// sharedPointLabels
// ),
// mergeDist,
// false,
// sharedToMerged,
// mergedPoints
//);
//
//// Find out which sets of points get merged and create a map from
//// mesh point to unique point.
//
//Map<label> pointToMaster(10*sharedToMerged.size());
//
//if (hasMerged)
//{
// labelListList mergeSets
// (
// invertOneToMany
// (
// sharedToMerged.size(),
// sharedToMerged
// )
// );
//
// label nMergeSets = 0;
//
// forAll(mergeSets, setI)
// {
// const labelList& mergeSet = mergeSets[setI];
//
// if (mergeSet.size() > 1)
// {
// // Take as master the shared point with the lowest mesh
// // point label. (rather arbitrarily - could use max or
// // any other one of the points)
//
// nMergeSets++;
//
// label masterI = labelMax;
//
// forAll(mergeSet, i)
// {
// label sharedI = mergeSet[i];
//
// masterI = min(masterI, sharedPointLabels[sharedI]);
// }
//
// forAll(mergeSet, i)
// {
// label sharedI = mergeSet[i];
//
// pointToMaster.insert(sharedPointLabels[sharedI], masterI);
// }
// }
// }
//
// //if (debug)
// //{
// // Pout<< "polyMeshAdder : merging:"
// // << pointToMaster.size() << " into " << nMergeSets
// // << " sets." << endl;
// //}
//}
return pointToMaster;
}
void CML::polyMeshAdder::mergePoints
(
const polyMesh& mesh,
const Map<label>& pointToMaster,
polyTopoChange& meshMod
)
{
// Remove all non-master points.
forAll(mesh.points(), pointI)
{
Map<label>::const_iterator iter = pointToMaster.find(pointI);
if (iter != pointToMaster.end())
{
if (iter() != pointI)
{
meshMod.removePoint(pointI, iter());
}
}
}
// Modify faces for points. Note: could use pointFaces here but want to
// avoid addressing calculation.
const faceList& faces = mesh.faces();
forAll(faces, faceI)
{
const face& f = faces[faceI];
bool hasMerged = false;
forAll(f, fp)
{
label pointI = f[fp];
Map<label>::const_iterator iter = pointToMaster.find(pointI);
if (iter != pointToMaster.end())
{
if (iter() != pointI)
{
hasMerged = true;
break;
}
}
}
if (hasMerged)
{
face newF(f);
forAll(f, fp)
{
label pointI = f[fp];
Map<label>::const_iterator iter = pointToMaster.find(pointI);
if (iter != pointToMaster.end())
{
newF[fp] = iter();
}
}
label patchID = mesh.boundaryMesh().whichPatch(faceI);
label nei = (patchID == -1 ? mesh.faceNeighbour()[faceI] : -1);
label zoneID = mesh.faceZones().whichZone(faceI);
bool zoneFlip = false;
if (zoneID >= 0)
{
const faceZone& fZone = mesh.faceZones()[zoneID];
zoneFlip = fZone.flipMap()[fZone.whichFace(faceI)];
}
meshMod.setAction
(
polyModifyFace
(
newF, // modified face
faceI, // label of face
mesh.faceOwner()[faceI], // owner
nei, // neighbour
false, // face flip
patchID, // patch for face
false, // remove from zone
zoneID, // zone for face
zoneFlip // face flip in zone
)
);
}
}
}
// ************************************************************************* //
| 25.632536 | 80 | 0.535784 | MrAwesomeRocks |
6f6cebc5a5242cb10918ffa63ed3aaa1083f3c1b | 4,766 | cc | C++ | chromeos/services/ime/decoder/decoder_engine.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/services/ime/decoder/decoder_engine.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/services/ime/decoder/decoder_engine.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/ime/decoder/decoder_engine.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "build/buildflag.h"
#include "chromeos/services/ime/constants.h"
#include "chromeos/services/ime/public/cpp/buildflags.h"
namespace chromeos {
namespace ime {
namespace {
// Whether to create a fake main entry.
bool g_fake_main_entry_for_testing = false;
#if BUILDFLAG(ENABLE_CROS_IME_SANITY_TEST_SO)
// This is for development purposes only.
const char kDecoderLibName[] = "imesanitytest";
#else
const char kDecoderLibName[] = "imedecoder";
#endif
// A client delegate that makes calls on client side.
class ClientDelegate : public ImeClientDelegate {
public:
ClientDelegate(const std::string& ime_spec,
mojo::PendingRemote<mojom::InputChannel> remote)
: ime_spec_(ime_spec), client_remote_(std::move(remote)) {
client_remote_.set_disconnect_handler(base::BindOnce(
&ClientDelegate::OnDisconnected, base::Unretained(this)));
}
~ClientDelegate() override {}
const char* ImeSpec() override { return ime_spec_.c_str(); }
void Process(const uint8_t* data, size_t size) override {
if (client_remote_ && client_remote_.is_bound()) {
std::vector<uint8_t> msg(data, data + size);
client_remote_->ProcessMessage(msg, base::DoNothing());
}
}
void Destroy() override {}
private:
void OnDisconnected() {
client_remote_.reset();
LOG(ERROR) << "Client remote is disconnected." << ime_spec_;
}
// The ime specification which is unique in the scope of engine.
std::string ime_spec_;
// The InputChannel remote used to talk to the client.
mojo::Remote<mojom::InputChannel> client_remote_;
};
} // namespace
void FakeEngineMainEntryForTesting() {
g_fake_main_entry_for_testing = true;
}
DecoderEngine::DecoderEngine(ImeCrosPlatform* platform) : platform_(platform) {
if (g_fake_main_entry_for_testing) {
// TODO(b/156897880): Impl the fake main entry.
} else {
if (!TryLoadDecoder()) {
LOG(ERROR) << "DecoderEngine INIT FAILED!";
}
}
}
DecoderEngine::~DecoderEngine() {}
bool DecoderEngine::TryLoadDecoder() {
if (engine_main_entry_)
return true;
// Load the decoder library.
base::FilePath lib_path(base::GetNativeLibraryName(kDecoderLibName));
library_ = base::ScopedNativeLibrary(lib_path);
if (!library_.is_valid()) {
LOG(ERROR) << "Failed to load decoder shared library from: " << lib_path
<< ", error: " << library_.GetError()->ToString();
return false;
}
// Prepare the decoder data directory before initialization.
base::FilePath data_dir(platform_->GetImeUserHomeDir());
base::CreateDirectory(data_dir.Append(kLanguageDataDirName));
ImeMainEntryCreateFn createMainEntryFn =
reinterpret_cast<ImeMainEntryCreateFn>(
library_.GetFunctionPointer(IME_MAIN_ENTRY_CREATE_FN_NAME));
engine_main_entry_ = createMainEntryFn(platform_);
return true;
}
bool DecoderEngine::BindRequest(
const std::string& ime_spec,
mojo::PendingReceiver<mojom::InputChannel> receiver,
mojo::PendingRemote<mojom::InputChannel> remote,
const std::vector<uint8_t>& extra) {
if (IsImeSupportedByDecoder(ime_spec)) {
// Activates an IME engine via the shared library. Passing a
// |ClientDelegate| for engine instance created by the shared library to
// make safe calls on the client.
if (engine_main_entry_->ActivateIme(
ime_spec.c_str(),
new ClientDelegate(ime_spec, std::move(remote)))) {
decoder_channel_receivers_.Add(this, std::move(receiver));
// TODO(https://crbug.com/837156): Registry connection error handler.
return true;
}
return false;
}
// Otherwise, try the rule-based engine.
return InputEngine::BindRequest(ime_spec, std::move(receiver),
std::move(remote), extra);
}
bool DecoderEngine::IsImeSupportedByDecoder(const std::string& ime_spec) {
return engine_main_entry_ &&
engine_main_entry_->IsImeSupported(ime_spec.c_str());
}
void DecoderEngine::ProcessMessage(const std::vector<uint8_t>& message,
ProcessMessageCallback callback) {
// TODO(https://crbug.com/837156): Set a default protobuf message.
std::vector<uint8_t> result;
// Handle message via corresponding functions of loaded decoder.
if (engine_main_entry_)
engine_main_entry_->Process(message.data(), message.size());
std::move(callback).Run(result);
}
} // namespace ime
} // namespace chromeos
| 31.562914 | 79 | 0.710869 | mghgroup |
6f72053a49d3d65e4318d2a9fe335cfa808a5d8d | 372 | hpp | C++ | src/EditorTraceBuilder.hpp | ryu-raptor/amf | 33a42cf1025ea512f23c4769a5be27d6a0c335bc | [
"MIT"
] | 1 | 2020-05-31T02:25:39.000Z | 2020-05-31T02:25:39.000Z | src/EditorTraceBuilder.hpp | ryu-raptor/amf | 33a42cf1025ea512f23c4769a5be27d6a0c335bc | [
"MIT"
] | null | null | null | src/EditorTraceBuilder.hpp | ryu-raptor/amf | 33a42cf1025ea512f23c4769a5be27d6a0c335bc | [
"MIT"
] | null | null | null | #pragma once
#include <fstream>
#include <string>
#include <vector>
#include <memory>
#include "Trace.hpp"
#include "Pacemaker.hpp"
namespace otoge2019 {
/// ファイルからトレースを作成
class EditorTraceBuilder
{
public:
/// @fn
/// トレースをビルド
std::shared_ptr<std::vector<std::shared_ptr<Trace>>> build(std::string, Pacemaker&);
};
} // namespace otoge2019
| 19.578947 | 90 | 0.666667 | ryu-raptor |
4cf7e02d9d072783424bd496685228e748517e01 | 608 | cpp | C++ | PAT_B/PAT_B1067.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | 3 | 2019-07-08T05:20:28.000Z | 2021-09-22T10:53:26.000Z | PAT_B/PAT_B1067.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | null | null | null | PAT_B/PAT_B1067.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
string ansStr, tempStr;
vector<string> strVec;
int i, n;
cin >> ansStr >> n;
getchar();
while(1)
{
getline(cin, tempStr);
if(tempStr == "#") break;
else strVec.push_back(tempStr);
}
for (i = 0; i < n; i++)
{
if(i == strVec.size()) break;
if(strVec[i] == ansStr)
{
printf("Welcome in\n");
return 0;
}
else printf("Wrong password: %s\n", strVec[i].c_str());
}
if(i == n) printf("Account locked\n");
return 0;
} | 20.965517 | 63 | 0.483553 | EnhydraGod |
4cfa2ea4349b1f9403c9e2b809b011000ba6f17e | 3,671 | cc | C++ | example/invindex_ex1.cc | Passw/estraier-tkrzw-btree | e149ffc0229f91014fb5de6f25fc1dbe4c35142a | [
"Apache-2.0"
] | 96 | 2020-07-18T07:22:37.000Z | 2022-03-24T21:04:16.000Z | example/invindex_ex1.cc | Passw/estraier-tkrzw-btree | e149ffc0229f91014fb5de6f25fc1dbe4c35142a | [
"Apache-2.0"
] | 32 | 2020-07-19T02:51:10.000Z | 2022-03-31T07:48:59.000Z | example/invindex_ex1.cc | Passw/estraier-tkrzw-btree | e149ffc0229f91014fb5de6f25fc1dbe4c35142a | [
"Apache-2.0"
] | 17 | 2020-07-19T15:35:32.000Z | 2022-03-30T11:53:03.000Z | /*************************************************************************************************
* Example for building an inverted index with the skip database
*
* Copyright 2020 Google LLC
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*************************************************************************************************/
#include "tkrzw_cmd_util.h"
#include "tkrzw_dbm_baby.h"
#include "tkrzw_dbm_skip.h"
#include "tkrzw_str_util.h"
using namespace tkrzw;
void DumpBuffer(BabyDBM* buffer, int32_t file_id);
// Main routine.
int main(int argc, char** argv) {
const std::vector<std::string> documents = {
"this is a pen", "this boy loves a girl", "the girl has the pen", "tokyo go",
"she loves tokyo", "tokyo is a big city", "boy meets girl", "girl meets boy"};
constexpr int32_t BUFFER_CAPACITY = 10;
// Register all documents into separate index files.
BabyDBM buffer;
int32_t num_files = 0;
int32_t num_words_in_buffer = 0;
int64_t doc_id = 0;
for (const auto& doc : documents) {
const std::string value = IntToStrBigEndian(doc_id);
const std::vector<std::string> words = StrSplit(doc, " ");
for (const std::string& word : words) {
buffer.Append(word, value);
num_words_in_buffer++;
}
if (num_words_in_buffer > BUFFER_CAPACITY) {
DumpBuffer(&buffer, num_files);
buffer.Clear();
num_files++;
num_words_in_buffer = 0;
}
doc_id++;
}
if (num_words_in_buffer > 0) {
DumpBuffer(&buffer, num_files);
buffer.Clear();
num_files++;
}
// Merge separate index files into one.
SkipDBM merged_dbm;
merged_dbm.Open("index-merged.tks", true, File::OPEN_TRUNCATE).OrDie();
for (int file_id = 0; file_id < num_files; file_id++) {
const std::string file_name = SPrintF("index-%05d.tks", file_id);
merged_dbm.MergeSkipDatabase(file_name).OrDie();
}
merged_dbm.SynchronizeAdvanced(false, nullptr, SkipDBM::ReduceConcat).OrDie();
merged_dbm.Close().OrDie();
// Search the merged index file.
merged_dbm.Open("index-merged.tks", false).OrDie();
const std::vector<std::string> queries = {"pen", "boy", "girl", "tokyo"};
for (const auto& query : queries) {
std::cout << query << ":";
std::string value;
if (merged_dbm.Get(query, &value).IsOK()) {
size_t pos = 0;
while (pos < value.size()) {
doc_id = StrToIntBigEndian(std::string_view(value.data() + pos, sizeof(int64_t)));
std::cout << " " << doc_id;
pos += sizeof(int64_t);
}
}
std::cout << std::endl;
}
merged_dbm.Close().OrDie();
}
// Dump the posting lists of a buffer into a database file.
void DumpBuffer(BabyDBM* buffer, int32_t file_id) {
const std::string file_name = SPrintF("index-%05d.tks", file_id);
SkipDBM::TuningParameters tuning_params;
tuning_params.insert_in_order = true;
SkipDBM dbm;
dbm.OpenAdvanced(file_name, true, File::OPEN_TRUNCATE, tuning_params).OrDie();
auto iter = buffer->MakeIterator();
iter->First();
std::string key, value;
while (iter->Get(&key, &value).IsOK()) {
dbm.Set(key, value).OrDie();
iter->Next();
}
dbm.Close().OrDie();
}
// END OF FILE
| 35.990196 | 99 | 0.639335 | Passw |
4cfb8a77b20fe613ad253e1681d17005225fda0b | 5,465 | cpp | C++ | buffer_cache.cpp | cephalicmarble/drumlin | c86319fbb0670fa7cf9437e335f0a41ab7496028 | [
"MIT"
] | null | null | null | buffer_cache.cpp | cephalicmarble/drumlin | c86319fbb0670fa7cf9437e335f0a41ab7496028 | [
"MIT"
] | null | null | null | buffer_cache.cpp | cephalicmarble/drumlin | c86319fbb0670fa7cf9437e335f0a41ab7496028 | [
"MIT"
] | null | null | null | #define TAOJSON
#include "buffer_cache.h"
#include <vector>
#include <algorithm>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "drumlin.h"
namespace drumlin {
namespace Buffers {
/**
* @brief BufferCache::BufferCache : only constructor
*/
BufferCache::BufferCache()
{
}
/**
* @brief BufferCache::~BufferCache : deletes buffers from the container, without flushing
*/
BufferCache::~BufferCache()
{
std::lock_guard<std::mutex> l(m_mutex);
}
/**
* @brief BufferCache::isLocked : check the cache mutex
* @return bool
*/
bool BufferCache::isLocked()
{
if(m_mutex.try_lock()){
m_mutex.unlock();
return false;
}
return true;
}
/**
* @brief BufferCache::addBuffer : adds buffer to the container
* @param std::pair<UseIdent, heap_ptr_type>
* @return quint32 number of buffers dealt
*/
guint32 BufferCache::addAllocated(buffers_heap_map_type::value_type const& pair)
{
{LOGLOCK;Debug() << "Cache" << pair.first.getSourceName() << boost::posix_time::microsec_clock();}
m_buffers.push_back(pair);
int n = 0;
std::for_each(pair.second->blocks.begin(), pair.second->blocks.end(),
[this, &n](auto & heap){
publish((HeapBuffer*)heap.second);
++n;
});
return n;
}
// /**
// * @brief BufferCache::flushDeadBuffers : loop within loop to find subscribed transforms and flush the dead buffers
// * @return number of buffers removed
// */
// guint32 BufferCache::flushDeadBuffers()
// {
// guint32 c(0);
// buffers.erase(std::remove_if(buffers.begin(),buffers.end(),[this,&c](buffers_type::value_type &buffer){
// if(buffer->isDead()){
// callSubscribed(buffer.get(),true);
// c++;
// return true;
// }
// return false;
// }),buffers.end());
// for(subs_type::value_type &sub : subscriptions){
// sub.second->flush(nullptr);
// }
// return c;
// }
/**
* @brief BufferCache::clearRelevantBuffers : loop to delete buffers by relevance
* @return number of buffers removed
*/
guint32 BufferCache::clearAllocated(UseIdentFilter use)
{
std::vector<buffers_heap_map_type::value_type> pairs;
int n = 0;
std::for_each(m_buffers.begin(), m_buffers.end(),
[&n, &pairs, use]
(buffers_heap_map_type::value_type & pair) {
if(use == pair.first) {
n += pair.second->freeAll();
pairs.push_back(pair);
}
});
for(auto it : pairs)
{
m_buffers.erase(std::remove(m_buffers.begin(), m_buffers.end(), it));
}
return n;
}
/**
* @brief BufferCache::findRelevant : loop over buffers to find relevant entries
* @param rel Relevance
* @return Buffers::VectorOfBuffers*
*/
buffer_list_type BufferCache::findRelevant(UseIdentFilter use)
{
buffer_list_type relevant;
std::for_each(m_buffers.begin(), m_buffers.end(),
[&relevant, use](auto & buffer){
{LOGLOCK;Debug() << "Cache" << __func__ << buffer.first;}
if(use == buffer.first) {
for(auto & block : buffer.second->blocks) {
relevant.push_back((HeapBuffer*)block.second);
}
}
});
return relevant;
}
/**
* @brief BufferCache::subscribe
* @param std::pair<UseIdent, Acceptor*> (see Buffers::make_sub)
* @return Buffers::VectorOfBuffers* relevant
*/
buffer_list_type BufferCache::subscribe(subs_map_type::value_type sub)
{
m_subscriptions.push_back(sub);
return findRelevant(sub.first);
}
int BufferCache::unsubscribe(subs_map_type::value_type::second_type &acceptor)
{
int n = 0;
std::vector<subs_map_type::iterator> pairs;
for(auto it(m_subscriptions.begin()); it != m_subscriptions.end(); ++it) {
if (it->second == acceptor) {
++n;
pairs.push_back(it);
}
}
for(auto & p : pairs) {
m_subscriptions.erase(p);
}
return n;
}
/**
* @brief BufferCache::callSubscribed : loop over subscriptions to find relevant transforms
* @param buffer Buffer
* @param flush bool
* @return guint32 number of transforms called
*/
guint32 BufferCache::publish(HeapBuffer * buffer)
{
guint32 c(0);
for(subs_map_type::value_type &sub : m_subscriptions)
{
if(sub.first == buffer->getUseIdent()){
sub.second->accept(buffer);
c++;
}
}
return c;
}
int BufferCache::getStatus(json::value *status)
{
json::value cache(json::empty_object);
json::object_t &obj(cache.get_object());
json::value subs(json::empty_array);
json::array_t &array(subs.get_array());
for(subs_map_type::value_type const& sub : m_subscriptions){
json::value _sub(json::empty_object);
UseIdent(sub.first).toJson(&_sub);
array.push_back(_sub);
}
obj.insert({"subs",subs});
status->get_object().insert({"cache",cache});
return 0;
}
/*
* thread-safe calls
*/
addAllocated_t addAllocated(&BufferCache::addAllocated);
clearAllocated_t clearAllocated(&BufferCache::clearAllocated);
findRelevant_t findRelevant(&BufferCache::findRelevant);
subscribe_t subscribe(&BufferCache::subscribe);
unsubscribe_t unsubscribe(&BufferCache::unsubscribe);
publish_t publish(&BufferCache::publish);
getCacheStatus_t getCacheStatus(&BufferCache::getStatus);
BufferCache access::s_cache;
Allocator access::s_allocator;
} // namespace Buffers
} // namespace drumlin
| 26.921182 | 118 | 0.64172 | cephalicmarble |
4cfc46a690d41a0bdbb90b03c781d3a6861ececf | 1,137 | cc | C++ | tests/invoke.cc | chip5441/ezy | 4e4ed4edcfe182b4a6b5fd3459a67200474013ec | [
"MIT"
] | null | null | null | tests/invoke.cc | chip5441/ezy | 4e4ed4edcfe182b4a6b5fd3459a67200474013ec | [
"MIT"
] | null | null | null | tests/invoke.cc | chip5441/ezy | 4e4ed4edcfe182b4a6b5fd3459a67200474013ec | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include <ezy/invoke.h>
int foo()
{
return 101;
}
SCENARIO("invoke")
{
GIVEN("a struct")
{
struct S
{
int f() { return 3; };
constexpr int cf() const { return 4; }
int mem{5};
};
struct D : S
{};
S s;
WHEN("its pointer to member function invoked")
{
REQUIRE(ezy::invoke(&S::f, s) == 3);
}
WHEN("its pointer to member function invoked in compile time")
{
constexpr S cs;
static_assert(ezy::invoke(&S::cf, cs) == 4);
}
WHEN("its pointer to member function invoked on derived")
{
D d;
REQUIRE(ezy::invoke(&S::f, d) == 3);
}
WHEN("its pointer to member invoked")
{
S s;
REQUIRE(ezy::invoke(&S::mem, s) == 5);
//REQUIRE(ezy::invoke(&S::mem, s, 1, 2, 3) == 5); // "Args cannot be provided for member pointer"
}
}
GIVEN("a function")
{
WHEN("it invoked")
{
REQUIRE(ezy::invoke(foo) == 101);
}
}
GIVEN("a lambda")
{
constexpr auto l = [] { return 102; };
WHEN("it invoked")
{
REQUIRE(ezy::invoke(l) == 102);
}
}
}
| 16.478261 | 103 | 0.510114 | chip5441 |
4cfd341ed7cbb30d4c2e926e0efdc0a52470e86d | 1,319 | cpp | C++ | qn3m.cpp | Gourav1695/pp_assignment2_part1 | 6cf3b1251741d161ff52c92eb0fcf1d985d1a8aa | [
"MIT"
] | null | null | null | qn3m.cpp | Gourav1695/pp_assignment2_part1 | 6cf3b1251741d161ff52c92eb0fcf1d985d1a8aa | [
"MIT"
] | null | null | null | qn3m.cpp | Gourav1695/pp_assignment2_part1 | 6cf3b1251741d161ff52c92eb0fcf1d985d1a8aa | [
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#include <time.h>
using namespace std;
struct node
{
int player_id;
struct node *next;
};
struct node *start, *ptr, *ptr1, *new_node, *beginn;
int main()
{
int v2;
srand(time(NULL));
int n, k, i, count;
cout << "enter the no.of player : " << endl;
cin >> n;
v2 = rand() % n + 1;
cout << v2 << endl;
cout << "enter the value of k (person position that is to be eliminated player) : " << endl;
cin >> k;
start = new struct node;
beginn = new struct node;
beginn->player_id = v2;
start->player_id = 1;
ptr = start;
ptr1 = beginn;
for (i = v2 + 1; i <= n; i++)
// for (i = 2; i <= n; i++)/
{
new_node = new struct node;
ptr->next = new_node;
new_node->player_id = i;
new_node->next = start;
ptr = new_node;
}
for (count = n; count > v2; count--)
// for (count = n; count > 1; count--)
{
for (int j = v2; j < v2 + k; ++j)
// for (i = 1; i < k; ++i)
ptr = ptr->next;
cout << " " << ptr->next->player_id << " "
<< "deleted";
ptr->next = ptr->next->next;
}
cout << "\n"
<< "The winner is " << ptr->player_id;
return 0;
}
| 23.140351 | 97 | 0.461713 | Gourav1695 |
9804f1cd2784d3bf0c2da9c8e89a89bdc09fd5d2 | 244 | hpp | C++ | typed_python/PyForwardInstance.hpp | npang1/nativepython | df311a5614a9660c15a8183b2dc606ff3e4600df | [
"Apache-2.0"
] | 7 | 2018-08-07T15:41:54.000Z | 2019-02-19T12:47:57.000Z | typed_python/PyForwardInstance.hpp | npang1/nativepython | df311a5614a9660c15a8183b2dc606ff3e4600df | [
"Apache-2.0"
] | 38 | 2018-10-17T13:37:46.000Z | 2019-04-11T20:50:14.000Z | typed_python/PyForwardInstance.hpp | npang1/nativepython | df311a5614a9660c15a8183b2dc606ff3e4600df | [
"Apache-2.0"
] | 4 | 2019-02-11T17:44:55.000Z | 2019-03-20T07:38:18.000Z | #pragma once
#include "PyInstance.hpp"
class PyForwardInstance : public PyInstance {
public:
typedef Forward modeled_type;
static bool pyValCouldBeOfTypeConcrete(Type* t, PyObject* pyRepresentation) {
return false;
}
};
| 17.428571 | 81 | 0.721311 | npang1 |
98050935011472f805092b04e23b07c900c7fb88 | 5,948 | cpp | C++ | src/input_parsers/BerkeleyNeuralNetwork.cpp | muizzk/Marabou | b938c474bbf7820854822ca407b64b53dfcf6c7c | [
"BSD-3-Clause"
] | null | null | null | src/input_parsers/BerkeleyNeuralNetwork.cpp | muizzk/Marabou | b938c474bbf7820854822ca407b64b53dfcf6c7c | [
"BSD-3-Clause"
] | null | null | null | src/input_parsers/BerkeleyNeuralNetwork.cpp | muizzk/Marabou | b938c474bbf7820854822ca407b64b53dfcf6c7c | [
"BSD-3-Clause"
] | 1 | 2021-06-29T06:54:29.000Z | 2021-06-29T06:54:29.000Z | /********************* */
/*! \file BerkeleyNeuralNetwork.cpp
** \verbatim
** Top contributors (to current version):
** Guy Katz
** This file is part of the Marabou project.
** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file COPYING in the top-level source
** directory for licensing information.\endverbatim
**
** [[ Add lengthier description here ]]
**/
#include "BerkeleyNeuralNetwork.h"
#include "CommonError.h"
BerkeleyNeuralNetwork::Equation::Equation()
: _constant( 0 )
{
}
void BerkeleyNeuralNetwork::Equation::dump()
{
printf( "lhs: %u\n", _lhs );
printf( "rhs:\n" );
for ( const auto &it : _rhs )
printf( "\t%lf * %u\n", it._coefficient, it._var );
printf( "\t%lf\n", _constant );
}
BerkeleyNeuralNetwork::BerkeleyNeuralNetwork( const String &path )
: _file( path )
, _maxVar( 0 )
{
_file.open( File::MODE_READ );
}
unsigned BerkeleyNeuralNetwork::getNumVariables() const
{
return _allVars.size();
}
unsigned BerkeleyNeuralNetwork::getNumEquations() const
{
return _equations.size();
}
unsigned BerkeleyNeuralNetwork::getNumInputVariables() const
{
return _inputVars.size();
}
unsigned BerkeleyNeuralNetwork::getNumOutputVariables() const
{
return _outputVars.size();
}
unsigned BerkeleyNeuralNetwork::getNumReluNodes() const
{
return _bToF.size();
}
Set<unsigned> BerkeleyNeuralNetwork::getInputVariables() const
{
return _inputVars;
}
Set<unsigned> BerkeleyNeuralNetwork::getOutputVariables() const
{
return _outputVars;
}
Map<unsigned, unsigned> BerkeleyNeuralNetwork::getFToB() const
{
return _fToB;
}
List<BerkeleyNeuralNetwork::Equation> BerkeleyNeuralNetwork::getEquations() const
{
return _equations;
}
void BerkeleyNeuralNetwork::parseFile()
{
String line;
try
{
while ( true )
{
line = _file.readLine();
processLine( line );
}
}
catch ( const CommonError &e )
{
if ( e.getCode() != CommonError::READ_FAILED )
throw e;
}
printf( "Max var: %u. Number of vars: %u. Number of LHS vars: %u. Number of equations: %u\n",
_maxVar, _allVars.size(), _allLhsVars.size(), _equations.size() );
_inputVars = Set<unsigned>::difference( _allVars, _allLhsVars );
_outputVars = Set<unsigned>::difference( _allVars, _allRhsVars );
printf( "Input vars: count = %u\n", _inputVars.size() );
printf( "Output vars: count = %u\n", _outputVars.size() );
}
void BerkeleyNeuralNetwork::processLine( const String &line )
{
if ( line.contains( "Relu" ) )
processReluLine( line );
else
processEquationLine( line );
}
void BerkeleyNeuralNetwork::processReluLine( const String &line )
{
List<String> tokens = line.tokenize( "=" );
if ( tokens.size() != 2 )
{
printf( "Error! Expected 2 tokens\n" );
exit( 1 );
}
List<String>::iterator it = tokens.begin();
String firstToken = *it;
++it;
String secondToken = *it;
unsigned f = varStringToUnsigned( firstToken.trim() );
String reluB = secondToken.trim();
if ( !reluB.contains( "Relu" ) )
{
printf( "Error! Not a valid reluB string: %s\n", reluB.ascii() );
exit( 1 );
}
unsigned b = varStringToUnsigned( reluB.substring( 5, reluB.length() - 6 ) );
_bToF[b] = f;
_fToB[f] = b;
processVar( b );
_allRhsVars.insert( b );
_allLhsVars.insert( f );
}
unsigned BerkeleyNeuralNetwork::varStringToUnsigned( String varString )
{
unsigned result = atoi( varString.substring( 1, varString.length() ).ascii() );
processVar( result );
return result;
}
void BerkeleyNeuralNetwork::processVar( unsigned var )
{
_allVars.insert( var );
if ( var > _maxVar )
_maxVar = var;
}
void BerkeleyNeuralNetwork::processEquationLine( const String &line )
{
BerkeleyNeuralNetwork::Equation equation;
equation._index = _equations.size();
List<String> tokens = line.tokenize( "=" );
if ( tokens.size() != 2 )
{
printf( "Error! Expected 2 tokens\n" );
exit( 1 );
}
List<String>::iterator it = tokens.begin();
String firstToken = *it;
++it;
String secondToken = *it;
equation._lhs = varStringToUnsigned( firstToken.trim() );
_allLhsVars.insert( equation._lhs );
List<String> rhsTokens = ( secondToken.trim() ).tokenize( "+" );
for ( it = rhsTokens.begin(); it != rhsTokens.end(); ++it )
{
String token = it->trim();
if ( token.contains( "*" ) )
{
// Coefficient times variable
List<String> varAndCoefficient = token.tokenize( "*" );
BerkeleyNeuralNetwork::Equation::RhsPair rhsPair;
List<String>::iterator it2 = varAndCoefficient.begin();
rhsPair._coefficient = atof( it2->trim().ascii() );
++it2;
rhsPair._var = varStringToUnsigned( it2->trim() );
equation._rhs.append( rhsPair );
_allRhsVars.insert( rhsPair._var );
}
else
{
// Single element. Either a varibale without a coefficient, or a constatnt
if ( token.contains( "v" ) )
{
BerkeleyNeuralNetwork::Equation::RhsPair rhsPair;
rhsPair._coefficient = 1.0;
rhsPair._var = varStringToUnsigned( token );
equation._rhs.append( rhsPair );
_allRhsVars.insert( rhsPair._var );
}
else
equation._constant = atof( token.ascii() );
}
}
_equations.append( equation );
}
//
// Local Variables:
// compile-command: "make -C ../.. "
// tags-file-name: "../../TAGS"
// c-basic-offset: 4
// End:
//
| 24.991597 | 97 | 0.608272 | muizzk |
98058cf9ef627263828704600f68564f95695420 | 831 | cpp | C++ | Lab 2/Chapter 3 Source Code/Ch3_ProgrammingEx4_Code.cpp | candr002/CS150 | 8270f60769fc8a9c18e5c5c46879b63663ba2117 | [
"Unlicense"
] | null | null | null | Lab 2/Chapter 3 Source Code/Ch3_ProgrammingEx4_Code.cpp | candr002/CS150 | 8270f60769fc8a9c18e5c5c46879b63663ba2117 | [
"Unlicense"
] | null | null | null | Lab 2/Chapter 3 Source Code/Ch3_ProgrammingEx4_Code.cpp | candr002/CS150 | 8270f60769fc8a9c18e5c5c46879b63663ba2117 | [
"Unlicense"
] | null | null | null | //Logic errors.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double cost;
double area;
double bagSize;
cout << fixed << showpoint << setprecision(2);
cout << "Enter the amount of fertilizer, in pounds, "
<< "in one bag: ";
cin >> bagSize;
cout << endl;
cout << "Enter the cost of the " << bagSize
<< " pound fertilizer bag: ";
cin >> cost;
cout << endl;
cout << "Enter the area, in square feet, that can be "
<< "fertilized by one bag: ";
cin >> area;
cout << endl;
cout << "The cost of the fertilizer per pound is: $"
<< bagSize / cost << endl;
cout << "The cost of fertilizing per square foot is: $"
<< area / cost << endl;
return 0;
}
| 21.868421 | 60 | 0.519856 | candr002 |
980c5d10b2a0330dc422ae7c448feb6a3bd93795 | 3,336 | cpp | C++ | software/protoDUNE/generic/MultDest.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | null | null | null | software/protoDUNE/generic/MultDest.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | 2 | 2017-05-11T04:22:27.000Z | 2018-09-18T16:10:29.000Z | software/protoDUNE/generic/MultDest.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | 2 | 2017-04-03T21:59:53.000Z | 2020-12-13T00:14:20.000Z | //-----------------------------------------------------------------------------
// File : MultDest.cpp
// Author : Ryan Herbst <rherbst@slac.stanford.edu>
// Created : 06/18/2014
// Project : General Purpose
//-----------------------------------------------------------------------------
// Description :
// Destination container for MultLink class.
//-----------------------------------------------------------------------------
// This file is part of 'SLAC Generic DAQ Software'.
// It is subject to the license terms in the LICENSE.txt file found in the
// top-level directory of this distribution and at:
// https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
// No part of 'SLAC Generic DAQ Software', including this file,
// may be copied, modified, propagated, or distributed except according to
// the terms contained in the LICENSE.txt file.
// Proprietary and confidential to SLAC.
//-----------------------------------------------------------------------------
// Modification history :
// 06/18/2014: created
//-----------------------------------------------------------------------------
#include <MultDest.h>
#include <Register.h>
#include <sys/select.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
using namespace std;
//! Constructor
MultDest::MultDest (uint32_t maxRegister) {
rxRegister_ = new Register("none",0,maxRegister);
rxData_ = NULL;
txData_ = NULL;
dataSize_ = 0;
idx_ = 0;
debug_ = false;
regIsSync_ = false;
fd_ = -1;
}
//! DeConstructor
MultDest::~MultDest () {
this->close();
}
// Add data configuration. The lower 8 bits are ignored.
void MultDest::addDataSource ( uint32_t source ) {
dataSources_.push_back(source);
}
// Set debug
void MultDest::setDebug ( bool debug ) {
debug_ = debug;
}
// Look for matching data source
bool MultDest::isDataSource ( uint32_t source ) {
vector<uint32_t>::iterator srcIter;
for (srcIter = dataSources_.begin(); srcIter != dataSources_.end(); srcIter++) {
if ( ((*srcIter)&0xFFFFFF00) == (source&0xFFFFFF00) ) return(true);
}
return(false);
}
// Set FD
void MultDest::fdSet ( fd_set *fds, int32_t *maxFd ) {
if ( fd_ >= 0 ) {
FD_SET(fd_,fds);
if ( fd_ > *maxFd ) *maxFd = fd_;
}
}
// Is FD Set?
bool MultDest::fdIsSet ( fd_set *fds ) {
if ( fd_ >= 0 ) return(FD_ISSET(fd_,fds));
else return(false);
}
//! Open link
void MultDest::open (uint32_t idx, uint32_t maxRxTx) {
if ( rxData_ != NULL ) free(rxData_);
if ( txData_ != NULL ) free(txData_);
rxData_ = (uint8_t *)malloc(maxRxTx);
txData_ = (uint8_t *)malloc(maxRxTx);
dataSize_ = maxRxTx;
idx_ = idx;
}
//! Stop link
void MultDest::close () {
::close(fd_);
if ( rxData_ != NULL ) free(rxData_);
if ( txData_ != NULL ) free(txData_);
rxData_ = 0;
txData_ = 0;
dataSize_ = 0;
idx_ = 0;
fd_ = -1;
}
//! Transmit data.
int32_t MultDest::transmit ( MultType type, void *ptr, uint32_t size, uint32_t context, uint32_t config ) {
return(0);
}
// Receive data
int32_t MultDest::receive ( MultType *type, void **ptr, uint32_t *context) {
return(0);
}
//! Determine if register access is synchronous
bool MultDest::regIsSync () {
return(regIsSync_);
}
| 27.8 | 107 | 0.565947 | slaclab |
980f2bd43fd11162e852dac327bd4541255ab413 | 431 | hpp | C++ | src/TitleScreen.hpp | ara159/gravity | d990bcae0b2f980a05a50705ec5633d9532bc599 | [
"MIT"
] | null | null | null | src/TitleScreen.hpp | ara159/gravity | d990bcae0b2f980a05a50705ec5633d9532bc599 | [
"MIT"
] | null | null | null | src/TitleScreen.hpp | ara159/gravity | d990bcae0b2f980a05a50705ec5633d9532bc599 | [
"MIT"
] | null | null | null | #ifndef TITLE_SCREEN
#define TITLE_SCREEN 1
#include "MyGameObject.hpp"
class TitleScreen : public MyGameObject
{
private:
Texture* txTitle;
Texture* txBtnStart;
Texture* txBtnRank;
Sprite* spTitle;
Sprite* spBtnStart;
Sprite* spBtnRank;
public:
TitleScreen();
~TitleScreen();
void start();
void update();
void draw(RenderWindow*);
void handleEvent(Event, RenderWindow*);
};
#endif | 18.73913 | 43 | 0.684455 | ara159 |
980ff7498832c784eab718a8b886e82891047599 | 2,811 | cpp | C++ | lavaMD-sycl/util/num/num.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 58 | 2020-08-06T18:53:44.000Z | 2021-10-01T07:59:46.000Z | lavaMD-sycl/util/num/num.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 66 | 2015-06-15T20:38:19.000Z | 2020-08-26T00:11:43.000Z | lavaMD-sycl/util/num/num.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 34 | 2017-12-14T01:06:58.000Z | 2022-02-14T09:40:35.000Z | #ifdef __cplusplus
extern "C" {
#endif
//===============================================================================================================================================================================================================200
// DESCRIPTION
//===============================================================================================================================================================================================================200
// Returns: 0 if string does not represent integer
// 1 if string represents integer
//===============================================================================================================================================================================================================200
// NUM CODE
//===============================================================================================================================================================================================================200
//======================================================================================================================================================150
// ISINTEGER FUNCTION
//======================================================================================================================================================150
int isInteger(char *str){
//====================================================================================================100
// make sure it's not empty
//====================================================================================================100
if (*str == '\0'){
return 0;
}
//====================================================================================================100
// if any digit is not a number, return false
//====================================================================================================100
for(; *str != '\0'; str++){
if (*str < 48 || *str > 57){ // digit characters (need to include . if checking for float)
return 0;
}
}
//====================================================================================================100
// it got past all my checks so I think it's a number
//====================================================================================================100
return 1;
}
//===============================================================================================================================================================================================================200
// END NUM CODE
//===============================================================================================================================================================================================================200
#ifdef __cplusplus
}
#endif
| 52.055556 | 212 | 0.144077 | BeauJoh |
981171efab95b7754e713c3bd4fb90e3cf489425 | 1,469 | cpp | C++ | src/position_postprocessor/position_smoother_lstsq.cpp | SokolovVadim/Indoor-Positioning-And-Navigation-Algorithms | f67c18ed42f9d40e1c274699caf4fa12df2d2ba9 | [
"MIT"
] | 132 | 2015-01-09T08:16:26.000Z | 2021-05-18T11:33:03.000Z | src/position_postprocessor/position_smoother_lstsq.cpp | SokolovVadim/Indoor-Positioning-And-Navigation-Algorithms | f67c18ed42f9d40e1c274699caf4fa12df2d2ba9 | [
"MIT"
] | 3 | 2021-09-27T15:54:10.000Z | 2022-02-10T09:29:55.000Z | src/position_postprocessor/position_smoother_lstsq.cpp | SokolovVadim/Indoor-Positioning-And-Navigation-Algorithms | f67c18ed42f9d40e1c274699caf4fa12df2d2ba9 | [
"MIT"
] | 59 | 2015-01-11T19:40:10.000Z | 2021-06-16T04:46:37.000Z | #include <navigine/navigation-core/navigation_settings.h>
#include "position_smoother_lstsq.h"
namespace navigine {
namespace navigation_core {
PositionSmootherLstsq::PositionSmootherLstsq(const NavigationSettings& navProps)
: mWasCalled(false)
, mUseBarriers(navProps.commonSettings.useBarriers)
, mTimeInterval(navProps.commonSettings.sigAveragingTime)
, mWindowShift(navProps.commonSettings.sigWindowShift)
, mSmoothing(std::min(1.0, std::max(0.0, navProps.commonSettings.smoothing)))
, mPolyFitX(1, mTimeInterval, mWindowShift, mSmoothing)
, mPolyFitY(1, mTimeInterval, mWindowShift, mSmoothing)
{
}
Position PositionSmootherLstsq::smoothPosition(Position pos, const Level& level)
{
if (!mWasCalled)
{
mStartTime = pos.ts;
mWasCalled = true;
return pos;
}
double t = (pos.ts - mStartTime) / 1000.0;
mPolyFitX.addSequencePoint(t, pos.x);
mPolyFitY.addSequencePoint(t, pos.y);
double xs = mPolyFitX.predict(t);
double ys = mPolyFitY.predict(t);
if (mUseBarriers && !boost::geometry::covered_by(Point(xs, ys), level.geometry().allowedArea()))
{
mPolyFitX.clear();
mPolyFitY.clear();
mStartTime = pos.ts;
return pos;
}
if (std::isfinite(xs) && std::isfinite(ys))
{
pos.x = xs;
pos.y = ys;
}
return pos;
}
void PositionSmootherLstsq::reset(Position pos)
{
mPolyFitX.clear();
mPolyFitY.clear();
mStartTime = pos.ts;
}
} } // namespace navigine::navigation_core
| 24.898305 | 98 | 0.710007 | SokolovVadim |
98129e2010a742c1e942454501b9ee2cc01aa60d | 23,600 | hxx | C++ | Utilities/itkVectorImageFileReader.hxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | null | null | null | Utilities/itkVectorImageFileReader.hxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | null | null | null | Utilities/itkVectorImageFileReader.hxx | KevinScholtes/ANTsX | 5462269c0c32e5d65560bae4014c5a05cb02588d | [
"BSD-3-Clause"
] | 1 | 2019-10-06T07:31:58.000Z | 2019-10-06T07:31:58.000Z | /*=========================================================================
Program: Advanced Normalization Tools
Copyright (c) ConsortiumOfANTS. All rights reserved.
See accompanying COPYING.txt or
https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef _itkVectorImageFileReader_hxx
#define _itkVectorImageFileReader_hxx
#include "itkVectorImageFileReader.h"
#include "itkObjectFactory.h"
#include "itkImageIOFactory.h"
#include "itkConvertPixelBuffer.h"
#include "itkImageRegion.h"
#include "itkPixelTraits.h"
#include "itkVectorImage.h"
#include "itkImageRegionIterator.h"
#include <itksys/SystemTools.hxx>
#include <fstream>
namespace itk
{
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::VectorImageFileReader()
{
m_ImageIO = 0;
m_FileName = "";
m_UserSpecifiedImageIO = false;
m_UseAvantsNamingConvention = true;
}
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::~VectorImageFileReader()
{
}
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
if( m_ImageIO )
{
os << indent << "ImageIO: \n";
m_ImageIO->Print(os, indent.GetNextIndent() );
}
else
{
os << indent << "ImageIO: (null)" << "\n";
}
os << indent << "UserSpecifiedImageIO flag: " << m_UserSpecifiedImageIO << "\n";
os << indent << "m_FileName: " << m_FileName << "\n";
}
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
void
VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::SetImageIO( ImageIOBase * imageIO)
{
itkDebugMacro("setting ImageIO to " << imageIO );
if( this->m_ImageIO != imageIO )
{
this->m_ImageIO = imageIO;
this->Modified();
}
m_UserSpecifiedImageIO = true;
}
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
void
VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::GenerateOutputInformation(void)
{
typename TVectorImage::Pointer output = this->GetOutput();
itkDebugMacro(<< "Reading file for GenerateOutputInformation()" << m_FileName);
// Check to see if we can read the file given the name or prefix
//
if( m_FileName == "" )
{
throw VectorImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION);
}
// Test if the files exist and if it can be open.
// and exception will be thrown otherwise.
//
std::string tmpFileName = this->m_FileName;
// Test if the file exists and if it can be opened.
// An exception will be thrown otherwise.
// We catch the exception because some ImageIO's may not actually
// open a file. Still reports file error if no ImageIO is loaded.
try
{
m_ExceptionMessage = "";
this->TestFileExistanceAndReadability();
}
catch( itk::ExceptionObject & err )
{
m_ExceptionMessage = err.GetDescription();
}
std::string::size_type pos = this->m_FileName.rfind( "." );
std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 );
std::string filename = std::string( this->m_FileName, 0, pos );
std::string gzExtension( "" );
if( extension == std::string( ".gz" ) )
{
gzExtension = extension;
std::string::size_type pos2 = filename.rfind( "." );
extension = std::string( filename, pos2, filename.length() - 1 );
filename = std::string( this->m_FileName, 0, pos2 );
}
// unsigned int dimension = itk::GetVectorDimension
// <VectorImagePixelType>::VectorDimension;
// Assume that the first image read contains all the information to generate
// the output image.
for( unsigned int i = 0; i <= 1; i++ )
{
this->m_FileName = filename;
if( this->m_UseAvantsNamingConvention )
{
switch( i )
{
case 0:
{
this->m_FileName += std::string( "xvec" );
}
break;
case 1:
{
this->m_FileName += std::string( "yvec" );
}
break;
case 2:
{
this->m_FileName += std::string( "zvec" );
}
break;
default:
{
this->m_FileName += std::string( "you_are_screwed_vec" );
}
break;
}
}
else
{
std::ostringstream buf;
buf << i;
this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) );
}
this->m_FileName += extension;
if( !gzExtension.empty() )
{
this->m_FileName += std::string( ".gz" );
}
if( i == 0 )
{
itkDebugMacro( << "Generating output information from the file " << this->m_FileName );
if( m_UserSpecifiedImageIO == false ) // try creating via factory
{
m_ImageIO = ImageIOFactory::CreateImageIO( m_FileName.c_str(), ImageIOFactory::ReadMode );
}
if( m_ImageIO.IsNull() )
{
std::ostringstream msg;
msg << " Could not create IO object for file "
<< m_FileName.c_str() << std::endl;
if( m_ExceptionMessage.size() )
{
msg << m_ExceptionMessage;
}
else
{
msg << " Tried to create one of the following:" << std::endl;
std::list<LightObject::Pointer> allobjects =
ObjectFactoryBase::CreateAllInstance("itkImageIOBase");
for( std::list<LightObject::Pointer>::iterator i = allobjects.begin();
i != allobjects.end(); ++i )
{
ImageIOBase* io = dynamic_cast<ImageIOBase *>(i->GetPointer() );
msg << " " << io->GetNameOfClass() << std::endl;
}
msg << " You probably failed to set a file suffix, or" << std::endl;
msg << " set the suffix to an unsupported type." << std::endl;
}
VectorImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION);
throw e;
return;
}
// Got to allocate space for the image. Determine the characteristics of
// the image.
//
m_ImageIO->SetFileName(m_FileName.c_str() );
m_ImageIO->ReadImageInformation();
typename TVectorImage::SizeType dimSize;
double spacing[TVectorImage::ImageDimension];
double origin[TVectorImage::ImageDimension];
typename TVectorImage::DirectionType direction;
std::vector<double> axis;
for( unsigned int k = 0; k < TImage::ImageDimension; k++ )
{
if( k < m_ImageIO->GetNumberOfDimensions() )
{
dimSize[k] = m_ImageIO->GetDimensions(k);
spacing[k] = m_ImageIO->GetSpacing(k);
origin[k] = m_ImageIO->GetOrigin(k);
// Please note: direction cosines are stored as columns of the
// direction matrix
axis = m_ImageIO->GetDirection(k);
for( unsigned j = 0; j < TImage::ImageDimension; j++ )
{
if( j < m_ImageIO->GetNumberOfDimensions() )
{
direction[j][k] = axis[j];
}
else
{
direction[j][k] = 0.0;
}
}
}
else
{
// Number of dimensions in the output is more than number of dimensions
// in the ImageIO object (the file). Use default values for the size,
// spacing, origin and direction for the final (degenerate) dimensions.
dimSize[i] = 1;
spacing[i] = 1.0;
origin[i] = 0.0;
for( unsigned j = 0; j < TImage::ImageDimension; j++ )
{
if( i == j )
{
direction[j][k] = 1.0;
}
else
{
direction[j][k] = 0.0;
}
}
}
}
output->SetSpacing( spacing ); // Set the image spacing
output->SetOrigin( origin ); // Set the image origin
output->SetDirection( direction ); // Set the image direction cosines
// Copy MetaDataDictionary from instantiated reader to output image.
output->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() );
this->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() );
this->m_Image->SetSpacing( spacing );
this->m_Image->SetOrigin( origin );
this->m_Image->SetDirection( direction );
this->m_Image->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary() );
typedef typename TVectorImage::IndexType IndexType;
IndexType start;
start.Fill(0);
VectorImageRegionType region;
region.SetSize(dimSize);
region.SetIndex(start);
ImageRegionType imageregion;
imageregion.SetSize(dimSize);
imageregion.SetIndex(start);
// If a VectorImage, this requires us to set the
// VectorLength before allocate
// if( strcmp( output->GetNameOfClass(), "VectorImage" ) == 0 )
// {
// typedef typename TImage::AccessorFunctorType AccessorFunctorType;
// AccessorFunctorType::SetVectorLength( output, m_ImageIO->GetNumberOfComponents() );
// }
output->SetLargestPossibleRegion( region );
this->m_Image->SetLargestPossibleRegion( imageregion );
}
}
this->m_FileName = tmpFileName;
}
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
void
VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::TestFileExistanceAndReadability()
{
std::string tmpFileName = this->m_FileName;
std::string::size_type pos = this->m_FileName.rfind( "." );
std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 );
std::string filename = std::string( this->m_FileName, 0, pos );
std::string gzExtension( "" );
if( extension == std::string( ".gz" ) )
{
gzExtension = extension;
std::string::size_type pos2 = filename.rfind( "." );
extension = std::string( filename, pos2, filename.length() - 1 );
filename = std::string( this->m_FileName, 0, pos2 );
}
unsigned int dimension = itk::GetVectorDimension
<VectorImagePixelType>::VectorDimension;
for( unsigned int i = 0; i < dimension; i++ )
{
this->m_FileName = filename;
if( this->m_UseAvantsNamingConvention )
{
switch( i )
{
case 0:
{
this->m_FileName += std::string( "xvec" );
}
break;
case 1:
{
this->m_FileName += std::string( "yvec" );
}
break;
case 2:
{
this->m_FileName += std::string( "zvec" );
}
break;
default:
{
this->m_FileName += std::string( "you_are_screwed_vec" );
}
break;
}
}
else
{
std::ostringstream buf;
buf << i;
this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) );
}
this->m_FileName += extension;
if( !gzExtension.empty() )
{
this->m_FileName += std::string( ".gz" );
}
itkDebugMacro( << "Checking for the file " << this->m_FileName );
// Test if the file exists.
if( !itksys::SystemTools::FileExists( m_FileName.c_str() ) )
{
VectorImageFileReaderException e(__FILE__, __LINE__);
std::ostringstream msg;
msg << "The file doesn't exists. "
<< std::endl << "Filename = " << m_FileName
<< std::endl;
e.SetDescription(msg.str().c_str() );
throw e;
return;
}
// Test if the file can be open for reading access.
std::ifstream readTester;
readTester.open( m_FileName.c_str() );
if( readTester.fail() )
{
readTester.close();
std::ostringstream msg;
msg << "The file couldn't be opened for reading. "
<< std::endl << "Filename: " << m_FileName
<< std::endl;
VectorImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION);
throw e;
return;
}
readTester.close();
}
this->m_FileName = tmpFileName;
}
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
void
VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::EnlargeOutputRequestedRegion(DataObject *output)
{
typename TVectorImage::Pointer out = dynamic_cast<TVectorImage *>(output);
// the ImageIO object cannot stream, then set the RequestedRegion to the
// LargestPossibleRegion
if( !m_ImageIO->CanStreamRead() )
{
if( out )
{
out->SetRequestedRegion( out->GetLargestPossibleRegion() );
}
else
{
throw VectorImageFileReaderException(__FILE__, __LINE__,
"Invalid output object type");
}
}
}
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
void VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::GenerateData()
{
typename TVectorImage::Pointer output = this->GetOutput();
// allocate the output buffer
output->SetBufferedRegion( output->GetRequestedRegion() );
output->Allocate();
this->m_Image->SetBufferedRegion( output->GetRequestedRegion() );
this->m_Image->Allocate();
// Test if the file exist and if it can be open.
// and exception will be thrown otherwise.
try
{
m_ExceptionMessage = "";
this->TestFileExistanceAndReadability();
}
catch( itk::ExceptionObject & err )
{
m_ExceptionMessage = err.GetDescription();
}
std::string tmpFileName = this->m_FileName;
std::string::size_type pos = this->m_FileName.rfind( "." );
std::string extension( this->m_FileName, pos, this->m_FileName.length() - 1 );
std::string filename = std::string( this->m_FileName, 0, pos );
std::string gzExtension( "" );
if( extension == std::string( ".gz" ) )
{
gzExtension = extension;
std::string::size_type pos2 = filename.rfind( "." );
extension = std::string( filename, pos2, filename.length() - 1 );
filename = std::string( this->m_FileName, 0, pos2 );
}
unsigned int dimension = itk::GetVectorDimension
<VectorImagePixelType>::VectorDimension;
for( unsigned int i = 0; i < dimension; i++ )
{
this->m_FileName = filename;
if( this->m_UseAvantsNamingConvention )
{
switch( i )
{
case 0:
{
this->m_FileName += std::string( "xvec" );
}
break;
case 1:
{
this->m_FileName += std::string( "yvec" );
}
break;
case 2:
{
this->m_FileName += std::string( "zvec" );
}
break;
default:
{
this->m_FileName += std::string( "you_are_screwed_vec" );
}
break;
}
}
else
{
std::ostringstream buf;
buf << i;
this->m_FileName += ( std::string( "." ) + std::string( buf.str().c_str() ) );
}
this->m_FileName += extension;
if( !gzExtension.empty() )
{
this->m_FileName += std::string( ".gz" );
}
itkDebugMacro( << "Reading image buffer from the file " << this->m_FileName );
// Tell the ImageIO to read the file
m_ImageIO->SetFileName(m_FileName.c_str() );
this->m_FileName = tmpFileName;
ImageIORegion ioRegion(TImage::ImageDimension);
ImageIORegion::SizeType ioSize = ioRegion.GetSize();
ImageIORegion::IndexType ioStart = ioRegion.GetIndex();
typename TImage::SizeType dimSize;
for( unsigned int j = 0; j < TImage::ImageDimension; j++ )
{
if( j < m_ImageIO->GetNumberOfDimensions() )
{
dimSize[j] = m_ImageIO->GetDimensions(j);
}
else
{
// Number of dimensions in the output is more than number of dimensions
// in the ImageIO object (the file). Use default values for the size,
// spacing, and origin for the final (degenerate) dimensions.
dimSize[j] = 1;
}
}
for( unsigned int j = 0; j < dimSize.GetSizeDimension(); ++j )
{
ioSize[j] = dimSize[j];
}
typedef typename TImage::IndexType IndexType;
IndexType start;
start.Fill(0);
for( unsigned int j = 0; j < start.GetIndexDimension(); ++j )
{
ioStart[j] = start[j];
}
ioRegion.SetSize(ioSize);
ioRegion.SetIndex(ioStart);
itkDebugMacro(<< "ioRegion: " << ioRegion);
m_ImageIO->SetIORegion(ioRegion);
char *loadBuffer = 0;
// the size of the buffer is computed based on the actual number of
// pixels to be read and the actual size of the pixels to be read
// (as opposed to the sizes of the output)
try
{
if( /** FIXME */
// m_ImageIO->GetComponentTypeInfo()
// != typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType)
// ||
(m_ImageIO->GetNumberOfComponents()
!= ConvertPixelTraits::GetNumberOfComponents() ) )
{
// the pixel types don't match so a type conversion needs to be
// performed
itkDebugMacro(<< "Buffer conversion required from: "
<< " FIXME m_ImageIO->GetComponentTypeInfo().name() "
<< " to: "
<< typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name() );
loadBuffer = new char[m_ImageIO->GetImageSizeInBytes()];
m_ImageIO->Read( static_cast<void *>(loadBuffer) );
// See note below as to why the buffered region is needed and
// not actualIOregion
this->DoConvertBuffer(static_cast<void *>(loadBuffer),
output->GetBufferedRegion().GetNumberOfPixels() );
}
else // a type conversion is not necessary
{
itkDebugMacro(<< "No buffer conversion required.");
ImagePixelType *buffer =
this->m_Image->GetPixelContainer()->GetBufferPointer();
m_ImageIO->Read( buffer );
}
}
catch( ... )
{
// if an exception is thrown catch it
if( loadBuffer )
{
// clean up
delete [] loadBuffer;
loadBuffer = 0;
}
// then rethrow
throw;
}
// clean up
if( loadBuffer )
{
delete [] loadBuffer;
loadBuffer = 0;
}
ImageRegionIterator<TVectorImage> Id( this->GetOutput(),
this->GetOutput()->GetLargestPossibleRegion() );
ImageRegionIterator<TImage> It( this->m_Image,
this->m_Image->GetLargestPossibleRegion() );
Id.GoToBegin();
It.GoToBegin();
while( !Id.IsAtEnd() || !It.IsAtEnd() )
{
VectorImagePixelType V = Id.Get();
V[i] = static_cast<typename VectorImagePixelType::ValueType>( It.Get() );
Id.Set( V );
++Id;
++It;
}
}
}
template <typename TImage, typename TVectorImage, typename ConvertPixelTraits>
void
VectorImageFileReader<TImage, TVectorImage, ConvertPixelTraits>
::DoConvertBuffer(void* inputData,
unsigned long numberOfPixels)
{
// get the pointer to the destination buffer
ImagePixelType *imageData =
this->m_Image->GetPixelContainer()->GetBufferPointer();
// TODO:
// Pass down the PixelType (RGB, VECTOR, etc.) so that any vector to
// scalar conversion be type specific. i.e. RGB to scalar would use
// a formula to convert to luminance, VECTOR to scalar would use
// vector magnitude.
// Create a macro as this code is a bit lengthy and repetitive
// if the ImageIO pixel type is typeid(type) then use the ConvertPixelBuffer
// class to convert the data block to TImage's pixel type
// see DefaultConvertPixelTraits and ConvertPixelBuffer
// The first else if block applies only to images of type itk::VectorImage
// VectorImage needs to copy out the buffer differently.. The buffer is of
// type InternalPixelType, but each pixel is really 'k' consecutive pixels.
#define ITK_CONVERT_BUFFER_IF_BLOCK(type) \
else if( true /** FIXME m_ImageIO->GetComponentTypeInfo() == typeid(type) ) */ ) \
{ \
if( strcmp( this->GetOutput()->GetNameOfClass(), "VectorImage" ) == 0 ) \
{ \
ConvertPixelBuffer< \
type, \
ImagePixelType, \
ConvertPixelTraits \
> \
::ConvertVectorImage( \
static_cast<type *>(inputData), \
m_ImageIO->GetNumberOfComponents(), \
imageData, \
numberOfPixels); \
} \
else \
{ \
ConvertPixelBuffer< \
type, \
ImagePixelType, \
ConvertPixelTraits \
> \
::Convert( \
static_cast<type *>(inputData), \
m_ImageIO->GetNumberOfComponents(), \
imageData, \
numberOfPixels); \
} \
}
if( 0 )
{
}
ITK_CONVERT_BUFFER_IF_BLOCK(unsigned char)
ITK_CONVERT_BUFFER_IF_BLOCK(char)
ITK_CONVERT_BUFFER_IF_BLOCK(unsigned short)
ITK_CONVERT_BUFFER_IF_BLOCK( short)
ITK_CONVERT_BUFFER_IF_BLOCK(unsigned int)
ITK_CONVERT_BUFFER_IF_BLOCK( int)
ITK_CONVERT_BUFFER_IF_BLOCK(unsigned long)
ITK_CONVERT_BUFFER_IF_BLOCK( long)
ITK_CONVERT_BUFFER_IF_BLOCK(float)
ITK_CONVERT_BUFFER_IF_BLOCK( double)
else
{
VectorImageFileReaderException e(__FILE__, __LINE__);
std::ostringstream msg;
msg << "Couldn't convert component type: "
<< std::endl << " "
<< m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType() )
<< std::endl << "to one of: "
<< std::endl << " " << typeid(unsigned char).name()
<< std::endl << " " << typeid(char).name()
<< std::endl << " " << typeid(unsigned short).name()
<< std::endl << " " << typeid(short).name()
<< std::endl << " " << typeid(unsigned int).name()
<< std::endl << " " << typeid(int).name()
<< std::endl << " " << typeid(unsigned long).name()
<< std::endl << " " << typeid(long).name()
<< std::endl << " " << typeid(float).name()
<< std::endl << " " << typeid(double).name()
<< std::endl;
e.SetDescription(msg.str().c_str() );
e.SetLocation(ITK_LOCATION);
throw e;
return;
}
#undef ITK_CONVERT_BUFFER_IF_BLOCK
}
} // namespace ITK
#endif
| 32.108844 | 105 | 0.579661 | KevinScholtes |
9812e651cae6469ba1eb30865d59758c8532b57f | 618 | cpp | C++ | Maps/map_stl_04.cpp | rishusingh022/Standard-template-libraries | 2776b632d70902d2ee82098266794b8d3bbd319d | [
"MIT"
] | null | null | null | Maps/map_stl_04.cpp | rishusingh022/Standard-template-libraries | 2776b632d70902d2ee82098266794b8d3bbd319d | [
"MIT"
] | null | null | null | Maps/map_stl_04.cpp | rishusingh022/Standard-template-libraries | 2776b632d70902d2ee82098266794b8d3bbd319d | [
"MIT"
] | null | null | null | #include <iostream>
#include<map>
#include<cstring>
#include<list>
using namespace std;
int main() {
map<string, list<pair<string,int> > > citymap;
int E;
cin>>E;
for(int i=0;i<E;i++){
string src,dest;
int dist;
cin>>src>>dest>>dist;
citymap[src].push_back(make_pair(dest,dist));
citymap[dest].push_back(make_pair(src,dist));
}
//Iterate over this
for(auto p:citymap){
cout<<p.first<<"->";
for(auto dd:p.second){
cout<<"("<<dd.first<<","<<dd.second<<")"<<",";
}
cout<<endl;
}
return 0;
}
| 18.727273 | 58 | 0.521036 | rishusingh022 |
98140f5ab75cbb6a9f7d5201745af88b5a7383ba | 6,750 | cpp | C++ | src/lib/rtm/SystemLogger.cpp | r-kurose/OpenRTM-aist | 258c922c55a97c6d1265dbf45e1e8b2ea29b2d86 | [
"RSA-MD"
] | 15 | 2019-01-08T15:34:04.000Z | 2022-03-01T08:36:17.000Z | src/lib/rtm/SystemLogger.cpp | r-kurose/OpenRTM-aist | 258c922c55a97c6d1265dbf45e1e8b2ea29b2d86 | [
"RSA-MD"
] | 448 | 2018-12-27T03:13:56.000Z | 2022-03-24T09:57:03.000Z | src/lib/rtm/SystemLogger.cpp | r-kurose/OpenRTM-aist | 258c922c55a97c6d1265dbf45e1e8b2ea29b2d86 | [
"RSA-MD"
] | 31 | 2018-12-26T04:34:22.000Z | 2021-11-25T04:39:51.000Z | // -*- C++ -*-
/*!
* @file SystemLogger.cpp
* @brief RT component logger class
* @date $Date: 2007-07-20 16:10:32 $
* @author Noriaki Ando <n-ando@aist.go.jp>
*
* Copyright (C) 2003-2008
* Task-intelligence Research Group,
* Intelligent Systems Research Institute,
* National Institute of
* Advanced Industrial Science and Technology (AIST), Japan
* All rights reserved.
*
* $Id: SystemLogger.cpp 845 2008-09-25 11:10:40Z n-ando $
*
*/
#include <rtm/SystemLogger.h>
#include <rtm/Manager.h>
#include <sstream>
#include <iomanip>
#define MAXSIZE 256
namespace RTC
{
const char* const Logger::m_levelString[] =
{
"SILENT",
"FATAL",
"ERROR",
"WARNING",
"INFO",
"DEBUG",
"TRACE",
"VERBOSE",
"PARANOID"
};
const char* const Logger::m_levelOutputString[] =
{
" SILENT: ",
" FATAL: ",
" ERROR: ",
" WARNING: ",
" INFO: ",
" DEBUG: ",
" TRACE: ",
" VERBOSE: ",
" PARANOID: "
};
const char* const Logger::m_levelColor[] =
{
"\x1b[0m", // SLILENT (none)
"\x1b[0m\x1b[31m", // FATAL (red)
"\x1b[0m\x1b[35m", // ERROR (magenta)
"\x1b[0m\x1b[33m", // WARN (yellow)
"\x1b[0m\x1b[34m", // INFO (blue)
"\x1b[0m\x1b[32m", // DEBUG (green)
"\x1b[0m\x1b[36m", // TRACE (cyan)
"\x1b[0m\x1b[39m", // VERBOSE (default)
"\x1b[0m\x1b[37m" // PARANOID (white)
};
Logger::Logger(const char* name)
: ::coil::LogStream(&(Manager::instance().getLogStreamBuf()),
RTL_SILENT, RTL_PARANOID, RTL_SILENT),
m_name(name)
{
setLevel(Manager::instance().getLogLevel().c_str());
coil::Properties& prop(Manager::instance().getConfig());
if (prop.findNode("logger.date_format") != nullptr)
{
setDateFormat(prop["logger.date_format"].c_str());
}
if (prop.findNode("logger.clock_type") != nullptr)
{
setClockType(prop["logger.clock_type"]);
}
}
Logger::Logger(LogStreamBuf* streambuf)
: ::coil::LogStream(streambuf,
RTL_SILENT, RTL_PARANOID, RTL_SILENT)
{
setDateFormat(m_dateFormat.c_str());
}
Logger::~Logger() = default;
/*!
* @if jp
* @brief ログレベルを文字列で設定する
* @else
* @brief Set log level by string
* @endif
*/
bool Logger::setLevel(const char* level)
{
return coil::LogStream::setLevel(strToLevel(level));
}
/*!
* @if jp
* @brief ヘッダに付加する日時フォーマットを指定する。
* @else
* @brief Set date/time format for adding the header
* @endif
*/
void Logger::setDateFormat(const char* format)
{
std::string fmt(format);
m_msEnable = std::string::npos != fmt.find("%Q");
m_usEnable = std::string::npos != fmt.find("%q");
if (m_msEnable){ fmt = coil::replaceString(std::move(fmt), "%Q", "#m#"); }
if (m_usEnable){ fmt = coil::replaceString(std::move(fmt), "%q", "#u#"); }
m_dateFormat = std::move(fmt);
}
void Logger::setClockType(const std::string& clocktype)
{
m_clock = &coil::ClockManager::instance().getClock(clocktype);
}
/*!
* @if jp
* @brief ヘッダの日時の後に付加する文字列を設定する。
* @else
* @brief Set suffix of date/time string of header.
* @endif
*/
void Logger::setName(const char* name)
{
m_name = name;
}
/*!
* @if jp
* @brief フォーマットされた現在日時文字列を取得する。
* @else
* @brief Get the current formatted date/time string
* @endif
*/
std::string Logger::getDate()
{
char buf[MAXSIZE];
auto tm = m_clock->gettime();
auto sec = std::chrono::duration_cast<std::chrono::seconds>(tm);
time_t timer = sec.count();
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
struct tm date;
errno_t error = gmtime_s(&date, &timer);
if (error == EOVERFLOW)
{
return std::string();
}
strftime(buf, sizeof(buf), m_dateFormat.c_str(), &date);
#else
struct tm* date;
date = gmtime(&timer);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
// The format parameter is not literal, as it allows the user to change the format.
// Therefore, we have controlled -Wformat-nonliteral with pragma.
strftime(buf, sizeof(buf), m_dateFormat.c_str(), date);
#pragma GCC diagnostic pop
#endif
std::string fmt(buf);
if (m_msEnable)
{
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(tm - sec);
std::stringstream msec("");
msec << std::setfill('0') << std::setw(3) << ms.count();
fmt = coil::replaceString(std::move(fmt), "#m#", msec.str());
}
if (m_usEnable)
{
auto us = std::chrono::duration_cast<std::chrono::microseconds>(tm - sec);
std::stringstream usec("");
usec << std::setfill('0') << std::setw(6) << us.count();
fmt = coil::replaceString(std::move(fmt), "#u#", usec.str());
}
return fmt;
}
/*!
* @if jp
* @brief ログレベル設定
* @else
* @brief Set the log level
* @endif
*/
int Logger::strToLevel(const char* level)
{
std::string lv(level);
if (lv == "SILENT")
return RTL_SILENT;
else if (lv == "FATAL")
return RTL_FATAL;
else if (lv == "ERROR")
return RTL_ERROR;
else if (lv == "WARN")
return RTL_WARN;
else if (lv == "INFO")
return RTL_INFO;
else if (lv == "DEBUG")
return RTL_DEBUG;
else if (lv == "TRACE")
return RTL_TRACE;
else if (lv == "VERBOSE")
return RTL_VERBOSE;
else if (lv == "PARANOID")
return RTL_PARANOID;
else
return RTL_SILENT;
}
/*!
* @if jp
*
* @brief ログの出力
*
* 指定したメッセージのログを出力する
*
* @param level ログレベル
* @param mes メッセージ
*
*
* @else
*
* @brief log output
*
*
*
* @param level log level
* @param mes message
*
* @endif
*/
void Logger::write(int level, const std::string &mes)
{
if (ostream_type != nullptr)
{
std::string date = getDate();
ostream_type->write(level, m_name, date, mes);
}
}
/*!
* @if jp
*
* @brief ログの出力
*
* 指定したプロパティを文字列に変換してログに出力する
*
* @param level ログレベル
* @param prop プロパティ
*
*
* @else
*
* @brief log output
*
*
*
* @param level log level
* @param prop properties
*
* @endif
*/
void Logger::write(int level, const coil::Properties &prop)
{
if (ostream_type != nullptr)
{
std::vector<std::string> vec(prop);
for (auto & str : vec)
{
ostream_type->write(level, m_name, getDate(), str);
}
}
}
} // namespace RTC
| 23.195876 | 87 | 0.560296 | r-kurose |
9815dd20ae1d892b46f7fe757df35eb2aa3adadc | 1,163 | cpp | C++ | LeetCode/H/Merge-k-Sorted-List.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | LeetCode/H/Merge-k-Sorted-List.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | LeetCode/H/Merge-k-Sorted-List.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<int, vector<int>, greater<int>> dp;
for (int i = 0; i < lists.size(); ++i) {
struct ListNode *tmp = lists[i];
while (tmp) {
dp.push(tmp -> val);
tmp = tmp -> next;
}
}
struct ListNode *reco = nullptr;
struct ListNode *ans = nullptr;
while (!dp.empty()) {
struct ListNode *tmp = new ListNode(dp.top());
dp.pop();
if (!ans) ans = tmp;
else {
reco = ans;
while (reco -> next != nullptr) { reco = reco -> next;}
reco -> next = tmp;
}
}
return ans;
}
int main(int argc, char const *argv[]) {
priority_queue<int> x;
x.push(1);
x.push(2);
x.push(-1);
x.push(1);
while (!x.empty()) {
cout << x.top() << ' '; x.pop();
}
return 0;
}
| 20.403509 | 67 | 0.490972 | luismoroco |
98163c6afbc3d3a665ff188ab2f43e399f3bfac9 | 3,335 | cpp | C++ | mojiben3/tests/c.cpp | katahiromz/mojiben | 8a8d1a3fdffe6ff78165c50e37a6c44aee335e82 | [
"MIT"
] | null | null | null | mojiben3/tests/c.cpp | katahiromz/mojiben | 8a8d1a3fdffe6ff78165c50e37a6c44aee335e82 | [
"MIT"
] | 3 | 2021-07-27T11:19:34.000Z | 2021-07-27T12:01:43.000Z | mojiben4/tests/c.cpp | katahiromz/mojiben | 8a8d1a3fdffe6ff78165c50e37a6c44aee335e82 | [
"MIT"
] | null | null | null | // Moji No Benkyo (3)
// Copyright (C) 2019 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
// This file is public domain software.
// Japanese, Shift_JIS
#include <windows.h>
#include <math.h>
static const TCHAR g_szCaption[] = "Win32 Template";
static const TCHAR g_szClassName[] = "Win32 Template";
HINSTANCE g_hInstance;
HWND g_hMainWnd;
INT g_k;
double theta = 90 * M_PI / 180.0;
VOID OnPaint(HWND hWnd, HDC hdc)
{
double cost, sint;
POINT apt[4];
cost = cos(theta);
sint = sin(theta);
apt[0].x = 150 + g_k * cost + 150 * sint;
apt[0].y = 150 + g_k * sint - 150 * cost;
apt[1].x = 150 + g_k * cost - 150 * sint;
apt[1].y = 150 + g_k * sint + 150 * cost;
apt[2].x = 150 + (g_k + 25) * cost - 150 * sint;
apt[2].y = 150 + (g_k + 25) * sint + 150 * cost;
apt[3].x = 150 + (g_k + 25) * cost + 150 * sint;
apt[3].y = 150 + (g_k + 25) * sint - 150 * cost;
BeginPath(hdc);
Polygon(hdc, apt, 4);
EndPath(hdc);
StrokeAndFillPath(hdc);
char sz[124];
wsprintf(sz, "%d", g_k);
TextOut(hdc, 0, 0, sz, lstrlen(sz));
}
LRESULT CALLBACK
WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch(uMsg)
{
case WM_CREATE:
g_k = -150;
SetTimer(hWnd, 999, 50, NULL);
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
if (hdc != NULL)
{
OnPaint(hWnd, hdc);
EndPaint(hWnd, &ps);
}
break;
case WM_TIMER:
InvalidateRect(hWnd, NULL, TRUE);
g_k += 25;
if (g_k > 150)
g_k = -150;
break;
case WM_DESTROY:
KillTimer(hWnd, 999);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
INT WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR pszCmdLine,
INT nCmdShow)
{
WNDCLASSEX wcx;
MSG msg;
BOOL f;
g_hInstance = hInstance;
wcx.cbSize = sizeof(WNDCLASSEX);
wcx.style = 0;
wcx.lpfnWndProc = WindowProc;
wcx.cbClsExtra = 0;
wcx.cbWndExtra = 0;
wcx.hInstance = hInstance;
wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
wcx.hbrBackground = (HBRUSH)(COLOR_3DFACE + 1);
wcx.lpszMenuName = NULL;
wcx.lpszClassName = g_szClassName;
wcx.hIconSm = (HICON)LoadImage(NULL, IDI_APPLICATION,
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON), 0);
if (!RegisterClassEx(&wcx))
return 1;
g_hMainWnd = CreateWindow(g_szClassName, g_szCaption,
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 300, 300,
NULL, NULL, hInstance, NULL);
if (g_hMainWnd == NULL)
return 2;
ShowWindow(g_hMainWnd, nCmdShow);
UpdateWindow(g_hMainWnd);
while((f = GetMessage(&msg, NULL, 0, 0)) != FALSE)
{
if (f == -1)
return -1;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (INT)msg.wParam;
}
| 26.259843 | 76 | 0.545127 | katahiromz |
982070a1a6ebe5e90785863829153ca3d78b46cb | 1,632 | cpp | C++ | DawnBreakers/Source/DawnBreakers/GameLogic/GameRules/GameMode/ZombieSurvive/ZombieSurvivalHUD.cpp | 954818696/FPSGame | bc82ceb1b56460a8e0e0c0e9a0da20fb5898e158 | [
"MIT"
] | 1 | 2017-01-21T14:08:06.000Z | 2017-01-21T14:08:06.000Z | DawnBreakers/Source/DawnBreakers/GameLogic/GameRules/GameMode/ZombieSurvive/ZombieSurvivalHUD.cpp | 954818696/FPSGame | bc82ceb1b56460a8e0e0c0e9a0da20fb5898e158 | [
"MIT"
] | null | null | null | DawnBreakers/Source/DawnBreakers/GameLogic/GameRules/GameMode/ZombieSurvive/ZombieSurvivalHUD.cpp | 954818696/FPSGame | bc82ceb1b56460a8e0e0c0e9a0da20fb5898e158 | [
"MIT"
] | 2 | 2017-11-14T10:36:01.000Z | 2020-07-13T08:52:08.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "DawnBreakers.h"
#include "ZombieSurvivalHUD.h"
AZombieSurvivalHUD::AZombieSurvivalHUD(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer),
m_ShowHUD(true)
{
static ConstructorHelpers::FObjectFinder<UTexture2D> CrosshiarTexObjDebug(TEXT("/Game/UI/HUD/T_CenterDot_M.T_CenterDot_M"));
CrosshairTex = CrosshiarTexObjDebug.Object;
DebugCenterDotIcon = UCanvas::MakeIcon(CrosshiarTexObjDebug.Object);
}
void AZombieSurvivalHUD::DrawHUD()
{
Super::DrawHUD();
ADBCharacter* ControlledPawn = Cast<ADBCharacter>(GetWorld()->GetFirstPlayerController()->GetPawn());
if (m_ShowHUD == false)
{
return;
}
if (ControlledPawn && ControlledPawn->GetHoldWeapon() == nullptr)
{
DrawDebugCrossHair();
}
}
void AZombieSurvivalHUD::DrawDebugCrossHair()
{
float CenterX = Canvas->ClipX / 2;
float CenterY = Canvas->ClipY / 2;
float CenterDotScale = 0.07f;
Canvas->SetDrawColor(255, 255, 255, 255);
Canvas->DrawIcon(DebugCenterDotIcon,
CenterX - DebugCenterDotIcon.UL * CenterDotScale / 2.0f,
CenterY - DebugCenterDotIcon.VL * CenterDotScale / 2.0f,
CenterDotScale);
}
void AZombieSurvivalHUD::DrawDefaultCrossHair()
{
const FVector2D Center(Canvas->ClipX * 0.5f, Canvas->ClipY * 0.5f);
const FVector2D CrosshairDrawPosition(Center.X, Center.Y);
FCanvasTileItem TileItem(CrosshairDrawPosition, CrosshairTex->Resource, FLinearColor::White);
TileItem.BlendMode = SE_BLEND_Translucent;
Canvas->DrawItem(TileItem);
}
void AZombieSurvivalHUD::SetHUDVisibility(bool bShow)
{
m_ShowHUD = bShow;
}
| 27.661017 | 125 | 0.765319 | 954818696 |
98219446db14f643fa7e1edcdcf079ce6842023a | 3,007 | hpp | C++ | NativeCore/Shared/Keys.hpp | jesterret/ReClass.NET | 0ee8a4cd6a00e2664f2ef3250a81089c32d69392 | [
"MIT"
] | 1,009 | 2018-02-07T05:07:34.000Z | 2022-03-31T10:27:35.000Z | NativeCore/Shared/Keys.hpp | EliteOutlaws/ReClass.NET | 8125eac282d56fa0b9040294ca49b2febd7d9237 | [
"MIT"
] | 161 | 2018-02-25T00:32:47.000Z | 2022-03-31T21:02:50.000Z | NativeCore/Shared/Keys.hpp | EliteOutlaws/ReClass.NET | 8125eac282d56fa0b9040294ca49b2febd7d9237 | [
"MIT"
] | 281 | 2018-02-07T05:07:43.000Z | 2022-03-28T16:42:57.000Z | #pragma once
enum class Keys : int32_t
{
None = 0,
LButton = 1,
RButton = 2,
Cancel = 3,
MButton = 4,
XButton1 = 5,
XButton2 = 6,
Back = 8,
Tab = 9,
LineFeed = 10,
Clear = 12,
Return = 13,
Enter = 13,
ShiftKey = 16,
ControlKey = 17,
Menu = 18,
Pause = 19,
Capital = 20,
CapsLock = 20,
KanaMode = 21,
HanguelMode = 21,
HangulMode = 21,
JunjaMode = 23,
FinalMode = 24,
HanjaMode = 25,
KanjiMode = 25,
Escape = 27,
IMEConvert = 28,
IMENonconvert = 29,
IMEAccept = 30,
IMEAceept = 30,
IMEModeChange = 31,
Space = 32,
Prior = 33,
PageUp = 33,
Next = 34,
PageDown = 34,
End = 35,
Home = 36,
Left = 37,
Up = 38,
Right = 39,
Down = 40,
Select = 41,
Print = 42,
Execute = 43,
Snapshot = 44,
PrintScreen = 44,
Insert = 45,
Delete = 46,
Help = 47,
D0 = 48,
D1 = 49,
D2 = 50,
D3 = 51,
D4 = 52,
D5 = 53,
D6 = 54,
D7 = 55,
D8 = 56,
D9 = 57,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LWin = 91,
RWin = 92,
Apps = 93,
Sleep = 95,
NumPad0 = 96,
NumPad1 = 97,
NumPad2 = 98,
NumPad3 = 99,
NumPad4 = 100,
NumPad5 = 101,
NumPad6 = 102,
NumPad7 = 103,
NumPad8 = 104,
NumPad9 = 105,
Multiply = 106,
Add = 107,
Separator = 108,
Subtract = 109,
Decimal = 110,
Divide = 111,
F1 = 112,
F2 = 113,
F3 = 114,
F4 = 115,
F5 = 116,
F6 = 117,
F7 = 118,
F8 = 119,
F9 = 120,
F10 = 121,
F11 = 122,
F12 = 123,
F13 = 124,
F14 = 125,
F15 = 126,
F16 = 127,
F17 = 128,
F18 = 129,
F19 = 130,
F20 = 131,
F21 = 132,
F22 = 133,
F23 = 134,
F24 = 135,
NumLock = 144,
Scroll = 145,
LShiftKey = 160,
RShiftKey = 161,
LControlKey = 162,
RControlKey = 163,
LMenu = 164,
RMenu = 165,
BrowserBack = 166,
BrowserForward = 167,
BrowserRefresh = 168,
BrowserStop = 169,
BrowserSearch = 170,
BrowserFavorites = 171,
BrowserHome = 172,
VolumeMute = 173,
VolumeDown = 174,
VolumeUp = 175,
MediaNextTrack = 176,
MediaPreviousTrack = 177,
MediaStop = 178,
MediaPlayPause = 179,
LaunchMail = 180,
SelectMedia = 181,
LaunchApplication1 = 182,
LaunchApplication2 = 183,
OemSemicolon = 186,
Oem1 = 186,
OemPlus = 187,
OemComma = 188,
OemMinus = 189,
OemPeriod = 190,
OemQuestion = 191,
Oem2 = 191,
Oemtilde = 192,
Oem3 = 192,
OemOpenBrackets = 219,
Oem4 = 219,
OemPipe = 220,
Oem5 = 220,
OemCloseBrackets = 221,
Oem6 = 221,
OemQuotes = 222,
Oem7 = 222,
Oem8 = 223,
OemBackslash = 226,
Oem102 = 226,
ProcessKey = 229,
Packet = 231,
Attn = 246,
Crsel = 247,
Exsel = 248,
EraseEof = 249,
Play = 250,
Zoom = 251,
NoName = 252,
Pa1 = 253,
OemClear = 254,
KeyCode = 65535,
Shift = 65536,
Control = 131072,
Alt = 262144,
Modifiers = -65536
};
inline Keys& operator|=(Keys& lhs, Keys rhs)
{
using T = std::underlying_type_t<Keys>;
lhs = static_cast<Keys>(static_cast<T>(lhs) | static_cast<T>(rhs));
return lhs;
} | 14.319048 | 68 | 0.588959 | jesterret |
98227ded10721c80b7e7cfd0faeb4a3c065e2b15 | 12,248 | cpp | C++ | Sources/Elastos/Frameworks/Droid/WebView/Chromium/src/elastos/droid/webview/chromium/native/android_webview/AwCookieManager.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/WebView/Chromium/src/elastos/droid/webview/chromium/native/android_webview/AwCookieManager.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/WebView/Chromium/src/elastos/droid/webview/chromium/native/android_webview/AwCookieManager.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include <Elastos.Droid.Os.h>
#include "elastos/droid/webkit/webview/chromium/native/android_webview/AwCookieManager.h"
#include "elastos/droid/webkit/webview/chromium/native/android_webview/api/AwCookieManager_dec.h"
#include <elastos/utility/logging/Logger.h>
using Elastos::Droid::Os::CHandler;
using Elastos::Droid::Os::ILooperHelper;
using Elastos::Droid::Os::CLooperHelper;
using Elastos::Core::EIID_IRunnable;
using Elastos::Core::IBoolean;
using Elastos::Core::CBoolean;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace Webkit {
namespace Webview {
namespace Chromium {
namespace AndroidWebview {
//===============================================================
// AwCookieManager::CookieCallback::InnerRunnable
//===============================================================
CAR_INTERFACE_IMPL(AwCookieManager::CookieCallback::InnerRunnable, Object, IRunnable);
AwCookieManager::CookieCallback::InnerRunnable::InnerRunnable(
/* [in] */ CookieCallback* owner,
/* [in] */ IInterface* t)
: mOwner(owner)
, mT(t)
{
}
ECode AwCookieManager::CookieCallback::InnerRunnable::Run()
{
return mOwner->mCallback->OnReceiveValue(mT);
}
//===============================================================
// AwCookieManager::CookieCallback
//===============================================================
AwCookieManager::CookieCallback::CookieCallback(
/* [in] */ IValueCallback* callback,
/* [in] */ IHandler* handler)
: mCallback(callback)
, mHandler(handler)
{
}
ECode AwCookieManager::CookieCallback::Convert(
/* [in] */ IValueCallback* callback,
/* [out] */ CookieCallback** cookieCallback)
{
VALIDATE_NOT_NULL(cookieCallback);
*cookieCallback = NULL;
if (callback == NULL) {
return NOERROR;
}
// if (Looper.myLooper() == null) {
// throw new IllegalStateException(
// "CookieCallback.convert should be called on a thread with a running Looper.");
// }
AutoPtr<ILooper> looper;
AutoPtr<ILooperHelper> looperHelper;
CLooperHelper::AcquireSingleton((ILooperHelper**)&looperHelper);
looperHelper->GetMyLooper((ILooper**)&looper);
if (looper == NULL)
{
Logger::E("AwCookieManager", "AwCookieManager::CookieCallback::Convert");
return E_ILLEGAL_STATE_EXCEPTION;
}
AutoPtr<IHandler> handler;
CHandler::New((IHandler**)&handler);
AutoPtr<CookieCallback> cookieCB= new CookieCallback(callback, handler);
*cookieCallback = cookieCB;
REFCOUNT_ADD(*cookieCallback);
return NOERROR;
}
void AwCookieManager::CookieCallback::OnReceiveValue(
/* [in] */ IInterface* t)
{
AutoPtr<IRunnable> runnable = new InnerRunnable(this, t);
Boolean result;
mHandler->Post(runnable, &result);
}
//===============================================================
// AwCookieManager
//===============================================================
// TODO(hjd): remove after landing android update to use new calls.
void AwCookieManager::RemoveExpiredCookie()
{
RemoveExpiredCookies();
}
// TODO(hjd): remove after landing android update to use new calls.
void AwCookieManager::RemoveAllCookie()
{
RemoveAllCookies();
}
// TODO(hjd): remove after landing android update to use new calls.
void AwCookieManager::RemoveSessionCookie()
{
RemoveSessionCookies();
}
/**
* Control whether cookie is enabled or disabled
* @param accept TRUE if accept cookie
*/
void AwCookieManager::SetAcceptCookie(
/* [in] */ Boolean accept)
{
NativeSetShouldAcceptCookies(accept);
}
/**
* Return whether cookie is enabled
* @return TRUE if accept cookie
*/
Boolean AwCookieManager::AcceptCookie()
{
return NativeGetShouldAcceptCookies();
}
/**
* Synchronous version of setCookie.
*/
void AwCookieManager::SetCookie(
/* [in] */ const String& url,
/* [in] */ const String& value)
{
NativeSetCookieSync(url, value);
}
/**
* Deprecated synchronous version of removeSessionCookies.
*/
void AwCookieManager::RemoveSessionCookies()
{
NativeRemoveSessionCookiesSync();
}
/**
* Deprecated synchronous version of removeAllCookies.
*/
void AwCookieManager::RemoveAllCookies()
{
NativeRemoveAllCookiesSync();
}
/**
* Set cookie for a given url. The old cookie with same host/path/name will
* be removed. The new cookie will be added if it is not expired or it does
* not have expiration which implies it is session cookie.
* @param url The url which cookie is set for.
* @param value The value for set-cookie: in http response header.
* @param callback A callback called with the success status after the cookie is set.
*/
ECode AwCookieManager::SetCookie(
/* [in] */ const String& url,
/* [in] */ const String& value,
/* [in] */ IValueCallback* callback)
{
//try {
AutoPtr<CookieCallback> cookieCallback;
ECode ecode = CookieCallback::Convert(callback, (CookieCallback**)&cookieCallback);
if (FAILED(ecode))
{
Logger::E("AwCookieManager", "AwCookieManager::SetCookie");
return E_ILLEGAL_STATE_EXCEPTION;
}
NativeSetCookie(url, value, cookieCallback);
return NOERROR;
//} catch (IllegalStateException e) {
// throw new IllegalStateException(
// "SetCookie must be called on a thread with a running Looper.");
//}
}
/**
* Get cookie(s) for a given url so that it can be set to "cookie:" in http
* request header.
* @param url The url needs cookie
* @return The cookies in the format of NAME=VALUE [; NAME=VALUE]
*/
String AwCookieManager::GetCookie(
/* [in] */ const String& url)
{
String cookie = NativeGetCookie(url);
// Return null if the string is empty to match legacy behavior
//return cookie == NULL || cookie.Trim().IsEmpty() ? NULL : cookie;
if (cookie.IsNullOrEmpty())
{
return String(NULL);
}
if (cookie.Trim().IsEmpty())
{
return String(NULL);
}
return cookie;
}
/**
* Remove all session cookies, the cookies without an expiration date.
* The value of the callback is true iff at least one cookie was removed.
* @param callback A callback called after the cookies (if any) are removed.
*/
ECode AwCookieManager::RemoveSessionCookies(
/* [in] */ IValueCallback* callback)
{
//try {
AutoPtr<CookieCallback> cookieCallback;
ECode ecode = CookieCallback::Convert(callback, (CookieCallback**)&cookieCallback);
if (FAILED(ecode))
{
Logger::E("AwCookieManager", "AwCookieManager::RemoveSessionCookies");
return E_ILLEGAL_STATE_EXCEPTION;
}
NativeRemoveSessionCookies(cookieCallback);
return NOERROR;
//} catch (IllegalStateException e) {
// throw new IllegalStateException(
// "removeSessionCookies must be called on a thread with a running Looper.");
//}
}
/**
* Remove all cookies.
* The value of the callback is true iff at least one cookie was removed.
* @param callback A callback called after the cookies (if any) are removed.
*/
ECode AwCookieManager::RemoveAllCookies(
/* [in] */ IValueCallback* callback)
{
//try {
AutoPtr<CookieCallback> cookieCallback;
ECode ecode = CookieCallback::Convert(callback, (CookieCallback**)&cookieCallback);
if (FAILED(ecode))
{
Logger::E("AwCookieManager", "AwCookieManager::RemoveSessionCookies");
return E_ILLEGAL_STATE_EXCEPTION;
}
NativeRemoveAllCookies(cookieCallback);
return NOERROR;
//} catch (IllegalStateException e) {
// throw new IllegalStateException(
// "removeAllCookies must be called on a thread with a running Looper.");
//}
}
/**
* Return true if there are stored cookies.
*/
Boolean AwCookieManager::HasCookies()
{
return NativeHasCookies();
}
/**
* Remove all expired cookies
*/
void AwCookieManager::RemoveExpiredCookies()
{
NativeRemoveExpiredCookies();
}
void AwCookieManager::FlushCookieStore()
{
NativeFlushCookieStore();
}
/**
* Whether cookies are accepted for file scheme URLs.
*/
Boolean AwCookieManager::AllowFileSchemeCookies()
{
return NativeAllowFileSchemeCookies();
}
/**
* Sets whether cookies are accepted for file scheme URLs.
*
* Use of cookies with file scheme URLs is potentially insecure. Do not use this feature unless
* you can be sure that no unintentional sharing of cookie data can take place.
* <p>
* Note that calls to this method will have no effect if made after a WebView or CookieManager
* instance has been created.
*/
void AwCookieManager::SetAcceptFileSchemeCookies(
/* [in] */ Boolean accept)
{
NativeSetAcceptFileSchemeCookies(accept);
}
//@CalledByNative
void AwCookieManager::InvokeBooleanCookieCallback(
/* [in] */ IInterface* callback,
/* [in] */ Boolean result)
{
AutoPtr<CookieCallback> cookieCB = (CookieCallback*)IObject::Probe(callback);
AutoPtr<IBoolean> res;
CBoolean::New(result, (IBoolean**)&res);
cookieCB->OnReceiveValue(res);
}
void AwCookieManager::NativeSetShouldAcceptCookies(
/* [in] */ Boolean accept)
{
Elastos_AwCookieManager_nativeSetShouldAcceptCookies(TO_IINTERFACE(this), accept);
}
Boolean AwCookieManager::NativeGetShouldAcceptCookies()
{
return Elastos_AwCookieManager_nativeGetShouldAcceptCookies(TO_IINTERFACE(this));
}
void AwCookieManager::NativeSetCookie(
/* [in] */ const String& url,
/* [in] */ const String& value,
/* [in] */ CookieCallback* callback)
{
Elastos_AwCookieManager_nativeSetCookie(TO_IINTERFACE(this), url, value, TO_IINTERFACE(callback));
}
void AwCookieManager::NativeSetCookieSync(
/* [in] */ const String& url,
/* [in] */ const String& value)
{
Elastos_AwCookieManager_nativeSetCookieSync(TO_IINTERFACE(this), url, value);
}
String AwCookieManager::NativeGetCookie(
/* [in] */ const String& url)
{
return Elastos_AwCookieManager_nativeGetCookie(TO_IINTERFACE(this), url);
}
void AwCookieManager::NativeRemoveSessionCookies(
/* [in] */ CookieCallback* callback)
{
Elastos_AwCookieManager_nativeRemoveSessionCookies(TO_IINTERFACE(this), TO_IINTERFACE(callback));
}
void AwCookieManager::NativeRemoveSessionCookiesSync()
{
Elastos_AwCookieManager_nativeRemoveSessionCookiesSync(TO_IINTERFACE(this));
}
void AwCookieManager::NativeRemoveAllCookies(
/* [in] */ CookieCallback* callback)
{
Elastos_AwCookieManager_nativeRemoveAllCookies(TO_IINTERFACE(this), TO_IINTERFACE(callback));
}
void AwCookieManager::NativeRemoveAllCookiesSync()
{
Elastos_AwCookieManager_nativeRemoveAllCookiesSync(TO_IINTERFACE(this));
}
void AwCookieManager::NativeRemoveExpiredCookies()
{
Elastos_AwCookieManager_nativeRemoveExpiredCookies(TO_IINTERFACE(this));
}
void AwCookieManager::NativeFlushCookieStore()
{
Elastos_AwCookieManager_nativeFlushCookieStore(TO_IINTERFACE(this));
}
Boolean AwCookieManager::NativeHasCookies()
{
return Elastos_AwCookieManager_nativeHasCookies(TO_IINTERFACE(this));
}
Boolean AwCookieManager::NativeAllowFileSchemeCookies()
{
return Elastos_AwCookieManager_nativeAllowFileSchemeCookies(TO_IINTERFACE(this));
}
void AwCookieManager::NativeSetAcceptFileSchemeCookies(
/* [in] */ Boolean accept)
{
Elastos_AwCookieManager_nativeSetAcceptFileSchemeCookies(TO_IINTERFACE(this), accept);
}
} // namespace AndroidWebview
} // namespace Chromium
} // namespace Webview
} // namespace Webkit
} // namespace Droid
} // namespace Elastos
| 29.371703 | 102 | 0.685745 | jingcao80 |
9822cd1f28ae392b5e549930721ef3a468c0eda7 | 46,171 | cpp | C++ | Test/Unit/future/FutureTest.cpp | erikzenker/asyncly | 550dbec10c3e74c10303345e44ad7c9f98e3db06 | [
"ECL-2.0",
"Apache-2.0"
] | 23 | 2020-02-25T14:11:58.000Z | 2021-09-23T04:32:09.000Z | Test/Unit/future/FutureTest.cpp | erikzenker/asyncly | 550dbec10c3e74c10303345e44ad7c9f98e3db06 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-03-11T14:04:19.000Z | 2020-11-09T20:50:41.000Z | Test/Unit/future/FutureTest.cpp | erikzenker/asyncly | 550dbec10c3e74c10303345e44ad7c9f98e3db06 | [
"ECL-2.0",
"Apache-2.0"
] | 9 | 2020-02-25T14:12:39.000Z | 2021-12-28T01:30:48.000Z | /*
* Copyright 2019 LogMeIn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <chrono>
#include <future>
#include <thread>
#include "gmock/gmock.h"
#include "asyncly/future/Future.h"
#include "StrandImplTestFactory.h"
#include "asyncly/executor/ExecutorStoppedException.h"
#include "asyncly/test/CurrentExecutorGuard.h"
#include "asyncly/test/ExecutorTestFactories.h"
#include "detail/ThrowingExecutor.h"
namespace asyncly {
using namespace testing;
template <typename TExecutorFactory> class FutureTest : public Test {
public:
FutureTest()
: factory_(std::make_unique<TExecutorFactory>())
, executor_(factory_->create())
{
}
std::unique_ptr<TExecutorFactory> factory_;
std::shared_ptr<IExecutor> executor_;
};
using ExecutorFactoryTypes = ::testing::Types<
asyncly::test::AsioExecutorFactory<>,
asyncly::test::DefaultExecutorFactory<>,
asyncly::test::StrandImplTestFactory<>>;
TYPED_TEST_SUITE(FutureTest, ExecutorFactoryTypes);
TYPED_TEST(FutureTest, shouldRunASimpleContinuation)
{
std::promise<int> value;
this->executor_->post([&value]() {
make_ready_future(42).then([&value](int v) {
value.set_value(v);
return make_ready_future();
});
});
EXPECT_EQ(42, value.get_future().get());
}
TYPED_TEST(FutureTest, shouldRunLValueContinuation)
{
std::promise<int> value;
const auto lambda = [&value](int v) {
value.set_value(v);
return make_ready_future();
};
this->executor_->post([&lambda]() { make_ready_future(42).then(lambda); });
EXPECT_EQ(42, value.get_future().get());
}
TYPED_TEST(FutureTest, shouldRunANoncopyableContinuation)
{
std::promise<int> value;
auto future = value.get_future();
this->executor_->post([&value]() {
make_ready_future(42).then([promise{ std::move(value) }](int v) mutable {
promise.set_value(v);
return make_ready_future();
});
});
EXPECT_EQ(42, future.get());
}
TYPED_TEST(FutureTest, shouldRunANoncopyableContinuationReturningVoid)
{
std::promise<int> value;
auto future = value.get_future();
this->executor_->post([&value]() {
make_ready_future(42).then(
[promise{ std::move(value) }](const int& v) mutable { promise.set_value(v); });
});
EXPECT_EQ(42, future.get());
}
// TODO: remove with ASYNCLY-45
TYPED_TEST(FutureTest, shouldUnpackReturnedFutureTupleForSubsequentContinuation)
{
const int a = 42;
const int b = 23;
std::promise<std::tuple<int, int>> tuplePromise;
this->executor_->post([&]() {
make_ready_future(std::make_tuple(a, b)).then([&tuplePromise](int first, int second) {
tuplePromise.set_value(std::make_tuple(first, second));
});
});
EXPECT_EQ(std::make_tuple(a, b), tuplePromise.get_future().get());
}
// TODO: remove with ASYNCLY-45
TYPED_TEST(FutureTest, shouldUnpackReturnedTupleForSubsequentContinuation)
{
const int a = 42;
const int b = 23;
std::promise<std::tuple<int, int>> tuplePromise;
this->executor_->post([&]() {
make_ready_future()
.then([&]() { return std::make_tuple(a, b); })
.then([&tuplePromise](auto first, auto second) {
tuplePromise.set_value(std::make_tuple(first, second));
});
});
EXPECT_EQ(std::make_tuple(a, b), tuplePromise.get_future().get());
}
TYPED_TEST(FutureTest, shouldRunAChainedContinuationWithFutures)
{
std::promise<int> value1;
std::promise<float> value2;
this->executor_->post([&value1, &value2]() {
make_ready_future(42)
.then([&value1](int v) {
value1.set_value(v);
return make_ready_future(v / 2.0f);
})
.then([&value2](float v) { value2.set_value(v); });
});
EXPECT_EQ(42, value1.get_future().get());
EXPECT_FLOAT_EQ(21.0, value2.get_future().get());
}
TYPED_TEST(FutureTest, shouldRunAChainedContinuationWithValues)
{
//! [Future Chain]
std::promise<int> value1;
std::promise<float> value2;
this->executor_->post([&value1, &value2]() {
make_ready_future(42)
.then([&value1](int v) {
value1.set_value(v);
return v / 2.0f;
})
.then([&value2](float v) { value2.set_value(v); });
});
EXPECT_EQ(42, value1.get_future().get());
EXPECT_FLOAT_EQ(21.0, value2.get_future().get());
//! [Future Chain]
}
TYPED_TEST(FutureTest, shouldWorkWithLazyFutures)
{
//! [Lazy Future]
std::promise<void> called;
this->executor_->post([&called]() {
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([&called]() { called.set_value(); });
promise.set_value();
});
called.get_future().wait();
//! [Lazy Future]
}
TYPED_TEST(FutureTest, shouldCreateReadyFuturesFromLValues)
{
std::promise<int> called;
this->executor_->post([&called]() {
auto v = 1;
make_ready_future(v).then([&called](int value) { called.set_value(value); });
});
EXPECT_EQ(1, called.get_future().get());
}
TYPED_TEST(FutureTest, shouldCreateReadyFuturesFromRValues)
{
std::promise<int> called;
this->executor_->post([&called]() {
auto v = 1;
make_ready_future(std::move(v)).then([&called](int value) { called.set_value(value); });
});
EXPECT_EQ(1, called.get_future().get());
}
TYPED_TEST(FutureTest, shouldResolvePromisesFromRValues)
{
std::promise<bool> called;
this->executor_->post([&called]() {
auto value = true;
auto lazy = make_lazy_future<bool>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([&called](bool v) { called.set_value(v); });
promise.set_value(std::move(value));
});
EXPECT_EQ(true, called.get_future().get());
}
TYPED_TEST(FutureTest, shouldResolvePromisesFromLValues)
{
std::promise<bool> called;
this->executor_->post([&called]() {
auto value = true;
auto lazy = make_lazy_future<bool>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([&called](bool v) { called.set_value(v); });
promise.set_value(value);
});
EXPECT_EQ(true, called.get_future().get());
}
TYPED_TEST(FutureTest, shouldCallThenInTheRightExecutorContext)
{
std::promise<std::thread::id> executorThreadIdPromise;
this->executor_->post([&executorThreadIdPromise]() {
executorThreadIdPromise.set_value(std::this_thread::get_id());
});
auto executorThreadId = executorThreadIdPromise.get_future().get();
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
std::promise<std::thread::id> continuationThreadIdPromise;
this->executor_->post([&future, &continuationThreadIdPromise]() {
future.then([&continuationThreadIdPromise]() {
continuationThreadIdPromise.set_value(std::this_thread::get_id());
});
});
promise.set_value();
EXPECT_EQ(executorThreadId, continuationThreadIdPromise.get_future().get());
}
TYPED_TEST(FutureTest, shouldCatchExceptionalFuture)
{
//! [Make Exceptional Future]
std::promise<void> exception;
this->executor_->post([&exception]() {
std::exception_ptr e;
try {
throw std::runtime_error("test error");
} catch (...) {
e = std::current_exception();
}
auto future = make_exceptional_future<int>(e);
future.catch_error([&exception](std::exception_ptr ex) { exception.set_exception(ex); });
});
EXPECT_THROW(exception.get_future().get(), std::runtime_error);
//! [Make Exceptional Future]
}
TYPED_TEST(FutureTest, shouldCatchErrorsWithoutAChain)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([]() { throw std::runtime_error("intentional exception"); })
.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
promise.set_value();
});
EXPECT_THROW(exception.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldCatchErrorsWithoutAChainAndNonCopyableHandler)
{
std::promise<void> exception;
auto future = exception.get_future();
this->executor_->post([exception{ std::move(exception) }]() mutable {
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([]() { throw std::runtime_error("intentional exception"); })
.catch_error([exception{ std::move(exception) }](std::exception_ptr e) mutable {
exception.set_exception(e);
});
promise.set_value();
});
EXPECT_THROW(future.get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldCatchErrorsInAChain)
{
std::promise<void> exception;
bool shouldNeverBeTrue = false;
this->executor_->post([&exception, &shouldNeverBeTrue]() {
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([]() -> Future<void> { throw std::runtime_error("intentional exception"); })
.then([&shouldNeverBeTrue]() { shouldNeverBeTrue = true; })
.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
promise.set_value();
});
EXPECT_THROW(exception.get_future().get(), std::runtime_error);
EXPECT_FALSE(shouldNeverBeTrue);
}
TYPED_TEST(FutureTest, shouldMakeExceptionalFutureFromStdException)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
make_exceptional_future<void>(std::logic_error{ "intentional exception" })
.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
});
EXPECT_THROW(exception.get_future().get(), std::logic_error);
}
TYPED_TEST(FutureTest, shouldMakeExceptionalFutureFromStdString)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
make_exceptional_future<void>(std::string{ "intentional exception" })
.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
});
EXPECT_THROW(exception.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldMakeExceptionalFutureFromZeroTerminatedString)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
make_exceptional_future<void>("intentional exception")
.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
});
EXPECT_THROW(exception.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldAllowForLazyExecptionsFromStdExceptionPtr)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
promise.set_exception(std::make_exception_ptr(std::logic_error{ "logic_error" }));
});
EXPECT_THROW(exception.get_future().get(), std::logic_error);
}
TYPED_TEST(FutureTest, shouldAllowForLazyExecptionsFromStdException)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
promise.set_exception(std::logic_error{ "logic_error" });
});
EXPECT_THROW(exception.get_future().get(), std::logic_error);
}
TYPED_TEST(FutureTest, shouldAllowForLazyExecptionsFromStdString)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
promise.set_exception(std::string{ "logic_error" });
});
EXPECT_THROW(exception.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldAllowForLazyExecptionsFromCharPtr)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.catch_error([&exception](std::exception_ptr e) { exception.set_exception(e); });
promise.set_exception("logic_error");
});
EXPECT_THROW(exception.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldHandleLazyUserErrors)
{
std::promise<void> exception;
this->executor_->post([&exception]() {
std::exception_ptr e;
try {
throw std::runtime_error("test error");
} catch (...) {
e = std::current_exception();
}
make_ready_future()
.then([e]() { return make_exceptional_future<int>(e); })
.catch_error([&exception](std::exception_ptr ex) { exception.set_exception(ex); });
});
EXPECT_THROW(exception.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldForwardValuesThroughCatch)
{
std::promise<int> propagated_value;
this->executor_->post([&propagated_value]() {
make_ready_future()
.then([]() { return 5; })
.catch_error([](std::exception_ptr) {})
.then([&propagated_value](int value) { propagated_value.set_value(value); });
});
EXPECT_EQ(5, propagated_value.get_future().get());
}
TYPED_TEST(FutureTest, shouldChooseTheRightErrorHandler)
{
//! [Error Chain]
struct WrongException : std::exception {
};
struct CorrectException : std::exception {
};
std::promise<void> exception_container;
this->executor_->post([&exception_container]() {
make_ready_future()
.then([]() { return 5; })
.catch_error([&exception_container](std::exception_ptr) {
std::exception_ptr e;
try {
throw WrongException{};
} catch (...) {
e = std::current_exception();
}
exception_container.set_exception(e);
})
.then([](int) -> Future<int> { throw CorrectException{}; })
.catch_error([&exception_container](std::exception_ptr e) {
exception_container.set_exception(e);
})
.then([](int value) { return value; })
.catch_error([&exception_container](std::exception_ptr) {
std::exception_ptr e;
try {
throw WrongException{};
} catch (...) {
e = std::current_exception();
}
exception_container.set_exception(e);
});
});
EXPECT_THROW(exception_container.get_future().get(), CorrectException);
//! [Error Chain]
}
TYPED_TEST(FutureTest, shouldChooseTheRightErrorHandlerOnExceptionalFuture)
{
struct WrongException : std::exception {
};
struct CorrectException : std::exception {
};
std::promise<void> exception_container;
this->executor_->post([&exception_container]() {
make_exceptional_future<int>(CorrectException{})
.then([](int i) { return i; })
.catch_error([&exception_container](std::exception_ptr e) {
exception_container.set_exception(e);
})
.then([](int value) { return value; })
.catch_error([&exception_container](std::exception_ptr) {
std::exception_ptr e;
try {
throw WrongException{};
} catch (...) {
e = std::current_exception();
}
exception_container.set_exception(e);
});
});
EXPECT_THROW(exception_container.get_future().get(), CorrectException);
}
TYPED_TEST(FutureTest, shouldCatchAndForwardError)
{
struct CorrectException : std::exception {
};
std::promise<void> exception1_container;
std::promise<void> exception2_container;
this->executor_->post([&exception1_container, &exception2_container]() {
// Use case: handle error internally within a function but also externally on the caller
// side.
// Setup:
// `auto foo() {return future.catch_and_forward_error(internal_error_handler);}`
// `foo().then(continuation).catch_error(external_error_handler);`
// Both error handlers (`internal_error_handler` and `external_error_handler`) should get
// called.
make_exceptional_future<int>(CorrectException{})
.then([](int i) { return i; })
.catch_and_forward_error([&exception1_container](std::exception_ptr e) {
exception1_container.set_exception(e);
})
.then([](int value) { return value; })
.catch_error([&exception2_container](std::exception_ptr e) {
exception2_container.set_exception(e);
});
});
EXPECT_THROW(exception1_container.get_future().get(), CorrectException);
EXPECT_THROW(exception2_container.get_future().get(), CorrectException);
}
TYPED_TEST(FutureTest, shouldWorkWithFutureProxies)
{
auto callerExecutorControl = ThreadPoolExecutorController::create(1);
auto callerExecutor = callerExecutorControl->get_executor();
auto calleeExecutorControl = ThreadPoolExecutorController::create(1);
auto calleeExecutor = calleeExecutorControl->get_executor();
struct Interface {
virtual ~Interface() = default;
virtual Future<int> op() = 0;
};
struct Implementation : public Interface {
Future<int> op() override
{
return make_ready_future(42);
}
};
struct Proxy : public Interface {
Proxy(
const std::shared_ptr<IExecutor>& executor,
const std::shared_ptr<Interface>& implementation)
: executor_(executor)
, implementation_(implementation)
{
}
Future<int> op() override
{
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
auto callerExecutor = this_thread::get_current_executor();
auto p = implementation_;
executor_->post([p, promise, callerExecutor]() mutable {
p->op().then([callerExecutor, promise](int value) mutable {
callerExecutor->post(
[promise, value]() mutable { promise.set_value(std::move(value)); });
});
});
return future;
}
const std::shared_ptr<IExecutor> executor_;
const std::shared_ptr<Interface> implementation_;
};
auto implementation = std::make_shared<Implementation>();
auto proxy = std::make_shared<Proxy>(calleeExecutor, implementation);
std::promise<int> valuePromise;
callerExecutor->post([proxy, &valuePromise]() {
proxy->op().then([&valuePromise](int value) { valuePromise.set_value(value); });
});
EXPECT_EQ(42, valuePromise.get_future().get());
}
TYPED_TEST(FutureTest, shouldThrowWhenOverwritingValueContinuations)
{
std::promise<void> exceptionThrown;
this->executor_->post([&exceptionThrown]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([](int) {});
try {
future.then([](int) {});
} catch (...) {
exceptionThrown.set_exception(std::current_exception());
}
});
ASSERT_THROW(exceptionThrown.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldThrowWhenOverwritingValueContinuationsEvenWhenResolved)
{
std::promise<void> exceptionThrown;
this->executor_->post([&exceptionThrown]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([](int) {});
promise.set_value(42);
try {
future.then([](int) {});
} catch (...) {
exceptionThrown.set_exception(std::current_exception());
}
});
ASSERT_THROW(exceptionThrown.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldThrowWhenOverwritingErrorContinuations)
{
std::promise<void> exceptionThrown;
this->executor_->post([&exceptionThrown]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.catch_error([](std::exception_ptr) {});
try {
future.catch_error([](std::exception_ptr) {});
} catch (...) {
exceptionThrown.set_exception(std::current_exception());
}
});
ASSERT_THROW(exceptionThrown.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldThrowWhenOverwritingErrorContinuationsEvenWhenRejected)
{
std::promise<void> exceptionThrown;
this->executor_->post([&exceptionThrown]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.catch_error([](std::exception_ptr) {});
promise.set_exception("intentional error");
try {
future.catch_error([](std::exception_ptr) {});
} catch (...) {
exceptionThrown.set_exception(std::current_exception());
}
});
ASSERT_THROW(exceptionThrown.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldPropagateMoveOnlyValues)
{
std::promise<std::unique_ptr<int>> propagatedValue;
this->executor_->post([&propagatedValue]() {
auto contained = new int(42);
auto value = std::unique_ptr<int>{ contained };
make_ready_future<std::unique_ptr<int>>(std::move(value))
.then([&propagatedValue](std::unique_ptr<int> v) {
propagatedValue.set_value(std::move(v));
});
});
EXPECT_EQ(42, *propagatedValue.get_future().get());
}
TYPED_TEST(FutureTest, shouldThrowWhenSettingValueTwice)
{
std::promise<void> shouldThrow;
this->executor_->post([&shouldThrow]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
promise.set_value(5);
try {
promise.set_value(5);
} catch (...) {
shouldThrow.set_exception(std::current_exception());
}
});
EXPECT_THROW(shouldThrow.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldThrowWhenSettingErrorsTwice)
{
std::promise<void> shouldThrow;
this->executor_->post([&shouldThrow]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
std::exception_ptr e;
try {
throw std::runtime_error("some error");
} catch (...) {
e = std::current_exception();
}
promise.set_exception(e);
try {
promise.set_exception(e);
} catch (...) {
shouldThrow.set_exception(std::current_exception());
}
});
EXPECT_THROW(shouldThrow.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldThrowWhenSettingErrorAfterValue)
{
std::promise<void> shouldThrow;
this->executor_->post([&shouldThrow]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
std::exception_ptr e;
try {
throw std::runtime_error("some error");
} catch (...) {
e = std::current_exception();
}
promise.set_value(5);
try {
promise.set_exception(e);
} catch (...) {
shouldThrow.set_exception(std::current_exception());
}
});
EXPECT_THROW(shouldThrow.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldThrowWhenSettingValueAfterError)
{
std::promise<void> shouldThrow;
this->executor_->post([&shouldThrow]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
std::exception_ptr e;
try {
throw std::runtime_error("some error");
} catch (...) {
e = std::current_exception();
}
promise.set_exception(e);
try {
promise.set_value(5);
} catch (...) {
shouldThrow.set_exception(std::current_exception());
}
});
EXPECT_THROW(shouldThrow.get_future().get(), std::runtime_error);
}
TYPED_TEST(FutureTest, shouldDeleteTheContinuationWhenTheErrorHandlerHasBeenExecuted)
{
std::promise<void> result;
auto i = std::make_shared<int>(42);
EXPECT_EQ(1, i.use_count());
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
this->executor_->post([&future, &promise, &i, &result]() {
future.catch_error([&result](std::exception_ptr ex) mutable { result.set_exception(ex); })
.then([i]() {});
EXPECT_EQ(2, i.use_count());
promise.set_exception("failure");
});
EXPECT_THROW(result.get_future().get(), std::runtime_error);
EXPECT_EQ(1, i.use_count());
}
TYPED_TEST(FutureTest, shouldDeleteTheErrorHandlerWhenTheContinuationHasBeenExecuted)
{
std::promise<void> result;
auto i = std::make_shared<int>(42);
EXPECT_EQ(1, i.use_count());
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
this->executor_->post([&future, &promise, &i, &result]() {
future.catch_error([i](auto) {}).then([&result]() mutable { result.set_value(); });
EXPECT_EQ(2, i.use_count());
promise.set_value();
});
result.get_future().get();
EXPECT_EQ(1, i.use_count());
}
TYPED_TEST(FutureTest, shouldDeleteTheContinuationWhenTheChainedErrorHandlerHasBeenExecuted)
{
std::promise<void> result;
auto i = std::make_shared<int>(42);
EXPECT_EQ(1, i.use_count());
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
this->executor_->post([&future, &promise, &i, &result]() {
future.then([i]() {}).catch_error(
[&result](std::exception_ptr ex) mutable { result.set_exception(ex); });
EXPECT_EQ(2, i.use_count());
promise.set_exception("failure");
});
EXPECT_THROW(result.get_future().get(), std::runtime_error);
EXPECT_EQ(1, i.use_count());
}
TYPED_TEST(FutureTest, shouldDeleteTheContinuationWhenThereIsNoErrorHandlerButTheFutureIsRejected)
{
std::promise<void> result;
auto i = std::make_shared<int>(42);
EXPECT_EQ(1, i.use_count());
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
this->executor_->post([&future, &promise, &i, &result]() {
future.then([i]() {});
EXPECT_EQ(2, i.use_count());
promise.set_exception("failure");
EXPECT_EQ(1, i.use_count());
result.set_value();
});
result.get_future().get();
EXPECT_EQ(1, i.use_count());
}
TYPED_TEST(FutureTest, shouldDeleteTheErrorHandlerWhenThereIsNoContinuationButTheFutureIsResolved)
{
std::promise<void> result;
auto i = std::make_shared<int>(42);
EXPECT_EQ(1, i.use_count());
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
this->executor_->post([&future, &promise, &i, &result]() {
future.catch_error([i](auto) {});
EXPECT_EQ(2, i.use_count());
promise.set_value();
EXPECT_EQ(1, i.use_count());
result.set_value();
});
result.get_future().get();
}
TYPED_TEST(FutureTest, shouldThrowWhenSchedulingContinuationsFromNonExecutorContext)
{
auto future = make_ready_future<int>(42);
EXPECT_THROW(future.then([](int) {}), std::runtime_error);
}
// Future<T>::then(T -> Future<void>) -> Future<void>
TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningVoidFutures)
{
std::promise<void> called;
this->executor_->post([&called]() {
make_ready_future<int>(42).then([&called](int) {
called.set_value();
return make_ready_future();
});
});
EXPECT_NO_THROW(called.get_future().get());
}
TYPED_TEST(
FutureTest,
shouldSupport_ValueFuture_ValueContinuations_ReturningVoidFutures_WithContinuationErrors)
{
std::promise<void> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future<int>(42)
.then([](int) -> Future<void> { throw test_error{}; })
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
TYPED_TEST(
FutureTest,
shouldSupport_ValueFuture_ValueContinuations_ReturningVoidFutures_WithExceptionalFutures)
{
std::promise<void> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future<int>(42)
.then([](int) {
std::exception_ptr e;
try {
throw test_error{};
} catch (...) {
e = std::current_exception();
}
return make_exceptional_future<void>(e);
})
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
// Future<void>::then(void -> Future<void>) -> Future<void>
TYPED_TEST(FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningVoidFutures)
{
std::promise<void> called;
this->executor_->post([&called]() {
make_ready_future().then([&called]() {
called.set_value();
return make_ready_future();
});
});
EXPECT_NO_THROW(called.get_future().get());
}
TYPED_TEST(
FutureTest,
shouldSupport_VoidFuture_ValueContinuations_ReturningVoidFutures_WithContinuationErrors)
{
std::promise<void> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future()
.then([]() -> Future<void> { throw test_error{}; })
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
TYPED_TEST(
FutureTest,
shouldSupport_VoidFuture_ValueContinuations_ReturningVoidFutures_WithExceptionalFutures)
{
std::promise<void> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future()
.then([]() {
std::exception_ptr e;
try {
throw test_error{};
} catch (...) {
e = std::current_exception();
}
return make_exceptional_future<void>(e);
})
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
// Future<T>::then(T -> Future<U>) -> Future<U>
TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningValueFutures)
{
std::promise<bool> called;
this->executor_->post([&called]() {
make_ready_future<int>(42)
.then([](int) { return make_ready_future(true); })
.then([&called](bool value) { called.set_value(value); });
});
EXPECT_EQ(true, called.get_future().get());
}
TYPED_TEST(
FutureTest,
shouldSupport_ValueFuture_ValueContinuations_ReturningValueFutures_WithContinuationErrors)
{
std::promise<bool> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future<int>(42)
.then([](int) -> Future<bool> { throw test_error{}; })
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); })
.then([&called](bool value) { called.set_value(value); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
TYPED_TEST(
FutureTest,
shouldSupport_ValueFuture_ValueContinuations_ReturningValueFutures_WithExceptionalFutures)
{
std::promise<bool> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future<int>(42)
.then([](int) {
std::exception_ptr e;
try {
throw test_error{};
} catch (...) {
e = std::current_exception();
}
return make_exceptional_future<bool>(e);
})
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); })
.then([&called](bool value) { called.set_value(value); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
// Future<void>::then(void -> Future<U>) -> Future<U>
TYPED_TEST(FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningValueFutures)
{
std::promise<bool> called;
this->executor_->post([&called]() {
make_ready_future()
.then([]() { return make_ready_future(true); })
.then([&called](bool value) { called.set_value(value); });
});
EXPECT_EQ(true, called.get_future().get());
}
TYPED_TEST(
FutureTest,
shouldSupport_VoidFuture_ValueContinuations_ReturningValueFutures_WithContinuationErrors)
{
std::promise<bool> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future()
.then([]() -> Future<bool> { throw test_error{}; })
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); })
.then([&called](bool value) { called.set_value(value); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
TYPED_TEST(
FutureTest,
shouldSupport_VoidFuture_ValueContinuations_ReturningValueFutures_WithExceptionalFutures)
{
std::promise<bool> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future()
.then([]() {
std::exception_ptr e;
try {
throw test_error{};
} catch (...) {
e = std::current_exception();
}
return make_exceptional_future<bool>(e);
})
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); })
.then([&called](bool value) { called.set_value(value); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
// Future<T>::then(T -> void) -> Future<void>
TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningVoid)
{
std::promise<void> called;
this->executor_->post([&called]() {
make_ready_future<int>(42).then([](int) {}).then([&called]() { called.set_value(); });
});
EXPECT_NO_THROW(called.get_future().get());
}
TYPED_TEST(
FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningVoid_WithContinuationErrors)
{
std::promise<void> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future<int>(42)
.then([](int) { throw test_error{}; })
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); })
.then([&called]() { called.set_value(); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ConstLValueValueContinuations_ReturningVoid)
{
std::promise<int> called;
const auto lambda = [&called](int v) { called.set_value(v); };
this->executor_->post([&lambda]() { make_ready_future(42).then(lambda); });
EXPECT_EQ(42, called.get_future().get());
}
TYPED_TEST(FutureTest, shouldSupport_ValueFuture_NonConstLValueValueContinuations_ReturningVoid)
{
std::promise<int> called;
auto lambda = [&called](int v) mutable { called.set_value(v); };
this->executor_->post([&lambda]() { make_ready_future(42).then(lambda); });
EXPECT_EQ(42, called.get_future().get());
}
// Future<void>::then(void -> void) -> Future<void>
TYPED_TEST(FutureTest, shouldSupport_VoidFuture_VoidContinuations_ReturningVoid)
{
std::promise<void> called;
this->executor_->post([&called]() {
make_ready_future().then([]() {}).then([&called]() { called.set_value(); });
});
EXPECT_NO_THROW(called.get_future().get());
}
TYPED_TEST(
FutureTest, shouldSupport_VoidFuture_VoidContinuations_ReturningVoid_WithContinuationErrors)
{
std::promise<void> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future()
.then([]() -> Future<void> { throw test_error{}; })
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); })
.then([&called]() { called.set_value(); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
TYPED_TEST(FutureTest, shouldSupport_VoidFuture_ConstLValueVoidContinuations_ReturningVoid)
{
std::promise<void> called;
const auto lambda = [&called]() { called.set_value(); };
this->executor_->post([&lambda]() { make_ready_future().then(lambda); });
EXPECT_NO_THROW(called.get_future().get());
}
TYPED_TEST(FutureTest, shouldSupport_VoidFuture_NonConstLValueVoidContinuations_ReturningVoid)
{
std::promise<void> called;
auto lambda = [&called]() mutable { called.set_value(); };
this->executor_->post([&lambda]() { make_ready_future().then(lambda); });
EXPECT_NO_THROW(called.get_future().get());
}
// Future<T>::then(T -> U) -> Future<U>
TYPED_TEST(FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningValues)
{
std::promise<bool> called;
this->executor_->post([&called]() {
make_ready_future<int>(42).then([](int) { return true; }).then([&called](bool value) {
called.set_value(value);
});
});
EXPECT_EQ(true, called.get_future().get());
}
TYPED_TEST(
FutureTest, shouldSupport_ValueFuture_ValueContinuations_ReturningValues_WithContinuationErrors)
{
std::promise<bool> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future<int>(42)
.then([](int) -> Future<bool> { throw test_error{}; })
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); })
.then([&called](bool value) { called.set_value(value); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
// Future<void>::then(void -> U) -> Future<U>
TYPED_TEST(FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningValues)
{
std::promise<bool> called;
this->executor_->post([&called]() {
make_ready_future().then([]() { return true; }).then([&called](bool value) {
called.set_value(value);
});
});
EXPECT_EQ(true, called.get_future().get());
}
TYPED_TEST(
FutureTest, shouldSupport_VoidFuture_ValueContinuations_ReturningValues_WithContinuationErrors)
{
std::promise<bool> called;
struct test_error : public std::exception {
};
this->executor_->post([&called]() {
make_ready_future()
.then([]() -> Future<bool> { throw test_error{}; })
.catch_error([&called](std::exception_ptr e) { called.set_exception(e); })
.then([&called](bool value) { called.set_value(value); });
});
EXPECT_THROW(called.get_future().get(), test_error);
}
TYPED_TEST(FutureTest, shouldSupportResolvingPromisesWithLValues)
{
std::promise<int> called;
auto value = 5;
this->executor_->post([&called, &value]() {
auto lazy = make_lazy_future<int>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
future.then([&called](int v) { called.set_value(v); });
promise.set_value(value);
});
EXPECT_EQ(called.get_future().get(), value);
}
TYPED_TEST(FutureTest, shouldSupportLValuesForMakeReadyFuture)
{
std::promise<int> called;
auto value = 5;
this->executor_->post([&called, &value]() {
auto future = make_ready_future<int>(value);
future.then([&called](int v) { called.set_value(v); });
});
EXPECT_EQ(called.get_future().get(), value);
}
TYPED_TEST(FutureTest, thenShouldHoldExecutorReference)
{
std::promise<void> thenCalled;
auto lazy = make_lazy_future<void>();
auto future = std::get<0>(lazy);
auto promise = std::get<1>(lazy);
this->executor_->post([&thenCalled, &future]() {
future.then([]() {});
thenCalled.set_value();
});
thenCalled.get_future().wait();
// there is no guarantee here that the posted lambda has been executed completely,
// so wait for a small amount of time,
// we can't use termination_awaiter here cause in the successful case it would block
// (future should still keep a reference, stored by future.then())
std::this_thread::sleep_for(std::chrono::milliseconds(50));
this->factory_.reset();
this->executor_.reset();
try {
promise.set_value(); // this is going to crash if the executor isn't held by the future
// (then())
} catch (const std::runtime_error&) { // this is going to throw because the executor is already
// stopped, TODO: check if this is correct behavior
}
}
/// FutureThrowingExecutorTest provides test cases that ensure futures behave correctly in case
/// underlying executors encounter runtime errors that prevent them to execute tasks that futures
/// schedule on them.
template <typename E> class FutureThrowingExecutorTestBase : public Test {
public:
FutureThrowingExecutorTestBase(std::tuple<asyncly::Future<void>, asyncly::Promise<void>> lazy)
: promise_(std::get<1>(lazy))
, future_(std::get<0>(lazy))
, throwingExecutor_(asyncly::detail::ThrowingExecutor<E>::create())
, currentExecutorGuard_(throwingExecutor_)
{
}
FutureThrowingExecutorTestBase()
: FutureThrowingExecutorTestBase(make_lazy_future<void>())
{
}
asyncly::Promise<void> promise_;
asyncly::Future<void> future_;
const std::shared_ptr<asyncly::detail::ThrowingExecutor<E>> throwingExecutor_;
const asyncly::test::CurrentExecutorGuard currentExecutorGuard_;
};
class FutureThrowingExecutorRuntimeErrorTest
: public FutureThrowingExecutorTestBase<std::runtime_error> {
};
TEST_F(FutureThrowingExecutorRuntimeErrorTest, throws_on_late_then)
{
promise_.set_value();
EXPECT_ANY_THROW(future_.then([]() { ADD_FAILURE(); }));
}
TEST_F(FutureThrowingExecutorRuntimeErrorTest, throws_on_late_set_value)
{
future_.then([]() { ADD_FAILURE(); });
EXPECT_ANY_THROW(promise_.set_value());
}
TEST_F(FutureThrowingExecutorRuntimeErrorTest, throws_on_late_catch_error)
{
promise_.set_exception("intentional error");
EXPECT_ANY_THROW(future_.catch_error([](auto) { ADD_FAILURE(); }));
}
TEST_F(FutureThrowingExecutorRuntimeErrorTest, throws_on_late_set_exception)
{
future_.catch_error([](auto) { ADD_FAILURE(); });
EXPECT_ANY_THROW(promise_.set_exception("intentional error"));
}
class FutureThrowingExecutorExecutorStoppedExceptionTest
: public FutureThrowingExecutorTestBase<ExecutorStoppedException> {
};
TEST_F(FutureThrowingExecutorExecutorStoppedExceptionTest, throws_on_late_then)
{
promise_.set_value();
EXPECT_ANY_THROW(future_.then([]() { ADD_FAILURE(); }));
}
TEST_F(
FutureThrowingExecutorExecutorStoppedExceptionTest,
catches_executor_post_exception_on_late_set_value)
{
future_.then([]() { ADD_FAILURE(); });
promise_.set_value();
}
TEST_F(FutureThrowingExecutorExecutorStoppedExceptionTest, throws_on_late_catch_error)
{
promise_.set_exception("intentional error");
EXPECT_ANY_THROW(future_.catch_error([](auto) { ADD_FAILURE(); }));
}
TEST_F(
FutureThrowingExecutorExecutorStoppedExceptionTest,
catches_executor_post_exception_on_late_set_exception)
{
future_.catch_error([](auto) { ADD_FAILURE(); });
promise_.set_exception("intentional error");
}
}
| 30.698803 | 100 | 0.631067 | erikzenker |
98249d9c1149eda957edef926e156186ef6433ca | 1,664 | hpp | C++ | src/ai/composite/engine_fai.hpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | 12 | 2015-03-04T15:07:00.000Z | 2019-09-13T16:31:06.000Z | src/ai/composite/engine_fai.hpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | null | null | null | src/ai/composite/engine_fai.hpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | 5 | 2017-04-22T08:16:48.000Z | 2020-07-12T03:35:16.000Z | /* $Id: engine_fai.hpp 48153 2011-01-01 15:57:50Z mordante $ */
/*
Copyright (C) 2009 - 2011 by Yurii Chernyi <terraninfo@terraninfo.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* FAI AI Support engine - creating specific ai components from config
* @file
*/
#ifndef AI_COMPOSITE_ENGINE_FAI_HPP_INCLUDED
#define AI_COMPOSITE_ENGINE_FAI_HPP_INCLUDED
#include "engine.hpp"
#include "contexts.hpp"
//============================================================================
namespace ai {
class formula_ai;
class engine_fai : public engine {
public:
engine_fai( readonly_context &context, const config &cfg );
virtual ~engine_fai();
virtual void do_parse_candidate_action_from_config( rca_context &context, const config &cfg, std::back_insert_iterator<std::vector< candidate_action_ptr > > b );
virtual void do_parse_stage_from_config( ai_context &context, const config &cfg, std::back_insert_iterator<std::vector< stage_ptr > > b );
virtual std::string evaluate(const std::string &str);
virtual config to_config() const;
virtual void set_ai_context(ai_context *context);
private:
boost::shared_ptr<formula_ai> formula_ai_;
};
} //end of namespace ai
#endif
| 30.814815 | 163 | 0.697115 | blackberry |
982537b9da42cfe4184a27d5b1f3deb91abdcd1e | 12,950 | cpp | C++ | MainWindow.cpp | azonenberg/sump-monitor | 74d44823990f4ad84fca32e8ddf47b96f5e5ee5c | [
"BSD-3-Clause"
] | null | null | null | MainWindow.cpp | azonenberg/sump-monitor | 74d44823990f4ad84fca32e8ddf47b96f5e5ee5c | [
"BSD-3-Clause"
] | null | null | null | MainWindow.cpp | azonenberg/sump-monitor | 74d44823990f4ad84fca32e8ddf47b96f5e5ee5c | [
"BSD-3-Clause"
] | null | null | null | /***********************************************************************************************************************
* *
* SUMP MONITOR v0.1 *
* *
* Copyright (c) 2020 Andrew D. Zonenberg *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
***********************************************************************************************************************/
/**
@file
@author Andrew D. Zonenberg
@brief Implementation of main application window class
*/
#include "sumpmon.h"
#include "MainWindow.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
/**
@brief Initializes the main window
*/
MainWindow::MainWindow()
: m_depthGraph(500)
, m_volumeGraph(500)
, m_flowGraph(500)
, m_alarming(false)
{
set_title("Sump Monitor");
//Initial setup
set_reallocate_redraws(true);
//Add widgets
CreateWidgets();
//Run the HMI in fullscreen mode
fullscreen();
//Set the update timer
sigc::slot<bool> slot = sigc::bind(sigc::mem_fun(*this, &MainWindow::OnTimer), 1);
sigc::connection conn = Glib::signal_timeout().connect(slot, 1000);
}
/**
@brief Application cleanup
*/
MainWindow::~MainWindow()
{
}
/**
@brief Helper function for creating widgets and setting up signal handlers
*/
void MainWindow::CreateWidgets()
{
m_tabs.override_font(Pango::FontDescription("sans bold 20"));
string font = "sans bold 14";
//Set up window hierarchy
add(m_tabs);
m_tabs.append_page(m_summaryTab, "Summary");
m_summaryTab.pack_start(m_depthBox, Gtk::PACK_SHRINK);
m_depthBox.pack_start(m_depthCaptionLabel, Gtk::PACK_SHRINK);
m_depthCaptionLabel.override_font(Pango::FontDescription("sans bold 20"));
m_depthCaptionLabel.set_label("Depth: ");
m_depthCaptionLabel.set_size_request(125, 1);
m_depthBox.pack_start(m_depthLabel, Gtk::PACK_SHRINK);
m_depthLabel.override_font(Pango::FontDescription("sans bold 20"));
m_summaryTab.pack_start(m_volumeBox, Gtk::PACK_SHRINK);
m_volumeBox.pack_start(m_volumeCaptionLabel, Gtk::PACK_SHRINK);
m_volumeCaptionLabel.override_font(Pango::FontDescription("sans bold 20"));
m_volumeCaptionLabel.set_label("Volume: ");
m_volumeCaptionLabel.set_size_request(125, 1);
m_volumeBox.pack_start(m_volumeLabel, Gtk::PACK_SHRINK);
m_volumeLabel.override_font(Pango::FontDescription("sans bold 20"));
m_summaryTab.pack_start(m_flowBox, Gtk::PACK_SHRINK);
m_flowBox.pack_start(m_flowCaptionLabel, Gtk::PACK_SHRINK);
m_flowCaptionLabel.override_font(Pango::FontDescription("sans bold 20"));
m_flowCaptionLabel.set_label("Flow: ");
m_flowCaptionLabel.set_size_request(125, 1);
m_flowBox.pack_start(m_flowLabel, Gtk::PACK_SHRINK);
m_flowLabel.override_font(Pango::FontDescription("sans bold 20"));
m_summaryTab.pack_start(m_silenceAlarmButton, Gtk::PACK_SHRINK);
m_silenceAlarmButton.set_label("Silence alarm");
m_silenceAlarmButton.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::SilenceAlarm));
m_summaryTab.pack_start(m_trendFrame, Gtk::PACK_EXPAND_WIDGET);
m_trendFrame.set_label("Weekly Flow Trend");
m_trendFrame.add(m_trendGraph);
m_trendGraph.m_units = "L/hr";
m_trendGraph.m_minScale = 0;
m_trendGraph.m_maxScale = 50;
m_trendGraph.m_scaleBump = 5;
m_trendGraph.m_maxRedline = 45;
m_trendGraph.m_series.push_back(&m_trendData);
m_trendGraph.m_seriesName = "flow";
m_trendGraph.m_timeScale = 0.001;
m_trendGraph.m_timeTick = 86400;
m_trendGraph.m_lineWidth = 3;
m_trendGraph.m_drawLegend = false;
m_trendData.m_color = Gdk::Color("#0000ff");
m_trendGraph.m_font = Pango::FontDescription(font);
m_tabs.append_page(m_depthTab, "Depth");
m_depthTab.add(m_depthGraph);
m_depthGraph.m_units = "mm";
m_depthGraph.m_minScale = 100;
m_depthGraph.m_maxScale = 225;
m_depthGraph.m_scaleBump = 25;
m_depthGraph.m_maxRedline = 200;
m_depthGraph.m_series.push_back(&m_depthData);
m_depthGraph.m_seriesName = "depth";
m_depthGraph.m_timeScale = 0.15;
m_depthGraph.m_timeTick = 600;
m_depthGraph.m_lineWidth = 3;
m_depthGraph.m_drawLegend = false;
m_depthData.m_color = Gdk::Color("#0000ff");
m_depthGraph.m_font = Pango::FontDescription(font);
m_tabs.append_page(m_volumeTab, "Volume");
m_volumeTab.add(m_volumeGraph);
m_volumeGraph.m_units = "L";
m_volumeGraph.m_minScale = 14;
m_volumeGraph.m_maxScale = 30;
m_volumeGraph.m_scaleBump = 2;
m_volumeGraph.m_maxRedline = 28;
m_volumeGraph.m_series.push_back(&m_volumeData);
m_volumeGraph.m_seriesName = "volume";
m_volumeGraph.m_timeScale = 0.15;
m_volumeGraph.m_timeTick = 600;
m_volumeGraph.m_lineWidth = 3;
m_volumeGraph.m_drawLegend = false;
m_volumeData.m_color = Gdk::Color("#0000ff");
m_volumeGraph.m_font = Pango::FontDescription(font);
m_tabs.append_page(m_inflowTab, "Flow");
m_inflowTab.add(m_flowGraph);
m_flowGraph.m_units = "L/hr";
m_flowGraph.m_minScale = 0;
m_flowGraph.m_maxScale = 50;
m_flowGraph.m_scaleBump = 5;
m_flowGraph.m_maxRedline = 45;
m_flowGraph.m_series.push_back(&m_flowData);
m_flowGraph.m_seriesName = "flow";
m_flowGraph.m_timeScale = 0.075;
m_flowGraph.m_timeTick = 1200;
m_flowGraph.m_lineWidth = 3;
m_flowGraph.m_drawLegend = false;
m_flowData.m_color = Gdk::Color("#0000ff");
m_flowGraph.m_font = Pango::FontDescription(font);
m_tabs.append_page(m_dutyTab, "Duty %");
//Done adding widgets
show_all();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Message handlers
bool MainWindow::OnTimer(int /*timer*/)
{
//Before we do anything else, check if any of the floor sensors are leaking and ring the alarm.
if(g_leakReading > 10)
{
if(!m_alarming)
AlarmOn();
}
//Clear alarms if no trouble conditions
else if(m_alarming)
AlarmOff();
double t = g_timeOfReading;
double depth = g_depth;
double volume = DepthToVolume(depth);
//If we get called before the first measurement shows up, do nothing.
//(Negative depth is physically impossible)
if(depth < 0)
return true;
auto dseries = m_depthData.GetSeries("depth");
auto vseries = m_volumeData.GetSeries("volume");
auto fseries = m_flowData.GetSeries("flow");
//Flow is calculated in liters per hour.
//Use a large Gaussian window to get a more accurate estimate.
const size_t window = 127;
const size_t mid = (window-1)/2;
const size_t delta = 120;
const size_t dwindow = window + delta;
double sigma = 30;
double coeffs[window];
double frac = 1 / (sqrt(2 * M_PI)*sigma);
double isq = 1 / (2*sigma*sigma);
double sum = 0;
for(size_t i=0; i<window; i++)
{
double dx = fabs(i - mid);
coeffs[i] = frac * exp(-dx*dx*isq);
sum += coeffs[i];
}
for(size_t i=0; i<window; i++) //normalize kernel
coeffs[i] /= sum;
double flow = 0;
if(vseries->size() > dwindow)
{
double samples[dwindow];
double times[dwindow];
auto it = vseries->end();
it --;
for(size_t i=0; i<dwindow && it != vseries->begin(); i ++)
{
samples[i] = it->value;
times[i] = it->time;
it --;
}
double center1 = times[mid];
double center2 = times[mid + delta];
//Smooth the volumetric data with a Gaussian kernel
double gauss1 = 0;
double gauss2 = 0;
for(size_t i=0; i<window; i++)
{
gauss1 += samples[i] * coeffs[i];
gauss2 += samples[i+delta] * coeffs[i];
}
double dt = center1 - center2;
//printf("dt = %.3f\n", dt);
double dvol = gauss1 - gauss2; //liters
flow = (dvol * 3600) / dt;
printf("rates: %.3f %.3f / %.3f L, %.3f L/hr, dt %f\n", gauss1, gauss2, dvol, flow, dt);
}
//TODO: determine if the pump is on or not
dseries->push_back(GraphPoint(t, depth));
vseries->push_back(GraphPoint(t, volume));
fseries->push_back(GraphPoint(t, flow));
//Format text
char tmp[128];
snprintf(tmp, sizeof(tmp), "%.1f mm", depth);
m_depthLabel.set_label(tmp);
snprintf(tmp, sizeof(tmp), "%.1f L", volume);
m_volumeLabel.set_label(tmp);
snprintf(tmp, sizeof(tmp), "%.1f L/hr", flow);
m_flowLabel.set_label(tmp);
//If the flow rate is positive (pump not running, water leaking in) add the current flow rate to the history
if(flow > 0)
{
if(m_flowSamples.empty())
printf("Pump stopped\n");
m_flowSamples.push_back(flow);
}
//Pump is running.
//Pump must have just started if we have samples in the buffer.
else if(!m_flowSamples.empty() && (flow < -1) )
{
printf("Pump started\n");
//Figure out total memory depth.
//Ignore 20 sec at start and end of buffer due to interference from the pump flow
size_t margin = 20;
double sum = 0;
double count = 0;
for(size_t i=margin; i+margin < m_flowSamples.size(); i++)
{
sum += m_flowSamples[i];
count ++;
}
double avg;
if(count == 0)
avg = 0;
else
avg = sum / count;
m_flowSamples.clear();
printf("Average flow during this pump cycle: %f\n", avg);
//Write current flow to a file we can read from munin
FILE* fp = fopen("avgflow.txt", "w");
fprintf(fp, "%f", avg);
fclose(fp);
auto tseries = m_trendData.GetSeries("flow");
tseries->push_back(GraphPoint(t, avg));
}
//No, pump has been running for a while. No action needed.
else
{
}
//Clean out old stuff
size_t max_points = 10000;
while(dseries->size() > max_points)
dseries->erase(dseries->begin());
while(vseries->size() > max_points)
vseries->erase(vseries->begin());
while(fseries->size() > max_points)
fseries->erase(fseries->begin());
return true;
}
void MainWindow::AlarmOn()
{
m_alarming = true;
system("python3 /home/azonenberg/alarm-on.py");
}
void MainWindow::AlarmOff()
{
m_alarming = false;
system("python3 /home/azonenberg/alarm-off.py");
}
void MainWindow::SilenceAlarm()
{
system("python3 /home/azonenberg/alarm-off.py");
}
| 36.685552 | 120 | 0.59529 | azonenberg |
9825da1c31e6dde9b247fba908733786293c6894 | 657 | cpp | C++ | Engine/Src/SFEngine/Asset/Importer/SFAssetImporterTexture.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | 1 | 2020-06-20T07:35:25.000Z | 2020-06-20T07:35:25.000Z | Engine/Src/SFEngine/Asset/Importer/SFAssetImporterTexture.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | Engine/Src/SFEngine/Asset/Importer/SFAssetImporterTexture.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2018 Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Asset Importer
//
////////////////////////////////////////////////////////////////////////////////
#include "SFEnginePCH.h"
#include "ResultCode/SFResultCodeSystem.h"
#include "Asset/Importer//SFAssetImporterTexture.h"
#include "Resource/SFTexture.h"
namespace SF
{
AssetImporterTexture::AssetImporterTexture(IHeap& heap, const StringCrc64& name)
: AssetImporter(heap, name)
{
}
AssetImporterTexture::~AssetImporterTexture()
{
}
}
| 17.289474 | 82 | 0.499239 | blue3k |
9829d1497da485c2fb5362ba89eb3a4f4f977d84 | 3,962 | cc | C++ | CalibFormats/HcalObjects/src/HcalCoderDb.cc | Nik-Menendez/L1Trigger | 5336631cc0a517495869279ed7d3a4cac8d4e5e5 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CalibFormats/HcalObjects/src/HcalCoderDb.cc | Nik-Menendez/L1Trigger | 5336631cc0a517495869279ed7d3a4cac8d4e5e5 | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CalibFormats/HcalObjects/src/HcalCoderDb.cc | Nik-Menendez/L1Trigger | 5336631cc0a517495869279ed7d3a4cac8d4e5e5 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | /** \class HcalCoderDB
coder which uses DB services to convert to fC
$Author: ratnikov
*/
#include "CondFormats/HcalObjects/interface/HcalQIECoder.h"
#include "CalibFormats/HcalObjects/interface/HcalCoderDb.h"
HcalCoderDb::HcalCoderDb (const HcalQIECoder& fCoder, const HcalQIEShape& fShape)
: mCoder (&fCoder),
mShape (&fShape)
{}
template <class Digi> void HcalCoderDb::adc2fC_ (const Digi& df, CaloSamples& clf) const {
clf=CaloSamples(df.id(),df.size());
for (int i=0; i<df.size(); i++) {
clf[i]=mCoder->charge (*mShape, df[i].adc (), df[i].capid ());
}
clf.setPresamples(df.presamples());
}
template <> void HcalCoderDb::adc2fC_<QIE10DataFrame> (const QIE10DataFrame& df, CaloSamples& clf) const {
clf=CaloSamples(df.id(),df.samples());
for (int i=0; i<df.samples(); i++) {
clf[i]=mCoder->charge (*mShape, df[i].adc (), df[i].capid ());
if(df[i].soi()) clf.setPresamples(i);
}
}
template <> void HcalCoderDb::adc2fC_<QIE11DataFrame> (const QIE11DataFrame& df, CaloSamples& clf) const {
clf=CaloSamples(df.id(),df.samples());
for (int i=0; i<df.samples(); i++) {
clf[i]=mCoder->charge (*mShape, df[i].adc (), df[i].capid ());
if(df[i].soi()) clf.setPresamples(i);
}
}
template <class Digi> void HcalCoderDb::fC2adc_ (const CaloSamples& clf, Digi& df, int fCapIdOffset) const {
df = Digi (clf.id ());
df.setSize (clf.size ());
df.setPresamples (clf.presamples ());
for (int i=0; i<clf.size(); i++) {
int capId = (fCapIdOffset + i) % 4;
df.setSample(i, HcalQIESample(mCoder->adc(*mShape, clf[i], capId), capId, 0, 0));
}
}
template <> void HcalCoderDb::fC2adc_<QIE10DataFrame> (const CaloSamples& clf, QIE10DataFrame& df, int fCapIdOffset) const {
int presample = clf.presamples ();
for (int i=0; i<clf.size(); i++) {
int capId = (fCapIdOffset + i) % 4;
bool soi = (i==presample);
df.setSample(i, mCoder->adc(*mShape, clf[i], capId), 0, 0, capId, soi, true);
}
}
template <> void HcalCoderDb::fC2adc_<QIE11DataFrame> (const CaloSamples& clf, QIE11DataFrame& df, int fCapIdOffset) const {
int presample = clf.presamples ();
df.setCapid0(fCapIdOffset%4);
for (int i=0; i<clf.size(); i++) {
int capId = (fCapIdOffset + i) % 4;
bool soi = (i==presample);
df.setSample(i, mCoder->adc(*mShape, clf[i], capId), 0, soi);
}
}
void HcalCoderDb::adc2fC(const HBHEDataFrame& df, CaloSamples& lf) const {adc2fC_ (df, lf);}
void HcalCoderDb::adc2fC(const HODataFrame& df, CaloSamples& lf) const {adc2fC_ (df, lf);}
void HcalCoderDb::adc2fC(const HFDataFrame& df, CaloSamples& lf) const {adc2fC_ (df, lf);}
void HcalCoderDb::adc2fC(const ZDCDataFrame& df, CaloSamples& lf) const {adc2fC_ (df, lf);}
void HcalCoderDb::adc2fC(const HcalCalibDataFrame& df, CaloSamples& lf) const {adc2fC_ (df, lf);}
void HcalCoderDb::adc2fC(const QIE10DataFrame& df, CaloSamples& lf) const {adc2fC_ (df, lf);}
void HcalCoderDb::adc2fC(const QIE11DataFrame& df, CaloSamples& lf) const {adc2fC_ (df, lf);}
void HcalCoderDb::fC2adc(const CaloSamples& clf, HBHEDataFrame& df, int fCapIdOffset) const {fC2adc_ (clf, df, fCapIdOffset);}
void HcalCoderDb::fC2adc(const CaloSamples& clf, HFDataFrame& df, int fCapIdOffset) const {fC2adc_ (clf, df, fCapIdOffset);}
void HcalCoderDb::fC2adc(const CaloSamples& clf, HODataFrame& df, int fCapIdOffset) const {fC2adc_ (clf, df, fCapIdOffset);}
void HcalCoderDb::fC2adc(const CaloSamples& clf, ZDCDataFrame& df, int fCapIdOffset) const {fC2adc_ (clf, df, fCapIdOffset);}
void HcalCoderDb::fC2adc(const CaloSamples& clf, HcalCalibDataFrame& df, int fCapIdOffset) const {fC2adc_ (clf, df, fCapIdOffset);}
void HcalCoderDb::fC2adc(const CaloSamples& clf, QIE10DataFrame& df, int fCapIdOffset) const {fC2adc_ (clf, df, fCapIdOffset);}
void HcalCoderDb::fC2adc(const CaloSamples& clf, QIE11DataFrame& df, int fCapIdOffset) const {fC2adc_ (clf, df, fCapIdOffset);}
| 47.166667 | 132 | 0.68425 | Nik-Menendez |
982dff168829c2a39d3740c43f2090545bc62a81 | 7,944 | cpp | C++ | src/mbgl/text/collision_tile.cpp | SylvainHocq/mapbox-gl-native | bca9d091805dc01a4456ab3f24e9de87f9b4aa48 | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2021-04-26T05:41:57.000Z | 2021-04-26T05:41:57.000Z | src/mbgl/text/collision_tile.cpp | SylvainHocq/mapbox-gl-native | bca9d091805dc01a4456ab3f24e9de87f9b4aa48 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/text/collision_tile.cpp | SylvainHocq/mapbox-gl-native | bca9d091805dc01a4456ab3f24e9de87f9b4aa48 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #include <mbgl/text/collision_tile.hpp>
#include <mbgl/geometry/feature_index.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/math.hpp>
#include <cmath>
namespace mbgl {
auto infinity = std::numeric_limits<float>::infinity();
CollisionTile::CollisionTile(PlacementConfig config_) : config(std::move(config_)),
edges({{
// left
CollisionBox(Point<float>(0, 0), 0, -infinity, 0, infinity, infinity),
// right
CollisionBox(Point<float>(util::EXTENT, 0), 0, -infinity, 0, infinity, infinity),
// top
CollisionBox(Point<float>(0, 0), -infinity, 0, infinity, 0, infinity),
// bottom
CollisionBox(Point<float>(0, util::EXTENT), -infinity, 0, infinity, 0, infinity),
}}) {
tree.clear();
// Compute the transformation matrix.
const float angle_sin = std::sin(config.angle);
const float angle_cos = std::cos(config.angle);
rotationMatrix = { { angle_cos, -angle_sin, angle_sin, angle_cos } };
reverseRotationMatrix = { { angle_cos, angle_sin, -angle_sin, angle_cos } };
// Stretch boxes in y direction to account for the map tilt.
const float _yStretch = 1.0f / std::cos(config.pitch);
// The amount the map is squished depends on the y position.
// Sort of account for this by making all boxes a bit bigger.
yStretch = std::pow(_yStretch, 1.3);
}
float CollisionTile::findPlacementScale(float minPlacementScale, const Point<float>& anchor,
const CollisionBox& box, const Point<float>& blockingAnchor, const CollisionBox& blocking) {
// Find the lowest scale at which the two boxes can fit side by side without overlapping.
// Original algorithm:
float s1 = (blocking.x1 - box.x2) / (anchor.x - blockingAnchor.x); // scale at which new box is to the left of old box
float s2 = (blocking.x2 - box.x1) / (anchor.x - blockingAnchor.x); // scale at which new box is to the right of old box
float s3 = (blocking.y1 - box.y2) * yStretch / (anchor.y - blockingAnchor.y); // scale at which new box is to the top of old box
float s4 = (blocking.y2 - box.y1) * yStretch / (anchor.y - blockingAnchor.y); // scale at which new box is to the bottom of old box
if (std::isnan(s1) || std::isnan(s2)) s1 = s2 = 1;
if (std::isnan(s3) || std::isnan(s4)) s3 = s4 = 1;
float collisionFreeScale = ::fmin(::fmax(s1, s2), ::fmax(s3, s4));
if (collisionFreeScale > blocking.maxScale) {
// After a box's maxScale the label has shrunk enough that the box is no longer needed to cover it,
// so unblock the new box at the scale that the old box disappears.
collisionFreeScale = blocking.maxScale;
}
if (collisionFreeScale > box.maxScale) {
// If the box can only be shown after it is visible, then the box can never be shown.
// But the label can be shown after this box is not visible.
collisionFreeScale = box.maxScale;
}
if (collisionFreeScale > minPlacementScale &&
collisionFreeScale >= blocking.placementScale) {
// If this collision occurs at a lower scale than previously found collisions
// and the collision occurs while the other label is visible
// this this is the lowest scale at which the label won't collide with anything
minPlacementScale = collisionFreeScale;
}
return minPlacementScale;
}
float CollisionTile::placeFeature(const CollisionFeature& feature, const bool allowOverlap, const bool avoidEdges) {
float minPlacementScale = minScale;
for (auto& box : feature.boxes) {
const auto anchor = util::matrixMultiply(rotationMatrix, box.anchor);
if (!allowOverlap) {
for (auto it = tree.qbegin(bgi::intersects(getTreeBox(anchor, box))); it != tree.qend(); ++it) {
const CollisionBox& blocking = std::get<1>(*it);
Point<float> blockingAnchor = util::matrixMultiply(rotationMatrix, blocking.anchor);
minPlacementScale = findPlacementScale(minPlacementScale, anchor, box, blockingAnchor, blocking);
if (minPlacementScale >= maxScale) return minPlacementScale;
}
}
if (avoidEdges) {
const Point<float> tl = { box.x1, box.y1 };
const Point<float> tr = { box.x2, box.y1 };
const Point<float> bl = { box.x1, box.y2 };
const Point<float> br = { box.x2, box.y2 };
const Point<float> rtl = util::matrixMultiply(reverseRotationMatrix, tl);
const Point<float> rtr = util::matrixMultiply(reverseRotationMatrix, tr);
const Point<float> rbl = util::matrixMultiply(reverseRotationMatrix, bl);
const Point<float> rbr = util::matrixMultiply(reverseRotationMatrix, br);
CollisionBox rotatedBox(box.anchor,
::fmin(::fmin(rtl.x, rtr.x), ::fmin(rbl.x, rbr.x)),
::fmin(::fmin(rtl.y, rtr.y), ::fmin(rbl.y, rbr.y)),
::fmax(::fmax(rtl.x, rtr.x), ::fmax(rbl.x, rbr.x)),
::fmax(::fmax(rtl.y, rtr.y), ::fmax(rbl.y, rbr.y)),
box.maxScale);
for (auto& blocking : edges) {
minPlacementScale = findPlacementScale(minPlacementScale, box.anchor, rotatedBox, blocking.anchor, blocking);
if (minPlacementScale >= maxScale) return minPlacementScale;
}
}
}
return minPlacementScale;
}
void CollisionTile::insertFeature(CollisionFeature& feature, const float minPlacementScale, const bool ignorePlacement) {
for (auto& box : feature.boxes) {
box.placementScale = minPlacementScale;
}
if (minPlacementScale < maxScale) {
std::vector<CollisionTreeBox> treeBoxes;
for (auto& box : feature.boxes) {
treeBoxes.emplace_back(getTreeBox(util::matrixMultiply(rotationMatrix, box.anchor), box), box, feature.indexedFeature);
}
if (ignorePlacement) {
ignoredTree.insert(treeBoxes.begin(), treeBoxes.end());
} else {
tree.insert(treeBoxes.begin(), treeBoxes.end());
}
}
}
Box CollisionTile::getTreeBox(const Point<float>& anchor, const CollisionBox& box, const float scale) {
return Box{
CollisionPoint{
anchor.x + box.x1 / scale,
anchor.y + box.y1 / scale * yStretch
},
CollisionPoint{
anchor.x + box.x2 / scale,
anchor.y + box.y2 / scale * yStretch
}
};
}
std::vector<IndexedSubfeature> CollisionTile::queryRenderedSymbols(const mapbox::geometry::box<int16_t>& box, const float scale) {
std::vector<IndexedSubfeature> result;
std::unordered_map<std::string, std::set<std::size_t>> sourceLayerFeatures;
auto anchor = util::matrixMultiply(rotationMatrix, convertPoint<float>(box.min));
CollisionBox queryBox(anchor, 0, 0, box.max.x - box.min.x, box.max.y - box.min.y, scale);
auto predicates = bgi::intersects(getTreeBox(anchor, queryBox));
auto fn = [&] (const Tree& tree_) {
for (auto it = tree_.qbegin(predicates); it != tree_.qend(); ++it) {
const CollisionBox& blocking = std::get<1>(*it);
const IndexedSubfeature& indexedFeature = std::get<2>(*it);
auto& seenFeatures = sourceLayerFeatures[indexedFeature.sourceLayerName];
if (seenFeatures.find(indexedFeature.index) == seenFeatures.end()) {
auto blockingAnchor = util::matrixMultiply(rotationMatrix, blocking.anchor);
float minPlacementScale = findPlacementScale(minScale, anchor, queryBox, blockingAnchor, blocking);
if (minPlacementScale >= scale) {
seenFeatures.insert(indexedFeature.index);
result.push_back(indexedFeature);
}
}
}
};
fn(tree);
fn(ignoredTree);
return result;
}
} // namespace mbgl
| 42.031746 | 135 | 0.634315 | SylvainHocq |
9831de890e9deaa18ea939c33f4de2368059108e | 13,427 | cpp | C++ | source/modules/neuralNetwork/layer/pooling/pooling.cpp | JonathanLehner/korali | 90f97d8e2fed2311f988f39cfe014f23ba7dd6cf | [
"MIT"
] | 43 | 2018-07-26T07:20:42.000Z | 2022-03-02T10:23:12.000Z | source/modules/neuralNetwork/layer/pooling/pooling.cpp | JonathanLehner/korali | 90f97d8e2fed2311f988f39cfe014f23ba7dd6cf | [
"MIT"
] | 212 | 2018-09-21T10:44:07.000Z | 2022-03-22T14:33:05.000Z | source/modules/neuralNetwork/layer/pooling/pooling.cpp | JonathanLehner/korali | 90f97d8e2fed2311f988f39cfe014f23ba7dd6cf | [
"MIT"
] | 16 | 2018-07-25T15:00:36.000Z | 2022-03-22T14:19:46.000Z | #include "modules/neuralNetwork/layer/pooling/pooling.hpp"
#include "modules/neuralNetwork/neuralNetwork.hpp"
#ifdef _KORALI_USE_CUDNN
#include "auxiliar/cudaUtils.hpp"
#endif
#ifdef _KORALI_USE_ONEDNN
#include "auxiliar/dnnUtils.hpp"
using namespace dnnl;
#endif
#include <Eigen/Dense>
using namespace Eigen;
namespace korali
{
namespace neuralNetwork
{
namespace layer
{
;
void Pooling::initialize()
{
// Checking Layer size
if (_outputChannels == 0) KORALI_LOG_ERROR("Node count for layer (%lu) should be larger than zero.\n", _index);
// Checking position
if (_index == 0) KORALI_LOG_ERROR("Pooling layers cannot be the starting layer of the NN\n");
if (_index == _nn->_layers.size() - 1) KORALI_LOG_ERROR("Pooling layers cannot be the last layer of the NN\n");
// Precalculating values for the pooling operation
N = _batchSize;
IH = _imageHeight;
IW = _imageWidth;
KH = _kernelHeight;
KW = _kernelWidth;
SV = _verticalStride;
SH = _horizontalStride;
PT = _paddingTop;
PL = _paddingLeft;
PB = _paddingBottom;
PR = _paddingRight;
// Check for non zeros
if (IH <= 0) KORALI_LOG_ERROR("Image height must be larger than zero for pooling layer.\n");
if (IW <= 0) KORALI_LOG_ERROR("Image width must be larger than zero for pooling layer.\n");
if (KH <= 0) KORALI_LOG_ERROR("Kernel height must be larger than zero for pooling layer.\n");
if (KW <= 0) KORALI_LOG_ERROR("Kernel width must be larger than zero for pooling layer.\n");
if (SV <= 0) KORALI_LOG_ERROR("Vertical stride must be larger than zero for pooling layer.\n");
if (SH <= 0) KORALI_LOG_ERROR("Horizontal stride must be larger than zero for pooling layer.\n");
// Several sanity checks
if (KH > IH) KORALI_LOG_ERROR("Kernel height cannot be larger than input image height.\n");
if (KW > IW) KORALI_LOG_ERROR("Kernel height cannot be larger than input image height.\n");
if (PR + PL > IW) KORALI_LOG_ERROR("L+R Paddings cannot exceed the width of the input image.\n");
if (PT + PB > IH) KORALI_LOG_ERROR("T+B Paddings cannot exceed the height of the input image.\n");
// Check whether the output channels of the previous layer is divided by the height and width
if (_prevLayer->_outputChannels % (IH * IW) > 0) KORALI_LOG_ERROR("Previous layer contains a number of channels (%lu) not divisible by the pooling 2D HxW setup (%lux%lu).\n", _prevLayer->_outputChannels, IH, IW);
IC = _prevLayer->_outputChannels / (IH * IW);
// Deriving output height and width
OH = std::floor((IH - (KH - (PR + PL))) / SH) + 1;
OW = std::floor((IW - (KW - (PT + PB))) / SV) + 1;
// Check whether the output channels of the previous layer is divided by the height and width
if (_outputChannels % (OH * OW) > 0) KORALI_LOG_ERROR("Pooling layer contains a number of output channels (%lu) not divisible by the output image size (%lux%lu) given kernel (%lux%lu) size and padding/stride configuration.\n", _outputChannels, OH, OW, KH, KW);
OC = _outputChannels / (OH * OW);
}
void Pooling::createForwardPipeline()
{
// Calling base layer function
Layer::createForwardPipeline();
if (_nn->_engine == "Korali") KORALI_LOG_ERROR("Pooling Layers still not supported in Korali's NN backend. Use OneDNN.\n");
if (_nn->_engine == "CuDNN") KORALI_LOG_ERROR("Pooling Layers still not supported in CuDNNbackend. Use OneDNN.\n");
#ifdef _KORALI_USE_ONEDNN
if (_nn->_engine == "OneDNN")
{
// Creating memory descriptor mappings for input memory
_srcMemDesc = memory::desc({N, IC, IH, IW}, memory::data_type::f32, memory::format_tag::nchw);
_dstMemDesc = memory::desc({N, OC, OH, OW}, memory::data_type::f32, memory::format_tag::nchw);
// Creating padding dims
memory::dims ST = {SV, SH}; // Horizontal Vertical
memory::dims PTL = {PT, PL}; // Top Left
memory::dims PBR = {PB, PR}; // Bottom Right
// Creating work memory
memory::dims kernelDims = {KH, KW};
// Determining algorithm
dnnl::algorithm algorithmType;
if (_function == "Max") algorithmType = dnnl::algorithm::pooling_max;
if (_function == "Inclusive Average") algorithmType = dnnl::algorithm::pooling_avg_include_padding;
if (_function == "Exclusive Average") algorithmType = dnnl::algorithm::pooling_avg_exclude_padding;
// We create the pooling operation
auto pooling_d = pooling_forward::desc(_propKind, algorithmType, _srcMemDesc, _dstMemDesc, ST, kernelDims, PTL, PBR);
// Create inner product primitive descriptor.
dnnl::primitive_attr poolingPrimitiveAttributes;
_forwardPoolingPrimitiveDesc = pooling_forward::primitive_desc(pooling_d, poolingPrimitiveAttributes, _nn->_dnnlEngine);
// Create pooling workspace memory
_workspaceMem.resize(_nn->_timestepCount);
for (size_t t = 0; t < _nn->_timestepCount; t++)
_workspaceMem[t] = memory(_forwardPoolingPrimitiveDesc.workspace_desc(), _nn->_dnnlEngine);
// Create the weights+bias primitive.
_forwardPoolingPrimitive = pooling_forward(_forwardPoolingPrimitiveDesc);
}
#endif
}
void Pooling::createBackwardPipeline()
{
// Initializing memory objects and primitives for BACKWARD propagation
// Calling base layer function
Layer::createBackwardPipeline();
#ifdef _KORALI_USE_ONEDNN
if (_nn->_engine == "OneDNN")
{
// Creating memory descriptor mappings for input memory
_srcMemDesc = memory::desc({N, IC, IH, IW}, memory::data_type::f32, memory::format_tag::nchw);
_dstMemDesc = memory::desc({N, OC, OH, OW}, memory::data_type::f32, memory::format_tag::nchw);
// Creating padding dims
memory::dims ST = {SV, SH}; // Horizontal Vertical
memory::dims PTL = {PT, PL}; // Top Left
memory::dims PBR = {PB, PR}; // Bottom Right
// Creating work memory
memory::dims kernelDims = {KH, KW};
// Determining algorithm
dnnl::algorithm algorithmType;
if (_function == "Max") algorithmType = dnnl::algorithm::pooling_max;
if (_function == "Inclusive Average") algorithmType = dnnl::algorithm::pooling_avg_include_padding;
if (_function == "Exclusive Average") algorithmType = dnnl::algorithm::pooling_avg_exclude_padding;
auto backwardDataDesc = pooling_backward::desc(
algorithmType,
_srcMemDesc,
_dstMemDesc,
ST,
kernelDims,
PTL,
PBR);
// Create the primitive.
auto backwardDataPrimitiveDesc = pooling_backward::primitive_desc(backwardDataDesc, _nn->_dnnlEngine, _forwardPoolingPrimitiveDesc);
_backwardDataPrimitive = pooling_backward(backwardDataPrimitiveDesc);
}
#endif
}
void Pooling::forwardData(const size_t t)
{
#ifdef _KORALI_USE_ONEDNN
if (_nn->_engine == "OneDNN")
{
// Arguments to the inner product operation
std::unordered_map<int, dnnl::memory> forwardPoolingArgs;
forwardPoolingArgs[DNNL_ARG_SRC] = _prevLayer->_outputMem[t];
forwardPoolingArgs[DNNL_ARG_DST] = _outputMem[t];
forwardPoolingArgs[DNNL_ARG_WORKSPACE] = _workspaceMem[t];
_forwardPoolingPrimitive.execute(_nn->_dnnlStream, forwardPoolingArgs);
}
#endif
}
void Pooling::backwardData(const size_t t)
{
if (_nn->_mode == "Inference")
KORALI_LOG_ERROR("Requesting Layer backward data propagation but NN was configured for inference only.\n");
#ifdef _KORALI_USE_ONEDNN
if (_nn->_engine == "OneDNN")
{
_backwardDataArgs[DNNL_ARG_DIFF_DST] = _outputGradientMem[t]; // Input
_backwardDataArgs[DNNL_ARG_DIFF_SRC] = _prevLayer->_outputGradientMem[t]; // Output
_backwardDataArgs[DNNL_ARG_WORKSPACE] = _workspaceMem[t];
_backwardDataPrimitive.execute(_nn->_dnnlStream, _backwardDataArgs);
}
#endif
}
void Pooling::setConfiguration(knlohmann::json& js)
{
if (isDefined(js, "Results")) eraseValue(js, "Results");
if (isDefined(js, "Function"))
{
try { _function = js["Function"].get<std::string>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Function']\n%s", e.what()); }
{
bool validOption = false;
if (_function == "Max") validOption = true;
if (_function == "Inclusive Average") validOption = true;
if (_function == "Exclusive Average") validOption = true;
if (validOption == false) KORALI_LOG_ERROR(" + Unrecognized value (%s) provided for mandatory setting: ['Function'] required by pooling.\n", _function.c_str());
}
eraseValue(js, "Function");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Function'] required by pooling.\n");
if (isDefined(js, "Image Height"))
{
try { _imageHeight = js["Image Height"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Image Height']\n%s", e.what()); }
eraseValue(js, "Image Height");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Image Height'] required by pooling.\n");
if (isDefined(js, "Image Width"))
{
try { _imageWidth = js["Image Width"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Image Width']\n%s", e.what()); }
eraseValue(js, "Image Width");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Image Width'] required by pooling.\n");
if (isDefined(js, "Kernel Height"))
{
try { _kernelHeight = js["Kernel Height"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Kernel Height']\n%s", e.what()); }
eraseValue(js, "Kernel Height");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Kernel Height'] required by pooling.\n");
if (isDefined(js, "Kernel Width"))
{
try { _kernelWidth = js["Kernel Width"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Kernel Width']\n%s", e.what()); }
eraseValue(js, "Kernel Width");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Kernel Width'] required by pooling.\n");
if (isDefined(js, "Vertical Stride"))
{
try { _verticalStride = js["Vertical Stride"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Vertical Stride']\n%s", e.what()); }
eraseValue(js, "Vertical Stride");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Vertical Stride'] required by pooling.\n");
if (isDefined(js, "Horizontal Stride"))
{
try { _horizontalStride = js["Horizontal Stride"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Horizontal Stride']\n%s", e.what()); }
eraseValue(js, "Horizontal Stride");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Horizontal Stride'] required by pooling.\n");
if (isDefined(js, "Padding Left"))
{
try { _paddingLeft = js["Padding Left"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Padding Left']\n%s", e.what()); }
eraseValue(js, "Padding Left");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Padding Left'] required by pooling.\n");
if (isDefined(js, "Padding Right"))
{
try { _paddingRight = js["Padding Right"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Padding Right']\n%s", e.what()); }
eraseValue(js, "Padding Right");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Padding Right'] required by pooling.\n");
if (isDefined(js, "Padding Top"))
{
try { _paddingTop = js["Padding Top"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Padding Top']\n%s", e.what()); }
eraseValue(js, "Padding Top");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Padding Top'] required by pooling.\n");
if (isDefined(js, "Padding Bottom"))
{
try { _paddingBottom = js["Padding Bottom"].get<ssize_t>();
} catch (const std::exception& e)
{ KORALI_LOG_ERROR(" + Object: [ pooling ] \n + Key: ['Padding Bottom']\n%s", e.what()); }
eraseValue(js, "Padding Bottom");
}
else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Padding Bottom'] required by pooling.\n");
Layer::setConfiguration(js);
_type = "layer/pooling";
if(isDefined(js, "Type")) eraseValue(js, "Type");
if(isEmpty(js) == false) KORALI_LOG_ERROR(" + Unrecognized settings for Korali module: pooling: \n%s\n", js.dump(2).c_str());
}
void Pooling::getConfiguration(knlohmann::json& js)
{
js["Type"] = _type;
js["Function"] = _function;
js["Image Height"] = _imageHeight;
js["Image Width"] = _imageWidth;
js["Kernel Height"] = _kernelHeight;
js["Kernel Width"] = _kernelWidth;
js["Vertical Stride"] = _verticalStride;
js["Horizontal Stride"] = _horizontalStride;
js["Padding Left"] = _paddingLeft;
js["Padding Right"] = _paddingRight;
js["Padding Top"] = _paddingTop;
js["Padding Bottom"] = _paddingBottom;
Layer::getConfiguration(js);
}
void Pooling::applyModuleDefaults(knlohmann::json& js)
{
std::string defaultString = "{}";
knlohmann::json defaultJs = knlohmann::json::parse(defaultString);
mergeJson(js, defaultJs);
Layer::applyModuleDefaults(js);
}
void Pooling::applyVariableDefaults()
{
Layer::applyVariableDefaults();
}
;
} //layer
} //neuralNetwork
} //korali
;
| 38.253561 | 262 | 0.690996 | JonathanLehner |
9835c5d53fd7f510175f18b821ffe393275534bf | 14,398 | cpp | C++ | npy/NNodePoints.cpp | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 11 | 2020-07-05T02:39:32.000Z | 2022-03-20T18:52:44.000Z | npy/NNodePoints.cpp | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | null | null | null | npy/NNodePoints.cpp | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 4 | 2020-09-03T20:36:32.000Z | 2022-01-19T07:42:21.000Z | /*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ios>
#include <iostream>
#include <set>
#include <map>
#include <sstream>
#include "OpticksCSG.h"
#include "NGLMExt.hpp"
#include "GLMFormat.hpp"
#include "NNode.hpp"
#include "NBBox.hpp"
#include "Nuv.hpp"
#include "NSceneConfig.hpp"
#include "NNodePoints.hpp"
#include "PLOG.hh"
NNodePoints::NNodePoints(nnode* root, const NSceneConfig* config)
:
m_root(root),
m_config(config),
m_verbosity(config ? config->verbosity : root->verbosity),
m_epsilon(config ? config->get_parsurf_epsilon() : 1e-5),
m_level(config ? config->parsurf_level : 2 ),
m_margin(config ? config->parsurf_margin : 0 ),
m_target(config ? config->parsurf_target : 200)
{
init();
}
void NNodePoints::setEpsilon(float epsilon)
{
m_epsilon = epsilon ;
}
void NNodePoints::init()
{
m_root->collect_prim_for_edit(m_primitives); // recursive collection of list of all primitives in tree
}
std::string NNodePoints::desc() const
{
std::stringstream ss;
ss << "NNP"
<< " verbosity " << m_verbosity
<< " level " << m_level
<< " margin " << m_margin
<< " target " << m_target
<< " num_prim " << m_primitives.size()
<< " num_composite_points " << m_composite_points.size()
<< " epsilon " << std::scientific << m_epsilon << std::fixed
;
return ss.str();
}
nbbox NNodePoints::bbox_surface_points() const
{
unsigned num_cp = getNumCompositePoints() ;
if(num_cp==0)
{
LOG(debug) << "NNodePoints::bbox_surface_points NONE FOUND : probably need larger parsurf_level " << desc() ;
}
return nbbox::from_points(getCompositePoints(), m_verbosity);
}
const std::vector<glm::vec3>& NNodePoints::getCompositePoints() const
{
return m_composite_points ;
}
unsigned NNodePoints::getNumCompositePoints() const
{
return m_composite_points.size() ;
}
float NNodePoints::getEpsilon() const
{
return m_epsilon ;
}
glm::uvec4 NNodePoints::collect_surface_points()
{
if(m_verbosity > 2 )
{
LOG(info) << "NNodePoints::collect_surface_points"
<< " verbosity " << m_verbosity
;
}
if(m_config && m_verbosity > 2) m_config->dump("NNodePoints::collect_surface_points");
/*
level divisions (+1 for uv points)
1 +-----+------+ 0x1 << 1 = 2
2 +--+--+--+---+ 0x1 << 2 = 4
3 0x1 << 3 = 8
4 0x1 << 4 = 16
5 0x1 << 5 = 32
6 0x1 << 6 = 64
7 0x1 << 7 = 128
8 0x1 << 8 = 256
9 0x1 << 9 = 512
10 0x1 << 10 = 1024
* Divisions are then effectively squared to give uv samplings
* margin > 0 , skips both ends
The below uses adaptive uv-levels, upping level from the configured
initial level up to 8 times or until the target number of points is exceeded.
*/
unsigned pointmask = POINT_SURFACE ;
unsigned num_composite_points = 0 ;
int countdown = 8 ;
unsigned level = m_level ;
glm::uvec4 tots ;
if(m_verbosity > 2)
LOG(error) << "before while"
<< " num_composite_points " << num_composite_points
<< " target " << m_target
;
while( num_composite_points < m_target && countdown-- )
{
clear();
tots = collectCompositePoints( level, m_margin , pointmask);
if(m_verbosity > 2)
std::cout
<< " verbosity " << m_verbosity
<< " countdown " << countdown
<< " level " << level
<< " target " << m_target
<< " num_composite_points " << num_composite_points
<< " tots (inside/surface/outside/selected) " << gpresent(tots)
<< std::endl ;
level++ ;
num_composite_points = m_composite_points.size() ;
}
if(m_verbosity > 2)
LOG(error) << "after while"
<< " num_composite_points " << num_composite_points
;
return tots ;
}
void NNodePoints::clear()
{
m_composite_points.clear();
m_composite_coords.clear();
m_prim_bb.clear();
m_prim_bb_selected.clear();
}
glm::uvec4 NNodePoints::collectCompositePoints( unsigned level, int margin , unsigned pointmask )
{
glm::uvec4 tot(0,0,0,0);
unsigned num_prim = m_primitives.size();
for(unsigned prim_idx=0 ; prim_idx < num_prim ; prim_idx++)
{
nnode* prim = m_primitives[prim_idx] ;
if(m_verbosity > 4)
LOG(info) << "NNodePoints::collectCompositePoints"
<< " prim_idx " << prim_idx
<< " level " << level
<< " margin " << margin
;
prim->collectParPoints(prim_idx, level, margin, FRAME_GLOBAL , m_verbosity );
glm::uvec4 isos = selectBySDF(prim, prim_idx, pointmask );
tot += isos ;
if(m_verbosity > 4)
std::cout << "NNodePoints::getCompositePoints"
<< " prim " << std::setw(3) << prim_idx
<< " pointmask " << std::setw(20) << NNodeEnum::PointMask(pointmask)
<< " num_inside " << std::setw(6) << isos.x
<< " num_surface " << std::setw(6) << isos.y
<< " num_outside " << std::setw(6) << isos.z
<< " num_select " << std::setw(6) << isos.w
<< std::endl ;
;
}
return tot ;
}
glm::uvec4 NNodePoints::selectBySDF(const nnode* prim, unsigned prim_idx, unsigned pointmask )
{
// this is invoked from root level, so no need to pass down a verbosity
std::function<float(float,float,float)> _sdf = m_root->sdf() ;
typedef std::vector<glm::vec3> VV ;
typedef std::vector<nuv> VC ;
const VV& prim_points = prim->get_par_points();
const VC& prim_coords = prim->get_par_coords();
unsigned num_prim_points = prim_points.size() ;
unsigned num_prim_coords = prim_coords.size() ;
unsigned num_inside(0);
unsigned num_outside(0);
unsigned num_surface(0);
unsigned num_select(0);
if(m_verbosity > 5)
{
LOG(info) << "NNodePoints::selectBySDF"
<< " verbosity " << m_verbosity
<< " prim_points " << num_prim_points
<< " prim_coords " << num_prim_coords
;
}
assert( num_prim_points == num_prim_coords );
std::vector<glm::vec3> _points ;
std::vector<nuv> _coords ;
for(unsigned i=0 ; i < num_prim_points ; i++)
{
glm::vec3 p = prim_points[i] ;
nuv uv = prim_coords[i] ;
assert( uv.p() == prim_idx );
// If there is a gtransform on the node, the inverse gtransform->v is
// applied to the query point within the primitives operator()
// thusly query points are treated as being in the CSG root frame.
float sd = _sdf(p.x, p.y, p.z) ;
NNodePointType pt = NNodeEnum::PointClassify(sd, m_epsilon );
if( pt & pointmask )
{
num_select++ ;
_points.push_back(p);
_coords.push_back(uv);
}
switch(pt)
{
case POINT_INSIDE : num_inside++ ; break ;
case POINT_SURFACE : num_surface++ ; break ;
case POINT_OUTSIDE : num_outside++ ; break ;
}
if(m_verbosity > 5)
std::cout
<< " i " << std::setw(4) << i
<< " p " << gpresent(p)
<< " pt " << std::setw(15) << NNodeEnum::PointType(pt)
<< " sd(fx4) " << std::setw(10) << std::fixed << std::setprecision(4) << sd
<< " sd(sci) " << std::setw(10) << std::scientific << sd
<< " sd(def) " << std::setw(10) << std::fixed << sd
<< std::endl
;
}
std::copy( _points.begin(), _points.end(), std::back_inserter(m_composite_points) );
std::copy( _coords.begin(), _coords.end(), std::back_inserter(m_composite_coords) );
nbbox pbb = nbbox::from_points( prim_points, m_verbosity);
m_prim_bb.push_back(pbb);
nbbox sbb = nbbox::from_points( _points, m_verbosity);
m_prim_bb_selected.push_back(sbb);
return glm::uvec4(num_inside, num_surface, num_outside, num_select );
}
void NNodePoints::dump(const char* msg, unsigned dmax) const
{
unsigned num_composite_points = m_composite_points.size() ;
LOG(info) << msg
<< " num_composite_points " << num_composite_points
<< " dmax " << dmax
<< " desc " << desc()
;
nbbox bbsp = bbox_surface_points();
std::cout << " bbsp " << bbsp.desc() << std::endl ;
glm::vec3 lsp ;
for(unsigned i=0 ; i < std::min<unsigned>(num_composite_points,dmax) ; i++)
{
glm::vec3 sp = m_composite_points[i];
nuv uv = m_composite_coords[i];
if(sp != lsp)
std::cout
<< " i " << std::setw(4) << i
<< " sp " << gpresent( sp )
<< " uv " << uv.desc()
<< std::endl
;
lsp = sp ;
}
dump_bb();
dump_sheets();
}
nbbox NNodePoints::selectPointsBBox( unsigned prim, unsigned sheet ) const
{
std::vector<glm::vec3> points ;
std::vector<nuv> coords ;
selectPoints(points, coords, prim, sheet);
return nbbox::from_points(points, m_verbosity );
}
void NNodePoints::selectPoints(std::vector<glm::vec3>& points, std::vector<nuv>& coords, unsigned prim, unsigned sheet) const
{
unsigned num_composite_points = m_composite_points.size() ;
unsigned num_composite_coords = m_composite_coords.size() ;
assert( num_composite_points == num_composite_coords );
for(unsigned i=0 ; i < num_composite_coords ; i++)
{
glm::vec3 p = m_composite_points[i];
nuv uv = m_composite_coords[i];
if(uv.matches(prim,sheet))
{
points.push_back(p) ;
coords.push_back(uv) ;
}
}
}
void NNodePoints::dump_bb() const
{
unsigned num_prim_bb = m_prim_bb.size();
unsigned num_prim_bb_selected = m_prim_bb_selected.size();
LOG(info) << "NNodePoints::dump_bb"
<< " num_prim_bb " << num_prim_bb
<< " num_prim_bb_selected " << num_prim_bb_selected
;
assert( num_prim_bb == m_primitives.size() );
assert( num_prim_bb_selected == m_primitives.size() );
std::cout << " prim_bb " << std::endl ;
for(unsigned i=0 ; i < num_prim_bb ; i++)
{
std::cout << std::setw(4) << i
<< " " << m_prim_bb[i].desc()
<< std::endl
;
}
std::cout << " prim_bb_selected " << std::endl ;
for(unsigned i=0 ; i < num_prim_bb ; i++)
{
std::cout << std::setw(4) << i
<< " " << m_prim_bb_selected[i].desc()
<< std::endl
;
}
}
void NNodePoints::dump_sheets() const
{
unsigned num_composite_points = m_composite_points.size() ;
unsigned num_composite_coords = m_composite_coords.size() ;
LOG(info) << "NNodePoints::dump_sheets"
<< " num_composite_points " << num_composite_points
<< " num_composite_coords " << num_composite_coords
;
assert( num_composite_points == num_composite_coords );
typedef std::map<unsigned, unsigned> MUU ;
MUU ps ;
for(unsigned i=0 ; i < num_composite_coords ; i++)
{
nuv uv = m_composite_coords[i];
ps[uv.ps()]++ ; // prim idx and sheet encoded into unsigned
}
LOG(info) << "NNodePoints::dump_sheets"
<< " nps " << ps.size()
;
nbbox bbsp = bbox_surface_points();
std::cout << " bbsp " << bbsp.desc() << std::endl ;
unsigned dmax = 200 ;
unsigned num_pass = 1 ;
for(unsigned pass=0 ; pass < num_pass ; pass++)
{
for(MUU::const_iterator it=ps.begin() ; it != ps.end() ; it++)
{
unsigned ps_ = it->first ;
unsigned count = it->second ;
unsigned prim = nuv::ps_to_prim(ps_);
unsigned sheet = nuv::ps_to_sheet(ps_);
std::vector<glm::vec3> points ;
std::vector<nuv> coords ;
selectPoints(points, coords, prim, sheet);
nbbox ps_bbox = nbbox::from_points(points, m_verbosity );
std::cout
<< " prim_sheet " << std::setw(5) << ps_
<< " prim " << std::setw(5) << prim
<< " sheet " << std::setw(5) << sheet
<< " count " << std::setw(5) << count
<< " ps_bbox " << ps_bbox.desc()
<< std::endl ;
if(pass == 1)
{
for(unsigned i=0 ; i < std::min<unsigned>(points.size(), dmax) ; i++)
{
std::cout << " i " << std::setw(5) << i
<< " p " << gpresent(points[i])
<< " c " << coords[i].detail()
<< std::endl
;
}
}
}
}
}
| 28.969819 | 126 | 0.531602 | hanswenzel |
9835d0a1c3f347d9f92019864766c823c4093a4b | 3,221 | cpp | C++ | ESRenderEngine/app/src/main/cpp/MapExample/MapFlushVertexApp.cpp | Woohyun-Kim/ESRenderEngine | 431dbbbc6529a599441b497f9797eeb223052627 | [
"MIT"
] | 1 | 2018-06-06T18:07:20.000Z | 2018-06-06T18:07:20.000Z | ESRenderEngine/app/src/main/cpp/MapExample/MapFlushVertexApp.cpp | artrointel/ESRenderEngine | 431dbbbc6529a599441b497f9797eeb223052627 | [
"MIT"
] | null | null | null | ESRenderEngine/app/src/main/cpp/MapExample/MapFlushVertexApp.cpp | artrointel/ESRenderEngine | 431dbbbc6529a599441b497f9797eeb223052627 | [
"MIT"
] | null | null | null | //
// Created by we.kim on 2017-07-20.
//
#include "MapFlushVertexApp.h"
bool MapFlushVertexApp::init()
{
if(TriangleVBOApp::init())
{
// Generate an additional VBO for map example
glGenBuffers(1, &vboMapId);
glBindBuffer(GL_ARRAY_BUFFER, vboMapId);
glBufferData(GL_ARRAY_BUFFER, Triangle3D::ByteSize, NULL, GL_DYNAMIC_DRAW);
if(triangle.attrib)
{
// options : We will WRITE data to the mapped buffer and
// gpu driver can invalidate data of the buffer.
// It's okay because we haven't ever updated before this buffer by any valid data.
mappedBuf = (GLfloat *)glMapBufferRange(GL_ARRAY_BUFFER, 0, Triangle3D::ByteSize,
GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
if(mappedBuf == NULL)
{
ALOGE("MapFlushVertexApp::init glMapBuffer fail");
return false;
}
memcpy(mappedBuf, triangle.attrib->data, Triangle3D::ByteSize);
glUnmapBuffer(GL_ARRAY_BUFFER); // full-memory of 'mappedBuf' Flush operation from GPU side
mappedBuf = NULL;
}
glGenVertexArrays(1, &vaoMapId);
glBindVertexArray(vaoMapId);
{
glBindBuffer(GL_ARRAY_BUFFER, vboMapId);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
Triangle3D::ByteStride, 0);
glEnableVertexAttribArray(POS_ATTRIB);
ALOGD("Generated VAO ID is %d", vaoMapId);
}
ALOGD("MapFlushVertexApp Initialized");
return true;
}
else return false;
}
MapFlushVertexApp::~MapFlushVertexApp() {
glDeleteBuffers(1, &vboMapId);
vboMapId = NULL;
}
void MapFlushVertexApp::render()
{
// Draw previous triangle on left screen.
glBindVertexArray(0);
TriangleVBOApp::render();
glBindVertexArray(vaoMapId);
{
// This time we made a Map with FLUSH option so user can call
// explicit Flush operation on some discrete data for updating.
mappedBuf = (GLfloat *)glMapBufferRange(GL_ARRAY_BUFFER, 0, Triangle3D::ByteSize,
GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT);
if(mappedBuf == NULL)
{
ALOGE("MapVertexApp::init glMapBuffer fail");
return;
}
// we only update a 'x' position of vertex 0
triangle.mapAttrib(mappedBuf);
triangle.mappedAttrib->vertex[0].pos.x += 0.1f;
if(triangle.mappedAttrib->vertex[0].pos.x >= 1.f)
triangle.mappedAttrib->vertex[0].pos.x = 0.f;
glFlushMappedBufferRange(GL_ARRAY_BUFFER, 0, sizeof(triangle.mappedAttrib->vertex[0].pos.x)); // sizeof Float
glUnmapBuffer(GL_ARRAY_BUFFER); // Flush only x data.
// data of the others will not be updated even if the data has really updated like this.
// because we didn't flushed.
// triangle.mappedAttrib->vertex[1].pos.x = -1.f;
glDrawArrays(GL_TRIANGLES, 0, 3);
}
checkGLError("MapFlushVertexApp::render");
}
| 37.022989 | 118 | 0.595157 | Woohyun-Kim |
983604f7fce37559c7a955132739d5389a33e810 | 14,811 | hpp | C++ | include/mgard-x/DataRefactoring/MultiDimension/Correction/LevelwiseProcessingKernel.hpp | JasonRuonanWang/MGARD | 70d3399f6169c8a369da9fe9786c45cb6f3bb9f1 | [
"Apache-2.0"
] | null | null | null | include/mgard-x/DataRefactoring/MultiDimension/Correction/LevelwiseProcessingKernel.hpp | JasonRuonanWang/MGARD | 70d3399f6169c8a369da9fe9786c45cb6f3bb9f1 | [
"Apache-2.0"
] | null | null | null | include/mgard-x/DataRefactoring/MultiDimension/Correction/LevelwiseProcessingKernel.hpp | JasonRuonanWang/MGARD | 70d3399f6169c8a369da9fe9786c45cb6f3bb9f1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021, Oak Ridge National Laboratory.
* MGARD-X: MultiGrid Adaptive Reduction of Data Portable across GPUs and CPUs
* Author: Jieyang Chen (chenj3@ornl.gov)
* Date: December 1, 2021
*/
#ifndef MGARD_X_LEVELWISE_PROCESSING_KERNEL_TEMPLATE
#define MGARD_X_LEVELWISE_PROCESSING_KERNEL_TEMPLATE
#include "../../../RuntimeX/RuntimeX.h"
namespace mgard_x {
template <DIM D, typename T, SIZE R, SIZE C, SIZE F, OPTION OP,
typename DeviceType>
class LwpkReoFunctor : public Functor<DeviceType> {
public:
MGARDX_CONT LwpkReoFunctor() {}
MGARDX_CONT LwpkReoFunctor(SubArray<1, SIZE, DeviceType> shape,
SubArray<D, T, DeviceType> v,
SubArray<D, T, DeviceType> work)
: shape(shape), v(v), work(work) {
Functor<DeviceType>();
}
MGARDX_EXEC void Operation1() {
threadId = (FunctorBase<DeviceType>::GetThreadIdZ() *
(FunctorBase<DeviceType>::GetBlockDimX() *
FunctorBase<DeviceType>::GetBlockDimY())) +
(FunctorBase<DeviceType>::GetThreadIdY() *
FunctorBase<DeviceType>::GetBlockDimX()) +
FunctorBase<DeviceType>::GetThreadIdX();
SIZE *sm = (SIZE *)FunctorBase<DeviceType>::GetSharedMemory();
shape_sm = sm;
if (threadId < D) {
shape_sm[threadId] = *shape(threadId);
}
}
MGARDX_EXEC void Operation2() {
SIZE idx[D];
SIZE firstD = div_roundup(shape_sm[0], F);
SIZE bidx = FunctorBase<DeviceType>::GetBlockIdX();
idx[0] = (bidx % firstD) * F + FunctorBase<DeviceType>::GetThreadIdX();
// printf("firstD %d idx[0] %d\n", firstD, idx[0]);
bidx /= firstD;
if (D >= 2)
idx[1] = FunctorBase<DeviceType>::GetBlockIdY() *
FunctorBase<DeviceType>::GetBlockDimY() +
FunctorBase<DeviceType>::GetThreadIdY();
if (D >= 3)
idx[2] = FunctorBase<DeviceType>::GetBlockIdZ() *
FunctorBase<DeviceType>::GetBlockDimZ() +
FunctorBase<DeviceType>::GetThreadIdZ();
for (DIM d = 3; d < D; d++) {
idx[d] = bidx % shape_sm[d];
bidx /= shape_sm[d];
}
// int z = blockIdx.z * blockDim.z + threadIdx.z;
// int y = blockIdx.y * blockDim.y + threadIdx.y;
// int x = blockIdx.z * blockDim.z + threadIdx.z;
bool in_range = true;
for (DIM d = 0; d < D; d++) {
if (idx[d] >= shape_sm[d])
in_range = false;
}
if (in_range) {
// printf("%d %d %d %d\n", idx[3], idx[2], idx[1], idx[0]);
if (OP == COPY)
*work(idx) = *v(idx);
if (OP == ADD)
*work(idx) += *v(idx);
if (OP == SUBTRACT)
*work(idx) -= *v(idx);
}
}
MGARDX_EXEC void Operation3() {}
MGARDX_EXEC void Operation4() {}
MGARDX_EXEC void Operation5() {}
MGARDX_CONT size_t shared_memory_size() {
size_t size = 0;
size = D * sizeof(SIZE);
return size;
}
private:
SubArray<1, SIZE, DeviceType> shape;
SubArray<D, T, DeviceType> v, work;
IDX threadId;
SIZE *shape_sm;
};
template <DIM D, typename T, OPTION OP, typename DeviceType>
class LwpkReo : public AutoTuner<DeviceType> {
public:
MGARDX_CONT
LwpkReo() : AutoTuner<DeviceType>() {}
template <SIZE R, SIZE C, SIZE F>
MGARDX_CONT Task<LwpkReoFunctor<D, T, R, C, F, OP, DeviceType>>
GenTask(SubArray<1, SIZE, DeviceType> shape, SubArray<D, T, DeviceType> v,
SubArray<D, T, DeviceType> work, int queue_idx) {
using FunctorType = LwpkReoFunctor<D, T, R, C, F, OP, DeviceType>;
FunctorType functor(shape, v, work);
SIZE total_thread_z = 1;
SIZE total_thread_y = 1;
SIZE total_thread_x = 1;
if (D >= 3)
total_thread_z = shape.dataHost()[2];
if (D >= 2)
total_thread_y = shape.dataHost()[1];
total_thread_x = shape.dataHost()[0];
SIZE tbx, tby, tbz, gridx, gridy, gridz;
size_t sm_size = functor.shared_memory_size();
tbz = R;
tby = C;
tbx = F;
gridz = ceil((float)total_thread_z / tbz);
gridy = ceil((float)total_thread_y / tby);
gridx = ceil((float)total_thread_x / tbx);
for (DIM d = 3; d < D; d++) {
gridx *= shape.dataHost()[d];
}
// printf("%u %u %u\n", shape.dataHost()[2], shape.dataHost()[1],
// shape.dataHost()[0]); PrintSubarray("shape", shape);
return Task(functor, gridz, gridy, gridx, tbz, tby, tbx, sm_size, queue_idx,
"LwpkReo");
}
MGARDX_CONT
void Execute(SubArray<1, SIZE, DeviceType> shape,
SubArray<D, T, DeviceType> v, SubArray<D, T, DeviceType> work,
int queue_idx) {
int range_l = std::min(6, (int)std::log2(shape.dataHost()[0]) - 1);
int arch = DeviceRuntime<DeviceType>::GetArchitectureGeneration();
int prec = TypeToIdx<T>();
double min_time = std::numeric_limits<double>::max();
int min_config = 0;
// int config = 0;
int config = AutoTuner<DeviceType>::autoTuningTable.lwpk[prec][range_l];
#define LWPK(CONFIG) \
if (config == CONFIG || AutoTuner<DeviceType>::ProfileKernels) { \
const int R = LWPK_CONFIG[D - 1][CONFIG][0]; \
const int C = LWPK_CONFIG[D - 1][CONFIG][1]; \
const int F = LWPK_CONFIG[D - 1][CONFIG][2]; \
using FunctorType = LwpkReoFunctor<D, T, R, C, F, OP, DeviceType>; \
using TaskType = Task<FunctorType>; \
TaskType task = GenTask<R, C, F>(shape, v, work, queue_idx); \
DeviceAdapter<TaskType, DeviceType> adapter; \
ExecutionReturn ret = adapter.Execute(task); \
if (AutoTuner<DeviceType>::ProfileKernels) { \
if (min_time > ret.execution_time) { \
min_time = ret.execution_time; \
min_config = CONFIG; \
} \
} \
}
LWPK(0)
LWPK(1)
LWPK(2)
LWPK(3)
LWPK(4)
LWPK(5)
LWPK(6)
#undef LWPK
if (AutoTuner<DeviceType>::ProfileKernels) {
FillAutoTunerTable<DeviceType>("lwpk", prec, range_l, min_config);
}
}
};
// template <DIM D, typename T, SIZE R, SIZE C, SIZE F, int OP>
// __global__ void _lwpk(SIZE *shape, T *dv, SIZE *ldvs, T *dwork, SIZE *ldws) {
// size_t threadId = (threadIdx.z * (blockDim.x * blockDim.y)) +
// (threadIdx.y * blockDim.x) + threadIdx.x;
// SIZE *sm = SharedMemory<SIZE>();
// SIZE *shape_sm = sm;
// SIZE *ldvs_sm = shape_sm + D;
// SIZE *ldws_sm = ldvs_sm + D;
// if (threadId < D) {
// shape_sm[threadId] = shape[threadId];
// ldvs_sm[threadId] = ldvs[threadId];
// ldws_sm[threadId] = ldws[threadId];
// }
// __syncthreads();
// SIZE idx[D];
// SIZE firstD = div_roundup(shape_sm[0], F);
// SIZE bidx = FunctorBase<DeviceType>::GetBlockIdX();
// idx[0] = (bidx % firstD) * F + threadIdx.x;
// // printf("firstD %d idx[0] %d\n", firstD, idx[0]);
// bidx /= firstD;
// if (D >= 2)
// idx[1] = blockIdx.y * blockDim.y + threadIdx.y;
// if (D >= 3)
// idx[2] = blockIdx.z * blockDim.z + threadIdx.z;
// for (DIM d = 3; d < D; d++) {
// idx[d] = bidx % shape_sm[d];
// bidx /= shape_sm[d];
// }
// // int z = blockIdx.z * blockDim.z + threadIdx.z;
// // int y = blockIdx.y * blockDim.y + threadIdx.y;
// // int x = blockIdx.z * blockDim.z + threadIdx.z;
// bool in_range = true;
// for (DIM d = 0; d < D; d++) {
// if (idx[d] >= shape_sm[d])
// in_range = false;
// }
// if (in_range) {
// // printf("%d %d %d %d\n", idx[3], idx[2], idx[1], idx[0]);
// if (OP == COPY)
// dwork[get_idx<D>(ldws, idx)] = dv[get_idx<D>(ldvs, idx)];
// if (OP == ADD)
// dwork[get_idx<D>(ldws, idx)] += dv[get_idx<D>(ldvs, idx)];
// if (OP == SUBTRACT)
// dwork[get_idx<D>(ldws, idx)] -= dv[get_idx<D>(ldvs, idx)];
// }
// }
// template <DIM D, typename T, SIZE R, SIZE C, SIZE F, int OP>
// void lwpk_adaptive_launcher(Handle<D, T> &handle, SIZE *shape_h, SIZE
// *shape_d,
// T *dv, SIZE *ldvs, T *dwork, SIZE *ldws,
// int queue_idx) {
// SIZE total_thread_z = shape_h[2];
// SIZE total_thread_y = shape_h[1];
// SIZE total_thread_x = shape_h[0];
// // linearize other dimensions
// SIZE tbz = R;
// SIZE tby = C;
// SIZE tbx = F;
// SIZE gridz = ceil((float)total_thread_z / tbz);
// SIZE gridy = ceil((float)total_thread_y / tby);
// SIZE gridx = ceil((float)total_thread_x / tbx);
// for (DIM d = 3; d < D; d++) {
// gridx *= shape_h[d];
// }
// // printf("exec: %d %d %d %d %d %d\n", tbx, tby, tbz, gridx, gridy, gridz);
// dim3 threadsPerBlock(tbx, tby, tbz);
// dim3 blockPerGrid(gridx, gridy, gridz);
// size_t sm_size = (D * 3) * sizeof(SIZE);
// _lwpk<D, T, R, C, F, OP><<<blockPerGrid, threadsPerBlock, sm_size,
// *(cudaStream_t *)handle.get(queue_idx)>>>(
// shape_d, dv, ldvs, dwork, ldws);
// gpuErrchk(cudaGetLastError());
// if (handle.sync_and_check_all_kernels) {
// gpuErrchk(cudaDeviceSynchronize());
// }
// }
// template <DIM D, typename T, int OP>
// void lwpk(Handle<D, T> &handle, SIZE *shape_h, SIZE *shape_d, T *dv, SIZE
// *ldvs,
// T *dwork, SIZE *ldws, int queue_idx) {
// #define COPYLEVEL(R, C, F) \
// { \
// lwpk_adaptive_launcher<D, T, R, C, F, OP>(handle, shape_h, shape_d, dv, \
// ldvs, dwork, ldws, queue_idx);
// \
// }
// if (D >= 3) {
// COPYLEVEL(4, 4, 4)
// }
// if (D == 2) {
// COPYLEVEL(1, 4, 4)
// }
// if (D == 1) {
// COPYLEVEL(1, 1, 8)
// }
// #undef COPYLEVEL
// }
template <mgard_x::DIM D, typename T, int R, int C, int F, OPTION OP,
typename DeviceType>
class LevelwiseCalcNDFunctor : public Functor<DeviceType> {
public:
MGARDX_CONT
LevelwiseCalcNDFunctor(SIZE *shape, SubArray<D, T, DeviceType> v,
SubArray<D, T, DeviceType> w)
: shape(shape), v(v), w(w) {
Functor<DeviceType>();
}
MGARDX_EXEC void Operation1() {
threadId = (FunctorBase<DeviceType>::GetThreadIdZ() *
(FunctorBase<DeviceType>::GetBlockDimX() *
FunctorBase<DeviceType>::GetBlockDimY())) +
(FunctorBase<DeviceType>::GetThreadIdY() *
FunctorBase<DeviceType>::GetBlockDimX()) +
FunctorBase<DeviceType>::GetThreadIdX();
int8_t *sm_p = (int8_t *)FunctorBase<DeviceType>::GetSharedMemory();
shape_sm = (SIZE *)sm_p;
sm_p += D * sizeof(SIZE);
if (threadId < D) {
shape_sm[threadId] = shape[threadId];
}
}
MGARDX_EXEC void Operation2() {
SIZE firstD = div_roundup(shape_sm[0], F);
SIZE bidx = FunctorBase<DeviceType>::GetBlockIdX();
idx[0] = (bidx % firstD) * F + FunctorBase<DeviceType>::GetThreadIdX();
// printf("firstD %d idx[0] %d\n", firstD, idx[0]);
bidx /= firstD;
if (D >= 2)
idx[1] = FunctorBase<DeviceType>::GetBlockIdY() *
FunctorBase<DeviceType>::GetBlockDimY() +
FunctorBase<DeviceType>::GetThreadIdY();
if (D >= 3)
idx[2] = FunctorBase<DeviceType>::GetBlockIdZ() *
FunctorBase<DeviceType>::GetBlockDimZ() +
FunctorBase<DeviceType>::GetThreadIdZ();
for (DIM d = 3; d < D; d++) {
idx[d] = bidx % shape_sm[d];
bidx /= shape_sm[d];
}
bool in_range = true;
for (DIM d = 0; d < D; d++) {
if (idx[d] >= shape_sm[d])
in_range = false;
}
if (in_range) {
// printf("%d %d %d %d\n", idx[3], idx[2], idx[1], idx[0]);
if (OP == COPY)
*w(idx) = *v(idx);
if (OP == ADD)
*w(idx) += *v(idx);
if (OP == SUBTRACT)
*w(idx) -= *v(idx);
}
}
MGARDX_EXEC void Operation3() {}
MGARDX_EXEC void Operation4() {}
MGARDX_EXEC void Operation5() {}
MGARDX_CONT size_t shared_memory_size() {
size_t size = 0;
size += D * sizeof(SIZE);
return size;
}
private:
SIZE *shape;
SubArray<D, T, DeviceType> v;
SubArray<D, T, DeviceType> w;
SIZE *shape_sm;
size_t threadId;
SIZE idx[D];
};
template <DIM D, typename T, OPTION Direction, typename DeviceType>
class LevelwiseCalcNDKernel : public AutoTuner<DeviceType> {
public:
MGARDX_CONT
LevelwiseCalcNDKernel() : AutoTuner<DeviceType>() {}
template <SIZE R, SIZE C, SIZE F>
MGARDX_CONT Task<LevelwiseCalcNDFunctor<D, T, R, C, F, Direction, DeviceType>>
GenTask(SIZE *shape_h, SIZE *shape_d, SubArray<D, T, DeviceType> v,
SubArray<D, T, DeviceType> w, int queue_idx) {
using FunctorType =
LevelwiseCalcNDFunctor<D, T, R, C, F, Direction, DeviceType>;
FunctorType functor(shape_d, v, w);
SIZE tbx, tby, tbz, gridx, gridy, gridz;
size_t sm_size = functor.shared_memory_size();
int total_thread_z = shape_h[2];
int total_thread_y = shape_h[1];
int total_thread_x = shape_h[0];
// linearize other dimensions
tbz = R;
tby = C;
tbx = F;
gridz = ceil((float)total_thread_z / tbz);
gridy = ceil((float)total_thread_y / tby);
gridx = ceil((float)total_thread_x / tbx);
for (int d = 3; d < D; d++) {
gridx *= shape_h[d];
}
return Task(functor, gridz, gridy, gridx, tbz, tby, tbx, sm_size,
queue_idx);
}
MGARDX_CONT
void Execute(SIZE *shape_h, SIZE *shape_d, SubArray<D, T, DeviceType> v,
SubArray<D, T, DeviceType> w, int queue_idx) {
#define KERNEL(R, C, F) \
{ \
using FunctorType = \
LevelwiseCalcNDFunctor<D, T, R, C, F, Direction, DeviceType>; \
using TaskType = Task<FunctorType>; \
TaskType task = GenTask<R, C, F>(shape_h, shape_d, v, w, queue_idx); \
DeviceAdapter<TaskType, DeviceType> adapter; \
adapter.Execute(task); \
}
if (D >= 3) {
KERNEL(4, 4, 16)
}
if (D == 2) {
KERNEL(1, 4, 32)
}
if (D == 1) {
KERNEL(1, 1, 64)
}
#undef KERNEL
}
};
} // namespace mgard_x
#endif | 32.623348 | 80 | 0.542165 | JasonRuonanWang |
983699e020a21e265b2bcd2ad02bc142c4d4d3c5 | 47,835 | cpp | C++ | src/components/application_manager/src/resume_ctrl.cpp | jacobkeeler/sdl_core | ad68c5d08986bb134651d06d22b4860c610b1f0f | [
"BSD-3-Clause"
] | null | null | null | src/components/application_manager/src/resume_ctrl.cpp | jacobkeeler/sdl_core | ad68c5d08986bb134651d06d22b4860c610b1f0f | [
"BSD-3-Clause"
] | null | null | null | src/components/application_manager/src/resume_ctrl.cpp | jacobkeeler/sdl_core | ad68c5d08986bb134651d06d22b4860c610b1f0f | [
"BSD-3-Clause"
] | 1 | 2017-02-15T07:49:12.000Z | 2017-02-15T07:49:12.000Z | /*
Copyright (c) 2015, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/resume_ctrl.h"
#include <fstream>
#include <algorithm>
#include "config_profile/profile.h"
#include "utils/file_system.h"
#include "connection_handler/connection_handler_impl.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application.h"
#include "application_manager/message_helper.h"
#include "smart_objects/smart_object.h"
#include "connection_handler/connection.h"
#include "formatters/CFormatterJsonBase.hpp"
#include "application_manager/commands/command_impl.h"
#include "resumption/last_state.h"
#include "policy/policy_manager_impl.h"
#include "application_manager/policies/policy_handler.h"
#include "application_manager/state_controller.h"
namespace application_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "ResumeCtrl")
namespace Formatters = NsSmartDeviceLink::NsJSONHandler::Formatters;
ResumeCtrl::ResumeCtrl(ApplicationManagerImpl* app_mngr)
: resumtion_lock_(true),
app_mngr_(app_mngr),
save_persistent_data_timer_("RsmCtrlPercist",
this, &ResumeCtrl::SaveDataOnTimer, true),
restore_hmi_level_timer_("RsmCtrlRstore",
this, &ResumeCtrl::ApplicationResumptiOnTimer),
is_resumption_active_(false),
is_data_saved(true),
launch_time_(time(NULL)) {
LoadResumeData();
save_persistent_data_timer_.start(profile::Profile::instance()->app_resumption_save_persistent_data_timeout());
}
void ResumeCtrl::SaveAllApplications() {
LOG4CXX_AUTO_TRACE(logger_);
std::set<ApplicationSharedPtr> apps(retrieve_application());
std::for_each(apps.begin(),
apps.end(),
std::bind1st(std::mem_fun(&ResumeCtrl::SaveApplication), this));
// remove old
}
void ResumeCtrl::SaveApplication(ApplicationConstSharedPtr application) {
DCHECK(application.get());
if (!application) {
LOG4CXX_FATAL(logger_, "Application object is NULL.");
return;
}
const std::string& m_app_id = application->mobile_app_id();
LOG4CXX_TRACE(logger_, "ENTER app_id : " << application->app_id()
<< " mobile app_id : " << m_app_id);
const std::string hash = application->curHash(); // let's make a copy not to depend on application
const uint32_t grammar_id = application->get_grammar_id();
const uint32_t time_stamp = (uint32_t)time(NULL);
const mobile_apis::HMILevel::eType hmi_level = application->hmi_level();
resumtion_lock_.Acquire();
Json::Value& json_app = GetFromSavedOrAppend(m_app_id);
json_app[strings::device_mac] =
MessageHelper::GetDeviceMacAddressForHandle(application->device());
json_app[strings::app_id] = m_app_id;
json_app[strings::grammar_id] = grammar_id;
json_app[strings::connection_key] = application->app_id();
json_app[strings::hmi_app_id] = application->hmi_app_id();
json_app[strings::is_media_application] = application->IsAudioApplication();
json_app[strings::hmi_level] = static_cast<int32_t> (hmi_level);
json_app[strings::ign_off_count] = 0;
json_app[strings::suspend_count] = 0;
json_app[strings::hash_id] = hash;
json_app[strings::application_commands] =
GetApplicationCommands(application);
json_app[strings::application_submenus] =
GetApplicationSubMenus(application);
json_app[strings::application_choise_sets] =
GetApplicationInteractionChoiseSets(application);
json_app[strings::application_global_properties] =
GetApplicationGlobalProperties(application);
json_app[strings::application_subscribtions] =
GetApplicationSubscriptions(application);
json_app[strings::application_files] = GetApplicationFiles(application);
json_app[strings::time_stamp] = time_stamp;
LOG4CXX_DEBUG(logger_, "SaveApplication : " << json_app.toStyledString());
resumtion_lock_.Release();
}
void ResumeCtrl::on_event(const event_engine::Event& event) {
LOG4CXX_TRACE(logger_, "Response from HMI command");
}
bool ResumeCtrl::RestoreAppHMIState(ApplicationSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace mobile_apis;
if (!application) {
LOG4CXX_ERROR(logger_, " RestoreApplicationHMILevel() application pointer in invalid");
return false;
}
LOG4CXX_DEBUG(logger_, "ENTER app_id : " << application->app_id());
sync_primitives::AutoLock lock(resumtion_lock_);
const int idx = GetObjectIndex(application->mobile_app_id());
if (-1 != idx) {
const Json::Value& json_app = GetSavedApplications()[idx];
if (json_app.isMember(strings::hmi_level)) {
const HMILevel::eType saved_hmi_level =
static_cast<mobile_apis::HMILevel::eType>(
json_app[strings::hmi_level].asInt());
LOG4CXX_DEBUG(logger_, "Saved HMI Level is : " << saved_hmi_level);
return SetAppHMIState(application, saved_hmi_level);
} else {
LOG4CXX_FATAL(logger_, "There are some unknown keys among the stored apps");
}
}
LOG4CXX_INFO(logger_, "Failed to restore application HMILevel");
return false;
}
bool ResumeCtrl::SetupDefaultHMILevel(ApplicationSharedPtr application) {
DCHECK_OR_RETURN(application, false);
LOG4CXX_AUTO_TRACE(logger_);
mobile_apis::HMILevel::eType default_hmi =
ApplicationManagerImpl::instance()-> GetDefaultHmiLevel(application);
bool result = SetAppHMIState(application, default_hmi, false);
return result;
}
bool ResumeCtrl::SetAppHMIState(ApplicationSharedPtr application,
const mobile_apis::HMILevel::eType hmi_level,
bool check_policy) {
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
if (false == application.valid()) {
LOG4CXX_ERROR(logger_, "Application pointer in invalid");
return false;
}
LOG4CXX_TRACE(logger_, " app_id : ( " << application->app_id()
<< ", hmi_level : " << hmi_level
<< ", check_policy : " << check_policy << " )");
const std::string device_id =
MessageHelper::GetDeviceMacAddressForHandle(application->device());
if (check_policy &&
policy::PolicyHandler::instance()->GetUserConsentForDevice(device_id)
!= policy::DeviceConsent::kDeviceAllowed) {
LOG4CXX_ERROR(logger_, "Resumption abort. Data consent wasn't allowed");
SetupDefaultHMILevel(application);
return false;
}
HMILevel::eType restored_hmi_level = hmi_level;
if ((hmi_level == application->hmi_level()) &&
(hmi_level != mobile_apis::HMILevel::HMI_NONE)) {
LOG4CXX_DEBUG(logger_, "Hmi level " << hmi_level << " should not be set to "
<< application->mobile_app_id()
<<" current hmi_level is " << application->hmi_level());
return false;
}
if (HMILevel::HMI_FULL == hmi_level) {
restored_hmi_level = app_mngr_->IsHmiLevelFullAllowed(application);
} else if (HMILevel::HMI_LIMITED == hmi_level) {
bool allowed_limited = application->is_media_application();
ApplicationManagerImpl::ApplicationListAccessor accessor;
ApplicationManagerImpl::ApplictionSetConstIt it = accessor.begin();
for (; accessor.end() != it && allowed_limited; ++it) {
const ApplicationSharedPtr curr_app = *it;
if (curr_app->is_media_application()) {
if (curr_app->hmi_level() == HMILevel::HMI_FULL ||
curr_app->hmi_level() == HMILevel::HMI_LIMITED) {
allowed_limited = false;
}
}
}
if (allowed_limited) {
restored_hmi_level = HMILevel::HMI_LIMITED;
} else {
restored_hmi_level =
ApplicationManagerImpl::instance()->GetDefaultHmiLevel(application);
}
}
if (HMILevel::HMI_LIMITED == restored_hmi_level) {
MessageHelper::SendOnResumeAudioSourceToHMI(application->app_id());
}
const AudioStreamingState::eType restored_audio_state =
application->is_media_application() &&
(HMILevel::HMI_FULL == restored_hmi_level ||
HMILevel::HMI_LIMITED == restored_hmi_level)
? AudioStreamingState::AUDIBLE : AudioStreamingState::NOT_AUDIBLE;
if (restored_hmi_level == HMILevel::HMI_FULL) {
ApplicationManagerImpl::instance()->SetState<true>(application->app_id(),
restored_hmi_level,
restored_audio_state);
} else {
ApplicationManagerImpl::instance()->SetState<false>(application->app_id(),
restored_hmi_level,
restored_audio_state);
}
LOG4CXX_INFO(logger_, "Set up application "
<< application->mobile_app_id()
<< " to HMILevel " << hmi_level);
return true;
}
bool ResumeCtrl::RestoreApplicationData(ApplicationSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
if (!application.valid()) {
LOG4CXX_ERROR(logger_, "Application pointer in invalid");
return false;
}
LOG4CXX_DEBUG(logger_, "ENTER app_id : " << application->app_id());
sync_primitives::AutoLock lock(resumtion_lock_);
const int idx = GetObjectIndex(application->mobile_app_id());
if (-1 == idx) {
LOG4CXX_WARN(logger_, "Application not saved");
return false;
}
const Json::Value& saved_app = GetSavedApplications()[idx];
if(saved_app.isMember(strings::grammar_id)) {
const uint32_t app_grammar_id = saved_app[strings::grammar_id].asUInt();
application->set_grammar_id(app_grammar_id);
AddFiles(application, saved_app);
AddSubmenues(application, saved_app);
AddCommands(application, saved_app);
AddChoicesets(application, saved_app);
SetGlobalProperties(application, saved_app);
AddSubscriptions(application, saved_app);
}
return true;
}
bool ResumeCtrl::IsHMIApplicationIdExist(uint32_t hmi_app_id) {
LOG4CXX_TRACE(logger_, "ENTER hmi_app_id :" << hmi_app_id);
sync_primitives::AutoLock lock(resumtion_lock_);
for (Json::Value::iterator it = GetSavedApplications().begin();
it != GetSavedApplications().end(); ++it) {
if ((*it).isMember(strings::hmi_app_id)) {
if ((*it)[strings::hmi_app_id].asUInt() == hmi_app_id) {
return true;
}
}
}
ApplicationManagerImpl::ApplicationListAccessor accessor;
ApplicationManagerImpl::ApplictionSet apps(accessor.applications());
ApplicationManagerImpl::ApplictionSetIt it = apps.begin();
ApplicationManagerImpl::ApplictionSetIt it_end = apps.end();
for (;it != it_end; ++it) {
if (hmi_app_id == (*it)->hmi_app_id()) {
LOG4CXX_TRACE(logger_, "EXIT result = true");
return true;
}
}
LOG4CXX_TRACE(logger_, "EXIT result = false");
return false;
}
bool ResumeCtrl::IsApplicationSaved(const std::string& mobile_app_id) {
LOG4CXX_TRACE(logger_, "ENTER mobile_app_id :" << mobile_app_id);
sync_primitives::AutoLock lock(resumtion_lock_);
int index = GetObjectIndex(mobile_app_id);
if (-1 == index) {
return false;
}
if (!IsResumptionDataValid(index)) {
LOG4CXX_INFO(logger_, "Resumption data for app " << mobile_app_id <<
" is corrupted. Remove application from resumption list");
RemoveApplicationFromSaved(mobile_app_id);
return false;
}
return true;
}
uint32_t ResumeCtrl::GetHMIApplicationID(const std::string& mobile_app_id) {
LOG4CXX_AUTO_TRACE(logger_);
uint32_t hmi_app_id = 0;
sync_primitives::AutoLock lock(resumtion_lock_);
const int idx = GetObjectIndex(mobile_app_id);
if (-1 == idx) {
LOG4CXX_WARN(logger_, "Application not saved");
return hmi_app_id;
}
const Json::Value& json_app = GetSavedApplications()[idx];
if (json_app.isMember(strings::app_id)) {
hmi_app_id = json_app[strings::hmi_app_id].asUInt();
}
LOG4CXX_DEBUG(logger_, "hmi_app_id :" << hmi_app_id);
return hmi_app_id;
}
bool ResumeCtrl::RemoveApplicationFromSaved(const std::string& mobile_app_id) {
LOG4CXX_TRACE(logger_, "Remove mobile_app_id " << mobile_app_id);
sync_primitives::AutoLock lock(resumtion_lock_);
bool result = false;
std::vector<Json::Value> temp;
for (Json::Value::iterator it = GetSavedApplications().begin();
it != GetSavedApplications().end(); ++it) {
if ((*it).isMember(strings::app_id)) {
const std::string& saved_m_app_id = (*it)[strings::app_id].asString();
if (saved_m_app_id != mobile_app_id) {
temp.push_back((*it));
} else {
result = true;
}
}
}
if (false == result) {
LOG4CXX_TRACE(logger_, "EXIT result: " << (result ? "true" : "false"));
return result;
}
GetSavedApplications().clear();
for (std::vector<Json::Value>::iterator it = temp.begin();
it != temp.end(); ++it) {
GetSavedApplications().append((*it));
}
LOG4CXX_TRACE(logger_, "EXIT result: " << (result ? "true" : "false"));
return result;
}
void ResumeCtrl::Suspend() {
LOG4CXX_AUTO_TRACE(logger_);
StopRestoreHmiLevelTimer();
StopSavePersistentDataTimer();
SaveAllApplications();
Json::Value to_save;
sync_primitives::AutoLock lock(resumtion_lock_);
for (Json::Value::iterator it = GetSavedApplications().begin();
it != GetSavedApplications().end(); ++it) {
if ((*it).isMember(strings::suspend_count)) {
const uint32_t suspend_count = (*it)[strings::suspend_count].asUInt();
(*it)[strings::suspend_count] = suspend_count + 1;
} else {
LOG4CXX_WARN(logger_, "Unknown key among saved applications");
(*it)[strings::suspend_count] = 1;
}
if ((*it).isMember(strings::ign_off_count)) {
const uint32_t ign_off_count = (*it)[strings::ign_off_count].asUInt();
if (ign_off_count < kApplicationLifes) {
(*it)[strings::ign_off_count] = ign_off_count + 1;
to_save.append(*it);
}
} else {
LOG4CXX_WARN(logger_, "Unknown key among saved applications");
(*it)[strings::ign_off_count] = 1;
}
}
SetSavedApplication(to_save);
SetLastIgnOffTime(time(NULL));
LOG4CXX_DEBUG(logger_,
GetResumptionData().toStyledString());
resumption::LastState::instance()->SaveToFileSystem();
}
void ResumeCtrl::OnAwake() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(resumtion_lock_);
for (Json::Value::iterator it = GetSavedApplications().begin();
it != GetSavedApplications().end(); ++it) {
if ((*it).isMember(strings::ign_off_count)) {
const uint32_t ign_off_count = (*it)[strings::ign_off_count].asUInt();
(*it)[strings::ign_off_count] = ign_off_count - 1;
} else {
LOG4CXX_WARN(logger_, "Unknown key among saved applications");
(*it)[strings::ign_off_count] = 0;
}
}
ResetLaunchTime();
StartSavePersistentDataTimer();
}
void ResumeCtrl::StartSavePersistentDataTimer() {
LOG4CXX_AUTO_TRACE(logger_);
if (!save_persistent_data_timer_.isRunning()) {
save_persistent_data_timer_.start(
profile::Profile::instance()->app_resumption_save_persistent_data_timeout());
}
}
void ResumeCtrl::StopSavePersistentDataTimer() {
LOG4CXX_AUTO_TRACE(logger_);
if (save_persistent_data_timer_.isRunning()) {
save_persistent_data_timer_.stop();
}
}
void ResumeCtrl::StopRestoreHmiLevelTimer() {
LOG4CXX_AUTO_TRACE(logger_);
if (restore_hmi_level_timer_.isRunning()) {
restore_hmi_level_timer_.stop();
}
}
bool ResumeCtrl::StartResumption(ApplicationSharedPtr application,
const std::string& hash) {
LOG4CXX_AUTO_TRACE(logger_);
if (!application) {
LOG4CXX_WARN(logger_, "Application not exist");
return false;
}
LOG4CXX_DEBUG(logger_, " Resume app_id = " << application->app_id()
<< " hmi_app_id = " << application->hmi_app_id()
<< " mobile_id = " << application->mobile_app_id()
<< "received hash = " << hash);
sync_primitives::AutoLock lock(resumtion_lock_);
const int idx = GetObjectIndex(application->mobile_app_id());
if (-1 == idx) {
LOG4CXX_WARN(logger_, "Application not saved");
return false;
}
const Json::Value& json_app = GetSavedApplications()[idx];
LOG4CXX_DEBUG(logger_, "Saved_application_data: " << json_app.toStyledString());
if (json_app.isMember(strings::hash_id) && json_app.isMember(strings::time_stamp)) {
const std::string& saved_hash = json_app[strings::hash_id].asString();
if (saved_hash == hash) {
RestoreApplicationData(application);
}
application->UpdateHash();
queue_lock_.Acquire();
waiting_for_timer_.push_back(application->app_id());
queue_lock_.Release();
if (!is_resumption_active_) {
is_resumption_active_ = true;
restore_hmi_level_timer_.start(
profile::Profile::instance()->app_resuming_timeout());
}
} else {
LOG4CXX_INFO(logger_, "There are some unknown keys in the dictionary.");
return false;
}
return true;
}
void ResumeCtrl::StartAppHmiStateResumption(ApplicationSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace profile;
using namespace date_time;
DCHECK_OR_RETURN_VOID(application);
const int idx = GetObjectIndex(application->mobile_app_id());
DCHECK_OR_RETURN_VOID(idx != -1);
const Json::Value& json_app = GetSavedApplications()[idx];
if (!json_app.isMember(strings::ign_off_count)) {
LOG4CXX_INFO(logger_, "Do not need to resume application "
<< application->app_id());
SetupDefaultHMILevel(application);
return;
}
// check if if is resumption during one IGN cycle
const uint32_t ign_off_count = json_app[strings::ign_off_count].asUInt();
if (0 == ign_off_count) {
if (CheckAppRestrictions(application, json_app)) {
LOG4CXX_INFO(logger_, "Resume application after short IGN cycle");
RestoreAppHMIState(application);
RemoveApplicationFromSaved(application->mobile_app_id());
} else {
LOG4CXX_INFO(logger_, "Do not need to resume application "
<< application->app_id());
}
} else {
if (CheckIgnCycleRestrictions(json_app) &&
CheckAppRestrictions(application, json_app)) {
LOG4CXX_INFO(logger_, "Resume application after IGN cycle");
RestoreAppHMIState(application);
RemoveApplicationFromSaved(application->mobile_app_id());
} else {
LOG4CXX_INFO(logger_, "Do not need to resume application "
<< application->app_id());
}
}
}
std::set<ApplicationSharedPtr> ResumeCtrl::retrieve_application() {
ApplicationManagerImpl::ApplicationListAccessor accessor;
return std::set<ApplicationSharedPtr>(accessor.begin(), accessor.end());
}
bool ResumeCtrl::StartResumptionOnlyHMILevel(ApplicationSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
if (!application.valid()) {
LOG4CXX_WARN(logger_, "Application do not exists");
return false;
}
LOG4CXX_DEBUG(logger_, "ENTER app_id = " << application->app_id()
<< "mobile_id = "
<< application->mobile_app_id());
sync_primitives::AutoLock lock(resumtion_lock_);
const int idx = GetObjectIndex(application->mobile_app_id());
if (-1 == idx) {
LOG4CXX_WARN(logger_, "Application not saved");
return false;
}
queue_lock_.Acquire();
waiting_for_timer_.push_back(application->app_id());
queue_lock_.Release();
if (!is_resumption_active_) {
is_resumption_active_ = true;
restore_hmi_level_timer_.start(
profile::Profile::instance()->app_resuming_timeout());
}
return true;
}
bool ResumeCtrl::CheckPersistenceFilesForResumption(ApplicationSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
if (!application.valid()) {
LOG4CXX_WARN(logger_, "Application do not exists");
return false;
}
LOG4CXX_DEBUG(logger_, "Process app_id = " << application->app_id());
sync_primitives::AutoLock lock(resumtion_lock_);
const int idx = GetObjectIndex(application->mobile_app_id());
if (-1 == idx) {
LOG4CXX_WARN(logger_, "Application not saved");
return false;
}
const Json::Value& saved_app = GetSavedApplications()[idx];
if (!saved_app.isMember(strings::application_commands) ||
!saved_app.isMember(strings::application_choise_sets)) {
LOG4CXX_WARN(logger_, "application_commands or "
"application_choise_sets are not exists");
return false;
}
if (!CheckIcons(application, saved_app[strings::application_commands])) {
return false;
}
if (!CheckIcons(application, saved_app[strings::application_choise_sets])) {
return false;
}
LOG4CXX_DEBUG(logger_, " result = true");
return true;
}
bool ResumeCtrl::CheckApplicationHash(ApplicationSharedPtr application,
const std::string& hash) {
if (!application) {
LOG4CXX_ERROR(logger_, "Application pointer is invalid");
return false;
}
LOG4CXX_DEBUG(logger_, "ENTER app_id : " << application->app_id()
<< " hash : " << hash);
sync_primitives::AutoLock lock(resumtion_lock_);
const int idx = GetObjectIndex(application->mobile_app_id());
if (-1 == idx) {
LOG4CXX_WARN(logger_, "Application not saved");
return false;
}
const Json::Value& json_app = GetSavedApplications()[idx];
if (json_app.isMember(strings::hash_id)) {
const std::string& saved_hash = json_app[strings::hash_id].asString();
LOG4CXX_TRACE(logger_, "Found saved application : " << json_app.toStyledString());
LOG4CXX_INFO(logger_, "received hash = " << hash);
LOG4CXX_INFO(logger_, "saved hash = " << saved_hash);
if (hash == saved_hash) {
return true;
}
}
return false;
}
void ResumeCtrl::SaveDataOnTimer() {
LOG4CXX_AUTO_TRACE(logger_);
if (is_resumption_active_) {
LOG4CXX_WARN(logger_, "Resumption timer is active skip saving");
return;
}
if (false == is_data_saved) {
SaveAllApplications();
is_data_saved = true;
resumption::LastState::instance()->SaveToFileSystem();
}
}
bool ResumeCtrl::IsDeviceMacAddressEqual(ApplicationSharedPtr application,
const std::string& saved_device_mac) {
const std::string device_mac =
MessageHelper::GetDeviceMacAddressForHandle(application->device());
return device_mac == saved_device_mac;
}
Json::Value&ResumeCtrl::GetResumptionData() {
LOG4CXX_AUTO_TRACE(logger_);
Json::Value& last_state = resumption::LastState::instance()->dictionary;
if (!last_state.isMember(strings::resumption)) {
last_state[strings::resumption] = Json::Value(Json::objectValue);
LOG4CXX_WARN(logger_, "resumption section is missed");
}
Json::Value& resumption = last_state[strings::resumption];
if (!resumption.isObject()) {
LOG4CXX_ERROR(logger_, "resumption type INVALID rewrite");
resumption = Json::Value(Json::objectValue);
}
return resumption;
}
Json::Value& ResumeCtrl::GetSavedApplications() {
LOG4CXX_AUTO_TRACE(logger_);
Json::Value& resumption = GetResumptionData();
if (!resumption.isMember(strings::resume_app_list)) {
resumption[strings::resume_app_list] = Json::Value(Json::arrayValue);
LOG4CXX_WARN(logger_, "app_list section is missed");
}
Json::Value& resume_app_list = resumption[strings::resume_app_list];
if (!resume_app_list.isArray()) {
LOG4CXX_ERROR(logger_, "resume_app_list type INVALID rewrite");
resume_app_list = Json::Value(Json::arrayValue);
}
return resume_app_list;
}
time_t ResumeCtrl::GetIgnOffTime() {
LOG4CXX_AUTO_TRACE(logger_);
Json::Value& resumption = GetResumptionData();
if (!resumption.isMember(strings::last_ign_off_time)) {
resumption[strings::last_ign_off_time] = 0;
LOG4CXX_WARN(logger_, "last_save_time section is missed");
}
time_t last_ign_off = static_cast<time_t>(
resumption[strings::last_ign_off_time].asUInt());
return last_ign_off;
}
void ResumeCtrl::SetLastIgnOffTime(time_t ign_off_time) {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_WARN(logger_, "ign_off_time = " << ign_off_time);
Json::Value& resumption = GetResumptionData();
resumption[strings::last_ign_off_time] = static_cast<uint32_t>(ign_off_time);
}
void ResumeCtrl::SetSavedApplication(Json::Value& apps_json) {
Json::Value& app_list = GetSavedApplications();
app_list = apps_json;
}
void ResumeCtrl::ClearResumptionInfo() {
LOG4CXX_AUTO_TRACE(logger_);
Json::Value empty_json;
SetSavedApplication(empty_json);
resumption::LastState::instance()->SaveToFileSystem();
}
Json::Value ResumeCtrl::GetApplicationCommands(
ApplicationConstSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
Json::Value result;
DCHECK(application.get());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL Pointer App");
return result;
}
const DataAccessor<CommandsMap> accessor = application->commands_map();
const CommandsMap& commands = accessor.GetData();
CommandsMap::const_iterator it = commands.begin();
for (;it != commands.end(); ++it) {
smart_objects::SmartObject* so = it->second;
Json::Value curr;
Formatters::CFormatterJsonBase::objToJsonValue(*so, curr);
result.append(curr);
}
return result;
}
Json::Value ResumeCtrl::GetApplicationSubMenus(
ApplicationConstSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
Json::Value result;
DCHECK(application.get());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL Pointer App");
return result;
}
const DataAccessor<SubMenuMap> accessor = application->sub_menu_map();
const SubMenuMap& sub_menus = accessor.GetData();
SubMenuMap::const_iterator it = sub_menus.begin();
for (;it != sub_menus.end(); ++it) {
smart_objects::SmartObject* so = it->second;
Json::Value curr;
Formatters::CFormatterJsonBase::objToJsonValue(*so, curr);
result.append(curr);
}
return result;
}
Json::Value ResumeCtrl::GetApplicationInteractionChoiseSets(
ApplicationConstSharedPtr application) {
DCHECK(application.get());
LOG4CXX_TRACE(logger_, "ENTER app_id:"
<< application->app_id());
Json::Value result;
const DataAccessor<ChoiceSetMap> accessor = application->choice_set_map();
const ChoiceSetMap& choices = accessor.GetData();
ChoiceSetMap::const_iterator it = choices.begin();
for ( ;it != choices.end(); ++it) {
smart_objects::SmartObject* so = it->second;
Json::Value curr;
Formatters::CFormatterJsonBase::objToJsonValue(*so, curr);
result.append(curr);
}
return result;
}
Json::Value ResumeCtrl::GetApplicationGlobalProperties(
ApplicationConstSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
Json::Value sgp;
DCHECK(application.get());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL Pointer App");
return sgp;
}
const smart_objects::SmartObject* help_promt = application->help_prompt();
const smart_objects::SmartObject* timeout_prompt = application->timeout_prompt();
const smart_objects::SmartObject* vr_help = application->vr_help();
const smart_objects::SmartObject* vr_help_title = application->vr_help_title();
const smart_objects::SmartObject* vr_synonyms = application->vr_synonyms();
const smart_objects::SmartObject* keyboard_props = application->keyboard_props();
const smart_objects::SmartObject* menu_title = application->menu_title();
const smart_objects::SmartObject* menu_icon = application->menu_icon();
sgp[strings::help_prompt] = JsonFromSO(help_promt);
sgp[strings::timeout_prompt] = JsonFromSO(timeout_prompt);
sgp[strings::vr_help] = JsonFromSO(vr_help);
sgp[strings::vr_help_title] = JsonFromSO(vr_help_title);
sgp[strings::vr_synonyms] = JsonFromSO(vr_synonyms);
sgp[strings::keyboard_properties] = JsonFromSO(keyboard_props);
sgp[strings::menu_title] = JsonFromSO(menu_title);
sgp[strings::menu_icon] = JsonFromSO(menu_icon);
return sgp;
}
Json::Value ResumeCtrl::GetApplicationSubscriptions(
ApplicationConstSharedPtr application) {
LOG4CXX_AUTO_TRACE(logger_);
Json::Value result;
DCHECK(application.get());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL Pointer App");
return result;
}
LOG4CXX_DEBUG(logger_, "app_id:" << application->app_id());
LOG4CXX_DEBUG(logger_, "SubscribedButtons:" << application->SubscribedButtons().size());
Append(application->SubscribedButtons().begin(),
application->SubscribedButtons().end(),
strings::application_buttons, result);
LOG4CXX_DEBUG(logger_, "SubscribesIVI:" << application->SubscribesIVI().size());
Append(application->SubscribesIVI().begin(),
application->SubscribesIVI().end(),
strings::application_vehicle_info, result);
return result;
}
Json::Value ResumeCtrl::GetApplicationFiles(
ApplicationConstSharedPtr application) {
DCHECK(application.get());
LOG4CXX_TRACE(logger_, "ENTER app_id:"
<< application->app_id());
Json::Value result;
const AppFilesMap& app_files = application->getAppFiles();
for(AppFilesMap::const_iterator file_it = app_files.begin();
file_it != app_files.end(); file_it++) {
const AppFile& file = file_it->second;
if (file.is_persistent) {
Json::Value file_data;
file_data[strings::persistent_file] = file.is_persistent;
file_data[strings::is_download_complete] = file.is_download_complete;
file_data[strings::sync_file_name] = file.file_name;
file_data[strings::file_type] = file.file_type;
result.append(file_data);
}
}
return result;
}
Json::Value ResumeCtrl::GetApplicationShow(
ApplicationConstSharedPtr application) {
DCHECK(application.get());
LOG4CXX_TRACE(logger_, "ENTER app_id:"
<< application->app_id());
Json::Value result;
const smart_objects::SmartObject* show_so = application->show_command();
if (!show_so) {
return result;
}
result = JsonFromSO(show_so);
return result;
}
Json::Value ResumeCtrl::JsonFromSO(const smart_objects::SmartObject *so) {
Json::Value temp;
if (so) {
Formatters::CFormatterJsonBase::objToJsonValue(*so, temp);
}
return temp;
}
bool ResumeCtrl::ProcessHMIRequest(smart_objects::SmartObjectSPtr request,
bool use_events) {
LOG4CXX_AUTO_TRACE(logger_);
if (use_events) {
const hmi_apis::FunctionID::eType function_id =
static_cast<hmi_apis::FunctionID::eType>(
(*request)[strings::function_id].asInt());
const int32_t hmi_correlation_id =
(*request)[strings::correlation_id].asInt();
subscribe_on_event(function_id, hmi_correlation_id);
}
if (!ApplicationManagerImpl::instance()->ManageHMICommand(request)) {
LOG4CXX_ERROR(logger_, "Unable to send request");
return true;
}
return false;
}
void ResumeCtrl::AddFiles(ApplicationSharedPtr application, const Json::Value& saved_app) {
LOG4CXX_AUTO_TRACE(logger_);
if (saved_app.isMember(strings::application_files)) {
const Json::Value& application_files = saved_app[strings::application_files];
for (Json::Value::iterator json_it = application_files.begin();
json_it != application_files.end(); ++json_it) {
const Json::Value& file_data = *json_it;
const bool is_persistent = file_data.isMember(strings::persistent_file) &&
file_data[strings::persistent_file].asBool();
if (is_persistent) {
AppFile file;
file.is_persistent = is_persistent;
file.is_download_complete = file_data[strings::is_download_complete].asBool();
file.file_name = file_data[strings::sync_file_name].asString();
file.file_type = static_cast<mobile_apis::FileType::eType> (
file_data[strings::file_type].asInt());
application->AddFile(file);
}
}
} else {
LOG4CXX_FATAL(logger_, "application_files section is not exists");
}
}
void ResumeCtrl::AddSubmenues(ApplicationSharedPtr application, const Json::Value& saved_app) {
LOG4CXX_AUTO_TRACE(logger_);
if (saved_app.isMember(strings::application_submenus)) {
const Json::Value& app_submenus = saved_app[strings::application_submenus];
for (Json::Value::iterator json_it = app_submenus.begin();
json_it != app_submenus.end(); ++json_it) {
const Json::Value& json_submenu = *json_it;
smart_objects::SmartObject message(smart_objects::SmartType::SmartType_Map);
Formatters::CFormatterJsonBase::jsonValueToObj(json_submenu, message);
application->AddSubMenu(message[strings::menu_id].asUInt(), message);
}
ProcessHMIRequests(MessageHelper::CreateAddSubMenuRequestToHMI(application));
} else {
LOG4CXX_FATAL(logger_, "application_submenus section is not exists");
}
}
void ResumeCtrl::AddCommands(ApplicationSharedPtr application, const Json::Value& saved_app) {
LOG4CXX_AUTO_TRACE(logger_);
if (saved_app.isMember(strings::application_commands)) {
const Json::Value& app_commands = saved_app[strings::application_commands];
for (Json::Value::iterator json_it = app_commands.begin();
json_it != app_commands.end(); ++json_it) {
const Json::Value& json_command = *json_it;
smart_objects::SmartObject message(smart_objects::SmartType::SmartType_Map);
Formatters::CFormatterJsonBase::jsonValueToObj(json_command, message);
application->AddCommand(message[strings::cmd_id].asUInt(), message);
}
ProcessHMIRequests(MessageHelper::CreateAddCommandRequestToHMI(application));
} else {
LOG4CXX_FATAL(logger_, "application_commands section is not exists");
}
}
void ResumeCtrl::AddChoicesets(ApplicationSharedPtr application, const Json::Value& saved_app) {
LOG4CXX_AUTO_TRACE(logger_);
if (saved_app.isMember(strings::application_choise_sets)) {
const Json::Value& app_choise_sets = saved_app[strings::application_choise_sets];
for (Json::Value::iterator json_it = app_choise_sets.begin();
json_it != app_choise_sets.end(); ++json_it) {
const Json::Value& json_choiset = *json_it;
smart_objects::SmartObject msg_param(smart_objects::SmartType::SmartType_Map);
Formatters::CFormatterJsonBase::jsonValueToObj(json_choiset , msg_param);
const int32_t choice_set_id = msg_param
[strings::interaction_choice_set_id].asInt();
uint32_t choice_grammar_id = msg_param[strings::grammar_id].asUInt();
application->AddChoiceSet(choice_set_id, msg_param);
const size_t size = msg_param[strings::choice_set].length();
for (size_t j = 0; j < size; ++j) {
smart_objects::SmartObject choise_params(smart_objects::SmartType_Map);
choise_params[strings::app_id] = application->app_id();
choise_params[strings::cmd_id] =
msg_param[strings::choice_set][j][strings::choice_id];
choise_params[strings::vr_commands] = smart_objects::SmartObject(
smart_objects::SmartType_Array);
choise_params[strings::vr_commands] =
msg_param[strings::choice_set][j][strings::vr_commands];
choise_params[strings::type] = hmi_apis::Common_VRCommandType::Choice;
choise_params[strings::grammar_id] = choice_grammar_id;
SendHMIRequest(hmi_apis::FunctionID::VR_AddCommand, &choise_params);
}
}
} else {
LOG4CXX_FATAL(logger_, "There is no any choicesets");
}
}
void ResumeCtrl::SetGlobalProperties(ApplicationSharedPtr application, const Json::Value& saved_app) {
LOG4CXX_AUTO_TRACE(logger_);
const Json::Value& global_properties = saved_app[strings::application_global_properties];
if (!global_properties.isNull()) {
smart_objects::SmartObject properties_so(smart_objects::SmartType::SmartType_Map);
Formatters::CFormatterJsonBase::jsonValueToObj(global_properties , properties_so);
application->load_global_properties(properties_so);
MessageHelper::SendGlobalPropertiesToHMI(application);
}
}
void ResumeCtrl::AddSubscriptions(ApplicationSharedPtr application, const Json::Value& saved_app) {
LOG4CXX_AUTO_TRACE(logger_);
if (saved_app.isMember(strings::application_subscribtions)) {
const Json::Value& subscribtions = saved_app[strings::application_subscribtions];
if (subscribtions.isMember(strings::application_buttons)) {
const Json::Value& subscribtions_buttons = subscribtions[strings::application_buttons];
mobile_apis::ButtonName::eType btn;
for (Json::Value::iterator json_it = subscribtions_buttons.begin();
json_it != subscribtions_buttons.end(); ++json_it) {
btn = static_cast<mobile_apis::ButtonName::eType>((*json_it).asInt());
application->SubscribeToButton(btn);
}
}
if (subscribtions.isMember(strings::application_vehicle_info)) {
const Json::Value& subscribtions_ivi= subscribtions[strings::application_vehicle_info];
VehicleDataType ivi;
for (Json::Value::iterator json_it = subscribtions_ivi.begin();
json_it != subscribtions_ivi.end(); ++json_it) {
ivi = static_cast<VehicleDataType>((*json_it).asInt());
application->SubscribeToIVI(ivi);
}
}
ProcessHMIRequests(MessageHelper::GetIVISubscriptionRequests(application));
MessageHelper::SendAllOnButtonSubscriptionNotificationsForApp(application);
}
}
void ResumeCtrl::ProcessHMIRequests(const smart_objects::SmartObjectList& requests) {
for (smart_objects::SmartObjectList::const_iterator it = requests.begin(),
total = requests.end();
it != total; ++it) {
ProcessHMIRequest(*it, true);
}
}
bool ResumeCtrl::CheckIcons(ApplicationSharedPtr application,
const Json::Value& json_object) {
LOG4CXX_AUTO_TRACE(logger_);
bool result = true;
if (!json_object.isNull()) {
Json::Value::const_iterator json_it = json_object.begin();
for (;json_it != json_object.end() && result; ++json_it) {
const Json::Value& json_command = *json_it;
if (!json_command.isNull()) {
smart_objects::SmartObject message(smart_objects::SmartType::SmartType_Map);
Formatters::CFormatterJsonBase::jsonValueToObj(json_command, message);
const mobile_apis::Result::eType verify_images =
MessageHelper::VerifyImageFiles(message, application);
result = (mobile_apis::Result::INVALID_DATA != verify_images);
} else {
LOG4CXX_WARN(logger_, "Invalid json object");
}
}
} else {
LOG4CXX_WARN(logger_, "Passed json object is null");
}
LOG4CXX_DEBUG(logger_, "CheckIcons result " << result);
return result;
}
Json::Value& ResumeCtrl::GetFromSavedOrAppend(const std::string& mobile_app_id) {
LOG4CXX_AUTO_TRACE(logger_);
for (Json::Value::iterator it = GetSavedApplications().begin();
it != GetSavedApplications().end(); ++it) {
if (mobile_app_id == (*it)[strings::app_id].asString()) {
return *it;
}
}
return GetSavedApplications().append(Json::Value());
}
bool ResumeCtrl::CheckIgnCycleRestrictions(const Json::Value& json_app) {
LOG4CXX_AUTO_TRACE(logger_);
bool result = true;
if (!CheckDelayAfterIgnOn()) {
LOG4CXX_INFO(logger_, "Application was connected long after ign on");
result = false;
}
if (!DisconnectedJustBeforeIgnOff(json_app)) {
LOG4CXX_INFO(logger_, "Application was dissconnected long before ign off");
result = false;
}
return result;
}
bool ResumeCtrl::DisconnectedInLastIgnCycle(const Json::Value& json_app) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN(json_app.isMember(strings::suspend_count), false);
const uint32_t suspend_count = json_app[strings::suspend_count].asUInt();
LOG4CXX_DEBUG(logger_, " suspend_count " << suspend_count);
return (1 == suspend_count);
}
bool ResumeCtrl::DisconnectedJustBeforeIgnOff(const Json::Value& json_app) {
using namespace date_time;
using namespace profile;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN(json_app.isMember(strings::time_stamp), false);
const time_t time_stamp =
static_cast<time_t>(json_app[strings::time_stamp].asUInt());
time_t ign_off_time = GetIgnOffTime();
const uint32_t sec_spent_before_ign = labs(ign_off_time - time_stamp);
LOG4CXX_DEBUG(logger_,"ign_off_time " << ign_off_time
<< "; app_disconnect_time " << time_stamp
<< "; sec_spent_before_ign " << sec_spent_before_ign
<< "; resumption_delay_before_ign " <<
Profile::instance()->resumption_delay_before_ign());
return sec_spent_before_ign <=
Profile::instance()->resumption_delay_before_ign();
}
bool ResumeCtrl::CheckDelayAfterIgnOn() {
using namespace date_time;
using namespace profile;
LOG4CXX_AUTO_TRACE(logger_);
time_t curr_time = time(NULL);
time_t sdl_launch_time = launch_time();
const uint32_t seconds_from_sdl_start = labs(curr_time - sdl_launch_time);
const uint32_t wait_time =
Profile::instance()->resumption_delay_after_ign();
LOG4CXX_DEBUG(logger_, "curr_time " << curr_time
<< "; sdl_launch_time " << sdl_launch_time
<< "; seconds_from_sdl_start " << seconds_from_sdl_start
<< "; wait_time " << wait_time);
return seconds_from_sdl_start <= wait_time;
}
bool ResumeCtrl::CheckAppRestrictions(ApplicationSharedPtr application,
const Json::Value& json_app) {
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN(json_app.isMember(strings::hmi_level), false);
const bool is_media_app = application->is_media_application();
const HMILevel::eType hmi_level =
static_cast<HMILevel::eType>(json_app[strings::hmi_level].asInt());
LOG4CXX_DEBUG(logger_, "is_media_app " << is_media_app
<< "; hmi_level " << hmi_level);
if (is_media_app) {
if (hmi_level == HMILevel::HMI_FULL ||
hmi_level == HMILevel::HMI_LIMITED) {
return true;
}
}
return false;
}
int ResumeCtrl::GetObjectIndex(const std::string& mobile_app_id) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(resumtion_lock_);
const Json::Value& apps = GetSavedApplications();
const Json::ArrayIndex size = apps.size();
Json::ArrayIndex idx = 0;
for (; idx != size; ++idx) {
const std::string& saved_app_id = apps[idx][strings::app_id].asString();
if (mobile_app_id == saved_app_id) {
LOG4CXX_DEBUG(logger_, "Found " << idx);
return idx;
}
}
return -1;
}
time_t ResumeCtrl::launch_time() const {
return launch_time_;
}
void ResumeCtrl::ResetLaunchTime() {
launch_time_ = time(NULL);
}
void ResumeCtrl::ApplicationResumptiOnTimer() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(queue_lock_);
is_resumption_active_ = false;
std::vector<uint32_t>::iterator it = waiting_for_timer_.begin();
for (; it != waiting_for_timer_.end(); ++it) {
ApplicationSharedPtr app =
ApplicationManagerImpl::instance()->application(*it);
if (!app.get()) {
LOG4CXX_ERROR(logger_, "Invalid app_id = " << *it);
continue;
}
StartAppHmiStateResumption(app);
}
waiting_for_timer_.clear();
}
void ResumeCtrl::LoadResumeData() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(resumtion_lock_);
Json::Value& resume_app_list = GetSavedApplications();
Json::Value::iterator full_app = resume_app_list.end();
time_t time_stamp_full = 0;
Json::Value::iterator limited_app = resume_app_list.end();
time_t time_stamp_limited = 0;
Json::Value::iterator it = resume_app_list.begin();
for (; it != resume_app_list.end(); ++it) {
if ((*it).isMember(strings::ign_off_count) &&
(*it).isMember(strings::hmi_level)) {
// only apps with first IGN should be resumed
const int32_t first_ign = 1;
if (first_ign == (*it)[strings::ign_off_count].asInt()) {
const mobile_apis::HMILevel::eType saved_hmi_level =
static_cast<mobile_apis::HMILevel::eType>((*it)[strings::hmi_level].asInt());
const time_t saved_time_stamp =
static_cast<time_t>((*it)[strings::time_stamp].asUInt());
if (mobile_apis::HMILevel::HMI_FULL == saved_hmi_level) {
if (time_stamp_full < saved_time_stamp) {
time_stamp_full = saved_time_stamp;
full_app = it;
}
}
if (mobile_apis::HMILevel::HMI_LIMITED == saved_hmi_level) {
if (time_stamp_limited < saved_time_stamp) {
time_stamp_limited = saved_time_stamp;
limited_app = it;
}
}
}
// set invalid HMI level for all
(*it)[strings::hmi_level] =
static_cast<int32_t>(mobile_apis::HMILevel::INVALID_ENUM);
}
}
if (full_app != resume_app_list.end()) {
(*full_app)[strings::hmi_level] =
static_cast<int32_t>(mobile_apis::HMILevel::HMI_FULL);
}
if (limited_app != resume_app_list.end()) {
(*limited_app)[strings::hmi_level] =
static_cast<int32_t>(mobile_apis::HMILevel::HMI_LIMITED);
}
LOG4CXX_DEBUG(logger_, GetResumptionData().toStyledString());
}
bool ResumeCtrl::IsResumptionDataValid(uint32_t index) {
const Json::Value& json_app = GetSavedApplications()[index];
if (!json_app.isMember(strings::app_id) ||
!json_app.isMember(strings::ign_off_count) ||
!json_app.isMember(strings::hmi_level) ||
!json_app.isMember(strings::hmi_app_id) ||
!json_app.isMember(strings::time_stamp)) {
LOG4CXX_ERROR(logger_, "Wrong resumption data");
return false;
}
if (json_app.isMember(strings::hmi_app_id) &&
0 >= json_app[strings::hmi_app_id].asUInt()) {
LOG4CXX_ERROR(logger_, "Wrong resumption hmi app ID");
return false;
}
return true;
}
uint32_t ResumeCtrl::SendHMIRequest(
const hmi_apis::FunctionID::eType& function_id,
const smart_objects::SmartObject* msg_params, bool use_events) {
LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObjectSPtr result =
MessageHelper::CreateModuleInfoSO(function_id);
uint32_t hmi_correlation_id =
(*result)[strings::params][strings::correlation_id].asUInt();
if (use_events) {
subscribe_on_event(function_id, hmi_correlation_id);
}
if (msg_params) {
(*result)[strings::msg_params] = *msg_params;
}
if (!ApplicationManagerImpl::instance()->ManageHMICommand(result)) {
LOG4CXX_ERROR(logger_, "Unable to send request");
}
return hmi_correlation_id;
}
} // namespace application_manager
| 36.459604 | 113 | 0.703188 | jacobkeeler |
9836a0f0f3dd061f82814efe967deec7430c1d90 | 8,602 | cpp | C++ | tests/Basics/OverloadTest.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | tests/Basics/OverloadTest.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | tests/Basics/OverloadTest.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Tobias Gödderz
////////////////////////////////////////////////////////////////////////////////
#include "Basics/overload.h"
#include "gtest/gtest.h"
#include <variant>
using namespace arangodb;
class OverloadTest : public ::testing::Test {};
TEST_F(OverloadTest, single_overload_no_args_void_return) {
auto i = int{0};
auto const call = overload{
[&]() { ++i; },
};
static_assert(std::is_same_v<void, std::invoke_result_t<decltype(call)>>);
ASSERT_EQ(0, i);
i = 0;
call();
ASSERT_EQ(1, i);
}
TEST_F(OverloadTest, single_overload_no_args_with_return) {
auto i = int{0};
auto const call = overload{
[&]() { return i + 1; },
};
static_assert(std::is_same_v<int, std::invoke_result_t<decltype(call)>>);
ASSERT_EQ(0, i);
i = 0;
auto result = call();
EXPECT_EQ(1, result);
ASSERT_EQ(0, i);
}
TEST_F(OverloadTest, single_overload_one_arg_void_return) {
auto i = int{0};
auto const call = overload{
[](int& i) { ++i; },
};
static_assert(
std::is_same_v<void, std::invoke_result_t<decltype(call), int&>>);
ASSERT_EQ(0, i);
i = 0;
call(i);
ASSERT_EQ(1, i);
}
TEST_F(OverloadTest, single_overload_one_arg_with_return) {
auto i = int{0};
auto const call = overload{
[](int i) { return i + 1; },
};
static_assert(std::is_same_v<int, std::invoke_result_t<decltype(call), int>>);
ASSERT_EQ(0, i);
i = 0;
auto result = call(i);
EXPECT_EQ(1, result);
ASSERT_EQ(0, i);
}
TEST_F(OverloadTest, overload_heterogenous_return_type_with_default) {
struct A {
int a{};
};
struct B {
int b{};
};
struct C {
int c{};
};
struct D {
int d{};
};
auto const call = overload{
[](A& x) {
x.a += 1;
return x;
},
[](B& x) {
x.b += 2;
return x;
},
[](auto& x) { return x; },
};
static_assert(std::is_same_v<A, std::invoke_result_t<decltype(call), A&>>);
static_assert(std::is_same_v<B, std::invoke_result_t<decltype(call), B&>>);
static_assert(std::is_same_v<C, std::invoke_result_t<decltype(call), C&>>);
static_assert(std::is_same_v<D, std::invoke_result_t<decltype(call), D&>>);
{
auto a = A{1};
auto result = call(a);
static_assert(std::is_same_v<A, decltype(result)>);
EXPECT_EQ(2, a.a);
EXPECT_EQ(2, result.a);
}
{
auto b = B{1};
auto result = call(b);
static_assert(std::is_same_v<B, decltype(result)>);
EXPECT_EQ(3, b.b);
EXPECT_EQ(3, result.b);
}
{
auto c = C{1};
auto result = call(c);
static_assert(std::is_same_v<C, decltype(result)>);
EXPECT_EQ(1, c.c);
EXPECT_EQ(1, result.c);
}
{
auto d = D{1};
auto result = call(d);
static_assert(std::is_same_v<D, decltype(result)>);
EXPECT_EQ(1, d.d);
EXPECT_EQ(1, result.d);
}
}
TEST_F(OverloadTest, overload_differing_return_type) {
auto const call = overload{
[](int i) { return i + 1; },
[](double d) { return d / 2; },
};
static_assert(std::is_same_v<int, std::invoke_result_t<decltype(call), int>>);
static_assert(
std::is_same_v<double, std::invoke_result_t<decltype(call), double>>);
auto intResult = call(int{1});
static_assert(std::is_same_v<int, decltype(intResult)>);
EXPECT_EQ(2, intResult);
auto doubleResult = call(double{1});
static_assert(std::is_same_v<double, decltype(doubleResult)>);
EXPECT_EQ(0.5, doubleResult);
}
TEST_F(OverloadTest, overload_same_return_type) {
auto const call = overload{
[](int i) { return static_cast<double>(i + 1); },
[](double d) { return d / 2; },
};
static_assert(
std::is_same_v<double, std::invoke_result_t<decltype(call), int>>);
static_assert(
std::is_same_v<double, std::invoke_result_t<decltype(call), double>>);
auto intResult = call(int{1});
static_assert(std::is_same_v<double, decltype(intResult)>);
EXPECT_EQ(2.0, intResult);
auto doubleResult = call(double{1});
static_assert(std::is_same_v<double, decltype(doubleResult)>);
EXPECT_EQ(0.5, doubleResult);
}
TEST_F(OverloadTest, visit_overload_void_return_type) {
struct A {
int a{};
};
struct B {
int b{};
};
auto const visitor = overload{
[](A& x) { x.a += 1; },
[](B& x) { x.b += 2; },
};
static_assert(
std::is_same_v<void, std::invoke_result_t<decltype(visitor), A&>>);
static_assert(
std::is_same_v<void, std::invoke_result_t<decltype(visitor), B&>>);
{
std::variant<A, B> variant = A{1};
std::visit(visitor, variant);
ASSERT_TRUE(std::holds_alternative<A>(variant));
ASSERT_EQ(2, std::get<A>(variant).a);
}
{
std::variant<A, B> variant = B{1};
std::visit(visitor, variant);
ASSERT_TRUE(std::holds_alternative<B>(variant));
ASSERT_EQ(3, std::get<B>(variant).b);
}
}
TEST_F(OverloadTest, visit_overload_homogenous_return_type) {
struct A {
int a{};
};
struct B {
int b{};
};
auto const visitor = overload{
[](A const& x) { return x.a + 1; },
[](B const& x) { return x.b + 2; },
};
static_assert(
std::is_same_v<int, std::invoke_result_t<decltype(visitor), A>>);
static_assert(
std::is_same_v<int, std::invoke_result_t<decltype(visitor), B>>);
{
std::variant<A, B> variant = A{1};
auto resultA = std::visit(visitor, variant);
static_assert(std::is_same_v<int, decltype(resultA)>);
EXPECT_EQ(2, resultA);
ASSERT_TRUE(std::holds_alternative<A>(variant));
ASSERT_EQ(1, std::get<A>(variant).a);
}
{
std::variant<A, B> variant = B{1};
auto resultB = std::visit(visitor, variant);
static_assert(std::is_same_v<int, decltype(resultB)>);
EXPECT_EQ(3, resultB);
ASSERT_TRUE(std::holds_alternative<B>(variant));
ASSERT_EQ(1, std::get<B>(variant).b);
}
}
TEST_F(OverloadTest, visit_overload_homogenous_return_type_with_default) {
struct A {
int a{};
};
struct B {
int b{};
};
struct C {
int c{};
};
struct D {
int d{};
};
auto const visitor = overload{
[](A const& x) { return x.a + 1; },
[](B const& x) { return x.b + 2; },
[](auto const& x) { return -1; },
};
static_assert(
std::is_same_v<int, std::invoke_result_t<decltype(visitor), A>>);
static_assert(
std::is_same_v<int, std::invoke_result_t<decltype(visitor), B>>);
static_assert(
std::is_same_v<int, std::invoke_result_t<decltype(visitor), C>>);
static_assert(
std::is_same_v<int, std::invoke_result_t<decltype(visitor), D>>);
{
std::variant<A, B, C, D> variant = A{1};
auto resultA = std::visit(visitor, variant);
static_assert(std::is_same_v<int, decltype(resultA)>);
EXPECT_EQ(2, resultA);
ASSERT_TRUE(std::holds_alternative<A>(variant));
ASSERT_EQ(1, std::get<A>(variant).a);
}
{
std::variant<A, B, C, D> variant = B{1};
std::visit(visitor, variant);
auto resultB = std::visit(visitor, variant);
static_assert(std::is_same_v<int, decltype(resultB)>);
EXPECT_EQ(3, resultB);
ASSERT_TRUE(std::holds_alternative<B>(variant));
ASSERT_EQ(1, std::get<B>(variant).b);
}
{
std::variant<A, B, C, D> variant = C{1};
std::visit(visitor, variant);
auto resultC = std::visit(visitor, variant);
static_assert(std::is_same_v<int, decltype(resultC)>);
EXPECT_EQ(-1, resultC);
ASSERT_TRUE(std::holds_alternative<C>(variant));
ASSERT_EQ(1, std::get<C>(variant).c);
}
{
std::variant<A, B, C, D> variant = D{1};
std::visit(visitor, variant);
auto resultD = std::visit(visitor, variant);
static_assert(std::is_same_v<int, decltype(resultD)>);
EXPECT_EQ(-1, resultD);
ASSERT_TRUE(std::holds_alternative<D>(variant));
ASSERT_EQ(1, std::get<D>(variant).d);
}
}
| 26.549383 | 80 | 0.618577 | Mu-L |
9838e28fe961cfe241d63ad265dc4125ab77dbd7 | 24,415 | cpp | C++ | src/limits.cpp | neivv/teippi | 05c006c2f74ad11285c39d37135aed03d1fb8806 | [
"MIT"
] | 11 | 2015-08-25T23:27:00.000Z | 2021-05-06T18:53:21.000Z | src/limits.cpp | neivv/teippi | 05c006c2f74ad11285c39d37135aed03d1fb8806 | [
"MIT"
] | 2 | 2015-08-30T21:22:59.000Z | 2016-05-31T17:49:42.000Z | src/limits.cpp | neivv/teippi | 05c006c2f74ad11285c39d37135aed03d1fb8806 | [
"MIT"
] | 5 | 2015-08-29T22:35:28.000Z | 2016-02-26T19:15:24.000Z | #include "limits.h"
#include "patch/patchmanager.h"
#include "ai.h"
#include "bullet.h"
#include "bunker.h"
#include "commands.h"
#include "dialog.h"
#include "draw.h"
#include "flingy.h"
#include "game.h"
#include "init.h"
#include "image.h"
#include "iscript.h"
#include "log.h"
#include "offsets_hooks.h"
#include "offsets.h"
#include "order.h"
#include "pathing.h"
#include "player.h"
#include "replay.h"
#include "rng.h"
#include "save.h"
#include "selection.h"
#include "sound.h"
#include "sprite.h"
#include "targeting.h"
#include "tech.h"
#include "triggers.h"
#include "unitsearch.h"
#include "warn.h"
#include "unit.h"
Common::PatchManager *patch_mgr;
// Hack from game.cpp
extern bool unitframes_in_progress;
void DamageUnit_Hook(int damage, Unit *target, Unit *attacker, int attacking_player, int show_attacker)
{
// Can't do UnitWasHit here, so warn
if (attacker != nullptr)
Warning("DamageUnit hooked");
vector<Unit *> killed_units;
DamageUnit(damage, target, &killed_units);
for (Unit *unit : killed_units)
unit->Kill(nullptr);
}
void AddMultipleOverlaySprites(Sprite *sprite, uint16_t base, int overlay_type, int count, int sprite_id, int flip)
{
sprite->AddMultipleOverlaySprites(overlay_type, count - base + 1, SpriteType(sprite_id), base, flip);
}
void SendUnloadCommand(const Unit *unit)
{
uint8_t buf[5];
buf[0] = commands::Unload;
*(uint32_t *)(buf + 1) = unit->lookup_id;
bw::SendCommand(buf, 5);
}
Unit ** FindUnitsRect(const Rect16 *rect)
{
int tmp;
Rect16 r = *rect;
// See unitsearch.h
r.right += 1;
r.bottom += 1;
if (r.right < r.left)
r.left = 0;
if (r.bottom < r.top)
r.top = 0;
r.right = std::min(r.right, *bw::map_width);
r.bottom = std::min(r.bottom, *bw::map_height);
Unit **ret = unit_search->FindUnitsRect(r, &tmp);
return ret;
}
Unit ** CheckMovementCollision(Unit *unit, int x, int y)
{
if (x >= 0x8000)
x |= 0xffff << 16;
if (y >= 0x8000)
y |= 0xffff << 16;
return unit_search->CheckMovementCollision(unit, x, y);
}
Unit **FindUnitBordersRect(const Rect16 *rect)
{
Rect16 r = *rect;
if (r.right < r.left)
r.left = 0;
if (r.bottom < r.top)
r.top = 0;
return unit_search->FindUnitBordersRect(&r);
}
Unit *FindNearestUnit(Rect16 *area, Unit *a, uint16_t b, uint16_t c, int d, int e, int f, int g,
int (__fastcall *h)(const Unit *, void *), void *i)
{
if (area->left > area->right)
area->left = 0;
if (area->top > area->bottom)
area->top = 0;
return unit_search->FindNearestUnit(a, Point(b, c), h, i, *area);
}
void CancelZergBuilding(Unit *unit)
{
//Warning("Calling Unit::Kill with nullptr from CancelZergBuilding (Extractor)");
// This *should* not matter, as human cancels are at least done from ProcessCommands
unit->CancelZergBuilding(nullptr);
}
Order *DeleteOrder_Hook(Order *order, Unit *unit)
{
unit->DeleteOrder(order);
// Bw assumes that it returns a order, but with this implementation
// it would be use-after-free, so just return nullptr and hope
// that any uses get caught with it.
return nullptr;
}
void KillSingleUnit(Unit *unit)
{
if (unitframes_in_progress)
Warning("Hooked Unit::Kill while unit frames are progressed (unit %x)", unit->unit_id);
unit->Kill(nullptr);
}
Unit **FindUnitsPoint(uint16_t x, uint16_t y)
{
Rect16 area(x, y, x + 1, y + 1);
return unit_search->FindUnitsRect(Rect16(x, y, x + 1, y + 1));
}
int IsTileBlockedBy(Unit **units, Unit *builder, int x_tile, int y_tile, int dont_ignore_reacting, int also_invisible)
{
int xpos = x_tile * 32;
int ypos = y_tile * 32;
for (Unit *unit = *units++; unit; unit = *units++)
{
if (unit == builder)
continue;
if (unit->flags & (UnitStatus::Building | UnitStatus::Air))
continue;
if (unit->Type() == UnitId::DarkSwarm || unit->Type() == UnitId::DisruptionWeb)
continue;
if (!dont_ignore_reacting && unit->flags & UnitStatus::Reacts)
continue;
bool invisible = false;
if (builder && unit->IsInvisibleTo(builder))
{
if (!also_invisible)
continue;
else
invisible = true;
}
if (unit->sprite->IsHidden())
continue;
Rect16 crect = unit->GetCollisionRect();
if (crect.left < xpos + 32 && crect.right > xpos)
{
if (crect.top < ypos + 32 && crect.bottom > ypos)
{
if (invisible)
return 0;
else
return 4;
}
}
}
return 0;
}
// Horribly misnamed
int DoesBuildingBlock(Unit *builder, int x_tile, int y_tile)
{
if (!builder || ~builder->flags & UnitStatus::Building || builder->Type() == UnitId::NydusCanal)
return true;
if (builder->sprite->IsHidden())
return true;
Rect16 crect = builder->GetCollisionRect();
if (crect.left >= (x_tile + 1) * 32 || crect.right <= x_tile * 32)
return true;
if (crect.top >= (y_tile + 1) * 32 || crect.bottom <= y_tile * 32)
return true;
return false;
}
class SimpleIscriptContext : public Iscript::Context
{
public:
constexpr SimpleIscriptContext(Rng *rng) : Iscript::Context(rng, false) { }
virtual Iscript::CmdResult HandleCommand(Image *img, Iscript::Script *script,
const Iscript::Command &cmd) override
{
auto result = img->HandleIscriptCommand(this, script, cmd);
if (result == Iscript::CmdResult::NotHandled)
{
Warning("Could not handle iscript command %s for image %s from SetIscriptAnimation hook",
cmd.DebugStr().c_str(), img->DebugStr().c_str());
}
return result;
}
};
void SetIscriptAnimation(Image *img, uint8_t anim)
{
if (*bw::active_iscript_unit != nullptr)
(*bw::active_iscript_unit)->SetIscriptAnimationForImage(img, anim);
else
{
// This is unable to handle any unit-specific commands
SimpleIscriptContext ctx(MainRng());
img->SetIscriptAnimation(&ctx, anim);
}
}
class MovementIscriptContext : public Iscript::Context
{
public:
constexpr MovementIscriptContext(Unit *unit, uint32_t *out_speed, Rng *rng) :
Iscript::Context(rng, false), unit(unit), out_speed(out_speed) { }
Unit * const unit;
uint32_t *out_speed;
virtual Iscript::CmdResult HandleCommand(Image *img, Iscript::Script *script,
const Iscript::Command &cmd) override
{
if (cmd.opcode == Iscript::Opcode::Move)
{
auto speed = bw::CalculateSpeedChange(unit, cmd.val * 256);
*out_speed = speed;
}
auto result = img->ConstIscriptCommand(this, script, cmd);
if (result == Iscript::CmdResult::NotHandled)
return Iscript::CmdResult::Handled;
return result;
}
};
static void ProgressIscriptFrame_Hook(Image *image, Iscript::Script *script, int test_run, uint32_t *out_speed)
{
// Shouldn't be hooked from elsewhere
Assert(*bw::active_iscript_unit != nullptr);
if (test_run)
{
Assert(out_speed != nullptr);
MovementIscriptContext ctx(*bw::active_iscript_unit, out_speed, MainRng());
script->ProgressFrame(&ctx, image);
}
else
{
// What to do? Could try determining if we are using unit, bullet, sprite or what,
// but this shouldn't be called anyways
Warning("ProgressIscriptFrame hooked");
}
}
int ForEachLoadedUnit(Unit *transport, int (__fastcall *Func)(Unit *unit, void *param), void *param)
{
for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded)
{
if ((*Func)(unit, param))
return 1;
}
return 0;
}
void AddLoadedUnitsToCompletedUnitLbScore(Unit *transport)
{
for (Unit *unit = transport->first_loaded; unit; unit = unit->next_loaded)
{
bw::AddToCompletedUnitLbScore(unit);
}
}
void TriggerPortraitFinished_Hook(Control *ctrl, int timer_id)
{
bw::DeleteTimer(ctrl, timer_id);
*bw::trigger_portrait_active = 0;
// Not including the code which clears waits in singleplayer, as it causes replays to desync
}
FILE *fopen_hook(const char *a, const char *b)
{
return fopen(a, b);
}
void fclose_hook(FILE *a)
{
fclose(a);
}
int fread_hook(void *a, int b, int c, FILE *d)
{
return fread(a, b, c, d);
}
int fwrite_hook(void *a, int b, int c, FILE *d)
{
return fwrite(a, b, c, d);
}
int fgetc_hook(FILE *a)
{
return fgetc(a);
}
int fseek_hook(FILE *a, int b, int c)
{
return fseek(a, b, c);
}
int setvbuf_hook(FILE *a, char *b, int c, int d)
{
return setvbuf(a, b, c, d);
}
void CreateSimplePath_Hook(Unit *unit, uint32_t waypoint_xy, uint32_t end_xy)
{
CreateSimplePath(unit, Point(waypoint_xy & 0xffff, waypoint_xy >> 16), Point(end_xy & 0xffff, end_xy >> 16));
}
static void ProgressMove_Hook(Flingy *flingy)
{
FlingyMoveResults unused;
flingy->ProgressMove(&unused);
}
static int IsDrawnPixel(GrpFrameHeader *frame, int x, int y)
{
if (x < 0 || x >= frame->w)
return 0;
if (y < 0 || y >= frame->h)
return 0;
return frame->GetPixel(x, y) != 0;
}
static bool __fastcall DrawGrp_Hook(int x, int y, GrpFrameHeader * frame_header, Rect32 * rect, void *unused)
{
if (frame_header->IsDecoded())
{
DrawNormal_NonFlipped(x, y, frame_header, rect, unused);
return true;
}
else
return false;
}
static bool __fastcall DrawGrp_Flipped_Hook(int x, int y, GrpFrameHeader * frame_header, Rect32 * rect, void *unused)
{
if (frame_header->IsDecoded())
{
DrawNormal_Flipped(x, y, frame_header, rect, unused);
return true;
}
else
return false;
}
static void MakeDetected_Hook(Sprite *sprite)
{
if (sprite->flags & 0x40)
bw::RemoveCloakDrawfuncs(sprite);
else
{
for (Image *img : sprite->first_overlay)
img->MakeDetected();
}
}
void PatchDraw(Common::PatchContext *patch)
{
patch->Hook(bw::SDrawLockSurface, SDrawLockSurface_Hook);
patch->Hook(bw::SDrawUnlockSurface, SDrawUnlockSurface_Hook);
patch->Hook(bw::DrawScreen, DrawScreen);
}
void RemoveLimits(Common::PatchContext *patch)
{
delete unit_search;
unit_search = new MainUnitSearch;
Ai::RemoveLimits(patch);
if (UseConsole)
{
patch->Hook(bw::GenerateFog, GenerateFog);
}
patch->Hook(bw::ProgressObjects, ProgressObjects);
patch->Hook(bw::GameFunc, ProgressFrames);
patch->Hook(bw::CreateOrder, [](uint8_t order, uint32_t pos, Unit *target, uint16_t fow) {
return new Order(OrderType(order), Point(pos & 0xffff, pos >> 16), target, UnitType(fow));
});
patch->Hook(bw::DeleteOrder, DeleteOrder_Hook);
patch->Hook(bw::DeleteSpecificOrder, [](Unit *unit, uint8_t order) {
return unit->DeleteSpecificOrder(OrderType(order));
});
patch->Hook(bw::GetEmptyImage, []{ return new Image; });
patch->Hook(bw::DeleteImage, &Image::SingleDelete);
patch->Hook(bw::CreateSprite, Sprite::AllocateWithBasicIscript_Hook);
patch->Hook(bw::DeleteSprite, [](Sprite *sprite) {
sprite->Remove();
delete sprite;
});
patch->Hook(bw::ProgressSpriteFrame, [](Sprite *sprite) {
// Shouldn't be hooked from elsewhere
Assert(*bw::active_iscript_unit != nullptr);
(*bw::active_iscript_unit)->ProgressIscript("ProgressSpriteFrame hook", nullptr);
});
patch->Hook(bw::CreateLoneSprite, [](uint16_t sprite_id, uint16_t x, uint16_t y, uint8_t player) {
return lone_sprites->AllocateLone(SpriteType(sprite_id), Point(x, y), player);
});
patch->Hook(bw::CreateFowSprite, [](uint16_t unit_id, Sprite *base) {
return lone_sprites->AllocateFow(base, UnitType(unit_id));
});
patch->Hook(bw::InitLoneSprites, InitCursorMarker);
patch->Hook(bw::DrawCursorMarker, DrawCursorMarker);
patch->Hook(bw::ShowRallyTarget, ShowRallyTarget);
patch->Hook(bw::ShowCursorMarker, ShowCursorMarker);
patch->Hook(bw::SetSpriteDirection, &Sprite::SetDirection32);
patch->Hook(bw::FindBlockingFowResource, FindBlockingFowResource);
patch->Hook(bw::DrawAllMinimapUnits, DrawMinimapUnits);
patch->Hook(bw::CreateBunkerShootOverlay, CreateBunkerShootOverlay);
patch->Hook(bw::AllocateUnit, &Unit::AllocateAndInit);
patch->CallHook(bw::InitUnitSystem_Hook, []{
Unit::DeleteAll();
// Hack to do it here but oh well.
score->Initialize();
});
patch->Hook(bw::InitSpriteSystem, Sprite::InitSpriteSystem);
patch->Hook(bw::CreateBullet,
[](Unit *parent, int x, int y, uint8_t player, uint8_t direction, uint8_t weapon_id) {
return bullet_system->AllocateBullet(parent, player, direction, WeaponType(weapon_id), Point(x, y));
});
patch->Hook(bw::GameEnd, GameEnd);
patch->Hook(bw::AddToPositionSearch, [](Unit *unit) { unit_search->Add(unit); } );
patch->Hook(bw::FindUnitPosition, [](int) { return 0; });
patch->Hook(bw::FindUnitsRect, FindUnitsRect);
patch->Hook(bw::FindNearbyUnits, [](Unit *u, int x, int y) {
return unit_search->FindCollidingUnits(u, x, y);
});
patch->Hook(bw::DoUnitsCollide, [](const Unit *a, const Unit *b) { return unit_search->DoUnitsCollide(a, b); });
patch->Hook(bw::CheckMovementCollision, CheckMovementCollision);
patch->Hook(bw::FindUnitBordersRect, FindUnitBordersRect);
patch->CallHook(bw::ClearPositionSearch, []{ unit_search->Clear(); });
patch->Hook(bw::ChangeUnitPosition, [](Unit *unit, int x_diff, int y_diff) {
unit_search->ChangeUnitPosition(unit, x_diff, y_diff);
});
patch->Hook(bw::FindNearestUnit, FindNearestUnit);
patch->Hook(bw::GetNearbyBlockingUnits, [](PathingData *pd) { unit_search->GetNearbyBlockingUnits(pd); });
patch->Hook(bw::RemoveFromPosSearch, [](Unit *unit) { unit_search->Remove(unit); });
patch->Hook(bw::FindUnitsPoint, FindUnitsPoint);
patch->Hook(bw::GetDodgingDirection, [](const Unit *self, const Unit *other) {
return unit_search->GetDodgingDirection(self, other);
});
patch->Hook(bw::DoesBlockArea, [](const Unit *unit, const CollisionArea *area) -> int {
return unit_search->DoesBlockArea(unit, area);
});
patch->Hook(bw::IsTileBlockedBy, IsTileBlockedBy);
patch->Hook(bw::DoesBuildingBlock, DoesBuildingBlock);
patch->Hook(bw::UnitToIndex, [](Unit *val) { return (uint32_t)val; });
patch->Hook(bw::IndexToUnit, [](uint32_t val) { return (Unit *)val; });
patch->Hook(bw::MakeDrawnSpriteList, [] {});
patch->Hook(bw::PrepareDrawSprites, Sprite::CreateDrawSpriteList);
patch->CallHook(bw::FullRedraw, Sprite::CreateDrawSpriteListFullRedraw);
patch->Hook(bw::DrawSprites, Sprite::DrawSprites);
// Disabled as I can't be bothered to figure it out.
patch->Hook(bw::VisionSync, [](void *, int) { return 1; });
patch->Hook(bw::RemoveUnitFromBulletTargets, RemoveFromBulletTargets);
patch->Hook(bw::DamageUnit, DamageUnit_Hook);
patch->Hook(bw::FindUnitInLocation_Check, FindUnitInLocation_Check);
patch->Hook(bw::ChangeInvincibility, ChangeInvincibility);
patch->Hook(bw::CanLoadUnit, [](const Unit *a, const Unit *b) -> int { return a->CanLoadUnit(b); });
patch->Hook(bw::LoadUnit, &Unit::LoadUnit);
patch->Hook(bw::HasLoadedUnits, [](const Unit *unit) -> int { return unit->HasLoadedUnits(); });
patch->Hook(bw::UnloadUnit, [](Unit *unit) -> int { return unit->related->UnloadUnit(unit); });
patch->Hook(bw::SendUnloadCommand, SendUnloadCommand);
patch->Hook(bw::GetFirstLoadedUnit, [](Unit *unit) { return unit->first_loaded; });
patch->Hook(bw::ForEachLoadedUnit, ForEachLoadedUnit);
patch->Hook(bw::AddLoadedUnitsToCompletedUnitLbScore, AddLoadedUnitsToCompletedUnitLbScore);
patch->Hook(bw::GetUsedSpace, &Unit::GetUsedSpace);
patch->Hook(bw::IsCarryingFlag, [](const Unit *unit) -> int { return unit->IsCarryingFlag(); });
patch->Hook(bw::DrawStatusScreen_LoadedUnits, DrawStatusScreen_LoadedUnits);
patch->Hook(bw::TransportStatus_UpdateDrawnValues, TransportStatus_UpdateDrawnValues);
patch->Hook(bw::TransportStatus_DoesNeedRedraw, TransportStatus_DoesNeedRedraw);
patch->Hook(bw::StatusScreen_DrawKills, StatusScreen_DrawKills);
patch->Hook(bw::AddMultipleOverlaySprites, AddMultipleOverlaySprites);
patch->Hook(bw::KillSingleUnit, KillSingleUnit);
patch->Hook(bw::Unit_Die, [] { Warning("Hooked Unit::Die, not doing anything"); });
patch->Hook(bw::CancelZergBuilding, CancelZergBuilding);
patch->Hook(bw::SetIscriptAnimation, SetIscriptAnimation);
patch->Hook(bw::ProgressIscriptFrame, ProgressIscriptFrame_Hook);
patch->Hook(bw::Order_AttackMove_ReactToAttack, [](Unit *unit, int order) {
return unit->Order_AttackMove_ReactToAttack(OrderType(order));
});
patch->Hook(bw::Order_AttackMove_TryPickTarget, [](Unit *unit, int order) {
unit->Order_AttackMove_TryPickTarget(OrderType(order));
});
// Won't be called when loading save though.
patch->CallHook(bw::PathingInited, [] { unit_search->Init(); });
patch->Hook(bw::ProgressUnstackMovement, &Unit::ProgressUnstackMovement);
patch->Hook(bw::MovementState13, &Unit::MovementState13);
patch->Hook(bw::MovementState17, &Unit::MovementState17);
patch->Hook(bw::MovementState20, &Unit::MovementState20);
patch->Hook(bw::MovementState1c, &Unit::MovementState1c);
patch->Hook(bw::MovementState_FollowPath, &Unit::MovementState_FollowPath);
patch->Hook(bw::MovementState_Flyer, [](Unit *) { return 0; });
patch->Hook(bw::Trig_KillUnitGeneric, [](Unit *unit, KillUnitArgs *args) {
return Trig_KillUnitGeneric(unit, args, args->check_height, false);
});
patch->Hook(bw::TriggerPortraitFinished, TriggerPortraitFinished_Hook);
bw::trigger_actions[0x7] = TrigAction_Transmission;
bw::trigger_actions[0xa] = TrigAction_CenterView;
patch->Hook(bw::ChangeMovementTargetToUnit, [](Unit *unit, Unit *target) -> int {
return unit->ChangeMovementTargetToUnit(target);
});
patch->Hook(bw::ChangeMovementTarget, [](Unit *unit, uint16_t x, uint16_t y) -> int {
return unit->ChangeMovementTarget(Point(x, y));
});
patch->JumpHook(bw::Sc_fclose, fclose_hook);
patch->JumpHook(bw::Sc_fopen, fopen_hook);
patch->JumpHook(bw::Sc_fwrite, fwrite_hook);
patch->JumpHook(bw::Sc_fread, fread_hook);
patch->JumpHook(bw::Sc_fgetc, fgetc_hook);
patch->JumpHook(bw::Sc_fseek, fseek_hook);
patch->JumpHook(bw::Sc_setvbuf, setvbuf_hook);
patch->Hook(bw::LoadGameObjects, LoadGameObjects);
patch->Hook(bw::AllocatePath, AllocatePath);
patch->Hook(bw::DeletePath, &Unit::DeletePath);
patch->Hook(bw::DeletePath2, &Unit::DeletePath);
patch->Hook(bw::CreateSimplePath, CreateSimplePath_Hook);
patch->Hook(bw::InitPathArray, [] {});
patch->Hook(bw::StatusScreenButton, StatusScreenButton);
patch->Hook(bw::LoadReplayMapDirEntry, LoadReplayMapDirEntry);
patch->Hook(bw::LoadReplayData, LoadReplayData);
patch->Hook(bw::DoNextQueuedOrder, &Unit::DoNextQueuedOrder);
patch->Hook(bw::ProcessLobbyCommands, ProcessLobbyCommands);
patch->Hook(bw::BriefingOk, BriefingOk);
patch->Hook(bw::ProgressFlingyTurning, [](Flingy *f) -> int { return f->ProgressTurning(); });
patch->Hook(bw::SetMovementDirectionToTarget, &Flingy::SetMovementDirectionToTarget);
patch->Hook(bw::ProgressMove, ProgressMove_Hook);
patch->Hook(bw::LoadGrp,
[](int image_id, uint32_t *grps, Tbl *tbl, GrpSprite **loaded_grps, void **overlapped, void **out_file) {
return LoadGrp(ImageType(image_id), grps, tbl, loaded_grps, overlapped, out_file);
});
patch->Hook(bw::IsDrawnPixel, IsDrawnPixel);
patch->Hook(bw::LoadBlendPalettes, LoadBlendPalettes);
patch->Hook(bw::DrawImage_Detected,
[](int x, int y, GrpFrameHeader *frame_header, Rect32 *rect, uint8_t *blend_table) {
DrawBlended_NonFlipped(x, y, frame_header, rect, blend_table);
});
patch->Hook(bw::DrawImage_Detected_Flipped,
[](int x, int y, GrpFrameHeader *frame_header, Rect32 *rect, uint8_t *blend_table) {
DrawBlended_Flipped(x, y, frame_header, rect, blend_table);
});
patch->Hook(bw::DrawUncloakedPart,
[](int x, int y, GrpFrameHeader *frame_header, Rect32 *rect, int state) {
DrawUncloakedPart_NonFlipped(x, y, frame_header, rect, state & 0xff);
});
patch->Hook(bw::DrawUncloakedPart_Flipped,
[](int x, int y, GrpFrameHeader *frame_header, Rect32 *rect, int state) {
DrawUncloakedPart_Flipped(x, y, frame_header, rect, state & 0xff);
});
patch->Hook(bw::DrawImage_Cloaked, DrawCloaked_NonFlipped);
patch->Hook(bw::DrawImage_Cloaked_Flipped, DrawCloaked_Flipped);
bw::image_renderfuncs[Image::Normal].nonflipped = &DrawNormal_NonFlipped;
bw::image_renderfuncs[Image::Normal].flipped = &DrawNormal_Flipped;
bw::image_renderfuncs[Image::NormalSpecial].nonflipped = &DrawNormal_NonFlipped;
bw::image_renderfuncs[Image::NormalSpecial].flipped = &DrawNormal_Flipped;
bw::image_renderfuncs[Image::Remap].nonflipped = &DrawBlended_NonFlipped;
bw::image_renderfuncs[Image::Remap].flipped = &DrawBlended_Flipped;
bw::image_renderfuncs[Image::Shadow].nonflipped = &DrawShadow_NonFlipped;
bw::image_renderfuncs[Image::Shadow].flipped = &DrawShadow_Flipped;
bw::image_renderfuncs[Image::UseWarpTexture].nonflipped = &DrawWarpTexture_NonFlipped;
bw::image_renderfuncs[Image::UseWarpTexture].flipped = &DrawWarpTexture_Flipped;
patch->Patch(bw::DrawGrp, (void *)&DrawGrp_Hook, 12, PATCH_OPTIONALHOOK | PATCH_SAFECALLHOOK);
patch->Patch(bw::DrawGrp_Flipped, (void *)&DrawGrp_Flipped_Hook, 12, PATCH_OPTIONALHOOK | PATCH_SAFECALLHOOK);
patch->Hook(bw::FindUnitAtPoint, FindUnitAtPoint);
patch->Hook(bw::MakeJoinedGameCommand, [](int flags, int x4, int proto_ver, int save_uniq_player,
int save_player, uint32_t save_hash, int create) {
MakeJoinedGameCommand(flags, x4, save_player, save_uniq_player, save_hash, create != 0);
});
patch->Hook(bw::Command_GameData, Command_GameData);
patch->Hook(bw::InitGame, InitGame);
patch->Hook(bw::InitStartingRacesAndTypes, InitStartingRacesAndTypes);
patch->Hook(bw::NeutralizePlayer, [](uint8_t player) { Neutralize(player); });
patch->Hook(bw::MakeDetected, MakeDetected_Hook);
patch->Hook(bw::AddDamageOverlay, &Sprite::AddDamageOverlay);
patch->Hook(bw::GameScreenRClickEvent, GameScreenRClickEvent);
patch->Hook(bw::GameScreenLClickEvent_Targeting, GameScreenLClickEvent_Targeting);
patch->Hook(bw::DoTargetedCommand, [](uint16_t x, uint16_t y, Unit *target, uint16_t fow_unit) {
DoTargetedCommand(x, y, target, UnitType(fow_unit));
});
patch->Hook(bw::SendChangeSelectionCommand, SendChangeSelectionCommand);
patch->Hook(bw::CenterOnSelectionGroup, CenterOnSelectionGroup);
patch->Hook(bw::SelectHotkeyGroup, SelectHotkeyGroup);
patch->Hook(bw::Command_SaveHotkeyGroup, [](uint8_t group, int create) {
Command_SaveHotkeyGroup(group, create == 0);
});
patch->Hook(bw::Command_SelectHotkeyGroup, Command_LoadHotkeyGroup);
patch->Hook(bw::TrySelectRecentHotkeyGroup, TrySelectRecentHotkeyGroup);
patch->Hook(bw::ProcessCommands, ProcessCommands);
patch->Hook(bw::ReplayCommands_Nothing, [](const void *) {});
patch->Hook(bw::UpdateBuildingPlacementState,
[](Unit *a, int b, int c, int d, uint16_t e, int f, int g, int h, int i) {
return UpdateBuildingPlacementState(a, b, c, d, UnitType(e), f, g, h, i);
});
patch->Hook(bw::PlaySelectionSound, PlaySelectionSound);
patch->Hook(bw::InitResourceAreas, InitResourceAreas);
patch->Hook(bw::Ai_RepairSomething, &Unit::Ai_RepairSomething);
}
| 36.992424 | 118 | 0.665452 | neivv |
983951a32d0533af38c0703846001c7c17931f15 | 591 | cpp | C++ | pathtrace/image.cpp | kiwixz/pathtracer | 62fbcee37ec6a60762061e430b9421a0177dde70 | [
"MIT"
] | 1 | 2019-04-08T07:59:26.000Z | 2019-04-08T07:59:26.000Z | pathtrace/image.cpp | kiwixz/pathtracer | 62fbcee37ec6a60762061e430b9421a0177dde70 | [
"MIT"
] | null | null | null | pathtrace/image.cpp | kiwixz/pathtracer | 62fbcee37ec6a60762061e430b9421a0177dde70 | [
"MIT"
] | null | null | null | #include "image.h"
#include <glm/common.hpp>
namespace pathtrace {
Image::Image(std::vector<Color>&& pixels, int width, int height) :
pixels_{std::move(pixels)}, width_{width}, height_{height}
{}
const std::vector<Color>& Image::pixels() const
{
return pixels_;
}
int Image::width() const
{
return width_;
}
int Image::height() const
{
return height_;
}
void Image::clamp(double min, double max)
{
for (Color& pix : pixels_)
glm::clamp(pix, min, max);
}
} // namespace pathtrace
| 21.107143 | 70 | 0.568528 | kiwixz |
98399246ad91f2cc21e4dae1b84b38932c124bf4 | 5,521 | cc | C++ | dense_map/volumetric_mapper/src/volumetric_mapper.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | 19 | 2021-11-18T19:29:16.000Z | 2022-02-23T01:55:51.000Z | dense_map/volumetric_mapper/src/volumetric_mapper.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | 13 | 2021-11-30T17:14:46.000Z | 2022-03-22T21:38:33.000Z | dense_map/volumetric_mapper/src/volumetric_mapper.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | 6 | 2021-12-03T02:38:21.000Z | 2022-02-23T01:52:03.000Z | /* Copyright (c) 2021, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The "ISAAC - Integrated System for Autonomous and Adaptive Caretaking
* platform" software is licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
// Shared project includes
#include <volumetric_mapper/volumetric_mapper.h>
namespace volumetric_mapper {
VolumetricMapper::VolumetricMapper(ros::NodeHandle* nh, std::string topic, double resolution,
double min_intensity, double max_intensity, double transparency, double offset) {
// Initialize mutex
mtx_ = new std::mutex();
// Define the map printing resolution
resolution_ = resolution;
min_intensity_ = min_intensity;
max_intensity_ = max_intensity;
transparency_ = transparency;
offset_ = offset;
// libgp::GaussianProcess gp(3, "CovSum ( CovSEiso, CovNoise)");
gp_ = new libgp::GaussianProcess(3, "CovSum ( CovSEiso, CovNoise)");
// initialize hyper parameter vector
Eigen::VectorXd params(gp_->covf().get_param_dim());
params << 0, 0, -1.6;
// Set parameters of covariance function
gp_->covf().set_loghyper(params);
// Hyperparameter optimizer
rprop_.init();
// Add publisher
publisher_ = nh->advertise<visualization_msgs::Marker>(
topic, 1, true);
}
VolumetricMapper::~VolumetricMapper() {}
// Add new point to the mapping iterpolation
void VolumetricMapper::AddMapData(double value, geometry_msgs::TransformStamped tf) {
// Convert from tf to vector to feed into gp regression
double x[] = {tf.transform.translation.x, tf.transform.translation.y, tf.transform.translation.z};
// Lock this operation to make interpolation effective
mtx_->lock();
gp_->add_pattern(x, static_cast<double>(value) + offset_);
mtx_->unlock();
}
// Publishes the map into a marker vector for visualization
void VolumetricMapper::PubMapData(double x_min, double x_max,
double y_min, double y_max, double z_min, double z_max) {
// Round the dimentions to fit the map resolution
x_min = roundPartial(x_min, resolution_);
x_max = roundPartial(x_max, resolution_);
y_min = roundPartial(y_min, resolution_);
y_max = roundPartial(y_max, resolution_);
z_min = roundPartial(z_min, resolution_);
z_max = roundPartial(z_max, resolution_);
// Position to interpolate map data
double x[] = {0, 0, 0};
// Initialize marker message
visualization_msgs::Marker marker;
// Fill in marker properties
marker.header.frame_id = "world";
marker.header.stamp = ros::Time::now();
marker.ns = "";
marker.id = 0;
marker.type = visualization_msgs::Marker::CUBE_LIST;
marker.scale.x = resolution_;
marker.scale.y = resolution_;
marker.scale.z = resolution_;
marker.pose.orientation.w = 1.0;
marker.action = visualization_msgs::Marker::ADD;
// Faster if we allocate the exact necessary size from beginning instead of appending
const int map_dim = (std::floor((x_max-x_min)/resolution_) + 1)
* (std::floor((y_max-y_min)/resolution_) + 1)
* (std::floor((z_max-z_min)/resolution_) + 1);
marker.colors.resize(map_dim);
marker.points.resize(map_dim);
// Lock such that the map does not change and computation is quicker
// Interpolation will only run once if no more data is added
int index = 0;
mtx_->lock();
// Maximize hyperparameters
// rprop_.maximize(gp_, 100, 1);
// ROS_ERROR_STREAM("0: " << gp_->covf().get_loghyper()(0) << " 1: " << gp_->covf().get_loghyper()(1)
// << " 2: " << gp_->covf().get_loghyper()(2));
// Assert if the optimization maes sense (enough measures)
// if (gp_->covf().get_loghyper()(0) > 0 && gp_->covf().get_loghyper()(0) < 5 &&
// gp_->covf().get_loghyper()(1) > 1 && gp_->covf().get_loghyper()(1) < 5)
// return;
for (double i = x_min; i < x_max; i += resolution_) {
for (double j = y_min; j < y_max; j += resolution_) {
for (double k = z_min; k < z_max; k += resolution_) {
// New marker point
marker.points[index].x = i;
marker.points[index].y = j;
marker.points[index].z = k;
// Calculate intensity
x[0] = i; x[1] = j; x[2] = k;
const double f = gp_->f(x) - offset_;
if (f < min_intensity_)
continue;
// Define Marker Color
const double h = (1.0 - std::min(std::max((f - min_intensity_)/
(max_intensity_ - min_intensity_), 0.0), 1.0));
marker.colors[index] = intensityMapColor(h, 0.02);
// Increment counter
index++;
// ROS_ERROR_STREAM(topic_ << " index " << index);
}
}
}
mtx_->unlock();
// Publish
publisher_.publish(marker);
}
} // namespace volumetric_mapper
| 37.304054 | 105 | 0.644811 | oleg-alexandrov |
983c1b878efed132e65028ff5e1119bce5e830f9 | 3,608 | cpp | C++ | hphp/compiler/statement/class_constant.cpp | kkopachev/hhvm | a9f242ec029c37b1e9d1715b13661e66293d87ab | [
"PHP-3.01",
"Zend-2.0"
] | 2 | 2019-09-01T19:40:10.000Z | 2019-10-18T13:30:30.000Z | hphp/compiler/statement/class_constant.cpp | alisha/hhvm | 523dc33b444bd5b59695eff2b64056629b0ed523 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2018-12-16T15:39:15.000Z | 2018-12-16T15:39:16.000Z | hphp/compiler/statement/class_constant.cpp | alisha/hhvm | 523dc33b444bd5b59695eff2b64056629b0ed523 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2020-12-30T13:22:47.000Z | 2020-12-30T13:22:47.000Z | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/statement/class_constant.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/expression/assignment_expression.h"
#include "hphp/compiler/expression/class_constant_expression.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/type_annotation.h"
using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
ClassConstant::ClassConstant
(STATEMENT_CONSTRUCTOR_PARAMETERS, std::string typeConstraint,
ExpressionListPtr exp, bool abstract,
bool typeconst, TypeAnnotationPtr typeAnnot)
: Statement(STATEMENT_CONSTRUCTOR_PARAMETER_VALUES(ClassConstant)),
m_typeConstraint(typeConstraint), m_exp(exp), m_abstract(abstract),
m_typeconst(typeconst) {
// for now only store TypeAnnotation info for type constants
if (typeconst && typeAnnot) {
m_typeStructure = Array(typeAnnot->getScalarArrayRep());
assertx(m_typeStructure.isDictOrDArray());
}
}
StatementPtr ClassConstant::clone() {
ClassConstantPtr stmt(new ClassConstant(*this));
stmt->m_exp = Clone(m_exp);
return stmt;
}
///////////////////////////////////////////////////////////////////////////////
// parser functions
void ClassConstant::onParseRecur(AnalysisResultConstRawPtr /*ar*/,
FileScopeRawPtr fs, ClassScopePtr scope) {
if (scope->isTrait()) {
parseTimeFatal(fs,
"Traits cannot have constants");
}
}
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
ConstructPtr ClassConstant::getNthKid(int n) const {
switch (n) {
case 0:
return m_exp;
default:
assert(false);
break;
}
return ConstructPtr();
}
int ClassConstant::getKidCount() const {
return 1;
}
void ClassConstant::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exp = dynamic_pointer_cast<ExpressionList>(cp);
break;
default:
assert(false);
break;
}
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
void ClassConstant::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
if (isAbstract()) {
cg_printf("abstract ");
}
cg_printf("const ");
if (isTypeconst()) {
cg_printf("type ");
}
m_exp->outputPHP(cg, ar);
cg_printf(";\n");
}
| 33.719626 | 79 | 0.561253 | kkopachev |
983d4a9a9f304a7d065a213220ce7e29bd7c02fc | 1,147 | cpp | C++ | csapex_vision_features/src/register_plugin.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 2 | 2016-09-02T15:33:22.000Z | 2019-05-06T22:09:33.000Z | csapex_vision_features/src/register_plugin.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 1 | 2021-02-14T19:53:30.000Z | 2021-02-14T19:53:30.000Z | csapex_vision_features/src/register_plugin.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 6 | 2016-10-12T00:55:23.000Z | 2021-02-10T17:49:25.000Z | /// HEADER
#include "register_plugin.h"
/// COMPONENT
#include <csapex/factory/generic_node_factory.hpp>
#include <csapex/factory/node_factory_impl.h>
#include <csapex/msg/generic_value_message.hpp>
#include <csapex_vision_features/descriptor_message.h>
#include <csapex_vision_features/keypoint_message.h>
/// PROJECT
#include <csapex/factory/message_factory.h>
#include <csapex/model/tag.h>
#include <csapex_opencv/yaml_io.hpp>
/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>
CSAPEX_REGISTER_CLASS(csapex::RegisterVisionFeaturePlugin, csapex::CorePlugin)
using namespace csapex;
RegisterVisionFeaturePlugin::RegisterVisionFeaturePlugin()
{
}
void rotateKeypoint(const connection_types::GenericValueMessage<cv::KeyPoint>& input, connection_types::GenericValueMessage<cv::KeyPoint>& output)
{
output = input;
}
void RegisterVisionFeaturePlugin::init(CsApexCore& core)
{
Tag::createIfNotExists("Features");
auto c = GenericNodeFactory::createConstructorFromFunction(rotateKeypoint, "rotateKeypoint");
c->setDescription("Test function for rotating a keypoint");
core.getNodeFactory()->registerNodeType(c);
}
| 28.675 | 146 | 0.79599 | AdrianZw |
983d8c0c9ed31633a81b5602348ec12912d6c2de | 11,936 | inl | C++ | include/Nazara/Core/Signal.inl | waruqi/NazaraEngine | a64de1ffe8b0790622a0b1cae5759c96b4f86907 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 376 | 2015-01-09T03:14:48.000Z | 2022-03-26T17:59:18.000Z | include/Nazara/Core/Signal.inl | waruqi/NazaraEngine | a64de1ffe8b0790622a0b1cae5759c96b4f86907 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 252 | 2015-01-21T17:34:39.000Z | 2022-03-20T16:15:50.000Z | include/Nazara/Core/Signal.inl | waruqi/NazaraEngine | a64de1ffe8b0790622a0b1cae5759c96b4f86907 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 104 | 2015-01-18T11:03:41.000Z | 2022-03-11T05:40:47.000Z | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/Error.hpp>
#include <utility>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::Signal
* \brief Core class that represents a signal, a list of objects waiting for its message
*/
/*!
* \brief Constructs a Signal object by default
*/
template<typename... Args>
Signal<Args...>::Signal() :
m_slotIterator(0)
{
}
/*!
* \brief Constructs a Signal object by default
*
* \remark It doesn't make sense to copy a signal, this is only available for convenience to allow compiler-generated copy constructors
*/
template<typename ...Args>
Signal<Args...>::Signal(const Signal&) :
Signal()
{
}
/*!
* \brief Constructs a Signal object by move semantic
*
* \param signal Signal to move in this
*/
template<typename... Args>
Signal<Args...>::Signal(Signal&& signal) noexcept
{
operator=(std::move(signal));
}
/*!
* \brief Clears the list of actions attached to the signal
*/
template<typename... Args>
void Signal<Args...>::Clear()
{
m_slots.clear();
m_slotIterator = 0;
}
/*!
* \brief Connects a function to the signal
* \return Connection attached to the signal
*
* \param func Non-member function
*/
template<typename... Args>
typename Signal<Args...>::Connection Signal<Args...>::Connect(const Callback& func)
{
return Connect(Callback(func));
}
/*!
* \brief Connects a function to the signal
* \return Connection attached to the signal
*
* \param func Non-member function
*/
template<typename... Args>
typename Signal<Args...>::Connection Signal<Args...>::Connect(Callback&& func)
{
NazaraAssert(func, "Invalid function");
// Since we're incrementing the slot vector size, we need to replace our iterator at the end
// (Except when we are iterating on the signal)
bool resetIt = (m_slotIterator >= m_slots.size());
auto tempPtr = std::make_shared<Slot>(this);
tempPtr->callback = std::move(func);
tempPtr->index = m_slots.size();
m_slots.emplace_back(std::move(tempPtr));
if (resetIt)
m_slotIterator = m_slots.size(); //< Replace the iterator to the end
return Connection(m_slots.back());
}
/*!
* \brief Connects a member function and its object to the signal
* \return Connection attached to the signal
*
* \param object Object to send the message
* \param method Member function
*/
template<typename... Args>
template<typename O>
typename Signal<Args...>::Connection Signal<Args...>::Connect(O& object, void (O::*method) (Args...))
{
return Connect([&object, method] (Args&&... args)
{
return (object .* method) (std::forward<Args>(args)...);
});
}
/*!
* \brief Connects a member function and its object to the signal
* \return Connection attached to the signal
*
* \param object Object to send the message
* \param method Member function
*/
template<typename... Args>
template<typename O>
typename Signal<Args...>::Connection Signal<Args...>::Connect(O* object, void (O::*method)(Args...))
{
return Connect([object, method] (Args&&... args)
{
return (object ->* method) (std::forward<Args>(args)...);
});
}
/*!
* \brief Connects a member function and its object to the signal
* \return Connection attached to the signal
*
* \param object Object to send the message
* \param method Member function
*/
template<typename... Args>
template<typename O>
typename Signal<Args...>::Connection Signal<Args...>::Connect(const O& object, void (O::*method) (Args...) const)
{
return Connect([&object, method] (Args&&... args)
{
return (object .* method) (std::forward<Args>(args)...);
});
}
/*!
* \brief Connects a member function and its object to the signal
* \return Connection attached to the signal
*
* \param object Object to send the message
* \param method Member function
*/
template<typename... Args>
template<typename O>
typename Signal<Args...>::Connection Signal<Args...>::Connect(const O* object, void (O::*method)(Args...) const)
{
return Connect([object, method] (Args&&... args)
{
return (object ->* method) (std::forward<Args>(args)...);
});
}
/*!
* \brief Applies the list of arguments to every callback functions
*
* \param args Arguments to send with the message
*/
template<typename... Args>
void Signal<Args...>::operator()(Args... args) const
{
for (m_slotIterator = 0; m_slotIterator < m_slots.size(); ++m_slotIterator)
m_slots[m_slotIterator]->callback(args...);
}
/*!
* \brief Doesn't do anything
* \return A reference to this
*
* \remark This is only for convenience to allow compiled-generated assignation operator
*/
template<typename... Args>
Signal<Args...>& Signal<Args...>::operator=(const Signal&)
{
return *this;
}
/*!
* \brief Moves the signal into this
* \return A reference to this
*
* \param signal Signal to move in this
*/
template<typename... Args>
Signal<Args...>& Signal<Args...>::operator=(Signal&& signal) noexcept
{
m_slots = std::move(signal.m_slots);
m_slotIterator = signal.m_slotIterator;
// We need to update the signal pointer inside of each slot
for (SlotPtr& slot : m_slots)
slot->signal = this;
return *this;
}
/*!
* \brief Disconnects a listener from this signal
*
* \param slot Pointer to the ith listener of the signal
*
* \remark Produces a NazaraAssert if slot is invalid (nullptr)
* \remark Produces a NazaraAssert if index of slot is invalid
* \remark Produces a NazaraAssert if slot is not attached to this signal
*/
template<typename... Args>
void Signal<Args...>::Disconnect(const SlotPtr& slot) noexcept
{
NazaraAssert(slot, "Invalid slot pointer");
NazaraAssert(slot->index < m_slots.size(), "Invalid slot index");
NazaraAssert(slot->signal == this, "Slot is not attached to this signal");
// "Swap this slot with the last one and pop" idiom
// This will preserve slot indexes
// Can we safely "remove" this slot?
if (m_slotIterator >= (m_slots.size() - 1) || slot->index > m_slotIterator)
{
// Yes we can
SlotPtr& newSlot = m_slots[slot->index];
newSlot = std::move(m_slots.back());
newSlot->index = slot->index; //< Update the moved slot index before resizing (in case it's the last one)
}
else
{
// Nope, let's be tricky
SlotPtr& current = m_slots[m_slotIterator];
SlotPtr& newSlot = m_slots[slot->index];
newSlot = std::move(current);
newSlot->index = slot->index; //< Update the moved slot index
current = std::move(m_slots.back());
current->index = m_slotIterator; //< Update the moved slot index
--m_slotIterator;
}
// Pop the last entry (from where we moved our slot)
m_slots.pop_back();
}
/*!
* \class Nz::Signal::Connection
* \brief Core class that represents a connection attached to a signal
*/
/*!
* \brief Constructs a Signal::Connection object with by move semantic
*
* \param connection Connection object to move
*/
template<typename... Args>
Signal<Args...>::Connection::Connection(Connection&& connection) noexcept :
m_ptr(std::move(connection.m_ptr))
{
connection.m_ptr.reset(); //< Fuck you GCC 4.9
}
/*!
* \brief Constructs a Signal::Connection object with a slot
*
* \param slot Slot of the listener
*/
template<typename... Args>
Signal<Args...>::Connection::Connection(const SlotPtr& slot) :
m_ptr(slot)
{
}
/*!
* \brief Connects to a signal with arguments
*
* \param signal New signal to listen
* \param args Arguments for the signal
*/
template<typename... Args>
template<typename... ConnectArgs>
void Signal<Args...>::Connection::Connect(BaseClass& signal, ConnectArgs&&... args)
{
operator=(signal.Connect(std::forward<ConnectArgs>(args)...));
}
/*!
* \brief Disconnects the connection from the signal
*/
template<typename... Args>
void Signal<Args...>::Connection::Disconnect() noexcept
{
if (SlotPtr ptr = m_ptr.lock())
ptr->signal->Disconnect(ptr);
}
/*!
* \brief Checks whether the connection is still active with the signal
* \return true if signal is still active
*/
template<typename... Args>
bool Signal<Args...>::Connection::IsConnected() const
{
return !m_ptr.expired();
}
/*!
* \brief Constructs a Signal::ConnectionGuard object by move semantic
*
* \param connection Connection to move
*/
template<typename... Args>
typename Signal<Args...>::Connection& Signal<Args...>::Connection::operator=(Connection&& connection) noexcept
{
m_ptr = std::move(connection.m_ptr);
connection.m_ptr.reset(); //< Fuck you GCC 4.9
return *this;
}
/*!
* \class Nz::Signal::ConnectionGuard
* \brief Core class that represents a RAII for a connection attached to a signal
*/
/*!
* \brief Constructs a Signal::ConnectionGuard object with a connection
*
* \param connection Connection for the scope
*/
template<typename... Args>
Signal<Args...>::ConnectionGuard::ConnectionGuard(const Connection& connection) :
m_connection(connection)
{
}
/*!
* \brief Constructs a Signal::ConnectionGuard object with a connection by move semantic
*
* \param connection Connection for the scope
*/
template<typename... Args>
Signal<Args...>::ConnectionGuard::ConnectionGuard(Connection&& connection) :
m_connection(std::move(connection))
{
}
/*!
* \brief Destructs the object and disconnects the connection
*/
template<typename... Args>
Signal<Args...>::ConnectionGuard::~ConnectionGuard()
{
m_connection.Disconnect();
}
/*!
* \brief Connects to a signal with arguments
*
* \param signal New signal to listen
* \param args Arguments for the signal
*/
template<typename... Args>
template<typename... ConnectArgs>
void Signal<Args...>::ConnectionGuard::Connect(BaseClass& signal, ConnectArgs&&... args)
{
m_connection.Disconnect();
m_connection.Connect(signal, std::forward<ConnectArgs>(args)...);
}
/*!
* \brief Disconnects the connection from the signal
*/
template<typename... Args>
void Signal<Args...>::ConnectionGuard::Disconnect() noexcept
{
m_connection.Disconnect();
}
/*!
* \brief Gets the connection attached to the signal
* \return Connection of the signal
*/
template<typename... Args>
typename Signal<Args...>::Connection& Signal<Args...>::ConnectionGuard::GetConnection()
{
return m_connection;
}
/*!
* \brief Checks whether the connection is still active with the signal
* \return true if signal is still active
*/
template<typename... Args>
bool Signal<Args...>::ConnectionGuard::IsConnected() const
{
return m_connection.IsConnected();
}
/*!
* \brief Assigns the connection into this
* \return A reference to this
*
* \param connection Connection to assign into this
*/
template<typename... Args>
typename Signal<Args...>::ConnectionGuard& Signal<Args...>::ConnectionGuard::operator=(const Connection& connection)
{
m_connection.Disconnect();
m_connection = connection;
return *this;
}
/*!
* \brief Moves the Connection into this
* \return A reference to this
*
* \param connection Connection to move in this
*/
template<typename... Args>
typename Signal<Args...>::ConnectionGuard& Signal<Args...>::ConnectionGuard::operator=(Connection&& connection)
{
if (&connection != this)
{
m_connection.Disconnect();
m_connection = std::move(connection);
}
return *this;
}
/*!
* \brief Moves the ConnectionGuard into this
* \return A reference to this
*
* \param connection ConnectionGuard to move in this
*/
template<typename... Args>
typename Signal<Args...>::ConnectionGuard& Signal<Args...>::ConnectionGuard::operator=(ConnectionGuard&& connection) noexcept
{
if (&connection != this)
{
m_connection.Disconnect();
m_connection = std::move(connection.m_connection);
}
return *this;
}
}
#include <Nazara/Core/DebugOff.hpp>
| 24.559671 | 135 | 0.686578 | waruqi |
983dab5f068bff4b81bd7f44ac96076516cd4ef9 | 1,102 | cpp | C++ | service/src/SharedMemoryScopedLock.cpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | service/src/SharedMemoryScopedLock.cpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | service/src/SharedMemoryScopedLock.cpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2015 - 2022, Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "config.h"
#include "geopm/SharedMemoryScopedLock.hpp"
#include <iostream>
#include "geopm/Exception.hpp"
namespace geopm
{
SharedMemoryScopedLock::SharedMemoryScopedLock(pthread_mutex_t *mutex)
: m_mutex(mutex)
{
if (m_mutex == nullptr) {
throw Exception("SharedMemoryScopedLock(): mutex cannot be NULL",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
int err = pthread_mutex_lock(m_mutex); // Default mutex will block until this completes.
if (err) {
throw Exception("SharedMemoryScopedLock(): pthread_mutex_lock() failed:", err, __FILE__, __LINE__);
}
}
SharedMemoryScopedLock::~SharedMemoryScopedLock()
{
int err = pthread_mutex_unlock(m_mutex);
if (err != 0) {
#ifdef GEOPM_DEBUG
std::cerr << "Warning: <geopm> pthread_mutex_unlock() failed with error: "
<< geopm::error_message(err) << std::endl;
#endif
}
}
}
| 30.611111 | 111 | 0.625227 | avilcheslopez |
983f29fcf4077739e40f1bb8cb78bbfb7c3f7d2f | 837 | cc | C++ | sync/internal_api/public/non_blocking_sync_common.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | sync/internal_api/public/non_blocking_sync_common.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | sync/internal_api/public/non_blocking_sync_common.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sync/internal_api/public/non_blocking_sync_common.h"
namespace syncer {
DataTypeState::DataTypeState() : next_client_id(0), initial_sync_done(false) {
}
DataTypeState::~DataTypeState() {
}
CommitRequestData::CommitRequestData()
: sequence_number(0),
base_version(0),
deleted(false) {
}
CommitRequestData::~CommitRequestData() {
}
CommitResponseData::CommitResponseData()
: sequence_number(0),
response_version(0) {
}
CommitResponseData::~CommitResponseData() {
}
UpdateResponseData::UpdateResponseData()
: response_version(0),
deleted(false) {
}
UpdateResponseData::~UpdateResponseData() {
}
} // namespace syncer
| 20.414634 | 78 | 0.732378 | kjthegod |
983f46aeeba033a9d84c6d7faeb1e26484552933 | 7,369 | cpp | C++ | QTDialogs/SceneEditorTab/SceneEditorTab.cpp | msolids/musen | 67d9a70d03d771ccda649c21b78d165684e31171 | [
"BSD-3-Clause"
] | 19 | 2020-09-28T07:22:50.000Z | 2022-03-07T09:52:20.000Z | QTDialogs/SceneEditorTab/SceneEditorTab.cpp | LasCondes/musen | 18961807928285ff802e050050f4c627dd7bec1e | [
"BSD-3-Clause"
] | 5 | 2020-12-26T18:18:27.000Z | 2022-02-23T22:56:43.000Z | QTDialogs/SceneEditorTab/SceneEditorTab.cpp | LasCondes/musen | 18961807928285ff802e050050f4c627dd7bec1e | [
"BSD-3-Clause"
] | 11 | 2020-11-02T11:32:03.000Z | 2022-01-27T08:22:04.000Z | /* Copyright (c) 2013-2020, MUSEN Development Team. All rights reserved.
This file is part of MUSEN framework http://msolids.net/musen.
See LICENSE file for license and warranty information. */
#include "SceneEditorTab.h"
#include <QMessageBox>
CSceneEditorTab::CSceneEditorTab(QWidget *parent /*= 0*/) : CMusenDialog(parent)
{
ui.setupUi(this);
QVector<QWidget*> labels;
labels.push_back(ui.setCenterOfMass);
labels.push_back(ui.labelRotation);
labels.push_back(ui.labelAngle);
labels.push_back(ui.labelOffset);
labels.push_back(ui.labelVelocity);
int maxWidth = (*std::max_element(labels.begin(), labels.end(), [](const QWidget* l, const QWidget* r) { return (l->width() < r->width()); }))->width();
for (QWidget* w : labels)
w->setFixedWidth(maxWidth);
m_bAllowUndoFunction = false;
connect(ui.rotateSystem, &QPushButton::clicked, this, &CSceneEditorTab::RotateSystem);
connect(ui.undoRotation, &QPushButton::clicked, this, &CSceneEditorTab::UndoRotation);
connect(ui.setCenterOfMass, &QPushButton::clicked, this, &CSceneEditorTab::SetCenterOfMass);
connect(ui.moveSystem, &QPushButton::clicked, this, &CSceneEditorTab::MoveSystem);
connect(ui.setVelocity, &QPushButton::clicked, this, &CSceneEditorTab::SetVelocity);
connect(ui.groupBoxPBC, &QGroupBox::toggled, this, &CSceneEditorTab::SetPBC);
connect(ui.checkBoxPBCX, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetPBC);
connect(ui.checkBoxPBCY, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetPBC);
connect(ui.checkBoxPBCZ, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditPBCMinX, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditPBCMinY, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditPBCMinZ, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditPBCMaxX, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditPBCMaxY, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditPBCMaxZ, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditVelocityX, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditVelocityY, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.lineEditVelocityZ, &QLineEdit::editingFinished, this, &CSceneEditorTab::SetPBC);
connect(ui.checkBoxAnisotropy, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetAnisotropy);
connect(ui.checkBoxContactRadius, &QCheckBox::stateChanged, this, &CSceneEditorTab::SetContactRadius);
}
void CSceneEditorTab::setVisible( bool _bVisible )
{
if (!_bVisible)
m_bAllowUndoFunction = false;
CMusenDialog::setVisible(_bVisible);
}
void CSceneEditorTab::UpdateWholeView()
{
ui.undoRotation->setEnabled(m_bAllowUndoFunction);
ShowConvLabel(ui.labelCenterX, "X", EUnitType::LENGTH);
ShowConvLabel(ui.labelCenterY, "Y", EUnitType::LENGTH);
ShowConvLabel(ui.labelCenterZ, "Z", EUnitType::LENGTH);
ShowConvLabel(ui.labelOffsetX, "X", EUnitType::LENGTH);
ShowConvLabel(ui.labelOffsetY, "Y", EUnitType::LENGTH);
ShowConvLabel(ui.labelOffsetZ, "Z", EUnitType::LENGTH);
ShowConvLabel(ui.labelVelocityX, "Vx", EUnitType::VELOCITY);
ShowConvLabel(ui.labelVelocityY, "Vy", EUnitType::VELOCITY);
ShowConvLabel(ui.labelVelocityZ, "Vz", EUnitType::VELOCITY);
ShowConvLabel(ui.labelPBCMin, "Min", EUnitType::LENGTH);
ShowConvLabel(ui.labelPBCMax, "Max", EUnitType::LENGTH);
ShowConvLabel(ui.labelPBCVel, "Velocity", EUnitType::VELOCITY);
UpdatePBC();
ui.checkBoxAnisotropy->setChecked(m_pSystemStructure->IsAnisotropyEnabled());
ui.checkBoxContactRadius->setChecked(m_pSystemStructure->IsContactRadiusEnabled());
}
void CSceneEditorTab::SetCenterOfMass()
{
ShowConvValue(ui.lineEditCenterX, ui.lineEditCenterY, ui.lineEditCenterZ, m_pSystemStructure->GetCenterOfMass(0), EUnitType::LENGTH);
}
void CSceneEditorTab::RotateSystem()
{
m_RotationCenter = GetConvValue(ui.lineEditCenterX, ui.lineEditCenterY, ui.lineEditCenterZ, EUnitType::LENGTH);
m_RotationAngle = GetConvValue(ui.lineEditAngleX, ui.lineEditAngleY, ui.lineEditAngleZ, EUnitType::NONE ) * PI / 180;
m_pSystemStructure->ClearAllStatesFrom(0);
m_pSystemStructure->RotateSystem(0, m_RotationCenter, m_RotationAngle);
m_bAllowUndoFunction = true;
UpdateWholeView();
emit UpdateOpenGLView();
}
void CSceneEditorTab::MoveSystem()
{
m_pSystemStructure->ClearAllStatesFrom(0);
m_pSystemStructure->MoveSystem(0, GetConvValue(ui.lineEditOffsetX, ui.lineEditOffsetY, ui.lineEditOffsetZ, EUnitType::LENGTH));
UpdateWholeView();
emit UpdateOpenGLView();
}
void CSceneEditorTab::SetVelocity()
{
m_pSystemStructure->ClearAllStatesFrom(0);
m_pSystemStructure->SetSystemVelocity(0, GetConvValue(ui.lineEditVelocityX, ui.lineEditVelocityY, ui.lineEditVelocityZ, EUnitType::VELOCITY));
UpdateWholeView();
emit UpdateOpenGLView();
}
void CSceneEditorTab::UndoRotation()
{
m_pSystemStructure->RotateSystem(0, m_RotationCenter, m_RotationAngle * (-1));
UpdateWholeView();
emit UpdateOpenGLView();
}
void CSceneEditorTab::SetPBC()
{
if (m_bAvoidSignal) return;
if (m_pSystemStructure->GetNumberOfSpecificObjects(SOLID_BOND) != 0)
QMessageBox::information(this, ("Bonds over PBC"), ("Modification of PBC will influence existing solid bonds!"), QMessageBox::Ok);
SPBC pbcNew;
pbcNew.bEnabled = ui.groupBoxPBC->isChecked();
pbcNew.bX = ui.checkBoxPBCX->isChecked();
pbcNew.bY = ui.checkBoxPBCY->isChecked();
pbcNew.bZ = ui.checkBoxPBCZ->isChecked();
pbcNew.SetDomain(GetConvValue(ui.lineEditPBCMinX, ui.lineEditPBCMinY, ui.lineEditPBCMinZ, EUnitType::LENGTH), GetConvValue(ui.lineEditPBCMaxX, ui.lineEditPBCMaxY, ui.lineEditPBCMaxZ, EUnitType::LENGTH));
pbcNew.vVel = GetConvValue(ui.lineEditVelX, ui.lineEditVelY, ui.lineEditVelZ, EUnitType::VELOCITY);
m_pSystemStructure->SetPBC(pbcNew);
UpdateWholeView();
emit UpdateOpenGLView();
}
void CSceneEditorTab::UpdatePBC()
{
m_bAvoidSignal = true;
const SPBC& pbc = m_pSystemStructure->GetPBC();
ui.groupBoxPBC->setChecked(pbc.bEnabled);
ShowConvValue( ui.lineEditPBCMinX, ui.lineEditPBCMinY, ui.lineEditPBCMinZ, pbc.initDomain.coordBeg, EUnitType::LENGTH);
ShowConvValue( ui.lineEditPBCMaxX, ui.lineEditPBCMaxY, ui.lineEditPBCMaxZ, pbc.initDomain.coordEnd, EUnitType::LENGTH);
ShowConvValue( ui.lineEditVelX, ui.lineEditVelY, ui.lineEditVelZ, pbc.vVel, EUnitType::VELOCITY);
ui.checkBoxPBCX->setChecked(pbc.bX);
ui.lineEditPBCMinX->setEnabled(pbc.bX && pbc.bEnabled);
ui.lineEditPBCMaxX->setEnabled(pbc.bX && pbc.bEnabled);
ui.lineEditVelX->setEnabled(pbc.bX && pbc.bEnabled);
ui.checkBoxPBCY->setChecked(pbc.bY);
ui.lineEditPBCMinY->setEnabled(pbc.bY && pbc.bEnabled);
ui.lineEditPBCMaxY->setEnabled(pbc.bY && pbc.bEnabled);
ui.lineEditVelY->setEnabled(pbc.bY && pbc.bEnabled);
ui.checkBoxPBCZ->setChecked(pbc.bZ);
ui.lineEditPBCMinZ->setEnabled(pbc.bZ && pbc.bEnabled);
ui.lineEditPBCMaxZ->setEnabled(pbc.bZ && pbc.bEnabled);
ui.lineEditVelZ->setEnabled(pbc.bZ && pbc.bEnabled);
m_bAvoidSignal = false;
}
void CSceneEditorTab::SetAnisotropy()
{
m_pSystemStructure->EnableAnisotropy(ui.checkBoxAnisotropy->isChecked());
}
void CSceneEditorTab::SetContactRadius()
{
m_pSystemStructure->EnableContactRadius(ui.checkBoxContactRadius->isChecked());
emit ContactRadiusEnabled();
}
| 41.398876 | 204 | 0.780703 | msolids |
9846bd5882d147f78ebdab29031e533a267552fb | 567 | hpp | C++ | include/Pomdog/Async/ImmediateScheduler.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | include/Pomdog/Async/ImmediateScheduler.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | include/Pomdog/Async/ImmediateScheduler.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_IMMEDIATESCHEDULER_6ABB0F4A_HPP
#define POMDOG_IMMEDIATESCHEDULER_6ABB0F4A_HPP
#include "Pomdog/Async/Scheduler.hpp"
namespace Pomdog {
namespace Concurrency {
class POMDOG_EXPORT ImmediateScheduler final : public Scheduler {
public:
void Schedule(
std::function<void()> && task,
const Duration& delayTime) override;
};
} // namespace Concurrency
} // namespace Pomdog
#endif // POMDOG_IMMEDIATESCHEDULER_6ABB0F4A_HPP
| 24.652174 | 70 | 0.767196 | bis83 |
98472f0fd30d73eb4c5e25a0bd27a6101d1a3d50 | 100 | cpp | C++ | Glop/OsLinux_TerribleXPassthrough.cpp | zorbathut/glop | 762d4f1e070ce9c7180a161b521b05c45bde4a63 | [
"BSD-3-Clause"
] | 1 | 2016-06-28T18:19:30.000Z | 2016-06-28T18:19:30.000Z | Glop/OsLinux_TerribleXPassthrough.cpp | zorbathut/glop | 762d4f1e070ce9c7180a161b521b05c45bde4a63 | [
"BSD-3-Clause"
] | null | null | null | Glop/OsLinux_TerribleXPassthrough.cpp | zorbathut/glop | 762d4f1e070ce9c7180a161b521b05c45bde4a63 | [
"BSD-3-Clause"
] | null | null | null |
#include "GlopWindow.h"
void WindowDashDestroy() {
LOGF("DESTROYING");
window()->Destroy();
}
| 12.5 | 26 | 0.66 | zorbathut |
984743eb1d9401ed2994b7146a29fcb0f743dbfc | 464 | cpp | C++ | Bots/DiversifyBot/DiversifyBot.cpp | Skibisky/InvestorBadness | 44f3a7477e83d5c53be10bc5a8ad537b06a78c81 | [
"MIT"
] | null | null | null | Bots/DiversifyBot/DiversifyBot.cpp | Skibisky/InvestorBadness | 44f3a7477e83d5c53be10bc5a8ad537b06a78c81 | [
"MIT"
] | null | null | null | Bots/DiversifyBot/DiversifyBot.cpp | Skibisky/InvestorBadness | 44f3a7477e83d5c53be10bc5a8ad537b06a78c81 | [
"MIT"
] | null | null | null | #include "DiversifyBot.h"
void DiversifyBot::Turn(std::vector<Contribution*> avail, int pts)
{
// point a point in every project
for each(auto inv in avail)
{
if (pts <= 0)
break;
if (inv->oldContrib == 0)
{
inv->myContrib++;
pts--;
}
}
// dump remaining points in projects we aren't even 5th in
for each(auto inv in avail)
{
if (inv->myRank > 5 && inv->contribs()[4] - inv->oldContrib < 3)
{
inv->myContrib++;
pts--;
}
}
}
| 16.571429 | 66 | 0.601293 | Skibisky |
9847b620b70486452d2670c88c88ef6015eda648 | 681 | hpp | C++ | school/TimeOfDay.hpp | Biyorne/learningcpp | bcf963990800ed939fa4cc1b30fadccaf098155b | [
"MIT"
] | null | null | null | school/TimeOfDay.hpp | Biyorne/learningcpp | bcf963990800ed939fa4cc1b30fadccaf098155b | [
"MIT"
] | null | null | null | school/TimeOfDay.hpp | Biyorne/learningcpp | bcf963990800ed939fa4cc1b30fadccaf098155b | [
"MIT"
] | null | null | null | #ifndef SCHOOL_TIMEOFDAY_HPP_INCLUDED
#define SCHOOL_TIMEOFDAY_HPP_INCLUDED
#include <string>
namespace school
{
class TimeOfDay
{
public:
TimeOfDay(const int HOUR, const int MINUTE, const int SECOND);
int hour() const { return m_hour; }
int minute() const { return m_minute; }
int second() const { return m_second; }
std::string toString() const;
private:
int m_hour;
int m_minute;
int m_second;
};
bool operator==(const TimeOfDay & L, const TimeOfDay & R);
bool operator!=(const TimeOfDay & L, const TimeOfDay & R);
} // namespace school
#endif // SCHOOL_TIMEOFDAY_HPP_INCLUDED
| 21.28125 | 70 | 0.646109 | Biyorne |
984b834d5adecfd4b2b2996578579a83de78b2a6 | 1,392 | cpp | C++ | CONTESTS/LIGHT OJ/light oj ramadan 2016/E.cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | 1 | 2021-11-22T02:26:43.000Z | 2021-11-22T02:26:43.000Z | CONTESTS/LIGHT OJ/light oj ramadan 2016/E.cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | CONTESTS/LIGHT OJ/light oj ramadan 2016/E.cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
char bin[100];
long long xtod(string str, long long base)
{
long long n=1,num=0;
for(int i =str.length()-1; i>=0; i--)
{
int x;
if(str[i]=='A')
x=10;
else if(str[i]=='B')
x=11;
else if(str[i]=='C')
x=12;
else if(str[i]=='D')
x=13;
else if(str[i]=='E')
x=14;
else if(str[i]=='F')
x=15;
else
x = str[i]-'0';
num+=(n*x);
n*=base;
}
return num;
}
void stringRev(char str[],int len) {
int half = len/2;
//printf("%s len %d\n",bin,len);
for(int i=0; i<half; i++)
swap(bin[i],bin[--len]);
}
void dtox(long long n, long long base) {
int i=0;
while(n>0)
{
int x =(n%base);
if(x>9)
bin[i++] = (x-10)+'A';
else
bin[i++] = x +'0';
n/=base;
}
if(i==0)
bin[i++] ='0';
bin[i]='\0';
stringRev(bin,strlen(bin));
}
int main ()
{
long long s,e;
string str;
int t;
scanf("%d",&t);
while(t--)
{
cin>>str>>s>>e;
s=xtod(str,s);
// printf("%lld\n",s);
dtox(s,e);
printf("%s\n",bin);
}
return 0;
}
| 16.376471 | 43 | 0.368534 | priojeetpriyom |
984e6cc1a7ca2389888b403378fcb8b376add0d2 | 38,327 | cpp | C++ | isis/src/qisis/objs/RubberBandTool/RubberBandTool.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | 1 | 2019-10-13T15:31:33.000Z | 2019-10-13T15:31:33.000Z | isis/src/qisis/objs/RubberBandTool/RubberBandTool.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | null | null | null | isis/src/qisis/objs/RubberBandTool/RubberBandTool.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | 1 | 2021-07-12T06:05:03.000Z | 2021-07-12T06:05:03.000Z | #include "RubberBandTool.h"
#include <cmath>
#include <float.h>
#include <QDebug>
#include <QList>
#include <QMessageBox>
#include <QPainter>
#include <QPen>
#include <QPoint>
#include <QRect>
#include "geos/geom/CoordinateArraySequence.h"
#include "geos/geom/CoordinateSequence.h"
#include "geos/geom/Coordinate.h"
#include "geos/geom/LineString.h"
#include "geos/geom/MultiLineString.h"
#include "geos/geom/Polygon.h"
#include "Angle.h"
#include "Constants.h"
#include "MdiCubeViewport.h"
#include "PolygonTools.h"
#include "SerialNumberList.h"
using namespace std;
namespace Isis {
/**
* This is the constructor. It's private because this class is a singleton.
*
* @param parent
*/
RubberBandTool::RubberBandTool(QWidget *parent) : Tool(parent) {
p_mouseLoc = NULL;
p_vertices = NULL;
p_mouseLoc = new QPoint;
p_vertices = new QList< QPoint >;
p_bandingMode = LineMode;
activate(false);
repaint();
}
RubberBandTool::~RubberBandTool() {
if(p_mouseLoc) {
delete p_mouseLoc;
p_mouseLoc = NULL;
}
if(p_vertices) {
delete p_vertices;
p_vertices = NULL;
}
}
/**
* This is the main paint method for the rubber bands.
*
* For angles and lines, simply connect the known vertices.vertices[0].x()
* For polygons, paint the vertices & close if completed the shape.
* For circles, figure out the circle's square and draw the circle inside of it.
* For EllipseModes, figure out the EllipseMode's rectangle and draw the circle inside of it.
* For rectangles, paint the rectangle either to the mouse or back to the start depending on if the shape is complete.
* For rotated rectangles, if we can interpolate extra sides draw them and draw all known sides.
*
* @param vp
* @param painter
*/
void RubberBandTool::paintViewport(MdiCubeViewport *vp, QPainter *painter) {
QPen pen(QColor(255, 0, 0));
QPen greenPen(QColor(0, 255, 0));
pen.setStyle(Qt::SolidLine);
greenPen.setStyle(Qt::SolidLine);
painter->setPen(pen);
if ( (vp != cubeViewport() && p_drawActiveOnly) ||
!(vp == cubeViewport() || (cubeViewport()->isLinked() &&
vp->isLinked()))) {
return;
}
switch(p_bandingMode) {
case AngleMode:
paintVerticesConnected(painter);
break;
case LineMode:
// if point needed, draw an X
if(figureIsPoint() && !p_tracking) {
painter->drawLine((*p_vertices)[0].x() - 10, (*p_vertices)[0].y() - 10,
(*p_vertices)[0].x() + 10, (*p_vertices)[0].y() + 10);
painter->drawLine((*p_vertices)[0].x() - 10, (*p_vertices)[0].y() + 10,
(*p_vertices)[0].x() + 10, (*p_vertices)[0].y() - 10);
}
else {
paintVerticesConnected(painter);
}
break;
case PolygonMode:
paintVerticesConnected(painter);
if(!p_tracking && p_vertices->size() > 0) {
painter->drawLine((*p_vertices)[0], (*p_vertices)[ p_vertices->size() - 1 ]);
}
break;
case CircleMode:
case EllipseMode: {
if(p_vertices->size() != 0) {
QList<QPoint> verticesList = vertices();
int width = 2 * (verticesList[1].x() - verticesList[0].x());
int height = 2 * (verticesList[1].y() - verticesList[0].y());
// upper left x,y,width,height
painter->drawEllipse(verticesList[0].x() - width / 2, verticesList[0].y() - height / 2,
width,
height
);
}
}
break;
case RectangleMode: {
if(figureIsPoint() && !p_tracking) {
painter->drawLine((*p_vertices)[0].x() - 10, (*p_vertices)[0].y() - 10,
(*p_vertices)[0].x() + 10, (*p_vertices)[0].y() + 10);
painter->drawLine((*p_vertices)[0].x() - 10, (*p_vertices)[0].y() + 10,
(*p_vertices)[0].x() + 10, (*p_vertices)[0].y() - 10);
}
else {
if(p_tracking && p_vertices->size() > 0) {
paintRectangle((*p_vertices)[0], *p_mouseLoc, painter);
}
else if(p_vertices->size() > 0) {
paintVerticesConnected(painter);
painter->drawLine((*p_vertices)[0], (*p_vertices)[ p_vertices->size() - 1 ]);
}
}
}
break;
case RotatedRectangleMode: {
if(p_vertices->size() == 2) {
QPoint missingVertex;
calcRectCorners((*p_vertices)[0], (*p_vertices)[1], *p_mouseLoc, missingVertex);
painter->drawLine(*p_mouseLoc, missingVertex);
painter->drawLine(missingVertex, (*p_vertices)[0]);
}
else if(p_vertices->size() == 4) {
painter->drawLine((*p_vertices)[0], (*p_vertices)[ 3 ]);
}
paintVerticesConnected(painter);
// Draw indicator on top of original lines if applicable
if(p_indicatorColors) {
painter->setPen(greenPen);
if(p_vertices->size() > 1) {
painter->drawLine((*p_vertices)[0], (*p_vertices)[1]);
}
else if(p_vertices->size() == 1) {
painter->drawLine((*p_vertices)[0], *p_mouseLoc);
}
painter->setPen(pen);
}
}
break;
case SegmentedLineMode:
paintVerticesConnected(painter);
break;
}
}
/**
* Given two set corners, and the mouse location, this method will interpolate the last two corners.
*
* @param corner1 Known point
* @param corner2 Known point
* @param corner3 Guessed corner (point to interpolate to).
* @param corner4 Unknown corner.
*/
void RubberBandTool::calcRectCorners(QPoint corner1, QPoint corner2, QPoint &corner3, QPoint &corner4) {
double slope = ((double)corner2.y() - (double)corner1.y()) / ((double)corner2.x() - (double)corner1.x());
if((fabs(slope) > DBL_EPSILON) && (slope < DBL_MAX) && (slope > -DBL_MAX)) {
// corner1,corner2 make up y=m(x-x1)+y1
// corner3,corner4 must make up || line crossing corner3.
// b (y-intercept) is what differs from the original line and our parallel line.
// Go ahead and figure out our new b by using b = -mx1+y1 from the point-slope formula.
double parallelB = -1 * slope * corner3.x() + corner3.y();
// Now we have our equation for a parallel line, which our new points lie on. Let's find the perpendicular lines
// which cross corner1,corner2 in order to figure out where they cross it. Use -1/slope = perpendicular slope and
// now we have y=m(x-x1)+y1. What we care about is b in y=mx+b, so figure it out using b = m*(-x1)+y1
double perpSlope = -1.0 / slope;
double perpLineMode1b = perpSlope * (-1 * corner1.x()) + corner1.y();
double perpLineMode2b = perpSlope * (-1 * corner2.x()) + corner2.y();
// Now let's find the perpendicular lines' intercepts on the parallel line.
// y = mx+b = y = mx+b => mx+b(perpendicular) = mx+b(parallel) for the perp. lines and the parallel line.
// Combine the b's on the left to make y= m(perp)x+k = m(par)x.
double perpLineMode1k = perpLineMode1b - parallelB;
double perpLineMode2k = perpLineMode2b - parallelB;
// Now we have mx + k = mx (parallel). Divive the parallel slope out to get
// (m(perp)x+k)/m(parallel) = x. Move the x over from the left side of the equation by subtracting...
// k/m(parallel) = x - m(perp)x/m(parallel). Factor out the x's... k/m(par) = x(1-m(per)/m(par)) and divive
// both sides by "(1-m(per)/m(par))". So we end up with: (k/m(par)) / (1 - m(per) / m(par) ) =
// k/m(par) / ( (m(par)-m(per)) / m(par) ) = k / m(par) * m(par) / (m(par) - m(per)) = k / (m(par) - m(per))
double perpLineMode1IntersectX = perpLineMode1k / (slope - perpSlope);
double perpLineMode2IntersectX = perpLineMode2k / (slope - perpSlope);
// The intersecting X values are now known, and the equation of the parallel line, so let's roll with it and
// get our two corners set. perpLineMode1 => corner1 => corner4, perpLineMode2 => corner2 => corner3
corner3.setX((int)perpLineMode2IntersectX);
corner3.setY((int)(perpLineMode2IntersectX * slope + parallelB)); //mx+b
corner4.setX((int)perpLineMode1IntersectX);
corner4.setY((int)(perpLineMode1IntersectX * slope + parallelB)); //mx+b
}
else if(fabs(slope) < DBL_EPSILON) {
corner3.setX(corner2.x());
corner3.setY(corner3.y());
corner4.setX(corner1.x());
corner4.setY(corner3.y());
}
else {
corner3.setX(corner3.x());
corner3.setY(corner2.y());
corner4.setX(corner3.x());
corner4.setY(corner1.y());
}
}
/**
* This paints connecting lines to p_vertices. If tracking, a line is also drawn to
* the mouse location.
*
* @param painter
*/
void RubberBandTool::paintVerticesConnected(QPainter *painter) {
for(int vertex = 1; vertex < p_vertices->size(); vertex++) {
QPoint start = (*p_vertices)[vertex - 1];
QPoint end = (*p_vertices)[vertex];
painter->drawLine(start, end);
}
if(p_tracking && (p_vertices->size() > 0)) {
QPoint start = (*p_vertices)[p_vertices->size() - 1];
QPoint end = *p_mouseLoc;
painter->drawLine(start, end);
}
}
/**
* Given opposite corners, the other two are interpolated and the rectangle is drawn.
*
* @param upperLeft Corner opposite of lowerRight
* @param lowerRight Corner opposite of upperLeft
* @param painter
*/
void RubberBandTool::paintRectangle(QPoint upperLeft, QPoint lowerRight, QPainter *painter) {
QPoint upperRight = QPoint(lowerRight.x(), upperLeft.y());
QPoint lowerLeft = QPoint(upperLeft.x(), lowerRight.y());
paintRectangle(upperLeft, upperRight, lowerLeft, lowerRight, painter);
}
/**
* This draws a box around the 4 points using the painter.
*
* @param upperLeft Initial corner
* @param upperRight Corner connected to upperLeft, lowerRight
* @param lowerLeft Corner connected to lowerRight, upperLeft
* @param lowerRight Corner connected to lowerLeft, upperRight
* @param painter
*/
void RubberBandTool::paintRectangle(QPoint upperLeft, QPoint upperRight,
QPoint lowerLeft, QPoint lowerRight, QPainter *painter) {
painter->drawLine(upperLeft, upperRight);
painter->drawLine(upperRight, lowerRight);
painter->drawLine(lowerRight, lowerLeft);
painter->drawLine(lowerLeft, upperLeft);
}
/**
* This is called when changing modes or turning on. So, set the mode, reset, and activate
* our event handlers.
*
* @param mode
* @param showIndicatorColors Color the first side of figures differently
*/
void RubberBandTool::enable(RubberBandMode mode, bool showIndicatorColors) {
RubberBandMode oldMode = p_bandingMode;
p_bandingMode = mode;
p_indicatorColors = showIndicatorColors;
//Took this out because it was reseting and not letting us plot single points.
//p_pointTolerance = 0;
p_allClicks = false;
p_drawActiveOnly = false;
reset();
activate(true);
if(oldMode != mode) {
emit modeChanged();
}
}
/**
* This is called when something is not using me, so
* turn off events, reset & repaint to clear the clear.
*/
void RubberBandTool::disable() {
activate(false);
reset();
repaint();
}
/**
* This called to set whether rubber band is drawn on active viewport only
* rather than all linked viewports.
*/
void RubberBandTool::setDrawActiveViewportOnly(bool activeOnly) {
p_drawActiveOnly = activeOnly;
repaint();
}
/**
* This triggers on a second mouse press. Only polygons care about this, and it signifies an end of
* shape. So, if we're in polygon mode, stop tracking the mouse and emit a complete.
* @param p
*/
void RubberBandTool::mouseDoubleClick(QPoint p) {
p_doubleClicking = true;
*p_mouseLoc = p;
switch(p_bandingMode) {
case AngleMode:
case CircleMode:
case EllipseMode:
case LineMode:
case RectangleMode:
case RotatedRectangleMode:
break;
case SegmentedLineMode:
case PolygonMode:
p_tracking = false;
repaint();
emit bandingComplete();
break;
}
}
/**
* If the click is not the left mouse button, this does nothing.
*
* This will set mouseDown as true. When the calculations are complete,
* p_mouseDown is set to true.
*
* For drag-only,
* A press means starting a new rubber band so reset & record the point. This applies to
* CircleModes, Eliipsoids, LineModes and RectangleModes.
*
* For Rotated RectangleModes,
* A mount press means we're starting over, setting the first point, or completing.
* For the first two, simply reset and record the point. For the latter, figure out the
* corners and store those points.
*
* For polygons,
* A press means record the current point. Reset first if we're not currently drawing.
*
* @param p
* @param s
*/
void RubberBandTool::mouseButtonPress(QPoint p, Qt::MouseButton s) {
*p_mouseLoc = p;
p_mouseButton = s;
if((s & Qt::LeftButton) != Qt::LeftButton && !p_allClicks) {
return;
}
switch(p_bandingMode) {
case AngleMode:
break;
case CircleMode:
case EllipseMode:
case LineMode:
case RectangleMode:
reset();
p_tracking = true;
p_vertices->push_back(p);
break;
case RotatedRectangleMode:
if(p_vertices->size() == 4) {
reset();
}
if(p_vertices->size() == 0) {
p_vertices->push_back(p);
p_tracking = true;
}
break;
case SegmentedLineMode:
case PolygonMode:
if(!p_tracking) {
reset();
p_tracking = true;
}
if(p_vertices->size() == 0 || (*p_vertices)[ p_vertices->size() - 1 ] != p) {
p_vertices->push_back(p);
}
break;
}
p_mouseDown = true;
}
/**
* If this is not the left mouse button, this does nothing.
*
* This will set mouseDown as false. When the calculations are complete,
* p_doubleClicking is
* set to false. The double click event occurs with
* `the press event so it's safe to set that flag here.
*
* The implementation differs, based on the mode, as follows:
*
* For angles,
* This signifies a click. We're always setting one of the
* three vertexes, but if there is an already
* complete vertex go ahead and reset first to start a new angle.
*
* For circles,
* Since this is a drag-only rubber band, a release signifies a complete. Figure out the corner, based
* on the mouse location, and push it onto the back of the vertex list and emit a complete.
*
* For EllipseModes,
* Since this is a drag-only rubber band, a release signifies a complete. We know the corner, it's the mouse loc,
* push it onto the back of the vertex list and emit a complete.
*
* For lines,
* Since this is a drag-only rubber band, a release signifies a complete. We know the end point,
* push it onto the back of the vertex list and emit a complete.
*
* For rectangles,
* Since this is a drag-only rubber band, a release signifies a complete. We know the opposite corner,
* figure out the others and push them onto the back of the vertex list and emit a complete.
*
* For rotated rectangles,
* If we're finishing dragging the first side, store the end point.
*
* For polygons,
* Do nothing, this is taken care of on press.
*
* @param p Current mouse Location
* @param s Which mouse button was released
*/
void RubberBandTool::mouseButtonRelease(QPoint p, Qt::MouseButton s) {
if ((s & Qt::ControlModifier) == Qt::ControlModifier)
*p_mouseLoc = snapMouse(p);
else
*p_mouseLoc = p;
p_mouseButton = s;
if((s & Qt::LeftButton) == Qt::LeftButton || p_allClicks) {
p_mouseDown = false;
}
else {
return;
}
switch(p_bandingMode) {
case AngleMode: {
if(p_vertices->size() == 3) {
reset();
}
p_vertices->push_back(*p_mouseLoc);
p_tracking = true;
if(p_vertices->size() == 3) {
p_tracking = false;
emit bandingComplete();
}
}
break;
case LineMode:
case CircleMode:
case EllipseMode:
case RectangleMode: {
*p_vertices = vertices();
p_tracking = false;
emit bandingComplete();
}
break;
case RotatedRectangleMode: {
if(p_vertices->size() == 1) {
p_vertices->push_back(*p_mouseLoc);
}
else if(p_vertices->size() == 2) {
*p_vertices = vertices();
p_tracking = false;
emit bandingComplete();
}
}
break;
case SegmentedLineMode:
case PolygonMode:
break;
}
p_doubleClicking = false; // If we were in a double click, it's over now.
MdiCubeViewport * activeViewport = cubeViewport();
for (int i = 0; i < (int) cubeViewportList()->size(); i++) {
MdiCubeViewport * curViewport = cubeViewportList()->at(i);
if (curViewport == activeViewport ||
(activeViewport->isLinked() && curViewport->isLinked())) {
curViewport->viewport()->repaint();
}
}
}
/**
* moves the mouse's location p to the nearest axis
*
* @param p The mouse's current location
*
* @returns The snapped point
*/
QPoint RubberBandTool::snapMouse(QPoint p) {
if (p_vertices->size()) {
QPoint lastVertex = p_vertices->at(p_vertices->size() - 1);
int deltaX = abs(p.x() - lastVertex.x());
int deltaY = abs(p.y() - lastVertex.y());
if (deltaX > deltaY)
p.setY(lastVertex.y());
else
p.setX(lastVertex.x());
}
return p;
}
/**
* If tracking is not enabled, this does nothing.
*
* This will first update the mouse location for painting purposes.
*
* Most of the implementation is a matter of emitting measureChanges:
* For angles, if the first two vertices are specified a measureChange will be emitted.
* For circles, if the center of the circle is known a measureChange will be emitted.
* For EllipseModes, if the center of the EllipseMode is known a measureChange will be emitted.
* For lines, if the first point of the line is known a measureChange will be emitted.
* For rectangles, if the starting point is known a measureChange will be emitted.
* For rotated rectangles, if the first side is specified a measureChange will be emitted.
*
* However, there is one exception:
* For polygons, if the mouse button is pressed the mouse location is recorded as a valid vertex.
*
* @param p Current mouse Location
*/
void RubberBandTool::mouseMove(QPoint p, Qt::MouseButton mouseButton) {
if(!p_tracking) {
return;
}
p_mouseButton = mouseButton;
if ((p_mouseButton & Qt::ControlModifier) == Qt::ControlModifier)
*p_mouseLoc = snapMouse(p);
else
*p_mouseLoc = p;
switch(p_bandingMode) {
case AngleMode:
case RotatedRectangleMode:
if(p_vertices->size() == 2) {
emit measureChange();
}
break;
case CircleMode:
case EllipseMode:
case RectangleMode:
if(p_vertices->size() == 1) {
emit measureChange();
}
break;
case LineMode:
emit measureChange();
break;
case SegmentedLineMode:
case PolygonMode: {
if(p_mouseDown && p != (*p_vertices)[ p_vertices->size() - 1 ]) {
p_vertices->push_back(p);
}
if (p_bandingMode == SegmentedLineMode)
emit measureChange();
}
break;
}
MdiCubeViewport * activeViewport = cubeViewport();
for (int i = 0; i < (int) cubeViewportList()->size(); i++) {
MdiCubeViewport * curViewport = cubeViewportList()->at(i);
if (curViewport == activeViewport ||
(activeViewport->isLinked() && curViewport->isLinked())) {
curViewport->viewport()->repaint();
}
}
}
/**
* This method returns the vertices. The return value is mode-specific, and the return will be
* consistent whether in a measureChange or bandingComplete slot.
*
* The return values are always in pixels.
*
* The return values are as follows:
* For angles, the return will always be of size 3. The elements at 0 and 2 are the edges of the angle,
* while the element at 1 is the vertex of the angle.
*
* For circles, the return will always be of size 2. The element at 0 is the center of the circle, and the
* element at 1 is offset by the radius in both directions.
*
* For EllipseModes, the return will always be of size 2. The element at 0 is the center of the circle, and the
* element at 1 is offset by the radius in both directions.
*
* For lines, the return will always be of size 2. The elements are the start and end points.
*
* For rectangles, the return will always be of size 4. The elements will be the corners,
* in either a clockwise or counter-clockwise direction.
*
* For rotated rectangles, the same applies.
*
* For polygons, the return will be a list of vertices in the order that the user drew them.
*
* **It is NOT valid to call this unless you're in a measureChange or bandingComplete slot.
*
* @return QList<QPoint>
*/
QList<QPoint> RubberBandTool::vertices() {
QList<QPoint> vertices = *p_vertices;
if(!figureComplete())
return vertices;
if(p_tracking) {
switch(p_bandingMode) {
case AngleMode:
case LineMode:
case SegmentedLineMode:
vertices.push_back(*p_mouseLoc);
break;
case RectangleMode: {
QPoint corner1 = QPoint(p_mouseLoc->x(), vertices[0].y());
QPoint corner2 = QPoint(p_mouseLoc->x(), p_mouseLoc->y());
QPoint corner3 = QPoint(vertices[0].x(), p_mouseLoc->y());
vertices.push_back(corner1);
vertices.push_back(corner2);
vertices.push_back(corner3);
}
break;
case RotatedRectangleMode: {
QPoint missingVertex;
calcRectCorners((*p_vertices)[0], (*p_vertices)[1], *p_mouseLoc, missingVertex);
vertices.push_back(*p_mouseLoc);
vertices.push_back(missingVertex);
}
break;
case CircleMode: {
int xradius = abs(p_mouseLoc->x() - vertices[0].x()) / 2;
int yradius = xradius;
if(p_mouseLoc->x() - vertices[0].x() < 0) {
xradius *= -1;
}
if(p_mouseLoc->y() - vertices[0].y() < 0) {
yradius *= -1;
}
// Adjust p_vertices[0] from upper left to center
vertices[0].setX(vertices[0].x() + xradius);
vertices[0].setY(vertices[0].y() + yradius);
vertices.push_back(*p_mouseLoc);
vertices[1].setX(vertices[0].x() + xradius);
vertices[1].setY(vertices[0].y() + yradius);
}
break;
case EllipseMode: {
// Adjust p_vertices[0] from upper left to center
double xradius = (p_mouseLoc->x() - vertices[0].x()) / 2.0;
double yradius = (p_mouseLoc->y() - vertices[0].y()) / 2.0;
vertices[0].setX((int)(vertices[0].x() + xradius));
vertices[0].setY((int)(vertices[0].y() + yradius));
vertices.push_back(*p_mouseLoc);
}
break;
case PolygonMode:
break;
}
}
return vertices;
}
/**
* This initializes the class except for the current mode, which is
* set on enable.
*
*/
void RubberBandTool::reset() {
p_vertices->clear();
p_tracking = false;
p_mouseDown = false;
p_doubleClicking = false;
repaint();
}
Angle RubberBandTool::angle() {
Angle result;
if(currentMode() == AngleMode) {
// We cancluate the angle by considering each line an angle itself, with respect to the
// X-Axis, and then differencing them.
//
// theta1 = arctan((point0Y - point1Y) / (point0X - point1X))
// theta2 = arctan((point2Y - point1Y) / (point2X - point1X))
// |
// | / <-- point0
// | / |
// | / |
// theta1 | / |
// --> |/ | <-- 90 degrees
// point1 --> ------|---------------------------
//(vertex) --> |\ | <-- 90 degrees
// theta2 | \ |
// | \ |
// | \ |
// | \ |
// | \|
// | | <-- point 2
//
// angle = theta1 - theta2; **
QList<QPoint> verticesList = vertices();
double theta1 = atan2((double)(verticesList[0].y() - verticesList[1].y()), (double)(verticesList[0].x() - verticesList[1].x()));
double theta2 = atan2((double)(verticesList[2].y() - verticesList[1].y()), (double)(verticesList[2].x() - verticesList[1].x()));
double angle = (theta1 - theta2);
// Force the angle into [0,2PI]
while(angle < 0.0) {
angle += PI * 2;
}
while(angle > PI * 2) {
angle -= PI * 2;
}
// With our [0,2PI] angle, let's make it [0,PI] to get the interior angle.
if(angle > PI) {
angle = (PI * 2.0) - angle;
}
result = Angle(angle, Angle::Radians);
}
return result;
}
/**
* This method will call the viewport's repaint if there is a current cube viewport.
*/
void RubberBandTool::repaint() {
if(cubeViewport() != NULL) {
cubeViewport()->viewport()->repaint();
}
}
/**
*
*
* @return geos::Geometry*
*/
geos::geom::Geometry *RubberBandTool::geometry() {
geos::geom::Geometry *geometry = NULL;
QList<QPoint> verticesList = vertices();
switch(p_bandingMode) {
case AngleMode: {
if(verticesList.size() != 3)
break;
geos::geom::CoordinateSequence *points1 = new geos::geom::CoordinateArraySequence();
geos::geom::CoordinateSequence *points2 = new geos::geom::CoordinateArraySequence();
points1->add(geos::geom::Coordinate(verticesList[0].x(), verticesList[0].y()));
points1->add(geos::geom::Coordinate(verticesList[1].x(), verticesList[1].y()));
points2->add(geos::geom::Coordinate(verticesList[1].x(), verticesList[1].y()));
points2->add(geos::geom::Coordinate(verticesList[2].x(), verticesList[2].y()));
geos::geom::LineString *line1 = globalFactory.createLineString(points1);
geos::geom::LineString *line2 = globalFactory.createLineString(points2);
std::vector<geos::geom::Geometry *> *lines = new std::vector<geos::geom::Geometry *>;
lines->push_back(line1);
lines->push_back(line2);
geos::geom::MultiLineString *angle = globalFactory.createMultiLineString(lines);
geometry = angle;
}
break;
case CircleMode:
case EllipseMode: {
if(verticesList.size() != 2)
break;
// A circle is an ellipse, so it gets no special case
// Equation of an ellipse: (x-h)^2/a^2 + (y-k)^2/b^2 = 1 where
// h is the X-location of the center, k is the Y-location of the center
// a is the x-radius and b is the y-radius.
// Solving for y, we get
// y = +-sqrt(b^2(1-(x-h)^2/a^2)) + k
// and our domain is [h-a,h+a]
// We need the equation of this ellipse!
double h = verticesList[0].x();
double k = verticesList[0].y();
double a = abs(verticesList[0].x() - verticesList[1].x());
double b = abs(verticesList[0].y() - verticesList[1].y());
if(a == 0)
break; // Return null, we can't make an ellipse from this.
if(b == 0)
break; // Return null, we can't make an ellipse from this.
// We're ready to try to solve
double originalX = 0.0, originalY = 0.0;
geos::geom::CoordinateSequence *points = new geos::geom::CoordinateArraySequence();
// Now iterate through our domain, solving for y positive, using 1/5th of a pixel increments
for(double x = h - a; x <= h + a; x += 0.2) {
double y = sqrt(pow(b, 2) * (1.0 - pow((x - h), 2) / pow(a, 2))) + k;
points->add(geos::geom::Coordinate(x, y));
if(x == h - a) {
originalX = x;
originalY = y;
}
}
// Iterate through our domain backwards, solving for y negative, using 1/5th of a pixel decrements
for(double x = h + a; x >= h - a; x -= 0.2) {
double y = -1.0 * sqrt(pow(b, 2) * (1.0 - pow((x - h), 2) / pow(a, 2))) + k;
points->add(geos::geom::Coordinate(x, y));
}
points->add(geos::geom::Coordinate(originalX, originalY));
geometry = globalFactory.createPolygon(
globalFactory.createLinearRing(points), NULL
);
}
break;
case RectangleMode:
case RotatedRectangleMode:
case PolygonMode: {
if(verticesList.size() < 3)
break;
geos::geom::CoordinateSequence *points = new geos::geom::CoordinateArraySequence();
for(int vertex = 0; vertex < verticesList.size(); vertex++) {
points->add(geos::geom::Coordinate(verticesList[vertex].x(), verticesList[vertex].y()));
}
points->add(geos::geom::Coordinate(verticesList[0].x(), verticesList[0].y()));
geometry = globalFactory.createPolygon(globalFactory.createLinearRing(points), NULL);
}
break;
case LineMode: {
if(verticesList.size() != 2)
break;
geos::geom::CoordinateSequence *points = new geos::geom::CoordinateArraySequence();
points->add(geos::geom::Coordinate(verticesList[0].x(), verticesList[0].y()));
points->add(geos::geom::Coordinate(verticesList[1].x(), verticesList[1].y()));
geos::geom::LineString *line = globalFactory.createLineString(points);
geometry = line;
}
break;
case SegmentedLineMode: {
if(verticesList.size() < 2)
break;
geos::geom::CoordinateSequence *points = new geos::geom::CoordinateArraySequence();
for(int vertex = 0; vertex < verticesList.size(); vertex++) {
points->add(geos::geom::Coordinate(verticesList[vertex].x(), verticesList[vertex].y()));
}
geos::geom::LineString *line = globalFactory.createLineString(points);
geometry = line;
}
break;
}
if(geometry != NULL && !geometry->isValid()) {
geometry = NULL;
}
return geometry;
}
/**
* This method returns a rectangle from the vertices set by the
* RubberBandTool. It calculates the upper left and bottom right
* points for the rectangle and properly initializes a QRect
* object with these vertices. If the RubberBandTool is in the
* incorrect mode, or the rectangle is not valid it will return
* an error message.
*
*
* @return QRect The QRect the user selected on the viewport in
* pixels
*/
QRect RubberBandTool::rectangle() {
QRect rect;
if(currentMode() == RectangleMode && figureValid()) {
QList<QPoint> verticesList = vertices();
//Check the corners for upper left and lower right.
int x1, x2, y1, y2;
//Point 1 is in the left, make point1.x upperleft.x
if(verticesList[0].x() < verticesList[2].x()) {
x1 = verticesList[0].x();
x2 = verticesList[2].x();
}
//Otherwise Point1 is in the right, make point1.x lowerright.x
else {
x1 = verticesList[2].x();
x2 = verticesList[0].x();
}
//Point 1 is in the top, make point1.y upperleft.y
if(verticesList[0].y() < verticesList[2].y()) {
y1 = verticesList[0].y();
y2 = verticesList[2].y();
}
//Otherwise Point1 is in the bottom, make point1.y lowerright.y
else {
y1 = verticesList[2].y();
y2 = verticesList[0].y();
}
rect = QRect(x1, y1, x2 - x1, y2 - y1);
}
//RectangleMode is not valid, or RubberBandTool is in the wrong mode, return error
else {
QMessageBox::information((QWidget *)parent(),
"Error", "**PROGRAMMER ERROR** Invalid RectangleMode");
}
return rect;
}
/**
* This method returns the mouse button modifier
*
* @return MouseButton Mouse button modifier on last release
*/
Qt::MouseButton RubberBandTool::mouseButton() {
return p_mouseButton;
}
bool RubberBandTool::isValid() {
return figureComplete() && figureValid();
}
bool RubberBandTool::figureComplete() {
bool complete = false;
switch(p_bandingMode) {
case AngleMode:
complete = (p_vertices->size() == 2 && p_tracking) || (p_vertices->size() == 3);
break;
case LineMode:
complete = (p_vertices->size() == 1 && p_tracking) || (p_vertices->size() == 2);
break;
case RectangleMode:
complete = (p_vertices->size() == 1 && p_tracking) || (p_vertices->size() == 4);
break;
case RotatedRectangleMode:
complete = (p_vertices->size() == 2 && p_tracking) || (p_vertices->size() == 4);
break;
case CircleMode:
case EllipseMode:
complete = (p_vertices->size() == 1 && p_tracking) || (p_vertices->size() == 2);
break;
case SegmentedLineMode:
complete = (p_vertices->size() > 1 && !p_tracking) || (p_vertices->size() > 0);
break;
case PolygonMode:
complete = (p_vertices->size() > 2 && !p_tracking);
break;
}
return complete;
}
bool RubberBandTool::figureValid() {
if(!figureComplete())
return false;
bool valid = true;
QList<QPoint> verticesList = vertices();
switch(p_bandingMode) {
case AngleMode: {
// Just make sure the vertex and an angle side don't lie on the same point
// No point tolerance allowed
valid = verticesList[0].x() != verticesList[1].x() || verticesList[0].y() != verticesList[1].y();
valid &= verticesList[2].x() != verticesList[1].x() || verticesList[2].y() != verticesList[1].y();
}
break;
case LineMode: {
// Just make sure the line doesnt start/end at same point if point not allowed
if(p_pointTolerance == 0) {
valid = verticesList[0].x() != verticesList[1].x() || verticesList[0].y() != verticesList[1].y();
}
}
break;
case RectangleMode: {
// Make sure there's a height and width if point not allowed
if(p_pointTolerance == 0) {
valid = verticesList[0].x() != verticesList[2].x() && verticesList[0].y() != verticesList[2].y();
}
}
break;
case RotatedRectangleMode: {
// Make sure there's a height and width once again, point tolerance not allowed
valid = verticesList[0].x() != verticesList[1].x() || verticesList[0].y() != verticesList[1].y();
valid &= verticesList[1].x() != verticesList[2].x() || verticesList[1].y() != verticesList[2].y();
}
break;
case CircleMode:
case EllipseMode: {
// Make sure there's a height and width, point tolerance not allowed
valid = verticesList[0].x() != verticesList[1].x() && verticesList[0].y() != verticesList[1].y();
}
break;
case SegmentedLineMode: {
valid = verticesList.size() > 1;
}
break;
case PolygonMode: {
// For polygons, we must revert back to using geos
geos::geom::Geometry *poly = geometry();
valid = poly && poly->isValid();
delete poly;
}
break;
}
return valid;
}
void RubberBandTool::enablePoints(unsigned int pixTolerance) {
p_pointTolerance = pixTolerance;
}
bool RubberBandTool::figureIsPoint() {
if(!figureValid())
return false;
bool isPoint = true;
QList<QPoint> verticesList = vertices();
switch(p_bandingMode) {
case AngleMode:
case RotatedRectangleMode:
case CircleMode:
case EllipseMode:
case PolygonMode:
case SegmentedLineMode:
isPoint = false;
break;
case LineMode: {
isPoint = (abs(verticesList[0].x() - verticesList[1].x()) +
abs(verticesList[0].y() - verticesList[1].y()) < (int)p_pointTolerance);
}
break;
case RectangleMode: {
isPoint = (abs(verticesList[0].x() - verticesList[2].x()) +
abs(verticesList[0].y() - verticesList[2].y()) < (int)p_pointTolerance);
}
break;
}
return isPoint;
}
//! clears the rubber band!
void RubberBandTool::clear() {
reset();
repaint();
}
RubberBandTool::RubberBandMode RubberBandTool::currentMode() {
return p_bandingMode;
};
double RubberBandTool::area() {
return 0.0; //<! Returns the area of the figure
}
void RubberBandTool::enableAllClicks() {
p_allClicks = true;
}
void RubberBandTool::escapeKeyPress() {
reset();
}
void RubberBandTool::scaleChanged() {
reset();
}
}
| 32.288964 | 134 | 0.58314 | ihumphrey-usgs |
984efefea7490c13b4069012e9cc4a8de4e67e0e | 1,611 | cpp | C++ | CPP_US/src/Engine/Camera.cpp | Basher207/Unity-style-Cpp-engine | 812b0be2c61aea828cfd8c6d6f06f2cf6e889661 | [
"MIT"
] | null | null | null | CPP_US/src/Engine/Camera.cpp | Basher207/Unity-style-Cpp-engine | 812b0be2c61aea828cfd8c6d6f06f2cf6e889661 | [
"MIT"
] | null | null | null | CPP_US/src/Engine/Camera.cpp | Basher207/Unity-style-Cpp-engine | 812b0be2c61aea828cfd8c6d6f06f2cf6e889661 | [
"MIT"
] | null | null | null | #include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/vector_angle.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <stdio.h>
#include "GameObject.hpp"
#include "Transform.hpp"
#include "glad.h"
#include "Camera.hpp"
//Allocating memory for the singleton
Camera* Camera::mainCamera;
Camera* Camera::StartCamera () {
if (!Camera::mainCamera) {//If camera is already started dont create a new one
GameObject* camObject = new GameObject(); //Create a new GameObject to hold the camera
camObject->AddComponent<Camera>(); //Add a camera MonoBehavior to the camObject, and stors it in the mainCamera singlton
}
return mainCamera; //Return the mainCamera
}
void Camera::Awake () {
mainCamera = this; //On camera object Awake, stores itself as the camera singlton
}
void Camera::Render () {
glPushMatrix(); //Pushes the matrix in preperations for rendering
// glMultMatrix takes in a float* to a matrix array
// glm::value_ptr returns such a pointer
glMultMatrixf(glm::value_ptr(this->perspective_mat));
//Turns the quaternion rotation into a matrix for multiplications
glm::mat4x4 rotation = glm::mat4_cast(transform->localRotation);
glMultMatrixf(glm::value_ptr(rotation));
//Translates the camera by it's position
glTranslatef (-this->transform->localPos.x,-this->transform->localPos.y,-this->transform->localPos.z);
//Start rendering all transforms.
Transform::RenderMasterParents();
glPopMatrix();//Pop the matrix
} | 33.5625 | 122 | 0.740534 | Basher207 |
9852d984a8e6a1d79f9c535944a64b9567edef84 | 4,887 | hpp | C++ | include/tudocomp/compressors/lz_pointer_jumping/PointerJumping.hpp | 421408/tudocomp | 9634742393995acdde148b0412f083bfdd0fbe9f | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-09-22T11:29:02.000Z | 2020-09-22T11:29:02.000Z | include/tudocomp/compressors/lz_pointer_jumping/PointerJumping.hpp | 421408/tudocomp | 9634742393995acdde148b0412f083bfdd0fbe9f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/tudocomp/compressors/lz_pointer_jumping/PointerJumping.hpp | 421408/tudocomp | 9634742393995acdde148b0412f083bfdd0fbe9f | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-09-29T08:57:13.000Z | 2020-09-29T08:57:13.000Z | #pragma once
#include <unordered_map>
#include <array>
#include <tudocomp/compressors/lz_common/factorid_t.hpp>
namespace tdc {namespace lz_pointer_jumping {
static constexpr bool PRINT_DEBUG_TRANSITIONS = false;
template<typename pj_trie_t>
class PointerJumping: public pj_trie_t {
using jump_buffer_handle = typename pj_trie_t::jump_buffer_handle;
public:
using lz_state_t = typename pj_trie_t::lz_state_t;
using traverse_state_t = typename pj_trie_t::traverse_state_t;
using factorid_t = lz_common::factorid_t;
inline PointerJumping(lz_state_t& lz_state, size_t jump_width):
pj_trie_t(jump_width),
m_lz_state(lz_state),
m_jump_width(jump_width),
m_jump_buffer_handle(this->get_working_buffer())
{}
inline uliteral_t& jump_buffer(size_t i) {
DCHECK_LT(i, m_jump_width);
return this->get_buffer(m_jump_buffer_handle)[i];
}
inline uliteral_t const& jump_buffer(size_t i) const {
DCHECK_LT(i, m_jump_width);
return this->get_buffer(m_jump_buffer_handle)[i];
}
inline factorid_t jump_buffer_parent_node() const {
return this->get_parent_node(m_jump_buffer_handle);
}
inline size_t jump_buffer_size() const {
return m_jump_buffer_size;
}
struct action_t {
bool m_was_full;
typename pj_trie_t::result_t m_result;
inline bool buffer_full_and_found() const {
return m_was_full && m_result.found();
}
inline bool buffer_full_and_not_found() const {
return m_was_full && (!m_result.found());
}
inline traverse_state_t traverse_state() const {
DCHECK(buffer_full_and_found());
return m_result.get();
}
};
inline action_t on_insert_char(uliteral_t c) {
DCHECK_LT(m_jump_buffer_size, m_jump_width);
jump_buffer(m_jump_buffer_size) = c;
m_jump_buffer_size++;
if(jump_buffer_full()) {
auto entry = find_jump_buffer();
if (entry.found()) {
debug_transition(std::cout, entry.get(), false);
}
return action_t { true, entry };
} else {
debug_open_transition(std::cout);
return action_t { false, typename pj_trie_t::result_t() };
}
}
inline void shift_buffer(size_t elements) {
factorid_t parent_node = current_lz_node_id();
size_t remaining = m_jump_width - elements;
for(size_t i = 0; i < remaining; i++) {
jump_buffer(i) = jump_buffer(i + elements);
}
m_jump_buffer_size -= elements;
this->set_parent_node(m_jump_buffer_handle, parent_node);
debug_open_transition(std::cout);
}
inline void reset_buffer() {
factorid_t parent_node = current_lz_node_id();
m_jump_buffer_size = 0;
this->set_parent_node(m_jump_buffer_handle, parent_node);
debug_open_transition(std::cout);
}
inline bool jump_buffer_full() const {
return m_jump_width == m_jump_buffer_size;
}
inline auto find_jump_buffer() const {
return this->find(m_jump_buffer_handle);
}
inline void insert_jump_buffer(traverse_state_t const& val) {
debug_transition(std::cout, val, true);
this->insert(m_jump_buffer_handle, val);
}
// DEBUG printing function
inline void debug_print_buffer(std::ostream& out, jump_buffer_handle const& handle, size_t size) const {
if (!PRINT_DEBUG_TRANSITIONS) return;
for(size_t i = 0; i < size; i++) {
out << this->get_buffer(handle)[i];
}
}
inline void debug_print_buffer(std::ostream& out) const {
if (!PRINT_DEBUG_TRANSITIONS) return;
debug_print_buffer(out, m_jump_buffer_handle, m_jump_buffer_size);
}
inline void debug_open_transition(std::ostream& out) const {
if (!PRINT_DEBUG_TRANSITIONS) return;
factorid_t parent_node = jump_buffer_parent_node();
out << "(" << parent_node << ") -[";
debug_print_buffer(out);
out << "..." << std::endl;
}
inline void debug_transition(std::ostream& out, traverse_state_t const& to, bool is_new) const {
if (!PRINT_DEBUG_TRANSITIONS) return;
factorid_t parent_node = jump_buffer_parent_node();
out << "(" << parent_node << ") -[";
debug_print_buffer(out);
out << "]-> (" << m_lz_state.get_node(to).id() << ")" ;
if (is_new) {
out << "*";
}
out << std::endl;
}
private:
lz_state_t& m_lz_state;
size_t m_jump_width;
jump_buffer_handle m_jump_buffer_handle;
size_t m_jump_buffer_size = 0;
inline factorid_t current_lz_node_id() const {
return m_lz_state.get_node(m_lz_state.get_traverse_state()).id();
}
};
}}
| 31.326923 | 108 | 0.638428 | 421408 |
985389ddabca4ca6bf2e079b45034eab875103d6 | 32,511 | cpp | C++ | source/base/processoptions.cpp | tomberek/RaySAR | b8f885e1b640662b67a568cf8c41b8dcfc9a9c8d | [
"Zlib"
] | null | null | null | source/base/processoptions.cpp | tomberek/RaySAR | b8f885e1b640662b67a568cf8c41b8dcfc9a9c8d | [
"Zlib"
] | null | null | null | source/base/processoptions.cpp | tomberek/RaySAR | b8f885e1b640662b67a568cf8c41b8dcfc9a9c8d | [
"Zlib"
] | null | null | null | /****************************************************************************
* processoptions.cpp
*
* This module contains the C++ interface for option processing.
*
* from Persistence of Vision(tm) Ray Tracer version 3.6.
* Copyright 1991-2003 Persistence of Vision Team
* Copyright 2003-2004 Persistence of Vision Raytracer Pty. Ltd.
*---------------------------------------------------------------------------
* NOTICE: This source code file is provided so that users may experiment
* with enhancements to POV-Ray and to port the software to platforms other
* than those supported by the POV-Ray developers. There are strict rules
* regarding how you are permitted to use this file. These rules are contained
* in the distribution and derivative versions licenses which should have been
* provided with this file.
*
* These licences may be found online, linked from the end-user license
* agreement that is located at http://www.povray.org/povlegal.html
*---------------------------------------------------------------------------
* This program is based on the popular DKB raytracer version 2.12.
* DKBTrace was originally written by David K. Buck.
* DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
*---------------------------------------------------------------------------
* $File: //depot/povray/3.6-release/source/base/processoptions.cpp $
* $Revision: #2 $
* $Change: 2939 $
* $DateTime: 2004/07/04 13:43:26 $
* $Author: root $
* $Log$
*****************************************************************************/
#include <cstdarg>
#include "configbase.h"
#include "processoptions.h"
#include "stringutilities.h"
#include "povmsgid.h"
#include "pov_err.h"
BEGIN_POV_BASE_NAMESPACE
ProcessOptions::ProcessOptions(INI_Parser_Table *pit, Cmd_Parser_Table *pct)
{
parse_ini_table = pit;
parse_cmd_table = pct;
}
ProcessOptions::~ProcessOptions()
{
}
int ProcessOptions::ParseFile(const char *filespec, POVMSObjectPtr obj)
{
ITextStream *file = NULL;
const char *currentsection = NULL;
char *sectionname = NULL;
char *filename = NULL;
int err = kNoErr;
POVMSObjectPtr section = NULL;
int currentline = 1;
// split the INI files specification into filename and optional section name
err = Parse_INI_Specification(filespec, filename, sectionname);
if(err == kNoErr)
{
file = OpenFileForRead(filename, obj);
if(file == NULL)
{
// all errors here are non-fatal, the calling code has to decide if an error is fatal
ParseError("Cannot open INI file '%s'.", filename);
err= kCannotOpenFileErr;
}
}
if(err == kNoErr)
{
int token = 0;
// apply options prior to any named section
section = obj;
// read the whole file to the end
while((file->eof() == false) && (err == kNoErr))
{
currentline += Parse_INI_Skip_Space(file, true);
token = file->getchar();
// INI file section name
if(token == '[')
{
// free old section name, if any
if(currentsection != NULL)
delete[] currentsection;
// read until the section name end marker
currentsection = Parse_INI_String(file, ']');
// if the user specified a section name, compare the two and enable reading
if((sectionname != NULL) && (currentsection != NULL))
{
if(pov_stricmp(currentsection, sectionname) == 0)
section = obj; // named section matches specified section name, apply options
else
section = NULL; // named section does not match specified section name, ignore options
}
// if there was no user specified section name, ignore all named sections
else
section = NULL; // no section name was specified, ignore options in named section
}
// skip lines that do not belong to the desired sections
else if(section == NULL)
{
currentline += Parse_INI_Skip_Line(file);
}
// fully process lines in desired sections
else
{
switch(token)
{
// end of file
case EOF:
break;
// quoted string
case '\"':
case '\'':
err = kFalseErr;
break;
// POV-Ray-style INI file with command-line switch
case '+':
case '-':
// POV-Ray-style INI file with system specific command-line switch on some systems (i.e. Windos)
#if(FILENAME_SEPARATOR != '/')
case '/':
#endif
err = Parse_INI_Switch(file, token, section);
break;
// INI file comment
case ';':
case '#':
currentline += Parse_INI_Skip_Line(file);
break;
// INI file option
default:
if(isalnum(token) || (token == '_'))
{
file->ungetchar(token);
ITextStream::FilePos backtrackpos = file->tellg();
err = Parse_INI_Option(file, section);
// only one option is allowed per line
if(err == kNoErr)
currentline += Parse_INI_Skip_Line(file);
else if(err == kParseErr)
{
file->seekg(backtrackpos);
err = kFalseErr;
}
}
else
err = kFalseErr;
break;
}
// if nothing else was appropriate, assume it is some other kind of string requiring special attention
if(err == kFalseErr)
{
char *plainstring = NULL;
if((token == '\"') || (token == '\''))
plainstring = Parse_INI_String(file, token, true);
// if there were no quotes, just read up to the next space or newline
else
plainstring = Parse_INI_String(file, -1, true);
err = ProcessUnknownString(plainstring, obj);
if(plainstring != NULL)
delete[] plainstring;
}
}
}
// all errors here are non-fatal, the calling code has to decide if an error is fatal
if(err != kNoErr)
{
if(currentsection != NULL)
{
ParseErrorAt(file,
"Cannot continue to process INI file '%s' due to a parse error in line %d section '%s'.\n"
"This is not a valid INI file. Check the file for syntax errors, correct them, and try again!\n"
"Valid options in INI files are explained in detail in the reference part of the documentation.",
filename, currentline, currentsection);
}
else
{
ParseErrorAt(file,
"Cannot continue to process INI file '%s' due to a parse error in line %d.\n"
"This is not a valid INI file. Check the file for syntax errors, correct them, and try again!\n"
"Valid options in INI files are explained in detail in the reference part of the documentation.",
filename, currentline);
}
}
if(currentsection != NULL)
delete[] currentsection;
}
if(filename != NULL)
delete[] filename;
if(sectionname != NULL)
delete[] sectionname;
if(file != NULL)
delete file;
return err;
}
int ProcessOptions::ParseString(const char *commandline, POVMSObjectPtr obj, bool singleswitch)
{
int err = kNoErr;
// read the whole command-line to the end
while((*commandline != 0) && (err == kNoErr))
{
if(singleswitch == false) // see if quotes had been stripped outside POV-Ray
Parse_CL_Skip_Space(commandline);
switch(*commandline)
{
// end of command-line
case 0:
break;
// quoted string
case '\"':
case '\'':
err = kFalseErr;
break;
// switch
case '+':
case '-':
// system specific switch on some systems (i.e. Windos)
#if(FILENAME_SEPARATOR != '/')
case '/':
#endif
commandline++;
err = Parse_CL_Switch(commandline, *(commandline - 1), obj, singleswitch);
break;
// INI file style option
default:
if(isalnum(*commandline) || (*commandline == '_'))
{
const char *cltemp = commandline;
err = Parse_CL_Option(commandline, obj, singleswitch);
if(err == kParseErr)
{
commandline = cltemp;
err = kFalseErr;
}
}
else
err = kFalseErr;
break;
}
// if nothing else was appropriate, assume it is some other kind of string requiring special attention
if(err == kFalseErr)
{
int chr = *commandline;
char *plainstring = NULL;
if((chr == '\"') || (chr == '\''))
{
commandline++;
plainstring = Parse_CL_String(commandline, chr);
}
// if there were no quotes, just read up to the next space or newline
else if(singleswitch == false) // see if quotes had been stripped outside POV-Ray
plainstring = Parse_CL_String(commandline);
else
plainstring = Parse_CL_String(commandline, 0);
err = ProcessUnknownString(plainstring, obj);
if(plainstring != NULL)
delete[] plainstring;
}
}
// all errors here are non-fatal, the calling code has to decide if an error is fatal
if(err != kNoErr)
{
if(*commandline != 0)
{
ParseError("Cannot process command-line at '%s' due to a parse error.\n"
"This is not a valid command-line. Check the command-line for syntax errors, correct them, and try again!\n"
"Valid command-line switches are explained in detail in the reference part of the documentation.\n"
"To get a short list of command-line switches, use either the '-h', '-?', '-help' or '--help' switch.",
commandline);
}
else
{
ParseError("Cannot process command-line due to a parse error.\n"
"This is not a valid command-line. Check the command-line for syntax errors, correct them, and try again!\n"
"Valid command-line switches are explained in detail in the reference part of the documentation.\n"
"To get a short list of command-line switches, use either the '-h', '-?', '-help' or '--help' switch.");
}
}
return err;
}
int ProcessOptions::WriteFile(OTextStream *ini_file, POVMSObjectPtr obj)
{
struct INI_Parser_Table *table = parse_ini_table;
// find the keyword
while(table->keyword != NULL)
{
if(WriteOptionFilter(table) == true)
Output_INI_Option(table, obj, ini_file);
table++;
}
return kNoErr;
}
int ProcessOptions::WriteFile(const char *filename, POVMSObjectPtr obj)
{
struct INI_Parser_Table *table = parse_ini_table;
OTextStream *ini_file;
int err = kNoErr;
if(!POV_ALLOW_FILE_WRITE(filename, POV_File_Text_INI))
return kCannotOpenFileErr;
ini_file = OpenFileForWrite(filename, obj);
if(ini_file == NULL)
return kCannotOpenFileErr;
err = WriteFile (ini_file, obj);
delete ini_file;
return err;
}
int ProcessOptions::ReadSpecialOptionHandler(INI_Parser_Table *, char *, POVMSObjectPtr)
{
// do nothing by default
return kNoErr;
}
int ProcessOptions::ReadSpecialSwitchHandler(Cmd_Parser_Table *, char *, POVMSObjectPtr, bool)
{
// do nothing by default
return kNoErr;
}
int ProcessOptions::WriteSpecialOptionHandler(INI_Parser_Table *, POVMSObjectPtr, OTextStream *)
{
// do nothing by default
return kNoErr;
}
bool ProcessOptions::WriteOptionFilter(INI_Parser_Table *)
{
// filter nothing out by default
return true;
}
bool ProcessOptions::ProcessUnknownSwitch(char *, char *, POVMSObjectPtr)
{
// accept no unknown switches by default
return false;
}
int ProcessOptions::ProcessUnknownString(char *, POVMSObjectPtr)
{
// do nothing by default
return kNoErr;
}
void ProcessOptions::ParseError(const char *format, ...)
{
va_list marker;
char error_buffer[1024];
va_start(marker, format);
vsnprintf(error_buffer, 1023, format, marker);
va_end(marker);
fprintf(stderr, "%s\n", error_buffer);
}
void ProcessOptions::ParseErrorAt(ITextStream *file, const char *format, ...)
{
va_list marker;
char error_buffer[1024];
va_start(marker, format);
vsnprintf(error_buffer, 1023, format, marker);
va_end(marker);
fprintf(stderr, "%s\nFile '%s' at line '%d'", error_buffer, file->name(), file->line());
}
void ProcessOptions::WriteError(const char *format, ...)
{
va_list marker;
char error_buffer[1024];
va_start(marker, format);
vsnprintf(error_buffer, 1023, format, marker);
va_end(marker);
fprintf(stderr, "%s\n", error_buffer);
}
int ProcessOptions::Output_INI_Option(INI_Parser_Table *option, POVMSObjectPtr obj, OTextStream *file)
{
POVMSFloat floatval;
POVMSBool b;
POVMSInt intval;
int err = 0;
int l;
POVMSAttribute item;
char *bufptr;
switch(option->type)
{
case kPOVMSType_Int:
if(POVMSUtil_GetInt(obj, option->key, &intval) == 0)
file->printf("%s=%d\n", option->keyword, (int)intval);
break;
case kPOVMSType_Float:
if(POVMSUtil_GetFloat(obj, option->key, &floatval) == 0)
file->printf("%s=%g\n", option->keyword, (float)floatval);
break;
case kPOVMSType_Bool:
if(POVMSUtil_GetBool(obj, option->key, &b) == 0)
{
if(b == true)
file->printf("%s=On\n", option->keyword);
else
file->printf("%s=Off\n", option->keyword);
}
break;
case kPOVObjectClass_File:
err = POVMSObject_Get(obj, &item, option->key);
if(err != 0)
break;
// get the file name and path string
l = 0;
err = POVMSAttr_Size(&item, &l);
if(l > 0)
{
bufptr = new char[l];
bufptr[0] = 0;
if(POVMSAttr_Get(&item, kPOVMSType_CString, bufptr, &l) == 0)
file->printf("%s=\"%s\"\n", option->keyword, bufptr);
delete[] bufptr;
}
(void)POVMSAttr_Delete(&item);
break;
case kPOVMSType_WildCard:
WriteSpecialOptionHandler(option, obj, file);
break;
default:
WriteError("Ignoring unknown INI option.");
break;
}
return err;
}
int ProcessOptions::Parse_INI_Specification(const char *filespec, char *&filename, char *§ionname)
{
const char *sectionpos = strchr(filespec, '[');
// if there is no section string, this is the whole filename
if(sectionpos == NULL)
{
filename = new char[strlen(filespec) + 1];
strcpy(filename, filespec);
}
// if there is a section string, the filename ends at the section beginning
else
{
const char *sectionend = strchr(filespec, ']');
// if there was no section end, this file specification is invalid
if(sectionend == NULL)
return kParamErr;
// if there valid section specification, use it
else
{
// section string starts at sectionpos + 1 and has the length sectionend - sectionpos - 1 + terminating zero
sectionname = new char[sectionend - sectionpos];
strncpy(sectionname, sectionpos + 1, sectionend - sectionpos - 1);
sectionname[sectionend - sectionpos - 1] = 0;
// filename string ends at sectionpos and the the length sectionpos - filespec + terminating zero
filename = new char[sectionpos - filespec + 1];
strncpy(filename, filespec, sectionpos - filespec);
filename[sectionpos - filespec] = 0;
}
}
return kNoErr;
}
int ProcessOptions::Parse_INI_Skip_Space(ITextStream *file, bool countnewlines)
{
int linecount = 0;
// read until the end of file or until a non-space is found
while(file->eof() == false)
{
int chr = file->getchar();
// count newlinegets
if((chr == 10) && (countnewlines == true))
{
int c2 = file->getchar();
if(c2 != 13)
file->ungetchar(c2);
linecount++;
}
else if((chr == 13) && (countnewlines == true))
{
int c2 = file->getchar();
if(c2 != 10)
file->ungetchar(c2);
linecount++;
}
// apart from a newline, spaces and tabs are considered "space"
else if((chr != ' ') && (chr != '\t'))
{
file->ungetchar(chr);
break;
}
}
return linecount;
}
int ProcessOptions::Parse_INI_Skip_Line(ITextStream *file)
{
int linecount = 0;
// read until the end of file or until a newline is found
while(file->eof() == false)
{
int chr = file->getchar();
// count newlines
if(chr == 10)
{
int c2 = file->getchar();
if(c2 != 13)
file->ungetchar(c2);
linecount++;
break;
}
else if(chr == 13)
{
int c2 = file->getchar();
if(c2 != 10)
file->ungetchar(c2);
linecount++;
break;
}
}
return linecount;
}
int ProcessOptions::Parse_INI_Option(ITextStream *file, POVMSObjectPtr obj)
{
struct INI_Parser_Table *table = parse_ini_table;
char *value = NULL;
char *key = NULL;
char chr = 0;
int err = kNoErr;
// read the key string
key = Parse_INI_String(file);
if(key == NULL)
{
ParseErrorAt(file, "Expected key in INI file, no key was found.");
return kParseErr;
}
// find the keyword
while(table->keyword != NULL)
{
if(pov_stricmp(table->keyword, key) == 0)
break;
table++;
}
// return if no valid keyword has been found
if(table->keyword == NULL)
{
ParseErrorAt(file, "Unknown key '%s' in INI file.", key);
delete[] key;
return kParseErr;
}
else
{
delete[] key;
key = NULL;
}
// skip any spaces
(void)Parse_INI_Skip_Space(file, false);
// expect the equal sign
if(file->getchar() != '=')
return kParseErr;
// skip any spaces
(void)Parse_INI_Skip_Space(file, false);
// if the string is quoted, parse it matching quotes
chr = file->getchar();
if((chr == '\"') || (chr == '\''))
value = Parse_INI_String(file, chr);
// if there were no quotes, just read up to the next space or newline
else
{
file->ungetchar(chr);
value = Parse_INI_String(file, -2, true);
}
if(value == NULL)
{
ParseErrorAt(file, "Expected value in INI file, no value was found.");
return kParseErr;
}
err = Process_INI_Option(table, value, obj);
delete[] value;
value = NULL;
// skip any spaces
(void)Parse_INI_Skip_Space(file, false);
// if there is a comma, parse more values and append them
chr = file->getchar();
if(chr == ',')
{
// read more value strings
while((file->eof() == false) && (err == kNoErr))
{
// skip any spaces
(void)Parse_INI_Skip_Space(file, false);
// if the string is quoted, parse it matching quotes
chr = file->getchar();
if((chr == '\"') || (chr == '\''))
value = Parse_INI_String(file, chr);
// if there were no quotes, just read up to the next space or newline
else
{
file->ungetchar(chr);
value = Parse_INI_String(file, -2);
}
if(value == NULL)
{
ParseErrorAt(file, "Expected value in INI file, no value was found.");
return kParseErr;
}
err = Process_INI_Option(table, value, obj);
delete[] value;
value = NULL;
// skip any spaces
(void)Parse_INI_Skip_Space(file, false);
// if there is no other comma, stop parsing values
chr = file->getchar();
if(chr != ',')
{
file->ungetchar(chr);
break;
}
}
}
else
file->ungetchar(chr);
return err;
}
int ProcessOptions::Parse_INI_Switch(ITextStream *file, int token, POVMSObjectPtr obj)
{
struct Cmd_Parser_Table *table = parse_cmd_table;
char *value = NULL;
char *key = NULL;
int err = kNoErr;
int chr = 0;
// read the switch string
key = Parse_INI_String(file);
if(key == NULL)
{
ParseErrorAt(file, "Expected command-line switch in INI file, no command-line switch was found.");
err = kParseErr;
}
else
{
// if there is a quoted string directory following the switch, parse it matching quotes
chr = file->getchar();
if((chr == '\"') || (chr == '\''))
{
char *value = Parse_INI_String(file, chr);
if(value == NULL)
ParseErrorAt(file, "Expected command-line switch in INI file to be followed by quoted parameter.");
}
else
file->ungetchar(chr);
// find the command-line switch
while(table->command != NULL)
{
char *srcptr = key;
const char *dstptr = table->command;
// compared ignoring case until the end of either string has been reached
while((toupper(*srcptr) == toupper(*dstptr)) && (*srcptr != 0) && (*dstptr != 0))
{
srcptr++;
dstptr++;
}
// if the end of the switch string in the table had been reached, see if there are parameters
// to consider and if there are, expect the source string to be followed by those parameters
if((*dstptr) == 0)
{
// if there was a quoted value string and the switch string is longer, this is an unknown switch
if((value != NULL) && (*srcptr != 0))
{
table = NULL;
break;
}
// if there was a quoted value string and the switch matches, use the value string as parameter
else if((value != NULL) && (*srcptr == 0))
srcptr = value;
// only if a paremeter is expected allow it, and vice versa
if(((*srcptr > ' ') && (table->type != kPOVMSType_Null)) || ((*srcptr <= ' ') && (table->type == kPOVMSType_Null)))
{
err = Process_Switch(table, srcptr, obj, (token != '-'));
break;
}
}
table++;
}
// if there was no sucessful match so far, see if it is a system specific switch
if(table == NULL)
{
if(ProcessUnknownSwitch(key, value, obj) == false)
{
if(value != NULL)
ParseErrorAt(file, "Unknown switch '%s' with value '%s' in INI file.", key, value);
else
ParseErrorAt(file, "Unknown switch '%s' in INI file.", key);
err = kParseErr;
}
else
err = kNoErr;
}
}
if(key != NULL)
delete[] key;
if(value != NULL)
delete[] value;
return err;
}
char *ProcessOptions::Parse_INI_String(ITextStream *file, int endchr, bool smartmode)
{
char *str = new char[65536];
char *pos = str;
while((pos - str) < 65535)
{
int chr = file->getchar();
// terminate the string if the end of file has been reached
if(chr == EOF)
break;
// parse to the next space or special token
else if((endchr == -1) || (endchr == -2))
{
if((smartmode == true) && ((chr == ' ') || (chr == '\t')))
{
// In "smart mode" the function called below tries to detect if the
// user is trying to use an unquoted path as value of an INI option.
// The detection logic is detailed in the function below!
file->ungetchar(chr);
if(Parse_INI_String_Smartmode(file) == false)
break;
else
{
chr = file->getchar();
endchr = -3; // switch to special mode
}
}
else if(isspace(chr) || (chr == ',') || (chr == ';') || (chr == '#') || (chr == '\"') || (chr == '\'') ||
((endchr == -1) && ((chr == '[') || (chr == ']') || (chr == '='))))
{
file->ungetchar(chr);
break;
}
}
// this should only be switched on by "smart mode" and parses to either the end of the line or the comment string
else if(endchr == -3)
{
if((chr == ';') || (chr == '#') || (chr == 10) || (chr == 13))
{
file->ungetchar(chr);
break;
}
}
// parse to the next character specified by the caller in endchr
else if(chr == endchr)
break;
*pos = chr;
pos++;
}
*pos = 0;
return str;
}
bool ProcessOptions::Parse_INI_String_Smartmode(ITextStream *file)
{
ITextStream::FilePos backtrackpos = file->tellg();
bool result = false; // false - end string here, true - continue parsing string
struct INI_Parser_Table *table = parse_ini_table;
char *key = NULL;
(void)Parse_INI_Skip_Space(file, false);
switch(file->getchar())
{
// end of file
case EOF:
break; // return false, parsing more of the string simply is not possible
// INI file comment
case ';':
case '#':
break; // return false, this is a comment which terminates the string
// INI value list separator
case ',':
break; // return false, this is a value list of unquoted strings
// POV-Ray-style INI file with command-line switch
case '+':
case '-':
// POV-Ray-style INI file with system specific command-line switch on some systems (i.e. Windos)
#if(FILENAME_SEPARATOR != '/')
case '/':
#endif
if(isalpha(file->getchar()))
break; // return false, this is most likely a command-line
else
file->seekg(backtrackpos); // most likely an unquoted string, so allow parsing it as a whole
// INI file option
default:
// read the key string
key = Parse_INI_String(file);
if(key != NULL)
{
// find the keyword
while(table->keyword != NULL)
{
if(pov_stricmp(table->keyword, key) == 0)
break;
table++;
}
// if no valid keyword has been found
if(table->keyword == NULL)
{
result = true; // return true, this is most likely an unquoted path
ParseErrorAt(file,
"Most likely detected an unquoted string with spaces in INI file. Assuming string ends at the of the line.\n"
"Make sure all strings with spaces are properly quoted in the INI file.\n"
"Use either \" or \' to quote strings. For details, please check the user manual!");
}
delete[] key;
key = NULL;
}
break; // return false, unless the code above did not find a valid keyword
}
file->seekg(backtrackpos);
return result;
}
void ProcessOptions::Parse_CL_Skip_Space(const char *&commandline)
{
// read until the end of the string or until a non-space is found
while(*commandline != 0)
{
// spaces and tabs are considered "space"
if((*commandline != ' ') && (*commandline != '\t'))
break;
commandline++;
}
}
int ProcessOptions::Parse_CL_Switch(const char *&commandline, int token, POVMSObjectPtr obj, bool singleswitch)
{
struct Cmd_Parser_Table *table = parse_cmd_table;
char *value = NULL;
char *key = NULL;
int err = kNoErr;
int chr = 0;
// read the switch string
if(singleswitch == false) // see if quotes had been stripped outside POV-Ray
key = Parse_CL_String(commandline);
else
key = Parse_CL_String(commandline, 0);
if(key == NULL)
{
ParseError("Expected command-line switch on command-line, no command-line switch was found.");
err = kParseErr;
}
else
{
// if there is a quoted string directly following the switch, parse its matching quotes
chr = *commandline;
commandline++;
if((chr == '\"') || (chr == '\''))
{
value = Parse_CL_String(commandline, chr);
if(value == NULL)
ParseError("Expected command-line switch on command-line to be followed by quoted parameter.");
}
else
commandline--;
// find the command-line switch
while(table->command != NULL)
{
char *srcptr = key;
const char *dstptr = table->command;
// compared ignoring case until the end of either string has been reached
while((toupper(*srcptr) == toupper(*dstptr)) && (*srcptr != 0) && (*dstptr != 0))
{
srcptr++;
dstptr++;
}
// if the end of the switch string in the table had been reached, see if there are parameters
// to consider and if there are, expect the source string to be followed by those parameters
if((*dstptr) == 0)
{
// if there was a quoted value string and the switch string is longer, this is an unknown switch
if((value != NULL) && (*srcptr != 0))
{
table = NULL;
break;
}
// if there was a quoted value string and the switch matches, use the value string as parameter
else if((value != NULL) && (*srcptr == 0))
srcptr = value;
// only if a paremeter is expected allow it, and vice versa
if(((*srcptr > ' ') && (table->type != kPOVMSType_Null)) || ((*srcptr <= ' ') && (table->type == kPOVMSType_Null)))
{
err = Process_Switch(table, srcptr, obj, (token != '-'));
break;
}
}
table++;
}
// if there was no successful match so far, see if it is a system specific switch
if(table == NULL)
{
if(ProcessUnknownSwitch(key, value, obj) == false)
{
if(value != NULL)
ParseError("Unknown switch '%s' with value '%s' on command-line.", key, value);
else
ParseError("Unknown switch '%s' on command-line.", key);
err = kParseErr;
}
else
err = kNoErr;
}
}
if(key != NULL)
delete[] key;
if(value != NULL)
delete[] value;
return err;
}
int ProcessOptions::Parse_CL_Option(const char *&commandline, POVMSObjectPtr obj, bool singleswitch)
{
struct INI_Parser_Table *table = parse_ini_table;
char *value = NULL;
char *key = NULL;
char chr = 0;
int err = kNoErr;
// read the key string
key = Parse_CL_String(commandline);
if(key == NULL)
{
ParseError("Expected INI file key on command-line, no key was found.");
return kParseErr;
}
// find the keyword
while(table->keyword != NULL)
{
if(pov_stricmp(table->keyword, key) == 0)
break;
table++;
}
// return false if no valid keyword has been found
if(table->keyword == NULL)
{
delete[] key;
return kParseErr;
}
else
{
delete[] key;
key = NULL;
}
// expect the equal sign
if(*commandline != '=')
return kParseErr;
commandline++;
// if the string is quoted, parse it matching quotes
chr = *commandline;
if((chr == '\"') || (chr == '\''))
{
commandline++;
value = Parse_CL_String(commandline, chr);
}
// if there were no quotes, just read up to the next space or newline
else if(singleswitch == false) // see if quotes had been stripped outside POV-Ray
value = Parse_CL_String(commandline, -2);
else
value = Parse_CL_String(commandline, 0);
if(value == NULL)
{
ParseError("Expected value on command-line, no value was found.");
return kParseErr;
}
err = Process_INI_Option(table, value, obj);
delete[] value;
value = NULL;
return err;
}
char *ProcessOptions::Parse_CL_String(const char *&commandline, int endchr)
{
int maxlen = strlen(commandline) + 1;
char *str = new char[maxlen];
char *pos = str;
while(*commandline != 0)
{
int chr = *commandline;
if(endchr <= -1)
{
if(isspace(chr) || (chr == ';') || (chr == '#') || (chr == '\"') || (chr == '\''))
break;
else if((endchr == -1) && ((chr == '[') || (chr == ']') || (chr == '=')))
break;
}
commandline++;
if(chr == endchr)
break;
*pos = chr;
pos++;
}
*pos = 0;
return str;
}
int ProcessOptions::Process_INI_Option(INI_Parser_Table *option, char *param, POVMSObjectPtr obj)
{
double floatval = 0.0;
int intval = 0;
int intval2 = 0;
int err = kNoErr;
switch(option->type)
{
case kPOVMSType_Int:
if(sscanf(param, "%d", &intval) == 1)
err = POVMSUtil_SetInt(obj, option->key, intval);
else
{
ParseError("Integer parameter expected for option '%s', found '%s'.", option->keyword, param);
err = kParseErr;
}
break;
case kPOVMSType_Float:
if(sscanf(param, "%lf", &floatval) == 1)
err = POVMSUtil_SetFloat(obj, option->key, floatval);
else
{
ParseError("Floating-point parameter expected for option '%s', found '%s'.", option->keyword, param);
err = kParseErr;
}
break;
case kPOVMSType_Bool:
err = POVMSUtil_SetBool(obj, option->key, IsTrue(param));
break;
case kPOVObjectClass_File:
// make the file object
if(err == kNoErr)
err = POVMSUtil_SetString(obj, option->key, param);
else
{
ParseError("File name or path parameter expected for option '%s', found '%s'.", option->keyword, param);
err = kParseErr;
}
break;
case kPOVMSType_WildCard:
err = ReadSpecialOptionHandler(option, param, obj);
break;
default:
err = kParseErr;
break;
}
return err;
}
int ProcessOptions::Process_Switch(Cmd_Parser_Table *option, char *param, POVMSObjectPtr obj, bool is_on)
{
double floatval = 0.0;
int intval = 0;
int intval2 = 0;
int err = 0;
char chr = 0;
if(option->is_switch != kPOVMSType_Null)
{
err = POVMSUtil_SetBool(obj, option->is_switch, is_on);
if(err != kNoErr)
return err;
}
switch(option->type)
{
case kPOVMSType_Int:
if(sscanf(param, "%d", &intval) == 1)
err = POVMSUtil_SetInt(obj, option->key, intval);
else
{
ParseError("Integer parameter expected for switch '%s', found '%s'.", option->command, param);
err = kParseErr;
}
break;
case kPOVMSType_Float:
if(sscanf(param, "%lf", &floatval) == 1)
err = POVMSUtil_SetFloat(obj, option->key, floatval);
else
{
ParseError("Floating-point parameter expected for switch '%s', found '%s'.", option->command, param);
err = kParseErr;
}
break;
case kPOVMSType_Bool:
err = POVMSUtil_SetBool(obj, option->key, IsTrue(param));
break;
case kPOVObjectClass_File:
// make the file object
if(err == kNoErr)
err = POVMSUtil_SetString(obj, option->key, param);
else
{
ParseError("File name or path parameter expected for switch '%s', found '%s'.", option->command, param);
err = kParseErr;
}
break;
case kPOVMSType_WildCard:
err = ReadSpecialSwitchHandler(option, param, obj, is_on);
break;
case kPOVMSType_Null:
break;
default:
err = kParseErr;
break;
}
return err;
}
bool ProcessOptions::Matches(const char *v1, const char *v2)
{
int i = 0;
int ans = 1;
while((ans) && (v1[i] != 0) && (v2[i] != 0))
{
ans = ans && (int)(v1[i] == tolower(v2[i]));
i++;
}
return (ans != 0);
}
bool ProcessOptions::IsTrue(const char *value)
{
return (Matches("on",value) || Matches("true",value) ||
Matches("yes",value) || Matches("1",value));
}
bool ProcessOptions::IsFalse(const char *value)
{
return (Matches("off",value) || Matches("false",value) ||
Matches("no",value) || Matches("0",value));
}
END_POV_BASE_NAMESPACE
| 25.905179 | 127 | 0.63517 | tomberek |
985542ecb86ddd8733babe7bcd1a92f736f771f1 | 5,868 | hpp | C++ | external_drivers/dhi_dfsu/mdal_dhi_dfsu.hpp | Mortal/MDAL | d1763885f868fe08a1a5107828a4f19ed58ede97 | [
"MIT"
] | null | null | null | external_drivers/dhi_dfsu/mdal_dhi_dfsu.hpp | Mortal/MDAL | d1763885f868fe08a1a5107828a4f19ed58ede97 | [
"MIT"
] | null | null | null | external_drivers/dhi_dfsu/mdal_dhi_dfsu.hpp | Mortal/MDAL | d1763885f868fe08a1a5107828a4f19ed58ede97 | [
"MIT"
] | 1 | 2021-04-08T12:21:36.000Z | 2021-04-08T12:21:36.000Z | /*
MDAL - Mesh Data Abstraction Library (MIT License)
Copyright (C) 2020 Vincent Cloarec (vcloarec at gmail dot com)
*/
#ifndef MDAL_DHI_HPP
#define MDAL_DHI_HPP
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <memory>
#include "eum.h"
#include "dfsio.h"
#undef min
#undef max
class Dataset
{
public:
Dataset( LPFILE Fp, LPHEAD Pdfs, LONG timeStepNo, size_t size, bool doublePrecision );
virtual ~Dataset() = default;
//! Fills the buffer with data
virtual int getData( int indexStart, int count, double *buffer ) = 0;
//! Fills the buffer with active flags
int getActive( int indexStart, int count, int *buffer );
//! Clears the data stored in memory
void unload();
protected:
LPFILE mFp;
LPHEAD mPdfs;
bool mLoaded = false;
std::vector<double> mData;
std::vector<int> mActive;
LONG mTimeStepNo = 0;
size_t mSize = 0;
bool mIsDoublePrecision = false;
// read all data and put them in pointed array
bool readData( LONG itemNo, void *ptr ) const;
};
class ScalarDataset: public Dataset
{
public:
ScalarDataset( LPFILE Fp,
LPHEAD Pdfs,
LONG timeStepNo,
LONG itemNo,
size_t size,
bool doublePrecision,
double deleteDoubleValue,
float deleteFloatValue );
int getData( int indexStart, int count, double *buffer ) override;
private:
LONG mItemNo = 0;
double mDoubleDeleteValue = 0.0;
double mFloatDeleteValue = 0.0;
};
class VectorDataset : public Dataset
{
public:
VectorDataset( LPFILE Fp,
LPHEAD Pdfs,
LONG timeStepNo,
LONG itemNoX,
LONG itemNoY,
size_t size,
bool doublePrecision,
double deleteDoubleValue,
float deleteFloatValue );
int getData( int indexStart, int count, double *buffer ) override;
private:
LONG mItemNoX = 0;
LONG mItemNoY = 0;
double mDoubleDeleteValue = 0.0;
double mFloatDeleteValue = 0.0;
};
typedef std::pair<std::string, std::string> Metadata;
class DatasetGroup
{
public:
//! Constructor for a scalar dataset group
DatasetGroup( std::string name,
std::string unit,
LONG idNumber,
bool isDoublePrecision,
LPFILE fp,
LPHEAD pdfs );
//! Constructor for a vector dataset group
DatasetGroup( std::string name,
std::string unit,
LONG idNumberX,
LONG idNumberY,
bool isDoublePrecision,
LPFILE fp,
LPHEAD pdfs );
//! Initiliaze the group by filling it with \a mTimeStepCount datasets ready to load data when needed (lazy loading)
void init( LONG timeStepCount, size_t elementsCount, double deleteDoubleValue, float deleteFloatValue );
const std::string &name() const;
bool isScalar() const;
const std::vector<Metadata> &metadata() const;
int datasetCount() const;
Dataset *dataset( int index ) const;
private:
LPFILE mFp;
LPHEAD mPdfs;
std::string mName;
std::vector<Metadata> mMetadata;
LONG mIdX = 0;
LONG mIdY = 0;
bool mIsDoublePrecision = false;
std::vector < std::unique_ptr<Dataset>> mDatasets;
};
class Mesh
{
public:
~Mesh();
static bool canRead( const std::string &uri );
static std::unique_ptr<Mesh> loadMesh( const std::string &uri );
void close();
//**************** Mesh frame *************
int verticesCount() const;
int facesCount() const;
//! Returqn a pointer to the vertices coordinates for \a index
double *vertexCoordinates( int index );
//! Returns connectivty informations
int connectivity( int startFaceIndex, int faceCount, int *faceOffsetsBuffer, int vertexIndicesBufferLen, int *vertexIndicesBuffer );
//! Returns wkt projection
const std::string &projection() const { return mWktProjection; }
//! Returns mesh extent
void extent( double *xMin, double *xMax, double *yMin, double *yMax ) const;
//**************** datasets *************
int datasetGroupsCount() const;
DatasetGroup *datasetgroup( int i ) const;
//! Returns reference time string (ISO8601)
const std::string &referenceTime() const;
int timeStepCount() const;
double time( int index ) const;
private:
Mesh() = default;
LPFILE mFp;
LPHEAD mPdfs;
std::string mWktProjection = "projection";
std::vector<double> mVertexCoordinates;
std::map<int, size_t> mNodeId2VertexIndex;
int mGapFromVertexToNode = 0;
double mXmin = std::numeric_limits<double>::max();
double mXmax = -std::numeric_limits<double>::max();
double mYmin = std::numeric_limits<double>::max();
double mYmax = -std::numeric_limits<double>::max();
std::vector<std::unique_ptr<DatasetGroup>> mDatasetGroups;
int mTimeStepCount;
std::string mReferenceTime;
std::vector<double> mTimes;
size_t vertexIdToIndex( int id ) const;
std::vector<int> mFaceNodeCount;
std::map<int, size_t> mElemId2faceIndex;
int mGapFromFaceToElement = 0;
size_t faceIdToIndex( int id ) const;
std::vector<int> mConnectivity;
size_t connectivityPosition( int faceIndex ) const;;
size_t mNextFaceIndexForConnectivity = 0; //cache to speed up acces to connectivity
size_t mNextConnectivityPosition = 0; //cache to speed up acces to connectivity
bool populateMeshFrame();
bool setCoordinate( LPVECTOR pvec, LPITEM staticItem, SimpleType itemDatatype, size_t offset, double &min, double &max );
bool populateDatasetGroups();
};
#endif //MDAL_DHI_HPP | 27.679245 | 136 | 0.633265 | Mortal |
985616e67abb831b525c3281a3d599f35c06559f | 2,848 | cc | C++ | chrome/browser/chromeos/web_socket_proxy_helper_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | chrome/browser/chromeos/web_socket_proxy_helper_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/web_socket_proxy_helper_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/chromeos/web_socket_proxy_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
class WebSocketProxyHelperTest : public testing::Test {
public:
void FetchAndTest(const std::string& input,
const std::string& passport,
const std::string& ip,
const std::string& hostname,
int port, bool success) {
std::string passport_out;
std::string ip_out;
std::string hostname_out;
int port_out;
bool result = WebSocketProxyHelper::FetchPassportAddrNamePort(
(uint8*)input.data(), (uint8*)input.data() + input.length(),
&passport_out, &ip_out, &hostname_out, &port_out);
ASSERT_EQ(success, result) << "Input was: " << input;
if (success) {
EXPECT_EQ(passport, passport_out);
EXPECT_EQ(ip, ip_out);
EXPECT_EQ(hostname, hostname_out);
EXPECT_EQ(port, port_out);
}
}
};
TEST_F(WebSocketProxyHelperTest, FetchPassportAddrNamePortSuccess) {
std::vector<std::string> ips;
ips.push_back("127.0.0.1");
ips.push_back("[ab:ab:ab:00:ed:78]");
std::vector<std::string> hostnames = ips;
hostnames.push_back("www.site.com");
hostnames.push_back("localhost");
hostnames.push_back("ab:ab:ab:ab:ab:ab");
ips.push_back(""); // Also valid ip, but not hostname.
std::vector<int> ports;
ports.push_back(1);
ports.push_back(65535);
for (size_t i = 0; i < ips.size(); ++i) {
for (size_t j = 0; j < hostnames.size(); ++j) {
for (size_t k = 0; k < ports.size(); ++k) {
std::string input = "passport:" + ips[i] + ":" +
hostnames[j] + ":" + base::IntToString(ports[k]) + ":";
FetchAndTest(input, "passport", ips[i], hostnames[j], ports[k], true);
}
}
}
}
TEST_F(WebSocketProxyHelperTest, FetchPassportAddrNamePortEmptyPassport) {
FetchAndTest("::localhost:1:", "", "", "", 0, false);
}
TEST_F(WebSocketProxyHelperTest, FetchPassportAddrNamePortBadIpv6) {
FetchAndTest("passport:[12:localhost:1:", "", "", "", 0, false);
}
TEST_F(WebSocketProxyHelperTest, FetchPassportAddrNameEmptyHostname) {
FetchAndTest("passport:::1:", "", "", "", 0, false);
}
TEST_F(WebSocketProxyHelperTest, FetchPassportAddrNameSmallPort) {
FetchAndTest("passport:::0:", "", "", "", 0, false);
}
TEST_F(WebSocketProxyHelperTest, FetchPassportAddrNameBigPort) {
FetchAndTest("passport:::65536:", "", "", "", 0, false);
}
TEST_F(WebSocketProxyHelperTest, FetchPassportAddrNoLastColon) {
FetchAndTest("passport::localhost:1", "", "", "", 0, false);
}
} // namespace chromeos
| 33.904762 | 78 | 0.656601 | pozdnyakov |
9857071301b5ba8687099d6d851100b9c308db46 | 1,670 | cpp | C++ | src/test/main_tests.cpp | coinkeeper/2015-06-22_19-00_ziftrcoin | 7c37ed9518bf822c51fa4de1c74d8e741e3263f6 | [
"MIT"
] | 10 | 2015-03-01T07:06:10.000Z | 2021-03-18T13:19:35.000Z | src/test/main_tests.cpp | coinkeeper/2015-06-22_19-00_ziftrcoin | 7c37ed9518bf822c51fa4de1c74d8e741e3263f6 | [
"MIT"
] | 11 | 2015-03-01T12:10:13.000Z | 2021-02-25T15:48:44.000Z | src/test/main_tests.cpp | coinkeeper/2015-06-22_19-00_ziftrcoin | 7c37ed9518bf822c51fa4de1c74d8e741e3263f6 | [
"MIT"
] | 14 | 2015-03-02T16:44:39.000Z | 2018-04-20T16:27:22.000Z | // Copyright (c) 2014 The Bitcoin Core developers
// Copyright (c) 2015 The ziftrCOIN developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "core.h"
#include "main.h"
#include "chainparams.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(main_tests)
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
// Takes a little longer, but is more accurate
int64_t nMinSum = 0;
int64_t nMaxSum = 0;
int nTotalDays = 2 * Params().GetMidwayPoint();
for (int nDay = 0; nDay < nTotalDays; nDay++)
{
int nHeight = nDay * 24 * 60;
nMinSum += GetBlockValue(nHeight, 0, false);
nMaxSum += GetBlockValue(nHeight, 0, true);
int64_t nMinSubsidy = GetBlockValue(nHeight + 1, 0, false);
int64_t nMaxSubsidy = GetBlockValue(nHeight + 1, 0, true);
BOOST_CHECK(nMinSubsidy >= MIN_SUBSIDY);
BOOST_CHECK(nMaxSubsidy >= MIN_SUBSIDY);
// Should have the same value through out the day (1440 block period)
BOOST_CHECK(nMinSubsidy == GetBlockValue(nHeight + 24 * 60 - 2, 0, false));
BOOST_CHECK(nMaxSubsidy == GetBlockValue(nHeight + 24 * 60 - 2, 0, true));
nMinSum += nMinSubsidy * (24 * 60 - 1);
nMaxSum += nMaxSubsidy * (24 * 60 - 1);
BOOST_CHECK(MoneyRange(nMinSum));
BOOST_CHECK(MoneyRange(nMaxSum));
}
// printf("min sum : %llu\n", nMinSum);
// printf("max sum : %llu\n", nMaxSum);
BOOST_CHECK(nMinSum == 993742021533401ULL);
BOOST_CHECK(nMaxSum == 1041179115130496ULL);
}
BOOST_AUTO_TEST_SUITE_END()
| 30.363636 | 83 | 0.656287 | coinkeeper |
98576a4bae953234331282ed52e8eabcd5564470 | 2,182 | cpp | C++ | N. Phone Numbers.cpp | Mahboub99/CodeForces_UVA | c5cfad64d573ef21b67d97e17bd4f14fb01de9fa | [
"MIT"
] | 3 | 2020-01-03T11:38:43.000Z | 2021-03-13T13:34:49.000Z | N. Phone Numbers.cpp | Mahboub99/CodeForces_UVA | c5cfad64d573ef21b67d97e17bd4f14fb01de9fa | [
"MIT"
] | null | null | null | N. Phone Numbers.cpp | Mahboub99/CodeForces_UVA | c5cfad64d573ef21b67d97e17bd4f14fb01de9fa | [
"MIT"
] | 2 | 2019-10-16T19:52:15.000Z | 2019-10-28T08:52:38.000Z | #include <iostream>
#include <cmath>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <iomanip>
#include <assert.h>
#include <vector>
#include <cstring>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <set>
#include <complex>
#include <list>
#include <climits>
#include <cctype>
#include <bitset>
#include <numeric>
#include<array>
#include<tuple>
#include <utility>
#include <functional>
#include <locale>
#define all(v) v.begin(),v.end()
#define mp make_pair
#define pb push_back
typedef long long int ll ;
#define dbg printf("in\n");
#define nl printf("\n");
#define pp pair<int,int>
#define N 21
using namespace std;
inline bool ends_with(std::string const & value, std::string const & ending)
{
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
bool cmp(string a,string b)
{
return a.length()<b.length();
}
int main()
{
int i,j,k;
int n,m,x;
string s, t;
map<string,vector<string> > mp;
scanf("%d",&n);
for(i=0;i<n;i++)
{
cin>>s;
scanf("%d",&m);
for(j=0;j<m;j++)
{
cin>>t;
mp[s].push_back(t);
}
}
vector<string> v;
map<string,vector<string> >::iterator p=mp.begin();
printf("%d\n",mp.size());
while(p!=mp.end())
{
v.clear();
v=p->second;
sort(v.begin(),v.end(),cmp);
for(i=0;i<v.size()-1;i++)
{
for(j=i+1;j<v.size();j++)
{
if(ends_with(v[j],v[i]))
{
v[i]="#";break;
}
}
}
s=p->first;x=0;
cout<<s<<" ";
for(i=0;i<v.size();i++)
{
if(v[i]!="#")
x++;
}
cout<<x<<" ";
for(i=0;i<v.size();i++)
{
if(v[i]!="#")
cout<<v[i]<<" ";
}
p++;printf("\n");
}
return 0;
}
| 18.973913 | 76 | 0.482126 | Mahboub99 |
985b8f3ef7e88804f57fd6c3beeec9d92ead404f | 1,287 | cpp | C++ | k-diff_pairs_in_an_array.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | k-diff_pairs_in_an_array.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | k-diff_pairs_in_an_array.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/k-diff-pairs-in-an-array/
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
int soln = 0;
int len = nums.size();
int nummk = 0;
std::unordered_map<int, int> h_map;
std::unordered_map<int, int> soln_vec;
if (k < 0) {
return 0;
}
if (k == 0) {
for (auto const& num : nums) {
if (soln_vec.count(num) > 0 && soln_vec[num] == 1) {
soln++;
soln_vec[num]++;
continue;
}
soln_vec.insert({num, 1});
}
} else {
for (auto const& num : nums) {
nummk = num - k;
if (h_map.count(nummk) > 0) continue;
h_map.insert({nummk, num});
}
for (auto const& [key, val] : h_map) {
if (h_map.count(val) > 0){
soln++;
// soln_vec.insert({val, h_map[val]});
}
}
}
// for (auto const& [key, val] : soln_vec) {
// cout << "(" << key << ", " << val << ")" << endl;
// }
return soln;
}
}; | 26.265306 | 68 | 0.37296 | shafitek |
986292ff951cb4ffac1ada6a5798601682b5cd3e | 2,323 | cpp | C++ | 3rdparty/webkit/Source/WebCore/dom/QualifiedName.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2020-05-25T16:06:49.000Z | 2020-05-25T16:06:49.000Z | 3rdparty/webkit/Source/WebCore/dom/QualifiedName.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | null | null | null | 3rdparty/webkit/Source/WebCore/dom/QualifiedName.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2019-01-25T13:55:25.000Z | 2019-01-25T13:55:25.000Z | /*
* Copyright (C) 2005, 2006, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "QualifiedName.h"
#include "QualifiedNameCache.h"
#include "ThreadGlobalData.h"
#include <wtf/Assertions.h>
namespace WebCore {
QualifiedName::QualifiedName(const AtomicString& p, const AtomicString& l, const AtomicString& n)
: m_impl(threadGlobalData().qualifiedNameCache().getOrCreate(QualifiedNameComponents { p.impl(), l.impl(), n.isEmpty() ? nullptr : n.impl() }))
{
}
QualifiedName::QualifiedNameImpl::~QualifiedNameImpl()
{
threadGlobalData().qualifiedNameCache().remove(*this);
}
// Global init routines
LazyNeverDestroyed<const QualifiedName> anyName;
void QualifiedName::init()
{
static bool initialized = false;
if (initialized)
return;
ASSERT_WITH_MESSAGE(WTF::nullAtomData.isConstructed(), "AtomicString::init should have been called");
anyName.construct(nullAtom(), starAtom(), starAtom());
initialized = true;
}
const QualifiedName& nullQName()
{
static NeverDestroyed<QualifiedName> nullName(nullAtom(), nullAtom(), nullAtom());
return nullName;
}
const AtomicString& QualifiedName::localNameUpper() const
{
if (!m_impl->m_localNameUpper)
m_impl->m_localNameUpper = m_impl->m_localName.convertToASCIIUppercase();
return m_impl->m_localNameUpper;
}
unsigned QualifiedName::QualifiedNameImpl::computeHash() const
{
QualifiedNameComponents components = { m_prefix.impl(), m_localName.impl(), m_namespace.impl() };
return hashComponents(components);
}
}
| 31.821918 | 147 | 0.740852 | mchiasson |
9863602af7a9e2b9c49cd752da9b49ef45576f21 | 26,286 | cpp | C++ | pmem-mariadb/plugin/handler_socket/handlersocket/hstcpsvr_worker.cpp | wc222/pmdk-examples | 64aadc3a70471c469ac8e214eb1e04ff47cf18ff | [
"BSD-3-Clause"
] | 1 | 2019-10-31T08:25:52.000Z | 2019-10-31T08:25:52.000Z | pmem-mariadb/plugin/handler_socket/handlersocket/hstcpsvr_worker.cpp | WSCWDA/pmdk-examples | c3d079e52cd18b0e14836ef42bad9a995336bf90 | [
"BSD-3-Clause"
] | 1 | 2021-02-24T05:26:44.000Z | 2021-02-24T05:26:44.000Z | pmem-mariadb/plugin/handler_socket/handlersocket/hstcpsvr_worker.cpp | isabella232/pmdk-examples | be7a5a18ba7bb8931e512f6d552eadf820fa2235 | [
"BSD-3-Clause"
] | 2 | 2022-02-27T14:00:01.000Z | 2022-03-31T06:24:22.000Z |
// vim:sw=2:ai
/*
* Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
* See COPYRIGHT.txt for details.
*/
#include <my_global.h>
#include <netinet/in.h>
#include <errno.h>
#include <poll.h>
#include <unistd.h>
#include <stdexcept>
#include <signal.h>
#include <list>
#if __linux__
#include <sys/epoll.h>
#endif
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#include "hstcpsvr_worker.hpp"
#include "string_buffer.hpp"
#include "auto_ptrcontainer.hpp"
#include "string_util.hpp"
#include "escape.hpp"
#define DBG_FD(x)
#define DBG_TR(x)
#define DBG_EP(x)
#define DBG_MULTI(x)
/* TODO */
#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
namespace dena {
struct dbconnstate {
string_buffer readbuf;
string_buffer writebuf;
std::vector<prep_stmt> prep_stmts;
size_t resp_begin_pos;
size_t find_nl_pos;
void reset() {
readbuf.clear();
writebuf.clear();
prep_stmts.clear();
resp_begin_pos = 0;
find_nl_pos = 0;
}
dbconnstate() : resp_begin_pos(0), find_nl_pos(0) { }
};
struct hstcpsvr_conn;
typedef auto_ptrcontainer< std::list<hstcpsvr_conn *> > hstcpsvr_conns_type;
struct hstcpsvr_conn : public dbcallback_i {
public:
auto_file fd;
sockaddr_storage addr;
size_socket addr_len;
dbconnstate cstate;
std::string err;
size_t readsize;
bool nonblocking;
bool read_finished;
bool write_finished;
time_t nb_last_io;
hstcpsvr_conns_type::iterator conns_iter;
bool authorized;
public:
bool closed() const;
bool ok_to_close() const;
void reset();
int accept(const hstcpsvr_shared_c& cshared);
bool write_more(bool *more_r = 0);
bool read_more(bool *more_r = 0);
public:
virtual void dbcb_set_prep_stmt(size_t pst_id, const prep_stmt& v);
virtual const prep_stmt *dbcb_get_prep_stmt(size_t pst_id) const;
virtual void dbcb_resp_short(uint32_t code, const char *msg);
virtual void dbcb_resp_short_num(uint32_t code, uint32_t value);
virtual void dbcb_resp_short_num64(uint32_t code, uint64_t value);
virtual void dbcb_resp_begin(size_t num_flds);
virtual void dbcb_resp_entry(const char *fld, size_t fldlen);
virtual void dbcb_resp_end();
virtual void dbcb_resp_cancel();
public:
hstcpsvr_conn() : addr_len(sizeof(addr)), readsize(4096),
nonblocking(false), read_finished(false), write_finished(false),
nb_last_io(0), authorized(false) { }
};
bool
hstcpsvr_conn::closed() const
{
return fd.get() < 0;
}
bool
hstcpsvr_conn::ok_to_close() const
{
return write_finished || (read_finished && cstate.writebuf.size() == 0);
}
void
hstcpsvr_conn::reset()
{
addr = sockaddr_storage();
addr_len = sizeof(addr);
cstate.reset();
fd.reset();
read_finished = false;
write_finished = false;
}
int
hstcpsvr_conn::accept(const hstcpsvr_shared_c& cshared)
{
reset();
return socket_accept(cshared.listen_fd.get(), fd, cshared.sockargs, addr,
addr_len, err);
}
bool
hstcpsvr_conn::write_more(bool *more_r)
{
if (write_finished || cstate.writebuf.size() == 0) {
return false;
}
const size_t wlen = cstate.writebuf.size();
ssize_t len = send(fd.get(), cstate.writebuf.begin(), wlen, MSG_NOSIGNAL);
if (len <= 0) {
if (len == 0 || !nonblocking || errno != EWOULDBLOCK) {
cstate.writebuf.clear();
write_finished = true;
}
return false;
}
cstate.writebuf.erase_front(len);
/* FIXME: reallocate memory if too large */
if (more_r) {
*more_r = (static_cast<size_t>(len) == wlen);
}
return true;
}
bool
hstcpsvr_conn::read_more(bool *more_r)
{
if (read_finished) {
return false;
}
const size_t block_size = readsize > 4096 ? readsize : 4096;
char *wp = cstate.readbuf.make_space(block_size);
const ssize_t len = read(fd.get(), wp, block_size);
if (len <= 0) {
if (len == 0 || !nonblocking || errno != EWOULDBLOCK) {
read_finished = true;
}
return false;
}
cstate.readbuf.space_wrote(len);
if (more_r) {
*more_r = (static_cast<size_t>(len) == block_size);
}
return true;
}
void
hstcpsvr_conn::dbcb_set_prep_stmt(size_t pst_id, const prep_stmt& v)
{
if (cstate.prep_stmts.size() <= pst_id) {
cstate.prep_stmts.resize(pst_id + 1);
}
cstate.prep_stmts[pst_id] = v;
}
const prep_stmt *
hstcpsvr_conn::dbcb_get_prep_stmt(size_t pst_id) const
{
if (cstate.prep_stmts.size() <= pst_id) {
return 0;
}
return &cstate.prep_stmts[pst_id];
}
void
hstcpsvr_conn::dbcb_resp_short(uint32_t code, const char *msg)
{
write_ui32(cstate.writebuf, code);
const size_t msglen = strlen(msg);
if (msglen != 0) {
cstate.writebuf.append_literal("\t1\t");
cstate.writebuf.append(msg, msg + msglen);
} else {
cstate.writebuf.append_literal("\t1");
}
cstate.writebuf.append_literal("\n");
}
void
hstcpsvr_conn::dbcb_resp_short_num(uint32_t code, uint32_t value)
{
write_ui32(cstate.writebuf, code);
cstate.writebuf.append_literal("\t1\t");
write_ui32(cstate.writebuf, value);
cstate.writebuf.append_literal("\n");
}
void
hstcpsvr_conn::dbcb_resp_short_num64(uint32_t code, uint64_t value)
{
write_ui32(cstate.writebuf, code);
cstate.writebuf.append_literal("\t1\t");
write_ui64(cstate.writebuf, value);
cstate.writebuf.append_literal("\n");
}
void
hstcpsvr_conn::dbcb_resp_begin(size_t num_flds)
{
cstate.resp_begin_pos = cstate.writebuf.size();
cstate.writebuf.append_literal("0\t");
write_ui32(cstate.writebuf, num_flds);
}
void
hstcpsvr_conn::dbcb_resp_entry(const char *fld, size_t fldlen)
{
if (fld != 0) {
cstate.writebuf.append_literal("\t");
escape_string(cstate.writebuf, fld, fld + fldlen);
} else {
static const char t[] = "\t\0";
cstate.writebuf.append(t, t + 2);
}
}
void
hstcpsvr_conn::dbcb_resp_end()
{
cstate.writebuf.append_literal("\n");
cstate.resp_begin_pos = 0;
}
void
hstcpsvr_conn::dbcb_resp_cancel()
{
cstate.writebuf.resize(cstate.resp_begin_pos);
cstate.resp_begin_pos = 0;
}
struct hstcpsvr_worker : public hstcpsvr_worker_i, private noncopyable {
hstcpsvr_worker(const hstcpsvr_worker_arg& arg);
virtual void run();
private:
const hstcpsvr_shared_c& cshared;
volatile hstcpsvr_shared_v& vshared;
long worker_id;
dbcontext_ptr dbctx;
hstcpsvr_conns_type conns; /* conns refs dbctx */
time_t last_check_time;
std::vector<pollfd> pfds;
#ifdef __linux__
std::vector<epoll_event> events_vec;
auto_file epoll_fd;
#endif
bool accept_enabled;
int accept_balance;
std::vector<string_ref> invalues_work;
std::vector<record_filter> filters_work;
private:
int run_one_nb();
int run_one_ep();
void execute_lines(hstcpsvr_conn& conn);
void execute_line(char *start, char *finish, hstcpsvr_conn& conn);
void do_open_index(char *start, char *finish, hstcpsvr_conn& conn);
void do_exec_on_index(char *cmd_begin, char *cmd_end, char *start,
char *finish, hstcpsvr_conn& conn);
void do_authorization(char *start, char *finish, hstcpsvr_conn& conn);
};
hstcpsvr_worker::hstcpsvr_worker(const hstcpsvr_worker_arg& arg)
: cshared(*arg.cshared), vshared(*arg.vshared), worker_id(arg.worker_id),
dbctx(cshared.dbptr->create_context(cshared.for_write_flag)),
last_check_time(time(0)), accept_enabled(true), accept_balance(0)
{
#ifdef __linux__
if (cshared.sockargs.use_epoll) {
epoll_fd.reset(epoll_create(10));
if (epoll_fd.get() < 0) {
fatal_abort("epoll_create");
}
epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.ptr = 0;
if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, cshared.listen_fd.get(), &ev)
!= 0) {
fatal_abort("epoll_ctl EPOLL_CTL_ADD");
}
events_vec.resize(10240);
}
#endif
accept_balance = cshared.conf.get_int("accept_balance", 0);
}
namespace {
struct thr_init {
thr_init(const dbcontext_ptr& dc, volatile int& shutdown_flag) : dbctx(dc) {
dbctx->init_thread(this, shutdown_flag);
}
~thr_init() {
dbctx->term_thread();
}
const dbcontext_ptr& dbctx;
};
}; // namespace
void
hstcpsvr_worker::run()
{
thr_init initobj(dbctx, vshared.shutdown);
#ifdef __linux__
if (cshared.sockargs.use_epoll) {
while (!vshared.shutdown && dbctx->check_alive()) {
run_one_ep();
}
} else if (cshared.sockargs.nonblocking) {
while (!vshared.shutdown && dbctx->check_alive()) {
run_one_nb();
}
} else {
/* UNUSED */
fatal_abort("run_one");
}
#else
while (!vshared.shutdown && dbctx->check_alive()) {
run_one_nb();
}
#endif
}
int
hstcpsvr_worker::run_one_nb()
{
size_t nfds = 0;
/* CLIENT SOCKETS */
for (hstcpsvr_conns_type::const_iterator i = conns.begin();
i != conns.end(); ++i) {
if (pfds.size() <= nfds) {
pfds.resize(nfds + 1);
}
pollfd& pfd = pfds[nfds++];
pfd.fd = (*i)->fd.get();
short ev = 0;
if ((*i)->cstate.writebuf.size() != 0) {
ev = POLLOUT;
} else {
ev = POLLIN;
}
pfd.events = pfd.revents = ev;
}
/* LISTENER */
{
const size_t cpt = cshared.nb_conn_per_thread;
const short ev = (cpt > nfds) ? POLLIN : 0;
if (pfds.size() <= nfds) {
pfds.resize(nfds + 1);
}
pollfd& pfd = pfds[nfds++];
pfd.fd = cshared.listen_fd.get();
pfd.events = pfd.revents = ev;
}
/* POLL */
const int npollev = poll(&pfds[0], nfds, 1 * 1000);
dbctx->set_statistics(conns.size(), npollev);
const time_t now = time(0);
size_t j = 0;
const short mask_in = ~POLLOUT;
const short mask_out = POLLOUT | POLLERR | POLLHUP | POLLNVAL;
/* READ */
for (hstcpsvr_conns_type::iterator i = conns.begin(); i != conns.end();
++i, ++j) {
pollfd& pfd = pfds[j];
if ((pfd.revents & mask_in) == 0) {
continue;
}
hstcpsvr_conn& conn = **i;
if (conn.read_more()) {
if (conn.cstate.readbuf.size() > 0) {
const char ch = conn.cstate.readbuf.begin()[0];
if (ch == 'Q') {
vshared.shutdown = 1;
} else if (ch == '/') {
conn.cstate.readbuf.clear();
conn.cstate.find_nl_pos = 0;
conn.cstate.writebuf.clear();
conn.read_finished = true;
conn.write_finished = true;
}
}
conn.nb_last_io = now;
}
}
/* EXECUTE */
j = 0;
for (hstcpsvr_conns_type::iterator i = conns.begin(); i != conns.end();
++i, ++j) {
pollfd& pfd = pfds[j];
if ((pfd.revents & mask_in) == 0 || (*i)->cstate.readbuf.size() == 0) {
continue;
}
execute_lines(**i);
}
/* COMMIT */
dbctx->unlock_tables_if();
const bool commit_error = dbctx->get_commit_error();
dbctx->clear_error();
/* WRITE/CLOSE */
j = 0;
for (hstcpsvr_conns_type::iterator i = conns.begin(); i != conns.end();
++j) {
pollfd& pfd = pfds[j];
hstcpsvr_conn& conn = **i;
hstcpsvr_conns_type::iterator icur = i;
++i;
if (commit_error) {
conn.reset();
continue;
}
if ((pfd.revents & (mask_out | mask_in)) != 0) {
if (conn.write_more()) {
conn.nb_last_io = now;
}
}
if (cshared.sockargs.timeout != 0 &&
conn.nb_last_io + cshared.sockargs.timeout < now) {
conn.reset();
}
if (conn.closed() || conn.ok_to_close()) {
conns.erase_ptr(icur);
}
}
/* ACCEPT */
{
pollfd& pfd = pfds[nfds - 1];
if ((pfd.revents & mask_in) != 0) {
std::auto_ptr<hstcpsvr_conn> c(new hstcpsvr_conn());
c->nonblocking = true;
c->readsize = cshared.readsize;
c->accept(cshared);
if (c->fd.get() >= 0) {
if (fcntl(c->fd.get(), F_SETFL, O_NONBLOCK) != 0) {
fatal_abort("F_SETFL O_NONBLOCK");
}
c->nb_last_io = now;
conns.push_back_ptr(c);
} else {
/* errno == 11 (EAGAIN) is not a fatal error. */
DENA_VERBOSE(100, fprintf(stderr,
"accept failed: errno=%d (not fatal)\n", errno));
}
}
}
DENA_VERBOSE(30, fprintf(stderr, "nb: %p nfds=%zu cns=%zu\n", this, nfds,
conns.size()));
if (conns.empty()) {
dbctx->close_tables_if();
}
dbctx->set_statistics(conns.size(), 0);
return 0;
}
#ifdef __linux__
int
hstcpsvr_worker::run_one_ep()
{
epoll_event *const events = &events_vec[0];
const size_t num_events = events_vec.size();
const time_t now = time(0);
size_t in_count = 0, out_count = 0, accept_count = 0;
int nfds = epoll_wait(epoll_fd.get(), events, num_events, 1000);
/* READ/ACCEPT */
dbctx->set_statistics(conns.size(), nfds);
for (int i = 0; i < nfds; ++i) {
epoll_event& ev = events[i];
if ((ev.events & EPOLLIN) == 0) {
continue;
}
hstcpsvr_conn *const conn = static_cast<hstcpsvr_conn *>(ev.data.ptr);
if (conn == 0) {
/* listener */
++accept_count;
DBG_EP(fprintf(stderr, "IN listener\n"));
std::auto_ptr<hstcpsvr_conn> c(new hstcpsvr_conn());
c->nonblocking = true;
c->readsize = cshared.readsize;
c->accept(cshared);
if (c->fd.get() >= 0) {
if (fcntl(c->fd.get(), F_SETFL, O_NONBLOCK) != 0) {
fatal_abort("F_SETFL O_NONBLOCK");
}
epoll_event cev;
memset(&cev, 0, sizeof(cev));
cev.events = EPOLLIN | EPOLLOUT | EPOLLET;
cev.data.ptr = c.get();
c->nb_last_io = now;
const int fd = c->fd.get();
conns.push_back_ptr(c);
conns.back()->conns_iter = --conns.end();
if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, fd, &cev) != 0) {
fatal_abort("epoll_ctl EPOLL_CTL_ADD");
}
} else {
DENA_VERBOSE(100, fprintf(stderr,
"accept failed: errno=%d (not fatal)\n", errno));
}
} else {
/* client connection */
++in_count;
DBG_EP(fprintf(stderr, "IN client\n"));
bool more_data = false;
while (conn->read_more(&more_data)) {
DBG_EP(fprintf(stderr, "IN client read_more\n"));
conn->nb_last_io = now;
if (!more_data) {
break;
}
}
}
}
/* EXECUTE */
for (int i = 0; i < nfds; ++i) {
epoll_event& ev = events[i];
hstcpsvr_conn *const conn = static_cast<hstcpsvr_conn *>(ev.data.ptr);
if ((ev.events & EPOLLIN) == 0 || conn == 0 ||
conn->cstate.readbuf.size() == 0) {
continue;
}
const char ch = conn->cstate.readbuf.begin()[0];
if (ch == 'Q') {
vshared.shutdown = 1;
} else if (ch == '/') {
conn->cstate.readbuf.clear();
conn->cstate.find_nl_pos = 0;
conn->cstate.writebuf.clear();
conn->read_finished = true;
conn->write_finished = true;
} else {
execute_lines(*conn);
}
}
/* COMMIT */
dbctx->unlock_tables_if();
const bool commit_error = dbctx->get_commit_error();
dbctx->clear_error();
/* WRITE */
for (int i = 0; i < nfds; ++i) {
epoll_event& ev = events[i];
hstcpsvr_conn *const conn = static_cast<hstcpsvr_conn *>(ev.data.ptr);
if (commit_error && conn != 0) {
conn->reset();
continue;
}
if ((ev.events & EPOLLOUT) == 0) {
continue;
}
++out_count;
if (conn == 0) {
/* listener */
DBG_EP(fprintf(stderr, "OUT listener\n"));
} else {
/* client connection */
DBG_EP(fprintf(stderr, "OUT client\n"));
bool more_data = false;
while (conn->write_more(&more_data)) {
DBG_EP(fprintf(stderr, "OUT client write_more\n"));
conn->nb_last_io = now;
if (!more_data) {
break;
}
}
}
}
/* CLOSE */
for (int i = 0; i < nfds; ++i) {
epoll_event& ev = events[i];
hstcpsvr_conn *const conn = static_cast<hstcpsvr_conn *>(ev.data.ptr);
if (conn != 0 && conn->ok_to_close()) {
DBG_EP(fprintf(stderr, "CLOSE close\n"));
conns.erase_ptr(conn->conns_iter);
}
}
/* TIMEOUT & cleanup */
if (last_check_time + 10 < now) {
for (hstcpsvr_conns_type::iterator i = conns.begin();
i != conns.end(); ) {
hstcpsvr_conns_type::iterator icur = i;
++i;
if (cshared.sockargs.timeout != 0 &&
(*icur)->nb_last_io + cshared.sockargs.timeout < now) {
conns.erase_ptr((*icur)->conns_iter);
}
}
last_check_time = now;
DENA_VERBOSE(20, fprintf(stderr, "ep: %p nfds=%d cns=%zu\n", this, nfds,
conns.size()));
}
DENA_VERBOSE(30, fprintf(stderr, "%p in=%zu out=%zu ac=%zu, cns=%zu\n",
this, in_count, out_count, accept_count, conns.size()));
if (conns.empty()) {
dbctx->close_tables_if();
}
/* STATISTICS */
const size_t num_conns = conns.size();
dbctx->set_statistics(num_conns, 0);
/* ENABLE/DISABLE ACCEPT */
if (accept_balance != 0) {
cshared.thread_num_conns[worker_id] = num_conns;
size_t total_num_conns = 0;
for (long i = 0; i < cshared.num_threads; ++i) {
total_num_conns += cshared.thread_num_conns[i];
}
bool e_acc = false;
if (num_conns < 10 ||
total_num_conns * 2 > num_conns * cshared.num_threads) {
e_acc = true;
}
epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.ptr = 0;
if (e_acc == accept_enabled) {
} else if (e_acc) {
if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, cshared.listen_fd.get(), &ev)
!= 0) {
fatal_abort("epoll_ctl EPOLL_CTL_ADD");
}
} else {
if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_DEL, cshared.listen_fd.get(), &ev)
!= 0) {
fatal_abort("epoll_ctl EPOLL_CTL_ADD");
}
}
accept_enabled = e_acc;
}
return 0;
}
#endif
void
hstcpsvr_worker::execute_lines(hstcpsvr_conn& conn)
{
DBG_MULTI(int cnt = 0);
dbconnstate& cstate = conn.cstate;
char *buf_end = cstate.readbuf.end();
char *line_begin = cstate.readbuf.begin();
char *find_pos = line_begin + cstate.find_nl_pos;
while (true) {
char *const nl = memchr_char(find_pos, '\n', buf_end - find_pos);
if (nl == 0) {
break;
}
char *const lf = (line_begin != nl && nl[-1] == '\r') ? nl - 1 : nl;
DBG_MULTI(cnt++);
execute_line(line_begin, lf, conn);
find_pos = line_begin = nl + 1;
}
cstate.readbuf.erase_front(line_begin - cstate.readbuf.begin());
cstate.find_nl_pos = cstate.readbuf.size();
DBG_MULTI(fprintf(stderr, "cnt=%d\n", cnt));
}
void
hstcpsvr_worker::execute_line(char *start, char *finish, hstcpsvr_conn& conn)
{
/* safe to modify, safe to dereference 'finish' */
char *const cmd_begin = start;
read_token(start, finish);
char *const cmd_end = start;
skip_one(start, finish);
if (cmd_begin == cmd_end) {
return conn.dbcb_resp_short(2, "cmd");
}
if (cmd_begin + 1 == cmd_end) {
if (cmd_begin[0] == 'P') {
if (cshared.require_auth && !conn.authorized) {
return conn.dbcb_resp_short(3, "unauth");
}
return do_open_index(start, finish, conn);
}
if (cmd_begin[0] == 'A') {
return do_authorization(start, finish, conn);
}
}
if (cmd_begin[0] >= '0' && cmd_begin[0] <= '9') {
if (cshared.require_auth && !conn.authorized) {
return conn.dbcb_resp_short(3, "unauth");
}
return do_exec_on_index(cmd_begin, cmd_end, start, finish, conn);
}
return conn.dbcb_resp_short(2, "cmd");
}
void
hstcpsvr_worker::do_open_index(char *start, char *finish, hstcpsvr_conn& conn)
{
const size_t pst_id = read_ui32(start, finish);
skip_one(start, finish);
/* dbname */
char *const dbname_begin = start;
read_token(start, finish);
char *const dbname_end = start;
skip_one(start, finish);
/* tblname */
char *const tblname_begin = start;
read_token(start, finish);
char *const tblname_end = start;
skip_one(start, finish);
/* idxname */
char *const idxname_begin = start;
read_token(start, finish);
char *const idxname_end = start;
skip_one(start, finish);
/* retfields */
char *const retflds_begin = start;
read_token(start, finish);
char *const retflds_end = start;
skip_one(start, finish);
/* filfields */
char *const filflds_begin = start;
read_token(start, finish);
char *const filflds_end = start;
dbname_end[0] = 0;
tblname_end[0] = 0;
idxname_end[0] = 0;
retflds_end[0] = 0;
filflds_end[0] = 0;
cmd_open_args args;
args.pst_id = pst_id;
args.dbn = dbname_begin;
args.tbl = tblname_begin;
args.idx = idxname_begin;
args.retflds = retflds_begin;
args.filflds = filflds_begin;
return dbctx->cmd_open(conn, args);
}
void
hstcpsvr_worker::do_exec_on_index(char *cmd_begin, char *cmd_end, char *start,
char *finish, hstcpsvr_conn& conn)
{
cmd_exec_args args;
const size_t pst_id = read_ui32(cmd_begin, cmd_end);
if (pst_id >= conn.cstate.prep_stmts.size()) {
return conn.dbcb_resp_short(2, "stmtnum");
}
args.pst = &conn.cstate.prep_stmts[pst_id];
char *const op_begin = start;
read_token(start, finish);
char *const op_end = start;
args.op = string_ref(op_begin, op_end);
skip_one(start, finish);
const uint32_t fldnum = read_ui32(start, finish);
string_ref *const flds = DENA_ALLOCA_ALLOCATE(string_ref, fldnum);
auto_alloca_free<string_ref> flds_autofree(flds);
args.kvals = flds;
args.kvalslen = fldnum;
for (size_t i = 0; i < fldnum; ++i) {
skip_one(start, finish);
char *const f_begin = start;
read_token(start, finish);
char *const f_end = start;
if (is_null_expression(f_begin, f_end)) {
/* null */
flds[i] = string_ref();
} else {
/* non-null */
char *wp = f_begin;
unescape_string(wp, f_begin, f_end);
flds[i] = string_ref(f_begin, wp - f_begin);
}
}
skip_one(start, finish);
args.limit = read_ui32(start, finish);
skip_one(start, finish);
args.skip = read_ui32(start, finish);
if (start == finish) {
/* simple query */
return dbctx->cmd_exec(conn, args);
}
/* has more options */
skip_one(start, finish);
/* in-clause */
if (start[0] == '@') {
read_token(start, finish); /* '@' */
skip_one(start, finish);
args.invalues_keypart = read_ui32(start, finish);
skip_one(start, finish);
args.invalueslen = read_ui32(start, finish);
if (args.invalueslen <= 0) {
return conn.dbcb_resp_short(2, "invalueslen");
}
if (invalues_work.size() < args.invalueslen) {
invalues_work.resize(args.invalueslen);
}
args.invalues = &invalues_work[0];
for (uint32_t i = 0; i < args.invalueslen; ++i) {
skip_one(start, finish);
char *const invalue_begin = start;
read_token(start, finish);
char *const invalue_end = start;
char *wp = invalue_begin;
unescape_string(wp, invalue_begin, invalue_end);
invalues_work[i] = string_ref(invalue_begin, wp - invalue_begin);
}
skip_one(start, finish);
}
if (start == finish) {
/* no more options */
return dbctx->cmd_exec(conn, args);
}
/* filters */
size_t filters_count = 0;
while (start != finish && (start[0] == 'W' || start[0] == 'F')) {
char *const filter_type_begin = start;
read_token(start, finish);
char *const filter_type_end = start;
skip_one(start, finish);
char *const filter_op_begin = start;
read_token(start, finish);
char *const filter_op_end = start;
skip_one(start, finish);
const uint32_t ff_offset = read_ui32(start, finish);
skip_one(start, finish);
char *const filter_val_begin = start;
read_token(start, finish);
char *const filter_val_end = start;
skip_one(start, finish);
if (filters_work.size() <= filters_count) {
filters_work.resize(filters_count + 1);
}
record_filter& fi = filters_work[filters_count];
if (filter_type_end != filter_type_begin + 1) {
return conn.dbcb_resp_short(2, "filtertype");
}
fi.filter_type = (filter_type_begin[0] == 'W')
? record_filter_type_break : record_filter_type_skip;
const uint32_t num_filflds = args.pst->get_filter_fields().size();
if (ff_offset >= num_filflds) {
return conn.dbcb_resp_short(2, "filterfld");
}
fi.op = string_ref(filter_op_begin, filter_op_end);
fi.ff_offset = ff_offset;
if (is_null_expression(filter_val_begin, filter_val_end)) {
/* null */
fi.val = string_ref();
} else {
/* non-null */
char *wp = filter_val_begin;
unescape_string(wp, filter_val_begin, filter_val_end);
fi.val = string_ref(filter_val_begin, wp - filter_val_begin);
}
++filters_count;
}
if (filters_count > 0) {
if (filters_work.size() <= filters_count) {
filters_work.resize(filters_count + 1);
}
filters_work[filters_count].op = string_ref(); /* sentinel */
args.filters = &filters_work[0];
} else {
args.filters = 0;
}
if (start == finish) {
/* no modops */
return dbctx->cmd_exec(conn, args);
}
/* has modops */
char *const mod_op_begin = start;
read_token(start, finish);
char *const mod_op_end = start;
args.mod_op = string_ref(mod_op_begin, mod_op_end);
const size_t num_uvals = args.pst->get_ret_fields().size();
string_ref *const uflds = DENA_ALLOCA_ALLOCATE(string_ref, num_uvals);
auto_alloca_free<string_ref> uflds_autofree(uflds);
for (size_t i = 0; i < num_uvals; ++i) {
skip_one(start, finish);
char *const f_begin = start;
read_token(start, finish);
char *const f_end = start;
if (is_null_expression(f_begin, f_end)) {
/* null */
uflds[i] = string_ref();
} else {
/* non-null */
char *wp = f_begin;
unescape_string(wp, f_begin, f_end);
uflds[i] = string_ref(f_begin, wp - f_begin);
}
}
args.uvals = uflds;
return dbctx->cmd_exec(conn, args);
}
void
hstcpsvr_worker::do_authorization(char *start, char *finish,
hstcpsvr_conn& conn)
{
/* auth type */
char *const authtype_begin = start;
read_token(start, finish);
char *const authtype_end = start;
const size_t authtype_len = authtype_end - authtype_begin;
skip_one(start, finish);
/* key */
char *const key_begin = start;
read_token(start, finish);
char *const key_end = start;
const size_t key_len = key_end - key_begin;
authtype_end[0] = 0;
key_end[0] = 0;
char *wp = key_begin;
unescape_string(wp, key_begin, key_end);
if (authtype_len != 1 || authtype_begin[0] != '1') {
return conn.dbcb_resp_short(3, "authtype");
}
if (cshared.plain_secret.size() == key_len &&
memcmp(cshared.plain_secret.data(), key_begin, key_len) == 0) {
conn.authorized = true;
} else {
conn.authorized = false;
}
if (!conn.authorized) {
return conn.dbcb_resp_short(3, "unauth");
} else {
return conn.dbcb_resp_short(0, "");
}
}
hstcpsvr_worker_ptr
hstcpsvr_worker_i::create(const hstcpsvr_worker_arg& arg)
{
return hstcpsvr_worker_ptr(new hstcpsvr_worker(arg));
}
};
| 27.438413 | 80 | 0.646694 | wc222 |
98650d1ae5c99092755527066c42c1317afde6e0 | 3,960 | cpp | C++ | 3rdparty/GPSTk/core/tests/GNSSCore/Convhelp_T.cpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/GPSTk/core/tests/GNSSCore/Convhelp_T.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/GPSTk/core/tests/GNSSCore/Convhelp_T.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | 14 | 2019-11-05T01:50:29.000Z | 2021-08-06T06:23:44.000Z | //============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 3.0 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include <iostream>
#include <cmath>
#include "convhelp.hpp"
#include "GPSEllipsoid.hpp"
#include "TestUtil.hpp"
int main()
{
TUDEF("convhelp", "");
double eps = 1e-12;
gpstk::WGS84Ellipsoid wem;
gpstk::GPSEllipsoid gem;
testFramework.changeSourceMethod("WGS84Ellipsoid cycles2meters");
TUASSERTFEPS(gpstk::cycles2meters(100000., 400000.,wem), 74948114.5, eps);
TUASSERTFEPS(gpstk::cycles2meters(0,5,wem), 0, eps);
TUASSERTFEPS(gpstk::cycles2meters(-100000.,400000.,wem), -74948114.5, eps);
testFramework.changeSourceMethod("GPSEllipsoid cycles2meters");
TUASSERTFEPS(gpstk::cycles2meters(100000.,400000.,gem), 74948114.5, eps);
TUASSERTFEPS(gpstk::cycles2meters(0,5,gem), 0, eps);
TUASSERTFEPS(gpstk::cycles2meters(-100000.,400000.,gem), -74948114.5, eps);
testFramework.changeSourceMethod("WGS84Ellipsoid meters2cycles");
TUASSERTFEPS(gpstk::meters2cycles(74948114.5,400000.,wem), 100000, eps);
TUASSERTFEPS(gpstk::meters2cycles(0,5,wem), 0, eps);
TUASSERTFEPS(gpstk::meters2cycles(-74948114.5,400000.,wem), -100000, eps);
testFramework.changeSourceMethod("GPSEllipsoid meters2cycles");
TUASSERTFEPS(gpstk::meters2cycles(74948114.5,400000.,gem), 100000, eps);
TUASSERTFEPS(gpstk::meters2cycles(0,5,gem), 0, eps);
TUASSERTFEPS(gpstk::meters2cycles(-74948114.5,400000.,gem), -100000, eps);
testFramework.changeSourceMethod("cel2far");
TUASSERTFEPS(gpstk::cel2far(100), 212, eps);
TUASSERTFEPS(gpstk::cel2far(0), 32, eps);
TUASSERTFEPS(gpstk::cel2far(-100), -148, eps);
testFramework.changeSourceMethod("far2cel");
TUASSERTFEPS(gpstk::far2cel(212), 100, eps);
TUASSERTFEPS(gpstk::far2cel(32), 0, eps);
TUASSERTFEPS(gpstk::far2cel(-148), -100, eps);
testFramework.changeSourceMethod("mb2hg");
TUASSERTFEPS(gpstk::mb2hg(100), 2.9529987508079487, eps);
TUASSERTFEPS(gpstk::mb2hg(0), 0, eps);
TUASSERTFEPS(gpstk::mb2hg(-100), -2.9529987508079487, eps);
testFramework.changeSourceMethod("hg2mb");
TUASSERTFEPS(gpstk::hg2mb(2.9529987508079487), 100, eps);
TUASSERTFEPS(gpstk::hg2mb(0), 0, eps);
TUASSERTFEPS(gpstk::hg2mb(-2.9529987508079487), -100, eps);
std::cout << "Total Failures for " << __FILE__ << ": " << testFramework.countFails() << std::endl;
return testFramework.countFails();
}
| 41.25 | 101 | 0.660606 | mfkiwl |
98661705d7d57f09be60d53e414ca8dd8293dc06 | 1,069 | cpp | C++ | backup/2/leetcode/c++/find-the-distance-value-between-two-arrays.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 21 | 2019-11-16T19:08:35.000Z | 2021-11-12T12:26:01.000Z | backup/2/leetcode/c++/find-the-distance-value-between-two-arrays.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 1 | 2022-02-04T16:02:53.000Z | 2022-02-04T16:02:53.000Z | backup/2/leetcode/c++/find-the-distance-value-between-two-arrays.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 4 | 2020-05-15T19:39:41.000Z | 2021-10-30T06:40:31.000Z | // Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/leetcode/find-the-distance-value-between-two-arrays.html .
class Solution {
public:
int findTheDistanceValue(vector<int> &arr1, vector<int> &arr2, int d) {
int res = 0;
for (auto num1 : arr1) {
bool valid = true;
for (auto num2 : arr2) {
if (abs(num1 - num2) <= d) {
valid = false;
break;
}
}
if (valid) {
res++;
}
}
return res;
}
};
| 42.76 | 345 | 0.595884 | yangyanzhan |
9869b535f8a1de758b0c35612dbd4ac2a1701ad9 | 368 | hpp | C++ | mmcv/ops/csrc/pytorch_cuda_helper.hpp | jinliwei1997/mmcv | f8d46df4a9fa32fb44d2e92a4ca5e7b26ee9cb79 | [
"Apache-2.0"
] | 3,748 | 2018-10-12T08:39:46.000Z | 2022-03-31T17:22:55.000Z | mmcv/ops/csrc/pytorch_cuda_helper.hpp | jinliwei1997/mmcv | f8d46df4a9fa32fb44d2e92a4ca5e7b26ee9cb79 | [
"Apache-2.0"
] | 1,637 | 2018-10-12T06:06:18.000Z | 2022-03-31T02:20:53.000Z | mmcv/ops/csrc/pytorch_cuda_helper.hpp | jinliwei1997/mmcv | f8d46df4a9fa32fb44d2e92a4ca5e7b26ee9cb79 | [
"Apache-2.0"
] | 1,234 | 2018-10-12T09:28:20.000Z | 2022-03-31T15:56:24.000Z | #ifndef PYTORCH_CUDA_HELPER
#define PYTORCH_CUDA_HELPER
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <ATen/cuda/CUDAApplyUtils.cuh>
#include <THC/THCAtomics.cuh>
#include "common_cuda_helper.hpp"
using at::Half;
using at::Tensor;
using phalf = at::Half;
#define __PHALF(x) (x)
#endif // PYTORCH_CUDA_HELPER
| 18.4 | 39 | 0.758152 | jinliwei1997 |
986a3d71d5fd170d0cb0abb91a3e56e62aa9ca66 | 681 | cpp | C++ | oi/tyvj/P1245/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | 3 | 2018-08-30T09:43:20.000Z | 2019-12-03T04:53:43.000Z | oi/tyvj/P1245/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | oi/tyvj/P1245/main.cpp | Riteme/test | b511d6616a25f4ae8c3861e2029789b8ee4dcb8d | [
"BSD-Source-Code"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long Int;
Int score=0;
void AddScore(Int points){
score=(score+points)%1000;
}
#define loop(n,step) for(int __Loop__=1;__Loop__<=(n);__Loop__+=(step))
int main(int argc, char *argv[]) {
ios::sync_with_stdio(false);
Int n,p;
vector<Int> d;
cin>>n>>p;
d.reserve(n);
Int tmp;
loop(n,1){
cin>>tmp;
d.push_back(tmp);
}
std::sort(d.begin(),d.end());
Int last=-1;
for(Int i=0;i<n;i++){
AddScore(d[i]*(i+1));
if (d[i]==last) {
AddScore(p);
}
last=d[i];
}
cout<<score;
return 0;
} // function main
| 13.62 | 72 | 0.563877 | Riteme |
986a6b275f28b3ee118baa9ea438c0ca5fa38f21 | 123,900 | cxx | C++ | dev/ese/src/ese/info.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | 1 | 2021-02-02T07:04:07.000Z | 2021-02-02T07:04:07.000Z | dev/ese/src/ese/info.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | null | null | null | dev/ese/src/ese/info.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "std.hxx"
#include "PageSizeClean.hxx"
typedef struct
{
JET_COLUMNID columnid;
JET_COLTYP coltyp;
USHORT wCountry;
LANGID langid;
USHORT cp;
USHORT wCollate;
ULONG cbMax;
JET_GRBIT grbit;
ULONG cbDefault;
BYTE *pbDefault;
CHAR szName[JET_cbNameMost + 1];
} INFOCOLUMNDEF;
CODECONST( JET_COLUMNDEF ) rgcolumndefGetObjectInfo_A[] =
{
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypDateTime, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypDateTime, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed }
};
CODECONST( JET_COLUMNDEF ) rgcolumndefGetObjectInfo_W[] =
{
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypDateTime, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypDateTime, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed }
};
const ULONG ccolumndefGetObjectInfoMax = ( sizeof(rgcolumndefGetObjectInfo_A) / sizeof(JET_COLUMNDEF) );
#define iContainerName 0
#define iObjectName 1
#define iObjectType 2
#define iCRecord 5
#define iCPage 6
#define iGrbit 7
#define iFlags 8
CODECONST( JET_COLUMNDEF ) rgcolumndefGetColumnInfo_A[] =
{
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed | JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLongBinary, 0, 0, 0, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, 0 }
};
CODECONST( JET_COLUMNDEF ) rgcolumndefGetColumnInfo_W[] =
{
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed | JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLongBinary, 0, 0, 0, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, 0 }
};
CODECONST( JET_COLUMNDEF ) rgcolumndefGetColumnInfoCompact_A[] =
{
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypBinary, 0, 0, 0, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, 0 }
};
CODECONST( JET_COLUMNDEF ) rgcolumndefGetColumnInfoCompact_W[] =
{
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypBinary, 0, 0, 0, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, 0 }
};
const ULONG ccolumndefGetColumnInfoMax = ( sizeof( rgcolumndefGetColumnInfo_A ) / sizeof( JET_COLUMNDEF ) );
#define iColumnPOrder 0
#define iColumnName 1
#define iColumnId 2
#define iColumnType 3
#define iColumnCountry 4
#define iColumnLangid 5
#define iColumnCp 6
#define iColumnCollate 7
#define iColumnSize 8
#define iColumnGrbit 9
#define iColumnDefault 10
#define iColumnTableName 11
#define iColumnColumnName 12
CODECONST( JET_COLUMNDEF ) rgcolumndefGetIndexInfo_A[] =
{
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed | JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, 0, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed }
};
CODECONST( JET_COLUMNDEF ) rgcolumndefGetIndexInfo_W[] =
{
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed | JET_bitColumnTTKey },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypShort, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypText, 0, 0, usUniCodePage, 0, 0, 0 },
{ sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed }
};
const ULONG ccolumndefGetIndexInfoMax = ( sizeof( rgcolumndefGetIndexInfo_A ) / sizeof( JET_COLUMNDEF ) );
#define iIndexName 0
#define iIndexGrbit 1
#define iIndexCKey 2
#define iIndexCEntry 3
#define iIndexCPage 4
#define iIndexCCol 5
#define iIndexICol 6
#define iIndexColId 7
#define iIndexColType 8
#define iIndexCountry 9
#define iIndexLangid 10
#define iIndexCp 11
#define iIndexCollate 12
#define iIndexColBits 13
#define iIndexColName 14
#define iIndexLCMapFlags 15
extern const ULONG cbIDXLISTNewMembersSinceOriginalFormat = 4;
LOCAL ERR ErrINFOGetTableColumnInfo(
FUCB *pfucb,
const CHAR *szColumnName,
INFOCOLUMNDEF *pcolumndef )
{
ERR err;
FCB *pfcb = pfucb->u.pfcb;
TDB *ptdb = pfcb->Ptdb();
FCB * const pfcbTemplate = ptdb->PfcbTemplateTable();
COLUMNID columnidT;
FIELD *pfield = pfieldNil;
JET_GRBIT grbit;
Assert( pcolumndef != NULL );
Assert( szColumnName != NULL || pcolumndef->columnid != 0 );
if ( szColumnName != NULL )
{
if ( *szColumnName == '\0' )
return ErrERRCheck( JET_errColumnNotFound );
BOOL fColumnWasDerived;
CallR( ErrFILEGetPfieldAndEnterDML(
pfucb->ppib,
pfcb,
szColumnName,
&pfield,
&columnidT,
&fColumnWasDerived,
fFalse ) );
if ( fColumnWasDerived )
{
ptdb->AssertValidDerivedTable();
Assert( FCOLUMNIDTemplateColumn( columnidT ) );
pfcb = pfcbTemplate;
ptdb = pfcbTemplate->Ptdb();
pfcb->EnterDML();
}
else
{
if ( FCOLUMNIDTemplateColumn( columnidT ) )
{
Assert( pfcb->FTemplateTable() );
}
else
{
Assert( !pfcb->FTemplateTable() );
}
}
}
else
{
const FID fid = FidOfColumnid( pcolumndef->columnid );
columnidT = pcolumndef->columnid;
if ( FCOLUMNIDTemplateColumn( columnidT ) && !pfcb->FTemplateTable() )
{
pfcb->Ptdb()->AssertValidDerivedTable();
pfcb = pfcbTemplate;
Assert( pfcbNil != pfcb );
Assert( pfcb->FTemplateTable() );
ptdb = pfcbTemplate->Ptdb();
Assert( ptdbNil != ptdb );
}
pfcb->EnterDML();
pfield = pfieldNil;
if ( FCOLUMNIDTagged( columnidT ) )
{
if ( fid >= ptdb->FidTaggedFirst() && fid <= ptdb->FidTaggedLast() )
pfield = ptdb->PfieldTagged( columnidT );
}
else if ( FCOLUMNIDFixed( columnidT ) )
{
if ( fid >= ptdb->FidFixedFirst() && fid <= ptdb->FidFixedLast() )
pfield = ptdb->PfieldFixed( columnidT );
}
else if ( FCOLUMNIDVar( columnidT ) )
{
if ( fid >= ptdb->FidVarFirst() && fid <= ptdb->FidVarLast() )
pfield = ptdb->PfieldVar( columnidT );
}
if ( pfieldNil == pfield )
{
pfcb->LeaveDML();
return ErrERRCheck( JET_errColumnNotFound );
}
Assert( !FFIELDCommittedDelete( pfield->ffield ) );
}
pfcb->AssertDML();
Assert( ptdb->Pfield( columnidT ) == pfield );
if ( FCOLUMNIDTagged( columnidT ) )
{
grbit = JET_bitColumnTagged;
}
else if ( FCOLUMNIDVar( columnidT ) )
{
grbit = 0;
}
else
{
Assert( FCOLUMNIDFixed( columnidT ) );
grbit = JET_bitColumnFixed;
}
if ( FFUCBUpdatable( pfucb ) )
grbit |= JET_bitColumnUpdatable;
if ( FFIELDNotNull( pfield->ffield ) )
grbit |= JET_bitColumnNotNULL;
if ( FFIELDAutoincrement( pfield->ffield ) )
grbit |= JET_bitColumnAutoincrement;
if ( FFIELDVersion( pfield->ffield ) )
grbit |= JET_bitColumnVersion;
if ( FFIELDMultivalued( pfield->ffield ) )
grbit |= JET_bitColumnMultiValued;
if ( FFIELDEscrowUpdate( pfield->ffield ) )
grbit |= JET_bitColumnEscrowUpdate;
if ( FFIELDFinalize( pfield->ffield ) )
grbit |= JET_bitColumnFinalize;
if ( FFIELDDeleteOnZero( pfield->ffield ) )
grbit |= JET_bitColumnDeleteOnZero;
if ( FFIELDUserDefinedDefault( pfield->ffield ) )
grbit |= JET_bitColumnUserDefinedDefault;
if ( FFIELDCompressed( pfield->ffield ) )
grbit |= JET_bitColumnCompressed;
if ( FFIELDEncrypted( pfield->ffield ) )
grbit |= JET_bitColumnEncrypted;
if ( FFIELDPrimaryIndexPlaceholder( pfield->ffield ) )
grbit |= JET_bitColumnRenameConvertToPrimaryIndexPlaceholder;
pcolumndef->columnid = columnidT;
pcolumndef->coltyp = pfield->coltyp;
pcolumndef->wCountry = countryDefault;
LCID lcid;
CallS( ErrNORMLocaleToLcid( PinstFromPfucb( pfucb )->m_wszLocaleNameDefault, &lcid ) );
pcolumndef->langid = LangidFromLcid( lcid );
pcolumndef->cp = pfield->cp;
pcolumndef->wCollate = 0;
pcolumndef->grbit = grbit;
pcolumndef->cbMax = pfield->cbMaxLen;
pcolumndef->cbDefault = 0;
OSStrCbCopyA( pcolumndef->szName, sizeof(pcolumndef->szName), ptdb->SzFieldName( pfield->itagFieldName, fFalse ) );
if( NULL != pcolumndef->pbDefault )
{
if ( FFIELDUserDefinedDefault( pfield->ffield ) )
{
CHAR szCallback[JET_cbNameMost+1];
ULONG cchSzCallback = 0;
BYTE rgbUserData[JET_cbCallbackUserDataMost];
ULONG cbUserData = 0;
CHAR szDependantColumns[ (JET_ccolKeyMost*(JET_cbNameMost+1)) + 1 ];
ULONG cchDependantColumns = 0;
COLUMNID columnidCallback = columnidT;
pfcb->LeaveDML();
COLUMNIDResetFTemplateColumn( columnidCallback );
err = ErrCATGetColumnCallbackInfo(
pfucb->ppib,
pfucb->ifmp,
pfcb->ObjidFDP(),
( NULL == pfcbTemplate ? objidNil : pfcbTemplate->ObjidFDP() ),
columnidCallback,
szCallback,
sizeof( szCallback ),
&cchSzCallback,
rgbUserData,
sizeof( rgbUserData ),
&cbUserData,
szDependantColumns,
sizeof( szDependantColumns ),
&cchDependantColumns );
if( err < 0 )
{
return err;
}
Assert( cchSzCallback <= sizeof( szCallback ) );
Assert( cbUserData <= sizeof( rgbUserData ) );
Assert( cchDependantColumns <= sizeof( szDependantColumns ) );
Assert( '\0' == szCallback[cchSzCallback-1] );
Assert( 0 == cchDependantColumns ||
( '\0' == szDependantColumns[cchDependantColumns-1]
&& '\0' == szDependantColumns[cchDependantColumns-2] ) );
BYTE * const pbMin = pcolumndef->pbDefault;
BYTE * const pbUserdefinedDefault = pbMin;
BYTE * const pbSzCallback = pbUserdefinedDefault + sizeof( JET_USERDEFINEDDEFAULT_A );
BYTE * const pbUserData = pbSzCallback + cchSzCallback;
BYTE * const pbDependantColumns = pbUserData + cbUserData;
BYTE * const pbMax = pbDependantColumns + cchDependantColumns;
JET_USERDEFINEDDEFAULT_A * const puserdefineddefault = (JET_USERDEFINEDDEFAULT_A *)pbUserdefinedDefault;
memcpy( pbSzCallback, szCallback, cchSzCallback );
memcpy( pbUserData, rgbUserData, cbUserData );
memcpy( pbDependantColumns, szDependantColumns, cchDependantColumns );
puserdefineddefault->szCallback = (CHAR *)pbSzCallback;
puserdefineddefault->pbUserData = rgbUserData;
puserdefineddefault->cbUserData = cbUserData;
if( 0 != cchDependantColumns )
{
puserdefineddefault->szDependantColumns = (CHAR *)pbDependantColumns;
}
else
{
puserdefineddefault->szDependantColumns = NULL;
}
pcolumndef->cbDefault = ULONG( pbMax - pbMin );
pfcb->EnterDML();
}
else if ( FFIELDDefault( pfield->ffield ) )
{
DATA dataT;
Assert( pfcb->Ptdb() == ptdb );
err = ErrRECIRetrieveDefaultValue( pfcb, columnidT, &dataT );
Assert( err >= JET_errSuccess );
Assert( wrnRECSeparatedLV != err );
Assert( wrnRECLongField != err );
pcolumndef->cbDefault = dataT.Cb();
UtilMemCpy( pcolumndef->pbDefault, dataT.Pv(), dataT.Cb() );
}
}
pfcb->LeaveDML();
return JET_errSuccess;
}
LOCAL ERR ErrInfoGetObjectInfo(
PIB *ppib,
const IFMP ifmp,
const CHAR *szObjectName,
VOID *pv,
const ULONG cbMax,
const BOOL fStats );
LOCAL ERR ErrInfoGetObjectInfoList(
PIB *ppib,
const IFMP ifmp,
const JET_OBJTYP objtyp,
VOID *pv,
const ULONG cbMax,
const BOOL fStats,
const BOOL fUnicodeNames);
LOCAL ERR ErrInfoGetTableColumnInfo(
PIB *ppib,
FUCB *pfucb,
const CHAR *szColumnName,
const JET_COLUMNID *pcolid,
VOID *pv,
const ULONG cbMax );
LOCAL ERR ErrInfoGetTableColumnInfoList(
PIB *ppib,
FUCB *pfucb,
VOID *pv,
const ULONG cbMax,
const JET_GRBIT grbit,
const BOOL fUnicodeNames );
LOCAL ERR ErrInfoGetTableColumnInfoBase(
PIB *ppib,
FUCB *pfucb,
const CHAR *szColumnName,
const JET_COLUMNID *pcolid,
VOID *pv,
const ULONG cbMax );
LOCAL ERR ErrINFOGetTableIndexInfo(
PIB *ppib,
FUCB *pfucb,
const CHAR *szIndexName,
VOID *pv,
const ULONG cbMax,
const BOOL fUnicodeNames );
LOCAL ERR ErrINFOGetTableIndexInfo(
PIB *ppib,
FUCB *pfucb,
IFMP ifmp,
OBJID objidTable,
const CHAR *szIndex,
void *pb,
ULONG cbMax,
ULONG lInfoLevel,
const BOOL fUnicodeNames );
LOCAL ERR ErrINFOGetTableIndexIdInfo(
PIB * ppib,
FUCB * pfucb,
const CHAR * szIndexName,
INDEXID * pindexid );
LOCAL ERR ErrINFOGetTableIndexInfoForCreateIndex(
PIB * ppib,
FUCB * pfucb,
const CHAR * szIndexName,
VOID * pvResult,
const ULONG cbMax,
const BOOL fUnicodeNames,
ULONG lIdxVersion );
LOCAL const CHAR szTcObject[] = "Tables";
LOCAL const WCHAR wszTcObject[] = L"Tables";
ERR VDBAPI ErrIsamGetObjectInfo(
JET_SESID vsesid,
JET_DBID vdbid,
JET_OBJTYP objtyp,
const CHAR *szContainer,
const CHAR *szObject,
VOID *pv,
ULONG cbMax,
ULONG lInfoLevel,
const BOOL fUnicodeNames )
{
ERR err;
PIB *ppib = (PIB *) vsesid;
const IFMP ifmp = (IFMP)vdbid;
CHAR szObjectName[JET_cbNameMost+1];
bool fTransactionStarted = false;
CallR( ErrPIBCheck( ppib ) );
CallR( ErrPIBCheckIfmp( ppib, ifmp ) );
if ( NULL != szContainer && '\0' != *szContainer )
{
CHAR szContainerName[JET_cbNameMost+1];
CallR( ErrUTILCheckName( szContainerName, szContainer, JET_cbNameMost+1 ) );
if ( 0 != _stricmp( szContainerName, szTcObject ) )
{
err = ErrERRCheck( JET_errObjectNotFound );
return err;
}
}
if ( szObject == NULL || *szObject == '\0' )
*szObjectName = '\0';
else
CallR( ErrUTILCheckName( szObjectName, szObject, JET_cbNameMost+1 ) );
if ( ppib->Level() == 0 )
{
CallR( ErrDIRBeginTransaction( ppib, 42523, NO_GRBIT ) );
fTransactionStarted = fTrue;
}
switch ( lInfoLevel )
{
case JET_ObjInfo:
case JET_ObjInfoNoStats:
err = ErrInfoGetObjectInfo(
ppib,
ifmp,
szObjectName,
pv,
cbMax,
JET_ObjInfo == lInfoLevel );
break;
case JET_ObjInfoList:
case JET_ObjInfoListNoStats:
err = ErrInfoGetObjectInfoList(
ppib,
ifmp,
objtyp,
pv,
cbMax,
JET_ObjInfoList == lInfoLevel,
fUnicodeNames );
break;
case JET_ObjInfoSysTabCursor:
case JET_ObjInfoSysTabReadOnly:
case JET_ObjInfoListACM:
case JET_ObjInfoRulesLoaded:
default:
Assert( fFalse );
err = ErrERRCheck( JET_errInvalidParameter );
break;
}
if( err >= 0 && fTransactionStarted )
{
err = ErrDIRCommitTransaction( ppib, NO_GRBIT );
}
if( err < 0 && fTransactionStarted )
{
const ERR errT = ErrDIRRollback( ppib );
if ( JET_errSuccess != errT )
{
Assert( errT < 0 );
Assert( PinstFromPpib( ppib )->FInstanceUnavailable() );
Assert( JET_errSuccess != ppib->ErrRollbackFailure() );
}
}
return err;
}
LOCAL ERR ErrInfoGetObjectInfo(
PIB *ppib,
const IFMP ifmp,
const CHAR *szObjectName,
VOID *pv,
const ULONG cbMax,
const BOOL fStats )
{
ERR err;
FUCB *pfucbInfo;
JET_OBJECTINFO objectinfo;
if ( cbMax < sizeof( JET_OBJECTINFO ) )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
CallR( ErrCATGetTableInfoCursor( ppib, ifmp, szObjectName, &pfucbInfo ) );
objectinfo.cbStruct = sizeof( JET_OBJECTINFO );
objectinfo.objtyp = JET_objtypTable;
objectinfo.grbit = JET_bitTableInfoBookmark | JET_bitTableInfoRollback;
if ( FFUCBUpdatable( pfucbInfo ) )
{
objectinfo.grbit |= JET_bitTableInfoUpdatable;
}
ULONG cbActual;
Call( ErrIsamRetrieveColumn(
ppib,
pfucbInfo,
fidMSO_Flags,
&objectinfo.flags,
sizeof( objectinfo.flags ),
&cbActual,
NO_GRBIT,
NULL ) );
CallS( err );
Assert( sizeof(ULONG) == cbActual );
if ( fStats )
{
LONG cRecord, cPage;
Call( ErrSTATSRetrieveTableStats(
ppib,
ifmp,
(CHAR *)szObjectName,
&cRecord,
NULL,
&cPage ) );
objectinfo.cRecord = cRecord;
objectinfo.cPage = cPage;
}
else
{
objectinfo.cRecord = 0;
objectinfo.cPage = 0;
}
memcpy( pv, &objectinfo, sizeof( JET_OBJECTINFO ) );
err = JET_errSuccess;
HandleError:
CallS( ErrCATClose( ppib, pfucbInfo ) );
return err;
}
LOCAL ERR ErrInfoGetObjectInfoList(
PIB *ppib,
const IFMP ifmp,
const JET_OBJTYP objtyp,
VOID *pv,
const ULONG cbMax,
const BOOL fStats,
const BOOL fUnicodeNames )
{
ERR err;
const JET_SESID sesid = (JET_SESID)ppib;
JET_TABLEID tableid;
JET_COLUMNID rgcolumnid[ccolumndefGetObjectInfoMax];
FUCB *pfucbCatalog = pfucbNil;
const JET_OBJTYP objtypTable = JET_objtypTable;
JET_GRBIT grbitTable;
ULONG ulFlags;
LONG cRecord = 0;
LONG cPage = 0;
ULONG cRows = 0;
ULONG cbActual;
CHAR szObjectName[JET_cbNameMost+1];
JET_OBJECTLIST objectlist;
C_ASSERT( sizeof(rgcolumndefGetObjectInfo_A) == sizeof(rgcolumndefGetObjectInfo_W) );
CallR( ErrIsamOpenTempTable(
sesid,
(JET_COLUMNDEF *)( fUnicodeNames ? rgcolumndefGetObjectInfo_W : rgcolumndefGetObjectInfo_A ),
ccolumndefGetObjectInfoMax,
NULL,
JET_bitTTScrollable|JET_bitTTIndexed,
&tableid,
rgcolumnid,
JET_cbKeyMost_OLD,
JET_cbKeyMost_OLD ) );
if ( JET_objtypNil != objtyp && JET_objtypTable != objtyp )
{
goto ResetTempTblCursor;
}
Call( ErrCATOpen( ppib, ifmp, &pfucbCatalog ) );
Assert( pfucbNil != pfucbCatalog );
Call( ErrIsamSetCurrentIndex( ppib, pfucbCatalog, szMSORootObjectsIndex ) );
grbitTable = JET_bitTableInfoBookmark|JET_bitTableInfoRollback;
if ( FFUCBUpdatable( pfucbCatalog ) )
grbitTable |= JET_bitTableInfoUpdatable;
err = ErrIsamMove( ppib, pfucbCatalog, JET_MoveFirst, NO_GRBIT );
while ( JET_errNoCurrentRecord != err )
{
Call( err );
CallS( err );
#ifdef DEBUG
SYSOBJ sysobj;
Call( ErrIsamRetrieveColumn(
ppib,
pfucbCatalog,
fidMSO_Type,
(BYTE *)&sysobj,
sizeof(sysobj),
&cbActual,
NO_GRBIT,
NULL ) );
CallS( err );
Assert( sizeof(SYSOBJ) == cbActual );
Assert( sysobjTable == sysobj );
#endif
Call( ErrIsamRetrieveColumn(
ppib,
pfucbCatalog,
fidMSO_Name,
szObjectName,
JET_cbNameMost,
&cbActual,
NO_GRBIT,
NULL ) );
CallS( err );
Assert( cbActual > 0 );
Assert( cbActual <= JET_cbNameMost );
if ( sizeof(szObjectName)/sizeof(szObjectName[0]) <= cbActual )
{
Error( ErrERRCheck(JET_errCatalogCorrupted) );
}
szObjectName[cbActual] = 0;
Call( ErrIsamRetrieveColumn(
ppib,
pfucbCatalog,
fidMSO_Flags,
&ulFlags,
sizeof(ulFlags),
&cbActual,
NO_GRBIT,
NULL ) );
CallS( err );
Assert( sizeof(ULONG) == cbActual );
if ( fStats )
{
Call( ErrSTATSRetrieveTableStats(
ppib,
ifmp,
szObjectName,
&cRecord,
NULL,
&cPage ) );
}
else
{
Assert( 0 == cRecord );
Assert( 0 == cPage );
}
Call( ErrDispPrepareUpdate(
sesid,
tableid,
JET_prepInsert ) );
Call( ErrDispSetColumn(
sesid,
tableid,
rgcolumnid[iContainerName],
fUnicodeNames ? (VOID *)wszTcObject : (VOID *)szTcObject,
(ULONG)( fUnicodeNames ? ( wcslen(wszTcObject) * sizeof( WCHAR ) ) : strlen(szTcObject) ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
sesid,
tableid,
rgcolumnid[iObjectType],
&objtypTable,
sizeof(objtypTable),
NO_GRBIT,
NULL ) );
if ( fUnicodeNames )
{
WCHAR wszObjectName[JET_cbNameMost+1];
size_t cwchActual;
Call( ErrOSSTRAsciiToUnicode( szObjectName, wszObjectName, JET_cbNameMost + 1, &cwchActual ) );
Call( ErrDispSetColumn(
sesid,
tableid,
rgcolumnid[iObjectName],
wszObjectName,
(ULONG) ( sizeof(WCHAR) * wcslen(wszObjectName) ),
NO_GRBIT,
NULL ) );
}
else
{
Call( ErrDispSetColumn(
sesid,
tableid,
rgcolumnid[iObjectName],
szObjectName,
(ULONG)strlen(szObjectName),
NO_GRBIT,
NULL ) );
}
Call( ErrDispSetColumn(
sesid,
tableid,
rgcolumnid[iFlags],
&ulFlags,
sizeof(ulFlags),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
sesid,
tableid,
rgcolumnid[iCRecord],
&cRecord,
sizeof(cRecord),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
sesid,
tableid,
rgcolumnid[iCPage],
&cPage,
sizeof(cPage),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
sesid,
tableid,
rgcolumnid[iGrbit],
&grbitTable,
sizeof(grbitTable),
NO_GRBIT,
NULL ) );
Call( ErrDispUpdate(
sesid,
tableid,
NULL,
0,
NULL,
NO_GRBIT ) );
cRows++;
err = ErrIsamMove( ppib, pfucbCatalog, JET_MoveNext, NO_GRBIT );
}
CallS( ErrCATClose( ppib, pfucbCatalog ) );
pfucbCatalog = pfucbNil;
ResetTempTblCursor:
err = ErrDispMove( sesid, tableid, JET_MoveFirst, NO_GRBIT );
if ( err < 0 )
{
if ( JET_errNoCurrentRecord != err )
goto HandleError;
}
objectlist.cbStruct = sizeof(JET_OBJECTLIST);
objectlist.tableid = tableid;
objectlist.cRecord = cRows;
objectlist.columnidcontainername = rgcolumnid[iContainerName];
objectlist.columnidobjectname = rgcolumnid[iObjectName];
objectlist.columnidobjtyp = rgcolumnid[iObjectType];
objectlist.columnidgrbit = rgcolumnid[iGrbit];
objectlist.columnidflags = rgcolumnid[iFlags];
objectlist.columnidcRecord = rgcolumnid[iCRecord];
objectlist.columnidcPage = rgcolumnid[iCPage];
AssertDIRNoLatch( ppib );
Assert( pfucbNil == pfucbCatalog );
memcpy( pv, &objectlist, sizeof( JET_OBJECTLIST ) );
return JET_errSuccess;
HandleError:
Assert( err < 0 );
AssertDIRNoLatch( ppib );
if ( pfucbNil != pfucbCatalog )
{
CallS( ErrCATClose( ppib, pfucbCatalog ) );
}
(VOID)ErrDispCloseTable( sesid, tableid );
return err;
}
LOCAL ERR ErrInfoGetTableAvailSpace(
PIB * const ppib,
FUCB * const pfucb,
void * const pvResult,
const ULONG cbMax )
{
ERR err = JET_errSuccess;
CPG* const pcpg = (CPG *)pvResult;
CPG cpgT = 0;
BOOL fLeaveDML = fFalse;
FCB* pfcbT = pfcbNil;
BOOL fUnpinFCB = fFalse;
FUCB* pfucbT = pfucbNil;
if ( sizeof( CPG ) != cbMax )
{
return ErrERRCheck( JET_errInvalidBufferSize );
}
*pcpg = 0;
Call( ErrSPGetInfo( ppib, pfucb->ifmp, pfucb, (BYTE *)&cpgT, sizeof( cpgT ), fSPAvailExtent ) );
*pcpg += cpgT;
pfucb->u.pfcb->EnterDML();
fLeaveDML = fTrue;
for ( pfcbT = pfucb->u.pfcb->PfcbNextIndex(); pfcbNil != pfcbT; pfcbT = pfcbT->PfcbNextIndex() )
{
Assert( !pfcbT->Pidb()->FPrimary() );
err = ErrFILEIAccessIndex( pfucb->ppib, pfucb->u.pfcb, pfcbT );
if ( err != JET_errIndexNotFound )
{
Call( err );
}
if ( err != JET_errIndexNotFound )
{
if ( !pfcbT->Pidb()->FTemplateIndex() )
{
pfcbT->Pidb()->IncrementCurrentIndex();
fUnpinFCB = fTrue;
}
pfucb->u.pfcb->LeaveDML();
fLeaveDML = fFalse;
Call( ErrDIROpen( ppib, pfcbT, &pfucbT ) );
Call( ErrSPGetInfo( ppib, pfucbT->ifmp, pfucbT, (BYTE *)&cpgT, sizeof( cpgT ), fSPAvailExtent ) );
*pcpg += cpgT;
DIRClose( pfucbT );
pfucbT = pfucbNil;
pfucb->u.pfcb->EnterDML();
fLeaveDML = fTrue;
if ( fUnpinFCB )
{
pfcbT->Pidb()->DecrementCurrentIndex();
fUnpinFCB = fFalse;
}
}
}
pfucb->u.pfcb->LeaveDML();
fLeaveDML = fFalse;
Call( ErrFILEOpenLVRoot( pfucb, &pfucbT, fFalse ) )
if ( JET_errSuccess == err )
{
Call( ErrSPGetInfo( ppib, pfucbT->ifmp, pfucbT, (BYTE *)&cpgT, sizeof( cpgT ), fSPAvailExtent ) );
*pcpg += cpgT;
DIRClose( pfucbT );
pfucbT = pfucbNil;
}
err = JET_errSuccess;
HandleError:
if ( fUnpinFCB )
{
pfcbT->Pidb()->DecrementCurrentIndex();
}
if ( fLeaveDML )
{
pfucb->u.pfcb->LeaveDML();
}
if ( pfucbNil != pfucbT )
{
DIRClose( pfucbT );
}
return err;
}
ERR VTAPI ErrIsamSetTableInfo(
JET_SESID sesid,
JET_VTID vtid,
_In_reads_bytes_opt_(cbParam) const void *pvParam,
ULONG cbParam,
ULONG InfoLevel)
{
ERR err;
PIB *ppib = (PIB *)sesid;
FUCB *pfucb = (FUCB *)vtid;
CallR( ErrPIBCheck( ppib ) );
CheckTable( ppib, pfucb );
OSTraceFMP(
pfucb->ifmp,
JET_tracetagDDLWrite,
OSFormat(
"Session=[0x%p:0x%x] setting table info for objid=[0x%x:0x%x] [level=0x%x]",
ppib,
( ppibNil != ppib ? ppib->trxBegin0 : trxMax ),
(ULONG)pfucb->ifmp,
pfucb->u.pfcb->ObjidFDP(),
InfoLevel ) );
switch( InfoLevel )
{
case JET_TblInfoEncryptionKey:
FUCBRemoveEncryptionKey( pfucb );
if ( cbParam > 0 )
{
err = ErrOSEncryptionVerifyKey( (BYTE*)pvParam, cbParam );
if ( err < JET_errSuccess )
{
AssertSz( fFalse, "Client is giving us a bad key" );
return err;
}
AllocR( pfucb->pbEncryptionKey = (BYTE*)PvOSMemoryHeapAlloc( cbParam ) );
memcpy( pfucb->pbEncryptionKey, pvParam, cbParam );
pfucb->cbEncryptionKey = cbParam;
}
return JET_errSuccess;
default:
Assert( fFalse );
return ErrERRCheck( JET_errFeatureNotAvailable );
}
}
ERR VTAPI ErrIsamGetTableInfo(
JET_SESID vsesid,
JET_VTID vtid,
void *pvResult,
ULONG cbMax,
ULONG lInfoLevel )
{
ERR err;
PIB *ppib = (PIB *)vsesid;
FUCB *pfucb = (FUCB *)vtid;
CHAR szTableName[JET_cbNameMost+1];
CallR( ErrPIBCheck( ppib ) );
CheckTable( ppib, pfucb );
OSTraceFMP(
pfucb->ifmp,
JET_tracetagDDLRead,
OSFormat(
"Session=[0x%p:0x%x] retrieving table info for objid=[0x%x:0x%x] [level=0x%x]",
ppib,
( ppibNil != ppib ? ppib->trxBegin0 : trxMax ),
(ULONG)pfucb->ifmp,
pfucb->u.pfcb->ObjidFDP(),
lInfoLevel ) );
switch( lInfoLevel )
{
case JET_TblInfo:
case JET_TblInfoName:
case JET_TblInfoTemplateTableName:
case JET_TblInfoDbid:
break;
case JET_TblInfoOLC:
case JET_TblInfoResetOLC:
return ErrERRCheck( JET_errFeatureNotAvailable );
case JET_TblInfoSpaceAlloc:
Assert( cbMax >= sizeof(ULONG) * 2);
err = ErrCATGetTableAllocInfo(
ppib,
pfucb->ifmp,
pfucb->u.pfcb->ObjidFDP(),
(ULONG *)pvResult,
((ULONG *)pvResult) + 1);
return err;
case JET_TblInfoSpaceUsage:
{
BYTE fSPExtents = fSPOwnedExtent|fSPAvailExtent;
if ( cbMax > 2 * sizeof(CPG) )
fSPExtents |= fSPExtentList;
err = ErrSPGetInfo(
ppib,
pfucb->ifmp,
pfucb,
static_cast<BYTE *>( pvResult ),
cbMax,
fSPExtents );
return err;
}
case JET_TblInfoSpaceOwned:
err = ErrSPGetInfo(
ppib,
pfucb->ifmp,
pfucb,
static_cast<BYTE *>( pvResult ),
cbMax,
fSPOwnedExtent );
return err;
case JET_TblInfoSpaceAvailable:
err = ErrInfoGetTableAvailSpace(
ppib,
pfucb,
pvResult,
cbMax );
return err;
case JET_TblInfoDumpTable:
Assert( fFalse );
return ErrERRCheck( JET_errFeatureNotAvailable );
case JET_TblInfoLVChunkMax:
if ( cbMax < sizeof(LONG) )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
*(LONG *)pvResult = pfucb->u.pfcb->Ptdb()->CbLVChunkMost();
return JET_errSuccess;
case JET_TblInfoEncryptionKey:
if ( cbMax < pfucb->cbEncryptionKey )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
#ifdef DEBUG
if ( pfucb->cbEncryptionKey > 0 )
{
err = ErrOSEncryptionVerifyKey( pfucb->pbEncryptionKey, pfucb->cbEncryptionKey );
if ( err < JET_errSuccess )
{
AssertSz( fFalse, "Client should not have been able to save a bad encryption key" );
}
}
#endif
memcpy( pvResult, pfucb->pbEncryptionKey, pfucb->cbEncryptionKey );
return JET_errSuccess;
default:
Assert( fFalse );
return ErrERRCheck( JET_errFeatureNotAvailable );
}
Assert( pfucb->u.pfcb->Ptdb() != ptdbNil );
pfucb->u.pfcb->EnterDML();
Assert( strlen( pfucb->u.pfcb->Ptdb()->SzTableName() ) <= JET_cbNameMost );
OSStrCbCopyA( szTableName, sizeof(szTableName), pfucb->u.pfcb->Ptdb()->SzTableName() );
pfucb->u.pfcb->LeaveDML();
switch ( lInfoLevel )
{
case JET_TblInfo:
{
JET_OBJECTINFO objectinfo;
LONG cRecord;
LONG cPage;
if ( cbMax < sizeof( JET_OBJECTINFO ) )
{
err = ErrERRCheck( JET_errBufferTooSmall );
goto HandleError;
}
if ( pfucb->u.pfcb->FTypeTemporaryTable() )
{
err = ErrERRCheck( JET_errObjectNotFound );
goto HandleError;
}
Assert( !FFMPIsTempDB( pfucb->u.pfcb->Ifmp() ) );
objectinfo.cbStruct = sizeof(JET_OBJECTINFO);
objectinfo.objtyp = JET_objtypTable;
objectinfo.flags = 0;
if ( FCATSystemTable( pfucb->u.pfcb->PgnoFDP() ) )
objectinfo.flags |= JET_bitObjectSystem;
else if ( FOLDSystemTable( szTableName ) )
objectinfo.flags |= JET_bitObjectSystemDynamic;
else if ( FCATUnicodeFixupTable( szTableName ) )
objectinfo.flags |= JET_bitObjectSystemDynamic;
else if ( FSCANSystemTable( szTableName ) )
objectinfo.flags |= JET_bitObjectSystemDynamic;
else if ( FCATObjidsTable( szTableName ) )
objectinfo.flags |= JET_bitObjectSystemDynamic;
else if ( MSysDBM::FIsSystemTable( szTableName ) )
objectinfo.flags |= JET_bitObjectSystemDynamic;
else if ( FCATLocalesTable( szTableName ) )
objectinfo.flags |= JET_bitObjectSystemDynamic;
if ( pfucb->u.pfcb->FFixedDDL() )
objectinfo.flags |= JET_bitObjectTableFixedDDL;
Assert( !( pfucb->u.pfcb->FTemplateTable() && pfucb->u.pfcb->FDerivedTable() ) );
if ( pfucb->u.pfcb->FTemplateTable() )
objectinfo.flags |= JET_bitObjectTableTemplate;
else if ( pfucb->u.pfcb->FDerivedTable() )
objectinfo.flags |= JET_bitObjectTableDerived;
objectinfo.grbit = JET_bitTableInfoBookmark | JET_bitTableInfoRollback;
if ( FFUCBUpdatable( pfucb ) )
objectinfo.grbit |= JET_bitTableInfoUpdatable;
Call( ErrSTATSRetrieveTableStats(
pfucb->ppib,
pfucb->ifmp,
szTableName,
&cRecord,
NULL,
&cPage ) );
objectinfo.cRecord = cRecord;
objectinfo.cPage = cPage;
memcpy( pvResult, &objectinfo, sizeof( JET_OBJECTINFO ) );
break;
}
case JET_TblInfoRvt:
err = ErrERRCheck( JET_errQueryNotSupported );
break;
case JET_TblInfoName:
case JET_TblInfoMostMany:
if ( pfucb->u.pfcb->FTypeTemporaryTable() )
{
err = ErrERRCheck( JET_errInvalidOperation );
goto HandleError;
}
if ( strlen( szTableName ) >= cbMax )
err = ErrERRCheck( JET_errBufferTooSmall );
else
{
OSStrCbCopyA( static_cast<CHAR *>( pvResult ), cbMax, szTableName );
}
break;
case JET_TblInfoDbid:
if ( pfucb->u.pfcb->FTypeTemporaryTable() )
{
err = ErrERRCheck( JET_errInvalidOperation );
goto HandleError;
}
if ( cbMax < sizeof(JET_DBID) )
{
err = ErrERRCheck( JET_errBufferTooSmall );
goto HandleError;
}
else
{
*(JET_DBID *)pvResult = (JET_DBID)pfucb->ifmp;
}
break;
case JET_TblInfoTemplateTableName:
if ( pfucb->u.pfcb->FTypeTemporaryTable() )
{
err = ErrERRCheck( JET_errInvalidOperation );
goto HandleError;
}
if ( cbMax <= JET_cbNameMost )
err = ErrERRCheck( JET_errBufferTooSmall );
else if ( pfucb->u.pfcb->FDerivedTable() )
{
FCB *pfcbTemplateTable = pfucb->u.pfcb->Ptdb()->PfcbTemplateTable();
Assert( pfcbNil != pfcbTemplateTable );
Assert( pfcbTemplateTable->FFixedDDL() );
Assert( strlen( pfcbTemplateTable->Ptdb()->SzTableName() ) <= JET_cbNameMost );
OSStrCbCopyA( (CHAR *)pvResult, cbMax, pfcbTemplateTable->Ptdb()->SzTableName() );
}
else
{
*( (CHAR *)pvResult ) = '\0';
}
break;
default:
err = ErrERRCheck( JET_errInvalidParameter );
}
HandleError:
return err;
}
ERR VDBAPI ErrIsamGetColumnInfo(
JET_SESID vsesid,
JET_DBID vdbid,
const CHAR *szTable,
const CHAR *szColumnName,
JET_COLUMNID *pcolid,
VOID *pv,
ULONG cbMax,
ULONG lInfoLevel,
const BOOL fUnicodeNames )
{
PIB *ppib = (PIB *) vsesid;
ERR err;
IFMP ifmp;
CHAR szTableName[ JET_cbNameMost+1 ];
FUCB *pfucb;
CallR( ErrPIBCheck( ppib ) );
CallR( ErrPIBCheckIfmp( ppib, (IFMP)vdbid ) );
ifmp = (IFMP) vdbid;
if ( szTable == NULL )
return ErrERRCheck( JET_errInvalidParameter );
CallR( ErrUTILCheckName( szTableName, szTable, JET_cbNameMost+1 ) );
CallR( ErrFILEOpenTable( ppib, ifmp, &pfucb, szTableName ) );
Assert( pfucbNil != pfucb );
Assert( ( g_rgfmp[ifmp].FReadOnlyAttach() && !FFUCBUpdatable( pfucb ) )
|| ( !g_rgfmp[ifmp].FReadOnlyAttach() && FFUCBUpdatable( pfucb ) ) );
FUCBResetUpdatable( pfucb );
Call( ErrIsamGetTableColumnInfo(
(JET_SESID)ppib,
(JET_VTID)pfucb,
szColumnName,
pcolid,
pv,
cbMax,
lInfoLevel,
fUnicodeNames ) );
HandleError:
CallS( ErrFILECloseTable( ppib, pfucb ) );
return err;
}
ERR VTAPI
ErrIsamGetTableColumnInfo(
JET_SESID vsesid,
JET_VTID vtid,
const CHAR *szColumn,
const JET_COLUMNID *pcolid,
void *pb,
ULONG cbMax,
ULONG lInfoLevel,
const BOOL fUnicodeNames )
{
ERR err;
PIB *ppib = (PIB *)vsesid;
FUCB *pfucb = (FUCB *)vtid;
const ULONG infolevelMask = 0x0fffffff;
const JET_GRBIT grbitMask = 0xf0000000;
const JET_GRBIT grbit = ( lInfoLevel & grbitMask );
CHAR szColumnName[ (JET_cbNameMost + 1) ];
BOOL fTransactionStarted = fFalse;
CallR( ErrPIBCheck( ppib ) );
CheckTable( ppib, pfucb );
if ( szColumn == NULL || *szColumn == '\0' )
{
szColumnName[0] = '\0';
}
else
{
CallR( ErrUTILCheckName( szColumnName, szColumn, ( JET_cbNameMost + 1 ) ) );
}
if ( ppib->Level() == 0 )
{
CallR( ErrDIRBeginTransaction( ppib, 33061, NO_GRBIT ) );
fTransactionStarted = fTrue;
}
OSTraceFMP(
pfucb->ifmp,
JET_tracetagDDLRead,
OSFormat(
"Session=[0x%p:0x%x] retrieving info for column '%s' of objid=[0x%x:0x%x] [level=0x%x]",
ppib,
( ppibNil != ppib ? ppib->trxBegin0 : trxMax ),
( 0 != szColumnName[0] ? szColumnName : "<null>" ),
(ULONG)pfucb->ifmp,
pfucb->u.pfcb->ObjidFDP(),
lInfoLevel ) );
switch ( lInfoLevel & infolevelMask )
{
case JET_ColInfo:
case JET_ColInfoByColid:
err = ErrInfoGetTableColumnInfo( ppib, pfucb, szColumnName, pcolid, pb, cbMax );
break;
case JET_ColInfoList:
err = ErrInfoGetTableColumnInfoList( ppib, pfucb, pb, cbMax, grbit, fUnicodeNames );
break;
case JET_ColInfoListSortColumnid:
err = ErrInfoGetTableColumnInfoList( ppib, pfucb, pb, cbMax, ( grbit | JET_ColInfoGrbitSortByColumnid ), fUnicodeNames );
break;
case JET_ColInfoBase:
case JET_ColInfoBaseByColid:
err = ErrInfoGetTableColumnInfoBase( ppib, pfucb, szColumnName, pcolid, pb, cbMax );
break;
case JET_ColInfoListCompact:
err = ErrInfoGetTableColumnInfoList( ppib, pfucb, pb, cbMax, ( grbit | JET_ColInfoGrbitCompacting ), fUnicodeNames );
break;
case JET_ColInfoSysTabCursor:
default:
Assert( fFalse );
err = ErrERRCheck( JET_errInvalidParameter );
}
if( err >= 0 && fTransactionStarted )
{
err = ErrDIRCommitTransaction( ppib, NO_GRBIT );
}
if( err < 0 && fTransactionStarted )
{
const ERR errT = ErrDIRRollback( ppib );
if ( JET_errSuccess != errT )
{
Assert( errT < 0 );
Assert( PinstFromPpib( ppib )->FInstanceUnavailable() );
Assert( JET_errSuccess != ppib->ErrRollbackFailure() );
}
}
return err;
}
LOCAL ERR ErrInfoGetTableColumnInfo(
PIB *ppib,
FUCB *pfucb,
const CHAR *szColumnName,
const JET_COLUMNID *pcolid,
VOID *pv,
const ULONG cbMax )
{
ERR err;
INFOCOLUMNDEF columndef;
columndef.pbDefault = NULL;
if ( cbMax < sizeof(JET_COLUMNDEF) || szColumnName == NULL )
{
return ErrERRCheck( JET_errInvalidParameter );
}
if ( szColumnName[0] == '\0' )
{
if ( pcolid )
{
columndef.columnid = *pcolid;
szColumnName = NULL;
}
else
{
columndef.columnid = 0;
}
}
CallR( ErrINFOGetTableColumnInfo( pfucb, szColumnName, &columndef ) );
((JET_COLUMNDEF *)pv)->cbStruct = sizeof(JET_COLUMNDEF);
((JET_COLUMNDEF *)pv)->columnid = columndef.columnid;
((JET_COLUMNDEF *)pv)->coltyp = columndef.coltyp;
((JET_COLUMNDEF *)pv)->cbMax = columndef.cbMax;
((JET_COLUMNDEF *)pv)->grbit = columndef.grbit;
((JET_COLUMNDEF *)pv)->wCollate = 0;
((JET_COLUMNDEF *)pv)->cp = columndef.cp;
((JET_COLUMNDEF *)pv)->wCountry = columndef.wCountry;
((JET_COLUMNDEF *)pv)->langid = columndef.langid;
return JET_errSuccess;
}
LOCAL ERR ErrINFOSetTableColumnInfoList(
PIB *ppib,
JET_TABLEID tableid,
const CHAR *szTableName,
COLUMNID *rgcolumnid,
INFOCOLUMNDEF *pcolumndef,
const JET_GRBIT grbit,
const BOOL fUnicodeNames )
{
ERR err;
const BOOL fMinimalInfo = ( grbit & JET_ColInfoGrbitMinimalInfo );
const BOOL fOrderByColid = ( grbit & JET_ColInfoGrbitSortByColumnid );
WCHAR wszName[JET_cbNameMost + 1];
size_t cwchActual;
Call( ErrDispPrepareUpdate( (JET_SESID)ppib, tableid, JET_prepInsert ) );
if ( fOrderByColid )
{
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnPOrder],
(BYTE *)&pcolumndef->columnid,
sizeof(pcolumndef->columnid),
NO_GRBIT,
NULL ) );
}
if ( fUnicodeNames )
{
Call( ErrOSSTRAsciiToUnicode( pcolumndef->szName, wszName, _countof(wszName), &cwchActual ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnName],
wszName,
(ULONG)( sizeof( WCHAR ) * wcslen( wszName ) ),
NO_GRBIT,
NULL ) );
}
else
{
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnName],
pcolumndef->szName,
(ULONG)strlen( pcolumndef->szName ),
NO_GRBIT,
NULL ) );
}
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnId],
(BYTE *)&pcolumndef->columnid,
sizeof(pcolumndef->columnid),
NO_GRBIT,
NULL ) );
if ( !fMinimalInfo )
{
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnType],
(BYTE *)&pcolumndef->coltyp,
sizeof(pcolumndef->coltyp),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnCountry],
&pcolumndef->wCountry,
sizeof( pcolumndef->wCountry ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnLangid],
&pcolumndef->langid,
sizeof( pcolumndef->langid ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnCp],
&pcolumndef->cp,
sizeof(pcolumndef->cp),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnSize],
(BYTE *)&pcolumndef->cbMax,
sizeof(pcolumndef->cbMax),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnGrbit],
&pcolumndef->grbit,
sizeof(pcolumndef->grbit),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnCollate],
&pcolumndef->wCollate,
sizeof(pcolumndef->wCollate),
NO_GRBIT,
NULL ) );
if ( pcolumndef->cbDefault > 0 )
{
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnDefault],
pcolumndef->pbDefault,
pcolumndef->cbDefault,
NO_GRBIT,
NULL ) );
}
if ( fUnicodeNames )
{
Call( ErrOSSTRAsciiToUnicode( szTableName, wszName, _countof(wszName), &cwchActual ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnTableName],
wszName,
(ULONG)( sizeof( WCHAR ) * ( wcslen( wszName ) ) ),
NO_GRBIT,
NULL ) );
Call( ErrOSSTRAsciiToUnicode( pcolumndef->szName, wszName, _countof(wszName), &cwchActual ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnColumnName],
wszName,
(ULONG)( sizeof( WCHAR ) * ( wcslen( wszName ) ) ),
NO_GRBIT,
NULL ) );
}
else
{
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnTableName],
szTableName,
(ULONG)strlen( szTableName ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iColumnColumnName],
pcolumndef->szName,
(ULONG)strlen( pcolumndef->szName ),
NO_GRBIT,
NULL ) );
}
}
Call( ErrDispUpdate( (JET_SESID)ppib, tableid, NULL, 0, NULL, NO_GRBIT ) );
HandleError:
return err;
}
BOOL g_fCompactTemplateTableColumnDropped = fFalse;
LOCAL ERR ErrInfoGetTableColumnInfoList(
PIB *ppib,
FUCB *pfucb,
VOID *pv,
const ULONG cbMax,
const JET_GRBIT grbit,
const BOOL fUnicodeNames )
{
ERR err;
JET_TABLEID tableid;
COLUMNID rgcolumnid[ccolumndefGetColumnInfoMax];
FCB *pfcb = pfucb->u.pfcb;
TDB *ptdb = pfcb->Ptdb();
FID fid;
FID fidFixedFirst;
FID fidFixedLast;
FID fidVarFirst;
FID fidVarLast;
FID fidTaggedFirst;
FID fidTaggedLast;
CHAR szTableName[JET_cbNameMost+1];
INFOCOLUMNDEF columndef;
ULONG cRows = 0;
const BOOL fNonDerivedColumnsOnly = ( grbit & JET_ColInfoGrbitNonDerivedColumnsOnly );
const BOOL fCompacting = ( grbit & JET_ColInfoGrbitCompacting );
const BOOL fTemplateTable = pfcb->FTemplateTable();
columndef.pbDefault = NULL;
if ( cbMax < sizeof(JET_COLUMNLIST) )
{
return ErrERRCheck( JET_errInvalidParameter );
}
C_ASSERT( sizeof( rgcolumndefGetColumnInfoCompact_A ) == sizeof( rgcolumndefGetColumnInfo_A ) );
C_ASSERT( sizeof( rgcolumndefGetColumnInfoCompact_A ) == sizeof( rgcolumndefGetColumnInfo_W ) );
C_ASSERT( sizeof( rgcolumndefGetColumnInfoCompact_A ) == sizeof( rgcolumndefGetColumnInfoCompact_W ) );
CallR( ErrIsamOpenTempTable(
(JET_SESID)ppib,
(JET_COLUMNDEF *)( fCompacting ? ( fUnicodeNames ? rgcolumndefGetColumnInfoCompact_W : rgcolumndefGetColumnInfoCompact_A ) :
( fUnicodeNames ? rgcolumndefGetColumnInfo_W : rgcolumndefGetColumnInfo_A ) ),
ccolumndefGetColumnInfoMax,
NULL,
JET_bitTTScrollable|JET_bitTTIndexed,
&tableid,
rgcolumnid,
JET_cbKeyMost_OLD,
JET_cbKeyMost_OLD ) );
C_ASSERT( (sizeof(JET_USERDEFINEDDEFAULT)
+ JET_cbNameMost + 1
+ JET_cbCallbackUserDataMost
+ ( ( JET_ccolKeyMost * ( JET_cbNameMost + 1 ) ) + 1 )
) < JET_cbCallbackDataAllMost );
columndef.pbDefault = (BYTE *)PvOSMemoryHeapAlloc( JET_cbCallbackDataAllMost );
if( NULL == columndef.pbDefault )
{
Call( ErrERRCheck( JET_errOutOfMemory ) );
}
pfcb->EnterDML();
fidFixedFirst = ptdb->FidFixedFirst();
fidVarFirst = ptdb->FidVarFirst();
fidTaggedFirst = ptdb->FidTaggedFirst();
fidFixedLast = ptdb->FidFixedLast();
fidVarLast = ptdb->FidVarLast();
fidTaggedLast = ptdb->FidTaggedLast();
Assert( fidFixedFirst.FFixed() || ( ( pfcbNil != ptdb->PfcbTemplateTable() ) && fidFixedFirst.FFixedNoneFull() ) );
Assert( fidVarFirst.FVar() || ( ( pfcbNil != ptdb->PfcbTemplateTable() ) && fidVarFirst.FVarNoneFull() ) );
Assert( fidTaggedFirst.FTagged() || ( (pfcbNil != ptdb->PfcbTemplateTable() ) && fidVarFirst.FTaggedNoneFull() ) );
Assert( fidFixedLast.FFixedNone() || fidFixedLast.FFixed() );
Assert( fidVarLast.FVarNone() || fidVarLast.FVar() );
Assert( fidTaggedLast.FTaggedNone() || fidTaggedLast.FTagged() );
Assert( strlen( ptdb->SzTableName() ) <= JET_cbNameMost );
OSStrCbCopyA( szTableName, sizeof(szTableName), ptdb->SzTableName() );
pfcb->LeaveDML();
if ( !fNonDerivedColumnsOnly
&& !fCompacting
&& pfcbNil != ptdb->PfcbTemplateTable() )
{
ptdb->AssertValidDerivedTable();
Assert( !fTemplateTable );
const FID fidTemplateFixedFirst = FID( fidtypFixed, fidlimMin );
const FID fidTemplateVarFirst = FID( fidtypVar, fidlimMin );
const FID fidTemplateTaggedFirst = FID( fidtypTagged, fidlimMin );
const FID fidTemplateFixedLast = ptdb->PfcbTemplateTable()->Ptdb()->FidFixedLast();
const FID fidTemplateVarLast = ptdb->PfcbTemplateTable()->Ptdb()->FidVarLast();
const FID fidTemplateTaggedLast = ptdb->PfcbTemplateTable()->Ptdb()->FidTaggedLast();
Assert( fidTemplateFixedFirst.FFixed() );
Assert( fidTemplateVarFirst.FVar() );
Assert( fidTemplateTaggedFirst.FTagged() );
Assert( fidTemplateFixedLast.FFixedNone() || fidTemplateFixedLast.FFixed() );
Assert( fidTemplateVarLast.FVarNone() || fidTemplateVarLast.FVar() );
Assert( fidTemplateTaggedLast.FTaggedNone() || fidTemplateTaggedLast.FTagged() );
FID rgrgfidTemplateTableIterationBounds[][2] = {
{ fidTemplateFixedFirst, fidTemplateFixedLast },
{ fidTemplateVarFirst, fidTemplateVarLast },
{ fidTemplateTaggedFirst, fidTemplateTaggedLast },
};
static_assert( 3 == _countof( rgrgfidTemplateTableIterationBounds ), "3 elements." );
static_assert( 2 == _countof( rgrgfidTemplateTableIterationBounds[0] ), "each element an array of 2.");
for ( INT iBounds = 0; iBounds < _countof( rgrgfidTemplateTableIterationBounds ); iBounds++ )
{
for ( FID_ITERATOR itfid( rgrgfidTemplateTableIterationBounds[iBounds][0], rgrgfidTemplateTableIterationBounds[iBounds][1] ); !itfid.FEnd(); itfid++ )
{
columndef.columnid = ColumnidOfFid( *itfid, fTrue );
CallS( ErrINFOGetTableColumnInfo( pfucb, NULL, &columndef ) );
Call( ErrINFOSetTableColumnInfoList(
ppib,
tableid,
szTableName,
rgcolumnid,
&columndef,
grbit,
fUnicodeNames) );
cRows++;
}
}
}
FID rgrgfidIterationBounds[][2] = {
{ fidFixedFirst, fidFixedLast },
{ fidVarFirst, fidVarLast },
{ fidTaggedFirst, fidTaggedLast }
};
for ( INT iBounds=0; iBounds < _countof( rgrgfidIterationBounds ); iBounds++ )
{
for ( FID_ITERATOR itfid( rgrgfidIterationBounds[iBounds][0], rgrgfidIterationBounds[iBounds][1] ); !itfid.FEnd(); ++itfid )
{
columndef.columnid = ColumnidOfFid( *itfid, fTemplateTable );
if ( !fTemplateTable )
{
err = ErrRECIAccessColumn( pfucb, columndef.columnid );
if ( err < 0 )
{
if ( JET_errColumnNotFound == err )
continue;
goto HandleError;
}
}
CallS( ErrINFOGetTableColumnInfo( pfucb, NULL, &columndef ) );
if ( !fCompacting || !( columndef.grbit & JET_bitColumnRenameConvertToPrimaryIndexPlaceholder ) )
{
Call( ErrINFOSetTableColumnInfoList(
ppib,
tableid,
szTableName,
rgcolumnid,
&columndef,
grbit,
fUnicodeNames) );
cRows++;
}
else if ( fCompacting && ( columndef.grbit & JET_bitColumnRenameConvertToPrimaryIndexPlaceholder ) )
{
g_fCompactTemplateTableColumnDropped = fTrue;
}
}
}
err = ErrDispMove( (JET_SESID)ppib, tableid, JET_MoveFirst, NO_GRBIT );
if ( err < 0 )
{
if ( err != JET_errNoCurrentRecord )
goto HandleError;
err = JET_errSuccess;
}
JET_COLUMNLIST *pcolumnlist;
pcolumnlist = reinterpret_cast<JET_COLUMNLIST *>( pv );
pcolumnlist->cbStruct = sizeof(JET_COLUMNLIST);
pcolumnlist->tableid = tableid;
pcolumnlist->cRecord = cRows;
pcolumnlist->columnidPresentationOrder = rgcolumnid[iColumnPOrder];
pcolumnlist->columnidcolumnname = rgcolumnid[iColumnName];
pcolumnlist->columnidcolumnid = rgcolumnid[iColumnId];
pcolumnlist->columnidcoltyp = rgcolumnid[iColumnType];
pcolumnlist->columnidCountry = rgcolumnid[iColumnCountry];
pcolumnlist->columnidLangid = rgcolumnid[iColumnLangid];
pcolumnlist->columnidCp = rgcolumnid[iColumnCp];
pcolumnlist->columnidCollate = rgcolumnid[iColumnCollate];
pcolumnlist->columnidcbMax = rgcolumnid[iColumnSize];
pcolumnlist->columnidgrbit = rgcolumnid[iColumnGrbit];
pcolumnlist->columnidDefault = rgcolumnid[iColumnDefault];
pcolumnlist->columnidBaseTableName = rgcolumnid[iColumnTableName];
pcolumnlist->columnidBaseColumnName = rgcolumnid[iColumnColumnName];
pcolumnlist->columnidDefinitionName = rgcolumnid[iColumnName];
Assert( NULL != columndef.pbDefault );
OSMemoryHeapFree( columndef.pbDefault );
return JET_errSuccess;
HandleError:
(VOID)ErrDispCloseTable( (JET_SESID)ppib, tableid );
OSMemoryHeapFree( columndef.pbDefault );
return err;
}
LOCAL ERR ErrInfoGetTableColumnInfoBase(
PIB *ppib,
FUCB *pfucb,
const CHAR *szColumnName,
const JET_COLUMNID *pcolid,
VOID *pv,
const ULONG cbMax )
{
ERR err;
INFOCOLUMNDEF columndef;
columndef.pbDefault = NULL;
if ( cbMax < sizeof(JET_COLUMNBASE_A) || szColumnName == NULL )
{
return ErrERRCheck( JET_errInvalidParameter );
}
if ( szColumnName[0] == '\0' )
{
if ( pcolid )
{
columndef.columnid = *pcolid;
szColumnName = NULL;
}
else
{
columndef.columnid = 0;
}
}
CallR( ErrINFOGetTableColumnInfo( pfucb, szColumnName, &columndef ) );
Assert( pfucb->u.pfcb->Ptdb() != ptdbNil );
((JET_COLUMNBASE_A *)pv)->cbStruct = sizeof(JET_COLUMNBASE_A);
((JET_COLUMNBASE_A *)pv)->columnid = columndef.columnid;
((JET_COLUMNBASE_A *)pv)->coltyp = columndef.coltyp;
((JET_COLUMNBASE_A *)pv)->wFiller = 0;
((JET_COLUMNBASE_A *)pv)->cbMax = columndef.cbMax;
((JET_COLUMNBASE_A *)pv)->grbit = columndef.grbit;
OSStrCbCopyA( ( ( JET_COLUMNBASE_A *)pv )->szBaseColumnName, sizeof(( ( JET_COLUMNBASE_A *)pv )->szBaseColumnName), columndef.szName );
((JET_COLUMNBASE_A *)pv)->wCountry = columndef.wCountry;
((JET_COLUMNBASE_A *)pv)->langid = columndef.langid;
((JET_COLUMNBASE_A *)pv)->cp = columndef.cp;
pfucb->u.pfcb->EnterDML();
OSStrCbCopyA( ( ( JET_COLUMNBASE_A *)pv )->szBaseTableName,
sizeof(( ( JET_COLUMNBASE_A *)pv )->szBaseTableName),
pfucb->u.pfcb->Ptdb()->SzTableName() );
pfucb->u.pfcb->LeaveDML();
return JET_errSuccess;
}
ERR VDBAPI
ErrIsamGetIndexInfo(
JET_SESID vsesid,
JET_DBID vdbid,
const CHAR *szTable,
const CHAR *szIndexName,
VOID *pv,
ULONG cbMax,
ULONG lInfoLevel,
const BOOL fUnicodeNames )
{
ERR err;
PIB *ppib = (PIB *)vsesid;
IFMP ifmp;
CHAR szTableName[ JET_cbNameMost+1 ];
FUCB *pfucb = pfucbNil;
PGNO pgnoFDP = pgnoNull;
OBJID objidTable = objidNil;
CallR( ErrPIBCheck( ppib ) );
CallR( ErrPIBCheckIfmp( ppib, (IFMP)vdbid ) );
ifmp = (IFMP) vdbid;
CallR( ErrUTILCheckName( szTableName, szTable, ( JET_cbNameMost + 1 ) ) );
switch ( lInfoLevel )
{
case JET_IdxInfoSpaceAlloc:
case JET_IdxInfoLCID:
case JET_IdxInfoLocaleName:
case JET_IdxInfoSortVersion:
case JET_IdxInfoDefinedSortVersion:
case JET_IdxInfoSortId:
case JET_IdxInfoVarSegMac:
case JET_IdxInfoKeyMost:
if ( !FCATHashLookup( ifmp, szTable, &pgnoFDP, &objidTable ) )
{
CallR( ErrCATSeekTable( ppib, ifmp, szTable, &pgnoFDP, &objidTable ) );
}
break;
default:
CallR( ErrFILEOpenTable( ppib, ifmp, &pfucb, szTableName ) );
Assert( pfucbNil != pfucb );
Assert( ( g_rgfmp[ifmp].FReadOnlyAttach() && !FFUCBUpdatable( pfucb ) )
|| ( !g_rgfmp[ifmp].FReadOnlyAttach() && FFUCBUpdatable( pfucb ) ) );
FUCBResetUpdatable( pfucb );
break;
}
Call( ErrINFOGetTableIndexInfo(
ppib,
pfucb,
ifmp,
objidTable,
szIndexName,
pv,
cbMax,
lInfoLevel,
fUnicodeNames ) );
HandleError:
if ( pfucb != pfucbNil )
{
CallS( ErrFILECloseTable( ppib, pfucb ) );
}
return err;
}
ERR VTAPI
ErrIsamGetTableIndexInfo(
JET_SESID vsesid,
JET_VTID vtid,
const CHAR *szIndex,
void *pb,
ULONG cbMax,
ULONG lInfoLevel,
const BOOL fUnicodeNames )
{
return ErrINFOGetTableIndexInfo( (PIB*)vsesid, (FUCB*)vtid, ifmpNil, objidNil, szIndex, pb, cbMax, lInfoLevel, fUnicodeNames );
}
ERR ErrINFOGetTableIndexInfo(
PIB *ppib,
FUCB *pfucb,
IFMP ifmp,
OBJID objidTable,
const CHAR *szIndex,
void *pb,
ULONG cbMax,
ULONG lInfoLevel,
const BOOL fUnicodeNames )
{
ERR err = JET_errSuccess;
CHAR szIndexName[JET_cbNameMost+1];
bool fTransactionStarted = false;
CallR( ErrPIBCheck( ppib ) );
if ( pfucb != pfucbNil )
{
CheckTable( ppib, pfucb );
ifmp = pfucb->ifmp;
objidTable = pfucb->u.pfcb->ObjidFDP();
}
if ( szIndex == NULL || *szIndex == '\0' )
{
*szIndexName = '\0';
}
else
{
CallR( ErrUTILCheckName( szIndexName, szIndex, ( JET_cbNameMost + 1 ) ) );
}
OSTraceFMP(
ifmp,
JET_tracetagDDLRead,
OSFormat(
"Session=[0x%p:0x%x] retrieving info for index '%s' of objid=[0x%x:0x%x] [level=0x%x]",
ppib,
( ppibNil != ppib ? ppib->trxBegin0 : trxMax ),
( 0 != szIndexName[0] ? szIndexName : "<null>" ),
(ULONG)ifmp,
objidTable,
lInfoLevel ) );
if ( ppib->Level() == 0 )
{
CallR( ErrDIRBeginTransaction( ppib, 54811, NO_GRBIT ) );
fTransactionStarted = fTrue;
}
switch ( lInfoLevel )
{
case JET_IdxInfo:
case JET_IdxInfoList:
Call( ErrINFOGetTableIndexInfo( ppib, pfucb, szIndexName, pb, cbMax, fUnicodeNames ) );
break;
case JET_IdxInfoIndexId:
Assert( sizeof(JET_INDEXID) <= cbMax );
Call( ErrINFOGetTableIndexIdInfo( ppib, pfucb, szIndexName, (INDEXID *)pb ) );
break;
case JET_IdxInfoSpaceAlloc:
Assert( sizeof(ULONG) == cbMax );
Call( ErrCATGetIndexAllocInfo(
ppib,
ifmp,
objidTable,
szIndexName,
(ULONG *)pb ) );
break;
case JET_IdxInfoLCID:
{
LCID lcid = lcidNone;
Assert( sizeof(LANGID) == cbMax
|| sizeof(LCID) == cbMax );
Call( ErrCATGetIndexLcid(
ppib,
ifmp,
objidTable,
szIndexName,
&lcid ) );
if ( cbMax < sizeof(LCID) )
{
*(LANGID *)pb = LangidFromLcid( lcid );
}
else
{
*(LCID *)pb = lcid;
}
}
break;
case JET_IdxInfoLocaleName:
{
WCHAR* wszLocaleName = (WCHAR*) pb;
Call( ErrCATGetIndexLocaleName(
ppib,
ifmp,
objidTable,
szIndexName,
wszLocaleName,
cbMax ) );
}
break;
case JET_IdxInfoSortVersion:
{
Call( ErrCATGetIndexSortVersion(
ppib,
ifmp,
objidTable,
szIndexName,
(DWORD*) pb ) );
}
break;
case JET_IdxInfoDefinedSortVersion:
{
Call( ErrCATGetIndexDefinedSortVersion(
ppib,
ifmp,
objidTable,
szIndexName,
(DWORD*) pb ) );
}
break;
case JET_IdxInfoSortId:
{
Call( ErrCATGetIndexSortid(
ppib,
ifmp,
objidTable,
szIndexName,
(SORTID*) pb ) );
}
break;
case JET_IdxInfoVarSegMac:
Assert( sizeof(USHORT) == cbMax );
Call( ErrCATGetIndexVarSegMac(
ppib,
ifmp,
objidTable,
szIndexName,
(USHORT *)pb ) );
break;
case JET_IdxInfoKeyMost:
Assert( sizeof(USHORT) == cbMax );
Call( ErrCATGetIndexKeyMost(
ppib,
ifmp,
objidTable,
szIndexName,
(USHORT *)pb ) );
break;
case JET_IdxInfoCount:
{
INT cIndexes = 1;
FCB *pfcbT;
FCB * const pfcbTable = pfucb->u.pfcb;
pfcbTable->EnterDML();
for ( pfcbT = pfcbTable->PfcbNextIndex();
pfcbT != pfcbNil;
pfcbT = pfcbT->PfcbNextIndex() )
{
err = ErrFILEIAccessIndex( pfucb->ppib, pfcbTable, pfcbT );
if ( err < 0 )
{
if ( JET_errIndexNotFound != err )
{
pfcbTable->LeaveDML();
goto HandleError;
}
}
else
{
cIndexes++;
}
}
pfcbTable->LeaveDML();
Assert( sizeof(INT) == cbMax );
*( (INT *)pb ) = cIndexes;
err = JET_errSuccess;
break;
}
case JET_IdxInfoCreateIndex:
case JET_IdxInfoCreateIndex2:
case JET_IdxInfoCreateIndex3:
Call( ErrINFOGetTableIndexInfoForCreateIndex( ppib, pfucb, szIndexName, pb, cbMax, fUnicodeNames, lInfoLevel ) );
break;
case JET_IdxInfoSysTabCursor:
case JET_IdxInfoOLC:
case JET_IdxInfoResetOLC:
default:
Assert( fFalse );
err = ErrERRCheck( JET_errInvalidParameter );
break;
}
HandleError:
if( err >= 0 && fTransactionStarted )
{
err = ErrDIRCommitTransaction( ppib, NO_GRBIT );
}
if( err < 0 && fTransactionStarted )
{
const ERR errT = ErrDIRRollback( ppib );
if ( JET_errSuccess != errT )
{
Assert( errT < 0 );
Assert( PinstFromPpib( ppib )->FInstanceUnavailable() );
Assert( JET_errSuccess != ppib->ErrRollbackFailure() );
}
}
return err;
}
LOCAL ERR ErrINFOGetTableIndexInfo(
PIB *ppib,
FUCB *pfucb,
const CHAR *szIndexName,
VOID *pv,
const ULONG cbMax,
const BOOL fUnicodeNames)
{
ERR err;
FCB *pfcbTable;
FCB *pfcbIndex;
TDB *ptdb;
LONG cRecord;
LONG cKey;
LONG cPage;
LONG cRows;
JET_TABLEID tableid;
JET_COLUMNID columnid;
JET_GRBIT grbit = 0;
JET_GRBIT grbitColumn;
JET_COLUMNID rgcolumnid[ccolumndefGetIndexInfoMax];
WORD wCollate = 0;
WORD wT;
LANGID langid;
DWORD dwMapFlags;
Assert( NULL != szIndexName );
BOOL fIndexList = ( '\0' == *szIndexName );
BOOL fUpdatingLatchSet = fFalse;
if ( cbMax < sizeof(JET_INDEXLIST) - cbIDXLISTNewMembersSinceOriginalFormat )
return ErrERRCheck( JET_wrnBufferTruncated );
const ULONG cbIndexList = sizeof(JET_INDEXLIST) -
( cbMax < sizeof(JET_INDEXLIST) ? cbIDXLISTNewMembersSinceOriginalFormat : 0 );
C_ASSERT( sizeof(rgcolumndefGetIndexInfo_W) == sizeof(rgcolumndefGetIndexInfo_A) );
CallR( ErrIsamOpenTempTable(
(JET_SESID)ppib,
(JET_COLUMNDEF *)( fUnicodeNames ? rgcolumndefGetIndexInfo_W : rgcolumndefGetIndexInfo_A ),
ccolumndefGetIndexInfoMax,
NULL,
JET_bitTTScrollable|JET_bitTTIndexed,
&tableid,
rgcolumnid,
JET_cbKeyMost_OLD,
JET_cbKeyMost_OLD ) );
cRows = 0;
pfcbTable = pfucb->u.pfcb;
Assert( pfcbTable != pfcbNil );
ptdb = pfcbTable->Ptdb();
Assert( ptdbNil != ptdb );
Call( pfcbTable->ErrSetUpdatingAndEnterDML( ppib, fTrue ) );
fUpdatingLatchSet = fTrue;
pfcbTable->AssertDML();
for ( pfcbIndex = pfcbTable; pfcbIndex != pfcbNil; pfcbIndex = pfcbIndex->PfcbNextIndex() )
{
Assert( pfcbIndex->Pidb() != pidbNil || pfcbIndex == pfcbTable );
if ( pfcbIndex->Pidb() != pidbNil )
{
if ( fIndexList )
{
err = ErrFILEIAccessIndex( ppib, pfcbTable, pfcbIndex );
}
else
{
Assert( NULL != szIndexName );
err = ErrFILEIAccessIndexByName( ppib, pfcbTable, pfcbIndex, szIndexName );
}
if ( err < 0 )
{
if ( JET_errIndexNotFound != err )
{
pfcbTable->LeaveDML();
goto HandleError;
}
}
else
break;
}
}
pfcbTable->AssertDML();
if ( pfcbNil == pfcbIndex && !fIndexList )
{
pfcbTable->LeaveDML();
err = ErrERRCheck( JET_errIndexNotFound );
goto HandleError;
}
while ( pfcbIndex != pfcbNil )
{
CHAR szCurrIndex[JET_cbNameMost+1];
IDXSEG rgidxseg[JET_ccolKeyMost];
pfcbTable->AssertDML();
const IDB *pidb = pfcbIndex->Pidb();
Assert( pidbNil != pidb );
Assert( pidb->ItagIndexName() != 0 );
OSStrCbCopyA(
szCurrIndex,
sizeof(szCurrIndex),
pfcbTable->Ptdb()->SzIndexName( pidb->ItagIndexName(), pfcbIndex->FDerivedIndex() ) );
const ULONG cColumn = pidb->Cidxseg();
UtilMemCpy( rgidxseg, PidxsegIDBGetIdxSeg( pidb, pfcbTable->Ptdb() ), cColumn * sizeof(IDXSEG) );
grbit = pidb->GrbitFromFlags();
LCID lcid;
Call( ErrNORMLocaleToLcid( pidb->WszLocaleName(), &lcid ) );
langid = LangidFromLcid( lcid );
dwMapFlags = pidb->DwLCMapFlags();
pfcbTable->LeaveDML();
for ( ULONG iidxseg = 0; iidxseg < cColumn; iidxseg++ )
{
FIELD field;
CHAR szFieldName[JET_cbNameMost+1];
WCHAR wszName[JET_cbNameMost+1];
size_t cwchActual;
Call( ErrDispPrepareUpdate( (JET_SESID)ppib, tableid, JET_prepInsert ) );
if ( fUnicodeNames )
{
Call( ErrOSSTRAsciiToUnicode( szCurrIndex, wszName, _countof(wszName), &cwchActual ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexName],
wszName,
(ULONG)( sizeof(WCHAR) * wcslen( wszName ) ),
NO_GRBIT,
NULL ) );
}
else
{
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexName],
szCurrIndex,
(ULONG)strlen( szCurrIndex ),
NO_GRBIT,
NULL ) );
}
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexGrbit],
&grbit,
sizeof( grbit ),
NO_GRBIT,
NULL ) );
Call( ErrSTATSRetrieveIndexStats(
pfucb,
szCurrIndex,
pfcbIndex->FPrimaryIndex(),
&cRecord,
&cKey,
&cPage ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexCKey],
&cKey,
sizeof( cKey ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexCEntry],
&cRecord,
sizeof( cRecord ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexCPage],
&cPage,
sizeof( cPage ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexCCol],
&cColumn,
sizeof( cColumn ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexICol],
&iidxseg,
sizeof( iidxseg ),
NO_GRBIT,
NULL ) );
grbitColumn = ( rgidxseg[iidxseg].FDescending() ?
JET_bitKeyDescending :
JET_bitKeyAscending );
columnid = rgidxseg[iidxseg].Columnid();
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexColId],
&columnid,
sizeof( columnid ),
0,
NULL ) );
if ( FCOLUMNIDTemplateColumn( columnid ) && !ptdb->FTemplateTable() )
{
ptdb->AssertValidDerivedTable();
const TDB * const ptdbTemplateTable = ptdb->PfcbTemplateTable()->Ptdb();
field = *( ptdbTemplateTable->Pfield( columnid ) );
OSStrCbCopyA( szFieldName, sizeof(szFieldName), ptdbTemplateTable->SzFieldName( field.itagFieldName, fFalse ) );
}
else
{
pfcbTable->EnterDML();
field = *( ptdb->Pfield( columnid ) );
OSStrCbCopyA( szFieldName, sizeof(szFieldName), ptdb->SzFieldName( field.itagFieldName, fFalse ) );
pfcbTable->LeaveDML();
}
{
JET_COLTYP coltyp = field.coltyp;
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexColType],
&coltyp,
sizeof( coltyp ),
NO_GRBIT,
NULL ) );
}
wT = countryDefault;
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexCountry],
&wT,
sizeof( wT ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexLangid],
&langid,
sizeof( langid ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexLCMapFlags],
&dwMapFlags,
sizeof( dwMapFlags ),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexCp],
&field.cp,
sizeof(field.cp),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexCollate],
&wCollate,
sizeof(wCollate),
NO_GRBIT,
NULL ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexColBits],
&grbitColumn,
sizeof( grbitColumn ),
NO_GRBIT,
NULL ) );
if ( fUnicodeNames )
{
Call( ErrOSSTRAsciiToUnicode( szFieldName, wszName, _countof(wszName), &cwchActual ) );
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexColName],
wszName,
(ULONG)( sizeof(WCHAR) * wcslen( wszName ) ),
NO_GRBIT,
NULL ) );
}
else
{
Call( ErrDispSetColumn(
(JET_SESID)ppib,
tableid,
rgcolumnid[iIndexColName],
szFieldName,
(ULONG)strlen( szFieldName ),
NO_GRBIT,
NULL ) );
}
Call( ErrDispUpdate( (JET_SESID)ppib, tableid, NULL, 0, NULL, NO_GRBIT ) );
cRows++;
}
pfcbTable->EnterDML();
if ( fIndexList )
{
for ( pfcbIndex = pfcbIndex->PfcbNextIndex(); pfcbIndex != pfcbNil; pfcbIndex = pfcbIndex->PfcbNextIndex() )
{
err = ErrFILEIAccessIndex( ppib, pfcbTable, pfcbIndex );
if ( err < 0 )
{
if ( JET_errIndexNotFound != err )
{
pfcbTable->LeaveDML();
goto HandleError;
}
}
else
break;
}
}
else
{
pfcbIndex = pfcbNil;
}
}
pfcbTable->ResetUpdatingAndLeaveDML();
fUpdatingLatchSet = fFalse;
err = ErrDispMove( (JET_SESID)ppib, tableid, JET_MoveFirst, NO_GRBIT );
if ( err < 0 )
{
if ( err != JET_errNoCurrentRecord )
goto HandleError;
err = JET_errSuccess;
}
((JET_INDEXLIST *)pv)->cbStruct = cbIndexList;
((JET_INDEXLIST *)pv)->tableid = tableid;
((JET_INDEXLIST *)pv)->cRecord = cRows;
((JET_INDEXLIST *)pv)->columnidindexname = rgcolumnid[iIndexName];
((JET_INDEXLIST *)pv)->columnidgrbitIndex = rgcolumnid[iIndexGrbit];
((JET_INDEXLIST *)pv)->columnidcEntry = rgcolumnid[iIndexCEntry];
((JET_INDEXLIST *)pv)->columnidcKey = rgcolumnid[iIndexCKey];
((JET_INDEXLIST *)pv)->columnidcPage = rgcolumnid[iIndexCPage];
((JET_INDEXLIST *)pv)->columnidcColumn = rgcolumnid[iIndexCCol];
((JET_INDEXLIST *)pv)->columnidiColumn = rgcolumnid[iIndexICol];
((JET_INDEXLIST *)pv)->columnidcolumnid = rgcolumnid[iIndexColId];
((JET_INDEXLIST *)pv)->columnidcoltyp = rgcolumnid[iIndexColType];
((JET_INDEXLIST *)pv)->columnidCountry = rgcolumnid[iIndexCountry];
((JET_INDEXLIST *)pv)->columnidLangid = rgcolumnid[iIndexLangid];
((JET_INDEXLIST *)pv)->columnidCp = rgcolumnid[iIndexCp];
((JET_INDEXLIST *)pv)->columnidCollate = rgcolumnid[iIndexCollate];
((JET_INDEXLIST *)pv)->columnidgrbitColumn = rgcolumnid[iIndexColBits];
((JET_INDEXLIST *)pv)->columnidcolumnname = rgcolumnid[iIndexColName];
if ( cbIndexList < sizeof(JET_INDEXLIST) )
{
Assert( cbMax >= sizeof(JET_INDEXLIST) - cbIDXLISTNewMembersSinceOriginalFormat );
}
else
{
Assert( cbMax >= sizeof(JET_INDEXLIST) );
((JET_INDEXLIST *)pv)->columnidLCMapFlags = rgcolumnid[iIndexLCMapFlags];
}
return JET_errSuccess;
HandleError:
if ( fUpdatingLatchSet )
{
pfcbTable->ResetUpdating();
}
(VOID)ErrDispCloseTable( (JET_SESID)ppib, tableid );
return err;
}
LOCAL ERR ErrINFOGetTableIndexIdInfo(
PIB * ppib,
FUCB * pfucb,
const CHAR * szIndexName,
INDEXID * pindexid )
{
ERR err;
FCB * const pfcbTable = pfucb->u.pfcb;
FCB * pfcbIndex;
Assert( NULL != szIndexName );
Assert( pfcbTable != pfcbNil );
CallR( pfcbTable->ErrSetUpdatingAndEnterDML( ppib, fTrue ) );
pfcbTable->AssertDML();
for ( pfcbIndex = pfcbTable; pfcbIndex != pfcbNil; pfcbIndex = pfcbIndex->PfcbNextIndex() )
{
Assert( pfcbIndex->Pidb() != pidbNil || pfcbIndex == pfcbTable );
if ( pfcbIndex->Pidb() != pidbNil )
{
err = ErrFILEIAccessIndexByName(
ppib,
pfcbTable,
pfcbIndex,
szIndexName );
if ( err < 0 )
{
if ( JET_errIndexNotFound != err )
{
goto HandleError;
}
}
else
{
CallS( err );
break;
}
}
}
pfcbTable->AssertDML();
if ( pfcbNil == pfcbIndex )
{
err = ErrERRCheck( JET_errIndexNotFound );
}
else
{
CallS( err );
Assert( pfcbIndex->FValid() );
Assert( sizeof(INDEXID) == sizeof(JET_INDEXID) );
pindexid->cbStruct = sizeof(INDEXID);
pindexid->pfcbIndex = pfcbIndex;
pindexid->objidFDP = pfcbIndex->ObjidFDP();
pindexid->pgnoFDP = pfcbIndex->PgnoFDP();
}
HandleError:
pfcbTable->AssertDML();
pfcbTable->ResetUpdatingAndLeaveDML();
return err;
}
LOCAL ERR ErrINFOICopyAsciiName(
_Out_writes_(cwchNameDest) WCHAR * const wszNameDest,
const size_t cwchNameDest,
const CHAR * const szNameSrc,
size_t * pcbActual )
{
size_t cwchActual = 0;
const ERR err = ErrOSSTRAsciiToUnicode( szNameSrc, wszNameDest, cwchNameDest, &cwchActual );
if ( NULL != pcbActual )
*pcbActual = cwchActual * sizeof( WCHAR );
return err;
}
LOCAL ERR ErrINFOICopyAsciiName(
_Out_writes_(cchNameDest) CHAR * const szNameDest,
const size_t cchNameDest,
const CHAR * const szNameSrc,
size_t * pcbActual )
{
const ERR err = ErrOSStrCbCopyA( szNameDest, cchNameDest, szNameSrc );
CallSx( err, JET_errBufferTooSmall );
if ( NULL != pcbActual )
*pcbActual = ( strlen( JET_errSuccess == err ? szNameDest : szNameSrc ) + 1 ) * sizeof( CHAR );
return err;
}
INLINE VOID INFOISetKeySegmentDescendingFlag(
__in WCHAR * const pwch,
const BOOL fDescending )
{
Assert( NULL != pwch );
*pwch = ( fDescending ? L'-' : L'+' );
}
INLINE VOID INFOISetKeySegmentDescendingFlag(
__in CHAR * const pch,
const BOOL fDescending )
{
Assert( NULL != pch );
*pch = ( fDescending ? '-' : '+' );
}
template< class JET_INDEXCREATE_T, class JET_CONDITIONALCOLUMN_T, class JET_UNICODEINDEX_T, class T, ULONG cbV2Reserve >
ERR ErrINFOIBuildIndexCreateVX(
FCB * const pfcbTable,
FCB * const pfcbIndex,
VOID * const pvResult,
const ULONG cbMax,
VOID ** ppvV2Reserve,
WCHAR ** pszLocaleName,
ULONG lIdxVersion )
{
ERR err = JET_errSuccess;
TDB * ptdb = ptdbNil;
IDB * pidb = pidbNil;
JET_INDEXCREATE_T * pindexcreate = NULL;
CHAR * szIndexName = NULL;
const IDXSEG * rgidxseg = NULL;
size_t cbKey = 0;
size_t cbActual = 0;
BYTE * pbBuffer = (BYTE *)pvResult;
size_t cbBufferRemaining = cbMax;
Assert( pfcbNil != pfcbTable );
Assert( pfcbNil != pfcbIndex );
Assert( lIdxVersion == JET_IdxInfoCreateIndex || lIdxVersion == JET_IdxInfoCreateIndex2 || lIdxVersion == JET_IdxInfoCreateIndex3);
if ( cbV2Reserve > 0 )
{
Assert( ppvV2Reserve != NULL );
}
else
{
Assert( ppvV2Reserve == NULL );
}
ptdb = pfcbTable->Ptdb();
Assert( ptdbNil != ptdb );
pidb = pfcbIndex->Pidb();
Assert( pidbNil != pidb );
Assert( NULL != pbBuffer );
Assert( cbBufferRemaining >= sizeof( JET_INDEXCREATE_T ) );
if ( cbBufferRemaining < sizeof( JET_INDEXCREATE_T ) )
{
Error( ErrERRCheck( JET_errBufferTooSmall ) );
}
pindexcreate = (JET_INDEXCREATE_T *)pbBuffer;
memset( pindexcreate, 0, sizeof( JET_INDEXCREATE_T ) );
pindexcreate->cbStruct = sizeof( JET_INDEXCREATE_T );
pbBuffer += sizeof( JET_INDEXCREATE_T );
cbBufferRemaining -= sizeof( JET_INDEXCREATE_T );
if ( cbV2Reserve )
{
if ( cbBufferRemaining < cbV2Reserve )
{
Error( ErrERRCheck( JET_errBufferTooSmall ) );
}
*ppvV2Reserve = pbBuffer;
pbBuffer += cbV2Reserve;
cbBufferRemaining -= cbV2Reserve;
}
pindexcreate->szIndexName = (T *)pbBuffer;
szIndexName = ptdb->SzIndexName( pidb->ItagIndexName() );
Assert( NULL != szIndexName );
Assert( strlen( szIndexName ) > 0 );
Assert( strlen( szIndexName ) <= JET_cbNameMost );
Call( ErrINFOICopyAsciiName(
pindexcreate->szIndexName,
cbBufferRemaining / sizeof( T ),
szIndexName,
&cbActual ) );
Assert( '\0' == pindexcreate->szIndexName[ ( cbActual / sizeof( T ) ) - 1 ] );
Assert( cbBufferRemaining >= cbActual );
pbBuffer += cbActual;
cbBufferRemaining -= cbActual;
pindexcreate->szKey = (T *)pbBuffer;
rgidxseg = PidxsegIDBGetIdxSeg( pidb, ptdb );
Assert( NULL != rgidxseg );
Assert( pidb->Cidxseg() > 0 );
Assert( pidb->Cidxseg() <= JET_ccolKeyMost );
for ( size_t iidxseg = 0; iidxseg < pidb->Cidxseg(); iidxseg++ )
{
const COLUMNID columnid = rgidxseg[ iidxseg ].Columnid();
const FIELD * const pfield = ptdb->Pfield( columnid );
Assert( pfieldNil != pfield );
if ( !FFIELDPrimaryIndexPlaceholder( pfield->ffield ) )
{
const BOOL fDerived = ( FCOLUMNIDTemplateColumn( columnid ) && !ptdb->FTemplateTable() );
const CHAR * szColumnName = ptdb->SzFieldName( pfield->itagFieldName, fDerived );
Assert( NULL != szColumnName );
Assert( strlen( szColumnName ) > 0 );
Assert( strlen( szColumnName ) <= JET_cbNameMost );
if ( cbBufferRemaining < sizeof( T ) )
{
Error( ErrERRCheck( JET_errBufferTooSmall ) );
}
INFOISetKeySegmentDescendingFlag( (T *)pbBuffer, rgidxseg[ iidxseg ].FDescending() );
pbBuffer += sizeof( T );
cbBufferRemaining -= sizeof( T );
Call( ErrINFOICopyAsciiName(
(T *)pbBuffer,
cbBufferRemaining / sizeof( T ),
szColumnName,
&cbActual ) );
Assert( '\0' == ( (T *)pbBuffer )[ ( cbActual / sizeof( T ) ) - 1 ] );
Assert( cbBufferRemaining >= cbActual );
pbBuffer += cbActual;
cbBufferRemaining -= cbActual;
cbKey += ( sizeof( T ) + cbActual );
}
else
{
Assert( pidb->FPrimary() );
Assert( 0 == iidxseg );
}
}
Assert( cbKey > sizeof( T ) + sizeof( T ) );
if ( cbBufferRemaining < sizeof( T ) )
{
Error( ErrERRCheck( JET_errBufferTooSmall ) );
}
*(T *)pbBuffer = 0;
cbKey += sizeof( T );
pbBuffer += sizeof( T );
cbBufferRemaining -= sizeof( T );
pindexcreate->cbKey = cbKey;
pindexcreate->grbit = pidb->GrbitFromFlags();
pindexcreate->ulDensity = pfcbIndex->UlDensity();
if ( cbBufferRemaining < sizeof( JET_UNICODEINDEX_T ) )
{
Error( ErrERRCheck( JET_errBufferTooSmall ) );
}
pindexcreate->grbit |= JET_bitIndexUnicode;
if ( lIdxVersion != JET_IdxInfoCreateIndex3 )
{
JET_UNICODEINDEX idxUnicode;
pindexcreate->pidxunicode = (JET_UNICODEINDEX_T *)pbBuffer;
Call( ErrNORMLocaleToLcid( pidb->WszLocaleName(), &idxUnicode.lcid ) );
idxUnicode.dwMapFlags = pidb->DwLCMapFlags();
#pragma warning(suppress:26000)
*( pindexcreate->pidxunicode ) = *( (JET_UNICODEINDEX_T *)&idxUnicode );
pbBuffer += sizeof( JET_UNICODEINDEX );
cbBufferRemaining -= sizeof( JET_UNICODEINDEX );
}
else
{
pindexcreate->pidxunicode = (JET_UNICODEINDEX_T *)pbBuffer;
pbBuffer += sizeof(WCHAR*);
cbBufferRemaining -= sizeof(WCHAR*);
pindexcreate->pidxunicode->dwMapFlags = pidb->DwLCMapFlags();
pbBuffer += sizeof( pidb->DwLCMapFlags() );
cbBufferRemaining -= sizeof( pidb->DwLCMapFlags() );
*pszLocaleName = (WCHAR *)pbBuffer;
Call( ErrOSStrCbCopyW( *pszLocaleName, cbBufferRemaining, pidb->WszLocaleName() ) );
Assert( NULL != *pszLocaleName );
const ULONG_PTR cbLocaleName = ( wcslen( *pszLocaleName ) + 1 ) * sizeof(WCHAR);
pbBuffer += cbLocaleName;
cbBufferRemaining -= cbLocaleName;
}
if ( pidb->FTuples() )
{
JET_TUPLELIMITS * ptuplelimits = (JET_TUPLELIMITS *)pbBuffer;
if ( cbBufferRemaining < sizeof( JET_TUPLELIMITS ) )
{
Error( ErrERRCheck( JET_errBufferTooSmall ) );
}
pindexcreate->grbit |= JET_bitIndexTupleLimits;
ptuplelimits->chLengthMin = pidb->CchTuplesLengthMin();
ptuplelimits->chLengthMax = pidb->CchTuplesLengthMax();
ptuplelimits->chToIndexMax = pidb->IchTuplesToIndexMax();
ptuplelimits->cchIncrement = pidb->CchTuplesIncrement();
ptuplelimits->ichStart = pidb->IchTuplesStart();
pindexcreate->ptuplelimits = ptuplelimits;
pbBuffer += sizeof( JET_TUPLELIMITS );
cbBufferRemaining -= sizeof( JET_TUPLELIMITS );
}
else
{
pindexcreate->cbVarSegMac = pidb->CbVarSegMac();
}
if ( pidb->CidxsegConditional() > 0 )
{
JET_CONDITIONALCOLUMN_T * rgconditionalcolumn = (JET_CONDITIONALCOLUMN_T *)pbBuffer;
if ( cbBufferRemaining < sizeof( JET_CONDITIONALCOLUMN_T ) * pidb->CidxsegConditional() )
{
Error( ErrERRCheck( JET_errBufferTooSmall ) );
}
pbBuffer += ( sizeof( JET_CONDITIONALCOLUMN_T ) * pidb->CidxsegConditional() );
cbBufferRemaining -= ( sizeof( JET_CONDITIONALCOLUMN_T ) * pidb->CidxsegConditional() );
rgidxseg = PidxsegIDBGetIdxSegConditional( pidb, ptdb );
Assert( NULL != rgidxseg );
for ( size_t iidxseg = 0; iidxseg < pidb->CidxsegConditional(); iidxseg++ )
{
const COLUMNID columnid = rgidxseg[ iidxseg ].Columnid();
const FIELD * pfield = ptdb->Pfield( columnid );
const BOOL fDerived = ( FCOLUMNIDTemplateColumn( columnid ) && !ptdb->FTemplateTable() );
const CHAR * szColumnName = ptdb->SzFieldName( pfield->itagFieldName, fDerived );
Assert( NULL != szColumnName );
Assert( strlen( szColumnName ) > 0 );
Assert( strlen( szColumnName ) <= JET_cbNameMost );
Call( ErrINFOICopyAsciiName(
(T *)pbBuffer,
cbBufferRemaining / sizeof( T ),
szColumnName,
&cbActual ) );
Assert( '\0' == ( (T *)pbBuffer )[ ( cbActual / sizeof( T ) ) - 1 ] );
rgconditionalcolumn[ iidxseg ].cbStruct = sizeof( JET_CONDITIONALCOLUMN_T );
rgconditionalcolumn[ iidxseg ].szColumnName = (T *)pbBuffer;
rgconditionalcolumn[ iidxseg ].grbit = ( rgidxseg[ iidxseg ].FMustBeNull() ?
JET_bitIndexColumnMustBeNull :
JET_bitIndexColumnMustBeNonNull );
Assert( cbBufferRemaining >= cbActual );
pbBuffer += cbActual;
cbBufferRemaining -= cbActual;
}
pindexcreate->rgconditionalcolumn = rgconditionalcolumn;
pindexcreate->cConditionalColumn = pidb->CidxsegConditional();
}
pindexcreate->cbKeyMost = max( JET_cbKeyMost_OLD, pidb->CbKeyMost() );
CallS( err );
HandleError:
return err;
}
LOCAL ERR ErrINFOGetTableIndexInfoForCreateIndex(
PIB * ppib,
FUCB * pfucb,
const CHAR * szIndex,
VOID * pvResult,
const ULONG cbMax,
const BOOL fUnicodeNames,
ULONG lIdxVersion )
{
ERR err = JET_errSuccess;
FCB * pfcbTable = pfcbNil;
FCB * pfcbIndex = pfcbNil;
BOOL fUpdatingLatchSet = fFalse;
Assert( ppibNil != ppib );
Assert( pfucbNil != pfucb );
pfcbTable = pfucb->u.pfcb;
Assert( pfcbNil != pfcbTable );
Assert( lIdxVersion == JET_IdxInfoCreateIndex || lIdxVersion == JET_IdxInfoCreateIndex2 || lIdxVersion == JET_IdxInfoCreateIndex3 );
Call( pfcbTable->ErrSetUpdatingAndEnterDML( ppib, fTrue ) );
fUpdatingLatchSet = fTrue;
if ( NULL == szIndex || '\0' == *szIndex )
{
if ( pidbNil != pfcbTable->Pidb() )
{
pfcbIndex = pfcbTable;
}
}
else
{
pfcbTable->AssertDML();
for ( pfcbIndex = pfcbTable; pfcbIndex != pfcbNil; pfcbIndex = pfcbIndex->PfcbNextIndex() )
{
Assert( pfcbIndex->Pidb() != pidbNil || pfcbIndex == pfcbTable );
if ( pfcbIndex->Pidb() != pidbNil )
{
err = ErrFILEIAccessIndexByName( ppib, pfcbTable, pfcbIndex, szIndex );
if ( err < JET_errSuccess )
{
if ( JET_errIndexNotFound == err )
{
err = JET_errSuccess;
}
else
{
goto HandleError;
}
}
else
break;
}
}
}
pfcbTable->AssertDML();
CallS( err );
if ( pfcbNil == pfcbIndex )
{
Error( ErrERRCheck( JET_errIndexNotFound ) );
goto HandleError;
}
if ( lIdxVersion == JET_IdxInfoCreateIndex )
if ( fUnicodeNames )
{
err = ErrINFOIBuildIndexCreateVX< JET_INDEXCREATE_W, JET_CONDITIONALCOLUMN_W, JET_UNICODEINDEX, WCHAR, 0 >(
pfcbTable,
pfcbIndex,
pvResult,
cbMax,
NULL,
NULL,
lIdxVersion );
}
else
{
err = ErrINFOIBuildIndexCreateVX< JET_INDEXCREATE_A, JET_CONDITIONALCOLUMN_A, JET_UNICODEINDEX, CHAR, 0 >(
pfcbTable,
pfcbIndex,
pvResult,
cbMax,
NULL,
NULL,
lIdxVersion );
}
else if ( lIdxVersion == JET_IdxInfoCreateIndex2 )
{
JET_SPACEHINTS * pSPHints = NULL;
if ( fUnicodeNames )
{
err = ErrINFOIBuildIndexCreateVX< JET_INDEXCREATE2_W, JET_CONDITIONALCOLUMN_W, JET_UNICODEINDEX, WCHAR, sizeof(JET_SPACEHINTS) >(
pfcbTable,
pfcbIndex,
pvResult,
cbMax,
(void**)&pSPHints,
NULL,
lIdxVersion );
}
else
{
err = ErrINFOIBuildIndexCreateVX< JET_INDEXCREATE2_A, JET_CONDITIONALCOLUMN_A, JET_UNICODEINDEX, CHAR, sizeof(JET_SPACEHINTS) >(
pfcbTable,
pfcbIndex,
pvResult,
cbMax,
(void**)&pSPHints,
NULL,
lIdxVersion );
}
if ( err >= JET_errSuccess )
{
C_ASSERT( OffsetOf(JET_INDEXCREATE2_W, pSpacehints) == OffsetOf(JET_INDEXCREATE2_A, pSpacehints) );
Assert( OffsetOf(JET_INDEXCREATE2_W, pSpacehints) == OffsetOf(JET_INDEXCREATE2_A, pSpacehints) );
Assert( pvResult );
Assert( pSPHints > pvResult );
Assert( ((BYTE*)(pSPHints + sizeof(JET_SPACEHINTS))) <= ((BYTE*)pvResult) + cbMax );
Assert( (size_t)pSPHints % sizeof(ULONG) == 0 );
pfcbIndex->GetAPISpaceHints( pSPHints );
Assert( pSPHints->cbStruct == sizeof(JET_SPACEHINTS) );
if ( fUnicodeNames )
{
((JET_INDEXCREATE2_W*)pvResult)->pSpacehints = pSPHints;
Assert( ((JET_INDEXCREATE2_W*)pvResult)->pSpacehints->ulInitialDensity == ((JET_INDEXCREATE2_W*)pvResult)->ulDensity );
}
else
{
((JET_INDEXCREATE2_A*)pvResult)->pSpacehints = pSPHints;
Assert( ((JET_INDEXCREATE2_A*)pvResult)->pSpacehints->ulInitialDensity == ((JET_INDEXCREATE2_A*)pvResult)->ulDensity );
}
}
}
else if ( lIdxVersion == JET_IdxInfoCreateIndex3 )
{
WCHAR *szLocaleName = NULL;
JET_SPACEHINTS * pSPHints = NULL;
if ( fUnicodeNames )
{
err = ErrINFOIBuildIndexCreateVX< JET_INDEXCREATE3_W, JET_CONDITIONALCOLUMN_W, JET_UNICODEINDEX2, WCHAR, sizeof(JET_SPACEHINTS) >(
pfcbTable,
pfcbIndex,
pvResult,
cbMax,
(void**)&pSPHints,
&szLocaleName,
lIdxVersion );
}
else
{
err = ErrINFOIBuildIndexCreateVX< JET_INDEXCREATE3_A, JET_CONDITIONALCOLUMN_A, JET_UNICODEINDEX2, CHAR, sizeof(JET_SPACEHINTS) >(
pfcbTable,
pfcbIndex,
pvResult,
cbMax,
(void**)&pSPHints,
&szLocaleName,
lIdxVersion );
}
if ( err >= JET_errSuccess )
{
C_ASSERT( OffsetOf(JET_INDEXCREATE3_W, pSpacehints) == OffsetOf(JET_INDEXCREATE3_A, pSpacehints) );
Assert( OffsetOf(JET_INDEXCREATE3_W, pSpacehints) == OffsetOf(JET_INDEXCREATE3_A, pSpacehints) );
Assert( pvResult );
Assert( szLocaleName > pvResult );
const ULONG_PTR cbLocaleName = ( wcslen( szLocaleName ) + 1 ) * sizeof(WCHAR);
Assert( ((BYTE*)szLocaleName) + cbLocaleName <= ((BYTE*)pvResult) + cbMax );
((JET_INDEXCREATE3_W*)pvResult)->pidxunicode->szLocaleName = szLocaleName;
Assert( pSPHints > pvResult );
Assert( (((BYTE*)pSPHints) + sizeof(JET_SPACEHINTS)) <= ((BYTE*)pvResult) + cbMax );
Assert( (size_t)pSPHints % sizeof(ULONG) == 0 );
pfcbIndex->GetAPISpaceHints( pSPHints );
Assert( pSPHints->cbStruct == sizeof(JET_SPACEHINTS) );
if ( fUnicodeNames )
{
((JET_INDEXCREATE3_W*)pvResult)->pSpacehints = pSPHints;
Assert( ((JET_INDEXCREATE3_W*)pvResult)->pSpacehints->ulInitialDensity == ((JET_INDEXCREATE3_W*)pvResult)->ulDensity );
}
else
{
((JET_INDEXCREATE3_A*)pvResult)->pSpacehints = pSPHints;
Assert( ((JET_INDEXCREATE3_A*)pvResult)->pSpacehints->ulInitialDensity == ((JET_INDEXCREATE3_A*)pvResult)->ulDensity );
}
}
}
else
{
AssertSz( fFalse, "Unknown lIdxVersion (%d)!\n", lIdxVersion );
}
Call( err );
CallS( err );
HandleError:
if ( fUpdatingLatchSet )
{
pfcbTable->ResetUpdatingAndLeaveDML();
}
return err;
}
ERR VDBAPI ErrIsamGetDatabaseInfo(
JET_SESID vsesid,
JET_DBID vdbid,
VOID *pvResult,
const ULONG cbMax,
const ULONG ulInfoLevel )
{
PIB *ppib = (PIB *)vsesid;
ERR err;
IFMP ifmp;
WORD cp = usEnglishCodePage;
WORD wCountry = countryDefault;
WORD wCollate = 0;
bool fUseCachedResult = 0;
ULONG ulT = 0;
CallR( ErrPIBCheck( ppib ) );
CallR( ErrPIBCheckIfmp( ppib, (IFMP)vdbid ) );
ifmp = (IFMP) vdbid;
Assert ( cbMax == 0 || pvResult != NULL );
Expected( FInRangeIFMP( ifmp ) );
if ( !FInRangeIFMP( ifmp ) || !g_rgfmp[ifmp].FInUse() )
{
err = ErrERRCheck( JET_errInvalidParameter );
goto HandleError;
}
fUseCachedResult = (bool)((ulInfoLevel & JET_DbInfoUseCachedResult) ? 1 : 0 );
ulT = (ulInfoLevel & ~(JET_DbInfoUseCachedResult));
switch ( ulT )
{
case JET_DbInfoFilename:
if ( sizeof( WCHAR ) * ( LOSStrLengthW( g_rgfmp[ifmp].WszDatabaseName() ) + 1UL ) > cbMax )
{
err = ErrERRCheck( JET_errBufferTooSmall );
goto HandleError;
}
OSStrCbCopyW( (WCHAR *)pvResult, cbMax, g_rgfmp[ifmp].WszDatabaseName() );
break;
case JET_DbInfoConnect:
if ( 1UL > cbMax )
{
err = ErrERRCheck( JET_errBufferTooSmall );
goto HandleError;
}
*(CHAR *)pvResult = '\0';
break;
case JET_DbInfoCountry:
if ( cbMax != sizeof(LONG) )
return ErrERRCheck( JET_errInvalidBufferSize );
*(LONG *)pvResult = wCountry;
break;
case JET_DbInfoLCID:
if ( cbMax != sizeof(LONG) )
return ErrERRCheck( JET_errInvalidBufferSize );
Call( ErrNORMLocaleToLcid( PinstFromPpib( ppib )->m_wszLocaleNameDefault, (LCID *)pvResult ) );
break;
case JET_DbInfoCp:
if ( cbMax != sizeof(LONG) )
return ErrERRCheck( JET_errInvalidBufferSize );
*(LONG *)pvResult = cp;
break;
case JET_DbInfoCollate:
if ( cbMax != sizeof(LONG) )
return ErrERRCheck( JET_errInvalidBufferSize );
*(LONG *)pvResult = wCollate;
break;
case JET_DbInfoOptions:
if ( cbMax != sizeof(JET_GRBIT) )
return ErrERRCheck( JET_errInvalidBufferSize );
*(JET_GRBIT *)pvResult = g_rgfmp[ifmp].FExclusiveBySession( ppib ) ? JET_bitDbExclusive : 0;
break;
case JET_DbInfoTransactions:
if ( cbMax != sizeof(LONG) )
return ErrERRCheck( JET_errInvalidBufferSize );
*(LONG*)pvResult = levelUserMost;
break;
case JET_DbInfoVersion:
if ( cbMax != sizeof(LONG) )
return ErrERRCheck( JET_errInvalidBufferSize );
*(LONG *)pvResult = ulDAEVersionMax;
break;
case JET_DbInfoIsam:
return ErrERRCheck( JET_errFeatureNotAvailable );
case JET_DbInfoMisc:
if ( sizeof( JET_DBINFOMISC ) != cbMax &&
sizeof( JET_DBINFOMISC2 ) != cbMax &&
sizeof( JET_DBINFOMISC3 ) != cbMax &&
sizeof( JET_DBINFOMISC4 ) != cbMax &&
sizeof( JET_DBINFOMISC5 ) != cbMax &&
sizeof( JET_DBINFOMISC6 ) != cbMax &&
sizeof( JET_DBINFOMISC7 ) != cbMax )
{
return ErrERRCheck( JET_errInvalidBufferSize );
}
ProbeClientBuffer( pvResult, cbMax );
{
UtilLoadDbinfomiscFromPdbfilehdr( ( JET_DBINFOMISC7* )pvResult, cbMax, g_rgfmp[ ifmp ].Pdbfilehdr().get() );
}
break;
case JET_DbInfoPageSize:
if ( sizeof( ULONG ) != cbMax )
{
err = ErrERRCheck( JET_errBufferTooSmall );
goto HandleError;
}
{
const ULONG cbPageSize = g_rgfmp[ifmp].Pdbfilehdr()->le_cbPageSize;
*(ULONG *)pvResult = ( 0 != cbPageSize ? cbPageSize : g_cbPageDefault );
}
break;
case JET_DbInfoFilesize:
{
QWORD cbFileSize = 0;
Call( g_rgfmp[ifmp].Pfapi()->ErrSize( &cbFileSize, IFileAPI::filesizeLogical ) );
*(ULONG *)pvResult = static_cast<ULONG>( g_rgfmp[ifmp].CpgOfCb( cbFileSize ) );
}
break;
case JET_DbInfoFilesizeOnDisk:
{
QWORD cbFileSize = 0;
Call( g_rgfmp[ifmp].Pfapi()->ErrSize( &cbFileSize, IFileAPI::filesizeOnDisk ) );
*(ULONG *)pvResult = static_cast<ULONG>( g_rgfmp[ifmp].CpgOfCb( cbFileSize ) );
}
break;
case JET_DbInfoSpaceOwned:
if ( cbMax != sizeof(ULONG) )
return ErrERRCheck( JET_errInvalidBufferSize );
err = ErrSPGetDatabaseInfo(
ppib,
ifmp,
static_cast<BYTE *>( pvResult ),
cbMax,
fSPOwnedExtent,
fUseCachedResult );
return err;
case JET_DbInfoSpaceAvailable:
err = ErrSPGetDatabaseInfo(
ppib,
ifmp,
static_cast<BYTE *>( pvResult ),
cbMax,
fSPAvailExtent,
fUseCachedResult );
return err;
case dbInfoSpaceShelved:
{
Expected( !fUseCachedResult );
ULONG rgcpg[2] = { 0 };
if ( cbMax < sizeof(*rgcpg) )
{
return ErrERRCheck( JET_errInvalidBufferSize );
}
err = ErrSPGetDatabaseInfo(
ppib,
ifmp,
(BYTE*)rgcpg,
sizeof(rgcpg),
fSPAvailExtent | fSPShelvedExtent,
fFalse );
*( (ULONG*)pvResult ) = rgcpg[1];
return err;
}
default:
return ErrERRCheck( JET_errInvalidParameter );
}
err = JET_errSuccess;
HandleError:
return err;
}
ERR VTAPI ErrIsamGetCursorInfo(
JET_SESID vsesid,
JET_VTID vtid,
void *pvResult,
ULONG cbMax,
ULONG InfoLevel )
{
ERR err;
PIB *ppib = (PIB *)vsesid;
FUCB *pfucb = (FUCB *)vtid;
VS vs;
Unused( ppib );
CallR( ErrPIBCheck( ppib ) );
CheckFUCB( pfucb->ppib, pfucb );
if ( cbMax != 0 || InfoLevel != 0 )
return ErrERRCheck( JET_errInvalidParameter );
if ( pfucb->locLogical != locOnCurBM )
return ErrERRCheck( JET_errNoCurrentRecord );
Assert( !Pcsr( pfucb )->FLatched() );
Call( ErrDIRGet( pfucb ) );
if ( FNDVersion( pfucb->kdfCurr ) )
{
vs = VsVERCheck( pfucb, pfucb->bmCurr );
if ( vs == vsUncommittedByOther )
{
CallS( ErrDIRRelease( pfucb ) );
OSTraceFMP(
pfucb->ifmp,
JET_tracetagDMLConflicts,
OSFormat(
"Session=[0x%p:0x%x] on objid=[0x%x:0x%x] is attempting to retrieve cursor info, but currency is on a node with uncommitted changes",
ppib,
( ppibNil != ppib ? ppib->trxBegin0 : trxMax ),
(ULONG)pfucb->ifmp,
pfucb->u.pfcb->ObjidFDP() ) );
return ErrERRCheck( JET_errWriteConflict );
}
}
CallS( ErrDIRRelease( pfucb ) );
if ( pfucb->u.pfcb->FTypeTemporaryTable() )
err = JET_errSuccess;
HandleError:
return err;
}
| 33.459357 | 162 | 0.51096 | augustoproiete-forks |
986bd55fbf659318fc91b13645a0c8136b482f93 | 15,523 | cpp | C++ | Source/JavaScriptCore/wasm/WasmBBQPlan.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Source/JavaScriptCore/wasm/WasmBBQPlan.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Source/JavaScriptCore/wasm/WasmBBQPlan.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2016-2020 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WasmBBQPlan.h"
#if ENABLE(WEBASSEMBLY)
#include "B3Compilation.h"
#include "JSToWasm.h"
#include "LinkBuffer.h"
#include "WasmAirIRGenerator.h"
#include "WasmB3IRGenerator.h"
#include "WasmCallee.h"
#include "WasmCodeBlock.h"
#include "WasmSignatureInlines.h"
#include "WasmTierUpCount.h"
#include <wtf/DataLog.h>
#include <wtf/Locker.h>
#include <wtf/StdLibExtras.h>
namespace JSC { namespace Wasm {
namespace WasmBBQPlanInternal {
static constexpr bool verbose = false;
}
BBQPlan::BBQPlan(Context* context, Ref<ModuleInformation> moduleInformation, uint32_t functionIndex, CodeBlock* codeBlock, CompletionTask&& completionTask)
: EntryPlan(context, WTFMove(moduleInformation), AsyncWork::FullCompile, WTFMove(completionTask))
, m_codeBlock(codeBlock)
, m_functionIndex(functionIndex)
{
ASSERT(Options::useBBQJIT());
setMode(m_codeBlock->mode());
dataLogLnIf(WasmBBQPlanInternal::verbose, "Starting BBQ plan for ", functionIndex);
}
bool BBQPlan::prepareImpl()
{
const auto& functions = m_moduleInformation->functions;
if (!tryReserveCapacity(m_wasmInternalFunctions, functions.size(), " WebAssembly functions")
|| !tryReserveCapacity(m_compilationContexts, functions.size(), " compilation contexts")
|| !tryReserveCapacity(m_tierUpCounts, functions.size(), " tier-up counts"))
return false;
m_wasmInternalFunctions.resize(functions.size());
m_compilationContexts.resize(functions.size());
m_tierUpCounts.resize(functions.size());
return true;
}
void BBQPlan::work(CompilationEffort effort)
{
if (!m_codeBlock) {
switch (m_state) {
case State::Initial:
parseAndValidateModule();
if (!hasWork()) {
ASSERT(m_state == State::Validated);
complete(holdLock(m_lock));
break;
}
FALLTHROUGH;
case State::Validated:
prepare();
break;
case State::Prepared:
compileFunctions(effort);
break;
default:
break;
}
return;
}
CompilationContext context;
Vector<UnlinkedWasmToWasmCall> unlinkedWasmToWasmCalls;
std::unique_ptr<TierUpCount> tierUp = makeUnique<TierUpCount>();
std::unique_ptr<InternalFunction> function = compileFunction(m_functionIndex, context, unlinkedWasmToWasmCalls, tierUp.get());
LinkBuffer linkBuffer(*context.wasmEntrypointJIT, nullptr, JITCompilationCanFail);
if (UNLIKELY(linkBuffer.didFailToAllocate())) {
Base::fail(holdLock(m_lock), makeString("Out of executable memory while tiering up function at index ", String::number(m_functionIndex)));
return;
}
size_t functionIndexSpace = m_functionIndex + m_moduleInformation->importFunctionCount();
SignatureIndex signatureIndex = m_moduleInformation->internalFunctionSignatureIndices[m_functionIndex];
const Signature& signature = SignatureInformation::get(signatureIndex);
function->entrypoint.compilation = makeUnique<B3::Compilation>(
FINALIZE_WASM_CODE_FOR_MODE(CompilationMode::BBQMode, linkBuffer, B3CompilationPtrTag, "WebAssembly BBQ function[%i] %s name %s", m_functionIndex, signature.toString().ascii().data(), makeString(IndexOrName(functionIndexSpace, m_moduleInformation->nameSection->get(functionIndexSpace))).ascii().data()),
WTFMove(context.wasmEntrypointByproducts));
MacroAssemblerCodePtr<WasmEntryPtrTag> entrypoint;
{
Ref<BBQCallee> callee = BBQCallee::create(WTFMove(function->entrypoint), functionIndexSpace, m_moduleInformation->nameSection->get(functionIndexSpace), WTFMove(tierUp), WTFMove(unlinkedWasmToWasmCalls));
MacroAssembler::repatchPointer(function->calleeMoveLocation, CalleeBits::boxWasm(callee.ptr()));
ASSERT(!m_codeBlock->m_bbqCallees[m_functionIndex]);
entrypoint = callee->entrypoint();
// We want to make sure we publish our callee at the same time as we link our callsites. This enables us to ensure we
// always call the fastest code. Any function linked after us will see our new code and the new callsites, which they
// will update. It's also ok if they publish their code before we reset the instruction caches because after we release
// the lock our code is ready to be published too.
LockHolder holder(m_codeBlock->m_lock);
m_codeBlock->m_bbqCallees[m_functionIndex] = callee.copyRef();
for (auto& call : callee->wasmToWasmCallsites()) {
MacroAssemblerCodePtr<WasmEntryPtrTag> entrypoint;
if (call.functionIndexSpace < m_moduleInformation->importFunctionCount())
entrypoint = m_codeBlock->m_wasmToWasmExitStubs[call.functionIndexSpace].code();
else
entrypoint = m_codeBlock->wasmEntrypointCalleeFromFunctionIndexSpace(call.functionIndexSpace).entrypoint().retagged<WasmEntryPtrTag>();
MacroAssembler::repatchNearCall(call.callLocation, CodeLocationLabel<WasmEntryPtrTag>(entrypoint));
}
Plan::updateCallSitesToCallUs(*m_codeBlock, CodeLocationLabel<WasmEntryPtrTag>(entrypoint), m_functionIndex, functionIndexSpace);
{
LLIntCallee& llintCallee = m_codeBlock->m_llintCallees->at(m_functionIndex).get();
auto locker = holdLock(llintCallee.tierUpCounter().m_lock);
llintCallee.setReplacement(callee.copyRef());
llintCallee.tierUpCounter().m_compilationStatus = LLIntTierUpCounter::CompilationStatus::Compiled;
}
}
dataLogLnIf(WasmBBQPlanInternal::verbose, "Finished BBQ ", m_functionIndex);
auto locker = holdLock(m_lock);
moveToState(State::Completed);
runCompletionTasks(locker);
}
void BBQPlan::compileFunction(uint32_t functionIndex)
{
m_unlinkedWasmToWasmCalls[functionIndex] = Vector<UnlinkedWasmToWasmCall>();
if (Options::useBBQTierUpChecks())
m_tierUpCounts[functionIndex] = makeUnique<TierUpCount>();
else
m_tierUpCounts[functionIndex] = nullptr;
m_wasmInternalFunctions[functionIndex] = compileFunction(functionIndex, m_compilationContexts[functionIndex], m_unlinkedWasmToWasmCalls[functionIndex], m_tierUpCounts[functionIndex].get());
if (m_exportedFunctionIndices.contains(functionIndex) || m_moduleInformation->referencedFunctions().contains(functionIndex)) {
auto locker = holdLock(m_lock);
SignatureIndex signatureIndex = m_moduleInformation->internalFunctionSignatureIndices[functionIndex];
const Signature& signature = SignatureInformation::get(signatureIndex);
auto result = m_embedderToWasmInternalFunctions.add(functionIndex, createJSToWasmWrapper(*m_compilationContexts[functionIndex].embedderEntrypointJIT, signature, &m_unlinkedWasmToWasmCalls[functionIndex], m_moduleInformation.get(), m_mode, functionIndex));
ASSERT_UNUSED(result, result.isNewEntry);
}
}
std::unique_ptr<InternalFunction> BBQPlan::compileFunction(uint32_t functionIndex, CompilationContext& context, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, TierUpCount* tierUp)
{
const auto& function = m_moduleInformation->functions[functionIndex];
SignatureIndex signatureIndex = m_moduleInformation->internalFunctionSignatureIndices[functionIndex];
const Signature& signature = SignatureInformation::get(signatureIndex);
unsigned functionIndexSpace = m_moduleInformation->importFunctionCount() + functionIndex;
ASSERT_UNUSED(functionIndexSpace, m_moduleInformation->signatureIndexFromFunctionIndexSpace(functionIndexSpace) == signatureIndex);
Expected<std::unique_ptr<InternalFunction>, String> parseAndCompileResult;
unsigned osrEntryScratchBufferSize = 0;
// FIXME: Some webpages use very large Wasm module, and it exhausts all executable memory in ARM64 devices since the size of executable memory region is only limited to 128MB.
// The long term solution should be to introduce a Wasm interpreter. But as a short term solution, we introduce heuristics to switch back to BBQ B3 at the sacrifice of start-up time,
// as BBQ Air bloats such lengthy Wasm code and will consume a large amount of executable memory.
bool forceUsingB3 = false;
if (Options::webAssemblyBBQAirModeThreshold() && m_moduleInformation->codeSectionSize >= Options::webAssemblyBBQAirModeThreshold())
forceUsingB3 = true;
if (!forceUsingB3 && Options::wasmBBQUsesAir())
parseAndCompileResult = parseAndCompileAir(context, function, signature, unlinkedWasmToWasmCalls, m_moduleInformation.get(), m_mode, functionIndex, tierUp);
else
parseAndCompileResult = parseAndCompile(context, function, signature, unlinkedWasmToWasmCalls, osrEntryScratchBufferSize, m_moduleInformation.get(), m_mode, CompilationMode::BBQMode, functionIndex, UINT32_MAX, tierUp);
if (UNLIKELY(!parseAndCompileResult)) {
auto locker = holdLock(m_lock);
if (!m_errorMessage) {
// Multiple compiles could fail simultaneously. We arbitrarily choose the first.
fail(locker, makeString(parseAndCompileResult.error(), ", in function at index ", String::number(functionIndex))); // FIXME make this an Expected.
}
m_currentIndex = m_moduleInformation->functions.size();
return nullptr;
}
return WTFMove(*parseAndCompileResult);
}
void BBQPlan::didCompleteCompilation(const AbstractLocker& locker)
{
for (uint32_t functionIndex = 0; functionIndex < m_moduleInformation->functions.size(); functionIndex++) {
CompilationContext& context = m_compilationContexts[functionIndex];
SignatureIndex signatureIndex = m_moduleInformation->internalFunctionSignatureIndices[functionIndex];
const Signature& signature = SignatureInformation::get(signatureIndex);
const uint32_t functionIndexSpace = functionIndex + m_moduleInformation->importFunctionCount();
ASSERT(functionIndexSpace < m_moduleInformation->functionIndexSpaceSize());
{
LinkBuffer linkBuffer(*context.wasmEntrypointJIT, nullptr, JITCompilationCanFail);
if (UNLIKELY(linkBuffer.didFailToAllocate())) {
Base::fail(locker, makeString("Out of executable memory in function at index ", String::number(functionIndex)));
return;
}
m_wasmInternalFunctions[functionIndex]->entrypoint.compilation = makeUnique<B3::Compilation>(
FINALIZE_CODE(linkBuffer, B3CompilationPtrTag, "WebAssembly BBQ function[%i] %s name %s", functionIndex, signature.toString().ascii().data(), makeString(IndexOrName(functionIndexSpace, m_moduleInformation->nameSection->get(functionIndexSpace))).ascii().data()),
WTFMove(context.wasmEntrypointByproducts));
}
if (const auto& embedderToWasmInternalFunction = m_embedderToWasmInternalFunctions.get(functionIndex)) {
LinkBuffer linkBuffer(*context.embedderEntrypointJIT, nullptr, JITCompilationCanFail);
if (UNLIKELY(linkBuffer.didFailToAllocate())) {
Base::fail(locker, makeString("Out of executable memory in function entrypoint at index ", String::number(functionIndex)));
return;
}
embedderToWasmInternalFunction->entrypoint.compilation = makeUnique<B3::Compilation>(
FINALIZE_CODE(linkBuffer, B3CompilationPtrTag, "Embedder->WebAssembly entrypoint[%i] %s name %s", functionIndex, signature.toString().ascii().data(), makeString(IndexOrName(functionIndexSpace, m_moduleInformation->nameSection->get(functionIndexSpace))).ascii().data()),
WTFMove(context.embedderEntrypointByproducts));
}
}
for (auto& unlinked : m_unlinkedWasmToWasmCalls) {
for (auto& call : unlinked) {
MacroAssemblerCodePtr<WasmEntryPtrTag> executableAddress;
if (m_moduleInformation->isImportedFunctionFromFunctionIndexSpace(call.functionIndexSpace)) {
// FIXME imports could have been linked in B3, instead of generating a patchpoint. This condition should be replaced by a RELEASE_ASSERT. https://bugs.webkit.org/show_bug.cgi?id=166462
executableAddress = m_wasmToWasmExitStubs.at(call.functionIndexSpace).code();
} else
executableAddress = m_wasmInternalFunctions.at(call.functionIndexSpace - m_moduleInformation->importFunctionCount())->entrypoint.compilation->code().retagged<WasmEntryPtrTag>();
MacroAssembler::repatchNearCall(call.callLocation, CodeLocationLabel<WasmEntryPtrTag>(executableAddress));
}
}
}
void BBQPlan::initializeCallees(const CalleeInitializer& callback)
{
ASSERT(!failed());
for (unsigned internalFunctionIndex = 0; internalFunctionIndex < m_wasmInternalFunctions.size(); ++internalFunctionIndex) {
RefPtr<EmbedderEntrypointCallee> embedderEntrypointCallee;
if (auto embedderToWasmFunction = m_embedderToWasmInternalFunctions.get(internalFunctionIndex)) {
embedderEntrypointCallee = EmbedderEntrypointCallee::create(WTFMove(embedderToWasmFunction->entrypoint));
MacroAssembler::repatchPointer(embedderToWasmFunction->calleeMoveLocation, CalleeBits::boxWasm(embedderEntrypointCallee.get()));
}
InternalFunction* function = m_wasmInternalFunctions[internalFunctionIndex].get();
size_t functionIndexSpace = internalFunctionIndex + m_moduleInformation->importFunctionCount();
Ref<BBQCallee> wasmEntrypointCallee = BBQCallee::create(WTFMove(function->entrypoint), functionIndexSpace, m_moduleInformation->nameSection->get(functionIndexSpace), WTFMove(m_tierUpCounts[internalFunctionIndex]), WTFMove(m_unlinkedWasmToWasmCalls[internalFunctionIndex]));
MacroAssembler::repatchPointer(function->calleeMoveLocation, CalleeBits::boxWasm(wasmEntrypointCallee.ptr()));
callback(internalFunctionIndex, WTFMove(embedderEntrypointCallee), WTFMove(wasmEntrypointCallee));
}
}
bool BBQPlan::didReceiveFunctionData(unsigned, const FunctionData&)
{
return true;
}
} } // namespace JSC::Wasm
#endif // ENABLE(WEBASSEMBLY)
| 53.899306 | 311 | 0.739677 | jacadcaps |
986c2380a48d40714960867b90044e1b3ae9b1d6 | 365 | hpp | C++ | ios/Framework/BanubaEffectPlayer.xcframework/ios-x86_64-simulator/BanubaEffectPlayer.framework/PrivateHeaders/bnb/renderer/interfaces/types.hpp | AbhishekDoshi-Bacancy/AgoraSDK | 030a024e5c10189526cb98b5db86998f8da43864 | [
"MIT"
] | 80 | 2020-10-30T07:14:40.000Z | 2022-03-27T08:52:16.000Z | ios/Framework/BanubaEffectPlayer.xcframework/ios-x86_64-simulator/BanubaEffectPlayer.framework/PrivateHeaders/bnb/renderer/interfaces/types.hpp | aayushparashar/plugin_tester | a43f8458f2f06ef2f5b7e7ac4aa067e8d6f65527 | [
"MIT"
] | 5 | 2020-10-27T14:07:20.000Z | 2021-06-01T09:03:01.000Z | ios/Framework/BanubaEffectPlayer.xcframework/ios-x86_64-simulator/BanubaEffectPlayer.framework/PrivateHeaders/bnb/renderer/interfaces/types.hpp | aayushparashar/plugin_tester | a43f8458f2f06ef2f5b7e7ac4aa067e8d6f65527 | [
"MIT"
] | 10 | 2020-12-01T15:24:24.000Z | 2022-02-22T12:38:09.000Z | #pragma once
#include <bnb/renderer/interfaces/all.hpp>
#include <memory>
namespace bnb::interfaces
{
using debug_renderer_sptr = std::shared_ptr<debug_renderer>;
using debug_renderer_wptr = std::weak_ptr<debug_renderer>;
using debug_renderer_uptr = std::unique_ptr<debug_renderer>;
using debug_renderer_ptr = bnb::interfaces::debug_renderer*;
}
| 26.071429 | 64 | 0.767123 | AbhishekDoshi-Bacancy |
9870a9dcd83852a27f22154f595b9a89bafed8dc | 935 | cpp | C++ | source/377.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | 2 | 2017-02-28T11:39:13.000Z | 2019-12-07T17:23:20.000Z | source/377.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | source/377.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | //
// 377.cpp
// LeetCode
//
// Created by Narikbi on 01.03.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <numeric>
using namespace std;
int combinationSum4(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector <int> res (target + 1, 0);
for (int i = 1; i < res.size(); i++) {
for (int x : nums) {
if (x > i) break;
else if (x == i) {
res[i]++;
} else {
res[i] += res[i-x];
}
}
}
return res[target];
}
//
//int main(int argc, const char * argv[]) {
//
// vector<int> v = {1, 2, 3};
// cout << combinationSum4(v, 4) << endl;
//
// return 0;
//}
//
| 17.980769 | 58 | 0.512299 | narikbi |
987129dde97a7838c3dacb13432153fc32d46972 | 1,261 | hpp | C++ | include/magic.hpp | zborffs/Prometheus | 1ab4f88620dcf45872ec1c9d0e7945ecc651636d | [
"MIT"
] | 1 | 2018-12-29T10:39:56.000Z | 2018-12-29T10:39:56.000Z | include/magic.hpp | zborffs/Prometheus | 1ab4f88620dcf45872ec1c9d0e7945ecc651636d | [
"MIT"
] | 3 | 2021-11-12T06:44:46.000Z | 2021-11-12T06:47:56.000Z | include/magic.hpp | zborffs/Prometheus | 1ab4f88620dcf45872ec1c9d0e7945ecc651636d | [
"MIT"
] | null | null | null | #ifndef PROMETHEUS_MAGIC_HPP
#define PROMETHEUS_MAGIC_HPP
#include "defines.hpp"
#include "extern.hpp"
#include "bitmask.hpp"
#include <x86intrin.h>
#ifdef USE_SSE
#if defined (__GNUC__)
#if defined (__BMI2__)
extern uint16_t* rook_attacks[64];
extern uint16_t* bishop_attacks[64];
extern uint64_t rook_masks[64];
extern uint64_t rook_masks2[64];
extern uint64_t bishop_masks[64];
extern uint64_t bishop_masks2[64];
void init_bmi2_fancy(uint16_t table[], uint16_t* attacks[], uint64_t masks[], uint64_t masks2[], bool is_rook);
inline Bitboard bmi2_index_bishop(Square_t square, Bitboard occupied) {
return (uint16_t)_pext_u64(occupied, bishop_masks[square]);
}
inline Bitboard bmi2_index_rook(Square_t square, Bitboard occupied) {
return (uint16_t)_pext_u64(occupied, rook_masks[square]);
}
inline Bitboard attacks_bishop(Square_t square, Bitboard occupied) {
return _pdep_u64(bishop_attacks[square][bmi2_index_bishop(square, occupied)], bishop_masks2[square]);
}
inline Bitboard attacks_rook(Square_t square, Bitboard occupied) {
return _pdep_u64(rook_attacks[square][bmi2_index_rook(square, occupied)], rook_masks2[square]);
}
void init_sliding_attacks();
#endif // __BMI2__
#endif // __GNUC__
#endif // USE_SSE
#endif // PROMETHEUS_MAGIC_HPP
| 28.022222 | 111 | 0.792228 | zborffs |
98715b0085ab867a15e6d0cf6ed3b23743e9921b | 3,295 | hpp | C++ | third_party/omr/gc/base/segregated/SegregatedMarkingScheme.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/gc/base/segregated/SegregatedMarkingScheme.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/gc/base/segregated/SegregatedMarkingScheme.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 1991, 2016 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#if !defined(SEGREGATEDMARKINGSCHEME_HPP_)
#define SEGREGATEDMARKINGSCHEME_HPP_
#include "omrcomp.h"
#include "objectdescription.h"
#include "GCExtensionsBase.hpp"
#include "HeapRegionDescriptorSegregated.hpp"
#include "MarkingScheme.hpp"
#include "BaseVirtual.hpp"
#if defined(OMR_GC_SEGREGATED_HEAP)
class MM_EnvironmentBase;
class MM_SegregatedMarkingScheme : public MM_MarkingScheme
{
/*
* Data members
*/
public:
protected:
private:
/*
* Function members
*/
public:
static MM_SegregatedMarkingScheme *newInstance(MM_EnvironmentBase *env);
void kill(MM_EnvironmentBase *env);
MMINLINE void
preMarkSmallCells(MM_EnvironmentBase* env, MM_HeapRegionDescriptorSegregated *containingRegion, uintptr_t *cellList, uintptr_t preAllocatedBytes)
{
if (NULL != cellList) {
uintptr_t cellSize = containingRegion->getCellSize();
uint8_t *objPtrLow = (uint8_t *)cellList;
/* objPtrHigh is the last object (cell) to be premarked.
* => if there is only one object to premark than low will be equal to high
*/
uint8_t *objPtrHigh = (uint8_t *)cellList + preAllocatedBytes - cellSize;
uintptr_t slotIndexLow, slotIndexHigh;
uintptr_t bitMaskLow, bitMaskHigh;
_markMap->getSlotIndexAndBlockMask((omrobjectptr_t)objPtrLow, &slotIndexLow, &bitMaskLow, false /* high bit block mask for low slot word */);
_markMap->getSlotIndexAndBlockMask((omrobjectptr_t)objPtrHigh, &slotIndexHigh, &bitMaskHigh, true /* low bit block mask for high slot word */);
if (slotIndexLow == slotIndexHigh) {
_markMap->markBlockAtomic(slotIndexLow, bitMaskLow & bitMaskHigh);
} else {
_markMap->markBlockAtomic(slotIndexLow, bitMaskLow);
_markMap->setMarkBlock(slotIndexLow + 1, slotIndexHigh - 1, (uintptr_t)-1);
_markMap->markBlockAtomic(slotIndexHigh, bitMaskHigh);
}
}
}
protected:
/**
* Create a MM_RealtimeMarkingScheme object
*/
MM_SegregatedMarkingScheme(MM_EnvironmentBase *env)
: MM_MarkingScheme(env)
{
_typeId = __FUNCTION__;
}
private:
};
#endif /* OMR_GC_SEGREGATED_HEAP */
#endif /* SEGREGATEDMARKINGSCHEME_HPP_ */
| 34.684211 | 146 | 0.719272 | xiacijie |
9872636f65ca6f797c0c60664af71b95daca9040 | 7,271 | hpp | C++ | src/mbgl/programs/collision_box_program.hpp | dataliz9r/mapbox-gl-native | 7cdc39bee90dbf7658cb280b4fba9e63de18bc31 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/programs/collision_box_program.hpp | dataliz9r/mapbox-gl-native | 7cdc39bee90dbf7658cb280b4fba9e63de18bc31 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/programs/collision_box_program.hpp | dataliz9r/mapbox-gl-native | 7cdc39bee90dbf7658cb280b4fba9e63de18bc31 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #pragma once
#include <mbgl/programs/program.hpp>
#include <mbgl/programs/attributes.hpp>
#include <mbgl/programs/uniforms.hpp>
#include <mbgl/shaders/collision_box.hpp>
#include <mbgl/shaders/collision_circle.hpp>
#include <mbgl/style/properties.hpp>
#include <mbgl/util/geometry.hpp>
#include <cmath>
namespace mbgl {
using CollisionBoxLayoutAttributes = TypeList<
attributes::a_pos,
attributes::a_anchor_pos,
attributes::a_extrude,
attributes::a_shift>;
using CollisionBoxDynamicAttributes = TypeList<attributes::a_placed>;
class CollisionBoxProgram : public Program<
shaders::collision_box,
gfx::Line,
TypeListConcat<CollisionBoxLayoutAttributes, CollisionBoxDynamicAttributes>,
TypeList<
uniforms::u_matrix,
uniforms::u_extrude_scale,
uniforms::u_camera_to_center_distance>,
style::Properties<>>
{
public:
using Program::Program;
static gfx::Vertex<CollisionBoxLayoutAttributes> layoutVertex(Point<float> a, Point<float> anchor, Point<float> o) {
return {
{{
static_cast<int16_t>(a.x),
static_cast<int16_t>(a.y)
}},
{{
static_cast<int16_t>(anchor.x),
static_cast<int16_t>(anchor.y)
}},
{{
static_cast<int16_t>(::round(o.x)),
static_cast<int16_t>(::round(o.y))
}},
{{
0.0f,
0.0f
}}
};
}
static gfx::Vertex<CollisionBoxDynamicAttributes> dynamicVertex(bool placed, bool notUsed) {
return {
{{ static_cast<uint8_t>(placed), static_cast<uint8_t>(notUsed) }}
};
}
template <class DrawMode>
void draw(gl::Context& context,
DrawMode drawMode,
gfx::DepthMode depthMode,
gfx::StencilMode stencilMode,
gfx::ColorMode colorMode,
gfx::CullFaceMode cullFaceMode,
const UniformValues& uniformValues,
const gfx::VertexBuffer<gfx::Vertex<CollisionBoxLayoutAttributes>>& layoutVertexBuffer,
const gfx::VertexBuffer<gfx::Vertex<CollisionBoxDynamicAttributes>>& dynamicVertexBuffer,
const gfx::IndexBuffer& indexBuffer,
const SegmentVector<Attributes>& segments,
const Binders& paintPropertyBinders,
const typename PaintProperties::PossiblyEvaluated& currentProperties,
float currentZoom,
const std::string& layerID) {
typename AllUniforms::Values allUniformValues = uniformValues
.concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties));
typename Attributes::Bindings allAttributeBindings = gl::Attributes<CollisionBoxLayoutAttributes>::bindings(layoutVertexBuffer)
.concat(gl::Attributes<CollisionBoxDynamicAttributes>::bindings(dynamicVertexBuffer))
.concat(paintPropertyBinders.attributeBindings(currentProperties));
assert(layoutVertexBuffer.elements == dynamicVertexBuffer.elements);
for (auto& segment : segments) {
auto vertexArrayIt = segment.vertexArrays.find(layerID);
if (vertexArrayIt == segment.vertexArrays.end()) {
vertexArrayIt = segment.vertexArrays.emplace(layerID, context.createVertexArray()).first;
}
program.draw(
context,
std::move(drawMode),
std::move(depthMode),
std::move(stencilMode),
std::move(colorMode),
std::move(cullFaceMode),
allUniformValues,
vertexArrayIt->second,
Attributes::offsetBindings(allAttributeBindings, segment.vertexOffset),
indexBuffer,
segment.indexOffset,
segment.indexLength);
}
}
};
class CollisionCircleProgram : public Program<
shaders::collision_circle,
gfx::Triangle,
TypeListConcat<CollisionBoxLayoutAttributes, CollisionBoxDynamicAttributes>,
TypeList<
uniforms::u_matrix,
uniforms::u_extrude_scale,
uniforms::u_overscale_factor,
uniforms::u_camera_to_center_distance>,
style::Properties<>>
{
public:
using Program::Program;
static gfx::Vertex<CollisionBoxLayoutAttributes> vertex(Point<float> a, Point<float> anchor, Point<float> o) {
return {
{{
static_cast<int16_t>(a.x),
static_cast<int16_t>(a.y)
}},
{{
static_cast<int16_t>(anchor.x),
static_cast<int16_t>(anchor.y)
}},
{{
static_cast<int16_t>(::round(o.x)),
static_cast<int16_t>(::round(o.y))
}},
{{
0.0f,
0.0f
}}
};
}
template <class DrawMode>
void draw(gl::Context& context,
DrawMode drawMode,
gfx::DepthMode depthMode,
gfx::StencilMode stencilMode,
gfx::ColorMode colorMode,
gfx::CullFaceMode cullFaceMode,
const UniformValues& uniformValues,
const gfx::VertexBuffer<gfx::Vertex<CollisionBoxLayoutAttributes>>& layoutVertexBuffer,
const gfx::VertexBuffer<gfx::Vertex<CollisionBoxDynamicAttributes>>& dynamicVertexBuffer,
const gfx::IndexBuffer& indexBuffer,
const SegmentVector<Attributes>& segments,
const Binders& paintPropertyBinders,
const typename PaintProperties::PossiblyEvaluated& currentProperties,
float currentZoom,
const std::string& layerID) {
typename AllUniforms::Values allUniformValues = uniformValues
.concat(paintPropertyBinders.uniformValues(currentZoom, currentProperties));
typename Attributes::Bindings allAttributeBindings = gl::Attributes<CollisionBoxLayoutAttributes>::bindings(layoutVertexBuffer)
.concat(gl::Attributes<CollisionBoxDynamicAttributes>::bindings(dynamicVertexBuffer))
.concat(paintPropertyBinders.attributeBindings(currentProperties));
for (auto& segment : segments) {
auto vertexArrayIt = segment.vertexArrays.find(layerID);
if (vertexArrayIt == segment.vertexArrays.end()) {
vertexArrayIt = segment.vertexArrays.emplace(layerID, context.createVertexArray()).first;
}
program.draw(
context,
std::move(drawMode),
std::move(depthMode),
std::move(stencilMode),
std::move(colorMode),
std::move(cullFaceMode),
allUniformValues,
vertexArrayIt->second,
Attributes::offsetBindings(allAttributeBindings, segment.vertexOffset),
indexBuffer,
segment.indexOffset,
segment.indexLength);
}
}
};
using CollisionBoxVertex = CollisionBoxProgram::LayoutVertex;
} // namespace mbgl
| 36.722222 | 135 | 0.602256 | dataliz9r |
9876f4e5980aff5a0bebcc1f60e67739ee3c06d5 | 4,308 | cpp | C++ | src/upcore/src/filesystem/posix/operations/absolute_path.cpp | upcaste/upcaste | 8174a2f40e7fde022806f8d1565bb4a415ecb210 | [
"MIT"
] | 1 | 2018-09-17T20:50:14.000Z | 2018-09-17T20:50:14.000Z | src/upcore/src/filesystem/posix/operations/absolute_path.cpp | jwtowner/upcaste | 8174a2f40e7fde022806f8d1565bb4a415ecb210 | [
"MIT"
] | null | null | null | src/upcore/src/filesystem/posix/operations/absolute_path.cpp | jwtowner/upcaste | 8174a2f40e7fde022806f8d1565bb4a415ecb210 | [
"MIT"
] | null | null | null | //
// Upcaste Performance Libraries
// Copyright (C) 2012-2013 Jesse W. Towner
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#include "../filesystem_internal.hpp"
namespace up { namespace filesystem
{
LIBUPCOREAPI
ssize_t absolute_path(char* d, size_t dsz, char const* p, char const* base) noexcept {
char* buffer, * res;
size_t n, buffer_length, buffer_max;
ssize_t retval;
// validate arguments
if ((!d && dsz) || (dsz > (SSIZE_MAX + 1)) || !p) {
errno = EINVAL;
return -1;
}
n = strlen(p);
if (n > SSIZE_MAX) {
errno = EOVERFLOW;
return -1;
}
// if the path is already absolute, just normalize it into the destination buffer
if (*p == '/') {
return normalize_path(d, dsz, p, n);
}
if (!base) {
// copy current directory path into temporary buffer
buffer_max = PATH_MAX + n + 2;
buffer = static_cast<char*>(malloca(buffer_max));
if (!buffer) {
return -1;
}
res = ::getcwd(buffer, PATH_MAX + 1);
if (res != buffer) {
freea(buffer);
return -1;
}
buffer_length = strlen(buffer);
}
else {
// get the absolute path of base and place it into temporary buffer
buffer_max = PATH_MAX + strlen(base) + n + 2;
buffer = static_cast<char*>(malloca(buffer_max));
if (!buffer) {
return -1;
}
retval = absolute_path(buffer, buffer_max, base, nullptr);
if (retval < 0) {
freea(buffer);
return -1;
}
buffer_length = static_cast<size_t>(retval);
}
// join the base path in the buffer with the input path
assert(buffer_length > 0);
if (buffer[buffer_length - 1] != '/') {
buffer[buffer_length] = '/';
++buffer_length;
}
assert((buffer_length + n) < buffer_max);
memcpy(buffer + buffer_length, p, n + 1);
buffer_length += n;
// normalize the joined path to get final result
retval = normalize_path(d, dsz, buffer, buffer_length);
freea(buffer);
return retval;
}
LIBUPCOREAPI UPALLOC UPWARNRESULT
char* absolute_path(char const* p, char const* base) noexcept {
size_t length;
ssize_t slength;
char* retval;
char default_buffer[1024];
slength = absolute_path(default_buffer, sizeof(default_buffer), p, base);
if (slength < 0) {
return nullptr;
}
length = static_cast<size_t>(slength);
if (length < sizeof(default_buffer)) {
return strndup(default_buffer, length);
}
retval = static_cast<char*>(malloc(length + 1));
if (!retval) {
return nullptr;
}
verify(slength == absolute_path(retval, length + 1, p, base));
return retval;
}
}}
| 33.65625 | 91 | 0.56337 | upcaste |
98789b66ae6a178e290078f46be683d59a2e13f4 | 7,297 | cpp | C++ | src/ros_comm/roscpp/src/libros/connection_manager.cpp | jungleni/ros_code_reading | 499e98c0b0d309da78060b19b55c420c22110d65 | [
"Apache-2.0"
] | null | null | null | src/ros_comm/roscpp/src/libros/connection_manager.cpp | jungleni/ros_code_reading | 499e98c0b0d309da78060b19b55c420c22110d65 | [
"Apache-2.0"
] | null | null | null | src/ros_comm/roscpp/src/libros/connection_manager.cpp | jungleni/ros_code_reading | 499e98c0b0d309da78060b19b55c420c22110d65 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2009, Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/connection_manager.h"
#include "ros/poll_manager.h"
#include "ros/connection.h"
#include "ros/transport_subscriber_link.h"
#include "ros/service_client_link.h"
#include "ros/transport/transport_tcp.h"
#include "ros/transport/transport_udp.h"
#include "ros/file_log.h"
#include "ros/network.h"
#include <ros/assert.h>
namespace ros
{
ConnectionManagerPtr g_connection_manager;
boost::mutex g_connection_manager_mutex;
const ConnectionManagerPtr& ConnectionManager::instance()
{
if (!g_connection_manager)
{
boost::mutex::scoped_lock lock(g_connection_manager_mutex);
if (!g_connection_manager)
{
g_connection_manager = boost::make_shared<ConnectionManager>();
}
}
return g_connection_manager;
}
ConnectionManager::ConnectionManager()
: connection_id_counter_(0)
{
}
ConnectionManager::~ConnectionManager()
{
shutdown();
}
void ConnectionManager::start()
{
poll_manager_ = PollManager::instance();
poll_conn_ = poll_manager_->addPollThreadListener(boost::bind(&ConnectionManager::removeDroppedConnections,
this));
// Bring up the TCP listener socket
tcpserver_transport_ = boost::make_shared<TransportTCP>(&poll_manager_->getPollSet());
if (!tcpserver_transport_->listen(network::getTCPROSPort(),
MAX_TCPROS_CONN_QUEUE,
boost::bind(&ConnectionManager::tcprosAcceptConnection, this, _1)))
{
ROS_FATAL("Listen on port [%d] failed", network::getTCPROSPort());
ROS_BREAK();
}
// Bring up the UDP listener socket
udpserver_transport_ = boost::make_shared<TransportUDP>(&poll_manager_->getPollSet());
if (!udpserver_transport_->createIncoming(0, true))
{
ROS_FATAL("Listen failed");
ROS_BREAK();
}
}
void ConnectionManager::shutdown()
{
if (udpserver_transport_)
{
udpserver_transport_->close();
udpserver_transport_.reset();
}
if (tcpserver_transport_)
{
tcpserver_transport_->close();
tcpserver_transport_.reset();
}
poll_manager_->removePollThreadListener(poll_conn_);
clear(Connection::Destructing);
}
void ConnectionManager::clear(Connection::DropReason reason)
{
S_Connection local_connections;
{
boost::mutex::scoped_lock conn_lock(connections_mutex_);
local_connections.swap(connections_);
}
for(S_Connection::iterator itr = local_connections.begin();
itr != local_connections.end();
itr++)
{
const ConnectionPtr& conn = *itr;
conn->drop(reason);
}
boost::mutex::scoped_lock dropped_lock(dropped_connections_mutex_);
dropped_connections_.clear();
}
uint32_t ConnectionManager::getTCPPort()
{
return tcpserver_transport_->getServerPort();
}
uint32_t ConnectionManager::getUDPPort()
{
return udpserver_transport_->getServerPort();
}
uint32_t ConnectionManager::getNewConnectionID()
{
boost::mutex::scoped_lock lock(connection_id_counter_mutex_);
uint32_t ret = connection_id_counter_++;
return ret;
}
void ConnectionManager::addConnection(const ConnectionPtr& conn)
{
boost::mutex::scoped_lock lock(connections_mutex_);
connections_.insert(conn);
conn->addDropListener(boost::bind(&ConnectionManager::onConnectionDropped, this, _1));
}
void ConnectionManager::onConnectionDropped(const ConnectionPtr& conn)
{
boost::mutex::scoped_lock lock(dropped_connections_mutex_);
dropped_connections_.push_back(conn);
}
void ConnectionManager::removeDroppedConnections()
{
V_Connection local_dropped;
{
boost::mutex::scoped_lock dropped_lock(dropped_connections_mutex_);
dropped_connections_.swap(local_dropped);
}
boost::mutex::scoped_lock conn_lock(connections_mutex_);
V_Connection::iterator conn_it = local_dropped.begin();
V_Connection::iterator conn_end = local_dropped.end();
for (;conn_it != conn_end; ++conn_it)
{
const ConnectionPtr& conn = *conn_it;
connections_.erase(conn);
}
}
void ConnectionManager::udprosIncomingConnection(const TransportUDPPtr& transport, Header& header)
{
std::string client_uri = ""; // TODO: transport->getClientURI();
ROSCPP_LOG_DEBUG("UDPROS received a connection from [%s]", client_uri.c_str());
ConnectionPtr conn(boost::make_shared<Connection>());
addConnection(conn);
conn->initialize(transport, true, NULL);
onConnectionHeaderReceived(conn, header);
}
void ConnectionManager::tcprosAcceptConnection(const TransportTCPPtr& transport)
{
std::string client_uri = transport->getClientURI();
ROSCPP_LOG_DEBUG("TCPROS received a connection from [%s]", client_uri.c_str());
ConnectionPtr conn(boost::make_shared<Connection>());
addConnection(conn);
conn->initialize(transport, true, boost::bind(&ConnectionManager::onConnectionHeaderReceived, this, _1, _2));
}
bool ConnectionManager::onConnectionHeaderReceived(const ConnectionPtr& conn, const Header& header)
{
bool ret = false;
std::string val;
if (header.getValue("topic", val))
{
ROSCPP_CONN_LOG_DEBUG("Connection: Creating TransportSubscriberLink for topic [%s] connected to [%s]",
val.c_str(), conn->getRemoteString().c_str());
TransportSubscriberLinkPtr sub_link(boost::make_shared<TransportSubscriberLink>());
sub_link->initialize(conn);
ret = sub_link->handleHeader(header);
}
else if (header.getValue("service", val))
{
ROSCPP_LOG_DEBUG("Connection: Creating ServiceClientLink for service [%s] connected to [%s]",
val.c_str(), conn->getRemoteString().c_str());
ServiceClientLinkPtr link(boost::make_shared<ServiceClientLink>());
link->initialize(conn);
ret = link->handleHeader(header);
}
else
{
ROSCPP_LOG_DEBUG("Got a connection for a type other than 'topic' or 'service' from [%s]. Fail.",
conn->getRemoteString().c_str());
return false;
}
return ret;
}
}
| 30.531381 | 111 | 0.745101 | jungleni |
9879d1ceabdae9df2980d94faf0ea7b7c8de3627 | 16,892 | hpp | C++ | src/ui/managers/WindowManager.hpp | inexorgame/entity-system | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 19 | 2018-10-11T09:19:48.000Z | 2020-04-19T16:36:58.000Z | src/ui/managers/WindowManager.hpp | inexorgame-obsolete/entity-system-inactive | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 132 | 2018-07-28T12:30:54.000Z | 2020-04-25T23:05:33.000Z | src/ui/managers/WindowManager.hpp | inexorgame-obsolete/entity-system-inactive | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 3 | 2019-03-02T16:19:23.000Z | 2020-02-18T05:15:29.000Z | #pragma once
#include "base/LifeCycleComponent.hpp"
#include "MonitorManager.hpp"
#include "client/ClientLifecycle.hpp"
#include "entity-system/managers/entities/entity-instance-manager/EntityInstanceManager.hpp"
#include "entity-system/model/data/DataTypes.hpp"
#include "input/managers/KeyboardInputManager.hpp"
#include "input/managers/MouseInputManager.hpp"
#include "logging/managers/LogManager.hpp"
#include "renderer/managers/UserInterfaceRenderer.hpp"
#include "renderer/managers/WorldRenderer.hpp"
#include "ui/factories/WindowFactory.hpp"
#include "ui/model/ManagedWindow.hpp"
#include "visual-scripting/managers/ConnectorManager.hpp"
#include "visual-scripting/model/Connector.hpp"
#include <Magnum/Math/Range.h>
#include <Magnum/Timeline.h>
#include <functional>
#include <list>
struct GLFWwindow;
struct GLFWmonitor;
namespace inexor::ui {
using WindowFactoryPtr = std::shared_ptr<WindowFactory>;
using MonitorManagerPtr = std::shared_ptr<MonitorManager>;
using KeyboardInputManagerPtr = std::shared_ptr<input::KeyboardInputManager>;
using MouseInputManagerPtr = std::shared_ptr<input::MouseInputManager>;
using EntityInstanceManagerPtr = std::shared_ptr<entity_system::EntityInstanceManager>;
using ConnectorManagerPtr = std::shared_ptr<visual_scripting::ConnectorManager>;
using WorldRendererPtr = std::shared_ptr<renderer::WorldRenderer>;
using UserInterfaceRendererPtr = std::shared_ptr<renderer::UserInterfaceRenderer>;
using ClientLifecyclePtr = std::shared_ptr<client::ClientLifecycle>;
using LogManagerPtr = std::shared_ptr<logging::LogManager>;
using EntityInstancePtr = std::shared_ptr<entity_system::EntityInstance>;
using EntityAttributeInstancePtr = std::shared_ptr<entity_system::EntityAttributeInstance>;
using Range2Di = Magnum::Math::Range2D<std::int32_t>;
/// @class WindowManager
/// @brief The WindowManager manages the windows of the application.
class WindowManager : public LifeCycleComponent, public std::enable_shared_from_this<WindowManager>
{
public:
/// @brief Constructor.
/// @note The dependencies of this class will be injected automatically.
/// @param window_factory Factory for creating instances of type 'WINDOW'.
/// @param keyboard_input_manager The keyboard input manager.
/// @param mouse_input_manager The mouse input manager.
/// @param entity_instance_manager The entity instance manager.
/// @param connector_manager The connector manager.
/// @param world_renderer Service, which renders the world on a window.
/// @param user_interface_renderer Service, which renders the user interface on a window.
/// @param log_manager The log manager.
WindowManager(WindowFactoryPtr window_factory, MonitorManagerPtr monitor_manager, KeyboardInputManagerPtr keyboard_input_manager, MouseInputManagerPtr mouse_input_manager, EntityInstanceManagerPtr entity_instance_manager,
ConnectorManagerPtr connector_manager, WorldRendererPtr world_renderer, UserInterfaceRendererPtr user_interface_renderer, ClientLifecyclePtr client_lifecycle, LogManagerPtr log_manager);
/// Destructor.
~WindowManager();
/// Initialize the window manager.
void init() override;
/// Shut down the window manager.
void destroy() override;
/// Returns the name of the component
std::string get_component_name() override;
/// @brief Creates a new window with the given title, position and dimensions.
/// @param window The GLFWwindow instance.
EntityInstancePtr create_window(const std::string& title, int x, int y, int width, int height);
/// @brief Creates a new window with the given title, position and dimensions.
/// @param window The GLFWwindow instance.
EntityInstancePtr create_window(const std::string& title, int x, int y, int width, int height, float opacity, bool visible, bool fullscreen, bool iconified, bool maximized, bool focused, bool vsync, float fps);
/// @brief Creates a new window with the given title, position and dimensions.
/// @param window The GLFWwindow instance.
EntityInstancePtr create_window(const std::string& title, int x, int y, int width, int height, float opacity, bool visible, bool fullscreen, bool iconified, bool maximized, bool focused, bool vsync, float fps,
std::optional<std::function<void(EntityInstancePtr, GLFWwindow *)>> init_function, std::optional<std::function<void(EntityInstancePtr, GLFWwindow *)>> shutdown_function);
/// @brief Destroys the given window.
/// @param window The entity instance of type WINDOW.
void destroy_window(const EntityInstancePtr& window);
/// @brief Destroys the given window.
/// @param window The entity instance of type WINDOW.
void close_window(const EntityInstancePtr& window);
/// @brief Sets the title of the given window.
/// @param window The entity instance of type WINDOW.
/// @param title The new title of the window.
void set_window_title(const EntityInstancePtr& window, std::string title);
/// @brief Sets the position of the given window.
/// @param window The entity instance of type WINDOW.
/// @param x The new x position of the window.
/// @param y The new y position of the window.
void set_window_position(const EntityInstancePtr& window, int x, int y);
/// @brief Sets the size of the given window.
/// @param window The entity instance of type WINDOW.
/// @param width The new width of the window.
/// @param height The new height of the window.
void set_window_size(const EntityInstancePtr& window, int width, int height);
/// @brief Returns the dimensions of the given window.
/// @param window The entity instance of type WINDOW.
Range2Di get_window_dimensions(const EntityInstancePtr& window);
/// @brief Centers the given window on the monitor which contains the window center.
/// @param window The entity instance of type WINDOW.
void center_window_on_current_monitor(const EntityInstancePtr& window);
/// @brief Centers the given window on the primary monitor.
/// @param window The entity instance of type WINDOW.
void center_window_on_primary_monitor(const EntityInstancePtr& window);
/// @brief Centers the given window on the next left monitor.
/// @param window The entity instance of type WINDOW.
void center_window_on_next_left_monitor(const EntityInstancePtr& window);
/// @brief Centers the given window on the next right monitor.
/// @param window The entity instance of type WINDOW.
void center_window_on_next_right_monitor(const EntityInstancePtr& window);
/// @brief Centers the given window to the given monitor.
/// @param window The entity instance of type 'WINDOW'.
/// @param monitor The entity instance of type 'MONITOR'.
void center_window_on_monitor(const EntityInstancePtr& window, const EntityInstancePtr& monitor);
/// @brief Returns true, if the given window is centered on the monitor which contains the window center.
/// @param window The entity instance of type WINDOW.
/// @return True, if the window is centered.
bool is_window_centered(const EntityInstancePtr& window);
/// @brief Returns true, if the given window is centered on the given monitor.
/// @param window The entity instance of type WINDOW.
/// @param monitor The entity instance of type 'MONITOR'.
/// @return True, if the given window is centered on the given monitor.
bool is_window_centered_on_monitor(EntityInstancePtr window, EntityInstancePtr monitor);
/// @brief Makes the given window fullscreen on the monitor which contains the window center.
/// @param window The entity instance of type WINDOW.
void fullscreen_window_on_current_monitor(const EntityInstancePtr& window);
/// @brief Makes the given window fullscreen on the primary monitor.
/// @param window The entity instance of type WINDOW.
void fullscreen_window_on_primary_monitor(const EntityInstancePtr& window);
/// @brief Makes the given window fullscreen on the next left monitor.
/// @param window The entity instance of type WINDOW.
void fullscreen_window_on_next_left_monitor(const EntityInstancePtr& window);
/// @brief Makes the given window fullscreen on the next right monitor.
/// @param window The entity instance of type WINDOW.
void fullscreen_window_on_next_right_monitor(const EntityInstancePtr& window);
/// @brief Makes the given window fullscreen on the given monitor.
/// @param window The entity instance of type 'WINDOW'.
/// @param monitor The entity instance of type 'MONITOR'.
void fullscreen_window_on_monitor(const EntityInstancePtr& window, const EntityInstancePtr& monitor);
/// @brief Returns the monitor which contains the given window.
/// @param window The entity instance of type 'WINDOW'.
std::optional<EntityInstancePtr> get_current_monitor(const EntityInstancePtr& window);
// TODO: document
void make_current(const EntityInstancePtr& window);
/// @brief Registers a function to be called at every frame.
/// @param window The entity instance of type WINDOW.
/// @param render_function The render function to register.
void register_render_function(const EntityInstancePtr& window, std::function<void(EntityInstancePtr, GLFWwindow *, Magnum::Timeline)> render_function);
/// @brief Returns the number of windows.
int get_window_count();
/// @brief Returns the window handle for the entity instance.
/// @param window The entity instance of type 'WINDOW'.
GLFWwindow *get_window_handle(const EntityInstancePtr& window);
/// The logger name of this service.
static constexpr char LOGGER_NAME[] = "inexor.renderer.window";
private:
// State management
/// @brief Starts the window thread.
/// @param window The entity instance of type WINDOW.
void start_window_thread(const EntityInstancePtr& window);
/// @brief Stops the window thread.
/// @param window The entity instance of type 'WINDOW'.
void stop_window_thread(EntityInstancePtr window);
/// @brief Returns true, if the given entity instance of type WINDOW is managed.
/// @param window The entity instance of type 'WINDOW'.
bool is_window_managed(const EntityInstancePtr& window);
/// @brief Returns true, if the given entity instance of type WINDOW is available.
/// @param window The entity instance of type 'WINDOW'.
bool is_window_available(const EntityInstancePtr& window);
/// @brief Returns true, if the thread is managed for the given entity instance of type 'WINDOW'.
/// @param window The entity instance of type 'WINDOW'.
bool is_thread_managed(EntityInstancePtr window);
/// @brief Returns true, if the thread is running for the given entity instance of type 'WINDOW'.
/// @param window The entity instance of type 'WINDOW'.
bool is_thread_running(const EntityInstancePtr& window);
// Internal window API
/// @brief Sets the position of the given window.
/// @param glfw_window The glfw window.
/// @param x The new x position of the window.
/// @param y The new y position of the window.
void set_window_position(GLFWwindow *glfw_window, int x, int y);
/// @brief Sets the size of the given window.
/// @param glfw_window The glfw window.
/// @param width The new width of the window.
/// @param height The new height of the window.
void set_window_size(GLFWwindow *glfw_window, int width, int height);
/// @brief Returns the dimensions of the given window.
/// @param glfw_window The glfw window.
Range2Di get_window_dimensions(GLFWwindow *glfw_window);
// Window initialization
/// @brief Initializes the callbacks on window state changes.
/// @param glfw_window The window handle.
void initialize_window_callbacks(GLFWwindow *glfw_window);
/// @brief Removes the callbacks on window state changes.
/// @param glfw_window The window handle.
void destroy_window_callbacks(GLFWwindow *glfw_window);
/// @brief Initializes observers on the attributes of the entity instance of type WINDOW.
/// @param window The entity instance of type 'WINDOW'.
void initialize_window_observers(const EntityInstancePtr& window, GLFWwindow *glfw_window);
// Event handling
/// This callback is called if a window has been closed.
/// @param glfw_window The window handle.
void window_closed(GLFWwindow *glfw_window);
/// This callback is called if a window has been focused / has lost the focus.
/// @param glfw_window The window handle.
void window_focused(GLFWwindow *glfw_window, bool has_focus);
/// This callback is called if a window has been iconified / restored.
/// @param glfw_window The window handle.
void window_iconified(GLFWwindow *glfw_window, bool is_iconified);
/// This callback is called if a window has been maximized / restored.
/// @param glfw_window The window handle.
void window_maximized(GLFWwindow *glfw_window, bool is_maximized);
/// This callback is called if the position of a window has been changed.
/// @param glfw_window The window handle.
void window_position_changed(GLFWwindow *glfw_window, int x, int y);
/// This callback is called if the size of a window has been changed.
/// @param glfw_window The window handle.
void window_size_changed(GLFWwindow *glfw_window, int width, int height);
/// This callback is called if the state of a key has been changed.
/// @param glfw_window The window handle.
void window_key_changed(GLFWwindow *glfw_window, int key, int scancode, int action, int mods);
/// This callback is called if a character is input.
/// The character callback is intended for Unicode text input. As
/// it deals with characters, it is keyboard layout dependent,
/// whereas the key callback is not. Characters do not map 1:1 to
/// physical keys, as a key may produce zero, one or more
/// characters. If you want to know whether a specific physical
/// key was pressed or released, see the key callback instead.
///
/// The character callback behaves as system text input normally
/// does and will not be called if modifier keys are held down
/// that would prevent normal text input on that platform, for
/// example a Super (Command) key on macOS or Alt key on Windows.
/// @param glfw_window The window handle.
void window_char_input(GLFWwindow *glfw_window, unsigned int codepoint);
/// This callback is called if the mouse position of a window has been changed.
/// @param glfw_window The window handle.
void window_mouse_position_changed(GLFWwindow *glfw_window, double xpos, double ypos);
/// This callback is called if the state of a mouse button has been changed.
/// @param glfw_window The window handle.
void window_mouse_button_changed(GLFWwindow *glfw_window, int button, int action, int mods);
/// This callback is called if the state of a mouse scroll wheel has been changed.
/// @param glfw_window The window handle.
void window_mouse_scroll_changed(GLFWwindow *glfw_window, double xoffset, double yoffset);
/// This callback is called if files are dropped on the window.
/// @param glfw_window The window handle.
void window_path_dropped(GLFWwindow *glfw_window, int count, const char **_paths);
// Services
/// The factory for creating entities of type WINDOW.
WindowFactoryPtr window_factory;
/// The monitor manager.
MonitorManagerPtr monitor_manager;
/// The keyboard input manager.
KeyboardInputManagerPtr keyboard_input_manager;
/// The mouse input manager.
MouseInputManagerPtr mouse_input_manager;
/// The entity instance manager.
EntityInstanceManagerPtr entity_instance_manager;
/// The connector manager.
ConnectorManagerPtr connector_manager;
/// The world renderer.
WorldRendererPtr world_renderer;
/// The user interface renderer.
UserInterfaceRendererPtr user_interface_renderer;
/// The client lifecycle.
ClientLifecyclePtr client_lifecycle;
/// The log manager.
LogManagerPtr log_manager;
// Managed windows and states
/// The mapping between the entity instance and the pointer to the
/// corresponding ManagedWindow.
/// @see ManagedWindow
std::unordered_map<EntityInstancePtr, std::shared_ptr<ManagedWindow>> windows;
/// The mapping between the pointer to the window and the
/// corresponding entity instance.
std::unordered_map<GLFWwindow *, EntityInstancePtr> window_entities;
/// The number of windows managed by the WindowManager.
int window_count;
/// The current window id.
int current_window_id;
};
} // namespace inexor::renderer
| 46.534435 | 225 | 0.738278 | inexorgame |
987d56fd802a7cf2ca78ad87a3d2a866543abc28 | 3,581 | hpp | C++ | src/v2/internal_aparse_grammar.hpp | mohitmv/aparse | 34a6811f9a3d4f1c5dd21ed874b14e59e6725746 | [
"MIT"
] | 2 | 2021-04-15T20:02:37.000Z | 2021-04-17T18:18:50.000Z | src/v2/internal_aparse_grammar.hpp | mohitmv/aparse | 34a6811f9a3d4f1c5dd21ed874b14e59e6725746 | [
"MIT"
] | 1 | 2019-10-07T10:41:52.000Z | 2019-10-07T10:41:52.000Z | src/v2/internal_aparse_grammar.hpp | mohitmv/aparse | 34a6811f9a3d4f1c5dd21ed874b14e59e6725746 | [
"MIT"
] | 1 | 2020-05-05T16:52:20.000Z | 2020-05-05T16:52:20.000Z | // Copyright: 2015 Mohit Saini
// Author: Mohit Saini (mohitsaini1196@gmail.com)
#ifndef APARSE_SRC_V2_INTERNAL_APARSE_GRAMMAR_HPP_
#define APARSE_SRC_V2_INTERNAL_APARSE_GRAMMAR_HPP_
#include <utility>
#include <list>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include "quick/unordered_map.hpp"
#include "quick/debug_stream_decl.hpp"
#include "aparse/common_headers.hpp"
#include "aparse/aparse_grammar.hpp"
namespace aparse {
namespace v2 {
/** InternalAParseGrammar' is a preprocessed version of AparseGrammar. We offer
* a lot of flexibility in AParseGrammar to make it easy to design. However
* these flexibilities can be reduced to non-flexible version of AParseGrammar
* by doing some preprocessing.
* Eg:
* 1). We allow a single non-terminal to be defined in multiple rules. After
* preprocessing step, these non-terminals are combibed into single rule by
* joining the corrosponding expressions with UNION operator.
* 2). In addition to that we attach a label (a unique-id (integer)) on the
* rule-regex so that later we can identify the grammar-rule a regex
* corrosponds to.
* 3). Constructs the enclosed-non-terminals by extraing out the
* sub-expressions wrapped in branching alphabets.
*
* Usage: InternalAParseGrammar igrammar; igrammar.Build(...); */
class InternalAParseGrammar {
public:
InternalAParseGrammar() {}
// Not idempotent.
void Init(const AParseGrammar& grammar);
void DebugStream(qk::DebugStream&) const;
////////////////////// Helpers Functions For Alphabets ////////////////////
//
// Both `IsBAStart` and `IsBAEnd` assumes that `ba_map` and `ba_inverse_map`
// is populated before calling them. Avoiding necessary fatal-assertions here.
//
// Checks if a given regex is a atomic regex and it's alphabet is
// start-branching-alphabet.
bool IsBAStart(const Regex& r) const;
// Checks if a given regex is a atomic regex and it's alphabet is
// end-branching-alphabet.
bool IsBAEnd(const Regex& r) const;
// Checks if a given regex is a atomic regex and it's alphabet is
// end-branching-alphabet and also it's closing end of @start_ba.
bool IsBAEnd(const Regex& r, Alphabet start_ba) const;
//
/////////////////// ----x----x----x----x---- ///////////////////////////////
protected:
// @id_counter: enclosed_non_terminal_id_counter
void ConstructEnclosedNonTerminals(
std::vector<std::pair<int, Regex>>* rules_list,
int* id_counter);
// Regex main_regex;
// Mapping from enclosed-non-terminals to corrosponding Regex.
// std::unordered_map<EnclosedsAlphabet, SubRegex> sub_regex_map;
public:
int alphabet_size;
int main_non_terminal;
std::unordered_map<int, Regex> rules;
// map(enclosed_non_terminal -> (branch_start_alphabet, regex))
std::unordered_map<int, Regex> enclosed_rules;
std::unordered_map<int, Alphabet> enclosed_ba_alphabet;
std::unordered_map<int, int> regex_label_to_original_rule_number_mapping;
// branching-alphabets-map.
std::unordered_map<int, int> ba_map;
// map(value -> key) of `ba_map`.
std::unordered_map<int, int> ba_inverse_map;
// Map(every non-terminal -> list of other non-terminals it's dependent on)
std::unordered_map<int, std::unordered_set<int>> dependency_graph;
std::vector<int> topological_sorted_non_terminals;
std::unordered_set<int> non_terminals;
std::unordered_set<int> enclosed_non_terminals;
};
} // namespace v2
} // namespace aparse
#endif // APARSE_SRC_V2_INTERNAL_APARSE_GRAMMAR_HPP_
| 36.540816 | 80 | 0.724099 | mohitmv |
987dfb4f2323f5c3ee5b7dd51aa36020d7af0c57 | 6,008 | cpp | C++ | mp/src/game/client/fortress/resourcezoneoverlay.cpp | MaartenS11/Team-Fortress-Invasion | f36b96d27f834d94e0db2d2a9470b05b42e9b460 | [
"Unlicense"
] | 1 | 2021-03-20T14:27:45.000Z | 2021-03-20T14:27:45.000Z | mp/src/game/client/fortress/resourcezoneoverlay.cpp | MaartenS11/Team-Fortress-Invasion | f36b96d27f834d94e0db2d2a9470b05b42e9b460 | [
"Unlicense"
] | null | null | null | mp/src/game/client/fortress/resourcezoneoverlay.cpp | MaartenS11/Team-Fortress-Invasion | f36b96d27f834d94e0db2d2a9470b05b42e9b460 | [
"Unlicense"
] | null | null | null | #include "cbase.h"
#include <VGUI_EntityPanel.h>
#include <KeyValues.h>
#include "commanderoverlay.h"
#include "clientmode_tfnormal.h"
#include "tf_shareddefs.h"
#include "shareddefs.h"
#include "c_func_resource.h"
#include "techtree.h"
#include "c_basetfplayer.h"
#include "vgui_HealthBar.h"
#include "vgui_BitmapImage.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
class CResourceZoneOverlay : public CEntityPanel
{
DECLARE_CLASS( CResourceZoneOverlay, CEntityPanel );
public:
CResourceZoneOverlay( vgui::Panel *parent, const char *panelName );
virtual ~CResourceZoneOverlay( void );
bool Init( KeyValues* pKeyValues, C_BaseEntity* pEntity );
bool InitResourceBitmaps( KeyValues* pKeyValues );
void SetColor( int r, int g, int b, int a );
void SetImage( BitmapImage *pImage );
virtual void OnTick();
virtual void Paint( void );
virtual void PaintBackground( void ) {}
private:
class CResourceBitmaps
{
public:
CResourceBitmaps() : m_pImage(0) {}
BitmapImage *m_pImage;
Color m_Color;
};
struct Rect_t
{
int x, y, w, h;
};
bool ParseSingleResourceBitmap( KeyValues *pKeyValues,
const char *pResourceName, CResourceBitmaps *pResourceBitmap );
bool ParseTeamResourceBitmaps( CResourceBitmaps *pT, KeyValues *pTeam );
int m_r, m_g, m_b, m_a;
CHealthBarPanel m_UsageBar;
Rect_t m_Icon;
C_ResourceZone *m_pResourceZone;
CResourceBitmaps m_pResourceBitmap;
BitmapImage *m_pImage;
};
//-----------------------------------------------------------------------------
// Class factory
//-----------------------------------------------------------------------------
DECLARE_OVERLAY_FACTORY( CResourceZoneOverlay, "resourcezone" );
CResourceZoneOverlay::CResourceZoneOverlay( vgui::Panel *parent, const char *panelName )
: BaseClass( parent, "CResourceZoneOverlay" )
{
m_pImage = 0;
SetPaintBackgroundEnabled( false );
}
CResourceZoneOverlay::~CResourceZoneOverlay( void )
{
if ( m_pResourceBitmap.m_pImage )
{
delete m_pResourceBitmap.m_pImage;
}
}
//-----------------------------------------------------------------------------
// Parse class icons
//-----------------------------------------------------------------------------
bool CResourceZoneOverlay::ParseSingleResourceBitmap( KeyValues *pKeyValues,
const char *pResourceName, CResourceBitmaps *pResourceBitmap )
{
const char *image;
KeyValues *pResource;
pResource = pKeyValues->FindKey( pResourceName );
if ( !pResource )
return false;
image = pResource->GetString( "material" );
if ( image && image[ 0 ] )
{
pResourceBitmap->m_pImage = new BitmapImage( GetVPanel(), image );
}
else
{
return( false );
}
return ParseRGBA( pResource, "color", pResourceBitmap->m_Color );
}
bool CResourceZoneOverlay::ParseTeamResourceBitmaps( CResourceBitmaps *pT, KeyValues *pTeam )
{
if ( !ParseSingleResourceBitmap( pTeam, "Alpha", pT ) )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Initialization
//-----------------------------------------------------------------------------
bool CResourceZoneOverlay::InitResourceBitmaps( KeyValues* pKeyValues )
{
// char teamkey[ 128 ];
// for (int i = 0; i < 3; ++i)
// {
// sprintf( teamkey, "Team%i", i );
// KeyValues *pTeam = pKeyValues->getSection( teamkey );
// if (pTeam)
{
if (!ParseTeamResourceBitmaps( &m_pResourceBitmap, pKeyValues ))
return false;
}
// }
return true;
}
//-----------------------------------------------------------------------------
// Initialization
//-----------------------------------------------------------------------------
bool CResourceZoneOverlay::Init( KeyValues* pKeyValues, C_BaseEntity* pEntity )
{
if (!BaseClass::Init( pKeyValues, pEntity))
return false;
if (!pKeyValues)
return false;
// We gotta be attached to a resource zone
m_pResourceZone = dynamic_cast<C_ResourceZone*>(GetEntity());
if (!m_pResourceZone)
return false;
KeyValues* pUsage = pKeyValues->FindKey("Usage");
if (!m_UsageBar.Init( pUsage ))
return false;
m_UsageBar.SetParent( this );
// get the icon info...
if (!ParseRect( pKeyValues, "iconposition", m_Icon.x, m_Icon.y, m_Icon.w, m_Icon.h ))
return false;
if (!InitResourceBitmaps( pKeyValues ))
return false;
SetImage( 0 );
SetColor( m_pResourceBitmap.m_Color[0], m_pResourceBitmap.m_Color[1], m_pResourceBitmap.m_Color[2], m_pResourceBitmap.m_Color[3] );
// we need updating
return true;
}
//-----------------------------------------------------------------------------
// called when we're ticked...
//-----------------------------------------------------------------------------
void CResourceZoneOverlay::OnTick()
{
// Update position
CEntityPanel::OnTick();
SetImage( m_pResourceBitmap.m_pImage );
int r, g, b, a;
m_pResourceBitmap.m_Color.GetColor( r, g, b, a );
SetColor( r, g, b, a );
m_UsageBar.SetHealth( m_pResourceZone->m_flClientResources );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pImage - Class specific image
//-----------------------------------------------------------------------------
void CResourceZoneOverlay::SetImage( BitmapImage *pImage )
{
m_pImage = pImage;
}
//-----------------------------------------------------------------------------
// Sets the draw color
//-----------------------------------------------------------------------------
void CResourceZoneOverlay::SetColor( int r, int g, int b, int a )
{
m_r = r;
m_g = g;
m_b = b;
m_a = a;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CResourceZoneOverlay::Paint( void )
{
if ( !m_pImage )
return;
ComputeAndSetSize();
Color color;
color.SetColor( m_r, m_g, m_b, m_a );
m_pImage->SetPos( m_Icon.x, m_Icon.y );
m_pImage->SetColor( color );
m_pImage->DoPaint( GetVPanel() );
} | 25.896552 | 132 | 0.565413 | MaartenS11 |
987e170d90dfc44b620e47d7fb76537248ef1ea0 | 14,697 | cpp | C++ | src/idatentest/main.cpp | nakdai/aten | f6de0840c1631bafbec3162da6a9af5767300e4d | [
"MIT"
] | 2 | 2017-09-29T02:36:45.000Z | 2017-11-16T03:25:25.000Z | src/idatentest/main.cpp | nakdai/aten | f6de0840c1631bafbec3162da6a9af5767300e4d | [
"MIT"
] | null | null | null | src/idatentest/main.cpp | nakdai/aten | f6de0840c1631bafbec3162da6a9af5767300e4d | [
"MIT"
] | null | null | null | #include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <imgui.h>
#include "aten.h"
#include "atenscene.h"
#include "idaten.h"
#include "../common/scenedefs.h"
#define ENABLE_ENVMAP
static int WIDTH = 1280;
static int HEIGHT = 720;
static const char* TITLE = "ReSTIR";
#ifdef ENABLE_OMP
static uint32_t g_threadnum = 8;
#else
static uint32_t g_threadnum = 1;
#endif
static aten::PinholeCamera g_camera;
static bool g_isCameraDirty = false;
static aten::AcceleratedScene<aten::GPUBvh> g_scene;
static aten::context g_ctxt;
static idaten::PathTracing g_tracer;
static aten::visualizer* g_visualizer;
static float g_avgcuda = 0.0f;
static float g_avgupdate = 0.0f;
static bool g_enableUpdate = false;
static aten::TAA g_taa;
static aten::FBO g_fbo;
static aten::RasterizeRenderer g_rasterizer;
static aten::RasterizeRenderer g_rasterizerAABB;
static bool g_willShowGUI = true;
static bool g_willTakeScreenShot = false;
static int g_cntScreenShot = 0;
static int g_maxSamples = 1;
static int g_maxBounce = 5;
static auto g_curMode = idaten::ReSTIRPathTracing::Mode::ReSTIR;
static auto g_curReSTIRMode = idaten::ReSTIRPathTracing::ReSTIRMode::ReSTIR;
static auto g_curAOVMode = idaten::ReSTIRPathTracing::AOVMode::WireFrame;
static auto g_enableProgressive = false;
static bool g_showAABB = false;
static float g_moveMultiply = 1.0f;
static bool g_enableFrameStep = false;
static bool g_frameStep = false;
static bool g_pickPixel = false;
void update()
{
static float y = 0.0f;
static float d = -0.1f;
auto obj = getMovableObj();
if (obj) {
auto t = obj->getTrans();
if (y >= -0.1f) {
d = -0.01f;
}
else if (y <= -1.5f) {
d = 0.01f;
}
y += d;
t.y += d;
obj->setTrans(t);
obj->update();
auto accel = g_scene.getAccel();
accel->update(g_ctxt);
{
std::vector<aten::GeomParameter> shapeparams;
std::vector<aten::PrimitiveParamter> primparams;
std::vector<aten::LightParameter> lightparams;
std::vector<aten::MaterialParameter> mtrlparms;
std::vector<aten::vertex> vtxparams;
aten::DataCollector::collect(
g_ctxt,
g_scene,
shapeparams,
primparams,
lightparams,
mtrlparms,
vtxparams);
const auto& nodes = g_scene.getAccel()->getNodes();
const auto& mtxs = g_scene.getAccel()->getMatrices();
g_tracer.updateBVH(
shapeparams,
nodes,
mtxs);
}
}
}
void onRun(aten::window* window)
{
if (g_enableFrameStep && !g_frameStep) {
return;
}
auto frame = g_tracer.frame();
g_frameStep = false;
float updateTime = 0.0f;
{
aten::timer timer;
timer.begin();
if (g_enableUpdate) {
update();
}
updateTime = timer.end();
g_avgupdate = g_avgupdate * (frame - 1) + updateTime;
g_avgupdate /= (float)frame;
}
if (g_isCameraDirty) {
g_camera.update();
auto camparam = g_camera.param();
camparam.znear = real(0.1);
camparam.zfar = real(10000.0);
g_tracer.updateCamera(camparam);
g_isCameraDirty = false;
g_visualizer->clear();
}
aten::GLProfiler::begin();
g_rasterizer.drawSceneForGBuffer(
g_tracer.frame(),
g_ctxt,
&g_scene,
&g_camera,
&g_fbo);
auto rasterizerTime = aten::GLProfiler::end();
aten::timer timer;
timer.begin();
g_tracer.render(
idaten::TileDomain(0, 0, WIDTH, HEIGHT),
g_maxSamples,
g_maxBounce);
auto cudaelapsed = timer.end();
g_avgcuda = g_avgcuda * (frame - 1) + cudaelapsed;
g_avgcuda /= (float)frame;
aten::GLProfiler::begin();
g_visualizer->render(false);
auto visualizerTime = aten::GLProfiler::end();
if (g_showAABB) {
g_rasterizerAABB.drawAABB(
&g_camera,
g_scene.getAccel());
}
if (g_willTakeScreenShot)
{
static char buffer[1024];
::sprintf(buffer, "sc_%d.png\0", g_cntScreenShot);
g_visualizer->takeScreenshot(buffer);
g_willTakeScreenShot = false;
g_cntScreenShot++;
AT_PRINTF("Take Screenshot[%s]\n", buffer);
}
if (g_willShowGUI)
{
ImGui::Text("[%d] %.3f ms/frame (%.1f FPS)", g_tracer.frame(), 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("cuda : %.3f ms (avg : %.3f ms)", cudaelapsed, g_avgcuda);
ImGui::Text("update : %.3f ms (avg : %.3f ms)", updateTime, g_avgupdate);
ImGui::Text("%.3f Mrays/sec", (WIDTH * HEIGHT * g_maxSamples) / real(1000 * 1000) * (real(1000) / cudaelapsed));
if (aten::GLProfiler::isEnabled()) {
ImGui::Text("GL : [rasterizer %.3f ms] [visualizer %.3f ms]", rasterizerTime, visualizerTime);
}
auto is_input_samples = ImGui::SliderInt("Samples", &g_maxSamples, 1, 100);
auto is_input_bounce = ImGui::SliderInt("Bounce", &g_maxBounce, 1, 10);
if (is_input_samples || is_input_bounce) {
g_tracer.reset();
}
#if 0
static const char* items[] = { "ReSTIR", "PT", "AOV" };
if (ImGui::Combo("mode", (int*)&g_curMode, items, AT_COUNTOF(items))) {
g_tracer.setMode(g_curMode);
}
if (g_curMode == idaten::ReSTIRPathTracing::Mode::ReSTIR) {
static const char* restir_items[] = { "ReSTIR", "SpatialReuse" };
if (ImGui::Combo("restir mode", (int*)&g_curReSTIRMode, restir_items, AT_COUNTOF(restir_items))) {
g_tracer.setReSTIRMode(g_curReSTIRMode);
}
}
if (g_curMode == idaten::ReSTIRPathTracing::Mode::AOVar) {
static const char* aovitems[] = { "Normal", "TexColor", "Depth", "Wire", "Barycentric", "Motion", "ObjId" };
if (ImGui::Combo("aov", (int*)&g_curAOVMode, aovitems, AT_COUNTOF(aovitems))) {
g_tracer.setAOVMode(g_curAOVMode);
}
}
#endif
if (ImGui::Checkbox("Progressive", &g_enableProgressive)) {
g_tracer.setEnableProgressive(g_enableProgressive);
}
#if 0
bool enableTAA = g_taa.isEnableTAA();
bool canShowTAADiff = g_taa.canShowTAADiff();
if (ImGui::Checkbox("Enable TAA", &enableTAA)) {
g_taa.enableTAA(enableTAA);
}
if (ImGui::Checkbox("Show TAA Diff", &canShowTAADiff)) {
g_taa.showTAADiff(canShowTAADiff);
}
#else
g_taa.enableTAA(false);
#endif
ImGui::Checkbox("Show AABB", &g_showAABB);
#if 0
bool canSSRTHitTest = g_tracer.canSSRTHitTest();
if (ImGui::Checkbox("Can SSRT Hit", &canSSRTHitTest)) {
g_tracer.setCanSSRTHitTest(canSSRTHitTest);
}
#endif
ImGui::SliderFloat("MoveMultiply", &g_moveMultiply, 1.0f, 100.0f);
auto cam = g_camera.param();
ImGui::Text("Pos %f/%f/%f", cam.origin.x, cam.origin.y, cam.origin.z);
ImGui::Text("At %f/%f/%f", cam.center.x, cam.center.y, cam.center.z);
}
}
void onClose()
{
}
bool g_isMouseLBtnDown = false;
bool g_isMouseRBtnDown = false;
int g_prevX = 0;
int g_prevY = 0;
void onMouseBtn(bool left, bool press, int x, int y)
{
g_isMouseLBtnDown = false;
g_isMouseRBtnDown = false;
if (press) {
g_prevX = x;
g_prevY = y;
g_isMouseLBtnDown = left;
g_isMouseRBtnDown = !left;
}
}
void onMouseMove(int x, int y)
{
if (g_isMouseLBtnDown) {
aten::CameraOperator::rotate(
g_camera,
WIDTH, HEIGHT,
g_prevX, g_prevY,
x, y);
g_isCameraDirty = true;
}
else if (g_isMouseRBtnDown) {
aten::CameraOperator::move(
g_camera,
g_prevX, g_prevY,
x, y,
real(0.001));
g_isCameraDirty = true;
}
g_prevX = x;
g_prevY = y;
}
void onMouseWheel(int delta)
{
aten::CameraOperator::dolly(g_camera, delta * real(0.1));
g_isCameraDirty = true;
}
void onKey(bool press, aten::Key key)
{
static const real offset_base = real(0.1);
if (press) {
if (key == aten::Key::Key_F1) {
g_willShowGUI = !g_willShowGUI;
return;
}
else if (key == aten::Key::Key_F2) {
g_willTakeScreenShot = true;
return;
}
else if (key == aten::Key::Key_F3) {
g_enableFrameStep = !g_enableFrameStep;
return;
}
else if (key == aten::Key::Key_F4) {
g_enableUpdate = !g_enableUpdate;
return;
}
else if (key == aten::Key::Key_F5) {
aten::GLProfiler::trigger();
return;
}
else if (key == aten::Key::Key_SPACE) {
if (g_enableFrameStep) {
g_frameStep = true;
return;
}
}
else if (key == aten::Key::Key_CONTROL) {
g_pickPixel = true;
return;
}
}
auto offset = offset_base * g_moveMultiply;
if (press) {
switch (key) {
case aten::Key::Key_W:
case aten::Key::Key_UP:
aten::CameraOperator::moveForward(g_camera, offset);
break;
case aten::Key::Key_S:
case aten::Key::Key_DOWN:
aten::CameraOperator::moveForward(g_camera, -offset);
break;
case aten::Key::Key_D:
case aten::Key::Key_RIGHT:
aten::CameraOperator::moveRight(g_camera, offset);
break;
case aten::Key::Key_A:
case aten::Key::Key_LEFT:
aten::CameraOperator::moveRight(g_camera, -offset);
break;
case aten::Key::Key_Z:
aten::CameraOperator::moveUp(g_camera, offset);
break;
case aten::Key::Key_X:
aten::CameraOperator::moveUp(g_camera, -offset);
break;
case aten::Key::Key_R:
{
aten::vec3 pos, at;
real vfov;
Scene::getCameraPosAndAt(pos, at, vfov);
g_camera.init(
pos,
at,
aten::vec3(0, 1, 0),
vfov,
WIDTH, HEIGHT);
}
break;
default:
break;
}
g_isCameraDirty = true;
}
}
int main()
{
aten::timer::init();
aten::OMPUtil::setThreadNum(g_threadnum);
aten::initSampler(WIDTH, HEIGHT);
aten::window::init(
WIDTH, HEIGHT, TITLE,
onRun,
onClose,
onMouseBtn,
onMouseMove,
onMouseWheel,
onKey);
aten::GLProfiler::start();
g_visualizer = aten::visualizer::init(WIDTH, HEIGHT);
aten::GammaCorrection gamma;
gamma.init(
WIDTH, HEIGHT,
"../shader/fullscreen_vs.glsl",
"../shader/gamma_fs.glsl");
aten::Blitter blitter;
blitter.init(
WIDTH, HEIGHT,
"../shader/fullscreen_vs.glsl",
"../shader/fullscreen_fs.glsl");
g_taa.init(
WIDTH, HEIGHT,
"../shader/fullscreen_vs.glsl", "../shader/taa_fs.glsl",
"../shader/fullscreen_vs.glsl", "../shader/taa_final_fs.glsl");
g_visualizer->addPostProc(&g_taa);
g_visualizer->addPostProc(&gamma);
//aten::visualizer::addPostProc(&blitter);
g_rasterizer.init(
WIDTH, HEIGHT,
"../shader/ssrt_vs.glsl",
"../shader/ssrt_gs.glsl",
"../shader/ssrt_fs.glsl");
g_rasterizerAABB.init(
WIDTH, HEIGHT,
"../shader/simple3d_vs.glsl",
"../shader/simple3d_fs.glsl");
g_fbo.asMulti(2);
g_fbo.init(
WIDTH, HEIGHT,
aten::PixelFormat::rgba32f,
true);
g_taa.setMotionDepthBufferHandle(g_fbo.getTexHandle(1));
aten::vec3 pos, at;
real vfov;
Scene::getCameraPosAndAt(pos, at, vfov);
g_camera.init(
pos,
at,
aten::vec3(0, 1, 0),
vfov,
WIDTH, HEIGHT);
Scene::makeScene(g_ctxt, &g_scene);
g_scene.build(g_ctxt);
#ifdef ENABLE_ENVMAP
auto envmap = aten::ImageLoader::load("../../asset/envmap/studio015.hdr", g_ctxt);
auto bg = std::make_shared<aten::envmap>();
bg->init(envmap);
auto ibl = std::make_shared<aten::ImageBasedLight>(bg);
g_scene.addImageBasedLight(ibl);
#endif
{
auto aabb = g_scene.getAccel()->getBoundingbox();
auto d = aabb.getDiagonalLenght();
g_tracer.setHitDistanceLimit(d * 0.25f);
std::vector<aten::GeomParameter> shapeparams;
std::vector<aten::PrimitiveParamter> primparams;
std::vector<aten::LightParameter> lightparams;
std::vector<aten::MaterialParameter> mtrlparms;
std::vector<aten::vertex> vtxparams;
aten::DataCollector::collect(
g_ctxt,
g_scene,
shapeparams,
primparams,
lightparams,
mtrlparms,
vtxparams);
const auto& nodes = g_scene.getAccel()->getNodes();
const auto& mtxs = g_scene.getAccel()->getMatrices();
std::vector<idaten::TextureResource> tex;
{
auto texNum = g_ctxt.getTextureNum();
for (int i = 0; i < texNum; i++) {
auto t = g_ctxt.getTexture(i);
tex.push_back(
idaten::TextureResource(t->colors(), t->width(), t->height()));
}
}
#ifdef ENABLE_ENVMAP
for (auto& l : lightparams) {
if (l.type == aten::LightType::IBL) {
l.idx = envmap->id();
}
}
#endif
auto camparam = g_camera.param();
camparam.znear = real(0.1);
camparam.zfar = real(10000.0);
g_tracer.update(
aten::visualizer::getTexHandle(),
WIDTH, HEIGHT,
camparam,
shapeparams,
mtrlparms,
lightparams,
nodes,
primparams, 0,
vtxparams, 0,
mtxs,
tex,
#ifdef ENABLE_ENVMAP
idaten::EnvmapResource(envmap->id(), ibl->getAvgIlluminace(), real(1)));
#else
idaten::EnvmapResource());
#endif
}
aten::window::run();
aten::GLProfiler::terminate();
g_rasterizer.release();
g_rasterizerAABB.release();
g_ctxt.release();
aten::window::terminate();
}
| 25.209262 | 133 | 0.564673 | nakdai |
9880985614eeca61f38b16c9ffc4f1f14995c3f3 | 29,850 | cpp | C++ | sparta/src/ConfigParserYAML.cpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/src/ConfigParserYAML.cpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | sparta/src/ConfigParserYAML.cpp | knute-sifive/map | fb25626830a56ad68ab896bcd01929023ff31c48 | [
"MIT"
] | null | null | null | // <ConfigParserYAML> -*- C++ -*-
#include <cassert>
#include <yaml-cpp/node/impl.h>
#include <yaml-cpp/node/node.h>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <cstddef>
#include <yaml-cpp/anchor.h>
#include <yaml-cpp/emitterstyle.h>
#include <yaml-cpp/mark.h>
#include <yaml-cpp/node/type.h>
#include <algorithm>
#include <cstdint>
#include <functional>
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include "sparta/parsers/ConfigParserYAML.hpp"
#include "sparta/simulation/TreeNode.hpp"
#include "sparta/simulation/TreeNodePrivateAttorney.hpp"
#include "sparta/utils/Printing.hpp"
#include "sparta/parsers/ConfigParser.hpp"
#include "sparta/simulation/Parameter.hpp"
#include "sparta/simulation/ParameterTree.hpp"
#include "sparta/utils/SpartaAssert.hpp"
#include "sparta/utils/SpartaException.hpp"
namespace YP = YAML; // Prevent collision with YAML class in ConfigParser namespace.
namespace sparta
{
namespace ConfigParser
{
//! Handle Scalar (key or value) YAML node from parser
void YAML::EventHandler::OnScalar(const YP::Mark& mark, const std::string& tag, YP::anchor_t anchor, const std::string& value)
{
(void) anchor;
(void) tag;
if(subtree_.size() > 0){
verbose() << indent_() << "(" << subtree_.size() << ") vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + Scalar " << value << " @" << mark.line << std::endl;
}else{
verbose() << indent_() << "(commented)" << " vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + Scalar " << value << " @" << mark.line << std::endl;
}
//if(subtree_.size() == 0){
// //! \todo Check to see if this is legal
// return;
//}
// New scalar within a sequence
if(seq_params_.size() > 0){
last_val_ = "";
cur_ = YP::NodeType::Scalar;
assert(sequence_pos_.size() > 0);
// Save sequence to parameter @ subtree
std::vector<ParameterBase*>& seq_ps = seq_params_.top();
for(ParameterBase* pb : seq_ps){
verbose() << "Storing " << value << " at " << sequence_pos_
<< " to parameter:" << *pb << std::endl;
if(filter_predicate_(pb)){ // Can apply?
if(write_to_default_){
pb->overrideDefaultItemValueFromString(sequence_pos_, value);
}else{
pb->setItemValueFromString(sequence_pos_, value);
}
}
verbose() << "Result = " << pb << std::endl;
}
seq_params_.addValue(value);
//std::cerr << "seq scalar assigned @\"" << pt_node_->getPath() << "\" \"" << sequence_pos_ << "\" <- " << value << std::endl;
//ptree_.recursPrint(std::cerr);
sequence_pos_.back() += 1;
return; // Done
} else if(last_val_ != ""){
// Value in a compact map
verbose() << indent_() << "COMPACT MAPPING {" << last_val_ << " : " << value << "}" << std::endl;
static const std::vector<std::string> include_keys(INCLUDE_KEYS);
if(std::find(include_keys.begin(), include_keys.end(), last_val_) != include_keys.end()){
verbose() << indent_() << " handling include directive" << std::endl;
handleIncludeDirective(value, subtree_, pt_node_);
}else if(last_val_.find(COMMENT_KEY_START) == 0){
verbose() << indent_() << " commented compact mapping. doing nothing" << std::endl;
}else{
// Assign this value to each parameter that matches pattern
if(subtree_.size() > 0){
bool found = false;
std::vector<TreeNode*> nodes;
for(TreeNode* tn : subtree_){
TreeNodePrivateAttorney::findChildren(tn, last_val_, nodes);
for(TreeNode* n : nodes){
ParameterBase* pb = dynamic_cast<ParameterBase*>(n);
if(pb){
if(filter_predicate_(pb)){ // Can apply?
if(write_to_default_){
pb->overrideDefaultFromString(value);
}else{
pb->setValueFromString(value);
}
found = true;
}
}
}
}
if(!found && !allow_missing_nodes_){
std::stringstream ss;
ss << "Could not find at least 1 parameter node matching pattern \""
<< last_val_ << "\" from tree nodes \"" << sparta::utils::stringize_value(subtree_)
<< "\". Maybe the typical 'params' node was omitted from the input file "
<< "between a node name and the actual parameter name (e.g. 'core.params.paramX')";
ss << markToString_(mark);
errors_.push_back(ss.str());
}
}
if(pt_node_){ // Because ptree does not handle parent references yet.
if(value == OPTIONAL_PARAMETER_KEYWORD){
const bool required = false; // Not required
auto n = pt_node_->create(last_val_, required);
n->unrequire();
}else{
const bool required = true; // Temporary value. Parameters created this way are always required
if(!pt_node_->set(last_val_, value, required, markToString_(mark, false))){ // Assign value
std::cerr << "WARNING: Encountered parameter path with parent reference: \"" << pt_node_->getPath()
<< "\" + \"" << last_val_ << "\". This node will not be available in the unbound parameter tree."
<< markToString_(mark) << std::endl;
}
}
//std::cerr << "set " << pt_node_->getPath() << " \"" << last_val_ << "\" <- " << value << std::endl;
//ptree_.recursPrint(std::cerr);
}
}
last_val_ = ""; // End of mapping pair. Clear
cur_ = YP::NodeType::Null;
return;
}else if(cur_ == YP::NodeType::Null && nesting_ == 1){
// Value in a compact map
verbose() << indent_() << "SINGULAR SCALAR : \"" << value << "\"" << std::endl;
if(value.find(COMMENT_KEY_START) == 0){
verbose() << indent_() << " commented singular scalar. doing nothing" << std::endl;
}else{
if(subtree_.size() > 0){
// Assign this value to each parameter that matches pattern
bool found = false;
for(TreeNode* tn : subtree_){
ParameterBase* pb = dynamic_cast<ParameterBase*>(tn);
if(pb){
if(filter_predicate_(pb)){ // Can apply?
if(write_to_default_){
pb->overrideDefaultFromString(value);
}else{
pb->setValueFromString(value);
}
found = true;
}
}
}
if(!found && !allow_missing_nodes_){
std::stringstream ss;
ss << "Could not find at least 1 parameter node in the current context \""
<< sparta::utils::stringize_value(subtree_)
<< "\". Maybe this YAML was parsed starting at the wrong context.";
ss << markToString_(mark);
errors_.push_back(ss.str());
}
}
}
if(pt_node_){ // Because ptree does not handle parent references yet.
if(value == OPTIONAL_PARAMETER_KEYWORD){
const bool required = false; // Not required
auto n = pt_node_->create(last_val_, required);
n->unrequire(); // In case it was already created
}else{
const bool required = true; // Temporary value. Parameters created this way are always required
pt_node_->setValue(value, required, markToString_(mark, false));
//std::cerr << "setValue " << pt_node_->getPath() << " \"" << last_val_ << "\" <- " << value << std::endl;
//ptree_.recursPrint(std::cerr);
}
}
cur_ = YP::NodeType::Null;
return;
}else{
// This is legitimate. In inline-maps with comma-separated k-v pairs, this
// case is encountered
verbose() << indent_() << "next scalar : " << value << std::endl;
}
if(cur_ == YP::NodeType::Map){
verbose() << indent_() << "<within map>" << std::endl;
}else if(cur_ == YP::NodeType::Sequence){
verbose() << indent_() << "<within seq>" << std::endl;
// Append value
}else{
verbose() << indent_() << "<new key?>" << std::endl;
}
last_val_ = value;
cur_ = YP::NodeType::Scalar;
}
//! Handle SequenceStart YAML node from parser
void YAML::EventHandler::OnSequenceStart(const YP::Mark& mark, const std::string& tag,
YP::anchor_t anchor, YP::EmitterStyle::value style)
{
(void) anchor;
(void) tag;
(void) style;
if(subtree_.size() > 0){
verbose() << indent_() << "(" << subtree_.size() << ") vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + SeqStart (" << last_val_ << ") @" << mark.line << std::endl;
}else{
verbose() << indent_() << "(commented)" << " vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + SeqStart (" << last_val_ << ") @" << mark.line << std::endl;
}
//if(subtree_.size() == 0){
// return;
//}
seq_vec_.push({}); // Add a new level of values to the stack
if(seq_params_.size() == 0){
// Handle entry into first level of the sequence
sequence_pos_.push_back(0);
seq_params_.push({});
std::vector<ParameterBase*>& seq_ps = seq_params_.top();
if(subtree_.size() > 0){
// Find next generation based on pattern of scalar (key) last_val_
NodeVector nodes;
findNextGeneration_(subtree_, last_val_, nodes, mark);
bool found = false;
for(TreeNode* tn : nodes){
ParameterBase* pb = dynamic_cast<ParameterBase*>(tn);
if(pb){
if(filter_predicate_(pb)){ // Can apply?
seq_ps.push_back(pb);
found = true;
// Clear the parameter value before setting it (in case it is larger than the new content)
if (write_to_default_) {
pb->overrideDefaultClearVectorValue();
} else {
pb->clearVectorValue();
}
}
}
}
//! \todo Implement filtering with a lambda functor such as:
//! [] (TreeNode* in) -> bool {return dynamic_cast<ParameterBase*>(in)));
if(!found && !allow_missing_nodes_){
std::stringstream ss;
ss << "Could not find at least 1 parameter node matching pattern \""
<< last_val_ << "\" from tree node \"" << sparta::utils::stringize_value(subtree_)
<< "\". Maybe the 'params' level was omitted from the input file's tree before the parameter";
ss << markToString_(mark);
errors_.push_back(ss.str());
}
}
pt_stack_.push(pt_node_); // Push on first entry
if(pt_node_){
const bool required = true; // Temporary value. Parameters created this way are always required
auto npt_node = pt_node_->create(last_val_, required); // Fails if it contains a parent reference
//std::cerr << "OnSequenceStart Create \"" << pt_node_->getPath() << "\" \"" << last_val_ << "\"" << std::endl;
//ptree_.recursPrint(std::cerr);
if(!npt_node){
std::cerr << "WARNING: Encountered parameter path with parent reference: \"" << pt_node_->getPath()
<< "\" + \"" << last_val_ << "\". This node will not be available in the unbound parameter tree."
<< markToString_(mark) << std::endl;
}
pt_node_ = npt_node;
}
}else{
// Enlarge the parameter at current indices before moving into the next level
for(auto pb : seq_params_.top()){
if(filter_predicate_(pb)){ // Can apply?
if (write_to_default_){
pb->overrideDefaultResizeVectorsFromString(sequence_pos_);
} else {
pb->resizeVectorsFromString(sequence_pos_);
}
}
}
sequence_pos_.push_back(0);
// Handle entry into nested sequence in YAML file
seq_params_.push(seq_params_.top()); // Copy previous level
}
last_val_ = "";
nesting_++;
}
//! Handle SequenceEnd YAML node from parser
void YAML::EventHandler::OnSequenceEnd()
{
sparta_assert(seq_vec_.size() > 0,
"Reached end of a YAML sequence in " << filename_
<< " without any sets of sequence values tracked");
auto& seq_vals = seq_vec_.top();
verbose() << indent_() << "Storing sequence to param: " << sparta::utils::stringize_value(seq_vals) << std::endl;
if(subtree_.size() > 0){
verbose() << indent_() << "(" << subtree_.size() << ") vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + SeqEnd" << std::endl;
}else{
verbose() << indent_() << "(commented)" << " vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + SeqEnd" << std::endl;
}
nesting_--;
//if(subtree_.size() == 0){
// return; // seq_params_ should be NULL and seq_vec_ empty
//}
sparta_assert(seq_params_.size() > 0,
"Reached end of YAML sequence in " << filename_
<< " without any sets of sequence parameters tracked");
seq_params_.pop();
// Assign popped sequence to parameter tree node once the nessted sequence has ended
if(seq_params_.size() == 0){
if(pt_node_){
// NOTE: cannot unrequire this parameter here because we're assigning a
// sequence to it. Only when assigning the OPTIONAL_PARAMETER_KEYWORD
// string can it be ignored.
// Just ensure a node with last_val_ exists, but do not assign to it yet.
const bool required = true; // Temporary value. Parameters created this way are always required
pt_node_->setValue(seq_params_.getValue(), required);
//std::cerr << "OnSequenceEnd setValue @\"" << pt_node_->getPath() << " \"" << seq_params_.getValue() << "\"" << std::endl;
//ptree_.recursPrint(std::cerr);
}
// Reached end of nested sequence, pop pt_stack_ tos to get node before sequences started
pt_node_ = pt_stack_.top();
pt_stack_.pop();
}
seq_vec_.pop();
sequence_pos_.pop_back();
if(!sequence_pos_.empty()){
sequence_pos_.back() += 1;
}
last_val_ = "";
}
//! Handle MapStart YAML node from parser
void YAML::EventHandler::OnMapStart(const YP::Mark& mark, const std::string& tag,
YP::anchor_t anchor, YP::EmitterStyle::value style)
{
(void) anchor;
(void) tag;
(void) style;
if(subtree_.size() > 0){
verbose() << indent_() << "(" << subtree_.size() << ") vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + MapStart (" << last_val_ << ") @" << mark.line << std::endl;
}else{
verbose() << indent_() << "(commented)" << " vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + MapStart (" << last_val_ << ") @" << mark.line << std::endl;
}
nesting_++;
sparta_assert(seq_params_.size() == 0,
"Cannot start a YAML map if already within a sequence " << markToString_(mark));
tree_stack_.push(subtree_); // Add to stack regardless of comment-state
pt_stack_.push(pt_node_);
//if(subtree_.size() == 0){
// return; // subtree_ remains NULL
//}
static const std::vector<std::string> include_keys(INCLUDE_KEYS);
if(std::find(include_keys.begin(), include_keys.end(), last_val_) != include_keys.end()){
verbose() << indent_() << " INCLUDE MAPPING" << std::endl;
SpartaException ex("Include directive contains a map. This is not allowed. ");
ex << "Includes must map directly to a filename scalar";
addMarkInfo_(ex, mark);
throw ex;
}else if(last_val_.find(COMMENT_KEY_START) == 0){
// comment
verbose() << indent_() << " COMMENTED MAPPING" << std::endl;
///subtree_
subtree_.clear(); // Clear current nodes
}else{
// current subtree_ already pushed to stack
// Move onto next generation of children
///subtree_ = subtree_->getChild(last_val_);
subtree_.clear(); // Clear this level to be reset
NodeVector& v = tree_stack_.top();
findNextGeneration_(v, last_val_, subtree_, mark); // Assures found num nodes in range [1, MAX_MATCHES_PER_LEVEL].
if(pt_node_){ // Because ptree cannot handle parent references yet
const bool required = true; // Temporary value. Parameters created this way are always required
auto npt_node = pt_node_->create(last_val_, required); // create child if not already existing
if(!npt_node){
std::cerr << "WARNING: Encountered parameter path with parent reference: \"" << pt_node_->getPath()
<< "\" + \"" << last_val_ << "\". This node will not be available in the unbound parameter tree."
<< markToString_(mark) << std::endl;
}
pt_node_ = npt_node;
}
}
last_val_ = "";
}
//! Handle MapEnd YAML node from parser
void YAML::EventHandler::OnMapEnd()
{
if(subtree_.size() > 0){
verbose() << indent_() << "(" << subtree_.size() << ") vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + MapEnd" << std::endl;
}else{
verbose() << indent_() << "(commented)" << " vptn:" << (pt_node_ ? pt_node_->getPath() : "<null>") << " + MapEnd" << std::endl;
}
nesting_--;
subtree_ = tree_stack_.top();
tree_stack_.pop();
pt_node_ = pt_stack_.top();
pt_stack_.pop();
last_val_ = "";
}
void YAML::EventHandler::findNextGeneration_(NodeVector& current, const std::string& pattern,
NodeVector& next, const YP::Mark& mark){
sparta_assert(next.size() == 0);
if(current.size() == 0){
// Breaks sparta TreeNode test
//sparta_assert(allow_missing_nodes_);
return;
}
for(TreeNode* tn : current){
TreeNodePrivateAttorney::findChildren(tn, pattern, next);
}
if(next.size() == 0 && !allow_missing_nodes_){
SpartaException ex("Could not find any nodes matching the pattern \"");
ex << pattern << "\" from nodes " << sparta::utils::stringize_value(current) << ".";
addMarkInfo_(ex, mark);
throw ex;
}
if(next.size() > MAX_MATCHES_PER_LEVEL){
SpartaException ex("Found more than ");
ex << (size_t)MAX_MATCHES_PER_LEVEL << " nodes matching the pattern \""
<< pattern << "\" from " << subtree_.size() << " nodes. "
<< "This is likely a very deep and dangerous search pattern (or possibly a bug). "
<< "If there really should be this many matches, increase MAX_MATCHES_PER_LEVEL.";
addMarkInfo_(ex, mark);
throw ex;
}
}
/*!
* \brief Sets the given sequence YAML node <node> as the value
* of the parameter described by <param_path> relative to the
* current node <subtree>.
* \param subtree Current node.
* \param param_path Path (pattern) relative to <subtree> to a
* node which is a sparta::Parameter.
* \param node The value to assign to the parameter decribed by
* <subtree> and <param_path>.
*/
void YAML::EventHandler::applyArrayParameter(TreeNode* subtree,
const std::string& param_path,
const YP::Node& node)
{
sparta_assert(node.Type() == YP::NodeType::Sequence);
sparta_assert(subtree || allow_missing_nodes_);
std::vector<TreeNode*> nodes;
findNextGeneration_(subtree_, param_path, nodes, node.Mark());
const bool required = true; // Temporary value. Parameters created this way are always required
ParameterTree::Node* ptn = pt_node_ ? pt_node_->create(param_path, required) : nullptr; // create child if not already existing
std::vector<std::string> values;
verbose() << indent_() << " [" << std::endl;
// Extract each value into values vector
for(size_t i=0; i<node.size(); ++i) {
std::string scalar;
scalar = node[i].Scalar();
verbose() << indent_() << " " << scalar << " " << std::endl;
values.push_back(scalar);
}
verbose() << indent_() << " ]" << std::endl;
// Assign this array of values to each node
bool found = false;
for(TreeNode* n : nodes){
ParameterBase* pb = dynamic_cast<ParameterBase*>(n);
if(pb){
if(filter_predicate_(pb)){ // Can apply?
if(write_to_default_){
pb->overrideDefaultFromStringVector(values);
}else{
pb->setValueFromStringVector(values);
}
found = true;
}
}
}
if(!found && !allow_missing_nodes_){
std::stringstream ss;
ss << "Could not find at least 1 parameter node matching pattern \""
<< param_path << "\" from tree nodes \"" << sparta::utils::stringize_value(subtree_)
<< "\". Maybe the typical 'params' node was omitted from the input file "
<< "between a node name and the actual parameter name (e.g. 'core.params.paramX')";
ss << markToString_(node.Mark());
errors_.push_back(ss.str());
}
if(ptn){ // Because ptree cannot handle parent references yet
std::stringstream ss;
ss << values;
ptn->setValue(ss.str(), required, markToString_(node.Mark()));
//std::cerr << "setValue " << pt_node_->getPath() << " \"" << ss.str() << "\"" << std::endl;
//ptree_.recursPrint(std::cerr);
}else if(pt_node_){
std::cerr << "WARNING: Encountered parameter path with parent reference: \"" << pt_node_->getPath()
<< "\" + \"" << param_path << "\". This node will not be available in the unbound parameter tree."
<< markToString_(node.Mark()) << std::endl;
}
}
/*!
* \brief Consumes a file based on an include directives destination.
* \param pfilename YAML file to read
* \param device_trees Vector of TreeNodes to act as roots of
* the filename being read. This allows includes to be scoped to specific
* nodes. The file will be parsed once an applied to all roots in
* device_trees.
*/
void YAML::EventHandler::handleIncludeDirective(const std::string& filename, NodeVector& device_trees, ParameterTree::Node* ptn)
{
//! \todo Be smarter about checking for indirect recursion by keeping a set
// files or limiting the depth of this include stack
// Prevent direct reursion by filename
if(filename == filename_){
throw SpartaException("Direct recursion detected in configuration file. File ")
<< filename_ << " includes " << filename;
//! \todo Include line number in this error
}
std::string filename_used = filename;
// Check to see if we can point to the relative filepath to include based on the
// filepath of the current yaml file in the case that the file does not exist.
boost::filesystem::path fp(filename);
bool found = false;
// Try to find the incldue in the include paths list
for(const auto & incl_path : include_paths_)
{
boost::filesystem::path curr_inc(incl_path);
const auto combined_path = curr_inc / filename;
if (boost::filesystem::exists(combined_path))
{
std::cout << " [PARAMETER INCLUDE NOTE] : Including " << combined_path << std::endl;
filename_used = combined_path.string();
found = true;
break;
}
}
if(!found) {
SpartaException e("Could not resolve location of included file: '");
e << filename << "' in source file: " << filename_ << "\nSearch paths: \n";
for(const auto & incl_path : include_paths_) {
e << "\t" << incl_path << '\n';
}
e << '\n';
throw e;
}
YAML incl(filename_used, include_paths_);
incl.allowMissingNodes(doesAllowMissingNodes()); // Allow missing nodes if parent does
incl.setParameterApplyFilter(filter_predicate_); // How to filter nodes that are about to be assigned
TreeNode dummy("dummy", "dummy");
NodeVector dummy_tree{&dummy};
incl.consumeParameters(device_trees.size() > 0 ? device_trees : dummy_tree, verbose_); // Throws on error
if(ptn){ // Because ptree cannot handle parent references yet
ptn->appendTree(incl.getParameterTree().getRoot()); // Bring over tree
}
}
}; // namespace ConfigParser
}; // namespace sparta
| 48.22294 | 192 | 0.479799 | knute-sifive |
98815a520bf31d25aeac0f04e309df6294cfa41f | 19,577 | cpp | C++ | tc 160+/FoxSearchingRuins.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/FoxSearchingRuins.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/FoxSearchingRuins.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int bestval[1001][1001];
int bestval2[1001][1001];
struct jewel {
int x, y, v;
jewel(int x_, int y_, int v_): x(x_), y(y_), v(v_) {}
};
bool operator<(const jewel &a, const jewel &b) {
if (a.y != b.y) {
return a.y < b.y;
} else if (a.x != b.x) {
return a.x < b.x;
} else {
return a.v < b.v;
}
}
class RunningMaxes {
// this structure uses an upper fenwick tree to support
// O(logn) set_value for insering a value at a position and
// get_max(from) that returns the maximal value from the interval [from, MAXVAL]
// using only O(n) space
public:
RunningMaxes(int MAXVAL_): MAXVAL(MAXVAL_), M(MAXVAL+1, 0) {} // change 0 with -INF if necessary
void set_value(int at, int x) {
M[0] = max(M[0], x);
while (at > 0) {
M[at] = max(M[at], x);
at -= at&-at;
}
}
int get_max(int from) { // get_max(from, MAXVAL)
if (from == 0) return M[0];
int ret = 0; // replace with -INF if necessary
while (from <= MAXVAL) {
ret = max(ret, M[from]);
from += from&-from;
}
return ret;
}
private:
const int MAXVAL;
vector<int> M;
};
class RunningMaxes2 {
// this structure uses a lower fenwick tree to support
// O(logn) set_value for insering a value at a position and
// get_max(to) that returns the maximal value from the interval [0, to]
// using only O(n) space
public:
RunningMaxes2(int MAXVAL_): MAXVAL(MAXVAL_), M(MAXVAL+1, 0) {} // change 0 with -INF if necessary
void set_value(int at, int x) {
while (at <= MAXVAL) {
M[at] = max(M[at], x);
at |= at+1;
}
}
int get_max(int to) { // get_max(0, to)
int ret = 0; // replace with -INF if necessary
while (to >= 0) {
ret = max(ret, M[to]);
to = (to & (to+1)) - 1;
}
return ret;
}
private:
const int MAXVAL;
vector<int> M;
};
class SegmentTree {
// only works for positive values!
public:
SegmentTree(int MAXVAL_): MAXVAL(MAXVAL_), M(2*(MAXVAL+1), 0) { init(0, 0, MAXVAL); }
void set_value(int at, int x) { set_value(0, 0, MAXVAL, at, x); }
int get_max(int a, int b) { return get_max(0, 0, MAXVAL, a, b); }
private:
int init(int node, int l, int r) {
while (node >= (int)M.size()) {
M.push_back(0);
}
if (l == r) {
return (M[node] = 0); // change with -INF if necessary or some A[l] for an array with inital values
} else {
int mid = l + (r-l)/2;
return (M[node] = max(init(2*node + 1, l, mid), init(2*node + 2, mid+1, r)));
}
}
int set_value(int node, int l, int r, int at, int x) {
if (at<l || r<at) {
return M[node];
}
if (l == r) {
assert(l == at);
return (M[node] = max(M[node], x));
} else {
int mid = l + (r-l)/2;
// don't need to check the old value since set_value will
// properly recalculate the max for the whole interval
return (M[node] = max(set_value(2*node + 1, l, mid, at, x),
set_value(2*node + 2, mid+1, r, at, x)));
}
}
int get_max(int node, int l, int r, int a, int b) {
if (a>r || b<l) {
return -1;
}
a = max(a, l);
b = min(b, r);
if (a==l && b==r) {
return M[node];
} else {
int mid = l + (r-l)/2;
return max(get_max(2*node + 1, l, mid, a, b),
get_max(2*node + 2, mid+1, r, a, b));
}
}
const int MAXVAL;
vector<int> M;
};
class FoxSearchingRuins {
public:
long long theMinTime(int W, int H, int n, int LR, int goalValue, int timeX, int timeY, vector <int> seeds) {
vector<jewel> J;
J.reserve(n);
J.push_back(jewel(((long long)seeds[1]*seeds[0] + seeds[2]) % W,
((long long)seeds[4]*seeds[3] + seeds[5]) % H,
((long long)seeds[7]*seeds[6] + seeds[8]) % seeds[9]));
for (int i=1; i<n; ++i) {
J.push_back(jewel(((long long)seeds[1]*J.back().x + seeds[2]) % W,
((long long)seeds[4]*J.back().y + seeds[5]) % H,
((long long)seeds[7]*J.back().v + seeds[8]) % seeds[9]));
}
sort(J.begin(), J.end());
for (int i=0; i<n-1; ++i) {
int j = i+1;
while (j<n && J[i].x==J[j].x && J[i].y==J[j].y) {
J[i].v += J[j].v;
J[j].y = H;
++j;
}
i = j - 1;
}
sort(J.begin(), J.end());
while (J.back().y == H) {
--n;
J.pop_back();
}
vector<int> ys;
for (int i=0; i<n; ++i) {
if (ys.size()==0 || J[i].y!=ys.back()) {
ys.push_back(J[i].y);
}
}
/* uncomment this for RuningMaxes with an upper fenwick tree
vector<RunningMaxes> left(W+LR, RunningMaxes(W-1));
vector<RunningMaxes> right(W+LR, RunningMaxes(W-1));
*/
/* uncomment this for RunningMaxes2 with a lower fenwick tree
vector<RunningMaxes2> left(W+LR, RunningMaxes2(W-1));
vector<RunningMaxes2> right(W+LR, RunningMaxes2(W-1));
*/
vector<SegmentTree> left(W+LR, SegmentTree(W-1));
vector<SegmentTree> right(W+LR, SegmentTree(W-1));
long long sol = -1;
for (int i=0; i<(int)ys.size(); ++i) {
const int Y = ys[i];
vector<int> xs, vals;
for (int j=0; j<n; ++j) {
if (J[j].y == Y) {
while (j<n && J[j].y==Y) {
if (xs.size() > 0) {
assert(xs.back() < J[j].x);
}
xs.push_back(J[j].x);
vals.push_back(J[j].v);
++j;
}
break;
}
}
/* this uses RunningMaxes with an upper fenwick tree
for (int j=0; j<(int)xs.size(); ++j) {
for (int lr=0; lr<=LR; ++lr) { // -> amount of LR moves used thus far
bestval[j][lr] = bestval2[j][lr] = vals[j] // -> this is the "entry" value to this row (motion within the row is handled later)
+ max(left[xs[j]+LR-lr].get_max(W-1-xs[j]), // -> the columns further left must have spent less lr so the difference x-lr is constant
// however, since that could be negative, we add LR to it to make it nonegative
// -> also, since we are using an upper fenwick tree for a segment tree, only get_max(from, MAXVAL)
// queries are supported (MAXVAL is W-1) - therefore, the values are reversed because we need
// queries get_max(0, to)... note also that a lower fenwick tree would work nicely for this, but
// requires a separate implementation
right[xs[j]+lr].get_max(xs[j])); // -> the columns further right must have spent less lr so the sum x+lr is constant
// -> also, when using an upper fenwick tree for a segment tree, only get_max(from, MAXVAL)
// queries are supported (MAXVAL here is W-1)
}
}
// now try moving left/right... it is always optimal to do a single sweep left or right
// this is because we can alwasy not take jewels moving right and then sweep to the left, or vice versa...
for (int j=1; j<(int)xs.size(); ++j) { // sweep right
for (int lr=xs[j]-xs[j-1]; lr<=LR; ++lr) {
bestval[j][lr] = max(bestval[j][lr], vals[j] + bestval[j-1][lr-(xs[j]-xs[j-1])]);
}
}
for (int j=(int)xs.size()-2; j>=0; --j) { // sweep left
for (int lr=xs[j+1]-xs[j]; lr<=LR; ++lr) {
bestval2[j][lr] = max(bestval2[j][lr], vals[j] + bestval2[j+1][lr-(xs[j+1]-xs[j])]);
}
}
for (int j=0; j<(int)xs.size(); ++j) {
for (int lr=0; lr<=LR; ++lr) {
int best = max(bestval[j][lr], bestval2[j][lr]);
if (best >= goalValue) {
long long t = (long long)Y*timeY + (long long)lr*timeX;
if (sol==-1 || t<sol) {
sol = t;
}
}
left[xs[j]+LR-lr].set_value(W-1-xs[j], best);
right[xs[j]+lr].set_value(xs[j], best);
}
} */
/* this uses running maxes with a lower fenwick tree.
for (int j=0; j<(int)xs.size(); ++j) {
for (int lr=0; lr<=LR; ++lr) {
bestval[j][lr] = bestval2[j][lr] = vals[j]
+ max(left[xs[j]+LR-lr].get_max(xs[j]), // since this uses a lower fenwick tree, it supports get_max(0, to) queries
// and that is exactly what is needed for the left hand side
right[xs[j]+lr].get_max(W-1-xs[j])); // similarly to the previous solution using RunningMaxes with an upper fenwick tree,
// we will reverse the values in 'right' trees so that we can use the get_max call
// to simulate (from, MAXVAL) queries
}
}
// this part is the same
for (int j=1; j<(int)xs.size(); ++j) {
for (int lr=xs[j]-xs[j-1]; lr<=LR; ++lr) {
bestval[j][lr] = max(bestval[j][lr], vals[j] + bestval[j-1][lr-(xs[j]-xs[j-1])]);
}
}
for (int j=(int)xs.size()-2; j>=0; --j) {
for (int lr=xs[j+1]-xs[j]; lr<=LR; ++lr) {
bestval2[j][lr] = max(bestval2[j][lr], vals[j] + bestval2[j+1][lr-(xs[j+1]-xs[j])]);
}
}
for (int j=0; j<(int)xs.size(); ++j) {
for (int lr=0; lr<=LR; ++lr) {
int best = max(bestval[j][lr], bestval2[j][lr]);
if (best >= goalValue) {
long long t = (long long)Y*timeY + (long long)lr*timeX;
if (sol==-1 || t<sol) {
sol = t;
}
}
// this is reversed from the previous case... here we are reversing the 'right' trees since we are using a lower fenwick tree
left[xs[j]+LR-lr].set_value(xs[j], best);
right[xs[j]+lr].set_value(W-1-xs[j], best);
}
} */
// this is by far the slowest solution... worst case is about 1.99 secs (or above)
for (int j=0; j<(int)xs.size(); ++j) {
for (int lr=0; lr<=LR; ++lr) {
bestval[j][lr] = bestval2[j][lr] = vals[j] + max(left[xs[j]+LR-lr].get_max(0, xs[j]), right[xs[j]+lr].get_max(xs[j], W-1));
}
}
for (int j=1; j<(int)xs.size(); ++j) {
for (int lr=xs[j]-xs[j-1]; lr<=LR; ++lr) {
bestval[j][lr] = max(bestval[j][lr], vals[j] + bestval[j-1][lr-(xs[j]-xs[j-1])]);
}
}
for (int j=(int)xs.size()-2; j>=0; --j) {
for (int lr=xs[j+1]-xs[j]; lr<=LR; ++lr) {
bestval2[j][lr] = max(bestval2[j][lr], vals[j] + bestval2[j+1][lr-(xs[j+1]-xs[j])]);
}
}
for (int j=0; j<(int)xs.size(); ++j) {
for (int lr=0; lr<=LR; ++lr) {
int best = max(bestval[j][lr], bestval2[j][lr]);
if (best >= goalValue) {
long long t = (long long)Y*timeY + (long long)lr*timeX;
if (sol==-1 || t<sol) {
sol = t;
}
}
left[xs[j]+LR-lr].set_value(xs[j], best);
right[xs[j]+lr].set_value(xs[j], best);
}
}
}
return sol;
}
/*
int L[1000], R[1000];
O(n^5) ili tako nesto... jako sporo, ali tocno
memset(L, 0xff, sizeof L);
memset(R, 0xff, sizeof R);
for (int i=0; i<n; ++i) {
if (i>0 && J[i-1].y==J[i].y) {
L[i] = i-1;
}
if (i<n-1 && J[i].y==J[i+1].y) {
R[i] = i+1;
}
}
long long sol = -1LL;
memset(bestval, 0xff, sizeof bestval);
for (int i=0; i<n; ++i) {
bestval[i][LR] = J[i].v;
for (int j=0; J[j].y<J[i].y; ++j) {
const int dlr = abs(J[j].x - J[i].x);
for (int lr=dlr; lr<=LR; ++lr) {
if (bestval[j][lr] == -1) {
continue;
}
int l = i;
int val_l = 0;
do {
val_l += J[l].v;
int r = i;
int val_r = 0;
do {
if (r != i) {
val_r += J[r].v;
}
int lr_cost;
lr_cost = abs(J[j].x - J[l].x) + abs(J[r].x - J[l].x) + abs(J[r].x - J[i].x);
if (lr_cost <= lr) {
bestval[i][lr-lr_cost] = max(bestval[i][lr-lr_cost], bestval[j][lr] + val_l + val_r);
}
lr_cost = abs(J[j].x - J[r].x) + abs(J[r].x - J[l].x) + abs(J[l].x - J[i].x);
if (lr_cost <= lr) {
bestval[i][lr-lr_cost] = max(bestval[i][lr-lr_cost], bestval[j][lr] + val_l + val_r);
}
r = R[r];
} while (r != -1);
l = L[l];
} while (l != -1);
}
}
for (int lr=0; lr<=LR; ++lr) {
long long t = (long long)J[i].y*timeY + (long long)(LR-lr)*timeX;
if (bestval[i][lr] >= goalValue) {
if (sol==-1 || sol>t) {
sol = t;
}
}
}
}*/
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 5; int Arg1 = 8; int Arg2 = 5; int Arg3 = 7; int Arg4 = 10; int Arg5 = 3; int Arg6 = 1; int Arr7[] = {979, 777, 878, 646, 441, 545, 789, 896, 987, 10}; vector <int> Arg7(Arr7, Arr7 + (sizeof(Arr7) / sizeof(Arr7[0]))); long long Arg8 = 5LL; verify_case(0, Arg8, theMinTime(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7)); }
void test_case_1() { int Arg0 = 7; int Arg1 = 8; int Arg2 = 10; int Arg3 = 3; int Arg4 = 10; int Arg5 = 3; int Arg6 = 10; int Arr7[] = {0, 1, 1, 0, 1, 3, 1011, 3033, 2022, 10}; vector <int> Arg7(Arr7, Arr7 + (sizeof(Arr7) / sizeof(Arr7[0]))); long long Arg8 = 29LL; verify_case(1, Arg8, theMinTime(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7)); }
void test_case_2() { int Arg0 = 7; int Arg1 = 8; int Arg2 = 10; int Arg3 = 3; int Arg4 = 14; int Arg5 = 3; int Arg6 = 10; int Arr7[] = {0, 1, 1, 0, 1, 3, 1011, 3033, 2022, 10}; vector <int> Arg7(Arr7, Arr7 + (sizeof(Arr7) / sizeof(Arr7[0]))); long long Arg8 = 59LL; verify_case(2, Arg8, theMinTime(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7)); }
void test_case_3() { int Arg0 = 7; int Arg1 = 8; int Arg2 = 10; int Arg3 = 4; int Arg4 = 14; int Arg5 = 3; int Arg6 = 10; int Arr7[] = {0, 1, 1, 0, 1, 3, 1011, 3033, 2022, 10}; vector <int> Arg7(Arr7, Arr7 + (sizeof(Arr7) / sizeof(Arr7[0]))); long long Arg8 = 42LL; verify_case(3, Arg8, theMinTime(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7)); }
void test_case_4() { int Arg0 = 497; int Arg1 = 503; int Arg2 = 989; int Arg3 = 647; int Arg4 = 100000; int Arg5 = 13; int Arg6 = 14; int Arr7[] = {7613497, 5316789, 1334537, 2217889, 6349551, 978463, 1234567, 2345678, 3456789, 1000}; vector <int> Arg7(Arr7, Arr7 + (sizeof(Arr7) / sizeof(Arr7[0]))); long long Arg8 = -1LL; verify_case(4, Arg8, theMinTime(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7)); }
void test_case_5() { int Arg0 = 1000; int Arg1 = 749613275; int Arg2 = 1000; int Arg3 = 1000; int Arg4 = 7500000; int Arg5 = 97; int Arg6 = 6; int Arr7[] = {224284427, 617001937, 294074399, 606566321, 202762619, 419798101, 200613401, 640663967, 417565817, 170000}; vector <int> Arg7(Arr7, Arr7 + (sizeof(Arr7) / sizeof(Arr7[0]))); long long Arg8 = 3780225876LL; verify_case(5, Arg8, theMinTime(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
FoxSearchingRuins ___test;
___test.run_test(-1);
}
// END CUT HERE
| 47.982843 | 447 | 0.427543 | ibudiselic |
9882f664ec54e7d3e5a94a7eff8ed960a2dcf1f8 | 6,215 | cpp | C++ | unit_tests/test_classes/const_functions.cpp | SoapyMan/oolua | 9d25a865b05bbb6aaff56726b46e5b746572e490 | [
"MIT"
] | 4 | 2018-12-19T09:30:24.000Z | 2021-06-26T05:38:11.000Z | unit_tests/test_classes/const_functions.cpp | SoapyMan/oolua | 9d25a865b05bbb6aaff56726b46e5b746572e490 | [
"MIT"
] | null | null | null | unit_tests/test_classes/const_functions.cpp | SoapyMan/oolua | 9d25a865b05bbb6aaff56726b46e5b746572e490 | [
"MIT"
] | 2 | 2017-03-28T18:38:30.000Z | 2018-10-17T19:01:05.000Z |
# include "oolua_tests_pch.h"
# include "oolua.h"
# include "common_cppunit_headers.h"
# include "gmock/gmock.h"
# include "expose_const_func.h"
namespace
{
struct ConstantMockHelper
{
ConstantMockHelper()
: mock()
, ptr_to_const(&mock)
, ptr_to(&mock)
{}
ConstantMock mock;
Constant const* ptr_to_const;
Constant * ptr_to;
};
} // namespace
/*
Tests that the object, on which are calls are requested, handles the following correctly :
call none constant function on a none constant object
call a constant function on a none constant object
call a constant function on a constant object
error:
call a none constant function on a constant object
Tested for C++ proxied functions either called directly in Lua or indirectly via functions
added to the type in Lua, which in turn will call the C++ functions.
*/
class Constant_functions : public CPPUNIT_NS::TestFixture
{
CPPUNIT_TEST_SUITE(Constant_functions);
CPPUNIT_TEST(callConstantFunction_passedConstantInstance_calledOnce);
CPPUNIT_TEST(callConstantFunction_passedNoneConstantInstance_calledOnce);
CPPUNIT_TEST(callNoneConstantFunction_passedNoneConstantInstance_calledOnce);
CPPUNIT_TEST(callLuaAddedFunctionWhichCallsConstMember_passedConstantInstance_calledOnce);
CPPUNIT_TEST(callLuaAddedFunctionWhichCallsConstMember_passedNoneConstantInstance_calledOnce);
CPPUNIT_TEST(callLuaAddedFunctionWhichCallsNoneConstMember_passedNoneConstantInstance_calledOnce);
#if OOLUA_STORE_LAST_ERROR == 1
CPPUNIT_TEST(callNoneConstantFunction_passedConstantInstance_callReturnsFalse);
CPPUNIT_TEST(callLuaAddedFunctionWhichCallsNoneConstMember_passedConstantInstance_callReturnsFalse);
CPPUNIT_TEST(callConstantMethodInBaseClass_usesConstantInstance_callReturnsTrue);
#endif
#if OOLUA_USE_EXCEPTIONS == 1
CPPUNIT_TEST(callNoneConstantFunction_passedConstantInstance_throwsRuntimeError);
CPPUNIT_TEST(callLuaAddedFunctionWhichCallsNoneConstMember_passedConstantInstance_callThrowsRuntimeError);
CPPUNIT_TEST(callConstantMethodInBaseClass_usesConstantInstance_noException);
#endif
CPPUNIT_TEST_SUITE_END();
OOLUA::Script * m_lua;
public:
Constant_functions()
: m_lua(0)
{}
LVD_NOCOPY(Constant_functions)
void setUp()
{
m_lua = new OOLUA::Script;
m_lua->register_class<Constant>();
}
void tearDown()
{
delete m_lua;
}
void callConstantFunction_passedConstantInstance_calledOnce()
{
ConstantMockHelper helper;
EXPECT_CALL(helper.mock, cpp_func_const()).Times(1);
m_lua->run_chunk("return function(obj) obj:cpp_func_const() end");
m_lua->call(1, helper.ptr_to_const);
}
void callConstantFunction_passedNoneConstantInstance_calledOnce()
{
ConstantMockHelper helper;
EXPECT_CALL(helper.mock, cpp_func_const()).Times(1);
m_lua->run_chunk("return function(obj) obj:cpp_func_const() end");
m_lua->call(1, helper.ptr_to);
}
void callNoneConstantFunction_passedNoneConstantInstance_calledOnce()
{
ConstantMockHelper helper;
EXPECT_CALL(helper.mock, cpp_func()).Times(1);
m_lua->run_chunk("return function(obj) obj:cpp_func() end");
m_lua->call(1, helper.ptr_to);
}
void callLuaAddedFunctionWhichCallsConstMember_passedConstantInstance_calledOnce()
{
ConstantMockHelper helper;
EXPECT_CALL(helper.mock, cpp_func_const()).Times(1);
m_lua->run_chunk("function Constant:lua_const_func() self:cpp_func_const() end "
"return function(object) object:lua_const_func() end ");
m_lua->call(1, helper.ptr_to_const);
}
void callLuaAddedFunctionWhichCallsConstMember_passedNoneConstantInstance_calledOnce()
{
ConstantMockHelper helper;
EXPECT_CALL(helper.mock, cpp_func_const()).Times(1);
m_lua->run_chunk("function Constant:lua_const_func() self:cpp_func_const() end "
"return function(object) object:lua_const_func() end ");
m_lua->call(1, helper.ptr_to_const);
}
void callLuaAddedFunctionWhichCallsNoneConstMember_passedNoneConstantInstance_calledOnce()
{
ConstantMockHelper helper;
EXPECT_CALL(helper.mock, cpp_func()).Times(1);
m_lua->run_chunk("function Constant:lua_func() self:cpp_func() end "
"return function(object) object:lua_func() end ");
m_lua->call(1, helper.ptr_to);
}
#if OOLUA_STORE_LAST_ERROR == 1
void callNoneConstantFunction_passedConstantInstance_callReturnsFalse()
{
ConstantMockHelper helper;
m_lua->run_chunk("return function(obj) obj:cpp_func() end");
CPPUNIT_ASSERT_EQUAL(false, m_lua->call(1, helper.ptr_to_const));
}
void callLuaAddedFunctionWhichCallsNoneConstMember_passedConstantInstance_callReturnsFalse()
{
ConstantMockHelper helper;
m_lua->run_chunk("function Constant:lua_func() self:cpp_func() end "
"return function(object) object:lua_func() end ");
CPPUNIT_ASSERT_EQUAL(false, m_lua->call(1, helper.ptr_to_const));
}
void callConstantMethodInBaseClass_usesConstantInstance_callReturnsTrue()
{
DerivesToUseConstMethod instance;
DerivesToUseConstMethod const* const_instance = &instance;
OOLUA::register_class<DerivesToUseConstMethod>(*m_lua);
m_lua->run_chunk("return function(obj) obj:cpp_func_const() end");
CPPUNIT_ASSERT_EQUAL(true, m_lua->call(1, const_instance));
}
#endif
#if OOLUA_USE_EXCEPTIONS == 1
void callNoneConstantFunction_passedConstantInstance_throwsRuntimeError()
{
ConstantMockHelper helper;
m_lua->run_chunk("return function(obj) obj:cpp_func() end");
CPPUNIT_ASSERT_THROW((m_lua->call(1, helper.ptr_to_const)), OOLUA::Runtime_error);
}
void callLuaAddedFunctionWhichCallsNoneConstMember_passedConstantInstance_callThrowsRuntimeError()
{
ConstantMockHelper helper;
m_lua->run_chunk("function Constant:lua_func() self:cpp_func() end "
"return function(object) object:lua_func() end ");
CPPUNIT_ASSERT_THROW((m_lua->call(1, helper.ptr_to_const)), OOLUA::Runtime_error);
}
void callConstantMethodInBaseClass_usesConstantInstance_noException()
{
DerivesToUseConstMethod instance;
DerivesToUseConstMethod const* const_instance = &instance;
OOLUA::register_class<DerivesToUseConstMethod>(*m_lua);
m_lua->run_chunk("return function(obj) obj:cpp_func_const() end");
CPPUNIT_ASSERT_NO_THROW(m_lua->call(1, const_instance));
}
#endif
};
CPPUNIT_TEST_SUITE_REGISTRATION(Constant_functions);
| 34.72067 | 108 | 0.799678 | SoapyMan |
98835bd12a610abbea1a7328c5aafd71d8410b7d | 2,339 | cc | C++ | icl/input_file_manager.cc | viettrungluu-cr/icl | 906eb067dee0084eee868d6f9d60f2eea393da4f | [
"BSD-3-Clause"
] | null | null | null | icl/input_file_manager.cc | viettrungluu-cr/icl | 906eb067dee0084eee868d6f9d60f2eea393da4f | [
"BSD-3-Clause"
] | null | null | null | icl/input_file_manager.cc | viettrungluu-cr/icl | 906eb067dee0084eee868d6f9d60f2eea393da4f | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "icl/input_file_manager.h"
#include <assert.h>
#include <memory>
#include <mutex>
#include <utility>
#include "icl/err.h"
#include "icl/input_file.h"
#include "icl/load_file.h"
#include "icl/source_file.h"
namespace icl {
struct InputFileManager::InputFileInfo {
InputFileInfo() = default;
~InputFileInfo() = default;
// This lock protects the unique_ptr. Once the input file is loaded (i.e.,
// |input_file| is non-null), it is const and can be accessed read-only
// outside of the lock.
std::mutex load_mutex;
// Even if loading fails, this will be set (with an error).
std::unique_ptr<const InputFile> input_file;
};
InputFileManager::InputFileManager(ReadFileFunction read_file_function)
: read_file_function_(std::move(read_file_function)) {}
InputFileManager::~InputFileManager() = default;
bool InputFileManager::GetFile(const LocationRange& origin,
const SourceFile& name,
const InputFile** file) {
// See if we have a cached load.
InputFileInfo* input_file_info = nullptr;
{
std::lock_guard<std::mutex> lock(input_files_mutex_);
std::unique_ptr<InputFileInfo>& info_ptr = input_files_[name];
if (!info_ptr)
info_ptr.reset(new InputFileInfo);
// Promote the InputFileInfo to outside of the input files lock.
input_file_info = info_ptr.get();
}
// Now use the per-input-file lock to block this thread if another thread is
// already processing the input file.
{
std::lock_guard<std::mutex> lock(input_file_info->load_mutex);
if (input_file_info->input_file) {
*file = input_file_info->input_file.get();
return (*file)->err().has_error();
}
if (!input_file_info->input_file) {
InputFile* f = new InputFile(name);
*file = f;
input_file_info->input_file.reset(f);
if (!LoadFile(read_file_function_, origin, name, f)) {
assert(f->err().has_error());
return false;
}
}
}
assert(input_file_info->input_file);
assert(*file == input_file_info->input_file.get());
assert(!(*file)->err().has_error());
return true;
}
} // namespace icl
| 28.876543 | 78 | 0.678068 | viettrungluu-cr |
988424b31efb92f9150e80d1211f8ead2b7755df | 2,137 | cc | C++ | agp-7.1.0-alpha01/tools/base/deploy/common/log.cc | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | null | null | null | agp-7.1.0-alpha01/tools/base/deploy/common/log.cc | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | null | null | null | agp-7.1.0-alpha01/tools/base/deploy/common/log.cc | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tools/base/deploy/common/log.h"
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <cstdio>
#include "tools/base/deploy/common/env.h"
namespace deploy {
void Log::V(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
Handle('V', fmt, args);
va_end(args);
}
void Log::D(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
Handle('D', fmt, args);
va_end(args);
}
void Log::I(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
Handle('I', fmt, args);
va_end(args);
}
void Log::W(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
Handle('W', fmt, args);
va_end(args);
}
void Log::E(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
Handle('E', fmt, args);
va_end(args);
}
void Log::T(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
Handle('I', fmt, args);
va_end(args);
}
void Log::Handle(const char level, const char* fmt, va_list args) {
if (Env::IsValid() && !Env::logcat().empty()) {
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_usec / 1000;
struct tm* timeinfo;
char time[1024];
timeinfo = localtime(&tp.tv_sec);
strftime(time, 1024, "%m-%d %T", timeinfo);
static int pid = getpid();
FILE* file = fopen(Env::logcat().c_str(), "ab+");
fprintf(file, "%s.%03ld %d %d %c %s: ", time, ms, pid, pid, level, kTag);
vfprintf(file, fmt, args);
fprintf(file, "\n");
fclose(file);
}
}
} // namespace deploy | 23.744444 | 79 | 0.639682 | jomof |
9884a4f7fbbb4d9bf9d9089281cc0f015b44c15e | 14,985 | cpp | C++ | preprocessing/meshing/gambit2netcdf/src/gambit2netcdf.cpp | fabian-kutschera/SeisSol | d5656cd38e9eb1d91c05ebcbf173acbc3083da57 | [
"BSD-3-Clause"
] | 165 | 2015-01-30T18:19:05.000Z | 2022-03-31T17:22:14.000Z | preprocessing/meshing/gambit2netcdf/src/gambit2netcdf.cpp | fabian-kutschera/SeisSol | d5656cd38e9eb1d91c05ebcbf173acbc3083da57 | [
"BSD-3-Clause"
] | 351 | 2015-10-06T15:06:48.000Z | 2022-03-30T11:23:13.000Z | preprocessing/meshing/gambit2netcdf/src/gambit2netcdf.cpp | fabian-kutschera/SeisSol | d5656cd38e9eb1d91c05ebcbf173acbc3083da57 | [
"BSD-3-Clause"
] | 96 | 2015-07-27T15:13:33.000Z | 2022-03-25T19:19:32.000Z | /**
* @file
* This file is part of SeisSol.
*
* @author Sebastian Rettenberger (rettenbs AT in.tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger,_M.Sc.)
*
* @section LICENSE
* Copyright (c) 2013, SeisSol Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
*/
#include <mpi.h>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <fstream>
#include <vector>
#include <netcdf.h>
#include <netcdf_par.h>
#include "mesh/GambitReader.h"
#include "utils/logger.h"
void checkNcError(int error)
{
if (error != NC_NOERR)
logError() << "Error while writing netCDF file:" << nc_strerror(error);
}
int main(int argc, char *argv[]) {
// Initialize MPI
MPI_Init(&argc, &argv);
int rank, procs;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &procs);
// Parse cmd line arguments
// TODO Use a more advanced tool here
if (argc != 4)
logError() << "Usage:" << argv[0] << "<mesh file> <partition file> <output netcdf>";
// Parse the partition once on rank 0 to get the number of partitions
int partInfo[2]; // Partition information (#partitions, max partition size)
if (rank == 0) {
std::ifstream partitionFile(argv[2]);
if (!partitionFile)
logError() << "Could not open partition file" << argv[2];
int p;
std::vector<int> partitionSizes;
while (!partitionFile.eof()) {
partitionFile >> p;
int oldSize = partitionSizes.size();
if (p+1 >= partitionSizes.size())
partitionSizes.resize(p+1);
for (int i = oldSize; i < partitionSizes.size(); i++)
partitionSizes[i] = 0;
partitionSizes[p]++;
// Skip white spaces
partitionFile >> std::ws;
}
logInfo() << "Found" << partitionSizes.size() << "partitions in" << argv[2];
partInfo[0] = partitionSizes.size();
partInfo[1] = *std::max_element(partitionSizes.begin(), partitionSizes.end());
}
// Broadcast partition information
MPI_Bcast(&partInfo, 2, MPI_INT, 0, MPI_COMM_WORLD);
// Create netcdf file
int ncFile;
checkNcError(nc_create_par(argv[3], NC_NETCDF4 | NC_MPIIO, MPI_COMM_WORLD, MPI_INFO_NULL, &ncFile));
// Create netcdf dimensions
int ncDimDimension;
nc_def_dim(ncFile, "dimension", 3, &ncDimDimension);
int ncDimPart;
nc_def_dim(ncFile, "partitions", partInfo[0], &ncDimPart);
int ncDimElem, ncDimElemSides, ncDimElemVertices;
nc_def_dim(ncFile, "elements", partInfo[1], &ncDimElem);
nc_def_dim(ncFile, "element_sides", 4, &ncDimElemSides);
nc_def_dim(ncFile, "element_vertices", 4, &ncDimElemVertices);
int ncDimVrtx;
nc_def_dim(ncFile, "vertices", NC_UNLIMITED, &ncDimVrtx);
int ncDimBnd, ncDimBndElem;
nc_def_dim(ncFile, "boundaries", NC_UNLIMITED, &ncDimBnd);
nc_def_dim(ncFile, "boundary_elements", NC_UNLIMITED, &ncDimBndElem);
// Create netcdf variables
int ncVarElemSize;
checkNcError(nc_def_var(ncFile, "element_size", NC_INT, 1, &ncDimPart, &ncVarElemSize));
checkNcError(nc_var_par_access(ncFile, ncVarElemSize, NC_COLLECTIVE));
int ncVarElemVertices;
int dimsElemVertices[] = {ncDimPart, ncDimElem, ncDimElemVertices};
checkNcError(nc_def_var(ncFile, "element_vertices", NC_INT, 3, dimsElemVertices, &ncVarElemVertices));
checkNcError(nc_var_par_access(ncFile, ncVarElemVertices, NC_COLLECTIVE));
int ncVarElemNeighbors;
int dimsElemSides[] = {ncDimPart, ncDimElem, ncDimElemSides};
checkNcError(nc_def_var(ncFile, "element_neighbors", NC_INT, 3, dimsElemSides, &ncVarElemNeighbors));
checkNcError(nc_var_par_access(ncFile, ncVarElemNeighbors, NC_COLLECTIVE));
int ncVarElemBoundaries;
checkNcError(nc_def_var(ncFile, "element_boundaries", NC_INT, 3, dimsElemSides, &ncVarElemBoundaries));
checkNcError(nc_var_par_access(ncFile, ncVarElemBoundaries, NC_COLLECTIVE));
int ncVarElemNeighborSides;
checkNcError(nc_def_var(ncFile, "element_neighbor_sides", NC_INT, 3, dimsElemSides, &ncVarElemNeighborSides));
checkNcError(nc_var_par_access(ncFile, ncVarElemNeighborSides, NC_COLLECTIVE));
int ncVarElemSideOrientations;
checkNcError(nc_def_var(ncFile, "element_side_orientations", NC_INT, 3, dimsElemSides, &ncVarElemSideOrientations));
checkNcError(nc_var_par_access(ncFile, ncVarElemSideOrientations, NC_COLLECTIVE));
int ncVarElemNeighborRanks;
checkNcError(nc_def_var(ncFile, "element_neighbor_ranks", NC_INT, 3, dimsElemSides, &ncVarElemNeighborRanks));
checkNcError(nc_var_par_access(ncFile, ncVarElemNeighborRanks, NC_COLLECTIVE));
int ncVarElemMPIIndices;
checkNcError(nc_def_var(ncFile, "element_mpi_indices", NC_INT, 3, dimsElemSides, &ncVarElemMPIIndices));
checkNcError(nc_var_par_access(ncFile, ncVarElemMPIIndices, NC_COLLECTIVE));
int ncVarVrtxSize;
checkNcError(nc_def_var(ncFile, "vertex_size", NC_INT, 1, &ncDimPart, &ncVarVrtxSize));
checkNcError(nc_var_par_access(ncFile, ncVarVrtxSize, NC_COLLECTIVE));
int ncVarVrtxCoords;
int dimsVrtxCoords[] = {ncDimPart, ncDimVrtx, ncDimDimension};
checkNcError(nc_def_var(ncFile, "vertex_coordinates", NC_DOUBLE, 3, dimsVrtxCoords, &ncVarVrtxCoords));
checkNcError(nc_var_par_access(ncFile, ncVarVrtxCoords, NC_COLLECTIVE));
int ncVarBndSize;
checkNcError(nc_def_var(ncFile, "boundary_size", NC_INT, 1, &ncDimPart, &ncVarBndSize));
checkNcError(nc_var_par_access(ncFile, ncVarBndSize, NC_COLLECTIVE));
int ncVarBndElemSize;
int dimsBndElemSize[] = {ncDimPart, ncDimBnd};
checkNcError(nc_def_var(ncFile, "boundary_element_size", NC_INT, 2, dimsBndElemSize, &ncVarBndElemSize));
checkNcError(nc_var_par_access(ncFile, ncVarBndElemSize, NC_COLLECTIVE));
int ncVarBndElemRank;
checkNcError(nc_def_var(ncFile, "boundary_element_rank", NC_INT, 2, dimsBndElemSize, &ncVarBndElemRank));
checkNcError(nc_var_par_access(ncFile, ncVarBndElemRank, NC_COLLECTIVE));
int ncVarBndElemLocalIds;
int dimsBndElemLocalIds[] = {ncDimPart, ncDimBnd, ncDimBndElem};
checkNcError(nc_def_var(ncFile, "boundary_element_localids", NC_INT, 3, dimsBndElemLocalIds, &ncVarBndElemLocalIds));
checkNcError(nc_var_par_access(ncFile, ncVarBndElemLocalIds, NC_COLLECTIVE));
// Start writing data
checkNcError(nc_enddef(ncFile));
// Variable buffers
ElemVertices* elemVertices = new ElemVertices[partInfo[1]];
ElemNeighbors* elemNeighbors = new ElemNeighbors[partInfo[1]];
ElemNeighborSides* elemNeighborSides = new ElemNeighborSides[partInfo[1]];
ElemSideOrientations* elemSideOrientations = new ElemSideOrientations[partInfo[1]];
ElemBoundaries* elemBoundaries = new ElemBoundaries[partInfo[1]];
ElemNeighborRanks* elemNeighborRanks = new ElemNeighborRanks[partInfo[1]];
ElemMPIIndices* elemMPIIndices = new ElemMPIIndices[partInfo[1]];
int i;
for (i = rank; i < partInfo[0]; i += procs) {
logInfo() << "Start mesh reconstruction for partition" << i;
GambitReader gambitReader(i, argv[1], argv[2]);
logInfo() << "Start writing mesh information for partition" << i;
// Elements
const std::vector<Element> elements = gambitReader.getElements();
assert(elements.size() <= partInfo[1]);
// Copy element values into buffers
for (int j = 0; j < elements.size(); j++) {
memcpy(&elemVertices[j], elements[j].vertices, sizeof(ElemVertices));
memcpy(&elemNeighbors[j], elements[j].neighbors, sizeof(ElemNeighbors));
memcpy(&elemNeighborSides[j], elements[j].neighborSides, sizeof(ElemNeighborSides));
memcpy(&elemSideOrientations[j], elements[j].sideOrientations, sizeof(ElemSideOrientations));
memcpy(&elemBoundaries[j], elements[j].boundaries, sizeof(ElemBoundaries));
memcpy(&elemNeighborRanks[j], elements[j].neighborRanks, sizeof(ElemNeighborRanks));
memcpy(&elemMPIIndices[j], elements[j].mpiIndices, sizeof(ElemMPIIndices));
}
// Write element buffers to netcdf
size_t start[3] = {i, 0, 0};
int size = elements.size();
checkNcError(nc_put_var1_int(ncFile, ncVarElemSize, start, &size));
size_t count[3] = {1, size, 4};
checkNcError(nc_put_vara_int(ncFile, ncVarElemVertices, start, count, reinterpret_cast<int*>(elemVertices)));
checkNcError(nc_put_vara_int(ncFile, ncVarElemNeighbors, start, count, reinterpret_cast<int*>(elemNeighbors)));
checkNcError(nc_put_vara_int(ncFile, ncVarElemNeighborSides, start, count, reinterpret_cast<int*>(elemNeighborSides)));
checkNcError(nc_put_vara_int(ncFile, ncVarElemSideOrientations, start, count, reinterpret_cast<int*>(elemSideOrientations)));
checkNcError(nc_put_vara_int(ncFile, ncVarElemBoundaries, start, count, reinterpret_cast<int*>(elemBoundaries)));
checkNcError(nc_put_vara_int(ncFile, ncVarElemNeighborRanks, start, count, reinterpret_cast<int*>(elemNeighborRanks)));
checkNcError(nc_put_vara_int(ncFile, ncVarElemMPIIndices, start, count, reinterpret_cast<int*>(elemMPIIndices)));
// Vertices
const std::vector<Vertex> vertices = gambitReader.getVertices();
VrtxCoords* vrtxCoords = new VrtxCoords[vertices.size()];
// Copy vertex values into buffers
for (int j = 0; j < vertices.size(); j++) {
memcpy(&vrtxCoords[j], vertices[j].coords, sizeof(VrtxCoords));
}
// Write vertex buffer to netcdf
size = vertices.size();
checkNcError(nc_put_var1_int(ncFile, ncVarVrtxSize, start, &size));
count[0] = 1; count[1] = size; count[2] = 3;
checkNcError(nc_put_vara_double(ncFile, ncVarVrtxCoords, start, count, reinterpret_cast<double*>(vrtxCoords)));
delete [] vrtxCoords;
// Boundaries (MPI neighbors)
const std::map<int, MPINeighbor> mpiNeighbors = gambitReader.getMPINeighbors();
// Get maximum number of neighbors (required to get collective MPI-IO right)
int maxNeighbors = mpiNeighbors.size();
MPI_Allreduce(MPI_IN_PLACE, &maxNeighbors, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
// Write number of boundaries to netcdf
size = mpiNeighbors.size();
checkNcError(nc_put_var1_int(ncFile, ncVarBndSize, start, &size));
int j = 0;
for (std::map<int, MPINeighbor>::const_iterator iter = mpiNeighbors.begin();
iter != mpiNeighbors.end(); iter++, j++) {
size_t bndStart[3] = {i, j, 0};
// Write size of this boundary to netcdf
int elemSize = iter->second.elements.size();
checkNcError(nc_put_var1_int(ncFile, ncVarBndElemSize, bndStart, &elemSize));
// Write neighbor rank to netcdf
int bndRank = iter->first;
checkNcError(nc_put_var1_int(ncFile, ncVarBndElemRank, bndStart, &bndRank));
// Max sure rank resizes the netCDF dimension
// -> everybody has to write maxBndElements
int maxBndElements = iter->second.elements.size();
MPI_Allreduce(MPI_IN_PLACE, &maxBndElements, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
// Copy local element ids to buffer
int* bndElemLocalIds = new int[maxBndElements];
for (int k = 0; k < iter->second.elements.size(); k++) {
bndElemLocalIds[k] = iter->second.elements[k].localElement;
}
// Write local element ids to netcdf
size_t bndCount[3] = {1, 1, maxBndElements};
checkNcError(nc_put_vara_int(ncFile, ncVarBndElemLocalIds, bndStart, bndCount, bndElemLocalIds));
delete [] bndElemLocalIds;
}
for (; j < maxNeighbors; j++) {
size_t bndStart[3] = {i, j, 0};
// Write some dummy values so netCDF run into a deadlock
int bndSize = 0;
checkNcError(nc_put_var1_int(ncFile, ncVarBndElemSize, bndStart, &bndSize));
int bndRank = 0;
checkNcError(nc_put_var1_int(ncFile, ncVarBndElemRank, bndStart, &bndRank));
// -> everybody has to write maxBndElements
int maxBndElements = 0;
MPI_Allreduce(MPI_IN_PLACE, &maxBndElements, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
int* bndElemLocalIds = new int[maxBndElements];
size_t bndCount[3] = {1, 1, maxBndElements};
checkNcError(nc_put_vara(ncFile, ncVarBndElemLocalIds, bndStart, bndCount, bndElemLocalIds));
delete [] bndElemLocalIds;
}
}
// Some processors may idle during the last iteration
if (i - rank < partInfo[0] && i >= partInfo[0]) {
size_t start[3] = {0, 0, 0};
size_t count[3] = {0, 0, 0};
checkNcError(nc_put_vara_int(ncFile, ncVarElemSize, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarElemVertices, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarElemNeighbors, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarElemNeighborSides, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarElemSideOrientations, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarElemBoundaries, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarElemNeighborRanks, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarElemMPIIndices, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarVrtxSize, start, count, 0L));
checkNcError(nc_put_vara_double(ncFile, ncVarVrtxCoords, start, count, 0L));
int maxNeighbors = 0;
MPI_Allreduce(MPI_IN_PLACE, &maxNeighbors, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
checkNcError(nc_put_vara_int(ncFile, ncVarBndSize, start, count, 0L));
for (int j = 0; j < maxNeighbors; j++) {
checkNcError(nc_put_vara_int(ncFile, ncVarBndElemSize, start, count, 0L));
checkNcError(nc_put_vara_int(ncFile, ncVarBndElemRank, start, count, 0L));
int maxBndElements = 0;
MPI_Allreduce(MPI_IN_PLACE, &maxBndElements, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
checkNcError(nc_put_vara_int(ncFile, ncVarBndElemLocalIds, start, count, 0L));
}
}
// Free buffers
delete [] elemVertices;
delete [] elemNeighbors;
delete [] elemNeighborSides;
delete [] elemSideOrientations;
delete [] elemBoundaries;
delete [] elemNeighborRanks;
delete [] elemMPIIndices;
// Close netcdf file
checkNcError(nc_close(ncFile));
// Cleanup MPI
MPI_Finalize();
}
| 41.054795 | 127 | 0.752152 | fabian-kutschera |
9884a740251508860f65340c7387fc41163c513b | 306 | cc | C++ | math/453.cc | MingfeiPan/leetcode | 55dc878cfb7b15a34252410ae7420a656da604f8 | [
"Apache-2.0"
] | null | null | null | math/453.cc | MingfeiPan/leetcode | 55dc878cfb7b15a34252410ae7420a656da604f8 | [
"Apache-2.0"
] | null | null | null | math/453.cc | MingfeiPan/leetcode | 55dc878cfb7b15a34252410ae7420a656da604f8 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int minMoves(vector<int>& nums) {
int min = nums[0];
for (const auto &num : nums) {
min = std::min(min, num);
}
int ret = 0;
for (const auto &num : nums) {
ret += num - min;
}
return ret;
}
};
| 20.4 | 38 | 0.431373 | MingfeiPan |
98854f72a0dae86d558a5c2a641d0428297072bb | 2,715 | cpp | C++ | tests/test_for_Status.cpp | PGZXB/PGBigNumber | a0f128a0b415bd1a63929c55c2f952205c1a59df | [
"MIT"
] | 2 | 2021-10-25T23:56:54.000Z | 2022-01-02T06:35:49.000Z | tests/test_for_Status.cpp | PGZXB/PGBigNumber | a0f128a0b415bd1a63929c55c2f952205c1a59df | [
"MIT"
] | 1 | 2021-11-12T09:03:39.000Z | 2021-12-27T02:03:41.000Z | tests/test_for_Status.cpp | PGZXB/PGBigNumber | a0f128a0b415bd1a63929c55c2f952205c1a59df | [
"MIT"
] | null | null | null | #include "Status.h"
#include <iostream>
#define STATUS (*pgbn::Status::getInstance())
std::int8_t a = 0, b = 0;
std::int8_t c = 0;
enum class CALCU_STATUS : pgbn::Enum {
SUCCESS,
DIV_ZERO_ERR,
ADD_OVERFLOW_ERR,
SUB_OVERFLOW_ERR,
ADD_GLOB_A_AND_B_ERROR,
};
#define TO_ENUM(val) static_cast<pgbn::Enum>(val)
std::int8_t add(std::int8_t a, std::int8_t b) {
std::int8_t res = a + b;
if (
(a > 0 && b > 0 && res <= 0) ||
(a < 0 && b < 0 && res >= 0)
) STATUS = TO_ENUM(CALCU_STATUS::ADD_OVERFLOW_ERR);
else {
STATUS = TO_ENUM(CALCU_STATUS::SUCCESS);
}
return res;
}
void add(std::int8_t a, std::int8_t b, std::int8_t & res) {
res = a + b;
if (
(a > 0 && b > 0 && res <= 0) ||
(a < 0 && b < 0 && res >= 0)
) STATUS = TO_ENUM(CALCU_STATUS::ADD_GLOB_A_AND_B_ERROR);
else {
STATUS = TO_ENUM(CALCU_STATUS::SUCCESS);
}
}
std::int8_t sub(std::int8_t a, std::int8_t b) {
std::int8_t res = a - b;
if (
(a > 0 && b < 0 && res <= 0) ||
(a < 0 && b > 0 && res >= 0)
) STATUS = TO_ENUM(CALCU_STATUS::SUB_OVERFLOW_ERR);
else {
STATUS = TO_ENUM(CALCU_STATUS::SUCCESS);
}
return res;
}
std::int8_t divide(std::int8_t a, std::int8_t b) {
if (b == 0) STATUS = TO_ENUM(CALCU_STATUS::DIV_ZERO_ERR);
else STATUS = TO_ENUM(CALCU_STATUS::SUCCESS);
return a / b;
}
void err_output(pgbn::Enum err_no) {
std::cerr << err_no << " : " << pgbn::Status::getInfo(err_no) << '\n';
}
void add_err(std::int8_t & a, std::int8_t & b, std::int8_t & c) {
std::cerr << "Calcu " << (int)a << " + " << (int)b << " = " << (int)c << " Error\n";
err_output(
static_cast<pgbn::Enum>(CALCU_STATUS::ADD_GLOB_A_AND_B_ERROR)
);
}
void err_exit(pgbn::Enum err_no) {
err_output(err_no);
std::cerr << "Exiting---\n";
exit(-1);
}
void test() {
std::cerr << "TEST\n";
}
#define REG pgbn::Status::registe
int main () {
// // 注册错误码
REG(CALCU_STATUS::SUCCESS, "SUCCESS");
REG(CALCU_STATUS::ADD_OVERFLOW_ERR, "Add Overflow\n", err_output, TO_ENUM(CALCU_STATUS::ADD_OVERFLOW_ERR));
REG(CALCU_STATUS::SUB_OVERFLOW_ERR, "Sub Overflow\n", err_output, TO_ENUM(CALCU_STATUS::SUB_OVERFLOW_ERR));
REG(CALCU_STATUS::ADD_GLOB_A_AND_B_ERROR, "Add a And b Error\n", add_err, std::ref<int8_t>(a), std::ref<int8_t>(b), std::ref<int8_t>(c));
REG(CALCU_STATUS::DIV_ZERO_ERR, "DIV 0 Error", err_exit, TO_ENUM(CALCU_STATUS::DIV_ZERO_ERR));
add(1, 2); // success
add(100, 100); // overflow
sub(2, 4); // success
sub(100, -100); // overflow
a = b = 100;
add(a, b, c); // error
divide(1, 0);
return 0;
}
| 24.241071 | 141 | 0.580479 | PGZXB |
98877f9748bf6d391328816228d16d81cad82645 | 741 | hpp | C++ | libraries/CMakeServerConnector/include/Messages/HandshakeRequest.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | null | null | null | libraries/CMakeServerConnector/include/Messages/HandshakeRequest.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | null | null | null | libraries/CMakeServerConnector/include/Messages/HandshakeRequest.hpp | Megaxela/HGEngineReloadedEditor | be79b6089985da1bf811be8a6d06ce25f71236b1 | [
"MIT"
] | 1 | 2020-03-12T04:39:14.000Z | 2020-03-12T04:39:14.000Z | #pragma once
#include <Messages/BasicMessage.hpp>
#include <Version.hpp>
#include <Messages/Register.hpp>
struct HandshakeRequest : public BasicMessage
{
HandshakeRequest() :
sourceDirectory(),
buildDirectory(),
generator(),
protocolVersion()
{
type = Messages::Type::HandshakeRequest;
}
static nlohmann::json serialize(const BasicMessage &msg);
std::string sourceDirectory;
std::string buildDirectory;
std::string generator;
Version protocolVersion;
};
namespace
{
Messages::Registrator<HandshakeRequest> HandshakeRequestRegistrator(
"handshake",
Messages::Type::HandshakeRequest,
&HandshakeRequest::serialize,
nullptr
);
} | 21.794118 | 72 | 0.672065 | Megaxela |
9889bf9696f91fd329ecd68c9de7357a14aef235 | 35,135 | cpp | C++ | windows/oleacc/oleacc/client.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/oleacc/oleacc/client.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/oleacc/oleacc/client.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // Copyright (c) 1996-1999 Microsoft Corporation
// --------------------------------------------------------------------------
//
// CLIENT.CPP
//
// Window client class.
//
// This handles navigation to other frame elements, and does its best
// to manage the client area. We recognize special classes, like listboxes,
// and those have their own classes to do stuff.
//
// --------------------------------------------------------------------------
#include "oleacc_p.h"
#include "default.h"
#include "classmap.h"
#include "ctors.h"
#include "window.h"
#include "client.h"
#include "debug.h"
#define CH_PREFIX ((TCHAR)'&')
#define CCH_WINDOW_SHORTCUTMAX 32
#define CCH_SHORTCUT 16
extern HRESULT DirNavigate(HWND, long, VARIANT *);
// --------------------------------------------------------------------------
//
// CreateClientObject()
//
// EXTERNAL function for CreatStdOle...
//
// --------------------------------------------------------------------------
HRESULT CreateClientObject(HWND hwnd, long idObject, REFIID riid, void** ppvObject)
{
UNUSED(idObject);
InitPv(ppvObject);
if (!IsWindow(hwnd))
return(E_FAIL);
// Look for (and create) a suitable proxy/handler if one
// exists. Use CreateClient as default if none found.
// (FALSE => use client, as opposed to window, classes)
return FindAndCreateWindowClass( hwnd, FALSE, CLASS_ClientObject,
OBJID_CLIENT, 0, riid, ppvObject );
}
// --------------------------------------------------------------------------
//
// CreateClient()
//
// INTERNAL function for CreateClientObject() and ::Clone()
//
// --------------------------------------------------------------------------
HRESULT CreateClient(HWND hwnd, long idChildCur, REFIID riid, void** ppvObject)
{
CClient * pclient;
HRESULT hr;
pclient = new CClient();
if (!pclient)
return(E_OUTOFMEMORY);
pclient->Initialize(hwnd, idChildCur);
hr = pclient->QueryInterface(riid, ppvObject);
if (!SUCCEEDED(hr))
delete pclient;
return(hr);
}
// --------------------------------------------------------------------------
//
// CClient::Initialize()
//
// --------------------------------------------------------------------------
void CClient::Initialize(HWND hwnd, long idChildCur)
{
m_hwnd = hwnd;
m_idChildCur = idChildCur;
// If this is a comboex32, we want to pick up a preceeding
// label, if one exists (just like we do for regular combos -
// which set m_fUseLabel to TRUE in their own ::Initialize().
// The combo will ask the parent comboex32 for its name, and
// it in turn will look for a label.
if( IsComboEx( m_hwnd ) )
{
m_fUseLabel = TRUE;
}
}
// --------------------------------------------------------------------------
//
// CClient::ValidateHwnd()
//
// This will validate VARIANTs for both HWND-children clients and normal
// clients. If m_cChildren is non-zero,
//
// --------------------------------------------------------------------------
BOOL CClient::ValidateHwnd(VARIANT* pvar)
{
HWND hwndChild;
switch (pvar->vt)
{
case VT_ERROR:
if (pvar->scode != DISP_E_PARAMNOTFOUND)
return(FALSE);
// FALL THRU
case VT_EMPTY:
pvar->vt = VT_I4;
pvar->lVal = 0;
break;
#ifdef VT_I2_IS_VALID // It should not be valid. That's why this is removed.
case VT_I2:
pvar->vt = VT_I4;
pvar->lVal = (long)pvar->iVal;
// FALL THROUGH
#endif
case VT_I4:
if (pvar->lVal == 0)
break;
hwndChild = HwndFromHWNDID(m_hwnd, pvar->lVal);
// This works for top-level AND child windows
if (MyGetAncestor(hwndChild, GA_PARENT) != m_hwnd)
return(FALSE);
break;
default:
return(FALSE);
}
return(TRUE);
}
// --------------------------------------------------------------------------
//
// CClient::get_accChildCount()
//
// This handles both non-HWND and HWND children.
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::get_accChildCount(long *pcCount)
{
HWND hwndChild;
HRESULT hr;
hr = CAccessible::get_accChildCount(pcCount);
if (!SUCCEEDED(hr))
return hr;
// popup menus (CMenuPopup) can have a NULL hwnd if created for an 'invisible'
// menu. We probably shouldn't create them in the first place, but don't want
// to change what objects we expose at this stage - so instead special case
// NULL. This is to avoid calling GetWindow( NULL ), which would produce
// debug output complaining, and those annoy the stress team.
if( m_hwnd != NULL )
{
for (hwndChild = ::GetWindow(m_hwnd, GW_CHILD); hwndChild; hwndChild = ::GetWindow(hwndChild, GW_HWNDNEXT))
++(*pcCount);
}
return S_OK;
}
// --------------------------------------------------------------------------
//
// CClient::get_accName()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::get_accName(VARIANT varChild, BSTR *pszName)
{
InitPv(pszName);
//
// Validate--this does NOT accept a child ID.
//
if (! ValidateChild(&varChild))
return(E_INVALIDARG);
return(HrGetWindowName(m_hwnd, m_fUseLabel, pszName));
}
// --------------------------------------------------------------------------
//
// CClient::get_accRole()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::get_accRole(VARIANT varChild, VARIANT *pvarRole)
{
InitPvar(pvarRole);
//
// Validate--this does NOT accept a child ID.
//
if (!ValidateChild(&varChild))
return(E_INVALIDARG);
pvarRole->vt = VT_I4;
pvarRole->lVal = ROLE_SYSTEM_CLIENT;
return(S_OK);
}
// --------------------------------------------------------------------------
//
// CClient::get_accState()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::get_accState(VARIANT varChild, VARIANT *pvarState)
{
WINDOWINFO wi;
HWND hwndActive;
InitPvar(pvarState);
//
// Validate--this does NOT accept a child ID.
//
if (!ValidateChild(&varChild))
return(E_INVALIDARG);
pvarState->vt = VT_I4;
pvarState->lVal = 0;
//
// Are we the focus? Are we enabled, visible, etc?
//
if (!MyGetWindowInfo(m_hwnd, &wi))
{
pvarState->lVal |= STATE_SYSTEM_INVISIBLE;
return(S_OK);
}
if (!(wi.dwStyle & WS_VISIBLE))
pvarState->lVal |= STATE_SYSTEM_INVISIBLE;
if (wi.dwStyle & WS_DISABLED)
pvarState->lVal |= STATE_SYSTEM_UNAVAILABLE;
if (MyGetFocus() == m_hwnd)
pvarState->lVal |= STATE_SYSTEM_FOCUSED;
hwndActive = GetForegroundWindow();
if (hwndActive == MyGetAncestor(m_hwnd, GA_ROOT))
pvarState->lVal |= STATE_SYSTEM_FOCUSABLE;
return(S_OK);
}
// --------------------------------------------------------------------------
//
// CClient::get_accKeyboardShortcut()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::get_accKeyboardShortcut(VARIANT varChild, BSTR* pszShortcut)
{
InitPv(pszShortcut);
//
// Validate--this does NOT accept a child ID
//
if (!ValidateChild(&varChild))
return(E_INVALIDARG);
// reject child elements - shortcut key only applies to the overall
// control.
if ( varChild.lVal != 0 )
return(E_NOT_APPLICABLE);
return(HrGetWindowShortcut(m_hwnd, m_fUseLabel, pszShortcut));
}
// --------------------------------------------------------------------------
//
// CClient::get_accFocus()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::get_accFocus(VARIANT *pvarFocus)
{
HWND hwndFocus;
InitPvar(pvarFocus);
//
// This RETURNS a child ID.
//
hwndFocus = MyGetFocus();
//
// Is the current focus a child of us?
//
if (m_hwnd == hwndFocus)
{
pvarFocus->vt = VT_I4;
pvarFocus->lVal = 0;
}
else if (IsChild(m_hwnd, hwndFocus))
return(GetWindowObject(hwndFocus, pvarFocus));
return(S_OK);
}
// --------------------------------------------------------------------------
//
// CClient::accLocation()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::accLocation(long* pxLeft, long* pyTop,
long* pcxWidth, long* pcyHeight, VARIANT varChild)
{
RECT rc;
InitAccLocation(pxLeft, pyTop, pcxWidth, pcyHeight);
//
// Validate--this does NOT take a child ID
//
if (!ValidateChild(&varChild))
return(E_INVALIDARG);
MyGetRect(m_hwnd, &rc, FALSE);
MapWindowPoints(m_hwnd, NULL, (LPPOINT)&rc, 2);
*pxLeft = rc.left;
*pyTop = rc.top;
*pcxWidth = rc.right - rc.left;
*pcyHeight = rc.bottom - rc.top;
return(S_OK);
}
// --------------------------------------------------------------------------
//
// CClient::accSelect()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::accSelect( long lSelFlags, VARIANT varChild )
{
if( ! ValidateChild( & varChild ) ||
! ValidateSelFlags( lSelFlags ) )
return E_INVALIDARG;
if( lSelFlags != SELFLAG_TAKEFOCUS )
return E_NOT_APPLICABLE;
if( varChild.lVal )
return S_FALSE;
MySetFocus( m_hwnd );
return S_OK;
}
// --------------------------------------------------------------------------
//
// CClient::accNavigate()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::accNavigate(long dwNavDir, VARIANT varStart, VARIANT * pvarEnd)
{
HWND hwndChild;
int gww;
InitPvar(pvarEnd);
//
// Validate--this accepts an HWND id.
//
if (!ValidateHwnd(&varStart) ||
!ValidateNavDir(dwNavDir, varStart.lVal))
return(E_INVALIDARG);
if (dwNavDir == NAVDIR_FIRSTCHILD)
{
gww = GW_HWNDNEXT;
hwndChild = ::GetWindow(m_hwnd, GW_CHILD);
if (!hwndChild)
return(S_FALSE);
goto NextPrevChild;
}
else if (dwNavDir == NAVDIR_LASTCHILD)
{
gww = GW_HWNDPREV;
hwndChild = ::GetWindow(m_hwnd, GW_CHILD);
if (!hwndChild)
return(S_FALSE);
// Start at the end and work backwards
hwndChild = ::GetWindow(hwndChild, GW_HWNDLAST);
goto NextPrevChild;
}
else if (!varStart.lVal)
return(GetParentToNavigate(OBJID_CLIENT, m_hwnd, OBJID_WINDOW,
dwNavDir, pvarEnd));
hwndChild = HwndFromHWNDID(m_hwnd, varStart.lVal);
if ((dwNavDir == NAVDIR_NEXT) || (dwNavDir == NAVDIR_PREVIOUS))
{
gww = ((dwNavDir == NAVDIR_NEXT) ? GW_HWNDNEXT : GW_HWNDPREV);
while (hwndChild = ::GetWindow(hwndChild, gww))
{
NextPrevChild:
if (IsWindowVisible(hwndChild))
return(GetWindowObject(hwndChild, pvarEnd));
}
}
else
return(DirNavigate(hwndChild, dwNavDir, pvarEnd));
return(S_FALSE);
}
// --------------------------------------------------------------------------
//
// CClient::accHitTest()
//
// This ALWAYS returns a real object.
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::accHitTest(long xLeft, long yTop, VARIANT *pvarHit)
{
HWND hwndChild;
POINT pt;
InitPvar(pvarHit);
pt.x = xLeft;
pt.y = yTop;
ScreenToClient(m_hwnd, &pt);
hwndChild = MyRealChildWindowFromPoint(m_hwnd, pt);
if (hwndChild)
{
if (hwndChild == m_hwnd)
{
pvarHit->vt = VT_I4;
pvarHit->lVal = 0;
return(S_OK);
}
else
return(GetWindowObject(hwndChild, pvarHit));
}
else
{
// Null window means point isn't in us at all...
return(S_FALSE);
}
}
// --------------------------------------------------------------------------
//
// CClient::Next()
//
// This loops through non-HWND children first, then HWND children.
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::Next(ULONG celt, VARIANT *rgvar, ULONG* pceltFetched)
{
HWND hwndChild;
VARIANT* pvar;
long cFetched;
HRESULT hr;
if( m_idChildCur == -1 )
{
// If we're at the end, can't return any more...
*pceltFetched = 0;
return celt == 0 ? S_OK : S_FALSE;
}
SetupChildren();
// Can be NULL
if (pceltFetched)
*pceltFetched = 0;
// Grab the non-HWND dudes first.
if (!IsHWNDID(m_idChildCur) && (m_idChildCur < m_cChildren))
{
cFetched = 0;
hr = CAccessible::Next(celt, rgvar, (ULONG*)&cFetched);
if (!SUCCEEDED(hr))
return hr;
celt -= cFetched;
rgvar += cFetched;
if (pceltFetched)
*pceltFetched += cFetched;
if (!celt)
return S_OK;
}
pvar = rgvar;
cFetched = 0;
if (!IsHWNDID(m_idChildCur))
{
Assert(m_idChildCur == m_cChildren);
hwndChild = ::GetWindow(m_hwnd, GW_CHILD);
}
else
{
hwndChild = HwndFromHWNDID(m_hwnd, m_idChildCur);
}
//
// Loop through our HWND children now
//
while (hwndChild && (cFetched < (long)celt))
{
hr = GetWindowObject(hwndChild, pvar);
if (SUCCEEDED(hr))
{
++pvar;
++cFetched;
}
else
{
// Failed - skip this one - but keep going.
TraceWarningHR( hr, TEXT("CClient::Next - GetWindowObject failed on hwnd 0x%p, skipping"), hwndChild );
}
hwndChild = ::GetWindow(hwndChild, GW_HWNDNEXT);
}
// Remember current position
// Have to special-case NULL - GetWindow(...) returns NULL
// when we reach the end - have to store a special value
// so we know that we're at the end the next time we're
// called.
if( hwndChild == NULL )
m_idChildCur = -1;
else
m_idChildCur = HWNDIDFromHwnd(m_hwnd, hwndChild);
//
// Fill in the number fetched
//
if (pceltFetched)
*pceltFetched += cFetched;
//
// Return S_FALSE if we grabbed fewer items than requested
//
return (cFetched < (long)celt) ? S_FALSE : S_OK;
}
// --------------------------------------------------------------------------
//
// CClient::Skip()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::Skip(ULONG celt)
{
HWND hwndT;
if( m_idChildCur == -1 )
{
// If we're at the end, can't return any more...
return celt == 0 ? S_FALSE : S_OK;
}
SetupChildren();
// Skip non-HWND items
if (!IsHWNDID(m_idChildCur) && (m_idChildCur < m_cChildren))
{
long dAway;
dAway = m_cChildren - m_idChildCur;
if (celt >= (DWORD)dAway)
{
celt -= dAway;
m_idChildCur = m_cChildren;
}
else
{
m_idChildCur += celt;
return S_OK;
}
}
// Skip the HWND children next
if (!IsHWNDID(m_idChildCur))
{
Assert(m_idChildCur == m_cChildren);
hwndT = ::GetWindow(m_hwnd, GW_CHILD);
}
else
hwndT = HwndFromHWNDID(m_hwnd, m_idChildCur);
while (hwndT && (celt-- > 0))
{
hwndT = ::GetWindow(hwndT, GW_HWNDNEXT);
}
// Remember current position
// Have to special-case NULL - GetWindow(...) returns NULL
// when we reach the end - have to store a special value
// so we know that we're at the end the next time we're
// called.
if( hwndT == NULL )
m_idChildCur = -1;
else
m_idChildCur = HWNDIDFromHwnd(m_hwnd, hwndT);
return celt ? S_FALSE : S_OK;
}
// --------------------------------------------------------------------------
//
// CClient::Reset()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::Reset(void)
{
m_idChildCur = 0;
return S_OK;
}
// --------------------------------------------------------------------------
//
// CClient::Clone()
//
// --------------------------------------------------------------------------
STDMETHODIMP CClient::Clone(IEnumVARIANT** ppenum)
{
InitPv(ppenum);
// Look for (and create) a suitable proxy/handler if one
// exists. Use CreateClient as default if none found.
// (FALSE => use client, as opposed to window, classes)
return FindAndCreateWindowClass( m_hwnd, FALSE, CLASS_ClientObject,
OBJID_CLIENT, m_idChildCur, IID_IEnumVARIANT, (void **)ppenum );
}
// --------------------------------------------------------------------------
//
// GetTextString()
//
// Parameters: hwnd of the window to get the text from, and a boolean
// that indicates whether or not we should always allocate memory to
// return. I.E., if the window says the size of the text is 0, and
// fAllocIfEmpty is TRUE, then we'll still allocate 1 byte (size+1).
//
// This contains a bit of a hack. The way it was originally written, this
// will try to get the ENTIRE text of say, a RichEdit control, even if that
// document is HUGE. Eventually we want to support that, but we are going to
// need to do better than LocalAlloc. With a big document, we would page
// fault sometimes, because even though the memory is allocated, it
// may not be able to be paged in. JeffBog suggested that the way to
// check is to try to read/write both ends of the allocated space, and
// assume that if that works everything in between is OK too.
//
// So here's the temporary hack (BOGUS!)
// I am putting an artificial limit of 4096 bytes on the allocation.
// I am also going to do IsBadWritePtr on the thing, instead of just
// checking if the pointer returned by alloc is null. duh.
// --------------------------------------------------------------------------
LPTSTR GetTextString(HWND hwnd, BOOL fAllocIfEmpty)
{
UINT cchText;
LPTSTR lpText;
#define MAX_TEXT_SIZE 4096
//
// Look for a name property!
//
lpText = NULL;
if (!IsWindow(hwnd))
return (NULL);
//
// Barring that, use window text.
// BOGUS! Strip out the '&'.
//
cchText = SendMessageINT(hwnd, WM_GETTEXTLENGTH, 0, 0);
// hack
cchText = (cchText > MAX_TEXT_SIZE ? MAX_TEXT_SIZE : cchText);
// Allocate a buffer
if (cchText || fAllocIfEmpty)
{
lpText = (LPTSTR)LocalAlloc(LPTR, (cchText+1)*sizeof(TCHAR));
if (IsBadWritePtr (lpText,cchText+1))
return(NULL);
if (cchText)
SendMessage(hwnd, WM_GETTEXT, cchText+1, (LPARAM)lpText);
}
return(lpText);
}
// --------------------------------------------------------------------------
//
// GetLabelString()
//
// This walks backwards among peer windows to find a static field. It stops
// if it gets to the front or hits a group/tabstop, just like the dialog
// manager does.
//
// --------------------------------------------------------------------------
LPTSTR GetLabelString(HWND hwnd)
{
HWND hwndLabel;
LONG lStyle;
LRESULT lResult;
LPTSTR lpszLabel;
lpszLabel = NULL;
if (!IsWindow(hwnd))
return (NULL);
hwndLabel = hwnd;
while (hwndLabel = ::GetWindow(hwndLabel, GW_HWNDPREV))
{
lStyle = GetWindowLong(hwndLabel, GWL_STYLE);
//
// Is this a static dude?
//
lResult = SendMessage(hwndLabel, WM_GETDLGCODE, 0, 0L);
if (lResult & DLGC_STATIC)
{
//
// Great, we've found our label.
//
lpszLabel = GetTextString(hwndLabel, FALSE);
break;
}
//
// Skip if invisible
// Note that we do this after checking if its a staic,
// so that we give invisible statics a chance. Using invisible
// statics is a easy workaround to add names to controls
// without changing the visual UI.
//
if (!(lStyle & WS_VISIBLE))
continue;
//
// Is this a tabstop or group? If so, bail out now.
//
if (lStyle & (WS_GROUP | WS_TABSTOP))
break;
}
return(lpszLabel);
}
// --------------------------------------------------------------------------
//
// HrGetWindowName()
//
// --------------------------------------------------------------------------
HRESULT HrGetWindowName(HWND hwnd, BOOL fLookForLabel, BSTR* pszName)
{
LPTSTR lpText;
lpText = NULL;
if (!IsWindow(hwnd))
return (E_INVALIDARG);
//
// Look for a name property!
//
//
// If use a label, do that instead
//
if (!fLookForLabel)
{
//
// Try using a label anyway if this control has no window text
// and the parent is a dialog.
//
lpText = GetTextString(hwnd, FALSE);
if (!lpText)
{
HWND hwndParent = MyGetAncestor( hwnd, GA_PARENT );
if( hwndParent && CLASS_DialogClient == GetWindowClass( hwndParent ) )
{
fLookForLabel = TRUE;
}
}
}
if (fLookForLabel)
lpText = GetLabelString(hwnd);
if (! lpText)
return(S_FALSE);
//
// Strip out the mnemonic.
//
StripMnemonic(lpText);
// Get a BSTR
*pszName = TCharSysAllocString(lpText);
// Free our buffer
LocalFree((HANDLE)lpText);
// Did the BSTR succeed?
if (! *pszName)
return(E_OUTOFMEMORY);
return(S_OK);
}
// --------------------------------------------------------------------------
//
// HrGetWindowShortcut()
//
// --------------------------------------------------------------------------
HRESULT HrGetWindowShortcut(HWND hwnd, BOOL fUseLabel, BSTR* pszShortcut)
{
//
// Get the window text, and see if the '&' character is in it.
//
LPTSTR lpText;
TCHAR chMnemonic;
if (!IsWindow(hwnd))
return (E_INVALIDARG);
lpText = NULL;
if (! fUseLabel)
{
//
// Try using a label anyway if this control has no window text
// and the parent is a dialog.
//
lpText = GetTextString(hwnd, FALSE);
if (!lpText)
{
HWND hwndParent = MyGetAncestor( hwnd, GA_PARENT );
if( hwndParent && CLASS_DialogClient == GetWindowClass( hwndParent ) )
{
fUseLabel = TRUE;
}
}
}
if (fUseLabel)
lpText = GetLabelString(hwnd);
if (! lpText)
return(S_FALSE);
chMnemonic = StripMnemonic(lpText);
LocalFree((HANDLE)lpText);
//
// Is there a mnemonic?
//
if (chMnemonic)
{
//
// Make a string of the form "Alt+ch".
//
TCHAR szKey[2];
*szKey = chMnemonic;
*(szKey+1) = 0;
return(HrMakeShortcut(szKey, pszShortcut));
}
return(S_FALSE);
}
// --------------------------------------------------------------------------
//
// HrMakeShortcut()
//
// This takes a string for the hotkey, then combines it with the "Alt+%s"
// shortcut format to make the real string combination. If asked, it will
// free the hotkey string passed in.
//
// --------------------------------------------------------------------------
HRESULT HrMakeShortcut(LPTSTR lpszKey, BSTR* pszShortcut)
{
TCHAR szFormat[CCH_SHORTCUT];
TCHAR szResult[CCH_WINDOW_SHORTCUTMAX];
// Get the format string
LoadString(hinstResDll, STR_MENU_SHORTCUT_FORMAT, szFormat,
ARRAYSIZE(szFormat));
// Make the result
wsprintf(szResult, szFormat, lpszKey);
// Alloc a BSTR of the result
*pszShortcut = TCharSysAllocString(szResult);
// Should we free the key string?
// Did the allocation fail?
if (!*pszShortcut)
return(E_OUTOFMEMORY);
else
return(S_OK);
}
// 'Slide' string along by one char, in-place, to effectively remove the
// char pointed to be pStr.
// eg. if pStr points to the 'd' of 'abcdefg', the string
// will be transformed to 'abcefg'.
// Note: the char pointed to by pStr is assumed to be a single-byte
// char (if compiled under ANSI - not an issue if compiled inder UNICODE)
// Note: Makes use of the fact that no DBCS char has NUL as the trail byte.
void SlideStrAndRemoveChar( LPTSTR pStr )
{
LPTSTR pLead = pStr + 1;
// Checking the trailing pStr ptr means that we continue until we've
// copied (not just encountered) the terminating NUL.
while( *pStr )
*pStr++ = *pLead++;
}
// --------------------------------------------------------------------------
//
// StripMnemonic()
//
// This removes the mnemonic prefix. However, if we see '&&', we keep
// one '&'.
//
//
// Modified to be DBCS 'aware' - uses CharNext() instead of ptr++ to
// advance through the string. Will only return shortcut char if its a
// single byte char, though. (Would have to change all usages of this
// function to allow return of a potentially DBCS char.) Will remove this
// restriction in the planned-for-future fully-UNICODE OLEACC.
// This restriction should not be much of a problem, because DBCS chars,
// which typically require an IME to compose, are very unlikely to be
// used as 'shortcut' chars. eg. Japanese Windows uses underlined roman
// chars as shortcut chars.
// (This will all be replaced by simpler code when we go UNICODE...)
// --------------------------------------------------------------------------
TCHAR StripMnemonic(LPTSTR lpszText)
{
TCHAR ch;
TCHAR chNext = 0;
while( *lpszText == (TCHAR)' ' )
lpszText = CharNext( lpszText );
while( ch = *lpszText )
{
lpszText = CharNext( lpszText );
if (ch == CH_PREFIX)
{
// Get the next character.
chNext = *lpszText;
// If it too is '&', then this isn't a mnemonic, it's the
// actual '&' character.
if (chNext == CH_PREFIX)
chNext = 0;
// Skip 'n' strip the '&' character
SlideStrAndRemoveChar( lpszText - 1 );
#ifdef UNICODE
CharLowerBuff(&chNext, 1);
#else
if( IsDBCSLeadByte( chNext ) )
{
// We're ignoring DBCS chars as shortcut chars
// - would need to change this func and all callers
// to handle a returned DB char otherwise.
// For the moment, we just ensure we don't return
// an 'orphaned' lead byte...
chNext = '\0';
}
else
{
CharLowerBuff(&chNext, 1);
}
#endif
break;
}
}
return(chNext);
}
// --------------------------------------------------------------------------
//
// DirNavigate()
//
// Figures out which peer window is closest to us in the given direction.
//
// --------------------------------------------------------------------------
HRESULT DirNavigate(HWND hwndSelf, long dwNavDir, VARIANT* pvarEnd)
{
HWND hwndPeer;
RECT rcSelf;
RECT rcPeer;
int dwClosest;
int dwT;
HWND hwndClosest;
if (!IsWindow(hwndSelf))
return (E_INVALIDARG);
MyGetRect(hwndSelf, &rcSelf, TRUE);
dwClosest = 0x7FFFFFFF;
hwndClosest = NULL;
for (hwndPeer = ::GetWindow(hwndSelf, GW_HWNDFIRST); hwndPeer;
hwndPeer = ::GetWindow(hwndPeer, GW_HWNDNEXT))
{
if ((hwndPeer == hwndSelf) || !IsWindowVisible(hwndPeer))
continue;
MyGetRect(hwndPeer, &rcPeer, TRUE);
dwT = 0x7FFFFFFF;
switch (dwNavDir)
{
case NAVDIR_LEFT:
//
// Bogus! Only try this one if it intersects us vertically
//
if (rcPeer.left < rcSelf.left)
dwT = rcSelf.left - rcPeer.left;
break;
case NAVDIR_UP:
//
// Bogus! Only try this one if it intersects us horizontally
//
if (rcPeer.top < rcSelf.top)
dwT = rcSelf.top - rcPeer.top;
break;
case NAVDIR_RIGHT:
//
// Bogus! Only try this one if it intersects us vertically
//
if (rcPeer.right > rcSelf.right)
dwT = rcPeer.right - rcSelf.right;
break;
case NAVDIR_DOWN:
//
// Bogus! Only try this one if it intersects us horizontally
//
if (rcPeer.bottom > rcSelf.bottom)
dwT = rcPeer.bottom - rcSelf.bottom;
break;
default:
AssertStr( TEXT("INVALID NAVDIR") );
}
if (dwT < dwClosest)
{
dwClosest = dwT;
hwndClosest = hwndPeer;
}
}
if (hwndClosest)
return(GetWindowObject(hwndClosest, pvarEnd));
else
return(S_FALSE);
}
// --------------------------------------------------------------------------
//
// InTheShell()
//
// Returns TRUE if the object is on the shell tray, desktop, or process.
//
// --------------------------------------------------------------------------
BOOL InTheShell(HWND hwnd, int nPart)
{
HWND hwndShell;
static TCHAR szShellTray[] = TEXT("Shell_TrayWnd");
DWORD idProcessUs;
DWORD idProcessShell;
hwndShell = GetShellWindow();
switch (nPart)
{
case SHELL_TRAY:
// Use the tray window instead.
hwndShell = FindWindowEx(NULL, NULL, szShellTray, NULL);
// Fall thru
case SHELL_DESKTOP:
if (!hwndShell)
return(FALSE);
return(MyGetAncestor(hwnd, GA_ROOT) == hwndShell);
case SHELL_PROCESS:
idProcessUs = NULL;
idProcessShell = NULL;
GetWindowThreadProcessId(hwnd, &idProcessUs);
GetWindowThreadProcessId(hwndShell, &idProcessShell);
return(idProcessUs && (idProcessUs == idProcessShell));
}
AssertStr( TEXT("GetShellWindow returned strange part") );
return(FALSE);
}
// --- start of original comment ---
//
// We need a way for HWND and non-HWND children to live in the same
// namespace together. Since children pass up peer-to-peer navigation to
// their parent, we need a way for HWND children to identify themselves in
// the navigate call. Since HWND children are always objects, it is fine
// for the client parent to not accept HWND ids in all other methods. One
// can do it, but it is a lot of work.
//
// Examples to date of mixed:
// (1) Comboboxes (dropdown always a window, cur item may or may not be,
// button never is)
// (2) Toolbars (dropdown is a window, buttons aren't)
//
// We want the client manager to handle IEnumVARIANT, validation, etc.
//
// --- end of original comment ---
//
// A 'HWNDID' is basically a HWND squeezed (somehow) into a DWORD idChild.
//
// IsHWNDID checks if a idChild is one of these HWNDIDs, or just a regular
// idChild (ie. a 1-based child element index)
//
// HWNDIDFromHwnd and HwndFromHWNDID encode and decode HWNDs as idChilds.
//
// Previous versions of these didn't have a hwndParent parameter,
// and squeezed a HWND into bits 0..30, with bit31 set to 1 as the
// 'this is a HWND id' flag. That scheme doesn't work for HWNDs
// which have bt31 set... (these do exist on long-running systems -
// the top WORD of the HWND is a 'uniqueifier', which gets inc'd every
// time the slot - indicated by the bottom HWND - is reused. Of course,
// this implementation can change at any time in the furure, so we
// shouldn't rely on it, or rely on any bits being 'always 0' or
// otherwise.)
//
// The current sceheme still uses the high bit as a flag, but if set,
// the remaining bits are now a count into the parent window's children
// chain.
//
//
// It may be possible to remove these althogther - if the destination object
// corresponds to a full HWND, instead of returning a HWNDID, instead return
// the full IAccessible for that object. (Still have to figure out what happens
// when that IAccessible needs to navigate to one of its siblings, though.)
BOOL IsHWNDID( DWORD id )
{
// hight bit indicates that it represents a HWND.
return id & 0x80000000;
}
DWORD HWNDIDFromHwnd( HWND hwndParent, HWND hwnd )
{
// Traverse the child list, counting as we go, till we hit the HWND we want...
int i = 0;
HWND hChild = GetWindow( hwndParent, GW_CHILD );
while( hChild != NULL )
{
if( hChild == hwnd )
{
return i | 0x80000000;
}
i++;
hChild = GetWindow( hChild, GW_HWNDNEXT );
}
return 0;
}
HWND HwndFromHWNDID( HWND hwndParent, DWORD id )
{
// Traverse the child list, till we get to the one with this index...
int i = id & ~ 0x80000000;
HWND hChild = GetWindow( hwndParent, GW_CHILD );
while( i != 0 && hChild != NULL )
{
i--;
hChild = GetWindow( hChild, GW_HWNDNEXT );
}
return hChild;
}
| 27.026923 | 116 | 0.50158 | npocmaka |
988e9863075cef4f68af0490e4101b368438be86 | 1,568 | cpp | C++ | src/data_model/documentation/register_documentation.cpp | uscope-platform/makefile_gen | 06bd4405afbbd9584911f495ebefff828f05aa0d | [
"Apache-2.0"
] | null | null | null | src/data_model/documentation/register_documentation.cpp | uscope-platform/makefile_gen | 06bd4405afbbd9584911f495ebefff828f05aa0d | [
"Apache-2.0"
] | null | null | null | src/data_model/documentation/register_documentation.cpp | uscope-platform/makefile_gen | 06bd4405afbbd9584911f495ebefff828f05aa0d | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Filippo Savi
// Author: Filippo Savi <filssavi@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "data_model/documentation/register_documentation.h"
register_documentation::register_documentation(const std::string& n, uint32_t off, const std::string& desc, bool read, bool write) {
name = n;
offset = off;
description = desc;
read_allowed = read;
write_allowed = write;
}
bool operator==(const register_documentation &lhs, const register_documentation &rhs) {
bool ret = true;
ret &= lhs.name == rhs.name;
ret &= lhs.offset == rhs.offset;
ret &= lhs.description == rhs.description;
ret &= lhs.read_allowed == rhs.read_allowed;
ret &= lhs.write_allowed == rhs.write_allowed;
ret &= lhs.fields.size() == rhs.fields.size();
if(ret){
for(int i = 0; i<lhs.fields.size(); i++){
ret &= lhs.fields[i] == rhs.fields[i];
}
}
return ret;
}
void register_documentation::add_field(field_documentation &doc) {
fields.push_back(doc);
}
| 32 | 132 | 0.6875 | uscope-platform |
988fb19474526c03629437f7759cd979b03d7665 | 10,133 | cpp | C++ | code/src/engine/application/window_user32.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 3 | 2020-04-29T14:55:58.000Z | 2020-08-20T08:43:24.000Z | code/src/engine/application/window_user32.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 1 | 2022-03-12T11:37:46.000Z | 2022-03-12T20:17:38.000Z | code/src/engine/application/window_user32.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | null | null | null | #include "config.h"
#if WINDOW_USE_USER32
#include "window.hpp"
#include "engine/application/config.hpp"
#include "engine/debug.hpp"
#if TEXT_USE_USER32
# include "utility/unicode/string_view.hpp"
#endif
#include <windowsx.h>
#include <windows.h>
#if HAVE_VERSIONHELPERS_H
# include <versionhelpers.h>
#endif
namespace engine
{
namespace graphics
{
extern void notify_resize(viewer & viewer, int width, int height);
}
namespace hid
{
#if INPUT_HAS_USER32_RAWINPUT
extern void add_device(devices & devices, HANDLE device);
extern void remove_device(devices & devices, HANDLE device);
extern void process_input(devices & devices, HRAWINPUT input);
#endif
extern void key_character(devices & devices, int scancode, const char16_t * character);
extern void key_down(devices & devices, WPARAM wParam, LPARAM lParam, LONG time);
extern void key_up(devices & devices, WPARAM wParam, LPARAM lParam, LONG time);
extern void syskey_down(devices & devices, WPARAM wParam, LPARAM lParam, LONG time);
extern void syskey_up(devices & devices, WPARAM wParam, LPARAM lParam, LONG time);
extern void lbutton_down(devices & devices, LONG time);
extern void lbutton_up(devices & devices, LONG time);
extern void mbutton_down(devices & devices, LONG time);
extern void mbutton_up(devices & devices, LONG time);
extern void rbutton_down(devices & devices, LONG time);
extern void rbutton_up(devices & devices, LONG time);
extern void mouse_move(devices & devices, int_fast16_t x, int_fast16_t y, LONG time);
extern void mouse_wheel(devices & devices, int_fast16_t delta, LONG time);
extern void notify_resize(ui & ui, const int width, const int height);
}
}
namespace
{
engine::graphics::viewer * viewer = nullptr;
engine::hid::devices * devices = nullptr;
engine::hid::ui * ui = nullptr;
/**
*/
HWND hWnd;
/**
*/
HDC hDC;
/**
*/
HGLRC hGLRC;
/**
*/
LRESULT CALLBACK WinProc(HWND hWnd_, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
#if INPUT_HAS_USER32_RAWINPUT
case WM_INPUT:
if (GET_RAWINPUT_CODE_WPARAM(wParam) == RIM_INPUT)
{
process_input(*::devices, reinterpret_cast<HRAWINPUT>(lParam));
}
return DefWindowProcW(hWnd_, msg, wParam, lParam);
case WM_INPUT_DEVICE_CHANGE:
switch (wParam)
{
case GIDC_ARRIVAL: add_device(*::devices, reinterpret_cast<HANDLE>(lParam)); break;
case GIDC_REMOVAL: remove_device(*::devices, reinterpret_cast<HANDLE>(lParam)); break;
default: debug_unreachable();
}
break;
#endif
case WM_CHAR:
key_character(*::devices, uint32_t(lParam & 0xff0000) >> 16, reinterpret_cast<const char16_t *>(&wParam));
break;
case WM_KEYDOWN:
key_down(*::devices, wParam, lParam, GetMessageTime());
break;
case WM_KEYUP:
key_up(*::devices, wParam, lParam, GetMessageTime());
break;
case WM_SYSKEYDOWN:
syskey_down(*::devices, wParam, lParam, GetMessageTime());
break;
case WM_SYSKEYUP:
syskey_up(*::devices, wParam, lParam, GetMessageTime());
break;
case WM_MOUSEMOVE:
mouse_move(*::devices, (int_fast16_t)GET_X_LPARAM(lParam), (int_fast16_t)GET_Y_LPARAM(lParam), GetMessageTime());
break;
case WM_LBUTTONDOWN:
lbutton_down(*::devices, GetMessageTime());
break;
case WM_LBUTTONUP:
lbutton_up(*::devices, GetMessageTime());
break;
case WM_RBUTTONDOWN:
rbutton_down(*::devices, GetMessageTime());
break;
case WM_RBUTTONUP:
rbutton_up(*::devices, GetMessageTime());
break;
case WM_MBUTTONDOWN:
mbutton_down(*::devices, GetMessageTime());
break;
case WM_MBUTTONUP:
mbutton_up(*::devices, GetMessageTime());
break;
case WM_MOUSEWHEEL:
mouse_wheel(*::devices, (int_fast16_t)HIWORD(wParam), GetMessageTime());
break;
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_SIZE:
notify_resize(*::viewer, (int_fast16_t)LOWORD(lParam), (int_fast16_t)HIWORD(lParam));
notify_resize(*::ui, (int_fast16_t)LOWORD(lParam), (int_fast16_t)HIWORD(lParam));
break;
default:
return DefWindowProcW(hWnd_, msg, wParam, lParam);
}
return 0;
}
/**
*/
inline int messageLoop()
{
MSG msg;
while (GetMessageW(&msg, nullptr, 0, 0)) // while the message isn't 'WM_QUIT'
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return (int)msg.wParam;
}
void RegisterRawInputDevicesWithFlags(const uint32_t * collections, int count, DWORD dwFlags, HWND hWnd_)
{
RAWINPUTDEVICE rids[10]; // arbitrary
debug_assert(std::size_t(count) < sizeof rids / sizeof rids[0]);
for (int i = 0; i < count; i++)
{
rids[i].usUsagePage = collections[i] >> 16;
rids[i].usUsage = collections[i] & 0x0000ffff;
rids[i].dwFlags = dwFlags;
rids[i].hwndTarget = hWnd_;
}
if (RegisterRawInputDevices(rids, count, sizeof rids[0]) == FALSE)
{
const auto err = GetLastError();
debug_fail("RegisterRawInputDevices failed: ", err);
}
}
HINSTANCE cast(void * hInstance)
{
return static_cast<HINSTANCE>(hInstance);
}
}
namespace engine
{
namespace application
{
window::~window()
{
wglDeleteContext(hGLRC);
ReleaseDC(hWnd, hDC);
DestroyWindow(hWnd);
UnregisterClassW(L"Tribunal Window Class Name", cast(hInstance_));
::ui = nullptr;
::devices = nullptr;
::viewer = nullptr;
}
// TODO: proper error handling
window::window(HINSTANCE hInstance, int nCmdShow, const config_t & config)
: hInstance_(hInstance)
{
OSVERSIONINFO osvi;
{
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
}
//GetVersionEx(&osvi);
//debug_printline(engine::application_channel, "GetVersionEx: ", osvi.dwMajorVersion, " ", osvi.dwMinorVersion);
// register window class
const WNDCLASSEX WndClass = {sizeof(WNDCLASSEX),
0,
WinProc,
0,
0,
cast(hInstance),
LoadIconW(0, IDI_APPLICATION),
LoadCursorW(nullptr, IDC_ARROW),
(HBRUSH)COLOR_WINDOW,
0,
L"Tribunal Window Class Name",
LoadIconW(cast(hInstance), IDI_APPLICATION)};
RegisterClassExW(&WndClass);
// create window
::hWnd = CreateWindowExW(WS_EX_CLIENTEDGE,
L"Tribunal Window Class Name",
L"Tribunal \U00010348 \u2603",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
config.window_width,
config.window_height,
0,
0,
cast(hInstance),
0);
// create window graphics
::hDC = GetDC(::hWnd);
const PIXELFORMATDESCRIPTOR pfd = {sizeof(PIXELFORMATDESCRIPTOR),
0,
PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL,
PFD_TYPE_RGBA,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
32,
0,
0,
0,
0,
0,
0,
0};
const int pf = ChoosePixelFormat(::hDC, &pfd);
SetPixelFormat(::hDC, pf, &pfd);
::hGLRC = wglCreateContext(::hDC);
ShowWindow(::hWnd, nCmdShow);
}
void window::set_dependencies(engine::graphics::viewer & viewer_, engine::hid::devices & devices_, engine::hid::ui & ui_)
{
::viewer = &viewer_;
::devices = &devices_;
::ui = &ui_;
}
void make_current(window & /*window*/)
{
wglMakeCurrent(hDC, hGLRC);
}
void swap_buffers(window & /*window*/)
{
SwapBuffers(hDC);
}
#if INPUT_HAS_USER32_RAWINPUT
void RegisterRawInputDevices(window & /*window*/, const uint32_t * collections, int count)
{
RegisterRawInputDevicesWithFlags(collections, count, RIDEV_DEVNOTIFY, hWnd);
}
void UnregisterRawInputDevices(window & /*window*/, const uint32_t * collections, int count)
{
RegisterRawInputDevicesWithFlags(collections, count, RIDEV_REMOVE, nullptr);
}
#endif
#if TEXT_USE_USER32
void buildFont(window & /*window*/, HFONT hFont, DWORD count, DWORD listBase)
{
HGDIOBJ hPrevious = SelectObject(hDC, hFont);
wglUseFontBitmaps(hDC, 0, count, listBase);
SelectObject(hDC, hPrevious);
}
void freeFont(window & /*window*/, HFONT hFont)
{
DeleteObject(hFont);
}
HFONT loadFont(window & /*window*/, utility::string_units_utf8 name, int height)
{
return CreateFontW(height,
0,
0,
0,
FW_DONTCARE,
FALSE,
FALSE,
FALSE,
DEFAULT_CHARSET,
OUT_OUTLINE_PRECIS,
CLIP_DEFAULT_PRECIS,
5, // CLEARTYPE_QUALITY,
VARIABLE_PITCH,
utility::heap_widen(name).data());
}
#endif
int execute(window & /*window*/)
{
return messageLoop();
}
void close()
{
PostMessageW(hWnd, WM_CLOSE, 0, 0);
}
}
}
#endif /* WINDOW_USE_USER32 */
| 28.147222 | 123 | 0.571992 | shossjer |
9890ecead40d0f9f1670b5adb6f40276d539c33a | 1,345 | cpp | C++ | Sources/Internal/Notification/Private/Win10/LocalNotificationListenerWin10.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Sources/Internal/Notification/Private/Win10/LocalNotificationListenerWin10.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Sources/Internal/Notification/Private/Win10/LocalNotificationListenerWin10.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "Notification/Private/Win10/LocalNotificationListenerWin10.h"
#if defined(__DAVAENGINE_WIN_UAP__)
#include "Notification/LocalNotificationController.h"
#include "Engine/Engine.h"
#include "Logger/Logger.h"
#include "Utils/UTF8Utils.h"
namespace DAVA
{
namespace Private
{
LocalNotificationListener::LocalNotificationListener(LocalNotificationController& controller)
: localNotificationController(controller)
{
PlatformApi::Win10::RegisterXamlApplicationListener(this);
}
LocalNotificationListener::~LocalNotificationListener()
{
PlatformApi::Win10::UnregisterXamlApplicationListener(this);
}
void LocalNotificationListener::OnLaunched(::Windows::ApplicationModel::Activation::LaunchActivatedEventArgs ^ launchArgs)
{
using namespace DAVA;
String arguments = UTF8Utils::EncodeToUTF8(launchArgs->Arguments->Data());
if (launchArgs->Kind == Windows::ApplicationModel::Activation::ActivationKind::Launch)
{
Platform::String ^ launchString = launchArgs->Arguments;
if (!arguments.empty())
{
auto function = [this, arguments]()
{
localNotificationController.OnNotificationPressed(arguments);
};
RunOnMainThreadAsync(function);
}
}
}
} // namespace Private
} // namespace DAVA
#endif // __DAVAENGINE_WIN_UAP__
| 29.888889 | 122 | 0.734572 | stinvi |
989213e950580ce23b78398ef53a8e6a90dce76e | 15,564 | cpp | C++ | src/planner.cpp | zgh551/ros_rrt_bias | fd0596603d11acd19dc05d263f6eb3e3354297ae | [
"Apache-2.0"
] | 1 | 2021-12-06T07:39:22.000Z | 2021-12-06T07:39:22.000Z | src/planner.cpp | zgh551/ros_rrt_bias | fd0596603d11acd19dc05d263f6eb3e3354297ae | [
"Apache-2.0"
] | null | null | null | src/planner.cpp | zgh551/ros_rrt_bias | fd0596603d11acd19dc05d263f6eb3e3354297ae | [
"Apache-2.0"
] | 1 | 2021-12-28T02:10:08.000Z | 2021-12-28T02:10:08.000Z | /*
* @brief The planner
*/
#include "../include/planner.h"
#include "../include/rrt_bias.h"
#include "../include/obstacle_checker.h"
#include "../include/convolution.h"
// the tf
#include <algorithm>
#include <fftw3.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/PoseStamped.h>
#include <nav_msgs/OccupancyGrid.h>
#include <nav_msgs/Path.h>
#include <ompl/base/ScopedState.h>
#include <ompl/geometric/PathGeometric.h>
#include <ompl/geometric/planners/rrt/RRTstar.h>
#include <ros/time.h>
#include <tf/transform_datatypes.h>
/*
* @brief OMPL lib
*/
#include <ompl/base/PlannerStatus.h>
#include <ompl/base/SpaceInformation.h>
#include <ompl/base/StateSampler.h>
#include <ompl/base/spaces/RealVectorBounds.h>
#include <ompl/base/spaces/SE2StateSpace.h>
#include <ompl/geometric/planners/rrt/BiTRRT.h>
#include <ompl/geometric/planners/rrt/RRTConnect.h>
#include <ompl/geometric/planners/rrt/InformedRRTstar.h>
#include <ompl/geometric/planners/informedtrees/AITstar.h>
/*
* @brief System lib
*/
#include <valarray>
#include <memory>
#include <vector>
#include <visualization_msgs/Marker.h>
using namespace Common;
RRT_planner::Planner::Planner(void)
{
_start_valid = false;
_goal_valid = false;
_is_map_update = false;
_disk_map_width = 7;
_disk_map_height = 7;
_disk_map_size = _disk_map_width * _disk_map_height;
_disk_origin_x = static_cast<int16_t>(-(_disk_map_width - 1) * 0.5);
_disk_origin_y = static_cast<int16_t>(-(_disk_map_height - 1) * 0.5);
_obstacle_map_width = BOUNDARY_SIZE_X;
_obstacle_map_height = BOUNDARY_SIZE_Y;
_obstacle_map_size = _obstacle_map_width * _obstacle_map_height;
_obstacle_origin_x = static_cast<int16_t>(-_obstacle_map_width * 0.5);
_obstacle_origin_y = static_cast<int16_t>(-_obstacle_map_height * 0.5);
/*
* @brief malloc the memory space for grid map
*/
_disk_grid_map = (int8_t*)fftw_malloc(sizeof(int8_t) * _disk_map_size);
/*
* @brief base on the radius of circle produce the grid map
*/
DrawCircle(2);
// the line strip init
_start_pose_line_strip.header.frame_id =
_goal_pose_line_strip.header.frame_id =
_sample_point.header.frame_id =
_plan_path.header.frame_id =
_disk_occ_map.header.frame_id =
_convolution_occ_map.header.frame_id =
_diatance_occ_map.header.frame_id =
"map";
_start_pose_line_strip.header.stamp =
_goal_pose_line_strip.header.stamp =
_sample_point.header.stamp =
_plan_path.header.stamp =
_disk_occ_map.header.stamp =
_convolution_occ_map.header.stamp =
_diatance_occ_map.header.stamp =
ros::Time::now();
_start_pose_line_strip.ns = "start_pose_line_strip";
_goal_pose_line_strip.ns = "goal_pose_line_strip";
_start_pose_line_strip.action =
_goal_pose_line_strip.action =
visualization_msgs::Marker::MODIFY;
_start_pose_line_strip.id = 0;
_goal_pose_line_strip.id = 1;
_start_pose_line_strip.type =
_goal_pose_line_strip.type =
visualization_msgs::Marker::ARROW;
// the line strip scale
_start_pose_line_strip.scale.x = _goal_pose_line_strip.scale.x = 1;
_start_pose_line_strip.scale.y = _goal_pose_line_strip.scale.y = 0.1;
_start_pose_line_strip.scale.z = _goal_pose_line_strip.scale.z = 0.1;
_start_pose_line_strip.color.b = 1.0;
_start_pose_line_strip.color.a = 1.0;
_goal_pose_line_strip.color.g = 1.0;
_goal_pose_line_strip.color.a = 1.0;
/*
* @brief The disk map configure
*/
_disk_occ_map.info.height = _disk_map_height;
_disk_occ_map.info.width = _disk_map_width;
_disk_occ_map.info.origin.position.x = _disk_origin_x;
_disk_occ_map.info.origin.position.y = _disk_origin_y;
_disk_occ_map.info.resolution = 1;
_convolution_occ_map.info.resolution = 1;
_diatance_occ_map.info.resolution = 1;
/*
* @brief The publisher
*/
line_marker_pub = n.advertise<visualization_msgs::Marker>("visualization_marker", 100);
pose_array_pub = n.advertise<geometry_msgs::PoseArray>("sampling_points", 100);
path_state_pub = n.advertise<nav_msgs::Path>("plan_path", 100);
disk_grid_map_pub = n.advertise<nav_msgs::OccupancyGrid>("disk_grid", 100);
sum_grid_map_pub = n.advertise<nav_msgs::OccupancyGrid>("sum_grid", 100);
distance_map_pub = n.advertise<nav_msgs::OccupancyGrid>("distance_map", 100);
/*
* @brief The subscribe
*/
map_sub = n.subscribe("map", 1, &RRT_planner::Planner::MapCallback, this);
start_pose_sub = n.subscribe("initialpose", 1, &RRT_planner::Planner::StartPoseCallback, this);
goal_pose_sub = n.subscribe("move_base_simple/goal", 1, &RRT_planner::Planner::GoalPoseCallback, this);
}
RRT_planner::Planner::~Planner(void)
{
// TODO free memory
}
/*
* @brief The initial function
*/
void RRT_planner::Planner::Init(void)
{
ob::RealVectorBounds obstacle_boundary = ob::RealVectorBounds(2);
obstacle_boundary.setLow(0, _obstacle_origin_x);
obstacle_boundary.setLow(1, _obstacle_origin_y);
obstacle_boundary.setHigh(0, _obstacle_map_width + _obstacle_origin_x);
obstacle_boundary.setHigh(1, _obstacle_map_height + _obstacle_origin_y);
_state_space = std::make_shared<ob::ReedsSheppStateSpace>(5.0);
//_state_space = std::make_shared<ob::SE2StateSpace>();
_state_space->as<ob::SE2StateSpace>()->setBounds(obstacle_boundary);
_si = std::make_shared<ob::SpaceInformation>(_state_space);
_si->setStateValidityChecker(std::make_shared<RRT_planner::ObstacleChecker>(_si));
_si->setStateValidityCheckingResolution(0.03);
_si->setup();
_ss = std::make_shared<og::SimpleSetup>(_si);
_ss->setPlanner(std::make_shared<og::RRT_Bias>(_si));
}
void RRT_planner::Planner::Init(int8_t *map, uint16_t map_width, uint16_t map_height)
{
ob::RealVectorBounds obstacle_boundary = ob::RealVectorBounds(2);
obstacle_boundary.setLow(0, -map_width / 2);
obstacle_boundary.setLow(1, -map_height / 2);
obstacle_boundary.setHigh(0, map_width / 2);
obstacle_boundary.setHigh(1, map_height / 2);
_state_space = std::make_shared<ob::ReedsSheppStateSpace>(5.0);
//_state_space = std::make_shared<ob::SE2StateSpace>();
_state_space->as<ob::SE2StateSpace>()->setBounds(obstacle_boundary);
_si = std::make_shared<ob::SpaceInformation>(_state_space);
_si->setStateValidityChecker(std::make_shared<RRT_planner::ObstacleChecker>(_si, map, map_width, map_height));
_si->setStateValidityCheckingResolution(0.03);
_si->setup();
_ss = std::make_shared<og::SimpleSetup>(_si);
//_ss->setPlanner(std::make_shared<og::RRT_Bias>(_si));
//_ss->setPlanner(std::make_shared<og::BiTRRT>(_si));
_ss->setPlanner(std::make_shared<og::RRTstar>(_si));
}
/*
* @brief The solve function
*/
void RRT_planner::Planner::solve(const double time)
{
if (_start_valid && _goal_valid && _is_map_update)
{
ob::ScopedState<> start_state(_state_space);
ob::ScopedState<> goal_state(_state_space);
start_state->as<ob::SE2StateSpace::StateType>()->setX(_start_position.x);
start_state->as<ob::SE2StateSpace::StateType>()->setY(_start_position.y);
start_state->as<ob::SE2StateSpace::StateType>()->setYaw(_start_position.yaw);
goal_state->as<ob::SE2StateSpace::StateType>()->setX(_goal_position.x);
goal_state->as<ob::SE2StateSpace::StateType>()->setY(_goal_position.y);
goal_state->as<ob::SE2StateSpace::StateType>()->setYaw(_goal_position.yaw);
_ss->setStartAndGoalStates(start_state, goal_state);
_ss->setup();
_ss->print();
ob::PlannerStatus solved = _ss->solve(time);
if (solved)
{
/*
* @brief Step1: the solution path state points
*/
_sample_point.poses.clear();
geometry_msgs::Pose pose_temp;
for (auto &state : _ss->getSolutionPath().getStates())
{
const auto *SE2_state = state->as<ob::SE2StateSpace::StateType>();
pose_temp.position.x = SE2_state->getX();
pose_temp.position.y = SE2_state->getY();
pose_temp.orientation = tf::createQuaternionMsgFromYaw(SE2_state->getYaw());
_sample_point.poses.push_back(pose_temp);
}
pose_array_pub.publish(_sample_point);
/*
* @brief Step2: base on the solution path points,interpolate the
* full path with small step lenght
*/
og::PathGeometric path_state = _ss->getSolutionPath();
// using the solution path to interpolate the state
path_state.interpolate(1000);
geometry_msgs::PoseStamped pose_stamp;
_plan_path.poses.clear();
for (auto &state : path_state.getStates())
{
auto *SE2_state = state->as<ob::SE2StateSpace::StateType>();
pose_stamp.pose.position.x = SE2_state->getX();
pose_stamp.pose.position.y = SE2_state->getY();
_plan_path.poses.push_back(pose_stamp);
}
path_state_pub.publish(_plan_path);
}
else
{
ROS_INFO("plan faile!");
}
_ss->clear();
_goal_valid = false;
}
else
{
//ROS_INFO("map no update or without start or goal point!");
}
}
void RRT_planner::Planner::DrawCircle(double r)
{
for (uint16_t i = 0; i < _disk_map_size; i++)
{
_disk_grid_map[i] = 0;
}
int16_t F = 1 - r;
int16_t x = r;
int16_t y = 0;
int16_t delta_up_left = -2 * r;
int16_t delta_up = 1;
while (y < x)
{
if (F >= 0)
{
for(uint16_t i = -x - _disk_origin_x; i < (x - _disk_origin_x + 1); i++)
{
for (uint16_t j = -y -_disk_origin_y; j < (y - _disk_origin_y + 1); j++)
{
_disk_grid_map[j + _disk_map_width * i] = 100;
}
}
for(uint16_t i = -y - _disk_origin_y; i < (y - _disk_origin_y + 1); i++)
{
for (uint16_t j = -x - _disk_origin_x; j < (x - _disk_origin_x + 1); j++)
{
_disk_grid_map[j + _disk_map_width * i] = 100;
}
}
x -= 1;
delta_up_left += 2;
F += delta_up_left;
}
y += 1;
delta_up += 2;
F += delta_up;
}
}
/*
* @brief the callback function for
*/
void RRT_planner::Planner::MapCallback(const nav_msgs::OccupancyGrid::Ptr map)
{
/*
* @brief obstacle map size update
*/
_obstacle_map_height = map->info.height;
_obstacle_map_width = map->info.width;
_obstacle_map_size = _obstacle_map_width * _obstacle_map_height;
_obstacle_origin_x = static_cast<int16_t>(-_obstacle_map_width * 0.5);
_obstacle_origin_y = static_cast<int16_t>(-_obstacle_map_height * 0.5);
if (_is_map_update)
{
fftw_free(_obstacle_grid_map);
fftw_free(_convolution_grid_map);
}
else
{
_is_map_update = true;
}
_obstacle_grid_map = (int8_t*)fftw_malloc(sizeof(int8_t) * _obstacle_map_size);
_convolution_grid_map = (int8_t*)fftw_malloc(sizeof(int8_t) * _obstacle_map_size);
_convolution_occ_map.info.height = _obstacle_map_height;
_convolution_occ_map.info.width = _obstacle_map_width;
_convolution_occ_map.info.origin.position.x = _obstacle_origin_x;
_convolution_occ_map.info.origin.position.y = _obstacle_origin_y;
_diatance_occ_map.info.height = _obstacle_map_height;
_diatance_occ_map.info.width = _obstacle_map_width;
_diatance_occ_map.info.origin.position.x = _obstacle_origin_x;
_diatance_occ_map.info.origin.position.y = _obstacle_origin_y;
// obstacle map update
for (uint16_t i = 0; i < _obstacle_map_height; i++)
{
for (uint16_t j = 0; j < _obstacle_map_width; j++)
{
_obstacle_grid_map[i * _obstacle_map_width + j] = map->data[i * _obstacle_map_width + j] > 0 ? 100 : 0;
}
}
ROS_INFO("grid map update width:%d,height:%d", _obstacle_map_width, _obstacle_map_height);
double *output_test_grid_map = (double*)fftw_malloc(sizeof(double) * _obstacle_map_size);
int8_t *distance_grid_map = (int8_t*)fftw_malloc(sizeof(int8_t) * _obstacle_map_size);
// calculate the time begin
ros::Time begin = ros::Time::now();
// map convolution
// convolution_2d(_disk_grid_map, _obstacle_grid_map, _convolution_grid_map);
Common::Convolution::convolution_2d( _disk_grid_map, _disk_map_width, _disk_map_height,
_obstacle_grid_map,_obstacle_map_width, _obstacle_map_height,
_convolution_grid_map);
// the end of calculate time
double pro_time = (ros::Time::now() - begin).toSec();
ROS_INFO("convolution time %f", pro_time);
// distance map update
_distance_map.DistanceMapUpdate(_obstacle_map_width, _obstacle_map_height, _obstacle_grid_map, output_test_grid_map);
for (uint16_t i = 0; i < _obstacle_map_size; i++)
{
distance_grid_map[i] = static_cast<int8_t>(output_test_grid_map[i] * 10);
}
/*
* @brief the convolution result map show
*/
std::vector<int8_t> convolution_map_temp(_convolution_grid_map , _convolution_grid_map + _obstacle_map_size);
_convolution_occ_map.data = convolution_map_temp;
sum_grid_map_pub.publish(_convolution_occ_map);
// the distance map show
std::vector<int8_t> distance_temp(distance_grid_map , distance_grid_map + _obstacle_map_size);
_diatance_occ_map.data = distance_temp;
distance_map_pub.publish(_diatance_occ_map);
// the disk map show
std::vector<int8_t> disk_map_temp(_disk_grid_map, _disk_grid_map + _disk_map_size );
_disk_occ_map.data = disk_map_temp;
disk_grid_map_pub.publish(_disk_occ_map);
// init the planner space and obstacle map
Init(_convolution_grid_map, _obstacle_map_width, _obstacle_map_height);
}
/*
* @brief The callback function of start position
*/
void RRT_planner::Planner::StartPoseCallback(const geometry_msgs::PoseWithCovarianceStamped &pose)
{
_start_position.x = pose.pose.pose.position.x;
_start_position.y = pose.pose.pose.position.y;
_start_position.yaw = tf::getYaw(pose.pose.pose.orientation);
_start_valid = true;
_start_pose_line_strip.pose = pose.pose.pose;
line_marker_pub.publish(_start_pose_line_strip);
ROS_INFO("start position x:%f, y:%f, yaw:%f", _start_position.x,
_start_position.y,
_start_position.yaw);
}
/*
* @brief The callback function of goal position
*/
void RRT_planner::Planner::GoalPoseCallback(const geometry_msgs::PoseStamped &pose)
{
_goal_position.x = pose.pose.position.x;
_goal_position.y = pose.pose.position.y;
_goal_position.yaw = tf::getYaw(pose.pose.orientation);
_goal_valid = true;
_goal_pose_line_strip.pose = pose.pose;
line_marker_pub.publish(_goal_pose_line_strip);
ROS_INFO("goal position x:%f, y:%f, yaw:%f", _goal_position.x,
_goal_position.y,
_goal_position.yaw);
}
| 33.982533 | 121 | 0.663133 | zgh551 |
9892d0b83d4c489b4daff50358d41e078fba08d0 | 12,953 | cpp | C++ | Adafruit_PCD8544.cpp | adafruit/Adafruit-PCD8544-Nokia-5110-LCD-library | d471178dda640ff046d605c16f5c79e5724e5d59 | [
"BSD-3-Clause"
] | 293 | 2015-01-02T09:38:05.000Z | 2022-03-30T05:52:04.000Z | Adafruit_PCD8544.cpp | adafruit/Adafruit-PCD8544-Nokia-5110-LCD-library | d471178dda640ff046d605c16f5c79e5724e5d59 | [
"BSD-3-Clause"
] | 32 | 2015-10-23T12:28:33.000Z | 2021-12-20T19:28:43.000Z | Adafruit_PCD8544.cpp | adafruit/Adafruit-PCD8544-Nokia-5110-LCD-library | d471178dda640ff046d605c16f5c79e5724e5d59 | [
"BSD-3-Clause"
] | 151 | 2015-01-03T12:58:20.000Z | 2021-12-19T16:17:55.000Z | /**************************************************************************/
/*!
@file Adafruit_PCD8544.cpp
@mainpage Adafruit PCD8544 Nokia 5110 LCD Library
@section intro Introduction
This is a library for our Monochrome Nokia 5110 LCD Displays
Pick one up today in the adafruit shop!
------> http://www.adafruit.com/products/338
These displays use SPI to communicate, 4 or 5 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section author Author
Written by Limor Fried/Ladyada for Adafruit Industries.
@section license License
BSD license, check license.txt for more information
All text above, and the splash screen below must be included in any
redistribution
*/
/**************************************************************************/
#include "Adafruit_PCD8544.h"
#include "Arduino.h"
#include <stdlib.h>
/** the memory buffer for the LCD */
uint8_t pcd8544_buffer[LCDWIDTH * LCDHEIGHT / 8] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFC, 0xFE, 0xFF, 0xFC, 0xE0,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8,
0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0, 0xE0, 0xE0, 0xC0, 0x80, 0xC0,
0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x3F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xC7, 0xC7, 0x87, 0x8F, 0x9F,
0x9F, 0xFF, 0xFF, 0xFF, 0xC1, 0xC0, 0xE0, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFC, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0xFE, 0xFC, 0xFC, 0xF8, 0xF8,
0xF0, 0xE0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0,
0xF1, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x1F, 0x0F, 0x0F, 0x87,
0xE7, 0xFF, 0xFF, 0xFF, 0x1F, 0x1F, 0x3F, 0xF9, 0xF8, 0xF8, 0xF8, 0xF8,
0xF8, 0xF8, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x7F, 0x3F, 0x0F, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFE, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x7E, 0x3F, 0x3F, 0x0F,
0x1F, 0xFF, 0xFF, 0xFF, 0xFC, 0xF0, 0xE0, 0xF1, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFC, 0xF0, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x03, 0x0F, 0x1F, 0x3F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF,
0x7F, 0x7F, 0x1F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
/*!
@brief Update the bounding box for partial updates
@param xmin left
@param ymin bottom
@param xmax right
@param ymax top
*/
void Adafruit_PCD8544::updateBoundingBox(uint8_t xmin, uint8_t ymin,
uint8_t xmax, uint8_t ymax) {
xUpdateMin = min(xUpdateMin, xmin);
xUpdateMax = max(xUpdateMax, xmax);
yUpdateMin = min(yUpdateMin, ymin);
yUpdateMax = max(yUpdateMax, ymax);
}
/*!
@brief Constructor for software SPI with explicit CS pin
@param sclk_pin SCLK pin
@param din_pin DIN pin
@param dc_pin DC pin
@param cs_pin CS pin
@param rst_pin RST pin
*/
Adafruit_PCD8544::Adafruit_PCD8544(int8_t sclk_pin, int8_t din_pin,
int8_t dc_pin, int8_t cs_pin, int8_t rst_pin)
: Adafruit_GFX(LCDWIDTH, LCDHEIGHT) {
spi_dev = new Adafruit_SPIDevice(cs_pin, sclk_pin, -1, din_pin,
4000000); // 4mhz max speed
_dcpin = dc_pin;
_rstpin = rst_pin;
}
/*!
@brief Constructor for hardware SPI based on hardware controlled SCK (SCLK)
and MOSI (DIN) pins. CS is still controlled by any IO pin. NOTE: MISO and SS
will be set as an input and output respectively, so be careful sharing those
pins!
@param dc_pin DC pin
@param cs_pin CS pin
@param rst_pin RST pin
@param theSPI Pointer to SPIClass device for hardware SPI
*/
Adafruit_PCD8544::Adafruit_PCD8544(int8_t dc_pin, int8_t cs_pin, int8_t rst_pin,
SPIClass *theSPI)
: Adafruit_GFX(LCDWIDTH, LCDHEIGHT) {
spi_dev = new Adafruit_SPIDevice(cs_pin, 4000000, SPI_BITORDER_MSBFIRST,
SPI_MODE0, theSPI);
_dcpin = dc_pin;
_rstpin = rst_pin;
}
/*!
@brief The most basic function, set a single pixel, in the main buffer
@param x x coord
@param y y coord
@param color pixel color (BLACK or WHITE)
*/
void Adafruit_PCD8544::drawPixel(int16_t x, int16_t y, uint16_t color) {
setPixel(x, y, color, pcd8544_buffer);
updateBoundingBox(x, y, x, y);
}
/*!
@brief The most basic function, set a single pixel
@param x x coord
@param y y coord
@param color pixel color (BLACK or WHITE)
@param buffer The framebuffer to set the pixel in
*/
void Adafruit_PCD8544::setPixel(int16_t x, int16_t y, bool color,
uint8_t *buffer) {
if ((x < 0) || (x >= _width) || (y < 0) || (y >= _height))
return;
int16_t t;
switch (rotation) {
case 1:
t = x;
x = y;
y = LCDHEIGHT - 1 - t;
break;
case 2:
x = LCDWIDTH - 1 - x;
y = LCDHEIGHT - 1 - y;
break;
case 3:
t = x;
x = LCDWIDTH - 1 - y;
y = t;
break;
}
// x is which column
if (color)
buffer[x + (y / 8) * LCDWIDTH] |= 1 << (y % 8);
else
buffer[x + (y / 8) * LCDWIDTH] &= ~(1 << (y % 8));
}
/*!
@brief The most basic function, get a single pixel
@param x x coord
@param y y coord
@param buffer The framebuffer to get the pixel from
@return color of the pixel at x,y
*/
bool Adafruit_PCD8544::getPixel(int16_t x, int16_t y, uint8_t *buffer) {
if ((x < 0) || (x >= _width) || (y < 0) || (y >= _height))
return false;
int16_t t;
switch (rotation) {
case 1:
t = x;
x = y;
y = LCDHEIGHT - 1 - t;
break;
case 2:
x = LCDWIDTH - 1 - x;
y = LCDHEIGHT - 1 - y;
break;
case 3:
t = x;
x = LCDWIDTH - 1 - y;
y = t;
break;
}
return (buffer[x + (y / 8) * LCDWIDTH] >> (y % 8)) & 0x1;
}
/*!
@brief Initialize the display. Set bias and contrast, enter normal mode.
*/
void Adafruit_PCD8544::initDisplay() {
// toggle RST low to reset
if (_rstpin >= 0) {
pinMode(_rstpin, OUTPUT);
digitalWrite(_rstpin, LOW);
delay(1); // 1 ns minimum
digitalWrite(_rstpin, HIGH);
}
setBias(_bias);
setContrast(_contrast);
// normal mode
command(PCD8544_FUNCTIONSET);
// Set display to Normal
command(PCD8544_DISPLAYCONTROL | PCD8544_DISPLAYNORMAL);
}
/*!
@brief Set up SPI, initialize the display, set the bounding box
@param contrast Initial contrast value
@param bias Initial bias value
@returns True on initialization success
*/
bool Adafruit_PCD8544::begin(uint8_t contrast, uint8_t bias) {
if (!spi_dev->begin()) {
return false;
}
// Set common pin outputs.
pinMode(_dcpin, OUTPUT);
if (_rstpin >= 0)
pinMode(_rstpin, OUTPUT);
_bias = bias;
_contrast = contrast;
_reinit_interval = 0;
_display_count = 0;
initDisplay();
// initial display line
// set page address
// set column address
// write display data
// set up a bounding box for screen updates
updateBoundingBox(0, 0, LCDWIDTH - 1, LCDHEIGHT - 1);
// Push out pcd8544_buffer to the Display (will show the AFI logo)
display();
return true;
}
/*!
@brief Send a command to the LCD
@param c Command byte
*/
void Adafruit_PCD8544::command(uint8_t c) {
digitalWrite(_dcpin, LOW);
spi_dev->write(&c, 1);
}
/*!
@brief Send data to the LCD
@param c Data byte
*/
void Adafruit_PCD8544::data(uint8_t c) {
digitalWrite(_dcpin, HIGH);
spi_dev->write(&c, 1);
}
/*!
@brief Set the contrast level
@param val Contrast value
*/
void Adafruit_PCD8544::setContrast(uint8_t val) {
if (val > 0x7f) {
val = 0x7f;
}
_contrast = val;
command(PCD8544_FUNCTIONSET | PCD8544_EXTENDEDINSTRUCTION);
command(PCD8544_SETVOP | val);
command(PCD8544_FUNCTIONSET);
}
/*!
@brief Set the bias level
@param val Bias value
*/
void Adafruit_PCD8544::setBias(uint8_t val) {
if (val > 0x07) {
val = 0x07;
}
_bias = val;
command(PCD8544_FUNCTIONSET | PCD8544_EXTENDEDINSTRUCTION);
command(PCD8544_SETBIAS | val);
command(PCD8544_FUNCTIONSET);
}
/*!
@brief Get the bias level
@return Bias value
*/
uint8_t Adafruit_PCD8544::getBias() { return _bias; }
/*!
@brief Get the contrast level
@return Contrast value
*/
uint8_t Adafruit_PCD8544::getContrast() { return _contrast; }
/*!
@brief Set the interval for reinitializing the display
@param val Reinit after this many calls to display()
*/
void Adafruit_PCD8544::setReinitInterval(uint8_t val) {
_reinit_interval = val;
}
/*!
@brief Get the reinit interval
@return Reinit interval
*/
uint8_t Adafruit_PCD8544::getReinitInterval() { return _reinit_interval; }
/*!
@brief Update the display
*/
void Adafruit_PCD8544::display(void) {
if (_reinit_interval) {
_display_count++;
if (_display_count >= _reinit_interval) {
_display_count = 0;
initDisplay();
}
}
for (uint8_t page = (yUpdateMin / 8); page < (yUpdateMax / 8) + 1; page++) {
command(PCD8544_SETYADDR | page);
uint8_t startcol = xUpdateMin;
uint8_t endcol = xUpdateMax;
command(PCD8544_SETXADDR | startcol);
digitalWrite(_dcpin, HIGH);
spi_dev->write(pcd8544_buffer + (LCDWIDTH * page) + startcol,
endcol - startcol + 1);
}
command(PCD8544_SETYADDR); // no idea why this is necessary but it is to
// finish the last byte?
xUpdateMin = LCDWIDTH - 1;
xUpdateMax = 0;
yUpdateMin = LCDHEIGHT - 1;
yUpdateMax = 0;
}
/*!
@brief Clear the entire display
*/
void Adafruit_PCD8544::clearDisplay(void) {
memset(pcd8544_buffer, 0, LCDWIDTH * LCDHEIGHT / 8);
updateBoundingBox(0, 0, LCDWIDTH - 1, LCDHEIGHT - 1);
cursor_y = cursor_x = 0;
}
/*!
@brief Invert the entire display
@param i True to invert the display, false to keep it uninverted
*/
void Adafruit_PCD8544::invertDisplay(bool i) {
command(PCD8544_FUNCTIONSET);
command(PCD8544_DISPLAYCONTROL |
(i ? PCD8544_DISPLAYINVERTED : PCD8544_DISPLAYNORMAL));
}
/*!
@brief Scroll the display by creating a new buffer and moving each pixel
@param xpixels The x offset, can be negative to scroll backwards
@param ypixels The y offset, can be negative to scroll updwards
*/
void Adafruit_PCD8544::scroll(int8_t xpixels, int8_t ypixels) {
uint8_t new_buffer[LCDWIDTH * LCDHEIGHT / 8];
memset(new_buffer, 0, LCDWIDTH * LCDHEIGHT / 8);
// negative pixels wrap around
while (ypixels < 0) {
ypixels += height();
}
ypixels %= height();
while (xpixels < 0) {
xpixels += width();
}
xpixels %= width();
for (int x = 0; x < width(); x++) {
for (int y = 0; y < height(); y++) {
if (getPixel(x, y, pcd8544_buffer)) {
int new_x = (x + xpixels) % _width;
int new_y = (y + ypixels) % _height;
setPixel(new_x, new_y, true, new_buffer);
}
}
}
memcpy(pcd8544_buffer, new_buffer, LCDWIDTH * LCDHEIGHT / 8);
updateBoundingBox(0, 0, LCDWIDTH - 1, LCDHEIGHT - 1);
}
| 29.91455 | 80 | 0.638771 | adafruit |